code
stringlengths 0
56.1M
| repo_name
stringclasses 515
values | path
stringlengths 2
147
| language
stringclasses 447
values | license
stringclasses 7
values | size
int64 0
56.8M
|
---|---|---|---|---|---|
/*
Copyright 2022 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package annotations contains the list of annotations for Dapr deployments.
package annotations
// Annotation keys.
// Name must start with "Key".
const (
KeyEnabled = "dapr.io/enabled"
KeyAppPort = "dapr.io/app-port"
KeyConfig = "dapr.io/config"
KeyAppProtocol = "dapr.io/app-protocol"
KeyAppSSL = "dapr.io/app-ssl" // Deprecated. Remove in a future Dapr version. Use "app-protocol" with "https" or "grpcs"
KeyAppID = "dapr.io/app-id"
KeyEnableProfiling = "dapr.io/enable-profiling"
KeyLogLevel = "dapr.io/log-level"
KeyAPITokenSecret = "dapr.io/api-token-secret" /* #nosec */
KeyAppTokenSecret = "dapr.io/app-token-secret" /* #nosec */
KeyLogAsJSON = "dapr.io/log-as-json"
KeyAppMaxConcurrency = "dapr.io/app-max-concurrency"
KeyEnableMetrics = "dapr.io/enable-metrics"
KeyMetricsPort = "dapr.io/metrics-port"
KeyEnableDebug = "dapr.io/enable-debug"
KeyDebugPort = "dapr.io/debug-port"
KeyEnv = "dapr.io/env"
KeyCPURequest = "dapr.io/sidecar-cpu-request"
KeyCPULimit = "dapr.io/sidecar-cpu-limit"
KeyMemoryRequest = "dapr.io/sidecar-memory-request"
KeyMemoryLimit = "dapr.io/sidecar-memory-limit"
KeySidecarListenAddresses = "dapr.io/sidecar-listen-addresses"
KeyLivenessProbeDelaySeconds = "dapr.io/sidecar-liveness-probe-delay-seconds"
KeyLivenessProbeTimeoutSeconds = "dapr.io/sidecar-liveness-probe-timeout-seconds"
KeyLivenessProbePeriodSeconds = "dapr.io/sidecar-liveness-probe-period-seconds"
KeyLivenessProbeThreshold = "dapr.io/sidecar-liveness-probe-threshold"
KeyReadinessProbeDelaySeconds = "dapr.io/sidecar-readiness-probe-delay-seconds"
KeyReadinessProbeTimeoutSeconds = "dapr.io/sidecar-readiness-probe-timeout-seconds"
KeyReadinessProbePeriodSeconds = "dapr.io/sidecar-readiness-probe-period-seconds"
KeyReadinessProbeThreshold = "dapr.io/sidecar-readiness-probe-threshold"
KeySidecarImage = "dapr.io/sidecar-image"
KeySidecarSeccompProfileType = "dapr.io/sidecar-seccomp-profile-type"
KeyHTTPMaxRequestSize = "dapr.io/http-max-request-size"
KeyMaxBodySize = "dapr.io/max-body-size"
KeyHTTPReadBufferSize = "dapr.io/http-read-buffer-size"
KeyReadBufferSize = "dapr.io/read-buffer-size"
KeyGracefulShutdownSeconds = "dapr.io/graceful-shutdown-seconds"
KeyBlockShutdownDuration = "dapr.io/block-shutdown-duration"
KeyEnableAPILogging = "dapr.io/enable-api-logging"
KeyUnixDomainSocketPath = "dapr.io/unix-domain-socket-path"
KeyVolumeMountsReadOnly = "dapr.io/volume-mounts"
KeyVolumeMountsReadWrite = "dapr.io/volume-mounts-rw"
KeyDisableBuiltinK8sSecretStore = "dapr.io/disable-builtin-k8s-secret-store" //nolint:gosec
KeyEnableAppHealthCheck = "dapr.io/enable-app-health-check"
KeyAppHealthCheckPath = "dapr.io/app-health-check-path"
KeyAppHealthProbeInterval = "dapr.io/app-health-probe-interval"
KeyAppHealthProbeTimeout = "dapr.io/app-health-probe-timeout"
KeyAppHealthThreshold = "dapr.io/app-health-threshold"
KeyPlacementHostAddresses = "dapr.io/placement-host-address"
KeyPluggableComponents = "dapr.io/pluggable-components"
KeyPluggableComponentsSocketsFolder = "dapr.io/pluggable-components-sockets-folder"
KeyPluggableComponentContainer = "dapr.io/component-container"
KeyPluggableComponentsInjection = "dapr.io/inject-pluggable-components"
KeyAppChannel = "dapr.io/app-channel-address"
)
|
mikeee/dapr
|
pkg/injector/annotations/annotations.go
|
GO
|
mit
| 4,647 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package annotations_test
import (
"go/ast"
"go/parser"
"go/token"
"reflect"
"strconv"
"strings"
"testing"
"github.com/stretchr/testify/require"
"golang.org/x/exp/slices"
"github.com/dapr/dapr/pkg/injector/patcher"
)
// This test makes sure that the SidecarConfig struct contains all and only the annotations defined as constants in the annotations package.
func TestAnnotationCompletness(t *testing.T) {
annotationsPkg := []string{}
annotationsStruct := []string{}
// Load the annotations defined as constants in annotations.go, whose name starts with Key*
fset := token.NewFileSet()
node, err := parser.ParseFile(fset, "annotations.go", nil, 0)
require.NoError(t, err)
require.NotNil(t, node)
require.Len(t, node.Decls, 1)
for _, decl := range node.Decls {
genDecl, ok := decl.(*ast.GenDecl)
if !ok || genDecl == nil || genDecl.Tok != token.CONST {
continue
}
for _, spec := range genDecl.Specs {
valueSpec, ok := spec.(*ast.ValueSpec)
if !ok || valueSpec == nil {
continue
}
for _, name := range valueSpec.Names {
if !strings.HasPrefix(name.Name, "Key") || len(valueSpec.Values) != 1 {
continue
}
lit := valueSpec.Values[0].(*ast.BasicLit)
if lit.Kind.String() != "STRING" {
continue
}
val, err := strconv.Unquote(lit.Value)
if err != nil {
continue
}
annotationsPkg = append(annotationsPkg, val)
}
}
}
// Load the annotations listed as properties in SidecarConfig
p := patcher.SidecarConfig{}
pt := reflect.TypeOf(p)
for i := 0; i < pt.NumField(); i++ {
field := pt.Field(i)
an := field.Tag.Get("annotation")
if an != "" {
annotationsStruct = append(annotationsStruct, an)
}
}
// Sort so order doesn't matter
slices.Sort(annotationsPkg)
slices.Sort(annotationsStruct)
// Check for completeness
require.EqualValues(t, annotationsPkg, annotationsStruct)
}
|
mikeee/dapr
|
pkg/injector/annotations/annotations_test.go
|
GO
|
mit
| 2,454 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package consts
import (
"github.com/dapr/dapr/pkg/modes"
)
// DaprMode is the runtime mode for Dapr.
type DaprMode = modes.DaprMode
const (
SidecarContainerName = "daprd" // Name of the Dapr sidecar container
SidecarHTTPPortName = "dapr-http"
SidecarGRPCPortName = "dapr-grpc"
SidecarInternalGRPCPortName = "dapr-internal"
SidecarMetricsPortName = "dapr-metrics"
SidecarDebugPortName = "dapr-debug"
SidecarHealthzPath = "healthz"
SidecarInjectedLabel = "dapr.io/sidecar-injected"
SidecarAppIDLabel = "dapr.io/app-id"
SidecarMetricsEnabledLabel = "dapr.io/metrics-enabled"
APIVersionV1 = "v1.0"
UnixDomainSocketVolume = "dapr-unix-domain-socket" // Name of the UNIX domain socket volume.
UnixDomainSocketDaprdPath = "/var/run/dapr-sockets" // Path in the daprd container where UNIX domain sockets are mounted.
UserContainerAppProtocolName = "APP_PROTOCOL" // Name of the variable exposed to the app containing the app protocol.
UserContainerDaprHTTPPortName = "DAPR_HTTP_PORT" // Name of the variable exposed to the app containing the Dapr HTTP port.
UserContainerDaprGRPCPortName = "DAPR_GRPC_PORT" // Name of the variable exposed to the app containing the Dapr gRPC port.
DaprContainerHostIP = "DAPR_HOST_IP" // Name of the variable injected in the daprd container containing the pod's IP
TokenVolumeKubernetesMountPath = "/var/run/secrets/dapr.io/sentrytoken" /* #nosec */ // Mount path for the Kubernetes service account volume with the sentry token.
TokenVolumeName = "dapr-identity-token" /* #nosec */ // Name of the volume with the service account token for daprd.
ComponentsUDSVolumeName = "dapr-components-unix-domain-socket" // Name of the Unix domain socket volume for components.
ComponentsUDSMountPathEnvVar = "DAPR_COMPONENT_SOCKETS_FOLDER"
ComponentsUDSDefaultFolder = "/tmp/dapr-components-sockets"
ModeKubernetes = modes.KubernetesMode // KubernetesMode is a Kubernetes Dapr mode.
ModeStandalone = modes.StandaloneMode // StandaloneMode is a Standalone Dapr mode.
)
|
mikeee/dapr
|
pkg/injector/consts/consts.go
|
GO
|
mit
| 2,877 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package namespacednamematcher
import (
"errors"
"fmt"
"sort"
"strings"
"github.com/dapr/dapr/utils"
)
// sort by length and if needed by regular comparison
type shortestPrefixSortedSlice []string
func (s shortestPrefixSortedSlice) Less(i, j int) bool { return len(s[i]) < len(s[j]) || s[i] < s[j] }
func (s shortestPrefixSortedSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s shortestPrefixSortedSlice) Len() int { return len(s) }
type equalPrefixLists struct {
equal []string
prefix []string
}
type EqualPrefixNameNamespaceMatcher struct {
prefixed map[string]*equalPrefixLists
equal map[string]*equalPrefixLists
sortedPrefixes []string
}
// CreateFromString creates two maps from the CSV provided by the user of ns:sa values,
// one with namespace prefixes and one with namespace exact values.
// Inside each map we can have exact name or prefixed names.
// Note there might be overlap in prefixes, but we are not filtering it for now.
func CreateFromString(s string) (*EqualPrefixNameNamespaceMatcher, error) {
matcher := &EqualPrefixNameNamespaceMatcher{}
for _, nameNamespace := range strings.Split(s, ",") {
saNs := strings.Split(nameNamespace, ":")
if len(saNs) != 2 {
return nil, errors.New("service account namespace pair not following expected format 'namespace:serviceaccountname'")
}
ns := strings.TrimSpace(saNs[0])
sa := strings.TrimSpace(saNs[1])
if len(ns) == 0 && len(sa) == 0 {
return nil, errors.New("service account name and namespace cannot both be empty")
}
nsPrefix, prefixFound, err := getPrefix(ns)
if err != nil {
return nil, err
}
if prefixFound {
if matcher.prefixed == nil {
matcher.prefixed = make(map[string]*equalPrefixLists)
}
if _, ok := matcher.prefixed[nsPrefix]; !ok {
matcher.prefixed[nsPrefix] = &equalPrefixLists{}
}
saPrefix, saPrefixFound, prefixErr := getSaEqualPrefix(sa, matcher.prefixed[nsPrefix])
if prefixErr != nil {
return nil, prefixErr
}
if saPrefixFound && saPrefix == "" && nsPrefix == "" {
return nil, errors.New("service account name and namespace prefixes cannot both be empty (ie '*:*'")
}
} else {
if matcher.equal == nil {
matcher.equal = make(map[string]*equalPrefixLists)
}
if _, ok := matcher.equal[ns]; !ok {
matcher.equal[ns] = &equalPrefixLists{}
}
if _, _, prefixErr := getSaEqualPrefix(sa, matcher.equal[ns]); prefixErr != nil {
return nil, prefixErr
}
}
}
if len(matcher.prefixed) != 0 {
matcher.sortedPrefixes = utils.MapToSlice(matcher.prefixed)
sort.Sort(shortestPrefixSortedSlice(matcher.sortedPrefixes))
}
return matcher, nil
}
func getSaEqualPrefix(sa string, namespaceNames *equalPrefixLists) (saPrefix string, saPrefixFound bool, err error) {
saPrefix, saPrefixFound, err = getPrefix(sa)
if err != nil {
return "", false, err
}
if saPrefixFound {
if !utils.Contains(namespaceNames.prefix, saPrefix) {
namespaceNames.prefix = append(namespaceNames.prefix, saPrefix)
}
} else if !utils.Contains(namespaceNames.equal, sa) {
namespaceNames.equal = append(namespaceNames.equal, sa)
}
// sort prefixes by length/value
sort.Sort(shortestPrefixSortedSlice(namespaceNames.prefix))
return saPrefix, saPrefixFound, nil
}
func getPrefix(s string) (string, bool, error) {
wildcardIndex := strings.Index(s, "*")
if wildcardIndex == -1 {
return "", false, nil
}
if wildcardIndex != (len(s) - 1) {
return "", false, fmt.Errorf("we only allow a single wildcard at the end of the string to indicate prefix matching for allowed servicename or namespace, and we were provided with: %s", s)
}
return s[:len(s)-1], true, nil
}
// MatchesNamespacedName matches an object against all the potential options in this matcher, we first check sorted prefixes
// to try to match the shortest one that could potentially cover others
func (m *EqualPrefixNameNamespaceMatcher) MatchesNamespacedName(namespace, name string) bool {
for _, nsPrefix := range m.sortedPrefixes {
if strings.HasPrefix(namespace, nsPrefix) {
return utils.ContainsPrefixed(m.prefixed[nsPrefix].prefix, name) || utils.Contains(m.prefixed[nsPrefix].equal, name)
}
}
for ns, values := range m.equal {
if ns == namespace {
return utils.ContainsPrefixed(values.prefix, name) || utils.Contains(values.equal, name)
}
}
return false
}
|
mikeee/dapr
|
pkg/injector/namespacednamematcher/namenamespacematcher.go
|
GO
|
mit
| 4,935 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package namespacednamematcher
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func TestGetNameNamespaces(t *testing.T) {
tests := []struct {
name string
s string
wantPrefixed map[string]*equalPrefixLists
wantEqual map[string]*equalPrefixLists
wantError bool
}{
{
name: "emptyNamespaceAndSANotAllowed",
s: ":",
wantError: true,
},
{
name: "emptyPrefixesNotAllowed",
s: "*:*",
wantError: true,
},
{
name: "emptyNSPrefixButSApresent",
s: "*:sa*",
wantPrefixed: map[string]*equalPrefixLists{"": {prefix: []string{"sa"}}},
},
{
name: "missingColon",
s: "namespace",
wantError: true,
},
{
name: "simpleExact",
s: "ns:sa",
wantEqual: map[string]*equalPrefixLists{"ns": {equal: []string{"sa"}}},
},
{
name: "simpleMultipleExact",
s: "ns:sa,ns2:sa2",
wantEqual: map[string]*equalPrefixLists{"ns": {equal: []string{"sa"}}, "ns2": {equal: []string{"sa2"}}},
},
{
name: "simpleMultipleExactSameNS",
s: "ns:sa,ns:sa2",
wantEqual: map[string]*equalPrefixLists{"ns": {equal: []string{"sa", "sa2"}}},
},
{
name: "simpleMultipleExactSameNSSameSA",
s: "ns:sa,ns:sa",
wantEqual: map[string]*equalPrefixLists{"ns": {equal: []string{"sa"}}},
},
{
name: "simpleMultipleExactSameNSSameSASpaces",
s: " ns: sa , ns: sa ",
wantEqual: map[string]*equalPrefixLists{"ns": {equal: []string{"sa"}}},
},
{
name: "simplePrefixNS",
s: "namespace*:sa",
wantPrefixed: map[string]*equalPrefixLists{"namespace": {equal: []string{"sa"}}},
},
{
name: "simplePrefixNSWildcarInMiddle",
s: "names*pace:sa",
wantError: true,
},
{
name: "errPrefixSAWildcardNotAtEnd",
s: "name:sa*sa",
wantError: true,
},
{
name: "errPrefixNSWildcardNotAtEnd",
s: "nam*e:salsa",
wantError: true,
},
{
name: "errPrefixNSNSWildcardNotAtEnd",
s: "name*:sal*sa",
wantError: true,
},
{
name: "errPrefixNSCanIncludeKube",
s: "kube2-*:sa,kube-*:sa",
wantPrefixed: map[string]*equalPrefixLists{"kube2-": {equal: []string{"sa"}}, "kube-": {equal: []string{"sa"}}},
},
{
name: "errPreNSCanINcludeDapr",
s: "kube-system:sa,dapr-system:sa",
wantEqual: map[string]*equalPrefixLists{"kube-system": {equal: []string{"sa"}}, "dapr-system": {equal: []string{"sa"}}},
},
{
name: "simpleMultiplePrefixNS",
s: "namespace*:sa,namespace2*:sa",
wantPrefixed: map[string]*equalPrefixLists{"namespace": {equal: []string{"sa"}}, "namespace2": {equal: []string{"sa"}}},
},
{
name: "simplePrefixSA",
s: "namespace:service*",
wantEqual: map[string]*equalPrefixLists{"namespace": {prefix: []string{"service"}}},
},
{
name: "simplePrefixSA",
s: "namespace:service*",
wantEqual: map[string]*equalPrefixLists{"namespace": {prefix: []string{"service"}}},
},
{
name: "multiple",
s: "namespace:service*, namespace:service, namespace:service2*, namespace*:service3, namespace2:service3*, namespace3*:service3*, namespace5:service5",
wantEqual: map[string]*equalPrefixLists{
"namespace": {
prefix: []string{"service", "service2"},
equal: []string{"service"},
},
"namespace5": {
equal: []string{"service5"},
},
"namespace2": {
prefix: []string{"service3"},
},
},
wantPrefixed: map[string]*equalPrefixLists{
"namespace": {
equal: []string{"service3"},
},
"namespace3": {
prefix: []string{"service3"},
},
},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
matcher, err := CreateFromString(tc.s)
if tc.wantError {
require.Error(t, err, "expecting error but did not get it")
return
} else {
require.NoError(t, err, "not expecting error to happen")
}
assert.Equalf(t, tc.wantPrefixed, matcher.prefixed, "CreateFromString(%v)", tc.s)
assert.Equalf(t, tc.wantEqual, matcher.equal, "CreateFromString(%v)", tc.s)
})
}
}
func TestEqualPrefixNameNamespaceMatcherMatchesObject(t *testing.T) {
tests := []struct {
name string
namespaceNames string
objectMeta metav1.ObjectMeta
wantMatch bool
wantError bool
}{
{
name: "equalPredicate",
namespaceNames: "ns:sa",
objectMeta: metav1.ObjectMeta{Name: "sa", Namespace: "ns"},
wantMatch: true,
wantError: false,
},
{
name: "equalPredicateNoMatch",
namespaceNames: "ns:sa,ns:sb,ns:sc",
objectMeta: metav1.ObjectMeta{Name: "sd", Namespace: "ns"},
wantMatch: false,
wantError: false,
},
{
name: "equalPredicateNoMatchWrongNS",
namespaceNames: "ns:sa,ns:sb,ns:sc",
objectMeta: metav1.ObjectMeta{Name: "sd", Namespace: "ns2"},
wantMatch: false,
wantError: false,
},
{
name: "equalNamespacePrefixSA",
namespaceNames: "ns:vc-sa*",
objectMeta: metav1.ObjectMeta{Name: "vc-sa-1234", Namespace: "ns"},
wantMatch: true,
wantError: false,
},
{
name: "equalNamespacePrefixSABadPrefix",
namespaceNames: "ns:vc-sa*sa",
objectMeta: metav1.ObjectMeta{Name: "vc-sa-1234", Namespace: "ns"},
wantMatch: true,
wantError: true,
},
{
name: "equalNamespacePrefixSANoMatch",
namespaceNames: "ns:vc-sa*",
objectMeta: metav1.ObjectMeta{Name: "vc-sb-1234", Namespace: "ns"},
wantMatch: false,
wantError: false,
},
{
name: "anyNamespaceWithPrefixSA",
namespaceNames: "*:vc-sa*",
objectMeta: metav1.ObjectMeta{Name: "vc-sa-1234", Namespace: "ns123456"},
wantMatch: true,
wantError: false,
},
{
name: "anySAWithEqualNamespace",
namespaceNames: "default:*,my-ns:*",
objectMeta: metav1.ObjectMeta{Name: "vc-sa-1234", Namespace: "default"},
wantMatch: true,
wantError: false,
},
{
name: "equalNamespaceMultiplePrefixSA",
namespaceNames: "ns:vc-sa*,ns:vc-sb*",
objectMeta: metav1.ObjectMeta{Name: "vc-sb-1234", Namespace: "ns"},
wantMatch: true,
wantError: false,
},
{
name: "prefixNamespaceMultiplePrefixSA",
namespaceNames: "name*:vc-sa*,name*:vc-sb*",
objectMeta: metav1.ObjectMeta{Name: "vc-sb-1234", Namespace: "namespace"},
wantMatch: true,
wantError: false,
},
{
name: "prefixNamespaceMultiplePrefixSANoMatch",
namespaceNames: "name*:vc-sa*,name*:vc-sb*",
objectMeta: metav1.ObjectMeta{Name: "vc-sb-1234", Namespace: "namspace"},
wantMatch: false,
wantError: false,
},
}
for _, tc := range tests {
matcher, err := CreateFromString(tc.namespaceNames)
if tc.wantError {
require.Error(t, err, "expecting error")
continue
}
sa := &corev1.ServiceAccount{
ObjectMeta: tc.objectMeta,
}
t.Run(tc.name, func(t *testing.T) {
assert.Equalf(t, tc.wantMatch, matcher.MatchesNamespacedName(sa.Namespace, sa.Name), "MatchesObject(%v)", tc.objectMeta)
})
}
}
|
mikeee/dapr
|
pkg/injector/namespacednamematcher/namenamespacematcher_test.go
|
GO
|
mit
| 7,983 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package patcher
import (
"encoding/json"
"fmt"
jsonpatch "github.com/evanphx/json-patch/v5"
corev1 "k8s.io/api/core/v1"
"github.com/dapr/kit/ptr"
)
const (
// Path for patching containers.
PatchPathContainers = "/spec/containers"
// Path for patching volumes.
PatchPathVolumes = "/spec/volumes"
// Path for patching labels.
PatchPathLabels = "/metadata/labels"
)
// NewPatchOperation returns a jsonpatch.Operation with the provided properties.
// This patch represents a discrete change to be applied to a Kubernetes resource.
func NewPatchOperation(op string, path string, value any) jsonpatch.Operation {
patchOp := jsonpatch.Operation{
"op": ptr.Of(json.RawMessage(`"` + op + `"`)),
"path": ptr.Of(json.RawMessage(`"` + path + `"`)),
}
if value != nil {
val, _ := json.Marshal(value)
if len(val) > 0 && string(val) != "null" {
patchOp["value"] = ptr.Of[json.RawMessage](val)
}
}
return patchOp
}
// GetEnvPatchOperations adds new environment variables only if they do not exist.
// It does not override existing values for those variables if they have been defined already.
func GetEnvPatchOperations(envs []corev1.EnvVar, addEnv []corev1.EnvVar, containerIdx int) jsonpatch.Patch {
path := fmt.Sprintf("%s/%d/env", PatchPathContainers, containerIdx)
if len(envs) == 0 {
// If there are no environment variables defined in the container, we initialize a slice of environment vars.
return jsonpatch.Patch{
NewPatchOperation("add", path, addEnv),
}
}
// If there are existing env vars, then we are adding to an existing slice of env vars.
path += "/-"
// Get a map with all the existing env var names
existing := make(map[string]struct{}, len(envs))
for _, e := range envs {
existing[e.Name] = struct{}{}
}
patchOps := make(jsonpatch.Patch, len(addEnv))
n := 0
for _, env := range addEnv {
// Add only env vars that do not conflict with existing user defined/injected env vars.
_, ok := existing[env.Name]
if ok {
continue
}
patchOps[n] = NewPatchOperation("add", path, env)
n++
}
return patchOps[:n]
}
// GetVolumeMountPatchOperations gets the patch operations for volume mounts
func GetVolumeMountPatchOperations(volumeMounts []corev1.VolumeMount, addMounts []corev1.VolumeMount, containerIdx int) jsonpatch.Patch {
path := fmt.Sprintf("%s/%d/volumeMounts", PatchPathContainers, containerIdx)
if len(volumeMounts) == 0 {
// If there are no volume mounts defined in the container, we initialize a slice of volume mounts.
return jsonpatch.Patch{
NewPatchOperation("add", path, addMounts),
}
}
// If there are existing volume mounts, then we are adding to an existing slice of volume mounts.
path += "/-"
// Get a map with all the existingMounts mount paths
existingMounts := make(map[string]struct{}, len(volumeMounts))
existingNames := make(map[string]struct{}, len(volumeMounts))
for _, m := range volumeMounts {
existingMounts[m.MountPath] = struct{}{}
existingNames[m.Name] = struct{}{}
}
patchOps := make(jsonpatch.Patch, len(addMounts))
n := 0
var ok bool
for _, mount := range addMounts {
// Do not add the mount if a volume is already mounted on the same path or has the same name
if _, ok = existingMounts[mount.MountPath]; ok {
continue
}
if _, ok = existingNames[mount.Name]; ok {
continue
}
patchOps[n] = NewPatchOperation("add", path, mount)
n++
}
return patchOps[:n]
}
|
mikeee/dapr
|
pkg/injector/patcher/patch.go
|
GO
|
mit
| 3,983 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package patcher contains utilities to patch a Pod to inject the Dapr sidecar container.
package patcher
import (
"encoding/json"
"fmt"
jsonpatch "github.com/evanphx/json-patch/v5"
corev1 "k8s.io/api/core/v1"
"github.com/dapr/kit/logger"
)
var log = logger.NewLogger("dapr.injector")
// PatchPod applies a jsonpatch.Patch to a Pod and returns the modified object.
func PatchPod(pod *corev1.Pod, patch jsonpatch.Patch) (*corev1.Pod, error) {
// Apply the patch
podJSON, err := json.Marshal(pod)
if err != nil {
return nil, fmt.Errorf("failed to marshal pod to JSON: %w", err)
}
newJSON, err := patch.Apply(podJSON)
if err != nil {
return nil, fmt.Errorf("failed to apply patch: %w", err)
}
// Get the Pod object
newPod := &corev1.Pod{}
err = json.Unmarshal(newJSON, newPod)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal JSON into a Pod: %w", err)
}
return newPod, nil
}
|
mikeee/dapr
|
pkg/injector/patcher/patcher.go
|
GO
|
mit
| 1,477 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package patcher
import (
"fmt"
"strconv"
"strings"
)
// Service represents a Dapr control plane service's information.
type Service struct {
name string
port int
}
// Predefined services
var (
// Dapr API service.
ServiceAPI = Service{"dapr-api", 443}
// Dapr placement service.
ServicePlacement = Service{"dapr-placement-server", 50005}
// Dapr Sentry service.
ServiceSentry = Service{"dapr-sentry", 443}
)
// NewService returns a Service with values from a string in the format "<name>:<port>"
func NewService(val string) (srv Service, err error) {
var (
ok bool
portStr string
)
srv.name, portStr, ok = strings.Cut(val, ":")
if !ok || srv.name == "" || portStr == "" {
return srv, fmt.Errorf("service is not in the correct format '<name>:<port>': %s", val)
}
srv.port, err = strconv.Atoi(portStr)
if err != nil || srv.port <= 0 {
return srv, fmt.Errorf("service is not in the correct format '<name>:<port>': port is invalid")
}
return srv, nil
}
// Address returns the address of a Dapr control plane service
func (svc Service) Address(namespace, clusterDomain string) string {
return fmt.Sprintf("%s.%s.svc.%s:%d", svc.name, namespace, clusterDomain, svc.port)
}
|
mikeee/dapr
|
pkg/injector/patcher/services.go
|
GO
|
mit
| 1,769 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package patcher
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestServiceAddress(t *testing.T) {
testCases := []struct {
svc Service
namespace string
clusterDomain string
expect string
}{
{
svc: Service{"a", 80},
namespace: "b",
clusterDomain: "cluster.local",
expect: "a.b.svc.cluster.local:80",
},
{
svc: Service{"app", 50001},
namespace: "default",
clusterDomain: "selfdefine.domain",
expect: "app.default.svc.selfdefine.domain:50001",
},
{
svc: ServiceSentry,
namespace: "foo",
clusterDomain: "selfdefine.domain",
expect: "dapr-sentry.foo.svc.selfdefine.domain:443",
},
}
for _, tc := range testCases {
dns := tc.svc.Address(tc.namespace, tc.clusterDomain)
assert.Equal(t, tc.expect, dns)
}
}
func TestNewService(t *testing.T) {
testCases := []struct {
input string
expected Service
err bool
}{
{
input: "a:80",
expected: Service{"a", 80},
err: false,
},
{
input: "app:50001",
expected: Service{"app", 50001},
err: false,
},
{
input: "invalid",
expected: Service{},
err: true,
},
{
input: "name:",
expected: Service{},
err: true,
},
{
input: ":80",
expected: Service{},
err: true,
},
}
for _, tc := range testCases {
srv, err := NewService(tc.input)
if tc.err {
require.Error(t, err)
} else {
require.NoError(t, err)
assert.Equal(t, tc.expected, srv)
}
}
}
|
mikeee/dapr
|
pkg/injector/patcher/services_test.go
|
GO
|
mit
| 2,175 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package patcher
import (
"reflect"
"strconv"
"strings"
"github.com/spf13/cast"
corev1 "k8s.io/api/core/v1"
injectorConsts "github.com/dapr/dapr/pkg/injector/consts"
"github.com/dapr/kit/utils"
)
// GetInjectedComponentContainersFn is a function that returns the list of component containers for a given appID and namespace.
type GetInjectedComponentContainersFn = func(appID string, namespace string) ([]corev1.Container, error)
// SidecarConfig contains the configuration for the sidecar container.
// Its parameters can be read from annotations on a pod.
// Note: make sure that the annotations defined here are in-sync with the constants in the pkg/injector/annotations package.
type SidecarConfig struct {
GetInjectedComponentContainers GetInjectedComponentContainersFn
Mode injectorConsts.DaprMode `default:"kubernetes"`
Namespace string
MTLSEnabled bool
Identity string
IgnoreEntrypointTolerations []corev1.Toleration
ImagePullPolicy corev1.PullPolicy
OperatorAddress string
SentryAddress string
RunAsNonRoot bool
EnableK8sDownwardAPIs bool
ReadOnlyRootFilesystem bool
SidecarDropALLCapabilities bool
DisableTokenVolume bool
CurrentTrustAnchors []byte
ControlPlaneNamespace string
ControlPlaneTrustDomain string
ActorsService string
RemindersService string
SentrySPIFFEID string
SidecarHTTPPort int32 `default:"3500"`
SidecarAPIGRPCPort int32 `default:"50001"`
SidecarInternalGRPCPort int32 `default:"50002"`
SidecarPublicPort int32 `default:"3501"`
Enabled bool `annotation:"dapr.io/enabled"`
AppPort int32 `annotation:"dapr.io/app-port"`
Config string `annotation:"dapr.io/config"`
AppProtocol string `annotation:"dapr.io/app-protocol" default:"http"`
AppSSL bool `annotation:"dapr.io/app-ssl"` // TODO: Deprecated in Dapr 1.11; remove in a future Dapr version
AppID string `annotation:"dapr.io/app-id"`
EnableProfiling bool `annotation:"dapr.io/enable-profiling"`
LogLevel string `annotation:"dapr.io/log-level" default:"info"`
APITokenSecret string `annotation:"dapr.io/api-token-secret"`
AppTokenSecret string `annotation:"dapr.io/app-token-secret"`
LogAsJSON bool `annotation:"dapr.io/log-as-json"`
AppMaxConcurrency *int `annotation:"dapr.io/app-max-concurrency"`
EnableMetrics bool `annotation:"dapr.io/enable-metrics" default:"true"`
SidecarMetricsPort int32 `annotation:"dapr.io/metrics-port" default:"9090"`
EnableDebug bool `annotation:"dapr.io/enable-debug" default:"false"`
SidecarDebugPort int32 `annotation:"dapr.io/debug-port" default:"40000"`
Env string `annotation:"dapr.io/env"`
SidecarCPURequest string `annotation:"dapr.io/sidecar-cpu-request"`
SidecarCPULimit string `annotation:"dapr.io/sidecar-cpu-limit"`
SidecarMemoryRequest string `annotation:"dapr.io/sidecar-memory-request"`
SidecarMemoryLimit string `annotation:"dapr.io/sidecar-memory-limit"`
SidecarListenAddresses string `annotation:"dapr.io/sidecar-listen-addresses" default:"[::1],127.0.0.1"`
SidecarLivenessProbeDelaySeconds int32 `annotation:"dapr.io/sidecar-liveness-probe-delay-seconds" default:"3"`
SidecarLivenessProbeTimeoutSeconds int32 `annotation:"dapr.io/sidecar-liveness-probe-timeout-seconds" default:"3"`
SidecarLivenessProbePeriodSeconds int32 `annotation:"dapr.io/sidecar-liveness-probe-period-seconds" default:"6"`
SidecarLivenessProbeThreshold int32 `annotation:"dapr.io/sidecar-liveness-probe-threshold" default:"3"`
SidecarReadinessProbeDelaySeconds int32 `annotation:"dapr.io/sidecar-readiness-probe-delay-seconds" default:"3"`
SidecarReadinessProbeTimeoutSeconds int32 `annotation:"dapr.io/sidecar-readiness-probe-timeout-seconds" default:"3"`
SidecarReadinessProbePeriodSeconds int32 `annotation:"dapr.io/sidecar-readiness-probe-period-seconds" default:"6"`
SidecarReadinessProbeThreshold int32 `annotation:"dapr.io/sidecar-readiness-probe-threshold" default:"3"`
SidecarImage string `annotation:"dapr.io/sidecar-image"`
SidecarSeccompProfileType string `annotation:"dapr.io/sidecar-seccomp-profile-type"`
HTTPMaxRequestSize *int `annotation:"dapr.io/http-max-request-size"` // Legacy flag
MaxBodySize string `annotation:"dapr.io/max-body-size"`
HTTPReadBufferSize *int `annotation:"dapr.io/http-read-buffer-size"` // Legacy flag
ReadBufferSize string `annotation:"dapr.io/read-buffer-size"`
GracefulShutdownSeconds int `annotation:"dapr.io/graceful-shutdown-seconds" default:"-1"`
BlockShutdownDuration *string `annotation:"dapr.io/block-shutdown-duration"`
EnableAPILogging *bool `annotation:"dapr.io/enable-api-logging"`
UnixDomainSocketPath string `annotation:"dapr.io/unix-domain-socket-path"`
VolumeMounts string `annotation:"dapr.io/volume-mounts"`
VolumeMountsRW string `annotation:"dapr.io/volume-mounts-rw"`
DisableBuiltinK8sSecretStore bool `annotation:"dapr.io/disable-builtin-k8s-secret-store"`
EnableAppHealthCheck bool `annotation:"dapr.io/enable-app-health-check"`
AppHealthCheckPath string `annotation:"dapr.io/app-health-check-path" default:"/healthz"`
AppHealthProbeInterval int32 `annotation:"dapr.io/app-health-probe-interval" default:"5"` // In seconds
AppHealthProbeTimeout int32 `annotation:"dapr.io/app-health-probe-timeout" default:"500"` // In milliseconds
AppHealthThreshold int32 `annotation:"dapr.io/app-health-threshold" default:"3"`
PlacementAddress string `annotation:"dapr.io/placement-host-address"`
PluggableComponents string `annotation:"dapr.io/pluggable-components"`
PluggableComponentsSocketsFolder string `annotation:"dapr.io/pluggable-components-sockets-folder"`
ComponentContainer string `annotation:"dapr.io/component-container"`
InjectPluggableComponents bool `annotation:"dapr.io/inject-pluggable-components"`
AppChannelAddress string `annotation:"dapr.io/app-channel-address"`
pod *corev1.Pod
}
// NewSidecarConfig returns a ContainerConfig object for a pod.
func NewSidecarConfig(pod *corev1.Pod) *SidecarConfig {
c := &SidecarConfig{
pod: pod,
}
c.setDefaultValues()
return c
}
func (c *SidecarConfig) SetFromPodAnnotations() {
c.setFromAnnotations(c.pod.Annotations)
}
func (c *SidecarConfig) setDefaultValues() {
// Iterate through the fields using reflection
val := reflect.ValueOf(c).Elem()
for i := 0; i < val.NumField(); i++ {
fieldT := val.Type().Field(i)
fieldV := val.Field(i)
def := fieldT.Tag.Get("default")
if !fieldV.CanSet() || def == "" {
continue
}
// Assign the default value
setValueFromString(fieldT.Type, fieldV, def, "")
}
}
// setFromAnnotations updates the object with properties from an annotation map.
func (c *SidecarConfig) setFromAnnotations(an map[string]string) {
// Iterate through the fields using reflection
val := reflect.ValueOf(c).Elem()
for i := 0; i < val.NumField(); i++ {
fieldV := val.Field(i)
fieldT := val.Type().Field(i)
key := fieldT.Tag.Get("annotation")
if !fieldV.CanSet() || key == "" {
continue
}
// Skip annotations that are not defined or which have an empty value
if an[key] == "" {
continue
}
// Assign the value
setValueFromString(fieldT.Type, fieldV, an[key], key)
}
}
func setValueFromString(rt reflect.Type, rv reflect.Value, val string, key string) bool {
switch rt.Kind() {
case reflect.Pointer:
pt := rt.Elem()
pv := reflect.New(rt.Elem()).Elem()
if setValueFromString(pt, pv, val, key) {
rv.Set(pv.Addr())
}
case reflect.String:
rv.SetString(val)
case reflect.Bool:
rv.SetBool(utils.IsTruthy(val))
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
v, err := strconv.ParseInt(val, 10, 64)
if err == nil {
rv.SetInt(v)
} else {
log.Warnf("Failed to parse int value from annotation %s (annotation will be ignored): %v", key, err)
return false
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
v, err := strconv.ParseUint(val, 10, 64)
if err == nil {
rv.SetUint(v)
} else {
log.Warnf("Failed to parse uint value from annotation %s (annotation will be ignored): %v", key, err)
return false
}
}
return true
}
// String implements fmt.Stringer and is used to print the state of the object, primarily for debugging purposes.
func (c *SidecarConfig) String() string {
return c.toString(false)
}
// StringAll returns the list of all annotations (including empty ones), primarily for debugging purposes.
func (c *SidecarConfig) StringAll() string {
return c.toString(true)
}
func (c *SidecarConfig) toString(includeAll bool) string {
res := strings.Builder{}
// Iterate through the fields using reflection
val := reflect.ValueOf(c).Elem()
for i := 0; i < val.NumField(); i++ {
fieldT := val.Type().Field(i)
fieldV := val.Field(i)
key := fieldT.Tag.Get("annotation")
def := fieldT.Tag.Get("default")
if key == "" {
continue
}
// Do not print default values or zero values when there's no default
val := cast.ToString(fieldV.Interface())
if includeAll || (def != "" && val != def) || (def == "" && !fieldV.IsZero()) {
res.WriteString(key + ": " + strconv.Quote(val) + "\n")
}
}
return res.String()
}
|
mikeee/dapr
|
pkg/injector/patcher/sidecar.go
|
GO
|
mit
| 10,866 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package patcher
import (
"encoding/json"
"strings"
jsonpatch "github.com/evanphx/json-patch/v5"
corev1 "k8s.io/api/core/v1"
componentsapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/injector/annotations"
injectorConsts "github.com/dapr/dapr/pkg/injector/consts"
"github.com/dapr/dapr/utils"
)
// splitContainers split containers between:
// - appContainers are containers related to apps.
// - componentContainers are containers related to pluggable components.
func (c *SidecarConfig) splitContainers() (appContainers map[int]corev1.Container, componentContainers map[int]corev1.Container) {
appContainers = make(map[int]corev1.Container, len(c.pod.Spec.Containers))
componentContainers = make(map[int]corev1.Container, len(c.pod.Spec.Containers))
componentsNames := strings.Split(c.PluggableComponents, ",")
isComponent := make(map[string]bool, len(componentsNames))
for _, name := range componentsNames {
isComponent[name] = true
}
for idx, container := range c.pod.Spec.Containers {
if isComponent[container.Name] {
componentContainers[idx] = container
} else {
appContainers[idx] = container
}
}
return appContainers, componentContainers
}
// componentsPatchOps returns the patch operations required to properly bootstrap the pluggable component and the respective volume mount for the sidecar.
func (c *SidecarConfig) componentsPatchOps(componentContainers map[int]corev1.Container, injectedContainers []corev1.Container) (jsonpatch.Patch, *corev1.VolumeMount) {
if len(componentContainers) == 0 && len(injectedContainers) == 0 {
return jsonpatch.Patch{}, nil
}
patches := make(jsonpatch.Patch, 0, (len(injectedContainers)+len(componentContainers)+1)*2)
mountPath := c.PluggableComponentsSocketsFolder
if mountPath == "" {
mountPath = utils.GetEnvOrElse(injectorConsts.ComponentsUDSMountPathEnvVar, injectorConsts.ComponentsUDSDefaultFolder)
}
sharedSocketVolume, sharedSocketVolumeMount, volumePatch := c.addSharedSocketVolume(mountPath)
patches = append(patches, volumePatch)
componentsEnvVars := []corev1.EnvVar{{
Name: injectorConsts.ComponentsUDSMountPathEnvVar,
Value: sharedSocketVolumeMount.MountPath,
}}
for idx, container := range componentContainers {
patches = append(patches, GetEnvPatchOperations(container.Env, componentsEnvVars, idx)...)
patches = append(patches, GetVolumeMountPatchOperations(container.VolumeMounts, []corev1.VolumeMount{sharedSocketVolumeMount}, idx)...)
}
podVolumes := make(map[string]bool, len(c.pod.Spec.Volumes)+1)
podVolumes[sharedSocketVolume.Name] = true
for _, volume := range c.pod.Spec.Volumes {
podVolumes[volume.Name] = true
}
for _, container := range injectedContainers {
container.Env = append(container.Env, componentsEnvVars...)
// mount volume as empty dir by default.
_, patch := emptyVolumePatches(container, podVolumes)
patches = append(patches, patch...)
container.VolumeMounts = append(container.VolumeMounts, sharedSocketVolumeMount)
patches = append(patches,
NewPatchOperation("add", PatchPathContainers+"/-", container),
)
}
return patches, &sharedSocketVolumeMount
}
// Injectable parses the container definition from components annotations returning them as a list. Uses the appID to filter
// only the eligble components for such apps avoiding injecting containers that will not be used.
func Injectable(appID string, components []componentsapi.Component) []corev1.Container {
componentContainers := make([]corev1.Container, 0, len(components))
componentImages := make(map[string]bool, len(components))
for _, component := range components {
containerAsStr := component.Annotations[annotations.KeyPluggableComponentContainer]
if containerAsStr == "" {
continue
}
var container *corev1.Container
if err := json.Unmarshal([]byte(containerAsStr), &container); err != nil {
log.Warnf("Could not unmarshal container %s: %v", component.Name, err)
continue
}
if componentImages[container.Image] {
continue
}
appScopped := len(component.Scopes) == 0
for _, scoppedApp := range component.Scopes {
if scoppedApp == appID {
appScopped = true
break
}
}
if appScopped {
componentImages[container.Image] = true
// if container name is not set, the component name will be used ensuring uniqueness
if container.Name == "" {
container.Name = component.Name
}
componentContainers = append(componentContainers, *container)
}
}
return componentContainers
}
// emptyVolumePatches return all patches for pod emptyvolumes (the default value for injected pluggable components) and the volumes.
func emptyVolumePatches(container corev1.Container, podVolumes map[string]bool) ([]corev1.Volume, jsonpatch.Patch) {
volumes := make([]corev1.Volume, 0, len(container.VolumeMounts))
volumePatches := make(jsonpatch.Patch, 0, len(container.VolumeMounts))
for _, volumeMount := range container.VolumeMounts {
if podVolumes[volumeMount.Name] {
continue
}
emptyDirVolume := corev1.Volume{
Name: volumeMount.Name,
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
}
volumes = append(volumes, emptyDirVolume)
volumePatches = append(volumePatches,
NewPatchOperation("add", PatchPathVolumes+"/-", emptyDirVolume),
)
}
return volumes, volumePatches
}
// addSharedSocketVolume adds the new volume to the pod and return the patch operation, the volume, and the volume mount.
func (c *SidecarConfig) addSharedSocketVolume(mountPath string) (corev1.Volume, corev1.VolumeMount, jsonpatch.Operation) {
sharedSocketVolume := sharedComponentsSocketVolume()
sharedSocketVolumeMount := sharedComponentsUnixSocketVolumeMount(mountPath)
var volumePatch jsonpatch.Operation
if len(c.pod.Spec.Volumes) == 0 {
volumePatch = NewPatchOperation("add", PatchPathVolumes, []corev1.Volume{sharedSocketVolume})
} else {
volumePatch = NewPatchOperation("add", PatchPathVolumes+"/-", sharedSocketVolume)
}
return sharedSocketVolume, sharedSocketVolumeMount, volumePatch
}
// sharedComponentsSocketVolume creates a shared unix socket volume to be used by sidecar.
func sharedComponentsSocketVolume() corev1.Volume {
return corev1.Volume{
Name: injectorConsts.ComponentsUDSVolumeName,
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
}
}
// sharedComponentsUnixSocketVolumeMount creates a shared unix socket volume mount to be used by pluggable component.
func sharedComponentsUnixSocketVolumeMount(mountPath string) corev1.VolumeMount {
return corev1.VolumeMount{
Name: injectorConsts.ComponentsUDSVolumeName,
MountPath: mountPath,
}
}
|
mikeee/dapr
|
pkg/injector/patcher/sidecar_components.go
|
GO
|
mit
| 7,255 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package patcher
import (
"encoding/json"
"fmt"
"testing"
jsonpatch "github.com/evanphx/json-patch/v5"
"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
commonapi "github.com/dapr/dapr/pkg/apis/common"
componentsapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/injector/annotations"
injectorConsts "github.com/dapr/dapr/pkg/injector/consts"
)
func TestComponentsPatch(t *testing.T) {
const appName, componentImage, componentName = "my-app", "my-image", "my-component"
socketSharedVolumeMount := sharedComponentsUnixSocketVolumeMount(injectorConsts.ComponentsUDSDefaultFolder)
appContainer := corev1.Container{
Name: "app",
}
testCases := []struct {
name string
appID string
componentsList []componentsapi.Component
pod *corev1.Pod
expPatch jsonpatch.Patch
expMount *corev1.VolumeMount
}{
{
"patch should return empty patch operations when none pluggable components are specified",
"",
[]componentsapi.Component{},
&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{},
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{appContainer},
},
},
jsonpatch.Patch{},
nil,
},
{
"patch should create pluggable component unix socket volume",
"",
[]componentsapi.Component{},
&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
annotations.KeyPluggableComponents: "component",
},
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{appContainer, {
Name: "component",
}},
},
},
jsonpatch.Patch{
NewPatchOperation("add", PatchPathVolumes, []corev1.Volume{sharedComponentsSocketVolume()}),
NewPatchOperation("add", PatchPathContainers+"/1/env", []corev1.EnvVar{{
Name: injectorConsts.ComponentsUDSMountPathEnvVar,
Value: socketSharedVolumeMount.MountPath,
}}),
NewPatchOperation("add", PatchPathContainers+"/1/volumeMounts", []corev1.VolumeMount{socketSharedVolumeMount}),
},
&socketSharedVolumeMount,
},
{
"patch should not create injectable containers operations when app is scopped but has no annotations",
appName,
[]componentsapi.Component{
{
Scoped: commonapi.Scoped{Scopes: []string{appName}},
},
},
&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
annotations.KeyPluggableComponents: "component",
},
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{appContainer, {
Name: "component",
}},
},
},
jsonpatch.Patch{
NewPatchOperation("add", PatchPathVolumes, []corev1.Volume{sharedComponentsSocketVolume()}),
NewPatchOperation("add", PatchPathContainers+"/1/env", []corev1.EnvVar{{
Name: injectorConsts.ComponentsUDSMountPathEnvVar,
Value: socketSharedVolumeMount.MountPath,
}}),
NewPatchOperation("add", PatchPathContainers+"/1/volumeMounts", []corev1.VolumeMount{socketSharedVolumeMount}),
},
&socketSharedVolumeMount,
},
{
"patch should create injectable containers operations when app is scopped but and has annotations",
appName,
[]componentsapi.Component{{
ObjectMeta: metav1.ObjectMeta{
Name: componentName,
Annotations: map[string]string{
annotations.KeyPluggableComponentContainer: fmt.Sprintf(`{
"image": "%s",
"env": [{"name": "A", "value": "B"}],
"volumeMounts": [{"mountPath": "/read-only", "name": "readonly", "readOnly": true}, {"mountPath": "/read-write", "name": "readwrite", "readOnly": false}]
}`, componentImage),
},
},
Scoped: commonapi.Scoped{Scopes: []string{appName}},
}},
&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
annotations.KeyPluggableComponents: "component",
},
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{appContainer, {
Name: "component",
}},
},
},
jsonpatch.Patch{
NewPatchOperation("add", PatchPathVolumes, []corev1.Volume{sharedComponentsSocketVolume()}),
NewPatchOperation("add", PatchPathContainers+"/1/env", []corev1.EnvVar{{
Name: injectorConsts.ComponentsUDSMountPathEnvVar,
Value: socketSharedVolumeMount.MountPath,
}}),
NewPatchOperation("add", PatchPathContainers+"/1/volumeMounts", []corev1.VolumeMount{socketSharedVolumeMount}),
NewPatchOperation("add", PatchPathVolumes+"/-", corev1.Volume{
Name: "readonly",
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
}),
NewPatchOperation("add", PatchPathVolumes+"/-", corev1.Volume{
Name: "readwrite",
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
}),
NewPatchOperation("add", PatchPathContainers+"/-", corev1.Container{
Name: componentName,
Image: componentImage,
Env: []corev1.EnvVar{
{
Name: "A",
Value: "B",
},
{
Name: injectorConsts.ComponentsUDSMountPathEnvVar,
Value: socketSharedVolumeMount.MountPath,
},
},
VolumeMounts: []corev1.VolumeMount{
{
Name: "readonly",
ReadOnly: true,
MountPath: "/read-only",
},
{
Name: "readwrite",
ReadOnly: false,
MountPath: "/read-write",
},
socketSharedVolumeMount,
},
}),
},
&socketSharedVolumeMount,
},
{
"patch should add pluggable component unix socket volume when pod already has volumes",
"",
[]componentsapi.Component{},
&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
annotations.KeyPluggableComponents: "component",
},
},
Spec: corev1.PodSpec{
Volumes: []corev1.Volume{{}},
Containers: []corev1.Container{appContainer, {
Name: "component",
}},
},
},
jsonpatch.Patch{
NewPatchOperation("add", PatchPathVolumes+"/-", sharedComponentsSocketVolume()),
NewPatchOperation("add", PatchPathContainers+"/1/env", []corev1.EnvVar{{
Name: injectorConsts.ComponentsUDSMountPathEnvVar,
Value: socketSharedVolumeMount.MountPath,
}}),
NewPatchOperation("add", PatchPathContainers+"/1/volumeMounts", []corev1.VolumeMount{socketSharedVolumeMount}),
},
&socketSharedVolumeMount,
},
}
for _, test := range testCases {
t.Run(test.name, func(t *testing.T) {
c := NewSidecarConfig(test.pod)
c.SetFromPodAnnotations()
_, componentContainers := c.splitContainers()
patch, volumeMount := c.componentsPatchOps(componentContainers, Injectable(test.appID, test.componentsList))
patchJSON, _ := json.Marshal(patch)
expPatchJSON, _ := json.Marshal(test.expPatch)
assert.Equal(t, string(expPatchJSON), string(patchJSON))
assert.Equal(t, test.expMount, volumeMount)
})
}
}
|
mikeee/dapr
|
pkg/injector/patcher/sidecar_components_test.go
|
GO
|
mit
| 7,541 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package patcher
import (
"fmt"
"path"
"regexp"
"strconv"
"strings"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/util/intstr"
"github.com/dapr/dapr/pkg/config/protocol"
injectorConsts "github.com/dapr/dapr/pkg/injector/consts"
securityConsts "github.com/dapr/dapr/pkg/security/consts"
"github.com/dapr/dapr/utils"
"github.com/dapr/kit/ptr"
)
type getSidecarContainerOpts struct {
VolumeMounts []corev1.VolumeMount
ComponentsSocketsVolumeMount *corev1.VolumeMount
}
// getSidecarContainer returns the Container object for the sidecar.
func (c *SidecarConfig) getSidecarContainer(opts getSidecarContainerOpts) (*corev1.Container, error) {
// Ports for the daprd container
ports := []corev1.ContainerPort{
{
ContainerPort: c.SidecarHTTPPort,
Name: injectorConsts.SidecarHTTPPortName,
},
{
ContainerPort: c.SidecarAPIGRPCPort,
Name: injectorConsts.SidecarGRPCPortName,
},
{
ContainerPort: c.SidecarInternalGRPCPort,
Name: injectorConsts.SidecarInternalGRPCPortName,
},
{
ContainerPort: c.SidecarMetricsPort,
Name: injectorConsts.SidecarMetricsPortName,
},
}
// Get the command (/daprd) and all CLI flags
cmd := []string{"/daprd"}
args := []string{
"--dapr-http-port", strconv.FormatInt(int64(c.SidecarHTTPPort), 10),
"--dapr-grpc-port", strconv.FormatInt(int64(c.SidecarAPIGRPCPort), 10),
"--dapr-internal-grpc-port", strconv.FormatInt(int64(c.SidecarInternalGRPCPort), 10),
"--dapr-listen-addresses", c.SidecarListenAddresses,
"--dapr-public-port", strconv.FormatInt(int64(c.SidecarPublicPort), 10),
"--app-id", c.GetAppID(),
"--app-protocol", c.AppProtocol,
"--log-level", c.LogLevel,
"--dapr-graceful-shutdown-seconds", strconv.Itoa(c.GracefulShutdownSeconds),
}
// Mode is omitted if it's an unsupported value
switch c.Mode {
case injectorConsts.ModeKubernetes:
args = append(args, "--mode", "kubernetes")
case injectorConsts.ModeStandalone:
args = append(args, "--mode", "standalone")
}
if c.OperatorAddress != "" {
args = append(args, "--control-plane-address", c.OperatorAddress)
}
if c.SentryAddress != "" {
args = append(args, "--sentry-address", c.SentryAddress)
}
if c.AppPort > 0 {
args = append(args, "--app-port", strconv.FormatInt(int64(c.AppPort), 10))
}
if c.EnableMetrics {
args = append(args,
"--enable-metrics",
"--metrics-port", strconv.FormatInt(int64(c.SidecarMetricsPort), 10),
)
}
if c.Config != "" {
args = append(args, "--config", c.Config)
}
if c.AppChannelAddress != "" {
args = append(args, "--app-channel-address", c.AppChannelAddress)
}
// Actor/placement/reminders services
// Note that PlacementAddress takes priority over ActorsAddress
if c.PlacementAddress != "" {
args = append(args, "--placement-host-address", c.PlacementAddress)
} else if c.ActorsService != "" {
args = append(args, "--actors-service", c.ActorsService)
}
if c.RemindersService != "" {
args = append(args, "--reminders-service", c.RemindersService)
}
// --enable-api-logging is set if and only if there's an explicit value (true or false) for that
// This is set explicitly even if "false"
// This is because if this CLI flag is missing, the default specified in the Config CRD is used
if c.EnableAPILogging != nil {
args = append(args, "--enable-api-logging="+strconv.FormatBool(*c.EnableAPILogging))
}
if c.DisableBuiltinK8sSecretStore {
args = append(args, "--disable-builtin-k8s-secret-store")
}
if c.EnableAppHealthCheck {
args = append(args,
"--enable-app-health-check",
"--app-health-check-path", c.AppHealthCheckPath,
"--app-health-probe-interval", strconv.FormatInt(int64(c.AppHealthProbeInterval), 10),
"--app-health-probe-timeout", strconv.FormatInt(int64(c.AppHealthProbeTimeout), 10),
"--app-health-threshold", strconv.FormatInt(int64(c.AppHealthThreshold), 10),
)
}
if c.LogAsJSON {
args = append(args, "--log-as-json")
}
if c.EnableProfiling {
args = append(args, "--enable-profiling")
}
if c.MTLSEnabled {
args = append(args, "--enable-mtls")
}
// Note: we are still passing --app-ssl as-is, rather than merging it into "app-protocol", for backwards-compatibility (ability to inject Dapr 1.10 and older sidecars).
// We will let Daprd "convert" this.
if c.AppSSL {
args = append(args, "--app-ssl")
}
if c.AppMaxConcurrency != nil {
args = append(args, "--app-max-concurrency", strconv.Itoa(*c.AppMaxConcurrency))
}
if c.HTTPMaxRequestSize != nil {
args = append(args, "--dapr-http-max-request-size", strconv.Itoa(*c.HTTPMaxRequestSize))
}
if c.MaxBodySize != "" {
args = append(args, "--max-body-size", c.MaxBodySize)
}
if c.HTTPReadBufferSize != nil {
args = append(args, "--dapr-http-read-buffer-size", strconv.Itoa(*c.HTTPReadBufferSize))
}
if c.ReadBufferSize != "" {
args = append(args, "--read-buffer-size", c.ReadBufferSize)
}
if c.UnixDomainSocketPath != "" {
// Note this is a constant path
// The passed annotation determines where the socket folder is mounted in the app container, but in the daprd container the path is a constant
args = append(args, "--unix-domain-socket", injectorConsts.UnixDomainSocketDaprdPath)
}
if c.BlockShutdownDuration != nil {
args = append(args, "--dapr-block-shutdown-duration", *c.BlockShutdownDuration)
}
// When debugging is enabled, we need to override the command and the flags
if c.EnableDebug {
ports = append(ports, corev1.ContainerPort{
Name: injectorConsts.SidecarDebugPortName,
ContainerPort: c.SidecarDebugPort,
})
cmd = []string{"/dlv"}
args = append([]string{
"--listen", ":" + strconv.FormatInt(int64(c.SidecarDebugPort), 10),
"--accept-multiclient",
"--headless=true",
"--log",
"--api-version=2",
"exec",
"/daprd",
"--",
}, args...)
}
// Security context
securityContext := &corev1.SecurityContext{
AllowPrivilegeEscalation: ptr.Of(false),
RunAsNonRoot: ptr.Of(c.RunAsNonRoot),
ReadOnlyRootFilesystem: ptr.Of(c.ReadOnlyRootFilesystem),
}
if c.SidecarSeccompProfileType != "" {
securityContext.SeccompProfile = &corev1.SeccompProfile{
Type: corev1.SeccompProfileType(c.SidecarSeccompProfileType),
}
}
if c.SidecarDropALLCapabilities {
securityContext.Capabilities = &corev1.Capabilities{
Drop: []corev1.Capability{"ALL"},
}
}
// Create the container object
probeHTTPHandler := getProbeHTTPHandler(c.SidecarPublicPort, injectorConsts.APIVersionV1, injectorConsts.SidecarHealthzPath)
env := []corev1.EnvVar{
{
Name: "NAMESPACE",
Value: c.Namespace,
},
{
Name: securityConsts.TrustAnchorsEnvVar,
Value: string(c.CurrentTrustAnchors),
},
{
Name: "POD_NAME",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{
FieldPath: "metadata.name",
},
},
},
// TODO: @joshvanl: In v1.14, these two env vars should be moved to flags.
{
Name: securityConsts.ControlPlaneNamespaceEnvVar,
Value: c.ControlPlaneNamespace,
},
{
Name: securityConsts.ControlPlaneTrustDomainEnvVar,
Value: c.ControlPlaneTrustDomain,
},
}
if c.EnableK8sDownwardAPIs {
env = append(env,
corev1.EnvVar{
Name: injectorConsts.DaprContainerHostIP,
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{
FieldPath: "status.podIP",
},
},
},
)
}
container := &corev1.Container{
Name: injectorConsts.SidecarContainerName,
Image: c.SidecarImage,
ImagePullPolicy: c.ImagePullPolicy,
SecurityContext: securityContext,
Ports: ports,
Args: append(cmd, args...),
Env: env,
VolumeMounts: opts.VolumeMounts,
ReadinessProbe: &corev1.Probe{
ProbeHandler: probeHTTPHandler,
InitialDelaySeconds: c.SidecarReadinessProbeDelaySeconds,
TimeoutSeconds: c.SidecarReadinessProbeTimeoutSeconds,
PeriodSeconds: c.SidecarReadinessProbePeriodSeconds,
FailureThreshold: c.SidecarReadinessProbeThreshold,
},
LivenessProbe: &corev1.Probe{
ProbeHandler: probeHTTPHandler,
InitialDelaySeconds: c.SidecarLivenessProbeDelaySeconds,
TimeoutSeconds: c.SidecarLivenessProbeTimeoutSeconds,
PeriodSeconds: c.SidecarLivenessProbePeriodSeconds,
FailureThreshold: c.SidecarLivenessProbeThreshold,
},
}
// If the pod contains any of the tolerations specified by the configuration,
// the Command and Args are passed as is. Otherwise, the Command is passed as a part of Args.
// This is to allow the Docker images to specify an ENTRYPOINT
// which is otherwise overridden by Command.
if podContainsTolerations(c.IgnoreEntrypointTolerations, c.pod.Spec.Tolerations) {
container.Command = cmd
container.Args = args
} else {
container.Args = cmd
container.Args = append(container.Args, args...)
}
// Set env vars if needed
containerEnvKeys, containerEnv := c.getEnv()
if len(containerEnv) > 0 {
container.Env = append(container.Env, containerEnv...)
container.Env = append(container.Env, corev1.EnvVar{
Name: securityConsts.EnvKeysEnvVar,
Value: strings.Join(containerEnvKeys, " "),
})
}
// This is a special case that requires administrator privileges in Windows containers
// to install the certificates to the root store. If this environment variable is set,
// the container security context should be set to run as administrator.
for _, env := range container.Env {
if env.Name == "SSL_CERT_DIR" {
container.SecurityContext.WindowsOptions = &corev1.WindowsSecurityContextOptions{
RunAsUserName: ptr.Of("ContainerAdministrator"),
}
// We also need to set RunAsNonRoot and ReadOnlyRootFilesystem to false, which would impact Linux too.
// The injector has no way to know if the pod is going to be deployed on Windows or Linux, so we need to err on the side of most compatibility.
// On Linux, our containers run with a non-root user, so the net effect shouldn't change: daprd is running as non-root and has no permission to write on the root FS.
// However certain security scanner may complain about this.
container.SecurityContext.RunAsNonRoot = ptr.Of(false)
container.SecurityContext.ReadOnlyRootFilesystem = ptr.Of(false)
break
}
}
if opts.ComponentsSocketsVolumeMount != nil {
container.VolumeMounts = append(container.VolumeMounts, *opts.ComponentsSocketsVolumeMount)
container.Env = append(container.Env, corev1.EnvVar{
Name: injectorConsts.ComponentsUDSMountPathEnvVar,
Value: opts.ComponentsSocketsVolumeMount.MountPath,
})
}
if c.APITokenSecret != "" {
container.Env = append(container.Env, corev1.EnvVar{
Name: securityConsts.APITokenEnvVar,
ValueFrom: &corev1.EnvVarSource{
SecretKeyRef: &corev1.SecretKeySelector{
Key: "token",
LocalObjectReference: corev1.LocalObjectReference{
Name: c.APITokenSecret,
},
},
},
})
}
if c.AppTokenSecret != "" {
container.Env = append(container.Env, corev1.EnvVar{
Name: securityConsts.AppAPITokenEnvVar,
ValueFrom: &corev1.EnvVarSource{
SecretKeyRef: &corev1.SecretKeySelector{
Key: "token",
LocalObjectReference: corev1.LocalObjectReference{
Name: c.AppTokenSecret,
},
},
},
})
}
// Resources for the container
resources, err := c.getResourceRequirements()
if err != nil {
log.Warnf("couldn't set container resource requirements: %s. using defaults", err)
} else if resources != nil {
container.Resources = *resources
}
return container, nil
}
func (c *SidecarConfig) getResourceRequirements() (*corev1.ResourceRequirements, error) {
r := corev1.ResourceRequirements{
Limits: corev1.ResourceList{},
Requests: corev1.ResourceList{},
}
if c.SidecarCPURequest != "" {
q, err := resource.ParseQuantity(c.SidecarCPURequest)
if err != nil {
return nil, fmt.Errorf("error parsing sidecar CPU request: %w", err)
}
r.Requests[corev1.ResourceCPU] = q
}
if c.SidecarCPULimit != "" {
q, err := resource.ParseQuantity(c.SidecarCPULimit)
if err != nil {
return nil, fmt.Errorf("error parsing sidecar CPU limit: %w", err)
}
r.Limits[corev1.ResourceCPU] = q
}
if c.SidecarMemoryRequest != "" {
q, err := resource.ParseQuantity(c.SidecarMemoryRequest)
if err != nil {
return nil, fmt.Errorf("error parsing sidecar memory request: %w", err)
}
r.Requests[corev1.ResourceMemory] = q
}
if c.SidecarMemoryLimit != "" {
q, err := resource.ParseQuantity(c.SidecarMemoryLimit)
if err != nil {
return nil, fmt.Errorf("error parsing sidecar memory limit: %w", err)
}
r.Limits[corev1.ResourceMemory] = q
}
if len(r.Limits) == 0 && len(r.Requests) == 0 {
return nil, nil
}
return &r, nil
}
// GetAppID returns the AppID property, fallinb back to the name of the pod.
func (c *SidecarConfig) GetAppID() string {
if c.AppID == "" {
log.Warnf("app-id not set defaulting the app-id to: %s", c.pod.GetName())
return c.pod.GetName()
}
return c.AppID
}
var envRegexp = regexp.MustCompile(`(?m)(,)\s*[a-zA-Z\_][a-zA-Z0-9\_]*=`)
// getEnv returns the EnvVar slice from the Env annotation.
func (c *SidecarConfig) getEnv() (envKeys []string, envVars []corev1.EnvVar) {
if c.Env == "" {
return []string{}, []corev1.EnvVar{}
}
indexes := envRegexp.FindAllStringIndex(c.Env, -1)
lastEnd := len(c.Env)
parts := make([]string, len(indexes)+1)
for i := len(indexes) - 1; i >= 0; i-- {
parts[i+1] = strings.TrimSpace(c.Env[indexes[i][0]+1 : lastEnd])
lastEnd = indexes[i][0]
}
parts[0] = c.Env[0:lastEnd]
envKeys = make([]string, 0, len(parts))
envVars = make([]corev1.EnvVar, 0, len(parts))
for _, s := range parts {
pairs := strings.Split(strings.TrimSpace(s), "=")
if len(pairs) != 2 {
continue
}
envKeys = append(envKeys, pairs[0])
envVars = append(envVars, corev1.EnvVar{
Name: pairs[0],
Value: pairs[1],
})
}
return envKeys, envVars
}
func (c *SidecarConfig) GetAppProtocol() string {
appProtocol := strings.ToLower(c.AppProtocol)
switch appProtocol {
case string(protocol.GRPCSProtocol), string(protocol.HTTPSProtocol), string(protocol.H2CProtocol):
return appProtocol
case string(protocol.HTTPProtocol):
// For backwards compatibility, when protocol is HTTP and --app-ssl is set, use "https"
// TODO: Remove in a future Dapr version
if c.AppSSL {
return string(protocol.HTTPSProtocol)
} else {
return string(protocol.HTTPProtocol)
}
case string(protocol.GRPCProtocol):
// For backwards compatibility, when protocol is GRPC and --app-ssl is set, use "grpcs"
// TODO: Remove in a future Dapr version
if c.AppSSL {
return string(protocol.GRPCSProtocol)
} else {
return string(protocol.GRPCProtocol)
}
case "":
return string(protocol.HTTPProtocol)
default:
return ""
}
}
func getProbeHTTPHandler(port int32, pathElements ...string) corev1.ProbeHandler {
return corev1.ProbeHandler{
HTTPGet: &corev1.HTTPGetAction{
Path: formatProbePath(pathElements...),
Port: intstr.IntOrString{IntVal: port},
},
}
}
func formatProbePath(elements ...string) string {
pathStr := path.Join(elements...)
if !strings.HasPrefix(pathStr, "/") {
pathStr = "/" + pathStr
}
return pathStr
}
// podContainsTolerations returns true if the pod contains any of the tolerations specified in ts.
func podContainsTolerations(ts []corev1.Toleration, podTolerations []corev1.Toleration) bool {
if len(ts) == 0 || len(podTolerations) == 0 {
return false
}
// If the pod contains any of the tolerations specified, return true.
for _, t := range ts {
if utils.Contains(podTolerations, t) {
return true
}
}
return false
}
|
mikeee/dapr
|
pkg/injector/patcher/sidecar_container.go
|
GO
|
mit
| 16,288 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package patcher
import (
"encoding/json"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"github.com/dapr/dapr/pkg/injector/annotations"
injectorConsts "github.com/dapr/dapr/pkg/injector/consts"
securityConsts "github.com/dapr/dapr/pkg/security/consts"
)
func TestParseEnvString(t *testing.T) {
testCases := []struct {
testName string
envStr string
expLen int
expKeys []string
expEnv []corev1.EnvVar
}{
{
testName: "empty environment string",
envStr: "",
expLen: 0,
expKeys: []string{},
expEnv: []corev1.EnvVar{},
},
{
testName: "common valid environment string",
envStr: "ENV1=value1,ENV2=value2, ENV3=value3",
expLen: 3,
expKeys: []string{"ENV1", "ENV2", "ENV3"},
expEnv: []corev1.EnvVar{
{
Name: "ENV1",
Value: "value1",
},
{
Name: "ENV2",
Value: "value2",
},
{
Name: "ENV3",
Value: "value3",
},
},
},
{
testName: "environment string with quotes",
envStr: `HTTP_PROXY=http://myproxy.com, NO_PROXY="localhost,127.0.0.1,.amazonaws.com"`,
expLen: 2,
expKeys: []string{"HTTP_PROXY", "NO_PROXY"},
expEnv: []corev1.EnvVar{
{
Name: "HTTP_PROXY",
Value: "http://myproxy.com",
},
{
Name: "NO_PROXY",
Value: `"localhost,127.0.0.1,.amazonaws.com"`,
},
},
},
}
for _, tc := range testCases {
tc := tc
t.Run(tc.testName, func(t *testing.T) {
c := NewSidecarConfig(&corev1.Pod{})
c.Env = tc.envStr
envKeys, envVars := c.getEnv()
assert.Len(t, envVars, tc.expLen)
assert.Equal(t, tc.expKeys, envKeys)
assert.Equal(t, tc.expEnv, envVars)
})
}
}
func TestGetResourceRequirements(t *testing.T) {
t.Run("no resource requirements", func(t *testing.T) {
c := NewSidecarConfig(&corev1.Pod{})
c.SetFromPodAnnotations()
r, err := c.getResourceRequirements()
require.NoError(t, err)
assert.Nil(t, r)
})
t.Run("valid resource limits", func(t *testing.T) {
c := NewSidecarConfig(&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
annotations.KeyCPULimit: "100m",
annotations.KeyMemoryLimit: "1Gi",
},
},
})
c.SetFromPodAnnotations()
r, err := c.getResourceRequirements()
require.NoError(t, err)
assert.Equal(t, "100m", r.Limits.Cpu().String())
assert.Equal(t, "1Gi", r.Limits.Memory().String())
})
t.Run("invalid cpu limit", func(t *testing.T) {
c := NewSidecarConfig(&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
annotations.KeyCPULimit: "invalid",
annotations.KeyMemoryLimit: "1Gi",
},
},
})
c.SetFromPodAnnotations()
r, err := c.getResourceRequirements()
require.Error(t, err)
assert.Nil(t, r)
})
t.Run("invalid memory limit", func(t *testing.T) {
c := NewSidecarConfig(&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
annotations.KeyCPULimit: "100m",
annotations.KeyMemoryLimit: "invalid",
},
},
})
c.SetFromPodAnnotations()
r, err := c.getResourceRequirements()
require.Error(t, err)
assert.Nil(t, r)
})
t.Run("valid resource requests", func(t *testing.T) {
c := NewSidecarConfig(&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
annotations.KeyCPURequest: "100m",
annotations.KeyMemoryRequest: "1Gi",
},
},
})
c.SetFromPodAnnotations()
r, err := c.getResourceRequirements()
require.NoError(t, err)
assert.Equal(t, "100m", r.Requests.Cpu().String())
assert.Equal(t, "1Gi", r.Requests.Memory().String())
})
t.Run("invalid cpu request", func(t *testing.T) {
c := NewSidecarConfig(&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
annotations.KeyCPURequest: "invalid",
annotations.KeyMemoryRequest: "1Gi",
},
},
})
c.SetFromPodAnnotations()
r, err := c.getResourceRequirements()
require.Error(t, err)
assert.Nil(t, r)
})
t.Run("invalid memory request", func(t *testing.T) {
c := NewSidecarConfig(&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
annotations.KeyCPURequest: "100m",
annotations.KeyMemoryRequest: "invalid",
},
},
})
c.SetFromPodAnnotations()
r, err := c.getResourceRequirements()
require.Error(t, err)
assert.Nil(t, r)
})
t.Run("limits and requests", func(t *testing.T) {
c := NewSidecarConfig(&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
annotations.KeyCPULimit: "200m",
annotations.KeyMemoryLimit: "2Gi",
annotations.KeyCPURequest: "100m",
annotations.KeyMemoryRequest: "1Gi",
},
},
})
c.SetFromPodAnnotations()
r, err := c.getResourceRequirements()
require.NoError(t, err)
assert.Equal(t, "200m", r.Limits.Cpu().String())
assert.Equal(t, "2Gi", r.Limits.Memory().String())
assert.Equal(t, "100m", r.Requests.Cpu().String())
assert.Equal(t, "1Gi", r.Requests.Memory().String())
})
}
func TestGetProbeHttpHandler(t *testing.T) {
pathElements := []string{"api", "v1", "healthz"}
expectedPath := "/api/v1/healthz"
expectedHandler := corev1.ProbeHandler{
HTTPGet: &corev1.HTTPGetAction{
Path: expectedPath,
Port: intstr.IntOrString{IntVal: 3500},
},
}
assert.EqualValues(t, expectedHandler, getProbeHTTPHandler(3500, pathElements...))
}
func TestFormatProbePath(t *testing.T) {
testCases := []struct {
given []string
expected string
}{
{
given: []string{"api", "v1"},
expected: "/api/v1",
},
{
given: []string{"//api", "v1"},
expected: "/api/v1",
},
{
given: []string{"//api", "/v1/"},
expected: "/api/v1",
},
{
given: []string{"//api", "/v1/", "healthz"},
expected: "/api/v1/healthz",
},
{
given: []string{""},
expected: "/",
},
}
for _, tc := range testCases {
assert.Equal(t, tc.expected, formatProbePath(tc.given...))
}
}
func TestGetSidecarContainer(t *testing.T) {
// Allows running multiple test suites in a more DRY way
type testCase struct {
name string
annotations map[string]string
podModifierFn func(pod *corev1.Pod)
sidecarConfigModifierFn func(c *SidecarConfig)
assertFn func(t *testing.T, container *corev1.Container)
getSidecarContainerOpts getSidecarContainerOpts
}
testCaseFn := func(tc testCase) func(t *testing.T) {
return func(t *testing.T) {
pod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: tc.annotations,
},
}
if tc.podModifierFn != nil {
tc.podModifierFn(pod)
}
c := NewSidecarConfig(pod)
c.AppID = "myapp"
if tc.sidecarConfigModifierFn != nil {
tc.sidecarConfigModifierFn(c)
}
c.SetFromPodAnnotations()
container, err := c.getSidecarContainer(tc.getSidecarContainerOpts)
require.NoError(t, err)
tc.assertFn(t, container)
}
}
testSuiteGenerator := func(tests []testCase) func(t *testing.T) {
return func(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, testCaseFn(tc))
}
}
}
t.Run("get sidecar container", func(t *testing.T) {
c := NewSidecarConfig(&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
annotations.KeyAppID: "app_id",
annotations.KeyConfig: "config",
annotations.KeyAppPort: "5000",
annotations.KeyLogAsJSON: "true",
annotations.KeyAPITokenSecret: "secret",
annotations.KeyAppTokenSecret: "appsecret",
},
},
})
c.SidecarImage = "daprio/dapr"
c.ImagePullPolicy = "Always"
c.Namespace = "dapr-system"
c.OperatorAddress = "controlplane:9000"
c.PlacementAddress = "placement:50000"
c.SentryAddress = "sentry:50000"
c.MTLSEnabled = true
c.Identity = "pod_identity"
c.ControlPlaneNamespace = "my-namespace"
c.ControlPlaneTrustDomain = "test.example.com"
c.SetFromPodAnnotations()
container, err := c.getSidecarContainer(getSidecarContainerOpts{})
require.NoError(t, err)
expectedArgs := []string{
"/daprd",
"--dapr-http-port", "3500",
"--dapr-grpc-port", "50001",
"--dapr-internal-grpc-port", "50002",
"--dapr-listen-addresses", "[::1],127.0.0.1",
"--dapr-public-port", "3501",
"--app-id", "app_id",
"--app-protocol", "http",
"--log-level", "info",
"--dapr-graceful-shutdown-seconds", "-1",
"--mode", "kubernetes",
"--control-plane-address", "controlplane:9000",
"--sentry-address", "sentry:50000",
"--app-port", "5000",
"--enable-metrics",
"--metrics-port", "9090",
"--config", "config",
"--placement-host-address", "placement:50000",
"--log-as-json",
"--enable-mtls",
}
// Command should be empty, image's entrypoint to be used.
assert.Empty(t, container.Command)
assertEqualJSON(t, container.Env, `[{"name":"NAMESPACE","value":"dapr-system"},{"name":"DAPR_TRUST_ANCHORS"},{"name":"POD_NAME","valueFrom":{"fieldRef":{"fieldPath":"metadata.name"}}},{"name":"DAPR_CONTROLPLANE_NAMESPACE","value":"my-namespace"},{"name":"DAPR_CONTROLPLANE_TRUST_DOMAIN","value":"test.example.com"},{"name":"DAPR_API_TOKEN","valueFrom":{"secretKeyRef":{"name":"secret","key":"token"}}},{"name":"APP_API_TOKEN","valueFrom":{"secretKeyRef":{"name":"appsecret","key":"token"}}}]`)
// default image
assert.Equal(t, "daprio/dapr", container.Image)
assert.EqualValues(t, expectedArgs, container.Args)
assert.Equal(t, corev1.PullAlways, container.ImagePullPolicy)
})
t.Run("get sidecar container with debugging", func(t *testing.T) {
c := NewSidecarConfig(&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
annotations.KeyAppID: "app_id",
annotations.KeyConfig: "config",
annotations.KeyAppPort: "5000",
annotations.KeyLogAsJSON: "true",
annotations.KeyAPITokenSecret: "secret",
annotations.KeyAppTokenSecret: "appsecret",
annotations.KeyEnableDebug: "true",
annotations.KeyDebugPort: "55555",
},
},
})
c.SidecarImage = "daprio/dapr"
c.ImagePullPolicy = "Always"
c.Namespace = "dapr-system"
c.OperatorAddress = "controlplane:9000"
c.PlacementAddress = "placement:50000"
c.SentryAddress = "sentry:50000"
c.MTLSEnabled = true
c.Identity = "pod_identity"
c.ControlPlaneNamespace = "my-namespace"
c.ControlPlaneTrustDomain = "test.example.com"
c.EnableK8sDownwardAPIs = true
c.SetFromPodAnnotations()
container, err := c.getSidecarContainer(getSidecarContainerOpts{})
require.NoError(t, err)
expectedArgs := []string{
"/dlv",
"--listen", ":55555",
"--accept-multiclient",
"--headless=true",
"--log",
"--api-version=2",
"exec",
"/daprd",
"--",
"--dapr-http-port", "3500",
"--dapr-grpc-port", "50001",
"--dapr-internal-grpc-port", "50002",
"--dapr-listen-addresses", "[::1],127.0.0.1",
"--dapr-public-port", "3501",
"--app-id", "app_id",
"--app-protocol", "http",
"--log-level", "info",
"--dapr-graceful-shutdown-seconds", "-1",
"--mode", "kubernetes",
"--control-plane-address", "controlplane:9000",
"--sentry-address", "sentry:50000",
"--app-port", "5000",
"--enable-metrics",
"--metrics-port", "9090",
"--config", "config",
"--placement-host-address", "placement:50000",
"--log-as-json",
"--enable-mtls",
}
// Command should be empty, image's entrypoint to be used.
assert.Empty(t, container.Command)
assertEqualJSON(t, container.Env, `[{"name":"NAMESPACE","value":"dapr-system"},{"name":"DAPR_TRUST_ANCHORS"},{"name":"POD_NAME","valueFrom":{"fieldRef":{"fieldPath":"metadata.name"}}},{"name":"DAPR_CONTROLPLANE_NAMESPACE","value":"my-namespace"},{"name":"DAPR_CONTROLPLANE_TRUST_DOMAIN","value":"test.example.com"},{"name":"DAPR_HOST_IP","valueFrom":{"fieldRef":{"fieldPath":"status.podIP"}}},{"name":"DAPR_API_TOKEN","valueFrom":{"secretKeyRef":{"name":"secret","key":"token"}}},{"name":"APP_API_TOKEN","valueFrom":{"secretKeyRef":{"name":"appsecret","key":"token"}}}]`)
// default image
assert.Equal(t, "daprio/dapr", container.Image)
assert.EqualValues(t, expectedArgs, container.Args)
assert.Equal(t, corev1.PullAlways, container.ImagePullPolicy)
})
t.Run("placement", testSuiteGenerator([]testCase{
{
name: "placement is included in options",
sidecarConfigModifierFn: func(c *SidecarConfig) {
c.PlacementAddress = "placement:1234"
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--placement-host-address placement:1234")
},
},
{
name: "placement is skipped in options",
sidecarConfigModifierFn: func(c *SidecarConfig) {
c.PlacementAddress = ""
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.NotContains(t, args, "--placement-host-address")
},
},
{
name: "placement is skipped in options but included in annotations",
sidecarConfigModifierFn: func(c *SidecarConfig) {
c.PlacementAddress = ""
},
annotations: map[string]string{
annotations.KeyPlacementHostAddresses: "some-host:50000",
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--placement-host-address some-host:50000")
},
},
{
name: "placement is set in options and overrriden in annotations",
sidecarConfigModifierFn: func(c *SidecarConfig) {
c.PlacementAddress = "placement:1234"
},
annotations: map[string]string{
annotations.KeyPlacementHostAddresses: "some-host:50000",
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--placement-host-address some-host:50000")
},
},
}))
t.Run("listen address", testSuiteGenerator([]testCase{
{
name: "default listen address",
annotations: map[string]string{},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--dapr-listen-addresses [::1],127.0.0.1")
},
},
{
name: "override listen address",
annotations: map[string]string{
annotations.KeySidecarListenAddresses: "1.2.3.4,[::1]",
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--dapr-listen-addresses 1.2.3.4,[::1]")
},
},
}))
t.Run("graceful shutdown seconds", testSuiteGenerator([]testCase{
{
name: "default to -1",
annotations: map[string]string{},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--dapr-graceful-shutdown-seconds -1")
},
},
{
name: "override the graceful shutdown",
annotations: map[string]string{
annotations.KeyGracefulShutdownSeconds: "3",
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--dapr-graceful-shutdown-seconds 3")
},
},
{
name: "-1 when value is invalid",
annotations: map[string]string{
annotations.KeyGracefulShutdownSeconds: "invalid",
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--dapr-graceful-shutdown-seconds -1")
},
},
}))
t.Run("block shutdown duration", testSuiteGenerator([]testCase{
{
name: "default to empty",
annotations: map[string]string{},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.NotContains(t, args, "--dapr-block-shutdown-duration")
},
},
{
name: "add a block shutdown duration",
annotations: map[string]string{
"dapr.io/block-shutdown-duration": "3s",
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--dapr-block-shutdown-duration 3s")
},
},
}))
t.Run("sidecar image", testSuiteGenerator([]testCase{
{
name: "no annotation",
annotations: map[string]string{},
sidecarConfigModifierFn: func(c *SidecarConfig) {
c.SidecarImage = "daprio/dapr"
},
assertFn: func(t *testing.T, container *corev1.Container) {
assert.Equal(t, "daprio/dapr", container.Image)
},
},
{
name: "override with annotation",
annotations: map[string]string{
annotations.KeySidecarImage: "override",
},
sidecarConfigModifierFn: func(c *SidecarConfig) {
c.SidecarImage = "daprio/dapr"
},
assertFn: func(t *testing.T, container *corev1.Container) {
assert.Equal(t, "override", container.Image)
},
},
}))
t.Run("unix domain socket", testSuiteGenerator([]testCase{
{
name: "default does not use UDS",
annotations: map[string]string{},
assertFn: func(t *testing.T, container *corev1.Container) {
assert.Empty(t, container.VolumeMounts)
},
},
{
name: "set UDS path",
annotations: map[string]string{
annotations.KeyUnixDomainSocketPath: "/tmp",
},
getSidecarContainerOpts: getSidecarContainerOpts{
VolumeMounts: []corev1.VolumeMount{
{Name: injectorConsts.UnixDomainSocketVolume, MountPath: "/tmp"},
},
},
assertFn: func(t *testing.T, container *corev1.Container) {
assert.Len(t, container.VolumeMounts, 1)
assert.Equal(t, injectorConsts.UnixDomainSocketVolume, container.VolumeMounts[0].Name)
assert.Equal(t, "/tmp", container.VolumeMounts[0].MountPath)
},
},
}))
t.Run("disable builtin K8s Secret Store", testCaseFn(testCase{
annotations: map[string]string{
annotations.KeyDisableBuiltinK8sSecretStore: "true",
},
assertFn: func(t *testing.T, container *corev1.Container) {
assert.Contains(t, container.Args, "--disable-builtin-k8s-secret-store")
},
}))
t.Run("test enable-api-logging", testSuiteGenerator([]testCase{
{
name: "not set by default",
annotations: map[string]string{},
assertFn: func(t *testing.T, container *corev1.Container) {
assert.NotContains(t, strings.Join(container.Args, " "), "--enable-api-logging")
},
},
{
name: "explicit true",
annotations: map[string]string{
annotations.KeyEnableAPILogging: "true",
},
assertFn: func(t *testing.T, container *corev1.Container) {
assert.Contains(t, container.Args, "--enable-api-logging=true")
},
},
{
name: "explicit false",
annotations: map[string]string{
annotations.KeyEnableAPILogging: "0",
},
assertFn: func(t *testing.T, container *corev1.Container) {
assert.Contains(t, container.Args, "--enable-api-logging=false")
},
},
{
name: "not set when annotation is empty",
annotations: map[string]string{
annotations.KeyEnableAPILogging: "",
},
assertFn: func(t *testing.T, container *corev1.Container) {
assert.NotContains(t, strings.Join(container.Args, " "), "--enable-api-logging")
},
},
}))
t.Run("sidecar container should have the correct security context on Windows", testSuiteGenerator([]testCase{
{
name: "windows security context is nil by default",
annotations: map[string]string{},
assertFn: func(t *testing.T, container *corev1.Container) {
assert.Nil(t, container.SecurityContext.WindowsOptions)
},
},
{
name: "setting SSL_CERT_DIR should set security context",
annotations: map[string]string{
annotations.KeyEnv: "SSL_CERT_DIR=/tmp/certificates",
},
assertFn: func(t *testing.T, container *corev1.Container) {
assert.NotNil(t, container.SecurityContext.WindowsOptions, "SecurityContext.WindowsOptions should not be nil")
assert.Equal(t, "ContainerAdministrator", *container.SecurityContext.WindowsOptions.RunAsUserName, "SecurityContext.WindowsOptions.RunAsUserName should be ContainerAdministrator")
},
},
{
name: "setting SSL_CERT_FILE should not set security context",
annotations: map[string]string{
annotations.KeyEnv: "SSL_CERT_FILE=/tmp/certificates/cert.pem",
},
assertFn: func(t *testing.T, container *corev1.Container) {
assert.Nil(t, container.SecurityContext.WindowsOptions)
},
},
}))
t.Run("sidecar container should have env vars injected", testCaseFn(testCase{
annotations: map[string]string{
annotations.KeyEnv: `HELLO=world, CIAO=mondo, BONJOUR=monde`,
},
assertFn: func(t *testing.T, container *corev1.Container) {
expect := map[string]string{
"HELLO": "world",
"CIAO": "mondo",
"BONJOUR": "monde",
securityConsts.EnvKeysEnvVar: "HELLO CIAO BONJOUR",
}
found := map[string]string{}
for _, env := range container.Env {
switch env.Name {
case "HELLO", "CIAO", "BONJOUR", securityConsts.EnvKeysEnvVar:
found[env.Name] = env.Value
}
}
assert.Equal(t, expect, found)
},
}))
t.Run("sidecar container should specify commands only when ignoreEntrypointTolerations match with the pod", func(t *testing.T) {
testCases := []struct {
name string
tolerations []corev1.Toleration
ignoreEntrypointTolerations []corev1.Toleration
explicitCommandSpecified bool
}{
{
"no tolerations",
[]corev1.Toleration{},
[]corev1.Toleration{},
false,
},
{
"pod contains tolerations from ignoreEntrypointTolerations (single)",
[]corev1.Toleration{
{
Key: "foo.com/bar",
Effect: "NoSchedule",
},
},
[]corev1.Toleration{
{
Key: "foo.com/bar",
Effect: "NoSchedule",
},
},
true,
},
{
"pod contains tolerations from ignoreEntrypointTolerations (multiple)",
[]corev1.Toleration{
{
Key: "foo.com/bar",
Effect: "NoSchedule",
},
{
Key: "foo.com/baz",
Effect: "NoSchedule",
},
{
Key: "foo.com/qux",
Effect: "NoSchedule",
},
},
[]corev1.Toleration{
{
Key: "foo.com/bar",
Effect: "NoSchedule",
},
{
Key: "foo.com/baz",
Effect: "NoSchedule",
},
},
true,
},
{
"pod contains partial tolerations from ignoreEntrypointTolerations",
[]corev1.Toleration{
{
Key: "foo.com/bar",
Effect: "NoSchedule",
},
{
Key: "foo.com/qux",
Effect: "NoSchedule",
},
},
[]corev1.Toleration{
{
Key: "foo.com/bar",
Effect: "NoSchedule",
},
{
Key: "foo.com/baz",
Effect: "NoSchedule",
},
},
true,
},
{
"pod contains no tolerations from ignoreEntrypointTolerations",
[]corev1.Toleration{},
[]corev1.Toleration{
{
Key: "foo.com/baz",
Effect: "NoSchedule",
},
},
false,
},
}
for _, tc := range testCases {
c := NewSidecarConfig(&corev1.Pod{
Spec: corev1.PodSpec{
Tolerations: tc.tolerations,
},
})
c.IgnoreEntrypointTolerations = tc.ignoreEntrypointTolerations
container, err := c.getSidecarContainer(getSidecarContainerOpts{})
require.NoError(t, err)
t.Run(tc.name, func(t *testing.T) {
if tc.explicitCommandSpecified {
assert.NotEmpty(t, container.Command, "Must contain a command")
assert.NotEmpty(t, container.Args, "Must contain arguments")
} else {
assert.Empty(t, container.Command, "Must not contain a command")
assert.NotEmpty(t, container.Args, "Must contain arguments")
}
})
}
})
t.Run("get sidecar container with appropriate security context", testSuiteGenerator([]testCase{
{
name: "set seccomp profile type",
annotations: map[string]string{
annotations.KeySidecarSeccompProfileType: "RuntimeDefault",
},
assertFn: func(t *testing.T, container *corev1.Container) {
assert.Nil(t, container.SecurityContext.Capabilities)
assert.NotNil(t, container.SecurityContext.SeccompProfile, "SecurityContext.SeccompProfile should not be nil")
assert.Equal(t, corev1.SeccompProfile{Type: corev1.SeccompProfileType("RuntimeDefault")}, *container.SecurityContext.SeccompProfile, "SecurityContext.SeccompProfile.Type should be RuntimeDefault")
},
},
{
name: "set drop all capabilities",
sidecarConfigModifierFn: func(c *SidecarConfig) {
c.SidecarDropALLCapabilities = true
},
assertFn: func(t *testing.T, container *corev1.Container) {
assert.NotNil(t, container.SecurityContext.Capabilities, "SecurityContext.Capabilities should not be nil")
assert.Equal(t, corev1.Capabilities{Drop: []corev1.Capability{"ALL"}}, *container.SecurityContext.Capabilities, "SecurityContext.Capabilities should drop all capabilities")
assert.Nil(t, container.SecurityContext.SeccompProfile)
},
},
}))
t.Run("app health checks", testSuiteGenerator([]testCase{
{
name: "disabled by default",
annotations: map[string]string{},
assertFn: func(t *testing.T, container *corev1.Container) {
assert.NotContains(t, container.Args, "--enable-app-health-check")
assert.NotContains(t, container.Args, "--app-health-check-path")
assert.NotContains(t, container.Args, "--app-health-probe-interval")
assert.NotContains(t, container.Args, "--app-health-probe-timeout")
assert.NotContains(t, container.Args, "--app-health-threshold")
},
},
{
name: "enabled with default options",
annotations: map[string]string{
annotations.KeyEnableAppHealthCheck: "1",
},
assertFn: func(t *testing.T, container *corev1.Container) {
assert.Contains(t, container.Args, "--enable-app-health-check")
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--app-health-check-path /healthz")
assert.Contains(t, args, "--app-health-probe-interval 5")
assert.Contains(t, args, "--app-health-probe-timeout 500")
assert.Contains(t, args, "--app-health-threshold 3")
},
},
{
name: "enabled with custom options",
annotations: map[string]string{
annotations.KeyEnableAppHealthCheck: "1",
annotations.KeyAppHealthCheckPath: "/healthcheck",
annotations.KeyAppHealthProbeInterval: "10",
annotations.KeyAppHealthProbeTimeout: "100",
annotations.KeyAppHealthThreshold: "2",
},
assertFn: func(t *testing.T, container *corev1.Container) {
assert.Contains(t, container.Args, "--enable-app-health-check")
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--app-health-check-path /healthcheck")
assert.Contains(t, args, "--app-health-probe-interval 10")
assert.Contains(t, args, "--app-health-probe-timeout 100")
assert.Contains(t, args, "--app-health-threshold 2")
},
},
}))
t.Run("sidecar container should have env vars injected", testCaseFn(testCase{
annotations: map[string]string{
annotations.KeyEnableProfiling: "true",
},
assertFn: func(t *testing.T, container *corev1.Container) {
assert.Contains(t, container.Args, "--enable-profiling")
},
}))
// This validates the current behavior
// TODO: When app-ssl is deprecated, change this test
t.Run("app protocol and TLS", testSuiteGenerator([]testCase{
{
name: "default to HTTP protocol",
annotations: map[string]string{},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--app-protocol http")
assert.NotContains(t, args, "--app-ssl")
},
},
{
name: "enable app-ssl",
annotations: map[string]string{
annotations.KeyAppSSL: "y",
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--app-protocol http")
assert.Contains(t, args, "--app-ssl")
},
},
{
name: "protocol is grpc with app-ssl",
annotations: map[string]string{
annotations.KeyAppProtocol: "grpc",
annotations.KeyAppSSL: "y",
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--app-protocol grpc")
assert.Contains(t, args, "--app-ssl")
},
},
{
name: "protocol is h2c",
annotations: map[string]string{
annotations.KeyAppProtocol: "h2c",
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--app-protocol h2c")
},
},
}))
t.Run("app-max-concurrency", testSuiteGenerator([]testCase{
{
name: "not present by default",
annotations: map[string]string{},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.NotContains(t, args, "--app-max-concurrency")
},
},
{
name: "set value",
annotations: map[string]string{
annotations.KeyAppMaxConcurrency: "10",
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--app-max-concurrency 10")
},
},
}))
t.Run("dapr-http-max-request-size", testSuiteGenerator([]testCase{
{
name: "not present by default",
annotations: map[string]string{},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.NotContains(t, args, "--dapr-http-max-request-size")
},
},
{
name: "set value",
annotations: map[string]string{
annotations.KeyHTTPMaxRequestSize: "10",
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--dapr-http-max-request-size 10")
},
},
}))
t.Run("max-body-size", testSuiteGenerator([]testCase{
{
name: "not present by default",
annotations: map[string]string{},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.NotContains(t, args, "--max-body-size")
},
},
{
name: "set value",
annotations: map[string]string{
annotations.KeyMaxBodySize: "1Mi",
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--max-body-size 1Mi")
},
},
}))
t.Run("set resources", testCaseFn(testCase{
annotations: map[string]string{
annotations.KeyCPURequest: "100",
annotations.KeyMemoryLimit: "100Mi",
},
assertFn: func(t *testing.T, container *corev1.Container) {
assert.Equal(t, "100", container.Resources.Requests.Cpu().String())
assert.Equal(t, "0", container.Resources.Requests.Memory().String())
assert.Equal(t, "0", container.Resources.Limits.Cpu().String())
assert.Equal(t, "100Mi", container.Resources.Limits.Memory().String())
},
}))
t.Run("modes", testSuiteGenerator([]testCase{
{
name: "default is kubernetes",
sidecarConfigModifierFn: func(c *SidecarConfig) {},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--mode kubernetes")
},
},
{
name: "set kubernetes mode explicitly",
sidecarConfigModifierFn: func(c *SidecarConfig) {
c.Mode = injectorConsts.ModeKubernetes
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--mode kubernetes")
},
},
{
name: "set standalone mode explicitly",
sidecarConfigModifierFn: func(c *SidecarConfig) {
c.Mode = injectorConsts.ModeStandalone
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--mode standalone")
},
},
{
name: "omit when value is explicitly empty",
sidecarConfigModifierFn: func(c *SidecarConfig) {
c.Mode = ""
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.NotContains(t, args, "--mode")
},
},
{
name: "omit when value is invalid",
sidecarConfigModifierFn: func(c *SidecarConfig) {
c.Mode = "foo"
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.NotContains(t, args, "--mode")
},
},
}))
t.Run("sentry address", testSuiteGenerator([]testCase{
{
name: "omitted if empty",
sidecarConfigModifierFn: func(c *SidecarConfig) {
c.SentryAddress = ""
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.NotContains(t, args, "--sentry-address")
},
},
{
name: "present when set",
sidecarConfigModifierFn: func(c *SidecarConfig) {
c.SentryAddress = "somewhere:4000"
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--sentry-address somewhere:4000")
},
},
}))
t.Run("operator address", testSuiteGenerator([]testCase{
{
name: "omitted if empty",
sidecarConfigModifierFn: func(c *SidecarConfig) {
c.OperatorAddress = ""
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.NotContains(t, args, "--control-plane-address")
},
},
{
name: "present when set",
sidecarConfigModifierFn: func(c *SidecarConfig) {
c.OperatorAddress = "somewhere:4000"
},
assertFn: func(t *testing.T, container *corev1.Container) {
args := strings.Join(container.Args, " ")
assert.Contains(t, args, "--control-plane-address somewhere:4000")
},
},
}))
}
func assertEqualJSON(t *testing.T, val any, expect string) {
t.Helper()
actual, err := json.Marshal(val)
require.NoError(t, err)
assert.Equal(t, expect, string(actual))
}
|
mikeee/dapr
|
pkg/injector/patcher/sidecar_container_test.go
|
GO
|
mit
| 34,790 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package patcher
import (
"strconv"
jsonpatch "github.com/evanphx/json-patch/v5"
corev1 "k8s.io/api/core/v1"
injectorConsts "github.com/dapr/dapr/pkg/injector/consts"
"github.com/dapr/dapr/pkg/validation"
)
// NeedsPatching returns true if patching is needed.
func (c *SidecarConfig) NeedsPatching() bool {
return c.Enabled && !c.podContainsSidecarContainer()
}
// GetPatch returns the patch to apply to a Pod to inject the Dapr sidecar
func (c *SidecarConfig) GetPatch() (patchOps jsonpatch.Patch, err error) {
// If Dapr is not enabled, or if the daprd container is already present, return
if !c.NeedsPatching() {
return nil, nil
}
// Validate AppID
err = validation.ValidateKubernetesAppID(c.GetAppID())
if err != nil {
return nil, err
}
patchOps = jsonpatch.Patch{}
// Get the list of app and component containers
appContainers, componentContainers := c.splitContainers()
if err != nil {
return nil, err
}
// Get volume mounts and add the UDS volume mount if needed
volumeMounts := c.getVolumeMounts()
volumes := make([]corev1.Volume, 0, 2)
containerVolumeMounts := make([]corev1.VolumeMount, 0, 1)
if c.UnixDomainSocketPath != "" {
volume, daprdMount, appMount := c.getUnixDomainSocketVolumeMount()
// Add to volumes so a new volume is created
volumes = append(volumes, volume)
// Add to volumeMounts so it's added to the daprd container
volumeMounts = append(volumeMounts, daprdMount)
// Add to containerVolumeMounts so it's added to the app containers
containerVolumeMounts = append(containerVolumeMounts, appMount)
}
// Pluggable components
var injectedComponentContainers []corev1.Container
if c.GetInjectedComponentContainers != nil && c.InjectPluggableComponents {
injectedComponentContainers, err = c.GetInjectedComponentContainers(c.GetAppID(), c.Namespace)
if err != nil {
return nil, err
}
}
componentPatchOps, componentsSocketVolumeMount := c.componentsPatchOps(componentContainers, injectedComponentContainers)
// Projected volume with the token
if !c.DisableTokenVolume {
tokenVolume := c.getTokenVolume()
// Add to volumes so a new volume is created
volumes = append(volumes, tokenVolume)
// Add to volumeMounts so it's added to the daprd container
volumeMounts = append(volumeMounts, corev1.VolumeMount{
Name: injectorConsts.TokenVolumeName,
MountPath: injectorConsts.TokenVolumeKubernetesMountPath,
ReadOnly: true,
})
}
// Get the sidecar container
sidecarContainer, err := c.getSidecarContainer(getSidecarContainerOpts{
ComponentsSocketsVolumeMount: componentsSocketVolumeMount,
VolumeMounts: volumeMounts,
})
if err != nil {
return nil, err
}
// Create the list of patch operations
if len(c.pod.Spec.Containers) == 0 {
// Set to empty to support add operations individually
patchOps = append(patchOps,
NewPatchOperation("add", PatchPathContainers, []corev1.Container{}),
)
}
if len(c.pod.Labels) == 0 {
// Set to empty to support add operations individually
patchOps = append(patchOps,
NewPatchOperation("add", PatchPathLabels, map[string]string{}),
)
}
// Add all volumes
if len(volumes) > 0 {
patchOps = append(patchOps, c.getVolumesPatchOperations(volumes, PatchPathVolumes)...)
}
// Other patch operations
patchOps = append(patchOps,
NewPatchOperation("add", PatchPathContainers+"/-", sidecarContainer),
NewPatchOperation("add", PatchPathLabels+"/dapr.io~1sidecar-injected", "true"),
NewPatchOperation("add", PatchPathLabels+"/dapr.io~1app-id", c.GetAppID()),
NewPatchOperation("add", PatchPathLabels+"/dapr.io~1metrics-enabled", strconv.FormatBool(c.EnableMetrics)),
)
patchOps = append(patchOps,
c.addDaprEnvVarsToContainers(appContainers, c.GetAppProtocol())...,
)
for _, vm := range containerVolumeMounts {
patchOps = append(patchOps,
addVolumeMountToContainers(appContainers, vm)...,
)
}
patchOps = append(patchOps, componentPatchOps...)
return patchOps, nil
}
// podContainsSidecarContainer returns true if the pod contains a sidecar container (i.e. a container named "daprd").
func (c *SidecarConfig) podContainsSidecarContainer() bool {
for _, c := range c.pod.Spec.Containers {
if c.Name == injectorConsts.SidecarContainerName {
return true
}
}
return false
}
// addDaprEnvVarsToContainers adds Dapr environment variables to all the containers in any Dapr-enabled pod.
// The containers can be injected or user-defined.
func (c *SidecarConfig) addDaprEnvVarsToContainers(containers map[int]corev1.Container, appProtocol string) jsonpatch.Patch {
envPatchOps := make(jsonpatch.Patch, 0, len(containers)*2)
envVars := []corev1.EnvVar{
{
Name: injectorConsts.UserContainerDaprHTTPPortName,
Value: strconv.FormatInt(int64(c.SidecarHTTPPort), 10),
},
{
Name: injectorConsts.UserContainerDaprGRPCPortName,
Value: strconv.FormatInt(int64(c.SidecarAPIGRPCPort), 10),
},
}
if appProtocol != "" {
envVars = append(envVars, corev1.EnvVar{
Name: injectorConsts.UserContainerAppProtocolName,
Value: appProtocol,
})
}
for i, container := range containers {
patchOps := GetEnvPatchOperations(container.Env, envVars, i)
envPatchOps = append(envPatchOps, patchOps...)
}
return envPatchOps
}
|
mikeee/dapr
|
pkg/injector/patcher/sidecar_patcher.go
|
GO
|
mit
| 5,817 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package patcher
import (
"strings"
"testing"
jsonpatch "github.com/evanphx/json-patch/v5"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/dapr/dapr/pkg/injector/annotations"
injectorConsts "github.com/dapr/dapr/pkg/injector/consts"
)
func TestAddDaprEnvVarsToContainers(t *testing.T) {
testCases := []struct {
testName string
mockContainer corev1.Container
appProtocol string
expOpsLen int
expOps jsonpatch.Patch
}{
{
testName: "empty environment vars",
mockContainer: corev1.Container{
Name: "MockContainer",
},
expOpsLen: 1,
expOps: jsonpatch.Patch{
NewPatchOperation("add", PatchPathContainers+"/0/env", []corev1.EnvVar{
{
Name: injectorConsts.UserContainerDaprHTTPPortName,
Value: "3500",
},
{
Name: injectorConsts.UserContainerDaprGRPCPortName,
Value: "50001",
},
}),
},
},
{
testName: "existing env var",
mockContainer: corev1.Container{
Name: "Mock Container",
Env: []corev1.EnvVar{
{
Name: "TEST",
Value: "Existing value",
},
},
},
expOpsLen: 2,
expOps: jsonpatch.Patch{
NewPatchOperation("add", PatchPathContainers+"/0/env/-", corev1.EnvVar{
Name: injectorConsts.UserContainerDaprHTTPPortName,
Value: "3500",
}),
NewPatchOperation("add", PatchPathContainers+"/0/env/-", corev1.EnvVar{
Name: injectorConsts.UserContainerDaprGRPCPortName,
Value: "50001",
}),
},
},
{
testName: "existing conflicting env var",
mockContainer: corev1.Container{
Name: "Mock Container",
Env: []corev1.EnvVar{
{
Name: "TEST",
Value: "Existing value",
},
{
Name: injectorConsts.UserContainerDaprGRPCPortName,
Value: "550000",
},
},
},
expOpsLen: 1,
expOps: jsonpatch.Patch{
NewPatchOperation("add", PatchPathContainers+"/0/env/-", corev1.EnvVar{
Name: injectorConsts.UserContainerDaprHTTPPortName,
Value: "3500",
}),
},
},
{
testName: "multiple existing conflicting env vars",
mockContainer: corev1.Container{
Name: "Mock Container",
Env: []corev1.EnvVar{
{
Name: injectorConsts.UserContainerDaprHTTPPortName,
Value: "3510",
},
{
Name: injectorConsts.UserContainerDaprGRPCPortName,
Value: "550000",
},
},
},
expOpsLen: 0,
expOps: jsonpatch.Patch{},
},
{
testName: "with app protocol",
mockContainer: corev1.Container{
Name: "MockContainer",
},
expOpsLen: 1,
appProtocol: "h2c",
expOps: jsonpatch.Patch{
NewPatchOperation("add", PatchPathContainers+"/0/env", []corev1.EnvVar{
{
Name: injectorConsts.UserContainerDaprHTTPPortName,
Value: "3500",
},
{
Name: injectorConsts.UserContainerDaprGRPCPortName,
Value: "50001",
},
{
Name: injectorConsts.UserContainerAppProtocolName,
Value: "h2c",
},
}),
},
},
}
for _, tc := range testCases {
t.Run(tc.testName, func(t *testing.T) {
c := NewSidecarConfig(&corev1.Pod{})
patchEnv := c.addDaprEnvVarsToContainers(map[int]corev1.Container{0: tc.mockContainer}, tc.appProtocol)
assert.Len(t, patchEnv, tc.expOpsLen)
assert.Equal(t, tc.expOps, patchEnv)
})
}
}
func TestPodNeedsPatching(t *testing.T) {
tests := []struct {
name string
want bool
pod *corev1.Pod
}{
{
name: "false if enabled annotation is missing",
want: false,
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{},
},
},
},
{
name: "false if enabled annotation is falsey",
want: false,
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
annotations.KeyEnabled: "0",
},
},
},
},
{
name: "true if enabled annotation is truthy",
want: true,
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
annotations.KeyEnabled: "yes",
},
},
},
},
{
name: "false if daprd container already exists",
want: false,
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
annotations.KeyEnabled: "yes",
},
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{Name: "daprd"},
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := NewSidecarConfig(tt.pod)
c.SetFromPodAnnotations()
got := c.NeedsPatching()
if got != tt.want {
t.Errorf("SidecarConfig.NeedsPatching() = %v, want %v", got, tt.want)
}
})
}
}
func TestPatching(t *testing.T) {
assertDaprdContainerFn := func(t *testing.T, pod *corev1.Pod) {
t.Helper()
assert.Len(t, pod.Spec.Containers, 2)
assert.Equal(t, "appcontainer", pod.Spec.Containers[0].Name)
assert.Equal(t, "daprd", pod.Spec.Containers[1].Name)
assert.Equal(t, "/daprd", pod.Spec.Containers[1].Args[0])
}
type testCase struct {
name string
podModifierFn func(pod *corev1.Pod)
sidecarConfigModifierFn func(c *SidecarConfig)
assertFn func(t *testing.T, pod *corev1.Pod)
}
testCaseFn := func(tc testCase) func(t *testing.T) {
return func(t *testing.T) {
pod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "myapp",
Annotations: map[string]string{
"dapr.io/enabled": "true",
"dapr.io/app-id": "myapp",
},
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: "appcontainer",
Image: "container:1.0",
Env: []corev1.EnvVar{
{Name: "CIAO", Value: "mondo"},
},
},
},
},
}
if tc.podModifierFn != nil {
tc.podModifierFn(pod)
}
c := NewSidecarConfig(pod)
c.Namespace = "testns"
c.Identity = "pod:identity"
c.SentrySPIFFEID = "spiffe://foo.bar/ns/example/dapr-sentry"
if tc.sidecarConfigModifierFn != nil {
tc.sidecarConfigModifierFn(c)
}
c.SetFromPodAnnotations()
patch, err := c.GetPatch()
require.NoError(t, err)
newPod, err := PatchPod(pod, patch)
require.NoError(t, err)
tc.assertFn(t, newPod)
}
}
tests := []testCase{
{
name: "basic test",
assertFn: func(t *testing.T, pod *corev1.Pod) {
assertDaprdContainerFn(t, pod)
// Assertions around the Daprd container
daprdContainer := pod.Spec.Containers[1]
assert.Equal(t, "/daprd", daprdContainer.Args[0])
daprdEnvVars := map[string]string{}
for _, env := range daprdContainer.Env {
daprdEnvVars[env.Name] = env.Value
}
assert.Equal(t, "testns", daprdEnvVars["NAMESPACE"])
assert.Len(t, daprdContainer.VolumeMounts, 1)
assert.Equal(t, "dapr-identity-token", daprdContainer.VolumeMounts[0].Name)
assert.Equal(t, "/var/run/secrets/dapr.io/sentrytoken", daprdContainer.VolumeMounts[0].MountPath)
assert.True(t, daprdContainer.VolumeMounts[0].ReadOnly)
assert.NotNil(t, daprdContainer.LivenessProbe)
assert.Equal(t, "/v1.0/healthz", daprdContainer.LivenessProbe.HTTPGet.Path)
assert.Equal(t, 3501, daprdContainer.LivenessProbe.HTTPGet.Port.IntValue())
// Assertions on added volumes
assert.Len(t, pod.Spec.Volumes, 1)
tokenVolume := pod.Spec.Volumes[0]
assert.Equal(t, "dapr-identity-token", tokenVolume.Name)
assert.NotNil(t, tokenVolume.Projected)
require.Len(t, tokenVolume.Projected.Sources, 1)
require.NotNil(t, tokenVolume.Projected.Sources[0].ServiceAccountToken)
assert.Equal(t, "spiffe://foo.bar/ns/example/dapr-sentry", tokenVolume.Projected.Sources[0].ServiceAccountToken.Audience)
// Assertions on added labels
assert.Equal(t, "true", pod.Labels[injectorConsts.SidecarInjectedLabel])
assert.Equal(t, "myapp", pod.Labels[injectorConsts.SidecarAppIDLabel])
assert.Equal(t, "true", pod.Labels[injectorConsts.SidecarMetricsEnabledLabel])
// Assertions on added envs
appEnvVars := map[string]string{}
for _, env := range pod.Spec.Containers[0].Env {
appEnvVars[env.Name] = env.Value
}
assert.Equal(t, "mondo", appEnvVars["CIAO"])
assert.Equal(t, "3500", appEnvVars["DAPR_HTTP_PORT"])
assert.Equal(t, "50001", appEnvVars["DAPR_GRPC_PORT"])
assert.Equal(t, "http", appEnvVars["APP_PROTOCOL"])
},
},
{
name: "with UDS",
podModifierFn: func(pod *corev1.Pod) {
pod.Annotations[annotations.KeyUnixDomainSocketPath] = "/tmp/socket"
},
assertFn: func(t *testing.T, pod *corev1.Pod) {
assertDaprdContainerFn(t, pod)
// Check the presence of the volume
assert.Len(t, pod.Spec.Volumes, 2)
socketVolume := pod.Spec.Volumes[0]
assert.Equal(t, "dapr-unix-domain-socket", socketVolume.Name)
assert.NotNil(t, socketVolume.EmptyDir)
assert.Equal(t, corev1.StorageMediumMemory, socketVolume.EmptyDir.Medium)
tokenVolume := pod.Spec.Volumes[1]
assert.Equal(t, "dapr-identity-token", tokenVolume.Name)
assert.NotNil(t, tokenVolume.Projected)
require.Len(t, tokenVolume.Projected.Sources, 1)
require.NotNil(t, tokenVolume.Projected.Sources[0].ServiceAccountToken)
assert.Equal(t, "spiffe://foo.bar/ns/example/dapr-sentry", tokenVolume.Projected.Sources[0].ServiceAccountToken.Audience)
// Check the presence of the volume mount in the app container
appContainer := pod.Spec.Containers[0]
assert.Len(t, appContainer.VolumeMounts, 1)
assert.Equal(t, "dapr-unix-domain-socket", appContainer.VolumeMounts[0].Name)
assert.Equal(t, "/tmp/socket", appContainer.VolumeMounts[0].MountPath)
// Check the presence of the volume mount in the daprd container
daprdContainer := pod.Spec.Containers[1]
assert.Len(t, daprdContainer.VolumeMounts, 2)
assert.Equal(t, "dapr-unix-domain-socket", daprdContainer.VolumeMounts[0].Name)
assert.Equal(t, "/var/run/dapr-sockets", daprdContainer.VolumeMounts[0].MountPath)
// Ensure the CLI flag is set
args := strings.Join(daprdContainer.Args, " ")
assert.Contains(t, args, "--unix-domain-socket /var/run/dapr-sockets")
},
},
}
for _, tc := range tests {
t.Run(tc.name, testCaseFn(tc))
}
}
|
mikeee/dapr
|
pkg/injector/patcher/sidecar_patcher_test.go
|
GO
|
mit
| 10,841 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package patcher
import (
"testing"
"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
"github.com/dapr/dapr/pkg/injector/annotations"
injectorConsts "github.com/dapr/dapr/pkg/injector/consts"
)
func TestSidecarConfigInit(t *testing.T) {
c := NewSidecarConfig(&corev1.Pod{})
// Ensure default values are set (and that those without a default value are zero)
// Check properties of supported kinds: bools, strings, ints
assert.Equal(t, "", c.Config)
assert.Equal(t, "info", c.LogLevel)
assert.Equal(t, int32(0), c.AppPort)
assert.Equal(t, int32(9090), c.SidecarMetricsPort)
assert.False(t, c.EnableProfiling)
assert.True(t, c.EnableMetrics)
// These properties don't have an annotation but should have a default value anyways
assert.Equal(t, injectorConsts.ModeKubernetes, c.Mode)
assert.Equal(t, int32(3500), c.SidecarHTTPPort)
assert.Equal(t, int32(50001), c.SidecarAPIGRPCPort)
// Nullable properties
assert.Nil(t, c.EnableAPILogging)
}
func TestSidecarConfigSetFromAnnotations(t *testing.T) {
t.Run("set properties", func(t *testing.T) {
c := NewSidecarConfig(&corev1.Pod{})
// Set properties of supported kinds: bools, strings, ints
c.setFromAnnotations(map[string]string{
annotations.KeyEnabled: "1", // Will be cast using utils.IsTruthy
annotations.KeyAppID: "myappid",
annotations.KeyAppPort: "9876",
annotations.KeyMetricsPort: "6789", // Override default value
annotations.KeyEnableAPILogging: "false", // Nullable property
})
assert.True(t, c.Enabled)
assert.Equal(t, "myappid", c.AppID)
assert.Equal(t, int32(9876), c.AppPort)
assert.Equal(t, int32(6789), c.SidecarMetricsPort)
// Nullable properties
_ = assert.NotNil(t, c.EnableAPILogging) &&
assert.False(t, *c.EnableAPILogging)
// Should maintain default values
assert.Equal(t, "info", c.LogLevel)
})
t.Run("skip invalid properties", func(t *testing.T) {
c := NewSidecarConfig(&corev1.Pod{})
// Set properties of supported kinds: bools, strings, ints
c.setFromAnnotations(map[string]string{
annotations.KeyAppPort: "zorro",
annotations.KeyHTTPMaxRequestSize: "batman", // Nullable property
})
assert.Equal(t, int32(0), c.AppPort)
assert.Nil(t, c.HTTPMaxRequestSize)
})
}
|
mikeee/dapr
|
pkg/injector/patcher/sidecar_test.go
|
GO
|
mit
| 2,855 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package patcher
import (
"strings"
jsonpatch "github.com/evanphx/json-patch/v5"
corev1 "k8s.io/api/core/v1"
injectorConsts "github.com/dapr/dapr/pkg/injector/consts"
"github.com/dapr/kit/ptr"
)
// getVolumeMounts returns the list of VolumeMount's for the sidecar container.
func (c *SidecarConfig) getVolumeMounts() []corev1.VolumeMount {
vs := append(
parseVolumeMountsString(c.VolumeMounts, true),
parseVolumeMountsString(c.VolumeMountsRW, false)...,
)
// Allocate with an extra 3 capacity because we are appending more volumes later
volumeMounts := make([]corev1.VolumeMount, 0, len(vs)+3)
for _, v := range vs {
if podContainsVolume(c.pod, v.Name) {
volumeMounts = append(volumeMounts, v)
} else {
log.Warnf("Volume %s is not present in pod %s, skipping", v.Name, c.pod.GetName())
}
}
return volumeMounts
}
// getUnixDomainSocketVolumeMount returns a volume and mounts for the pod to append the UNIX domain socket.
func (c *SidecarConfig) getUnixDomainSocketVolumeMount() (vol corev1.Volume, daprdVolMount corev1.VolumeMount, appVolMount corev1.VolumeMount) {
vol = corev1.Volume{
Name: injectorConsts.UnixDomainSocketVolume,
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{
Medium: corev1.StorageMediumMemory,
},
},
}
daprdVolMount = corev1.VolumeMount{
Name: injectorConsts.UnixDomainSocketVolume,
MountPath: injectorConsts.UnixDomainSocketDaprdPath,
}
appVolMount = corev1.VolumeMount{
Name: injectorConsts.UnixDomainSocketVolume,
MountPath: c.UnixDomainSocketPath,
}
return
}
// getTokenVolume returns the volume projection for the Kubernetes service account.
// Requests a new projected volume with a service account token for our specific audience.
func (c *SidecarConfig) getTokenVolume() corev1.Volume {
return corev1.Volume{
Name: injectorConsts.TokenVolumeName,
VolumeSource: corev1.VolumeSource{
Projected: &corev1.ProjectedVolumeSource{
DefaultMode: ptr.Of(int32(420)),
Sources: []corev1.VolumeProjection{{
ServiceAccountToken: &corev1.ServiceAccountTokenProjection{
Audience: c.SentrySPIFFEID,
ExpirationSeconds: ptr.Of(int64(7200)),
Path: "token",
},
}},
},
},
}
}
func addVolumeMountToContainers(containers map[int]corev1.Container, addMounts corev1.VolumeMount) jsonpatch.Patch {
volumeMount := []corev1.VolumeMount{addMounts}
volumeMountPatchOps := make(jsonpatch.Patch, 0, len(containers))
for i, container := range containers {
patchOps := GetVolumeMountPatchOperations(container.VolumeMounts, volumeMount, i)
volumeMountPatchOps = append(volumeMountPatchOps, patchOps...)
}
return volumeMountPatchOps
}
func (c *SidecarConfig) getVolumesPatchOperations(addVolumes []corev1.Volume, path string) jsonpatch.Patch {
if len(c.pod.Spec.Volumes) == 0 {
// If there are no volumes defined in the container, we initialize a slice of volumes.
return jsonpatch.Patch{
NewPatchOperation("add", path, addVolumes),
}
}
// If there are existing volumes, then we are adding to an existing slice of volumes.
path += "/-"
patchOps := make(jsonpatch.Patch, len(addVolumes))
n := 0
for _, addVolume := range addVolumes {
isConflict := false
for _, mount := range c.pod.Spec.Volumes {
// conflict cases
if addVolume.Name == mount.Name {
isConflict = true
break
}
}
if isConflict {
continue
}
patchOps[n] = NewPatchOperation("add", path, addVolume)
n++
}
return patchOps[:n]
}
func podContainsVolume(pod *corev1.Pod, name string) bool {
for _, volume := range pod.Spec.Volumes {
if volume.Name == name {
return true
}
}
return false
}
// parseVolumeMountsString parses the annotation and returns volume mounts.
// The format of the annotation is: "mountPath1:hostPath1,mountPath2:hostPath2"
// The readOnly parameter applies to all mounts.
func parseVolumeMountsString(volumeMountStr string, readOnly bool) []corev1.VolumeMount {
vs := strings.Split(volumeMountStr, ",")
volumeMounts := make([]corev1.VolumeMount, 0, len(vs))
for _, v := range vs {
vmount := strings.Split(strings.TrimSpace(v), ":")
if len(vmount) != 2 {
continue
}
volumeMounts = append(volumeMounts, corev1.VolumeMount{
Name: vmount[0],
MountPath: vmount[1],
ReadOnly: readOnly,
})
}
return volumeMounts
}
|
mikeee/dapr
|
pkg/injector/patcher/sidecar_volumes.go
|
GO
|
mit
| 4,933 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package patcher
import (
"testing"
jsonpatch "github.com/evanphx/json-patch/v5"
"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
injectorConsts "github.com/dapr/dapr/pkg/injector/consts"
)
func TestParseVolumeMountsString(t *testing.T) {
testCases := []struct {
testName string
mountStr string
readOnly bool
expMountsLen int
expMounts []corev1.VolumeMount
}{
{
testName: "empty volume mount string.",
mountStr: "",
readOnly: false,
expMountsLen: 0,
expMounts: []corev1.VolumeMount{},
},
{
testName: "valid volume mount string with readonly false.",
mountStr: "my-mount:/tmp/mount1,another-mount:/home/user/mount2, mount3:/root/mount3",
readOnly: false,
expMountsLen: 3,
expMounts: []corev1.VolumeMount{
{
Name: "my-mount",
MountPath: "/tmp/mount1",
},
{
Name: "another-mount",
MountPath: "/home/user/mount2",
},
{
Name: "mount3",
MountPath: "/root/mount3",
},
},
},
{
testName: "valid volume mount string with readonly true.",
mountStr: " my-mount:/tmp/mount1,mount2:/root/mount2 ",
readOnly: true,
expMountsLen: 2,
expMounts: []corev1.VolumeMount{
{
Name: "my-mount",
MountPath: "/tmp/mount1",
ReadOnly: true,
},
{
Name: "mount2",
MountPath: "/root/mount2",
ReadOnly: true,
},
},
},
{
testName: "volume mount string with invalid mounts",
mountStr: "my-mount:/tmp/mount1:rw,mount2:/root/mount2,mount3",
readOnly: false,
expMountsLen: 1,
expMounts: []corev1.VolumeMount{
{
Name: "mount2",
MountPath: "/root/mount2",
},
},
},
}
for _, tc := range testCases {
tc := tc
t.Run(tc.testName, func(t *testing.T) {
mounts := parseVolumeMountsString(tc.mountStr, tc.readOnly)
assert.Len(t, mounts, tc.expMountsLen)
assert.Equal(t, tc.expMounts, mounts)
})
}
}
func TestPodContainsVolume(t *testing.T) {
testCases := []struct {
testName string
podVolumes []corev1.Volume
volumeName string
expect bool
}{
{
"pod with no volumes",
[]corev1.Volume{},
"volume1",
false,
},
{
"pod does not contain volume",
[]corev1.Volume{
{Name: "volume"},
},
"volume1",
false,
},
{
"pod contains volume",
[]corev1.Volume{
{Name: "volume1"},
{Name: "volume2"},
},
"volume2",
true,
},
}
for _, tc := range testCases {
t.Run(tc.testName, func(t *testing.T) {
pod := &corev1.Pod{
Spec: corev1.PodSpec{
Volumes: tc.podVolumes,
},
}
assert.Equal(t, tc.expect, podContainsVolume(pod, tc.volumeName))
})
}
}
func TestGetVolumeMounts(t *testing.T) {
testCases := []struct {
testName string
volumeReadOnlyAnnotation string
volumeReadWriteAnnotation string
podVolumeMountNames []string
expVolumeMounts []corev1.VolumeMount
}{
{
"no annotations",
"",
"",
[]string{"mount1", "mount2"},
[]corev1.VolumeMount{},
},
{
"annotations with volumes present in pod",
"mount1:/tmp/mount1,mount2:/tmp/mount2",
"mount3:/tmp/mount3,mount4:/tmp/mount4",
[]string{"mount1", "mount2", "mount3", "mount4"},
[]corev1.VolumeMount{
{Name: "mount1", MountPath: "/tmp/mount1", ReadOnly: true},
{Name: "mount2", MountPath: "/tmp/mount2", ReadOnly: true},
{Name: "mount3", MountPath: "/tmp/mount3", ReadOnly: false},
{Name: "mount4", MountPath: "/tmp/mount4", ReadOnly: false},
},
},
{
"annotations with volumes not present in pod",
"mount1:/tmp/mount1,mount2:/tmp/mount2",
"mount3:/tmp/mount3,mount4:/tmp/mount4",
[]string{"mount1", "mount2", "mount4"},
[]corev1.VolumeMount{
{Name: "mount1", MountPath: "/tmp/mount1", ReadOnly: true},
{Name: "mount2", MountPath: "/tmp/mount2", ReadOnly: true},
{Name: "mount4", MountPath: "/tmp/mount4", ReadOnly: false},
},
},
}
for _, tc := range testCases {
t.Run(tc.testName, func(t *testing.T) {
pod := &corev1.Pod{
Spec: corev1.PodSpec{
Volumes: []corev1.Volume{},
},
}
for _, volumeName := range tc.podVolumeMountNames {
pod.Spec.Volumes = append(pod.Spec.Volumes, corev1.Volume{Name: volumeName})
}
c := NewSidecarConfig(pod)
c.VolumeMounts = tc.volumeReadOnlyAnnotation
c.VolumeMountsRW = tc.volumeReadWriteAnnotation
volumeMounts := c.getVolumeMounts()
assert.Equal(t, tc.expVolumeMounts, volumeMounts)
})
}
}
func TestGetUnixDomainSocketVolume(t *testing.T) {
c := NewSidecarConfig(&corev1.Pod{})
c.UnixDomainSocketPath = "/tmp"
volume, daprdMount, appMount := c.getUnixDomainSocketVolumeMount()
assert.Equal(t, injectorConsts.UnixDomainSocketVolume, volume.Name)
assert.NotNil(t, volume.VolumeSource.EmptyDir)
assert.Equal(t, injectorConsts.UnixDomainSocketVolume, daprdMount.Name)
assert.Equal(t, injectorConsts.UnixDomainSocketDaprdPath, daprdMount.MountPath)
assert.Equal(t, injectorConsts.UnixDomainSocketVolume, appMount.Name)
assert.Equal(t, "/tmp", appMount.MountPath)
}
func TestAddVolumeToContainers(t *testing.T) {
testCases := []struct {
testName string
mockContainer corev1.Container
socketMount corev1.VolumeMount
expOpsLen int
expOps jsonpatch.Patch
}{
{
testName: "existing var, empty volume",
mockContainer: corev1.Container{
Name: "MockContainer",
},
socketMount: corev1.VolumeMount{
Name: injectorConsts.UnixDomainSocketVolume,
MountPath: "/tmp",
},
expOpsLen: 1,
expOps: jsonpatch.Patch{
NewPatchOperation("add", "/spec/containers/0/volumeMounts", []corev1.VolumeMount{{
Name: injectorConsts.UnixDomainSocketVolume,
MountPath: "/tmp",
}}),
},
},
{
testName: "existing var, existing volume",
mockContainer: corev1.Container{
Name: "MockContainer",
VolumeMounts: []corev1.VolumeMount{
{Name: "mock1"},
},
},
socketMount: corev1.VolumeMount{
Name: injectorConsts.UnixDomainSocketVolume,
MountPath: "/tmp",
},
expOpsLen: 1,
expOps: jsonpatch.Patch{
NewPatchOperation("add", "/spec/containers/0/volumeMounts/-", corev1.VolumeMount{
Name: injectorConsts.UnixDomainSocketVolume,
MountPath: "/tmp",
}),
},
},
{
testName: "existing var, multiple existing volumes",
mockContainer: corev1.Container{
Name: "MockContainer",
VolumeMounts: []corev1.VolumeMount{
{Name: "mock1"},
{Name: "mock2"},
},
},
socketMount: corev1.VolumeMount{
Name: injectorConsts.UnixDomainSocketVolume,
MountPath: "/tmp",
},
expOpsLen: 1,
expOps: jsonpatch.Patch{
NewPatchOperation("add", "/spec/containers/0/volumeMounts/-", corev1.VolumeMount{
Name: injectorConsts.UnixDomainSocketVolume,
MountPath: "/tmp",
}),
},
},
{
testName: "existing var, conflict volume name",
mockContainer: corev1.Container{
Name: "MockContainer",
VolumeMounts: []corev1.VolumeMount{
{Name: injectorConsts.UnixDomainSocketVolume},
},
},
socketMount: corev1.VolumeMount{
Name: injectorConsts.UnixDomainSocketVolume,
MountPath: "/tmp",
},
expOpsLen: 0,
expOps: jsonpatch.Patch{},
},
{
testName: "existing var, conflict volume mount path",
mockContainer: corev1.Container{
Name: "MockContainer",
VolumeMounts: []corev1.VolumeMount{
{MountPath: "/tmp"},
},
},
socketMount: corev1.VolumeMount{
Name: injectorConsts.UnixDomainSocketVolume,
MountPath: "/tmp",
},
expOpsLen: 0,
expOps: jsonpatch.Patch{},
},
}
for _, tc := range testCases {
t.Run(tc.testName, func(t *testing.T) {
patchEnv := addVolumeMountToContainers(map[int]corev1.Container{0: tc.mockContainer}, tc.socketMount)
assert.Len(t, patchEnv, tc.expOpsLen)
assert.Equal(t, tc.expOps, patchEnv)
})
}
}
|
mikeee/dapr
|
pkg/injector/patcher/sidecar_volumes_test.go
|
GO
|
mit
| 8,532 |
/*
Copyright 2022 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package service
import (
"encoding/json"
"fmt"
"github.com/kelseyhightower/envconfig"
corev1 "k8s.io/api/core/v1"
"github.com/dapr/dapr/pkg/injector/patcher"
"github.com/dapr/dapr/utils"
kitutils "github.com/dapr/kit/utils"
)
// Config represents configuration options for the Dapr Sidecar Injector webhook server.
type Config struct {
SidecarImage string `envconfig:"SIDECAR_IMAGE" required:"true"`
SidecarImagePullPolicy string `envconfig:"SIDECAR_IMAGE_PULL_POLICY"`
Namespace string `envconfig:"NAMESPACE" required:"true"`
KubeClusterDomain string `envconfig:"KUBE_CLUSTER_DOMAIN"`
AllowedServiceAccounts string `envconfig:"ALLOWED_SERVICE_ACCOUNTS"`
AllowedServiceAccountsPrefixNames string `envconfig:"ALLOWED_SERVICE_ACCOUNTS_PREFIX_NAMES"`
IgnoreEntrypointTolerations string `envconfig:"IGNORE_ENTRYPOINT_TOLERATIONS"`
ActorsEnabled string `envconfig:"ACTORS_ENABLED"`
ActorsServiceName string `envconfig:"ACTORS_SERVICE_NAME"`
ActorsServiceAddress string `envconfig:"ACTORS_SERVICE_ADDRESS"`
RemindersServiceName string `envconfig:"REMINDERS_SERVICE_NAME"`
RemindersServiceAddress string `envconfig:"REMINDERS_SERVICE_ADDRESS"`
RunAsNonRoot string `envconfig:"SIDECAR_RUN_AS_NON_ROOT"`
ReadOnlyRootFilesystem string `envconfig:"SIDECAR_READ_ONLY_ROOT_FILESYSTEM"`
EnableK8sDownwardAPIs string `envconfig:"ENABLE_K8S_DOWNWARD_APIS"`
SidecarDropALLCapabilities string `envconfig:"SIDECAR_DROP_ALL_CAPABILITIES"`
TrustAnchorsFile string `envconfig:"DAPR_TRUST_ANCHORS_FILE"`
ControlPlaneTrustDomain string `envconfig:"DAPR_CONTROL_PLANE_TRUST_DOMAIN"`
SentryAddress string `envconfig:"DAPR_SENTRY_ADDRESS"`
parsedActorsEnabled bool
parsedActorsService patcher.Service
parsedRemindersService patcher.Service
parsedRunAsNonRoot bool
parsedReadOnlyRootFilesystem bool
parsedEnableK8sDownwardAPIs bool
parsedSidecarDropALLCapabilities bool
parsedEntrypointTolerations []corev1.Toleration
}
// NewConfigWithDefaults returns a Config object with default values already
// applied. Callers are then free to set custom values for the remaining fields
// and/or override default values.
func NewConfigWithDefaults() Config {
return Config{
SidecarImagePullPolicy: "Always",
ControlPlaneTrustDomain: "cluster.local",
TrustAnchorsFile: "/var/run/dapr.io/tls/ca.crt",
}
}
// GetConfig returns configuration derived from environment variables.
func GetConfig() (Config, error) {
// get config from environment variables
c := NewConfigWithDefaults()
err := envconfig.Process("", &c)
if err != nil {
return c, err
}
if c.KubeClusterDomain == "" {
// auto-detect KubeClusterDomain from resolv.conf file
var clusterDomain string
clusterDomain, err = utils.GetKubeClusterDomain()
if err != nil {
log.Errorf("Failed to get clusterDomain err:%s, set default:%s", err, utils.DefaultKubeClusterDomain)
c.KubeClusterDomain = utils.DefaultKubeClusterDomain
} else {
c.KubeClusterDomain = clusterDomain
}
}
err = c.parse()
if err != nil {
return c, fmt.Errorf("failed to parse configuration: %w", err)
}
return c, nil
}
func (c Config) GetPullPolicy() corev1.PullPolicy {
switch c.SidecarImagePullPolicy {
case "Always":
return corev1.PullAlways
case "Never":
return corev1.PullNever
case "IfNotPresent":
return corev1.PullIfNotPresent
default:
return corev1.PullIfNotPresent
}
}
func (c Config) GetIgnoreEntrypointTolerations() []corev1.Toleration {
return c.parsedEntrypointTolerations
}
func (c Config) GetRunAsNonRoot() bool {
return c.parsedRunAsNonRoot
}
func (c Config) GetReadOnlyRootFilesystem() bool {
return c.parsedReadOnlyRootFilesystem
}
func (c Config) GetEnableK8sDownwardAPIs() bool {
return c.parsedEnableK8sDownwardAPIs
}
func (c Config) GetDropCapabilities() bool {
return c.parsedSidecarDropALLCapabilities
}
func (c Config) GetActorsEnabled() bool {
return c.parsedActorsEnabled
}
func (c Config) GetActorsService() (string, patcher.Service) {
return c.ActorsServiceName, c.parsedActorsService
}
// GetRemindersService returns the configured reminders service.
// The returned boolean value will be false if the configuration uses the built-in reminders subsystem
func (c Config) GetRemindersService() (string, patcher.Service, bool) {
if c.RemindersServiceName == "" {
return "", patcher.Service{}, false
}
return c.RemindersServiceName, c.parsedRemindersService, true
}
func (c *Config) parse() (err error) {
// If there's no configuration for the actors service, use the traditional placement
if c.ActorsServiceName == "" {
c.ActorsServiceName = "placement"
c.parsedActorsService = patcher.ServicePlacement
} else {
c.parsedActorsService, err = patcher.NewService(c.ActorsServiceAddress)
if err != nil {
return fmt.Errorf("invalid value for actor service address: %w", err)
}
}
// If the name of the reminders service is empty, we assume we are using the built-in capabilities
if c.RemindersServiceName != "" && c.RemindersServiceName != "default" {
c.parsedRemindersService, err = patcher.NewService(c.RemindersServiceAddress)
if err != nil {
return fmt.Errorf("invalid value for reminder service address: %w", err)
}
}
// Parse the tolerations as JSON
c.parseTolerationsJSON()
// Set some booleans
c.parsedActorsEnabled = isTruthyDefaultTrue(c.ActorsEnabled)
c.parsedRunAsNonRoot = isTruthyDefaultTrue(c.RunAsNonRoot)
c.parsedReadOnlyRootFilesystem = isTruthyDefaultTrue(c.ReadOnlyRootFilesystem)
c.parsedEnableK8sDownwardAPIs = kitutils.IsTruthy(c.EnableK8sDownwardAPIs)
c.parsedSidecarDropALLCapabilities = kitutils.IsTruthy(c.SidecarDropALLCapabilities)
return nil
}
func (c *Config) parseTolerationsJSON() {
if c.IgnoreEntrypointTolerations == "" {
return
}
// If the string contains an invalid value, log a warning and continue.
ts := []corev1.Toleration{}
err := json.Unmarshal([]byte(c.IgnoreEntrypointTolerations), &ts)
if err != nil {
log.Warnf("Couldn't parse entrypoint tolerations (%s): %v", c.IgnoreEntrypointTolerations, err)
return
}
c.parsedEntrypointTolerations = ts
}
func isTruthyDefaultTrue(val string) bool {
// Default is true if empty
if val == "" {
return true
}
return kitutils.IsTruthy(val)
}
|
mikeee/dapr
|
pkg/injector/service/config.go
|
GO
|
mit
| 7,080 |
/*
Copyright 2022 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package service
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
)
func TestGetInjectorConfig(t *testing.T) {
t.Run("with kube cluster domain env", func(t *testing.T) {
t.Setenv("TLS_CERT_FILE", "test-cert-file")
t.Setenv("TLS_KEY_FILE", "test-key-file")
t.Setenv("SIDECAR_IMAGE", "daprd-test-image")
t.Setenv("SIDECAR_IMAGE_PULL_POLICY", "Always")
t.Setenv("NAMESPACE", "test-namespace")
t.Setenv("KUBE_CLUSTER_DOMAIN", "cluster.local")
t.Setenv("ALLOWED_SERVICE_ACCOUNTS", "test1:test-service-account1,test2:test-service-account2")
t.Setenv("ALLOWED_SERVICE_ACCOUNTS_PREFIX_NAMES", "namespace:test-service-account1,namespace2*:test-service-account2")
cfg, err := GetConfig()
require.NoError(t, err)
assert.Equal(t, "daprd-test-image", cfg.SidecarImage)
assert.Equal(t, "Always", cfg.SidecarImagePullPolicy)
assert.Equal(t, "test-namespace", cfg.Namespace)
assert.Equal(t, "cluster.local", cfg.KubeClusterDomain)
assert.Equal(t, "test1:test-service-account1,test2:test-service-account2", cfg.AllowedServiceAccounts)
assert.Equal(t, "namespace:test-service-account1,namespace2*:test-service-account2", cfg.AllowedServiceAccountsPrefixNames)
})
t.Run("not set kube cluster domain env", func(t *testing.T) {
t.Setenv("TLS_CERT_FILE", "test-cert-file")
t.Setenv("TLS_KEY_FILE", "test-key-file")
t.Setenv("SIDECAR_IMAGE", "daprd-test-image")
t.Setenv("SIDECAR_IMAGE_PULL_POLICY", "IfNotPresent")
t.Setenv("NAMESPACE", "test-namespace")
t.Setenv("KUBE_CLUSTER_DOMAIN", "")
cfg, err := GetConfig()
require.NoError(t, err)
assert.Equal(t, "daprd-test-image", cfg.SidecarImage)
assert.Equal(t, "IfNotPresent", cfg.SidecarImagePullPolicy)
assert.Equal(t, "test-namespace", cfg.Namespace)
assert.NotEqual(t, "", cfg.KubeClusterDomain)
})
t.Run("sidecar run options not set", func(t *testing.T) {
t.Setenv("TLS_CERT_FILE", "test-cert-file")
t.Setenv("TLS_KEY_FILE", "test-key-file")
t.Setenv("SIDECAR_IMAGE", "daprd-test-image")
t.Setenv("NAMESPACE", "test-namespace")
// Default values are true
t.Setenv("SIDECAR_RUN_AS_NON_ROOT", "")
t.Setenv("SIDECAR_READ_ONLY_ROOT_FILESYSTEM", "")
cfg, err := GetConfig()
require.NoError(t, err)
assert.True(t, cfg.GetRunAsNonRoot())
assert.True(t, cfg.GetReadOnlyRootFilesystem())
// Set to true explicitly
t.Setenv("SIDECAR_RUN_AS_NON_ROOT", "true")
t.Setenv("SIDECAR_READ_ONLY_ROOT_FILESYSTEM", "1")
cfg, err = GetConfig()
require.NoError(t, err)
assert.True(t, cfg.GetRunAsNonRoot())
assert.True(t, cfg.GetReadOnlyRootFilesystem())
// Set to false
t.Setenv("SIDECAR_RUN_AS_NON_ROOT", "0")
t.Setenv("SIDECAR_READ_ONLY_ROOT_FILESYSTEM", "no")
cfg, err = GetConfig()
require.NoError(t, err)
assert.False(t, cfg.GetRunAsNonRoot())
assert.False(t, cfg.GetReadOnlyRootFilesystem())
})
}
func TestImagePullPolicy(t *testing.T) {
testCases := []struct {
testName string
pullPolicy string
expectedPolicy corev1.PullPolicy
}{
{
"TestDefaultPullPolicy",
"",
corev1.PullIfNotPresent,
},
{
"TestAlwaysPullPolicy",
"Always",
corev1.PullAlways,
},
{
"TestNeverPullPolicy",
"Never",
corev1.PullNever,
},
{
"TestIfNotPresentPullPolicy",
"IfNotPresent",
corev1.PullIfNotPresent,
},
}
for _, tc := range testCases {
t.Run(tc.testName, func(t *testing.T) {
c := NewConfigWithDefaults()
c.SidecarImagePullPolicy = tc.pullPolicy
assert.Equal(t, tc.expectedPolicy, c.GetPullPolicy())
})
}
}
func TestTolerationsParsing(t *testing.T) {
testCases := []struct {
name string
expect []corev1.Toleration
input string
}{
{
"empty tolerations",
nil,
"",
},
{
"single toleration",
[]corev1.Toleration{
{
Key: "foo.com/bar",
Effect: "NoSchedule",
},
},
`[{"key":"foo.com/bar","Effect":"NoSchedule"}]`,
},
{
"multiple tolerations",
[]corev1.Toleration{
{
Key: "foo.com/bar",
Effect: "NoSchedule",
},
{
Key: "foo.com/baz",
Operator: "Equal",
Value: "foobar",
Effect: "NoSchedule",
},
},
`[{"key":"foo.com/bar","Effect":"NoSchedule"},{"key":"foo.com/baz","Operator":"Equal","Value":"foobar","Effect":"NoSchedule"}]`,
},
{
"invalid JSON",
nil,
`hi`,
},
{
"invalid JSON structure",
nil,
`{}`,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
c := &Config{
IgnoreEntrypointTolerations: tc.input,
}
c.parseTolerationsJSON()
assert.EqualValues(t, tc.expect, c.GetIgnoreEntrypointTolerations())
})
}
}
|
mikeee/dapr
|
pkg/injector/service/config_test.go
|
GO
|
mit
| 5,250 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package service
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
jsonpatch "github.com/evanphx/json-patch/v5"
admissionv1 "k8s.io/api/admission/v1"
"k8s.io/apimachinery/pkg/runtime"
"github.com/dapr/dapr/utils"
)
func (i *injector) handleRequest(w http.ResponseWriter, r *http.Request) {
RecordSidecarInjectionRequestsCount()
var body []byte
var err error
if r.Body != nil {
defer r.Body.Close()
body, err = io.ReadAll(r.Body)
if err != nil {
body = nil
}
}
if len(body) == 0 {
log.Error("Empty body")
http.Error(w, "empty body", http.StatusBadRequest)
return
}
contentType := r.Header.Get("Content-Type")
if contentType != runtime.ContentTypeJSON {
log.Errorf("Content-Type=%s, expect %s", contentType, runtime.ContentTypeJSON)
errStr := fmt.Sprintf("invalid Content-Type, expected `%s`", runtime.ContentTypeJSON)
http.Error(w, errStr, http.StatusUnsupportedMediaType)
return
}
var patchOps jsonpatch.Patch
patchedSuccessfully := false
ar := admissionv1.AdmissionReview{}
_, gvk, err := i.deserializer.Decode(body, nil, &ar)
if err != nil {
log.Errorf("Can't decode body: %v", err)
} else {
allowServiceAccountUser := i.allowServiceAccountUser(ar.Request.UserInfo.Username)
if !(allowServiceAccountUser || utils.Contains(i.authUIDs, ar.Request.UserInfo.UID) || utils.Contains(ar.Request.UserInfo.Groups, systemGroup)) {
log.Errorf("service account '%s' not on the list of allowed controller accounts", ar.Request.UserInfo.Username)
} else if ar.Request.Kind.Kind != "Pod" {
log.Errorf("invalid kind for review: %s", ar.Kind)
} else {
patchOps, err = i.getPodPatchOperations(r.Context(), &ar)
if err == nil {
patchedSuccessfully = true
}
}
}
diagAppID := getAppIDFromRequest(ar.Request)
var admissionResponse *admissionv1.AdmissionResponse
if err != nil {
admissionResponse = errorToAdmissionResponse(err)
log.Errorf("Sidecar injector failed to inject for app '%s'. Error: %s", diagAppID, err)
RecordFailedSidecarInjectionCount(diagAppID, "patch")
} else if len(patchOps) == 0 {
admissionResponse = &admissionv1.AdmissionResponse{
Allowed: true,
}
} else {
var patchBytes []byte
patchBytes, err = json.Marshal(patchOps)
if err != nil {
admissionResponse = errorToAdmissionResponse(err)
} else {
admissionResponse = &admissionv1.AdmissionResponse{
Allowed: true,
Patch: patchBytes,
PatchType: func() *admissionv1.PatchType {
pt := admissionv1.PatchTypeJSONPatch
return &pt
}(),
}
}
}
admissionReview := admissionv1.AdmissionReview{
Response: admissionResponse,
}
if admissionResponse != nil && ar.Request != nil {
admissionReview.Response.UID = ar.Request.UID
admissionReview.SetGroupVersionKind(*gvk)
}
respBytes, err := json.Marshal(admissionReview)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Errorf("Sidecar injector failed to inject for app '%s'. Can't serialize response: %s", diagAppID, err)
RecordFailedSidecarInjectionCount(diagAppID, "response")
return
}
w.Header().Set("Content-Type", runtime.ContentTypeJSON)
_, err = w.Write(respBytes)
if err != nil {
log.Errorf("Sidecar injector failed to inject for app '%s'. Failed to write response: %v", diagAppID, err)
RecordFailedSidecarInjectionCount(diagAppID, "write_response")
return
}
if patchedSuccessfully {
log.Infof("Sidecar injector succeeded injection for app '%s'", diagAppID)
RecordSuccessfulSidecarInjectionCount(diagAppID)
} else {
log.Errorf("Admission succeeded, but pod was not patched. No sidecar injected for '%s'", diagAppID)
RecordFailedSidecarInjectionCount(diagAppID, "pod_patch")
}
}
func (i *injector) allowServiceAccountUser(reviewRequestUserInfo string) (allowedUID bool) {
if i.namespaceNameMatcher == nil {
return false
}
namespacedName, prefixFound := strings.CutPrefix(reviewRequestUserInfo, serviceAccountUserInfoPrefix)
if !prefixFound {
return false
}
namespacedNameParts := strings.Split(namespacedName, ":")
if len(namespacedNameParts) <= 1 {
return false
}
return i.namespaceNameMatcher.MatchesNamespacedName(namespacedNameParts[0], namespacedNameParts[1])
}
|
mikeee/dapr
|
pkg/injector/service/handler.go
|
GO
|
mit
| 4,775 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package service
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
admissionv1 "k8s.io/api/admission/v1"
authenticationv1 "k8s.io/api/authentication/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/uuid"
kubernetesfake "k8s.io/client-go/kubernetes/fake"
"github.com/dapr/dapr/pkg/client/clientset/versioned/fake"
)
func TestHandleRequest(t *testing.T) {
authID := "test-auth-id"
i, err := NewInjector(Options{
AuthUIDs: []string{authID},
Config: Config{
SidecarImage: "test-image",
Namespace: "test-ns",
ControlPlaneTrustDomain: "test-trust-domain",
AllowedServiceAccountsPrefixNames: "vc-proj*:sa-dev*,vc-all-allowed*:*",
},
DaprClient: fake.NewSimpleClientset(),
KubeClient: kubernetesfake.NewSimpleClientset(),
})
require.NoError(t, err)
injector := i.(*injector)
injector.currentTrustAnchors = func(context.Context) ([]byte, error) {
return nil, nil
}
podBytes, _ := json.Marshal(corev1.Pod{
TypeMeta: metav1.TypeMeta{
Kind: "Pod",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "test-app",
Namespace: "default",
CreationTimestamp: metav1.Time{Time: time.Now()},
Labels: map[string]string{
"app": "test-app",
},
Annotations: map[string]string{
"dapr.io/enabled": "true",
"dapr.io/app-id": "test-app",
"dapr.io/app-port": "3000",
},
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: "main",
Image: "docker.io/app:latest",
},
},
},
})
testCases := []struct {
testName string
request admissionv1.AdmissionReview
contentType string
expectStatusCode int
expectPatched bool
}{
{
"TestSidecarInjectSuccess",
admissionv1.AdmissionReview{
Request: &admissionv1.AdmissionRequest{
UID: uuid.NewUUID(),
Kind: metav1.GroupVersionKind{Group: "", Version: "v1", Kind: "Pod"},
Name: "test-app",
Namespace: "test-ns",
Operation: "CREATE",
UserInfo: authenticationv1.UserInfo{
Groups: []string{systemGroup},
},
Object: runtime.RawExtension{Raw: podBytes},
},
},
runtime.ContentTypeJSON,
http.StatusOK,
true,
},
{
"TestSidecarInjectWrongContentType",
admissionv1.AdmissionReview{},
runtime.ContentTypeYAML,
http.StatusUnsupportedMediaType,
true,
},
{
"TestSidecarInjectInvalidKind",
admissionv1.AdmissionReview{
Request: &admissionv1.AdmissionRequest{
UID: uuid.NewUUID(),
Kind: metav1.GroupVersionKind{Group: "", Version: "v1", Kind: "Deployment"},
Name: "test-app",
Namespace: "test-ns",
Operation: "CREATE",
UserInfo: authenticationv1.UserInfo{
Groups: []string{systemGroup},
},
Object: runtime.RawExtension{Raw: podBytes},
},
},
runtime.ContentTypeJSON,
http.StatusOK,
false,
},
{
"TestSidecarInjectGroupsNotContains",
admissionv1.AdmissionReview{
Request: &admissionv1.AdmissionRequest{
UID: uuid.NewUUID(),
Kind: metav1.GroupVersionKind{Group: "", Version: "v1", Kind: "Pod"},
Name: "test-app",
Namespace: "test-ns",
Operation: "CREATE",
UserInfo: authenticationv1.UserInfo{
Groups: []string{"system:kubelet"},
},
Object: runtime.RawExtension{Raw: podBytes},
},
},
runtime.ContentTypeJSON,
http.StatusOK,
false,
},
{
"TestSidecarInjectUIDContains",
admissionv1.AdmissionReview{
Request: &admissionv1.AdmissionRequest{
UID: uuid.NewUUID(),
Kind: metav1.GroupVersionKind{Group: "", Version: "v1", Kind: "Pod"},
Name: "test-app",
Namespace: "test-ns",
Operation: "CREATE",
UserInfo: authenticationv1.UserInfo{
UID: authID,
},
Object: runtime.RawExtension{Raw: podBytes},
},
},
runtime.ContentTypeJSON,
http.StatusOK,
true,
},
{
"TestSidecarInjectUIDNotContains",
admissionv1.AdmissionReview{
Request: &admissionv1.AdmissionRequest{
UID: uuid.NewUUID(),
Kind: metav1.GroupVersionKind{Group: "", Version: "v1", Kind: "Pod"},
Name: "test-app",
Namespace: "test-ns",
Operation: "CREATE",
UserInfo: authenticationv1.UserInfo{
UID: "auth-id-123",
},
Object: runtime.RawExtension{Raw: podBytes},
},
},
runtime.ContentTypeJSON,
http.StatusOK,
false,
},
{
"TestSidecarInjectEmptyPod",
admissionv1.AdmissionReview{
Request: &admissionv1.AdmissionRequest{
UID: uuid.NewUUID(),
Kind: metav1.GroupVersionKind{Group: "", Version: "v1", Kind: "Pod"},
Name: "test-app",
Namespace: "test-ns",
Operation: "CREATE",
UserInfo: authenticationv1.UserInfo{
Groups: []string{systemGroup},
},
Object: runtime.RawExtension{Raw: nil},
},
},
runtime.ContentTypeJSON,
http.StatusOK,
false,
},
{
"TestSidecarInjectUserInfoMatchesServiceAccountPrefix",
admissionv1.AdmissionReview{
Request: &admissionv1.AdmissionRequest{
UID: uuid.NewUUID(),
Kind: metav1.GroupVersionKind{Group: "", Version: "v1", Kind: "Pod"},
Name: "test-app",
Namespace: "test-ns",
Operation: "CREATE",
UserInfo: authenticationv1.UserInfo{
Username: "system:serviceaccount:vc-project-star:sa-dev-team-usa",
},
Object: runtime.RawExtension{Raw: podBytes},
},
},
runtime.ContentTypeJSON,
http.StatusOK,
true,
},
{
"TestSidecarInjectUserInfoMatchesAllAllowedServiceAccountPrefix",
admissionv1.AdmissionReview{
Request: &admissionv1.AdmissionRequest{
UID: uuid.NewUUID(),
Kind: metav1.GroupVersionKind{Group: "", Version: "v1", Kind: "Pod"},
Name: "test-app",
Namespace: "test-ns",
Operation: "CREATE",
UserInfo: authenticationv1.UserInfo{
Username: "system:serviceaccount:vc-all-allowed-project:dapr",
},
Object: runtime.RawExtension{Raw: podBytes},
},
},
runtime.ContentTypeJSON,
http.StatusOK,
true,
},
{
"TestSidecarInjectUserInfoNotMatchesServiceAccountPrefix",
admissionv1.AdmissionReview{
Request: &admissionv1.AdmissionRequest{
UID: uuid.NewUUID(),
Kind: metav1.GroupVersionKind{Group: "", Version: "v1", Kind: "Pod"},
Name: "test-app",
Namespace: "test-ns",
Operation: "CREATE",
UserInfo: authenticationv1.UserInfo{
Username: "system:serviceaccount:vc-bad-project-star:sa-dev-team-usa",
},
Object: runtime.RawExtension{Raw: podBytes},
},
},
runtime.ContentTypeJSON,
http.StatusOK,
false,
},
}
ts := httptest.NewServer(http.HandlerFunc(injector.handleRequest))
defer ts.Close()
for _, tc := range testCases {
tc := tc
t.Run(tc.testName, func(t *testing.T) {
requestBytes, err := json.Marshal(tc.request)
require.NoError(t, err)
resp, err := http.Post(ts.URL, tc.contentType, bytes.NewBuffer(requestBytes))
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, tc.expectStatusCode, resp.StatusCode)
if resp.StatusCode == http.StatusOK {
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var ar admissionv1.AdmissionReview
err = json.Unmarshal(body, &ar)
require.NoError(t, err)
assert.Equal(t, tc.expectPatched, len(ar.Response.Patch) > 0)
}
})
}
}
|
mikeee/dapr
|
pkg/injector/service/handler_test.go
|
GO
|
mit
| 8,273 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package service
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/spiffe/go-spiffe/v2/spiffeid"
admissionv1 "k8s.io/api/admission/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/client-go/kubernetes"
scheme "github.com/dapr/dapr/pkg/client/clientset/versioned"
"github.com/dapr/dapr/pkg/injector/annotations"
"github.com/dapr/dapr/pkg/injector/namespacednamematcher"
"github.com/dapr/kit/logger"
)
const (
getKubernetesServiceAccountTimeoutSeconds = 10
systemGroup = "system:masters"
serviceAccountUserInfoPrefix = "system:serviceaccount:"
)
var log = logger.NewLogger("dapr.injector.service")
var AllowedServiceAccountInfos = []string{
"kube-system:replicaset-controller",
"kube-system:deployment-controller",
"kube-system:cronjob-controller",
"kube-system:job-controller",
"kube-system:statefulset-controller",
"kube-system:daemon-set-controller",
"tekton-pipelines:tekton-pipelines-controller",
}
type (
currentTrustAnchorsFn func(context.Context) (ca []byte, err error)
)
// Injector is the interface for the Dapr runtime sidecar injection component.
type Injector interface {
Run(context.Context, *tls.Config, spiffeid.ID, currentTrustAnchorsFn) error
Ready(context.Context) error
}
type Options struct {
AuthUIDs []string
Config Config
DaprClient scheme.Interface
KubeClient kubernetes.Interface
Port int
ListenAddress string
ControlPlaneNamespace string
ControlPlaneTrustDomain string
}
type injector struct {
config Config
deserializer runtime.Decoder
server *http.Server
kubeClient kubernetes.Interface
daprClient scheme.Interface
authUIDs []string
controlPlaneNamespace string
controlPlaneTrustDomain string
currentTrustAnchors currentTrustAnchorsFn
sentrySPIFFEID spiffeid.ID
namespaceNameMatcher *namespacednamematcher.EqualPrefixNameNamespaceMatcher
ready chan struct{}
}
// errorToAdmissionResponse is a helper function to create an AdmissionResponse
// with an embedded error.
func errorToAdmissionResponse(err error) *admissionv1.AdmissionResponse {
return &admissionv1.AdmissionResponse{
Result: &metav1.Status{
Message: err.Error(),
},
}
}
// getAppIDFromRequest returns the app ID for the pod, which is used for diagnostics purposes only
func getAppIDFromRequest(req *admissionv1.AdmissionRequest) (appID string) {
if req == nil {
return ""
}
// Parse the request as a pod
var pod corev1.Pod
err := json.Unmarshal(req.Object.Raw, &pod)
if err != nil {
log.Warnf("could not unmarshal raw object: %v", err)
return ""
}
// Search for an app-id in the annotations first
for k, v := range pod.GetObjectMeta().GetAnnotations() {
if k == annotations.KeyAppID {
return v
}
}
// Fallback to pod name
return pod.GetName()
}
// NewInjector returns a new Injector instance with the given config.
func NewInjector(opts Options) (Injector, error) {
mux := http.NewServeMux()
i := &injector{
config: opts.Config,
deserializer: serializer.NewCodecFactory(
runtime.NewScheme(),
).UniversalDeserializer(),
server: &http.Server{
Addr: fmt.Sprintf("%s:%d", opts.ListenAddress, opts.Port),
Handler: mux,
ReadHeaderTimeout: 10 * time.Second,
},
kubeClient: opts.KubeClient,
daprClient: opts.DaprClient,
authUIDs: opts.AuthUIDs,
controlPlaneNamespace: opts.ControlPlaneNamespace,
controlPlaneTrustDomain: opts.ControlPlaneTrustDomain,
ready: make(chan struct{}),
}
matcher, err := createNamespaceNameMatcher(opts.Config.AllowedServiceAccountsPrefixNames)
if err != nil {
return nil, err
}
i.namespaceNameMatcher = matcher
mux.HandleFunc("/mutate", i.handleRequest)
return i, nil
}
func createNamespaceNameMatcher(allowedPrefix string) (matcher *namespacednamematcher.EqualPrefixNameNamespaceMatcher, err error) {
allowedPrefix = strings.TrimSpace(allowedPrefix)
if allowedPrefix != "" {
matcher, err = namespacednamematcher.CreateFromString(allowedPrefix)
if err != nil {
return nil, err
}
log.Debugf("Sidecar injector configured to allowed serviceaccounts prefixed by: %s", allowedPrefix)
}
return matcher, nil
}
// AllowedControllersServiceAccountUID returns an array of UID, list of allowed service account on the webhook handler.
func AllowedControllersServiceAccountUID(ctx context.Context, cfg Config, kubeClient kubernetes.Interface) ([]string, error) {
allowedList := []string{}
if cfg.AllowedServiceAccounts != "" {
allowedList = append(allowedList, strings.Split(cfg.AllowedServiceAccounts, ",")...)
}
allowedList = append(allowedList, AllowedServiceAccountInfos...)
return getServiceAccount(ctx, kubeClient, allowedList)
}
// getServiceAccount parses "service-account:namespace" k/v list and returns an array of UID.
func getServiceAccount(ctx context.Context, kubeClient kubernetes.Interface, allowedServiceAccountInfos []string) ([]string, error) {
ctxWithTimeout, cancel := context.WithTimeout(ctx, getKubernetesServiceAccountTimeoutSeconds*time.Second)
defer cancel()
serviceaccounts, err := kubeClient.CoreV1().ServiceAccounts("").List(ctxWithTimeout, metav1.ListOptions{})
if err != nil {
return nil, err
}
allowedUids := []string{}
for _, allowedServiceInfo := range allowedServiceAccountInfos {
serviceAccountInfo := strings.Split(allowedServiceInfo, ":")
found := false
for _, sa := range serviceaccounts.Items {
if sa.Namespace == serviceAccountInfo[0] && sa.Name == serviceAccountInfo[1] {
allowedUids = append(allowedUids, string(sa.ObjectMeta.UID))
found = true
break
}
}
if !found {
log.Warnf("Unable to get SA %s UID", allowedServiceInfo)
}
}
return allowedUids, nil
}
func (i *injector) Run(ctx context.Context, tlsConfig *tls.Config, sentryID spiffeid.ID, currentTrustAnchors currentTrustAnchorsFn) error {
select {
case <-i.ready:
return errors.New("injector already running")
default:
// Nop
}
log.Infof("Sidecar injector is listening on %s, patching Dapr-enabled pods", i.server.Addr)
i.currentTrustAnchors = currentTrustAnchors
i.sentrySPIFFEID = sentryID
i.server.TLSConfig = tlsConfig
errCh := make(chan error, 1)
go func() {
err := i.server.ListenAndServeTLS("", "")
if !errors.Is(err, http.ErrServerClosed) {
errCh <- fmt.Errorf("sidecar injector error: %w", err)
return
}
errCh <- nil
}()
close(i.ready)
select {
case <-ctx.Done():
log.Info("Sidecar injector is shutting down")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := i.server.Shutdown(shutdownCtx); err != nil {
return fmt.Errorf("error while shutting down injector: %v; %v", err, <-errCh)
}
return <-errCh
case err := <-errCh:
return err
}
}
func (i *injector) Ready(ctx context.Context) error {
select {
case <-i.ready:
return nil
case <-ctx.Done():
return errors.New("timed out waiting for injector to become ready")
}
}
|
mikeee/dapr
|
pkg/injector/service/injector.go
|
GO
|
mit
| 7,803 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package service
import (
"context"
"encoding/json"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
admissionv1 "k8s.io/api/admission/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
kubernetesfake "k8s.io/client-go/kubernetes/fake"
"github.com/dapr/dapr/pkg/injector/namespacednamematcher"
)
func TestConfigCorrectValues(t *testing.T) {
i, err := NewInjector(Options{
Config: Config{
SidecarImage: "c",
SidecarImagePullPolicy: "d",
Namespace: "e",
AllowedServiceAccountsPrefixNames: "ns*:sa,namespace:sa*",
ControlPlaneTrustDomain: "trust.domain",
},
})
require.NoError(t, err)
injector := i.(*injector)
assert.Equal(t, "c", injector.config.SidecarImage)
assert.Equal(t, "d", injector.config.SidecarImagePullPolicy)
assert.Equal(t, "e", injector.config.Namespace)
m, err := namespacednamematcher.CreateFromString("ns*:sa,namespace:sa*")
require.NoError(t, err)
assert.Equal(t, m, injector.namespaceNameMatcher)
}
func TestNewInjectorBadAllowedPrefixedServiceAccountConfig(t *testing.T) {
_, err := NewInjector(Options{
Config: Config{
SidecarImage: "c",
SidecarImagePullPolicy: "d",
Namespace: "e",
AllowedServiceAccountsPrefixNames: "ns*:sa,namespace:sa*sa",
},
})
require.Error(t, err)
}
func TestGetAppIDFromRequest(t *testing.T) {
t.Run("can handle nil", func(t *testing.T) {
appID := getAppIDFromRequest(nil)
assert.Equal(t, "", appID)
})
t.Run("can handle empty admissionrequest object", func(t *testing.T) {
fakeReq := &admissionv1.AdmissionRequest{}
appID := getAppIDFromRequest(fakeReq)
assert.Equal(t, "", appID)
})
t.Run("get appID from annotations", func(t *testing.T) {
fakePod := corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
"dapr.io/app-id": "fakeID",
},
},
}
rawBytes, _ := json.Marshal(fakePod)
fakeReq := &admissionv1.AdmissionRequest{
Object: runtime.RawExtension{
Raw: rawBytes,
},
}
appID := getAppIDFromRequest(fakeReq)
assert.Equal(t, "fakeID", appID)
})
t.Run("fall back to pod name", func(t *testing.T) {
fakePod := corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "mypod",
},
}
rawBytes, _ := json.Marshal(fakePod)
fakeReq := &admissionv1.AdmissionRequest{
Object: runtime.RawExtension{
Raw: rawBytes,
},
}
appID := getAppIDFromRequest(fakeReq)
assert.Equal(t, "mypod", appID)
})
}
func TestAllowedControllersServiceAccountUID(t *testing.T) {
client := kubernetesfake.NewSimpleClientset()
testCases := []struct {
namespace string
name string
}{
{metav1.NamespaceSystem, "replicaset-controller"},
{"tekton-pipelines", "tekton-pipelines-controller"},
{"test", "test"},
}
for _, testCase := range testCases {
sa := &corev1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Name: testCase.name,
Namespace: testCase.namespace,
},
}
_, err := client.CoreV1().ServiceAccounts(testCase.namespace).Create(context.TODO(), sa, metav1.CreateOptions{})
require.NoError(t, err)
}
t.Run("injector config has no allowed service account", func(t *testing.T) {
uids, err := AllowedControllersServiceAccountUID(context.TODO(), Config{}, client)
require.NoError(t, err)
assert.Len(t, uids, 2)
})
t.Run("injector config has a valid allowed service account", func(t *testing.T) {
uids, err := AllowedControllersServiceAccountUID(context.TODO(), Config{AllowedServiceAccounts: "test:test"}, client)
require.NoError(t, err)
assert.Len(t, uids, 3)
})
t.Run("injector config has a invalid allowed service account", func(t *testing.T) {
uids, err := AllowedControllersServiceAccountUID(context.TODO(), Config{AllowedServiceAccounts: "abc:abc"}, client)
require.NoError(t, err)
assert.Len(t, uids, 2)
})
t.Run("injector config has multiple allowed service accounts", func(t *testing.T) {
uids, err := AllowedControllersServiceAccountUID(context.TODO(), Config{AllowedServiceAccounts: "test:test,abc:abc"}, client)
require.NoError(t, err)
assert.Len(t, uids, 3)
})
}
func TestReady(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
t.Run("if injector ready return nil", func(t *testing.T) {
i := &injector{ready: make(chan struct{})}
close(i.ready)
require.NoError(t, i.Ready(ctx))
})
t.Run("if not ready then should return timeout error if context cancelled", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*10)
defer cancel()
i := &injector{ready: make(chan struct{})}
require.EqualError(t, i.Ready(ctx), "timed out waiting for injector to become ready")
})
}
|
mikeee/dapr
|
pkg/injector/service/injector_test.go
|
GO
|
mit
| 5,451 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package service
import (
"context"
"go.opencensus.io/stats"
"go.opencensus.io/stats/view"
"go.opencensus.io/tag"
diagUtils "github.com/dapr/dapr/pkg/diagnostics/utils"
)
const (
appID = "app_id"
failedReason = "reason"
)
var (
sidecarInjectionRequestsTotal = stats.Int64(
"injector/sidecar_injection/requests_total",
"The total number of sidecar injection requests.",
stats.UnitDimensionless)
succeededSidecarInjectedTotal = stats.Int64(
"injector/sidecar_injection/succeeded_total",
"The total number of successful sidecar injections.",
stats.UnitDimensionless)
failedSidecarInjectedTotal = stats.Int64(
"injector/sidecar_injection/failed_total",
"The total number of failed sidecar injections.",
stats.UnitDimensionless)
noKeys = []tag.Key{}
// appIDKey is a tag key for App ID.
appIDKey = tag.MustNewKey(appID)
// failedReasonKey is a tag key for failed reason.
failedReasonKey = tag.MustNewKey(failedReason)
)
// RecordSidecarInjectionRequestsCount records the total number of sidecar injection requests.
func RecordSidecarInjectionRequestsCount() {
stats.Record(context.Background(), sidecarInjectionRequestsTotal.M(1))
}
// RecordSuccessfulSidecarInjectionCount records the number of successful sidecar injections.
func RecordSuccessfulSidecarInjectionCount(appID string) {
stats.RecordWithTags(context.Background(), diagUtils.WithTags(succeededSidecarInjectedTotal.Name(), appIDKey, appID), succeededSidecarInjectedTotal.M(1))
}
// RecordFailedSidecarInjectionCount records the number of failed sidecar injections.
func RecordFailedSidecarInjectionCount(appID, reason string) {
stats.RecordWithTags(context.Background(), diagUtils.WithTags(failedSidecarInjectedTotal.Name(), appIDKey, appID, failedReasonKey, reason), failedSidecarInjectedTotal.M(1))
}
// InitMetrics initialize the injector service metrics.
func InitMetrics() error {
err := view.Register(
diagUtils.NewMeasureView(sidecarInjectionRequestsTotal, noKeys, view.Count()),
diagUtils.NewMeasureView(succeededSidecarInjectedTotal, []tag.Key{appIDKey}, view.Count()),
diagUtils.NewMeasureView(failedSidecarInjectedTotal, []tag.Key{appIDKey, failedReasonKey}, view.Count()),
)
return err
}
|
mikeee/dapr
|
pkg/injector/service/metrics.go
|
GO
|
mit
| 2,783 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package service
import (
"fmt"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/dapr/dapr/pkg/injector/patcher"
)
// getInjectedComponentContainers implements GetInjectedComponentContainersFn and returns the list of injected component.
func (i *injector) getInjectedComponentContainers(appID string, namespace string) ([]corev1.Container, error) {
// FIXME There is a potential issue with the components being fetched from the operator versus at runtime.
// This would lead in two possible scenarios:
// 1) If the component is not listed here but listed in runtime,
// you may encounter runtime errors related to the missing container for the component's bootstrapping process.
// However, due to Kubernetes' reconciling approach, this issue should resolve itself over time.
// 2) If the component is listed here but not listed in runtime,
// the pod will include a redundant container that should be removed when this code is executed again.
// To resolve this issue, it is important to ensure that the same component list is used both here and in runtime,
// such as by passing it as an environment variable or populating a volume with an init container.
componentsList, err := i.daprClient.ComponentsV1alpha1().Components(namespace).List(metav1.ListOptions{})
if err != nil {
return nil, fmt.Errorf("error when fetching components: %w", err)
}
return patcher.Injectable(appID, componentsList.Items), nil
}
|
mikeee/dapr
|
pkg/injector/service/pod_containers.go
|
GO
|
mit
| 2,030 |
/*
Copyright 2022 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package service
import (
"context"
"encoding/json"
"fmt"
jsonpatch "github.com/evanphx/json-patch/v5"
admissionv1 "k8s.io/api/admission/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
scheme "github.com/dapr/dapr/pkg/client/clientset/versioned"
injectorConsts "github.com/dapr/dapr/pkg/injector/consts"
"github.com/dapr/dapr/pkg/injector/patcher"
"github.com/dapr/dapr/pkg/security/token"
)
const (
defaultConfig = "daprsystem"
defaultMtlsEnabled = true
)
func (i *injector) getPodPatchOperations(ctx context.Context, ar *admissionv1.AdmissionReview) (patchOps jsonpatch.Patch, err error) {
pod := &corev1.Pod{}
err = json.Unmarshal(ar.Request.Object.Raw, pod)
if err != nil {
return nil, fmt.Errorf("could not unmarshal raw object: %w", err)
}
log.Infof(
"AdmissionReview for Kind=%v, Namespace=%s Name=%s (%s) UID=%v patchOperation=%v UserInfo=%v",
ar.Request.Kind, ar.Request.Namespace, ar.Request.Name, pod.Name, ar.Request.UID, ar.Request.Operation, ar.Request.UserInfo,
)
// Keep DNS resolution outside of GetSidecarContainer for unit testing.
sentryAddress := patcher.ServiceSentry.Address(i.config.Namespace, i.config.KubeClusterDomain)
operatorAddress := patcher.ServiceAPI.Address(i.config.Namespace, i.config.KubeClusterDomain)
trustAnchors, err := i.currentTrustAnchors(ctx)
if err != nil {
return nil, err
}
// Create the sidecar configuration object from the pod
sidecar := patcher.NewSidecarConfig(pod)
sidecar.GetInjectedComponentContainers = i.getInjectedComponentContainers
sidecar.Mode = injectorConsts.ModeKubernetes
sidecar.Namespace = ar.Request.Namespace
sidecar.MTLSEnabled = mTLSEnabled(i.controlPlaneNamespace, i.daprClient)
sidecar.Identity = ar.Request.Namespace + ":" + pod.Spec.ServiceAccountName
sidecar.IgnoreEntrypointTolerations = i.config.GetIgnoreEntrypointTolerations()
sidecar.ImagePullPolicy = i.config.GetPullPolicy()
sidecar.OperatorAddress = operatorAddress
sidecar.SentryAddress = sentryAddress
sidecar.RunAsNonRoot = i.config.GetRunAsNonRoot()
sidecar.ReadOnlyRootFilesystem = i.config.GetReadOnlyRootFilesystem()
sidecar.EnableK8sDownwardAPIs = i.config.GetEnableK8sDownwardAPIs()
sidecar.SidecarDropALLCapabilities = i.config.GetDropCapabilities()
sidecar.ControlPlaneNamespace = i.controlPlaneNamespace
sidecar.ControlPlaneTrustDomain = i.controlPlaneTrustDomain
sidecar.SentrySPIFFEID = i.sentrySPIFFEID.String()
sidecar.CurrentTrustAnchors = trustAnchors
sidecar.DisableTokenVolume = !token.HasKubernetesToken()
// Set addresses for actor services
// Even if actors are disabled, however, the placement-host-address flag will still be included if explicitly set in the annotation dapr.io/placement-host-address
// So, if the annotation is already set, we accept that and also use placement for actors services
if sidecar.PlacementAddress == "" {
// Set configuration for the actors service
actorsSvcName, actorsSvc := i.config.GetActorsService()
actorsSvcAddr := actorsSvc.Address(i.config.Namespace, i.config.KubeClusterDomain)
if actorsSvcName == "placement" {
// If the actors service is "placement" (default if empty), then we use the PlacementAddress option for backwards compatibility
// TODO: In the future, use the actors-service CLI flag too
sidecar.ActorsService = ""
sidecar.PlacementAddress = actorsSvcAddr
} else {
// We have a different actors service, not placement
// Set the actors-service CLI flag with "<name>:<address>"
sidecar.ActorsService = actorsSvcName + ":" + actorsSvcAddr
}
} else {
// If we are using placement forcefully, do not set "ActorsService"
sidecar.ActorsService = ""
}
// Set address for reminders service
// This could be empty, indicating sidecars to use the built-in reminders subsystem
remindersSvcName, remindersSvc, useRemindersSvc := i.config.GetRemindersService()
if useRemindersSvc {
// Set the reminders-service CLI flag with "<name>:<address>"
sidecar.RemindersService = remindersSvcName + ":" + remindersSvc.Address(i.config.Namespace, i.config.KubeClusterDomain)
}
// Default value for the sidecar image, which can be overridden by annotations
sidecar.SidecarImage = i.config.SidecarImage
// Set the configuration from annotations
sidecar.SetFromPodAnnotations()
// Get the patch to apply to the pod
// Patch may be empty if there's nothing that needs to be done
patch, err := sidecar.GetPatch()
if err != nil {
return nil, err
}
return patch, nil
}
func mTLSEnabled(controlPlaneNamespace string, daprClient scheme.Interface) bool {
resp, err := daprClient.ConfigurationV1alpha1().
Configurations(controlPlaneNamespace).
Get(defaultConfig, metav1.GetOptions{})
if apierrors.IsNotFound(err) {
log.Infof("Dapr system configuration '%s' does not exist; using default value %t for mTLSEnabled", defaultConfig, defaultMtlsEnabled)
return defaultMtlsEnabled
}
if err != nil {
log.Errorf("Failed to load dapr configuration from k8s, use default value %t for mTLSEnabled: %s", defaultMtlsEnabled, err)
return defaultMtlsEnabled
}
return resp.Spec.MTLSSpec.GetEnabled()
}
|
mikeee/dapr
|
pkg/injector/service/pod_patch.go
|
GO
|
mit
| 5,760 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package service
import (
"testing"
"github.com/stretchr/testify/assert"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
configapi "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1"
clientfake "github.com/dapr/dapr/pkg/client/clientset/versioned/fake"
"github.com/dapr/kit/ptr"
)
func Test_mtlsEnabled(t *testing.T) {
t.Run("if configuration doesn't exist, return true", func(t *testing.T) {
cl := clientfake.NewSimpleClientset()
assert.True(t, mTLSEnabled("test-ns", cl))
})
t.Run("if configuration exists and is false, return false", func(t *testing.T) {
cl := clientfake.NewSimpleClientset()
cl.ConfigurationV1alpha1().Configurations("test-ns").Create(
&configapi.Configuration{
ObjectMeta: metav1.ObjectMeta{
Name: "daprsystem",
Namespace: "test-ns",
},
Spec: configapi.ConfigurationSpec{MTLSSpec: &configapi.MTLSSpec{Enabled: ptr.Of(false)}},
},
)
assert.False(t, mTLSEnabled("test-ns", cl))
})
t.Run("if configuration exists and is true, return true", func(t *testing.T) {
cl := clientfake.NewSimpleClientset()
cl.ConfigurationV1alpha1().Configurations("test-ns").Create(
&configapi.Configuration{
ObjectMeta: metav1.ObjectMeta{
Name: "daprsystem",
Namespace: "test-ns",
},
Spec: configapi.ConfigurationSpec{MTLSSpec: &configapi.MTLSSpec{Enabled: ptr.Of(true)}},
},
)
assert.True(t, mTLSEnabled("test-ns", cl))
})
t.Run("if configuration exists and is nil, return true", func(t *testing.T) {
cl := clientfake.NewSimpleClientset()
cl.ConfigurationV1alpha1().Configurations("test-ns").Create(
&configapi.Configuration{
ObjectMeta: metav1.ObjectMeta{
Name: "daprsystem",
Namespace: "test-ns",
},
Spec: configapi.ConfigurationSpec{MTLSSpec: &configapi.MTLSSpec{Enabled: nil}},
},
)
assert.True(t, mTLSEnabled("test-ns", cl))
})
}
|
mikeee/dapr
|
pkg/injector/service/pod_patch_test.go
|
GO
|
mit
| 2,442 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package apis
import (
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/dapr/dapr/pkg/apis/common"
)
type GenericNameValueResource struct {
Name string
Namespace string
SecretStore string
ResourceKind string
ResourceAPIVersion string
Pairs []common.NameValuePair
}
func (g GenericNameValueResource) Kind() string {
return g.ResourceKind
}
func (g GenericNameValueResource) GetName() string {
return g.Name
}
func (g GenericNameValueResource) APIVersion() string {
return g.ResourceAPIVersion
}
func (g GenericNameValueResource) GetNamespace() string {
return g.Namespace
}
func (g GenericNameValueResource) GetSecretStore() string {
return g.SecretStore
}
func (g GenericNameValueResource) NameValuePairs() []common.NameValuePair {
return g.Pairs
}
func (g GenericNameValueResource) LogName() string {
return fmt.Sprintf("%s (%s)", g.Name, g.ResourceKind)
}
func (g GenericNameValueResource) EmptyMetaDeepCopy() metav1.Object {
return &metav1.ObjectMeta{Name: g.Name}
}
func (g GenericNameValueResource) ClientObject() client.Object {
return nil
}
func (g GenericNameValueResource) GetScopes() []string {
return nil
}
|
mikeee/dapr
|
pkg/internal/apis/namevaluepair.go
|
GO
|
mit
| 1,820 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package disk
import (
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/internal/loader"
)
func NewComponents(opts Options) loader.Loader[compapi.Component] {
return new[compapi.Component](opts)
}
|
mikeee/dapr
|
pkg/internal/loader/disk/components.go
|
GO
|
mit
| 799 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package disk
import (
"context"
"errors"
"fmt"
"os"
"github.com/dapr/dapr/pkg/runtime/meta"
"github.com/dapr/dapr/pkg/security"
"github.com/dapr/dapr/utils"
)
// disk loads a specific manifest kind from a folder.
type disk[T meta.Resource] struct {
kind string
apiVersion string
dirs []string
namespace string
appID string
}
type Options struct {
AppID string
Paths []string
}
// new creates a new manifest loader for the given paths and kind.
func new[T meta.Resource](opts Options) *disk[T] {
var zero T
return &disk[T]{
dirs: opts.Paths,
kind: zero.Kind(),
apiVersion: zero.APIVersion(),
namespace: security.CurrentNamespace(),
appID: opts.AppID,
}
}
// load loads manifests for the given directory.
func (d *disk[T]) Load(context.Context) ([]T, error) {
set, err := d.loadWithOrder()
if err != nil {
return nil, err
}
nsDefined := len(os.Getenv("NAMESPACE")) != 0
names := make(map[string]string)
filteredManifests := make([]T, 0)
var errs []error
for i := range set.ts {
// If the process or manifest namespace are not defined, ignore the
// manifest namespace.
ignoreNamespace := !nsDefined || len(set.ts[i].GetNamespace()) == 0
// Ignore manifests that are not in the process security namespace.
if !ignoreNamespace && set.ts[i].GetNamespace() != d.namespace {
continue
}
if existing, ok := names[set.ts[i].GetName()]; ok {
errs = append(errs, fmt.Errorf("duplicate definition of %s name %s with existing %s",
set.ts[i].Kind(), set.ts[i].LogName(), existing))
continue
}
// Skip manifests which are not in scope
scopes := set.ts[i].GetScopes()
if !(len(scopes) == 0 || utils.Contains(scopes, d.appID)) {
continue
}
names[set.ts[i].GetName()] = set.ts[i].LogName()
filteredManifests = append(filteredManifests, set.ts[i])
}
if len(errs) > 0 {
return nil, errors.Join(errs...)
}
return filteredManifests, nil
}
func (d *disk[T]) loadWithOrder() (*manifestSet[T], error) {
set := &manifestSet[T]{d: d}
for _, dir := range d.dirs {
if err := set.loadManifestsFromDirectory(dir); err != nil {
return nil, err
}
}
return set, nil
}
|
mikeee/dapr
|
pkg/internal/loader/disk/disk.go
|
GO
|
mit
| 2,745 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package disk
import (
"context"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/dapr/dapr/pkg/apis/common"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/kit/ptr"
)
func TestLoad(t *testing.T) {
t.Run("valid yaml content", func(t *testing.T) {
tmp := t.TempDir()
request := NewComponents(Options{
Paths: []string{tmp},
})
filename := "test-component-valid.yaml"
yaml := `
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: statestore
spec:
type: state.couchbase
metadata:
- name: prop1
value: value1
- name: prop2
value: value2
`
require.NoError(t, os.WriteFile(filepath.Join(tmp, filename), []byte(yaml), fs.FileMode(0o600)))
components, err := request.Load(context.Background())
require.NoError(t, err)
assert.Len(t, components, 1)
})
t.Run("invalid yaml head", func(t *testing.T) {
tmp := t.TempDir()
request := NewComponents(Options{
Paths: []string{tmp},
})
filename := "test-component-invalid.yaml"
yaml := `
INVALID_YAML_HERE
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: statestore`
require.NoError(t, os.WriteFile(filepath.Join(tmp, filename), []byte(yaml), fs.FileMode(0o600)))
components, err := request.Load(context.Background())
require.NoError(t, err)
assert.Empty(t, components)
})
t.Run("load components file not exist", func(t *testing.T) {
request := NewComponents(Options{
Paths: []string{"test-path-no-exists"},
})
components, err := request.Load(context.Background())
require.Error(t, err)
assert.Empty(t, components)
})
t.Run("error and namespace", func(t *testing.T) {
buildComp := func(name string, namespace *string, scopes ...string) string {
var ns string
if namespace != nil {
ns = fmt.Sprintf("\n namespace: %s\n", *namespace)
}
var scopeS string
if len(scopes) > 0 {
scopeS = fmt.Sprintf("\nscopes:\n- %s", strings.Join(scopes, "\n- "))
}
return fmt.Sprintf(`apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: %s%s%s`, name, ns, scopeS)
}
tests := map[string]struct {
comps []string
namespace *string
expComps []compapi.Component
expErr bool
}{
"if no manifests, return nothing": {
comps: nil,
namespace: nil,
expComps: []compapi.Component{},
expErr: false,
},
"if single manifest, return manifest": {
comps: []string{buildComp("comp1", nil)},
namespace: nil,
expComps: []compapi.Component{
{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "comp1"},
},
},
expErr: false,
},
"if namespace not set, return all manifests": {
comps: []string{
buildComp("comp1", nil),
buildComp("comp2", ptr.Of("default")),
buildComp("comp3", ptr.Of("foo")),
},
namespace: nil,
expComps: []compapi.Component{
{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "comp1"},
},
{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "comp2", Namespace: "default"},
},
{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "comp3", Namespace: "foo"},
},
},
},
"if namespace set, return only manifests in that namespace": {
comps: []string{
buildComp("comp1", nil),
buildComp("comp2", ptr.Of("default")),
buildComp("comp3", ptr.Of("foo")),
buildComp("comp4", ptr.Of("foo")),
buildComp("comp5", ptr.Of("bar")),
},
namespace: ptr.Of("foo"),
expComps: []compapi.Component{
{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: ""},
},
{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "comp3", Namespace: "foo"},
},
{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "comp4", Namespace: "foo"},
},
},
},
"if duplicate manifest, return error": {
comps: []string{
buildComp("comp1", nil),
buildComp("comp1", nil),
},
namespace: nil,
expComps: nil,
expErr: true,
},
"ignore duplicate manifest if namespace doesn't match": {
comps: []string{
buildComp("comp1", ptr.Of("foo")),
buildComp("comp1", ptr.Of("bar")),
},
namespace: ptr.Of("foo"),
expComps: []compapi.Component{
{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: "foo"},
},
},
expErr: false,
},
"only return manifests in scope": {
comps: []string{
buildComp("comp1", nil, "myappid"),
buildComp("comp2", nil, "myappid", "anotherappid"),
buildComp("comp3", nil, "anotherappid"),
},
namespace: ptr.Of("foo"),
expComps: []compapi.Component{
{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: ""},
Scoped: common.Scoped{Scopes: []string{"myappid"}},
},
{
TypeMeta: metav1.TypeMeta{APIVersion: "dapr.io/v1alpha1", Kind: "Component"},
ObjectMeta: metav1.ObjectMeta{Name: "comp2", Namespace: ""},
Scoped: common.Scoped{Scopes: []string{"myappid", "anotherappid"}},
},
},
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
tmp := t.TempDir()
b := strings.Join(test.comps, "\n---\n")
require.NoError(t, os.WriteFile(filepath.Join(tmp, "components.yaml"), []byte(b), fs.FileMode(0o600)))
t.Setenv("NAMESPACE", "")
if test.namespace != nil {
t.Setenv("NAMESPACE", *test.namespace)
}
loader := NewComponents(Options{
Paths: []string{tmp},
AppID: "myappid",
})
components, err := loader.Load(context.Background())
assert.Equal(t, test.expErr, err != nil, "%v", err)
assert.Equal(t, test.expComps, components)
})
}
})
}
func Test_loadWithOrder(t *testing.T) {
t.Run("no file should return empty set", func(t *testing.T) {
tmp := t.TempDir()
d := NewComponents(Options{Paths: []string{tmp}}).(*disk[compapi.Component])
set, err := d.loadWithOrder()
require.NoError(t, err)
assert.Empty(t, set.order)
assert.Empty(t, set.ts)
})
t.Run("single manifest file should return", func(t *testing.T) {
tmp := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(tmp, "test-component.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: statestore
spec:
type: state.couchbase
`), fs.FileMode(0o600)))
d := NewComponents(Options{Paths: []string{tmp}}).(*disk[compapi.Component])
set, err := d.loadWithOrder()
require.NoError(t, err)
assert.Equal(t, []manifestOrder{
{dirIndex: 0, fileIndex: 0, manifestIndex: 0},
}, set.order)
assert.Len(t, set.ts, 1)
})
t.Run("3 manifest file should have order set", func(t *testing.T) {
tmp := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(tmp, "test-component.yaml"), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: foo1
spec:
type: state.couchbase
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: foo2
spec:
type: state.couchbase
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: foo3
spec:
type: state.couchbase
`), fs.FileMode(0o600)))
d := NewComponents(Options{Paths: []string{tmp}}).(*disk[compapi.Component])
set, err := d.loadWithOrder()
require.NoError(t, err)
assert.Equal(t, []manifestOrder{
{dirIndex: 0, fileIndex: 0, manifestIndex: 0},
{dirIndex: 0, fileIndex: 0, manifestIndex: 1},
{dirIndex: 0, fileIndex: 0, manifestIndex: 2},
}, set.order)
assert.Len(t, set.ts, 3)
})
t.Run("3 dirs, 3 files, 3 manifests should return order. Skips manifests of different type", func(t *testing.T) {
tmp1, tmp2, tmp3 := t.TempDir(), t.TempDir(), t.TempDir()
for _, dir := range []string{tmp1, tmp2, tmp3} {
for _, file := range []string{"1.yaml", "2.yaml", "3.yaml"} {
require.NoError(t, os.WriteFile(filepath.Join(dir, file), []byte(`
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: foo1
spec:
type: state.couchbase
---
apiVersion: dapr.io/v1alpha1
kind: Subscription
metadata:
name: foo2
spec:
type: state.couchbase
---
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: foo3
spec:
type: state.couchbase
`), fs.FileMode(0o600)))
}
}
d := NewComponents(Options{
Paths: []string{tmp1, tmp2, tmp3},
}).(*disk[compapi.Component])
set, err := d.loadWithOrder()
require.NoError(t, err)
assert.Equal(t, []manifestOrder{
{dirIndex: 0, fileIndex: 0, manifestIndex: 0},
{dirIndex: 0, fileIndex: 0, manifestIndex: 2},
{dirIndex: 0, fileIndex: 1, manifestIndex: 0},
{dirIndex: 0, fileIndex: 1, manifestIndex: 2},
{dirIndex: 0, fileIndex: 2, manifestIndex: 0},
{dirIndex: 0, fileIndex: 2, manifestIndex: 2},
{dirIndex: 1, fileIndex: 0, manifestIndex: 0},
{dirIndex: 1, fileIndex: 0, manifestIndex: 2},
{dirIndex: 1, fileIndex: 1, manifestIndex: 0},
{dirIndex: 1, fileIndex: 1, manifestIndex: 2},
{dirIndex: 1, fileIndex: 2, manifestIndex: 0},
{dirIndex: 1, fileIndex: 2, manifestIndex: 2},
{dirIndex: 2, fileIndex: 0, manifestIndex: 0},
{dirIndex: 2, fileIndex: 0, manifestIndex: 2},
{dirIndex: 2, fileIndex: 1, manifestIndex: 0},
{dirIndex: 2, fileIndex: 1, manifestIndex: 2},
{dirIndex: 2, fileIndex: 2, manifestIndex: 0},
{dirIndex: 2, fileIndex: 2, manifestIndex: 2},
}, set.order)
assert.Len(t, set.ts, 18)
})
}
|
mikeee/dapr
|
pkg/internal/loader/disk/disk_test.go
|
GO
|
mit
| 10,668 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package disk
import (
endpointapi "github.com/dapr/dapr/pkg/apis/httpEndpoint/v1alpha1"
"github.com/dapr/dapr/pkg/internal/loader"
)
func NewHTTPEndpoints(opts Options) loader.Loader[endpointapi.HTTPEndpoint] {
return new[endpointapi.HTTPEndpoint](opts)
}
|
mikeee/dapr
|
pkg/internal/loader/disk/httpendpoints.go
|
GO
|
mit
| 822 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package disk
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"k8s.io/apimachinery/pkg/api/validation/path"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/yaml"
"github.com/dapr/dapr/pkg/runtime/meta"
"github.com/dapr/kit/logger"
"github.com/dapr/kit/utils"
)
const yamlSeparator = "\n---"
var log = logger.NewLogger("dapr.runtime.loader.disk")
type manifestSet[T meta.Resource] struct {
d *disk[T]
dirIndex int
fileIndex int
manifestIndex int
order []manifestOrder
ts []T
}
type manifestOrder struct {
dirIndex int
fileIndex int
manifestIndex int
}
func (m *manifestSet[T]) loadManifestsFromDirectory(dir string) error {
defer func() {
m.dirIndex++
}()
files, err := os.ReadDir(dir)
if err != nil {
return err
}
m.fileIndex = 0
for _, file := range files {
if file.IsDir() {
continue
}
fileName := file.Name()
if !utils.IsYaml(fileName) {
log.Warnf("A non-YAML %s file %s was detected, it will not be loaded", m.d.kind, fileName)
continue
}
m.loadManifestsFromFile(filepath.Join(dir, fileName))
}
return nil
}
func (m *manifestSet[T]) loadManifestsFromFile(path string) {
defer func() {
m.fileIndex++
}()
f, err := os.Open(path)
if err != nil {
log.Warnf("daprd load %s error when opening file %s: %v", m.d.kind, path, err)
return
}
defer f.Close()
if err := m.decodeYaml(f); err != nil {
log.Warnf("daprd load %s error when parsing manifests yaml resource in %s: %v", m.d.kind, path, err)
}
}
func (m *manifestSet[T]) decodeYaml(f io.Reader) error {
var errs []error
scanner := bufio.NewScanner(f)
scanner.Split(splitYamlDoc)
m.manifestIndex = 0
for {
m.manifestIndex++
if !scanner.Scan() {
err := scanner.Err()
if err != nil {
errs = append(errs, err)
continue
}
break
}
scannerBytes := scanner.Bytes()
var ti struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
}
if err := yaml.Unmarshal(scannerBytes, &ti); err != nil {
errs = append(errs, err)
continue
}
if ti.APIVersion != m.d.apiVersion || ti.Kind != m.d.kind {
continue
}
if patherrs := path.IsValidPathSegmentName(ti.Name); len(patherrs) > 0 {
errs = append(errs, fmt.Errorf("invalid name %q for %q: %s", ti.Name, m.d.kind, strings.Join(patherrs, "; ")))
continue
}
var manifest T
if err := yaml.Unmarshal(scannerBytes, &manifest); err != nil {
errs = append(errs, err)
continue
}
m.order = append(m.order, manifestOrder{
dirIndex: m.dirIndex,
fileIndex: m.fileIndex,
manifestIndex: m.manifestIndex - 1,
})
m.ts = append(m.ts, manifest)
}
if len(errs) > 0 {
return errors.Join(errs...)
}
return nil
}
// splitYamlDoc - splits the yaml docs.
func splitYamlDoc(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
sep := len([]byte(yamlSeparator))
if i := bytes.Index(data, []byte(yamlSeparator)); i >= 0 {
i += sep
after := data[i:]
if len(after) == 0 {
if atEOF {
return len(data), data[:len(data)-sep], nil
}
return 0, nil, nil
}
if j := bytes.IndexByte(after, '\n'); j >= 0 {
return i + j + 1, data[0 : i-sep], nil
}
return 0, nil, nil
}
// If we're at EOF, we have a final, non-terminated line. Return it.
if atEOF {
return len(data), data, nil
}
// Request more data.
return 0, nil, nil
}
func (m *manifestSet[T]) Len() int {
return len(m.order)
}
func (m *manifestSet[T]) Swap(i, j int) {
m.order[i], m.order[j] = m.order[j], m.order[i]
m.ts[i], m.ts[j] = m.ts[j], m.ts[i]
}
func (m *manifestSet[T]) Less(i, j int) bool {
return m.order[i].dirIndex < m.order[j].dirIndex ||
m.order[i].fileIndex < m.order[j].fileIndex ||
m.order[i].manifestIndex < m.order[j].manifestIndex
}
|
mikeee/dapr
|
pkg/internal/loader/disk/manifest.go
|
GO
|
mit
| 4,434 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package disk
import (
"context"
"sort"
"github.com/dapr/dapr/pkg/apis/subscriptions/v1alpha1"
"github.com/dapr/dapr/pkg/apis/subscriptions/v2alpha1"
"github.com/dapr/dapr/pkg/internal/loader"
)
type subscriptions struct {
v1 *disk[v1alpha1.Subscription]
v2 *disk[v2alpha1.Subscription]
}
func NewSubscriptions(opts Options) loader.Loader[v2alpha1.Subscription] {
return &subscriptions{
v1: new[v1alpha1.Subscription](opts),
v2: new[v2alpha1.Subscription](opts),
}
}
func (s *subscriptions) Load(context.Context) ([]v2alpha1.Subscription, error) {
v1, err := s.v1.loadWithOrder()
if err != nil {
return nil, err
}
v2, err := s.v2.loadWithOrder()
if err != nil {
return nil, err
}
v2.order = append(v2.order, v1.order...)
for _, s := range v1.ts {
var subv2 v2alpha1.Subscription
if err := subv2.ConvertFrom(s.DeepCopy()); err != nil {
return nil, err
}
v2.ts = append(v2.ts, subv2)
}
// Preserve manifest load order between v1 and v2.
sort.Sort(v2)
return v2.ts, nil
}
|
mikeee/dapr
|
pkg/internal/loader/disk/subscriptions.go
|
GO
|
mit
| 1,580 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubernetes
import (
"context"
"encoding/json"
"fmt"
grpcretry "github.com/grpc-ecosystem/go-grpc-middleware/retry"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
config "github.com/dapr/dapr/pkg/config/modes"
"github.com/dapr/dapr/pkg/internal/loader"
operatorv1pb "github.com/dapr/dapr/pkg/proto/operator/v1"
)
// components loads components from a Kubernetes environment.
type components struct {
config config.KubernetesConfig
client operatorv1pb.OperatorClient
namespace string
podName string
}
// NewComponents returns a new Kubernetes loader.
func NewComponents(opts Options) loader.Loader[compapi.Component] {
return &components{
config: opts.Config,
client: opts.Client,
namespace: opts.Namespace,
podName: opts.PodName,
}
}
// Load loads dapr components from a given directory.
func (c *components) Load(ctx context.Context) ([]compapi.Component, error) {
resp, err := c.client.ListComponents(ctx, &operatorv1pb.ListComponentsRequest{
Namespace: c.namespace,
PodName: c.podName,
}, grpcretry.WithMax(operatorMaxRetries), grpcretry.WithPerRetryTimeout(operatorCallTimeout))
if err != nil {
return nil, err
}
comps := resp.GetComponents()
components := make([]compapi.Component, len(comps))
for i, c := range comps {
var component compapi.Component
if err := json.Unmarshal(c, &component); err != nil {
return nil, fmt.Errorf("error deserializing component: %s", err)
}
components[i] = component
}
return components, nil
}
|
mikeee/dapr
|
pkg/internal/loader/kubernetes/components.go
|
GO
|
mit
| 2,086 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubernetes
import (
"context"
"encoding/json"
"fmt"
"net"
"testing"
"github.com/phayes/freeport"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/dapr/dapr/pkg/apis/components/v1alpha1"
subapi "github.com/dapr/dapr/pkg/apis/subscriptions/v2alpha1"
config "github.com/dapr/dapr/pkg/config/modes"
operatorv1pb "github.com/dapr/dapr/pkg/proto/operator/v1"
)
type mockOperator struct {
operatorv1pb.UnimplementedOperatorServer
}
func (o *mockOperator) GetConfiguration(ctx context.Context, in *operatorv1pb.GetConfigurationRequest) (*operatorv1pb.GetConfigurationResponse, error) {
return nil, nil
}
func (o *mockOperator) ListComponents(ctx context.Context, in *operatorv1pb.ListComponentsRequest) (*operatorv1pb.ListComponentResponse, error) {
component := v1alpha1.Component{}
component.ObjectMeta.Name = "test"
component.ObjectMeta.Labels = map[string]string{
"podName": in.GetPodName(),
}
component.Spec = v1alpha1.ComponentSpec{
Type: "testtype",
}
b, _ := json.Marshal(&component)
return &operatorv1pb.ListComponentResponse{
Components: [][]byte{b},
}, nil
}
func (o *mockOperator) ListSubscriptionsV2(ctx context.Context, in *operatorv1pb.ListSubscriptionsRequest) (*operatorv1pb.ListSubscriptionsResponse, error) {
subscription := subapi.Subscription{}
subscription.ObjectMeta.Name = "test"
subscription.Spec = subapi.SubscriptionSpec{
Topic: "topic",
Routes: subapi.Routes{Default: "route"},
Pubsubname: "pubsub",
}
b, _ := json.Marshal(&subscription)
return &operatorv1pb.ListSubscriptionsResponse{
Subscriptions: [][]byte{b},
}, nil
}
func (o *mockOperator) ComponentUpdate(in *operatorv1pb.ComponentUpdateRequest, srv operatorv1pb.Operator_ComponentUpdateServer) error { //nolint:nosnakecase
return nil
}
func getOperatorClient(address string) operatorv1pb.OperatorClient {
conn, _ := grpc.Dial(address, grpc.WithTransportCredentials(insecure.NewCredentials()))
return operatorv1pb.NewOperatorClient(conn)
}
func TestLoadComponents(t *testing.T) {
port, _ := freeport.GetFreePort()
lis, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
require.NoError(t, err)
s := grpc.NewServer()
operatorv1pb.RegisterOperatorServer(s, &mockOperator{})
errCh := make(chan error)
t.Cleanup(func() {
s.Stop()
require.NoError(t, <-errCh)
})
go func() {
errCh <- s.Serve(lis)
}()
request := &components{
client: getOperatorClient(fmt.Sprintf("localhost:%d", port)),
config: config.KubernetesConfig{
ControlPlaneAddress: fmt.Sprintf("localhost:%v", port),
},
podName: "testPodName",
}
response, err := request.Load(context.Background())
require.NoError(t, err)
assert.NotNil(t, response)
assert.Equal(t, "test", response[0].Name)
assert.Equal(t, "testtype", response[0].Spec.Type)
assert.Equal(t, "testPodName", response[0].ObjectMeta.Labels["podName"])
}
|
mikeee/dapr
|
pkg/internal/loader/kubernetes/components_test.go
|
GO
|
mit
| 3,544 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubernetes
import (
"context"
"encoding/json"
"fmt"
grpcretry "github.com/grpc-ecosystem/go-grpc-middleware/retry"
endpointapi "github.com/dapr/dapr/pkg/apis/httpEndpoint/v1alpha1"
config "github.com/dapr/dapr/pkg/config/modes"
"github.com/dapr/dapr/pkg/internal/loader"
operatorv1pb "github.com/dapr/dapr/pkg/proto/operator/v1"
)
type httpendpoints struct {
config config.KubernetesConfig
client operatorv1pb.OperatorClient
namespace string
podName string
}
// NewHTTPEndpoints returns a new Kubernetes loader.
func NewHTTPEndpoints(opts Options) loader.Loader[endpointapi.HTTPEndpoint] {
return &httpendpoints{
config: opts.Config,
client: opts.Client,
namespace: opts.Namespace,
podName: opts.PodName,
}
}
// Load loads dapr components from a given directory.
func (h *httpendpoints) Load(ctx context.Context) ([]endpointapi.HTTPEndpoint, error) {
resp, err := h.client.ListHTTPEndpoints(ctx, &operatorv1pb.ListHTTPEndpointsRequest{
Namespace: h.namespace,
}, grpcretry.WithMax(operatorMaxRetries), grpcretry.WithPerRetryTimeout(operatorCallTimeout))
if err != nil {
log.Errorf("Error listing http endpoints: %v", err)
return nil, err
}
ends := resp.GetHttpEndpoints()
if ends == nil {
log.Debug("No http endpoints found")
return nil, nil
}
endpoints := make([]endpointapi.HTTPEndpoint, len(ends))
for i, e := range ends {
var endpoint endpointapi.HTTPEndpoint
if err := json.Unmarshal(e, &endpoint); err != nil {
return nil, fmt.Errorf("error deserializing http endpoint: %s", err)
}
endpoints[i] = endpoint
}
return endpoints, nil
}
|
mikeee/dapr
|
pkg/internal/loader/kubernetes/httpendpoints.go
|
GO
|
mit
| 2,187 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubernetes
import (
"time"
config "github.com/dapr/dapr/pkg/config/modes"
operatorv1pb "github.com/dapr/dapr/pkg/proto/operator/v1"
"github.com/dapr/kit/logger"
)
var log = logger.NewLogger("dapr.runtime.loader.kubernetes")
const (
operatorCallTimeout = time.Second * 5
operatorMaxRetries = 100
)
type Options struct {
Config config.KubernetesConfig
Client operatorv1pb.OperatorClient
Namespace string
PodName string
}
|
mikeee/dapr
|
pkg/internal/loader/kubernetes/kubernetes.go
|
GO
|
mit
| 1,012 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubernetes
import (
"context"
"encoding/json"
"fmt"
grpcretry "github.com/grpc-ecosystem/go-grpc-middleware/retry"
subapi "github.com/dapr/dapr/pkg/apis/subscriptions/v2alpha1"
"github.com/dapr/dapr/pkg/internal/loader"
operatorv1pb "github.com/dapr/dapr/pkg/proto/operator/v1"
)
// subscriptions loads subscriptions from a Kubernetes environment.
type subscriptions struct {
client operatorv1pb.OperatorClient
namespace string
podName string
}
// NewSubscriptions returns a new Kubernetes loader.
func NewSubscriptions(opts Options) loader.Loader[subapi.Subscription] {
return &subscriptions{
client: opts.Client,
namespace: opts.Namespace,
podName: opts.PodName,
}
}
func (s *subscriptions) Load(ctx context.Context) ([]subapi.Subscription, error) {
resp, err := s.client.ListSubscriptionsV2(ctx, &operatorv1pb.ListSubscriptionsRequest{
Namespace: s.namespace,
PodName: s.podName,
}, grpcretry.WithMax(operatorMaxRetries), grpcretry.WithPerRetryTimeout(operatorCallTimeout))
if err != nil {
return nil, err
}
subs := resp.GetSubscriptions()
subscriptions := make([]subapi.Subscription, len(subs))
for i, s := range subs {
var subscription subapi.Subscription
if err := json.Unmarshal(s, &subscription); err != nil {
return nil, fmt.Errorf("error deserializing subscription: %s", err)
}
subscriptions[i] = subscription
}
return subscriptions, nil
}
|
mikeee/dapr
|
pkg/internal/loader/kubernetes/subscriptions.go
|
GO
|
mit
| 1,984 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package loader
import (
"context"
"github.com/dapr/dapr/pkg/runtime/meta"
)
// Loader loads manifest-like files.
type Loader[T meta.Resource] interface {
// Load loads all manifests.
Load(context.Context) ([]T, error)
}
|
mikeee/dapr
|
pkg/internal/loader/loader.go
|
GO
|
mit
| 788 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package messages
import (
"encoding/json"
"errors"
"fmt"
"net/http"
grpcCodes "google.golang.org/grpc/codes"
grpcStatus "google.golang.org/grpc/status"
)
const (
defaultMessage = "unknown error"
defaultTag = "ERROR"
errStringFormat = "api error: code = %s desc = %s"
)
// APIError implements the Error interface and the interface that complies with "google.golang.org/grpc/status".FromError().
// It can be used to send errors to HTTP and gRPC servers, indicating the correct status code for each.
type APIError struct {
// Message is the human-readable error message.
message string
// Tag is a string identifying the error, used with HTTP responses only.
tag string
// Status code for HTTP responses.
httpCode int
// Status code for gRPC responses.
grpcCode grpcCodes.Code
}
// WithFormat returns a copy of the error with the message going through fmt.Sprintf with the arguments passed to this method.
func (e APIError) WithFormat(a ...any) APIError {
return APIError{
message: fmt.Sprintf(e.message, a...),
tag: e.tag,
httpCode: e.httpCode,
grpcCode: e.grpcCode,
}
}
// Message returns the value of the message property.
func (e APIError) Message() string {
if e.message == "" {
return defaultMessage
}
return e.message
}
// Tag returns the value of the tag property.
func (e APIError) Tag() string {
if e.tag == "" {
return defaultTag
}
return e.tag
}
// HTTPCode returns the value of the HTTPCode property.
func (e APIError) HTTPCode() int {
if e.httpCode == 0 {
return http.StatusInternalServerError
}
return e.httpCode
}
// GRPCStatus returns the gRPC status.Status object.
// This method allows APIError to comply with the interface expected by status.FromError().
func (e APIError) GRPCStatus() *grpcStatus.Status {
return grpcStatus.New(e.grpcCode, e.Message())
}
// Error implements the error interface.
func (e APIError) Error() string {
return e.String()
}
// JSONErrorValue implements the errorResponseValue interface.
func (e APIError) JSONErrorValue() []byte {
b, _ := json.Marshal(struct {
ErrorCode string `json:"errorCode"`
Message string `json:"message"`
}{
ErrorCode: e.Tag(),
Message: e.Message(),
})
return b
}
// Is implements the interface that checks if the error matches the given one.
func (e APIError) Is(targetI error) bool {
// Ignore the message in the comparison because the target could have been formatted
var target APIError
if !errors.As(targetI, &target) {
return false
}
return e.tag == target.tag &&
e.grpcCode == target.grpcCode &&
e.httpCode == target.httpCode
}
// String returns the string representation, useful for debugging.
func (e APIError) String() string {
return fmt.Sprintf(errStringFormat, e.grpcCode, e.Message())
}
|
mikeee/dapr
|
pkg/messages/api_error.go
|
GO
|
mit
| 3,330 |
/*
Copyright 2022 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package messages
import (
"fmt"
"net/http"
"reflect"
"testing"
grpcCodes "google.golang.org/grpc/codes"
grpcStatus "google.golang.org/grpc/status"
)
func TestAPIError_WithFormat(t *testing.T) {
type fields struct {
message string
tag string
httpCode int
grpcCode grpcCodes.Code
}
type args struct {
a []any
}
tests := []struct {
name string
fields fields
args args
want APIError
}{
{
name: "no formatting",
fields: fields{message: "ciao", tag: "MYERR", httpCode: http.StatusTeapot, grpcCode: grpcCodes.ResourceExhausted},
args: args{a: []any{}},
want: APIError{message: "ciao", tag: "MYERR", httpCode: http.StatusTeapot, grpcCode: grpcCodes.ResourceExhausted},
},
{
name: "string parameter",
fields: fields{message: "ciao %s", tag: "MYERR", httpCode: http.StatusTeapot, grpcCode: grpcCodes.ResourceExhausted},
args: args{a: []any{"mondo"}},
want: APIError{message: "ciao mondo", tag: "MYERR", httpCode: http.StatusTeapot, grpcCode: grpcCodes.ResourceExhausted},
},
{
name: "multiple params",
fields: fields{message: "ciao %s %d", tag: "MYERR", httpCode: http.StatusTeapot, grpcCode: grpcCodes.ResourceExhausted},
args: args{a: []any{"mondo", 42}},
want: APIError{message: "ciao mondo 42", tag: "MYERR", httpCode: http.StatusTeapot, grpcCode: grpcCodes.ResourceExhausted},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
e := APIError{
message: tt.fields.message,
tag: tt.fields.tag,
httpCode: tt.fields.httpCode,
grpcCode: tt.fields.grpcCode,
}
if got := e.WithFormat(tt.args.a...); !reflect.DeepEqual(got, tt.want) {
t.Errorf("APIError.WithFormat() = %v, want %v", got, tt.want)
}
})
}
}
func TestAPIError_Message(t *testing.T) {
type fields struct {
message string
}
tests := []struct {
name string
fields fields
want string
}{
{
name: "has message",
fields: fields{message: "Cantami, o Diva, del Pelide Achille"},
want: "Cantami, o Diva, del Pelide Achille",
},
{
name: "no message",
fields: fields{message: ""},
want: defaultMessage,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
e := APIError{
message: tt.fields.message,
}
if got := e.Message(); got != tt.want {
t.Errorf("APIError.Message() = %v, want %v", got, tt.want)
}
})
}
}
func TestAPIError_Tag(t *testing.T) {
type fields struct {
tag string
}
tests := []struct {
name string
fields fields
want string
}{
{
name: "has tag",
fields: fields{tag: "SOME_ERROR"},
want: "SOME_ERROR",
},
{
name: "no tag",
fields: fields{tag: ""},
want: defaultTag,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
e := APIError{
tag: tt.fields.tag,
}
if got := e.Tag(); got != tt.want {
t.Errorf("APIError.Tag() = %v, want %v", got, tt.want)
}
})
}
}
func TestAPIError_HTTPCode(t *testing.T) {
type fields struct {
httpCode int
}
tests := []struct {
name string
fields fields
want int
}{
{
name: "has httpCode",
fields: fields{httpCode: http.StatusTeapot},
want: http.StatusTeapot,
},
{
name: "no httpCode",
fields: fields{httpCode: 0},
want: http.StatusInternalServerError,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
e := APIError{
httpCode: tt.fields.httpCode,
}
if got := e.HTTPCode(); got != tt.want {
t.Errorf("APIError.HTTPCode() = %v, want %v", got, tt.want)
}
})
}
}
func TestAPIError_GRPCStatus(t *testing.T) {
type fields struct {
message string
grpcCode grpcCodes.Code
}
tests := []struct {
name string
fields fields
want *grpcStatus.Status
}{
{
name: "has grpcCode and message",
fields: fields{
message: "Oy vey",
grpcCode: grpcCodes.ResourceExhausted,
},
want: grpcStatus.New(grpcCodes.ResourceExhausted, "Oy vey"),
},
{
name: "has only message",
fields: fields{
message: "Oy vey",
},
// The default code is 0, i.e. OK
want: grpcStatus.New(grpcCodes.OK, "Oy vey"),
},
{
name: "has only grpcCode",
fields: fields{
grpcCode: grpcCodes.Canceled,
},
want: grpcStatus.New(grpcCodes.Canceled, defaultMessage),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
e := APIError{
message: tt.fields.message,
grpcCode: tt.fields.grpcCode,
}
if got := e.GRPCStatus(); !reflect.DeepEqual(got, tt.want) {
t.Errorf("APIError.GRPCStatus() = %v, want %v", got, tt.want)
}
})
}
}
func TestAPIError_Error(t *testing.T) {
type fields struct {
message string
grpcCode grpcCodes.Code
}
tests := []struct {
name string
fields fields
want string
}{
{
name: "has grpcCode and message",
fields: fields{
message: "Oy vey",
grpcCode: grpcCodes.ResourceExhausted,
},
want: fmt.Sprintf(errStringFormat, grpcCodes.ResourceExhausted, "Oy vey"),
},
{
name: "has only message",
fields: fields{
message: "Oy vey",
},
// The default code is 0, i.e. OK
want: fmt.Sprintf(errStringFormat, grpcCodes.OK, "Oy vey"),
},
{
name: "has only grpcCode",
fields: fields{
grpcCode: grpcCodes.Canceled,
},
want: fmt.Sprintf(errStringFormat, grpcCodes.Canceled, defaultMessage),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
e := APIError{
message: tt.fields.message,
grpcCode: tt.fields.grpcCode,
}
if got := e.Error(); got != tt.want {
t.Errorf("APIError.Error() = %v, want %v", got, tt.want)
}
})
}
}
|
mikeee/dapr
|
pkg/messages/api_error_test.go
|
GO
|
mit
| 6,226 |
/*
Copyright 2022 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package messages
import (
"net/http"
grpcCodes "google.golang.org/grpc/codes"
)
const (
// Http.
ErrNotFound = "method %q is not found"
ErrMalformedRequestData = "can't serialize request data field: %s"
// State.
ErrStateGet = "fail to get %s from state store %s: %s"
ErrStateDelete = "failed deleting state with key %s: %s"
ErrStateSave = "failed saving state in state store %s: %s"
ErrStateDeleteBulk = "failed deleting state in state store %s: %s"
// StateTransaction.
ErrNotSupportedStateOperation = "operation type %s not supported"
ErrStateTransaction = "error while executing state transaction: %s"
// Binding.
ErrInvokeOutputBinding = "error invoking output binding %s: %s"
// PubSub.
ErrPubsubForbidden = "topic %s is not allowed for app id %s"
// AppChannel.
ErrChannelNotFound = "app channel is not initialized"
ErrInternalInvokeRequest = "parsing InternalInvokeRequest error: %s"
ErrChannelInvoke = "error invoking app channel: %s"
// AppHealth.
ErrAppUnhealthy = "app is not in a healthy state"
// Configuration.
ErrConfigurationStoresNotConfigured = "configuration stores not configured"
ErrConfigurationStoreNotFound = "configuration store %s not found"
ErrConfigurationGet = "failed to get %s from Configuration store %s: %v"
ErrConfigurationSubscribe = "failed to subscribe %s from Configuration store %s: %v"
ErrConfigurationUnsubscribe = "failed to unsubscribe to configuration request %s: %v"
)
var (
// Generic.
ErrBadRequest = APIError{"invalid request: %v", "ERR_BAD_REQUEST", http.StatusBadRequest, grpcCodes.InvalidArgument}
ErrAPIUnimplemented = APIError{"this API is currently not implemented", "ERR_API_UNIMPLEMENTED", http.StatusNotImplemented, grpcCodes.Unimplemented}
// HTTP.
ErrBodyRead = APIError{"failed to read request body: %v", "ERR_BODY_READ", http.StatusBadRequest, grpcCodes.InvalidArgument}
ErrMalformedRequest = APIError{"failed deserializing HTTP body: %v", "ERR_MALFORMED_REQUEST", http.StatusBadRequest, grpcCodes.InvalidArgument}
// DirectMessaging.
ErrDirectInvoke = APIError{"failed to invoke, id: %s, err: %v", "ERR_DIRECT_INVOKE", http.StatusInternalServerError, grpcCodes.Internal}
ErrDirectInvokeNoAppID = APIError{"failed getting app id either from the URL path or the header dapr-app-id", "ERR_DIRECT_INVOKE", http.StatusNotFound, grpcCodes.NotFound}
ErrDirectInvokeNotReady = APIError{"invoke API is not ready", "ERR_DIRECT_INVOKE", http.StatusInternalServerError, grpcCodes.Internal}
// Healthz.
ErrHealthNotReady = APIError{"dapr is not ready", "ERR_HEALTH_NOT_READY", http.StatusInternalServerError, grpcCodes.Internal}
ErrOutboundHealthNotReady = APIError{"dapr outbound is not ready", "ERR_OUTBOUND_HEALTH_NOT_READY", http.StatusInternalServerError, grpcCodes.Internal}
ErrHealthAppIDNotMatch = APIError{"dapr app-id does not match", "ERR_HEALTH_APPID_NOT_MATCH", http.StatusInternalServerError, grpcCodes.Internal}
// Secrets.
ErrSecretStoreNotConfigured = APIError{"secret store is not configured", "ERR_SECRET_STORES_NOT_CONFIGURED", http.StatusInternalServerError, grpcCodes.FailedPrecondition}
ErrSecretStoreNotFound = APIError{"failed finding secret store with key %s", "ERR_SECRET_STORE_NOT_FOUND", http.StatusUnauthorized, grpcCodes.InvalidArgument}
ErrSecretPermissionDenied = APIError{"access denied by policy to get %q from %q", "ERR_PERMISSION_DENIED", http.StatusForbidden, grpcCodes.PermissionDenied}
ErrSecretGet = APIError{"failed getting secret with key %s from secret store %s: %s", "ERR_SECRET_GET", http.StatusInternalServerError, grpcCodes.Internal}
ErrBulkSecretGet = APIError{"failed getting secrets from secret store %s: %v", "ERR_SECRET_GET", http.StatusInternalServerError, grpcCodes.Internal}
// Crypto.
ErrCryptoProvidersNotConfigured = APIError{"crypto providers not configured", "ERR_CRYPTO_PROVIDERS_NOT_CONFIGURED", http.StatusInternalServerError, grpcCodes.Internal}
ErrCryptoProviderNotFound = APIError{"crypto provider %s not found", "ERR_CRYPTO_PROVIDER_NOT_FOUND", http.StatusBadRequest, grpcCodes.InvalidArgument}
ErrCryptoGetKey = APIError{"failed to retrieve key %s: %v", "ERR_CRYPTO_KEY", http.StatusInternalServerError, grpcCodes.Internal}
ErrCryptoOperation = APIError{"failed to perform operation: %v", "ERR_CRYPTO", http.StatusInternalServerError, grpcCodes.Internal}
// Actor.
ErrActorReminderOpActorNotHosted = APIError{"operations on actor reminders are only possible on hosted actor types", "ERR_ACTOR_REMINDER_NON_HOSTED", http.StatusForbidden, grpcCodes.PermissionDenied}
ErrActorRuntimeNotFound = APIError{`the state store is not configured to use the actor runtime. Have you set the - name: actorStateStore value: "true" in your state store component file?`, "ERR_ACTOR_RUNTIME_NOT_FOUND", http.StatusInternalServerError, grpcCodes.Internal}
ErrActorInstanceMissing = APIError{"actor instance is missing", "ERR_ACTOR_INSTANCE_MISSING", http.StatusBadRequest, grpcCodes.Internal}
ErrActorInvoke = APIError{"error invoke actor method: %s", "ERR_ACTOR_INVOKE_METHOD", http.StatusInternalServerError, grpcCodes.Internal}
ErrActorStateGet = APIError{"error getting actor state: %s", "ERR_ACTOR_STATE_GET", http.StatusInternalServerError, grpcCodes.Internal}
ErrActorStateTransactionSave = APIError{"error saving actor transaction state: %s", "ERR_ACTOR_STATE_TRANSACTION_SAVE", http.StatusInternalServerError, grpcCodes.Internal}
ErrActorReminderCreate = APIError{"error creating actor reminder: %s", "ERR_ACTOR_REMINDER_CREATE", http.StatusInternalServerError, grpcCodes.Internal}
ErrActorReminderGet = APIError{"error getting actor reminder: %s", "ERR_ACTOR_REMINDER_GET", http.StatusInternalServerError, grpcCodes.Internal}
ErrActorReminderDelete = APIError{"error deleting actor reminder: %s", "ERR_ACTOR_REMINDER_DELETE", http.StatusInternalServerError, grpcCodes.Internal}
ErrActorTimerCreate = APIError{"error creating actor timer: %s", "ERR_ACTOR_TIMER_CREATE", http.StatusInternalServerError, grpcCodes.Internal}
ErrActorTimerDelete = APIError{"error deleting actor timer: %s", "ERR_ACTOR_TIMER_DELETE", http.StatusInternalServerError, grpcCodes.Internal}
// Lock.
ErrLockStoresNotConfigured = APIError{"lock store is not configured", "ERR_LOCK_STORE_NOT_CONFIGURED", http.StatusInternalServerError, grpcCodes.FailedPrecondition}
ErrResourceIDEmpty = APIError{"ResourceId is empty in lock store %s", "ERR_MALFORMED_REQUEST", http.StatusBadRequest, grpcCodes.InvalidArgument}
ErrLockOwnerEmpty = APIError{"LockOwner is empty in lock store %s", "ERR_MALFORMED_REQUEST", http.StatusBadRequest, grpcCodes.InvalidArgument}
ErrExpiryInSecondsNotPositive = APIError{"ExpiryInSeconds is not positive in lock store %s", "ERR_MALFORMED_REQUEST", http.StatusBadRequest, grpcCodes.InvalidArgument}
ErrLockStoreNotFound = APIError{"lock store %s not found", "ERR_LOCK_STORE_NOT_FOUND", http.StatusBadRequest, grpcCodes.InvalidArgument}
ErrTryLockFailed = APIError{"failed to try acquiring lock: %s", "ERR_TRY_LOCK", http.StatusInternalServerError, grpcCodes.Internal}
ErrUnlockFailed = APIError{"failed to release lock: %s", "ERR_UNLOCK", http.StatusInternalServerError, grpcCodes.Internal}
// Workflow.
ErrStartWorkflow = APIError{"error starting workflow '%s': %s", "ERR_START_WORKFLOW", http.StatusInternalServerError, grpcCodes.Internal}
ErrWorkflowGetResponse = APIError{"error while getting workflow info on instance '%s': %s", "ERR_GET_WORKFLOW", http.StatusInternalServerError, grpcCodes.Internal}
ErrWorkflowNameMissing = APIError{"workflow name is not configured", "ERR_WORKFLOW_NAME_MISSING", http.StatusBadRequest, grpcCodes.InvalidArgument}
ErrInstanceIDTooLong = APIError{"workflow instance ID exceeds the max length of %d characters", "ERR_INSTANCE_ID_TOO_LONG", http.StatusBadRequest, grpcCodes.InvalidArgument}
ErrInvalidInstanceID = APIError{"workflow instance ID '%s' is invalid: only alphanumeric and underscore characters are allowed", "ERR_INSTANCE_ID_INVALID", http.StatusBadRequest, grpcCodes.InvalidArgument}
ErrWorkflowComponentDoesNotExist = APIError{"workflow component '%s' does not exist", "ERR_WORKFLOW_COMPONENT_NOT_FOUND", http.StatusBadRequest, grpcCodes.InvalidArgument}
ErrMissingOrEmptyInstance = APIError{"no instance ID was provided", "ERR_INSTANCE_ID_PROVIDED_MISSING", http.StatusBadRequest, grpcCodes.InvalidArgument}
ErrWorkflowInstanceNotFound = APIError{"unable to find workflow with the provided instance ID: %s", "ERR_INSTANCE_ID_NOT_FOUND", http.StatusNotFound, grpcCodes.NotFound}
ErrNoOrMissingWorkflowComponent = APIError{"no workflow component was provided", "ERR_WORKFLOW_COMPONENT_MISSING", http.StatusBadRequest, grpcCodes.InvalidArgument}
ErrTerminateWorkflow = APIError{"error terminating workflow '%s': %s", "ERR_TERMINATE_WORKFLOW", http.StatusInternalServerError, grpcCodes.Internal}
ErrMissingWorkflowEventName = APIError{"missing workflow event name", "ERR_WORKFLOW_EVENT_NAME_MISSING", http.StatusBadRequest, grpcCodes.InvalidArgument}
ErrRaiseEventWorkflow = APIError{"error raising event on workflow '%s': %s", "ERR_RAISE_EVENT_WORKFLOW", http.StatusInternalServerError, grpcCodes.Internal}
ErrPauseWorkflow = APIError{"error pausing workflow %s: %s", "ERR_PAUSE_WORKFLOW", http.StatusInternalServerError, grpcCodes.Internal}
ErrResumeWorkflow = APIError{"error resuming workflow %s: %s", "ERR_RESUME_WORKFLOW", http.StatusInternalServerError, grpcCodes.Internal}
ErrPurgeWorkflow = APIError{"error purging workflow %s: %s", "ERR_PURGE_WORKFLOW", http.StatusInternalServerError, grpcCodes.Internal}
)
|
mikeee/dapr
|
pkg/messages/predefined.go
|
GO
|
mit
| 10,661 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package messaging
import (
"context"
"errors"
"fmt"
"io"
"os"
"strings"
"sync/atomic"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/valyala/fasthttp"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
nr "github.com/dapr/components-contrib/nameresolution"
"github.com/dapr/dapr/pkg/channel"
diag "github.com/dapr/dapr/pkg/diagnostics"
diagUtils "github.com/dapr/dapr/pkg/diagnostics/utils"
invokev1 "github.com/dapr/dapr/pkg/messaging/v1"
"github.com/dapr/dapr/pkg/modes"
commonv1pb "github.com/dapr/dapr/pkg/proto/common/v1"
internalv1pb "github.com/dapr/dapr/pkg/proto/internals/v1"
"github.com/dapr/dapr/pkg/resiliency"
"github.com/dapr/dapr/pkg/retry"
"github.com/dapr/dapr/pkg/runtime/channels"
"github.com/dapr/dapr/pkg/runtime/compstore"
"github.com/dapr/dapr/utils"
"github.com/dapr/kit/logger"
"github.com/dapr/kit/ttlcache"
)
var log = logger.NewLogger("dapr.runtime.direct_messaging")
const streamingUnsupportedErr = "target app '%s' is running a version of Dapr that does not support streaming-based service invocation"
// Maximum TTL in seconds for the nameresolution cache
const resolverCacheTTL = 20
// messageClientConnection is the function type to connect to the other
// applications to send the message using service invocation.
type messageClientConnection func(ctx context.Context, address string, id string, namespace string, customOpts ...grpc.DialOption) (*grpc.ClientConn, func(destroy bool), error)
type directMessaging struct {
channels *channels.Channels
connectionCreatorFn messageClientConnection
appID string
mode modes.DaprMode
grpcPort int
namespace string
resolver nr.Resolver
resolverMulti nr.ResolverMulti
hostAddress string
hostName string
maxRequestBodySize int
proxy Proxy
readBufferSize int
resiliency resiliency.Provider
compStore *compstore.ComponentStore
resolverCache *ttlcache.Cache[nr.AddressList]
closed atomic.Bool
}
type remoteApp struct {
id string
namespace string
address string
cacheKey string
}
// NewDirectMessaging contains the options for NewDirectMessaging.
type NewDirectMessagingOpts struct {
AppID string
Namespace string
Port int
CompStore *compstore.ComponentStore
Mode modes.DaprMode
Channels *channels.Channels
ClientConnFn messageClientConnection
Resolver nr.Resolver
MultiResolver nr.ResolverMulti
MaxRequestBodySize int
Proxy Proxy
ReadBufferSize int
Resiliency resiliency.Provider
}
// NewDirectMessaging returns a new direct messaging api.
func NewDirectMessaging(opts NewDirectMessagingOpts) invokev1.DirectMessaging {
hAddr, _ := utils.GetHostAddress()
hName, _ := os.Hostname()
dm := &directMessaging{
appID: opts.AppID,
namespace: opts.Namespace,
grpcPort: opts.Port,
mode: opts.Mode,
channels: opts.Channels,
connectionCreatorFn: opts.ClientConnFn,
resolver: opts.Resolver,
maxRequestBodySize: opts.MaxRequestBodySize,
proxy: opts.Proxy,
readBufferSize: opts.ReadBufferSize,
resiliency: opts.Resiliency,
hostAddress: hAddr,
hostName: hName,
compStore: opts.CompStore,
}
// Set resolverMulti if the resolver implements the ResolverMulti interface
dm.resolverMulti, _ = opts.Resolver.(nr.ResolverMulti)
if dm.resolverMulti != nil {
dm.resolverCache = ttlcache.NewCache[nr.AddressList](ttlcache.CacheOptions{
MaxTTL: resolverCacheTTL,
})
}
if dm.proxy != nil {
dm.proxy.SetRemoteAppFn(dm.getRemoteApp)
dm.proxy.SetTelemetryFn(dm.setContextSpan)
}
return dm
}
func (d *directMessaging) Close() error {
if !d.closed.CompareAndSwap(false, true) {
return nil
}
if d.resolverCache != nil {
d.resolverCache.Stop()
}
return nil
}
// Invoke takes a message requests and invokes an app, either local or remote.
func (d *directMessaging) Invoke(ctx context.Context, targetAppID string, req *invokev1.InvokeMethodRequest) (*invokev1.InvokeMethodResponse, error) {
app, err := d.getRemoteApp(targetAppID)
if err != nil {
return nil, err
}
// invoke external calls first if appID matches an httpEndpoint.Name or app.id == baseURL that is overwritten
if d.isHTTPEndpoint(app.id) || strings.HasPrefix(app.id, "http://") || strings.HasPrefix(app.id, "https://") {
return d.invokeWithRetry(ctx, retry.DefaultLinearRetryCount, retry.DefaultLinearBackoffInterval, app, d.invokeHTTPEndpoint, req)
}
if app.id == d.appID && app.namespace == d.namespace {
return d.invokeLocal(ctx, req)
}
return d.invokeWithRetry(ctx, retry.DefaultLinearRetryCount, retry.DefaultLinearBackoffInterval, app, d.invokeRemote, req)
}
// requestAppIDAndNamespace takes an app id and returns the app id, namespace and error.
func (d *directMessaging) requestAppIDAndNamespace(targetAppID string) (string, string, error) {
if targetAppID == "" {
return "", "", errors.New("app id is empty")
}
// external invocation with targetAppID == baseURL
if strings.HasPrefix(targetAppID, "http://") || strings.HasPrefix(targetAppID, "https://") {
return targetAppID, "", nil
}
items := strings.Split(targetAppID, ".")
switch len(items) {
case 1:
return targetAppID, d.namespace, nil
case 2:
return items[0], items[1], nil
default:
return "", "", fmt.Errorf("invalid app id %s", targetAppID)
}
}
// checkHTTPEndpoints takes an app id and checks if the app id is associated with the http endpoint CRDs,
// and returns the baseURL if an http endpoint is found.
func (d *directMessaging) checkHTTPEndpoints(targetAppID string) string {
endpoint, ok := d.compStore.GetHTTPEndpoint(targetAppID)
if ok {
if endpoint.Name == targetAppID {
return endpoint.Spec.BaseURL
}
}
return ""
}
// invokeWithRetry will call a remote endpoint for the specified number of retries and will only retry in the case of transient failures.
// TODO: check why https://github.com/grpc-ecosystem/go-grpc-middleware/blob/master/retry/examples_test.go doesn't recover the connection when target server shuts down.
func (d *directMessaging) invokeWithRetry(
ctx context.Context,
numRetries int,
backoffInterval time.Duration,
app remoteApp,
fn func(ctx context.Context, appID, namespace, appAddress string, req *invokev1.InvokeMethodRequest) (*invokev1.InvokeMethodResponse, func(destroy bool), error),
req *invokev1.InvokeMethodRequest,
) (*invokev1.InvokeMethodResponse, error) {
if !d.resiliency.PolicyDefined(app.id, resiliency.EndpointPolicy{}) {
// This policy has built-in retries so enable replay in the request
req.WithReplay(true)
policyRunner := resiliency.NewRunnerWithOptions(ctx,
d.resiliency.BuiltInPolicy(resiliency.BuiltInServiceRetries),
resiliency.RunnerOpts[*invokev1.InvokeMethodResponse]{
Disposer: resiliency.DisposerCloser[*invokev1.InvokeMethodResponse],
},
)
return policyRunner(func(ctx context.Context) (*invokev1.InvokeMethodResponse, error) {
attempt := resiliency.GetAttempt(ctx)
rResp, teardown, rErr := fn(ctx, app.id, app.namespace, app.address, req)
if rErr == nil {
teardown(false)
return rResp, nil
}
code := status.Code(rErr)
if code == codes.Unavailable || code == codes.Unauthenticated {
// Destroy the connection and force a re-connection on the next attempt
// We also remove the resolved name from the cache
teardown(true)
if app.cacheKey != "" && d.resolverCache != nil {
d.resolverCache.Delete(app.cacheKey)
}
return rResp, fmt.Errorf("failed to invoke target %s after %d retries. Error: %w", app.id, attempt-1, rErr)
}
teardown(false)
return rResp, backoff.Permanent(rErr)
})
}
resp, teardown, err := fn(ctx, app.id, app.namespace, app.address, req)
teardown(false)
return resp, err
}
func (d *directMessaging) invokeLocal(ctx context.Context, req *invokev1.InvokeMethodRequest) (*invokev1.InvokeMethodResponse, error) {
appChannel := d.channels.AppChannel()
if appChannel == nil {
return nil, errors.New("cannot invoke local endpoint: app channel not initialized")
}
return appChannel.InvokeMethod(ctx, req, "")
}
func (d *directMessaging) setContextSpan(ctx context.Context) context.Context {
span := diagUtils.SpanFromContext(ctx)
ctx = diag.SpanContextToGRPCMetadata(ctx, span.SpanContext())
return ctx
}
func (d *directMessaging) isHTTPEndpoint(appID string) bool {
_, ok := d.compStore.GetHTTPEndpoint(appID)
return ok
}
func (d *directMessaging) invokeHTTPEndpoint(ctx context.Context, appID, appNamespace, appAddress string, req *invokev1.InvokeMethodRequest) (*invokev1.InvokeMethodResponse, func(destroy bool), error) {
ctx = d.setContextSpan(ctx)
// Set up timers
start := time.Now()
diag.DefaultMonitoring.ServiceInvocationRequestSent(appID)
imr, err := d.invokeRemoteUnaryForHTTPEndpoint(ctx, req, appID)
// Diagnostics
if imr != nil {
diag.DefaultMonitoring.ServiceInvocationResponseReceived(appID, imr.Status().GetCode(), start)
}
return imr, nopTeardown, err
}
func (d *directMessaging) invokeRemote(ctx context.Context, appID, appNamespace, appAddress string, req *invokev1.InvokeMethodRequest) (*invokev1.InvokeMethodResponse, func(destroy bool), error) {
conn, teardown, err := d.connectionCreatorFn(ctx, appAddress, appID, appNamespace)
if err != nil {
if teardown == nil {
teardown = nopTeardown
}
return nil, teardown, err
}
ctx = d.setContextSpan(ctx)
d.addForwardedHeadersToMetadata(req)
d.addDestinationAppIDHeaderToMetadata(appID, req)
d.addCallerAndCalleeAppIDHeaderToMetadata(d.appID, appID, req)
clientV1 := internalv1pb.NewServiceInvocationClient(conn)
opts := []grpc.CallOption{
grpc.MaxCallRecvMsgSize(d.maxRequestBodySize),
grpc.MaxCallSendMsgSize(d.maxRequestBodySize),
}
// Set up timers
start := time.Now()
diag.DefaultMonitoring.ServiceInvocationRequestSent(appID)
// Do invoke
imr, err := d.invokeRemoteStream(ctx, clientV1, req, appID, opts)
// Diagnostics
if imr != nil {
diag.DefaultMonitoring.ServiceInvocationResponseReceived(appID, imr.Status().GetCode(), start)
}
return imr, teardown, err
}
func (d *directMessaging) invokeRemoteUnaryForHTTPEndpoint(ctx context.Context, req *invokev1.InvokeMethodRequest, appID string) (*invokev1.InvokeMethodResponse, error) {
var channel channel.HTTPEndpointAppChannel
if ch, ok := d.channels.EndpointChannels()[appID]; ok {
channel = ch
} else {
channel = d.channels.HTTPEndpointsAppChannel()
}
if channel == nil {
return nil, fmt.Errorf("cannot invoke http endpoint %s: app channel not initialized", appID)
}
return channel.InvokeMethod(ctx, req, appID)
}
func (d *directMessaging) invokeRemoteUnary(ctx context.Context, clientV1 internalv1pb.ServiceInvocationClient, req *invokev1.InvokeMethodRequest, opts []grpc.CallOption) (*invokev1.InvokeMethodResponse, error) {
pd, err := req.ProtoWithData()
if err != nil {
return nil, fmt.Errorf("failed to read data from request object: %w", err)
}
resp, err := clientV1.CallLocal(ctx, pd, opts...)
if err != nil {
return nil, err
}
return invokev1.InternalInvokeResponse(resp)
}
func (d *directMessaging) invokeRemoteStream(ctx context.Context, clientV1 internalv1pb.ServiceInvocationClient, req *invokev1.InvokeMethodRequest, appID string, opts []grpc.CallOption) (*invokev1.InvokeMethodResponse, error) {
stream, err := clientV1.CallLocalStream(ctx, opts...)
if err != nil {
return nil, err
}
buf := invokev1.BufPool.Get().(*[]byte)
defer func() {
invokev1.BufPool.Put(buf)
}()
r := req.RawData()
reqProto := req.Proto()
// If there's a message in the proto, we remove it from the message we send to avoid sending it twice
// However we need to keep a reference to those bytes, and if needed add them back, to retry the request with resiliency
// We re-add it when the method ends to ensure we can perform retries
messageData := reqProto.GetMessage().GetData()
messageDataValue := messageData.GetValue()
if len(messageDataValue) > 0 {
messageData.Value = nil
defer func() {
if messageDataValue != nil {
messageData.Value = messageDataValue
}
}()
}
proto := &internalv1pb.InternalInvokeRequestStream{}
var (
n int
seq uint64
done bool
)
for {
if ctx.Err() != nil {
return nil, ctx.Err()
}
// First message only - add the request
if reqProto != nil {
proto.Request = reqProto
reqProto = nil
} else {
// Reset the object so we can re-use it
proto.Reset()
}
if r != nil {
n, err = r.Read(*buf)
if err == io.EOF {
done = true
} else if err != nil {
return nil, err
}
if n > 0 {
proto.Payload = &commonv1pb.StreamPayload{
Data: (*buf)[:n],
Seq: seq,
}
seq++
}
} else {
done = true
}
// Send the chunk if there's anything to send
if proto.GetRequest() != nil || proto.GetPayload() != nil {
err = stream.SendMsg(proto)
if errors.Is(err, io.EOF) {
// If SendMsg returns an io.EOF error, it usually means that there's a transport-level error
// The exact error can only be determined by RecvMsg, so if we encounter an EOF error here, just consider the stream done and let RecvMsg handle the error
done = true
} else if err != nil {
return nil, fmt.Errorf("error sending message: %w", err)
}
}
// Stop with the last chunk
if done {
err = stream.CloseSend()
if err != nil {
return nil, fmt.Errorf("failed to close the send direction of the stream: %w", err)
}
break
}
}
// Read the first chunk of the response
chunk := &internalv1pb.InternalInvokeResponseStream{}
err = stream.RecvMsg(chunk)
if err != nil {
// If we get an "Unimplemented" status code, it means that we're connecting to a sidecar that doesn't support CallLocalStream
// This happens if we're connecting to an older version of daprd
// What we do here depends on whether the request is replayable:
// - If the request is replayable, we will re-submit it as unary. This will have a small performance impact due to the additional round-trip, but it will still work (and the warning will remind users to upgrade)
// - If the request is not replayable, the data stream has already been consumed at this point so nothing else we can do - just show an error and tell users to upgrade the target app… (or disable streaming for now)
// At this point it seems that this is the best we can do, since we cannot detect Unimplemented status codes earlier (unless we send a "ping", which would add latency).
// See: https://github.com/grpc/grpc-go/issues/5910
if status.Code(err) == codes.Unimplemented {
// If we took out the data from the message, re-add it, so we can attempt to perform an unary invocation
if messageDataValue != nil {
messageData.Value = messageDataValue
messageDataValue = nil
}
if req.CanReplay() {
log.Warnf("App %s does not support streaming-based service invocation (most likely because it's using an older version of Dapr); falling back to unary calls", appID)
return d.invokeRemoteUnary(ctx, clientV1, req, opts)
} else {
log.Errorf("App %s does not support streaming-based service invocation (most likely because it's using an older version of Dapr) and the request is not replayable. Please upgrade the Dapr sidecar used by the target app, or use Resiliency policies to add retries", appID)
return nil, fmt.Errorf(streamingUnsupportedErr, appID)
}
}
return nil, err
}
if chunk.GetResponse().GetStatus() == nil {
return nil, errors.New("response does not contain the required fields in the leading chunk")
}
pr, pw := io.Pipe()
res, err := invokev1.InternalInvokeResponse(chunk.GetResponse())
if err != nil {
return nil, err
}
if chunk.GetResponse().GetMessage() != nil {
res.WithContentType(chunk.GetResponse().GetMessage().GetContentType())
res.WithDataTypeURL(chunk.GetResponse().GetMessage().GetData().GetTypeUrl()) // Could be empty
}
res.WithRawData(pr)
// Read the response into the stream in the background
go func() {
var (
expectSeq uint64
readSeq uint64
payload *commonv1pb.StreamPayload
readErr error
)
for {
// Get the payload from the chunk that was previously read
payload = chunk.GetPayload()
if payload != nil {
readSeq, readErr = ReadChunk(payload, pw)
if readErr != nil {
pw.CloseWithError(readErr)
return
}
// Check if the sequence number is greater than the previous
if readSeq != expectSeq {
pw.CloseWithError(fmt.Errorf("invalid sequence number received: %d (expected: %d)", readSeq, expectSeq))
return
}
expectSeq++
}
// Read the next chunk
readErr = stream.RecvMsg(chunk)
if errors.Is(readErr, io.EOF) {
// Receiving an io.EOF signifies that the client has stopped sending data over the pipe, so we can stop reading
break
} else if readErr != nil {
pw.CloseWithError(fmt.Errorf("error receiving message: %w", readErr))
return
}
if chunk.GetResponse().GetStatus() != nil || chunk.GetResponse().GetHeaders() != nil || chunk.GetResponse().GetMessage() != nil {
pw.CloseWithError(errors.New("response metadata found in non-leading chunk"))
return
}
}
pw.Close()
}()
return res, nil
}
func (d *directMessaging) addDestinationAppIDHeaderToMetadata(appID string, req *invokev1.InvokeMethodRequest) {
req.Metadata()[invokev1.DestinationIDHeader] = &internalv1pb.ListStringValue{
Values: []string{appID},
}
}
func (d *directMessaging) addCallerAndCalleeAppIDHeaderToMetadata(callerAppID, calleeAppID string, req *invokev1.InvokeMethodRequest) {
req.Metadata()[invokev1.CallerIDHeader] = &internalv1pb.ListStringValue{
Values: []string{callerAppID},
}
req.Metadata()[invokev1.CalleeIDHeader] = &internalv1pb.ListStringValue{
Values: []string{calleeAppID},
}
}
func (d *directMessaging) addForwardedHeadersToMetadata(req *invokev1.InvokeMethodRequest) {
metadata := req.Metadata()
var forwardedHeaderValue string
addOrCreate := func(header string, value string) {
if metadata[header] == nil {
metadata[header] = &internalv1pb.ListStringValue{
Values: []string{value},
}
} else {
metadata[header].Values = append(metadata[header].GetValues(), value)
}
}
if d.hostAddress != "" {
// Add X-Forwarded-For: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
addOrCreate(fasthttp.HeaderXForwardedFor, d.hostAddress)
forwardedHeaderValue += "for=" + d.hostAddress + ";by=" + d.hostAddress + ";"
}
if d.hostName != "" {
// Add X-Forwarded-Host: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Host
addOrCreate(fasthttp.HeaderXForwardedHost, d.hostName)
forwardedHeaderValue += "host=" + d.hostName
}
// Add Forwarded header: https://tools.ietf.org/html/rfc7239
addOrCreate(fasthttp.HeaderForwarded, forwardedHeaderValue)
}
func (d *directMessaging) getRemoteApp(appID string) (res remoteApp, err error) {
res.id, res.namespace, err = d.requestAppIDAndNamespace(appID)
if err != nil {
return res, err
}
if d.resolver == nil {
return res, errors.New("name resolver not initialized")
}
// Note: check for case where URL is overwritten for external service invocation,
// or if current app id is associated with an http endpoint CRD.
// This will also forgo service discovery.
switch {
case strings.HasPrefix(res.id, "http://") || strings.HasPrefix(res.id, "https://"):
res.address = res.id
case d.isHTTPEndpoint(res.id):
res.address = d.checkHTTPEndpoints(res.id)
default:
request := nr.ResolveRequest{
ID: res.id,
Namespace: res.namespace,
Port: d.grpcPort,
}
// If the component implements ResolverMulti, we can use caching
if d.resolverMulti != nil {
var addresses nr.AddressList
if d.resolverCache != nil {
// Check if the value is in the cache
res.cacheKey = request.CacheKey()
addresses, _ = d.resolverCache.Get(res.cacheKey)
if len(addresses) > 0 {
// Pick a random one
res.address = addresses.Pick()
}
}
// If there was nothing in the cache (including the case of the cache disabled)
if res.address == "" {
// Resolve
addresses, err = d.resolverMulti.ResolveIDMulti(context.TODO(), request)
if err != nil {
return res, err
}
res.address = addresses.Pick()
if len(addresses) > 0 && res.cacheKey != "" {
// Store the result in cache
// Note that we may have a race condition here if another goroutine was resolving the same address
// This is acceptable, as the waste caused by an extra DNS resolution is very small
d.resolverCache.Set(res.cacheKey, addresses, resolverCacheTTL)
}
}
} else {
res.address, err = d.resolver.ResolveID(context.TODO(), request)
if err != nil {
return res, err
}
}
}
return res, nil
}
// ReadChunk reads a chunk of data from a StreamPayload object.
// The returned value "seq" indicates the sequence number
func ReadChunk(payload *commonv1pb.StreamPayload, out io.Writer) (seq uint64, err error) {
if len(payload.GetData()) > 0 {
var n int
n, err = out.Write(payload.GetData())
if err != nil {
return 0, err
}
if n != len(payload.GetData()) {
return 0, fmt.Errorf("wrote %d out of %d bytes", n, len(payload.GetData()))
}
}
return payload.GetSeq(), nil
}
|
mikeee/dapr
|
pkg/messaging/direct_messaging.go
|
GO
|
mit
| 22,174 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package messaging
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"net"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/valyala/fasthttp"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/protobuf/types/known/anypb"
"github.com/dapr/dapr/pkg/channel"
invokev1 "github.com/dapr/dapr/pkg/messaging/v1"
commonv1pb "github.com/dapr/dapr/pkg/proto/common/v1"
internalv1pb "github.com/dapr/dapr/pkg/proto/internals/v1"
"github.com/dapr/dapr/pkg/runtime/channels"
"github.com/dapr/kit/logger"
)
func TestDestinationHeaders(t *testing.T) {
t.Run("destination header present", func(t *testing.T) {
const appID = "test1"
req := invokev1.NewInvokeMethodRequest("GET").
WithMetadata(map[string][]string{})
defer req.Close()
dm := &directMessaging{}
dm.addDestinationAppIDHeaderToMetadata(appID, req)
md := req.Metadata()[invokev1.DestinationIDHeader]
assert.Equal(t, appID, md.GetValues()[0])
})
}
func TestCallerAndCalleeHeaders(t *testing.T) {
t.Run("caller and callee header present", func(t *testing.T) {
callerAppID := "caller-app"
calleeAppID := "callee-app"
req := invokev1.NewInvokeMethodRequest("GET").
WithMetadata(map[string][]string{})
defer req.Close()
dm := &directMessaging{}
dm.addCallerAndCalleeAppIDHeaderToMetadata(callerAppID, calleeAppID, req)
actualCallerAppID := req.Metadata()[invokev1.CallerIDHeader]
actualCalleeAppID := req.Metadata()[invokev1.CalleeIDHeader]
assert.Equal(t, callerAppID, actualCallerAppID.GetValues()[0])
assert.Equal(t, calleeAppID, actualCalleeAppID.GetValues()[0])
})
}
func TestForwardedHeaders(t *testing.T) {
t.Run("forwarded headers present", func(t *testing.T) {
req := invokev1.NewInvokeMethodRequest("GET").
WithMetadata(map[string][]string{})
defer req.Close()
dm := &directMessaging{}
dm.hostAddress = "1"
dm.hostName = "2"
dm.addForwardedHeadersToMetadata(req)
md := req.Metadata()[fasthttp.HeaderXForwardedFor]
assert.Equal(t, "1", md.GetValues()[0])
md = req.Metadata()[fasthttp.HeaderXForwardedHost]
assert.Equal(t, "2", md.GetValues()[0])
md = req.Metadata()[fasthttp.HeaderForwarded]
assert.Equal(t, "for=1;by=1;host=2", md.GetValues()[0])
})
t.Run("forwarded headers get appended", func(t *testing.T) {
req := invokev1.NewInvokeMethodRequest("GET").
WithMetadata(map[string][]string{
fasthttp.HeaderXForwardedFor: {"originalXForwardedFor"},
fasthttp.HeaderXForwardedHost: {"originalXForwardedHost"},
fasthttp.HeaderForwarded: {"originalForwarded"},
})
defer req.Close()
dm := &directMessaging{}
dm.hostAddress = "1"
dm.hostName = "2"
dm.addForwardedHeadersToMetadata(req)
md := req.Metadata()[fasthttp.HeaderXForwardedFor]
assert.Equal(t, "originalXForwardedFor", md.GetValues()[0])
assert.Equal(t, "1", md.GetValues()[1])
md = req.Metadata()[fasthttp.HeaderXForwardedHost]
assert.Equal(t, "originalXForwardedHost", md.GetValues()[0])
assert.Equal(t, "2", md.GetValues()[1])
md = req.Metadata()[fasthttp.HeaderForwarded]
assert.Equal(t, "originalForwarded", md.GetValues()[0])
assert.Equal(t, "for=1;by=1;host=2", md.GetValues()[1])
})
}
func TestKubernetesNamespace(t *testing.T) {
t.Run("no namespace", func(t *testing.T) {
appID := "app1"
dm := &directMessaging{}
id, ns, err := dm.requestAppIDAndNamespace(appID)
require.NoError(t, err)
assert.Empty(t, ns)
assert.Equal(t, appID, id)
})
t.Run("with namespace", func(t *testing.T) {
appID := "app1.ns1"
dm := &directMessaging{}
id, ns, err := dm.requestAppIDAndNamespace(appID)
require.NoError(t, err)
assert.Equal(t, "ns1", ns)
assert.Equal(t, "app1", id)
})
t.Run("invalid namespace", func(t *testing.T) {
appID := "app1.ns1.ns2"
dm := &directMessaging{}
_, _, err := dm.requestAppIDAndNamespace(appID)
require.Error(t, err)
})
}
func TestInvokeRemote(t *testing.T) {
log.SetOutputLevel(logger.FatalLevel)
defer log.SetOutputLevel(logger.InfoLevel)
socketDir := t.TempDir()
prepareEnvironment := func(t *testing.T, enableStreaming bool, chunks []string) (*directMessaging, func()) {
// Generate a random file name
name := make([]byte, 8)
_, err := io.ReadFull(rand.Reader, name)
require.NoError(t, err)
socket := filepath.Join(socketDir, hex.EncodeToString(name))
server := startInternalServer(socket, enableStreaming, chunks)
clientConn := createTestClient(socket)
messaging := NewDirectMessaging(NewDirectMessagingOpts{
MaxRequestBodySize: 10 << 20,
ClientConnFn: func(ctx context.Context, address string, id string, namespace string, customOpts ...grpc.DialOption) (*grpc.ClientConn, func(destroy bool), error) {
return clientConn, func(_ bool) {}, nil
},
}).(*directMessaging)
teardown := func() {
messaging.Close()
server.Stop()
clientConn.Close()
}
return messaging, teardown
}
t.Run("streaming with no data", func(t *testing.T) {
messaging, teardown := prepareEnvironment(t, true, nil)
defer teardown()
request := invokev1.
NewInvokeMethodRequest("method").
WithMetadata(map[string][]string{invokev1.DestinationIDHeader: {"app1"}})
defer request.Close()
res, _, err := messaging.invokeRemote(context.Background(), "app1", "namespace1", "addr1", request)
require.NoError(t, err)
pd, err := res.ProtoWithData()
require.NoError(t, err)
if err != nil {
return
}
assert.True(t, pd.GetMessage().GetData() == nil || len(pd.GetMessage().GetData().GetValue()) == 0)
})
t.Run("streaming with single chunk", func(t *testing.T) {
messaging, teardown := prepareEnvironment(t, true, []string{"🐱"})
defer teardown()
request := invokev1.
NewInvokeMethodRequest("method").
WithMetadata(map[string][]string{invokev1.DestinationIDHeader: {"app1"}})
defer request.Close()
res, _, err := messaging.invokeRemote(context.Background(), "app1", "namespace1", "addr1", request)
require.NoError(t, err)
pd, err := res.ProtoWithData()
require.NoError(t, err)
assert.Equal(t, "🐱", string(pd.GetMessage().GetData().GetValue()))
})
t.Run("streaming with multiple chunks", func(t *testing.T) {
chunks := []string{
"Sempre caro mi fu quest'ermo colle ",
"e questa siepe, che da tanta parte ",
"dell'ultimo orizzonte il guardo esclude. ",
"… ",
"E il naufragar m'è dolce in questo mare.",
}
messaging, teardown := prepareEnvironment(t, true, chunks)
defer teardown()
request := invokev1.
NewInvokeMethodRequest("method").
WithMetadata(map[string][]string{invokev1.DestinationIDHeader: {"app1"}})
defer request.Close()
res, _, err := messaging.invokeRemote(context.Background(), "app1", "namespace1", "addr1", request)
require.NoError(t, err)
pd, err := res.ProtoWithData()
require.NoError(t, err)
assert.Equal(t, "Sempre caro mi fu quest'ermo colle e questa siepe, che da tanta parte dell'ultimo orizzonte il guardo esclude. … E il naufragar m'è dolce in questo mare.", string(pd.GetMessage().GetData().GetValue()))
})
t.Run("target does not support streaming - request is not replayable", func(t *testing.T) {
messaging, teardown := prepareEnvironment(t, false, nil)
defer teardown()
request := invokev1.
NewInvokeMethodRequest("method").
WithMetadata(map[string][]string{invokev1.DestinationIDHeader: {"app1"}})
defer request.Close()
res, _, err := messaging.invokeRemote(context.Background(), "app1", "namespace1", "addr1", request)
require.Error(t, err)
assert.Equal(t, fmt.Sprintf(streamingUnsupportedErr, "app1"), err.Error())
assert.Nil(t, res)
})
t.Run("target does not support streaming - request is replayable", func(t *testing.T) {
messaging, teardown := prepareEnvironment(t, false, nil)
defer teardown()
request := invokev1.
NewInvokeMethodRequest("method").
WithMetadata(map[string][]string{invokev1.DestinationIDHeader: {"app1"}}).
WithReplay(true)
defer request.Close()
res, _, err := messaging.invokeRemote(context.Background(), "app1", "namespace1", "addr1", request)
require.NoError(t, err)
pd, err := res.ProtoWithData()
require.NoError(t, err)
assert.Equal(t, "🐶", string(pd.GetMessage().GetData().GetValue()))
})
t.Run("target does not support streaming - request has data in-memory", func(t *testing.T) {
messaging, teardown := prepareEnvironment(t, false, nil)
defer teardown()
request := invokev1.
FromInvokeRequestMessage(&commonv1pb.InvokeRequest{
Method: "method",
Data: &anypb.Any{
Value: []byte("nel blu dipinto di blu"),
},
ContentType: "text/plain",
}).
WithMetadata(map[string][]string{invokev1.DestinationIDHeader: {"app1"}})
defer request.Close()
res, _, err := messaging.invokeRemote(context.Background(), "app1", "namespace1", "addr1", request)
require.NoError(t, err)
pd, err := res.ProtoWithData()
require.NoError(t, err)
assert.Equal(t, "🐶", string(pd.GetMessage().GetData().GetValue()))
})
}
func createTestClient(socket string) *grpc.ClientConn {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
conn, err := grpc.DialContext(
ctx,
socket,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithBlock(),
grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {
return net.Dial("unix", addr)
}),
)
if err != nil {
panic(err)
}
return conn
}
func startInternalServer(socket string, enableStreaming bool, chunks []string) *grpc.Server {
lis, _ := net.Listen("unix", socket)
server := grpc.NewServer()
if enableStreaming {
stream := &mockGRPCServerStream{
chunks: chunks,
}
server.RegisterService(&grpc.ServiceDesc{
ServiceName: "dapr.proto.internals.v1.ServiceInvocation",
HandlerType: (*mockGRPCServerStreamI)(nil),
Methods: stream.methods(),
Streams: stream.streams(),
}, stream)
} else {
unary := &mockGRPCServerUnary{}
server.RegisterService(&grpc.ServiceDesc{
ServiceName: "dapr.proto.internals.v1.ServiceInvocation",
HandlerType: (*mockGRPCServerUnaryI)(nil),
Methods: unary.methods(),
}, unary)
}
go func() {
if err := server.Serve(lis); err != nil {
panic(err)
}
}()
return server
}
type mockGRPCServerUnaryI interface {
CallLocal(ctx context.Context, in *internalv1pb.InternalInvokeRequest) (*internalv1pb.InternalInvokeResponse, error)
}
type mockGRPCServerUnary struct{}
func (m *mockGRPCServerUnary) CallLocal(ctx context.Context, in *internalv1pb.InternalInvokeRequest) (*internalv1pb.InternalInvokeResponse, error) {
resp := invokev1.NewInvokeMethodResponse(0, "", nil).
WithRawDataString("🐶").
WithContentType("text/plain")
return resp.ProtoWithData()
}
func (m *mockGRPCServerUnary) methods() []grpc.MethodDesc {
return []grpc.MethodDesc{
{
MethodName: "CallLocal",
Handler: func(srv any, ctx context.Context, dec func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) {
in := new(internalv1pb.InternalInvokeRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(mockGRPCServerUnaryI).CallLocal(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/dapr.proto.internals.v1.ServiceInvocation/CallLocal",
}
handler := func(ctx context.Context, req any) (any, error) {
return srv.(mockGRPCServerUnaryI).CallLocal(ctx, req.(*internalv1pb.InternalInvokeRequest))
}
return interceptor(ctx, in, info, handler)
},
},
}
}
type mockGRPCServerStreamI interface {
mockGRPCServerUnaryI
CallLocalStream(stream internalv1pb.ServiceInvocation_CallLocalStreamServer) error //nolint:nosnakecase
}
type mockGRPCServerStream struct {
mockGRPCServerUnary
chunks []string
}
func (m *mockGRPCServerStream) CallLocalStream(stream internalv1pb.ServiceInvocation_CallLocalStreamServer) error { //nolint:nosnakecase
// Send the first chunk
resp := invokev1.NewInvokeMethodResponse(200, "OK", nil).
WithContentType("text/plain").
WithHTTPHeaders(map[string][]string{"foo": {"bar"}})
defer resp.Close()
chunksLen := uint64(len(m.chunks))
var payload *commonv1pb.StreamPayload
if chunksLen > 0 {
payload = &commonv1pb.StreamPayload{
Data: []byte(m.chunks[0]),
Seq: 0,
}
}
stream.Send(&internalv1pb.InternalInvokeResponseStream{
Response: resp.Proto(),
Payload: payload,
})
// Send the next chunks if needed
// Note this starts from index 1 on purpose
for i := uint64(1); i < chunksLen; i++ {
stream.Send(&internalv1pb.InternalInvokeResponseStream{
Payload: &commonv1pb.StreamPayload{
Data: []byte(m.chunks[i]),
Seq: i,
},
})
}
return nil
}
func (m *mockGRPCServerStream) streams() []grpc.StreamDesc {
return []grpc.StreamDesc{
{
StreamName: "CallLocalStream",
Handler: func(srv any, stream grpc.ServerStream) error {
return srv.(mockGRPCServerStreamI).CallLocalStream(&serviceInvocationCallLocalStreamServer{stream})
},
ServerStreams: true,
ClientStreams: true,
},
}
}
type serviceInvocationCallLocalStreamServer struct {
grpc.ServerStream
}
func (x *serviceInvocationCallLocalStreamServer) Send(m *internalv1pb.InternalInvokeResponseStream) error {
return x.ServerStream.SendMsg(m)
}
func (x *serviceInvocationCallLocalStreamServer) Recv() (*internalv1pb.InternalInvokeRequestStream, error) {
m := new(internalv1pb.InternalInvokeRequestStream)
if err := x.ServerStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
func TestInvokeRemoteUnaryForHTTPEndpoint(t *testing.T) {
t.Run("channel found", func(t *testing.T) {
d := directMessaging{
channels: (new(channels.Channels)).WithEndpointChannels(map[string]channel.HTTPEndpointAppChannel{"abc": &mockChannel{}}),
}
_, err := d.invokeRemoteUnaryForHTTPEndpoint(context.Background(), nil, "abc")
require.NoError(t, err)
})
t.Run("channel not found", func(t *testing.T) {
d := directMessaging{
channels: new(channels.Channels),
}
_, err := d.invokeRemoteUnaryForHTTPEndpoint(context.Background(), nil, "abc")
require.Error(t, err)
})
}
type mockChannel struct{}
func (m *mockChannel) InvokeMethod(ctx context.Context, req *invokev1.InvokeMethodRequest, appID string) (*invokev1.InvokeMethodResponse, error) {
return nil, nil
}
|
mikeee/dapr
|
pkg/messaging/direct_messaging_test.go
|
GO
|
mit
| 14,974 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package messaging
import (
"context"
"errors"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"github.com/dapr/dapr/pkg/acl"
grpcProxy "github.com/dapr/dapr/pkg/api/grpc/proxy"
codec "github.com/dapr/dapr/pkg/api/grpc/proxy/codec"
"github.com/dapr/dapr/pkg/config"
"github.com/dapr/dapr/pkg/diagnostics"
invokev1 "github.com/dapr/dapr/pkg/messaging/v1"
"github.com/dapr/dapr/pkg/proto/common/v1"
"github.com/dapr/dapr/pkg/resiliency"
"github.com/dapr/dapr/pkg/security"
securityConsts "github.com/dapr/dapr/pkg/security/consts"
)
// Proxy is the interface for a gRPC transparent proxy.
type Proxy interface {
Handler() grpc.StreamHandler
SetRemoteAppFn(func(string) (remoteApp, error))
SetTelemetryFn(func(context.Context) context.Context)
}
type proxy struct {
appID string
appClientFn func() (grpc.ClientConnInterface, error)
connectionFactory messageClientConnection
remoteAppFn func(appID string) (remoteApp, error)
telemetryFn func(context.Context) context.Context
acl *config.AccessControlList
resiliency resiliency.Provider
maxRequestBodySize int
}
// ProxyOpts is the struct with options for NewProxy.
type ProxyOpts struct {
AppClientFn func() (grpc.ClientConnInterface, error)
ConnectionFactory messageClientConnection
AppID string
ACL *config.AccessControlList
Resiliency resiliency.Provider
MaxRequestBodySize int
}
// NewProxy returns a new proxy.
func NewProxy(opts ProxyOpts) Proxy {
return &proxy{
appClientFn: opts.AppClientFn,
appID: opts.AppID,
connectionFactory: opts.ConnectionFactory,
acl: opts.ACL,
resiliency: opts.Resiliency,
maxRequestBodySize: opts.MaxRequestBodySize,
}
}
// Handler returns a Stream Handler for handling requests that arrive for services that are not recognized by the server.
func (p *proxy) Handler() grpc.StreamHandler {
return grpcProxy.TransparentHandler(p.intercept,
func(appID, methodName string) *resiliency.PolicyDefinition {
_, isLocal, err := p.isLocal(appID)
if err == nil && !isLocal {
return p.resiliency.EndpointPolicy(appID, appID+":"+methodName)
}
return resiliency.NoOp{}.EndpointPolicy("", "")
},
grpcProxy.DirectorConnectionFactory(p.connectionFactory),
p.maxRequestBodySize,
)
}
func nopTeardown(destroy bool) {
// Nop
}
func (p *proxy) intercept(ctx context.Context, fullName string) (context.Context, *grpc.ClientConn, *grpcProxy.ProxyTarget, func(destroy bool), error) {
md, _ := metadata.FromIncomingContext(ctx)
v := md[diagnostics.GRPCProxyAppIDKey]
if len(v) == 0 {
return ctx, nil, nil, nopTeardown, fmt.Errorf("failed to proxy request: required metadata %s not found", diagnostics.GRPCProxyAppIDKey)
}
outCtx := metadata.NewOutgoingContext(ctx, md.Copy())
appID := v[0]
if p.remoteAppFn == nil {
return ctx, nil, nil, nopTeardown, errors.New("failed to proxy request: proxy not initialized. daprd startup may be incomplete")
}
target, isLocal, err := p.isLocal(appID)
if err != nil {
return ctx, nil, nil, nopTeardown, err
}
if isLocal {
// proxy locally to the app
if p.acl != nil {
ok, authError := acl.ApplyAccessControlPolicies(ctx, fullName, common.HTTPExtension_NONE, false, p.acl) //nolint:nosnakecase
if !ok {
return ctx, nil, nil, nopTeardown, status.Errorf(codes.PermissionDenied, authError)
}
}
var appClient grpc.ClientConnInterface
appClient, err = p.appClientFn()
if err != nil {
return ctx, nil, nil, nopTeardown, err
}
appMetadataToken := security.GetAppToken()
if appMetadataToken != "" {
outCtx = metadata.AppendToOutgoingContext(outCtx, securityConsts.APITokenHeader, appMetadataToken)
}
return outCtx, appClient.(*grpc.ClientConn), nil, nopTeardown, nil
}
// proxy to a remote daprd
conn, teardown, cErr := p.connectionFactory(outCtx, target.address, target.id, target.namespace,
grpc.WithDefaultCallOptions(grpc.CallContentSubtype((&codec.Proxy{}).Name())),
)
outCtx = p.telemetryFn(outCtx)
outCtx = metadata.AppendToOutgoingContext(outCtx, invokev1.CallerIDHeader, p.appID, invokev1.CalleeIDHeader, target.id)
pt := &grpcProxy.ProxyTarget{
ID: target.id,
Namespace: target.namespace,
Address: target.address,
}
return outCtx, conn, pt, teardown, cErr
}
// SetRemoteAppFn sets a function that helps the proxy resolve an app ID to an actual address.
func (p *proxy) SetRemoteAppFn(remoteAppFn func(appID string) (remoteApp, error)) {
p.remoteAppFn = remoteAppFn
}
// SetTelemetryFn sets a function that enriches the context with telemetry.
func (p *proxy) SetTelemetryFn(spanFn func(context.Context) context.Context) {
p.telemetryFn = spanFn
}
func (p *proxy) isLocal(appID string) (remoteApp, bool, error) {
if p.remoteAppFn == nil {
return remoteApp{}, false, errors.New("failed to proxy request: proxy not initialized; daprd startup may be incomplete")
}
target, err := p.remoteAppFn(appID)
if err != nil {
return remoteApp{}, false, err
}
return target, target.id == p.appID, nil
}
|
mikeee/dapr
|
pkg/messaging/grpc_proxy.go
|
GO
|
mit
| 5,766 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package messaging
import (
"context"
"net"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
"github.com/dapr/dapr/pkg/config"
"github.com/dapr/dapr/pkg/diagnostics"
invokev1 "github.com/dapr/dapr/pkg/messaging/v1"
"github.com/dapr/dapr/pkg/resiliency"
securityConsts "github.com/dapr/dapr/pkg/security/consts"
)
func connectionFn(ctx context.Context, address, id string, namespace string, customOpts ...grpc.DialOption) (*grpc.ClientConn, func(bool), error) {
conn, err := grpc.Dial(id,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithContextDialer(func(ctx context.Context, s string) (net.Conn, error) {
// Don't actually connect to anything
return &net.TCPConn{}, nil
}),
)
if err != nil {
return nil, func(bool) {}, err
}
teardown := func(bool) { conn.Close() }
return conn, teardown, err
}
func appClientFn() (grpc.ClientConnInterface, error) {
appClient, _, err := connectionFn(context.Background(), "a:123", "a", "")
return appClient, err
}
func TestNewProxy(t *testing.T) {
p := NewProxy(ProxyOpts{
ConnectionFactory: connectionFn,
AppClientFn: appClientFn,
AppID: "a",
ACL: nil,
Resiliency: resiliency.New(nil),
})
proxy := p.(*proxy)
assert.Equal(t, "a", proxy.appID)
assert.NotNil(t, proxy.connectionFactory)
assert.Equal(t, reflect.ValueOf(connectionFn).Pointer(), reflect.ValueOf(proxy.connectionFactory).Pointer())
}
func TestSetRemoteAppFn(t *testing.T) {
p := NewProxy(ProxyOpts{
ConnectionFactory: connectionFn,
AppClientFn: appClientFn,
AppID: "a",
ACL: nil,
Resiliency: resiliency.New(nil),
})
p.SetRemoteAppFn(func(s string) (remoteApp, error) {
return remoteApp{
id: "a",
}, nil
})
proxy := p.(*proxy)
app, err := proxy.remoteAppFn("a")
require.NoError(t, err)
assert.Equal(t, "a", app.id)
}
func TestSetTelemetryFn(t *testing.T) {
p := NewProxy(ProxyOpts{
ConnectionFactory: connectionFn,
AppClientFn: appClientFn,
AppID: "a",
ACL: nil,
Resiliency: resiliency.New(nil),
})
p.SetTelemetryFn(func(ctx context.Context) context.Context {
return ctx
})
proxy := p.(*proxy)
ctx := metadata.NewOutgoingContext(context.TODO(), metadata.MD{"a": []string{"b"}})
ctx = proxy.telemetryFn(ctx)
md, _ := metadata.FromOutgoingContext(ctx)
assert.Equal(t, "b", md["a"][0])
}
func TestHandler(t *testing.T) {
p := NewProxy(ProxyOpts{
ConnectionFactory: connectionFn,
AppClientFn: appClientFn,
AppID: "a",
Resiliency: resiliency.New(nil),
})
h := p.Handler()
assert.NotNil(t, h)
}
func TestIntercept(t *testing.T) {
t.Run("no app-id in metadata", func(t *testing.T) {
p := NewProxy(ProxyOpts{
ConnectionFactory: connectionFn,
AppClientFn: appClientFn,
AppID: "a",
Resiliency: resiliency.New(nil),
})
p.SetTelemetryFn(func(ctx context.Context) context.Context {
return ctx
})
p.SetRemoteAppFn(func(s string) (remoteApp, error) {
return remoteApp{
id: "a",
}, nil
})
ctx := metadata.NewOutgoingContext(context.TODO(), metadata.MD{"a": []string{"b"}})
proxy := p.(*proxy)
_, conn, _, teardown, err := proxy.intercept(ctx, "/test")
defer teardown(true)
require.Error(t, err)
assert.Nil(t, conn)
})
t.Run("app-id exists in metadata", func(t *testing.T) {
p := NewProxy(ProxyOpts{
ConnectionFactory: connectionFn,
AppClientFn: appClientFn,
AppID: "a",
Resiliency: resiliency.New(nil),
})
p.SetTelemetryFn(func(ctx context.Context) context.Context {
return ctx
})
p.SetRemoteAppFn(func(s string) (remoteApp, error) {
return remoteApp{
id: "a",
}, nil
})
ctx := metadata.NewIncomingContext(context.TODO(), metadata.MD{diagnostics.GRPCProxyAppIDKey: []string{"b"}})
proxy := p.(*proxy)
_, _, _, _, err := proxy.intercept(ctx, "/test")
require.NoError(t, err)
})
t.Run("proxy to the app", func(t *testing.T) {
p := NewProxy(ProxyOpts{
ConnectionFactory: connectionFn,
AppClientFn: appClientFn,
AppID: "a",
Resiliency: resiliency.New(nil),
})
p.SetTelemetryFn(func(ctx context.Context) context.Context {
return ctx
})
p.SetRemoteAppFn(func(s string) (remoteApp, error) {
return remoteApp{
id: "a",
}, nil
})
t.Setenv(securityConsts.AppAPITokenEnvVar, "token1")
ctx := metadata.NewIncomingContext(context.TODO(), metadata.MD{diagnostics.GRPCProxyAppIDKey: []string{"a"}})
proxy := p.(*proxy)
ctx, conn, _, teardown, err := proxy.intercept(ctx, "/test")
defer teardown(true)
require.NoError(t, err)
assert.NotNil(t, conn)
assert.Equal(t, "a", conn.Target())
md, _ := metadata.FromOutgoingContext(ctx)
assert.Equal(t, "token1", md[securityConsts.APITokenHeader][0])
})
t.Run("proxy to a remote app", func(t *testing.T) {
p := NewProxy(ProxyOpts{
ConnectionFactory: connectionFn,
AppClientFn: appClientFn,
AppID: "a",
Resiliency: resiliency.New(nil),
})
p.SetTelemetryFn(func(ctx context.Context) context.Context {
ctx = metadata.AppendToOutgoingContext(ctx, "a", "b")
return ctx
})
p.SetRemoteAppFn(func(s string) (remoteApp, error) {
return remoteApp{
id: "b",
}, nil
})
t.Setenv(securityConsts.AppAPITokenEnvVar, "token1")
ctx := metadata.NewIncomingContext(context.TODO(), metadata.MD{diagnostics.GRPCProxyAppIDKey: []string{"b"}})
proxy := p.(*proxy)
ctx, conn, _, teardown, err := proxy.intercept(ctx, "/test")
defer teardown(true)
require.NoError(t, err)
assert.NotNil(t, conn)
assert.Equal(t, "b", conn.Target())
md, _ := metadata.FromOutgoingContext(ctx)
assert.Equal(t, "b", md["a"][0])
assert.Equal(t, "a", md[invokev1.CallerIDHeader][0])
assert.Equal(t, "b", md[invokev1.CalleeIDHeader][0])
assert.NotContains(t, md, securityConsts.APITokenHeader)
})
t.Run("access policies applied", func(t *testing.T) {
acl := &config.AccessControlList{
DefaultAction: "deny",
TrustDomain: "public",
}
p := NewProxy(ProxyOpts{
ConnectionFactory: connectionFn,
AppClientFn: appClientFn,
AppID: "a",
ACL: acl,
Resiliency: resiliency.New(nil),
})
p.SetRemoteAppFn(func(s string) (remoteApp, error) {
return remoteApp{
id: "a",
address: "a:123",
}, nil
})
p.SetTelemetryFn(func(ctx context.Context) context.Context {
ctx = metadata.AppendToOutgoingContext(ctx, "a", "b")
return ctx
})
ctx := metadata.NewIncomingContext(context.TODO(), metadata.MD{diagnostics.GRPCProxyAppIDKey: []string{"a"}})
proxy := p.(*proxy)
_, conn, _, teardown, err := proxy.intercept(ctx, "/test")
defer teardown(true)
require.Error(t, err)
assert.Nil(t, conn)
})
t.Run("SetRemoteAppFn never called", func(t *testing.T) {
p := NewProxy(ProxyOpts{
ConnectionFactory: connectionFn,
AppClientFn: appClientFn,
AppID: "a",
Resiliency: resiliency.New(nil),
})
p.SetTelemetryFn(func(ctx context.Context) context.Context {
return ctx
})
ctx := metadata.NewIncomingContext(context.TODO(), metadata.MD{diagnostics.GRPCProxyAppIDKey: []string{"a"}})
proxy := p.(*proxy)
_, conn, _, teardown, err := proxy.intercept(ctx, "/test")
defer teardown(true)
require.Error(t, err)
assert.Nil(t, conn)
})
}
|
mikeee/dapr
|
pkg/messaging/grpc_proxy_test.go
|
GO
|
mit
| 8,173 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
"bytes"
"encoding/json"
"errors"
"io"
"net/http"
"strings"
"github.com/valyala/fasthttp"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/anypb"
commonv1pb "github.com/dapr/dapr/pkg/proto/common/v1"
internalv1pb "github.com/dapr/dapr/pkg/proto/internals/v1"
)
const (
// DefaultAPIVersion is the default Dapr API version.
DefaultAPIVersion = internalv1pb.APIVersion_V1 //nolint:nosnakecase
)
// InvokeMethodRequest holds InternalInvokeRequest protobuf message
// and provides the helpers to manage it.
type InvokeMethodRequest struct {
replayableRequest
r *internalv1pb.InternalInvokeRequest
dataObject any
dataTypeURL string
}
// NewInvokeMethodRequest creates InvokeMethodRequest object for method.
func NewInvokeMethodRequest(method string) *InvokeMethodRequest {
return &InvokeMethodRequest{
r: &internalv1pb.InternalInvokeRequest{
Ver: DefaultAPIVersion,
Message: &commonv1pb.InvokeRequest{
Method: method,
},
},
}
}
// FromInvokeRequestMessage creates InvokeMethodRequest object from InvokeRequest pb object.
func FromInvokeRequestMessage(pb *commonv1pb.InvokeRequest) *InvokeMethodRequest {
return &InvokeMethodRequest{
r: &internalv1pb.InternalInvokeRequest{
Ver: DefaultAPIVersion,
Message: pb,
},
}
}
// FromInternalInvokeRequest creates InvokeMethodRequest object from FromInternalInvokeRequest pb object.
func FromInternalInvokeRequest(pb *internalv1pb.InternalInvokeRequest) (*InvokeMethodRequest, error) {
req := &InvokeMethodRequest{r: pb}
if pb.GetMessage() == nil {
return nil, errors.New("field Message is nil")
}
return req, nil
}
// WithActor sets actor type and id.
func (imr *InvokeMethodRequest) WithActor(actorType, actorID string) *InvokeMethodRequest {
imr.r.Actor = &internalv1pb.Actor{ActorType: actorType, ActorId: actorID}
return imr
}
// WithMetadata sets metadata.
func (imr *InvokeMethodRequest) WithMetadata(md map[string][]string) *InvokeMethodRequest {
imr.r.Metadata = internalv1pb.MetadataToInternalMetadata(md)
return imr
}
// WithHTTPHeaders sets metadata from HTTP request headers.
func (imr *InvokeMethodRequest) WithHTTPHeaders(header http.Header) *InvokeMethodRequest {
imr.r.Metadata = internalv1pb.HTTPHeadersToInternalMetadata(header)
return imr
}
// WithFastHTTPHeaders sets metadata from fasthttp request headers.
func (imr *InvokeMethodRequest) WithFastHTTPHeaders(header *fasthttp.RequestHeader) *InvokeMethodRequest {
imr.r.Metadata = internalv1pb.FastHTTPHeadersToInternalMetadata(header)
return imr
}
// WithRawData sets message data from a readable stream.
func (imr *InvokeMethodRequest) WithRawData(data io.Reader) *InvokeMethodRequest {
imr.dataObject = nil
imr.ResetMessageData()
imr.replayableRequest.WithRawData(data)
return imr
}
// WithRawDataBytes sets message data from a []byte.
func (imr *InvokeMethodRequest) WithRawDataBytes(data []byte) *InvokeMethodRequest {
return imr.WithRawData(bytes.NewReader(data))
}
// WithRawDataString sets message data from a string.
func (imr *InvokeMethodRequest) WithRawDataString(data string) *InvokeMethodRequest {
return imr.WithRawData(strings.NewReader(data))
}
// WithDataObject sets message from an object which will be serialized as JSON
func (imr *InvokeMethodRequest) WithDataObject(data any) *InvokeMethodRequest {
enc, _ := json.Marshal(data)
res := imr.WithRawDataBytes(enc)
res.dataObject = data
return res
}
// WithContentType sets the content type.
func (imr *InvokeMethodRequest) WithContentType(contentType string) *InvokeMethodRequest {
imr.r.Message.ContentType = contentType
return imr
}
// WithDataTypeURL sets the type_url property for the data.
// When a type_url is set, the Content-Type automatically becomes the protobuf one.
func (imr *InvokeMethodRequest) WithDataTypeURL(val string) *InvokeMethodRequest {
imr.dataTypeURL = val
return imr
}
// WithHTTPExtension sets new HTTP extension with verb and querystring.
//
//nolint:nosnakecase
func (imr *InvokeMethodRequest) WithHTTPExtension(verb string, querystring string) *InvokeMethodRequest {
httpMethod, ok := commonv1pb.HTTPExtension_Verb_value[strings.ToUpper(verb)]
if !ok {
httpMethod = int32(commonv1pb.HTTPExtension_POST)
}
imr.r.Message.HttpExtension = &commonv1pb.HTTPExtension{
Verb: commonv1pb.HTTPExtension_Verb(httpMethod),
Querystring: querystring,
}
return imr
}
// WithCustomHTTPMetadata applies a metadata map to a InvokeMethodRequest.
func (imr *InvokeMethodRequest) WithCustomHTTPMetadata(md map[string]string) *InvokeMethodRequest {
for k, v := range md {
if strings.EqualFold(k, ContentLengthHeader) {
// There is no use of the original payload's content-length because
// the entire data is already in the cloud event.
continue
}
if imr.r.GetMetadata() == nil {
imr.r.Metadata = make(map[string]*internalv1pb.ListStringValue)
}
// NOTE: We don't explicitly lowercase the keys here but this will be done
// later when attached to the HTTP request as headers.
imr.r.Metadata[k] = &internalv1pb.ListStringValue{Values: []string{v}}
}
return imr
}
// WithReplay enables replaying for the data stream.
func (imr *InvokeMethodRequest) WithReplay(enabled bool) *InvokeMethodRequest {
// If the object has data in-memory, WithReplay is a nop
if !imr.HasMessageData() {
imr.replayableRequest.SetReplay(enabled)
}
return imr
}
// CanReplay returns true if the data stream can be replayed.
func (imr *InvokeMethodRequest) CanReplay() bool {
// We can replay if:
// - The object has data in-memory
// - The request is replayable
return imr.HasMessageData() || imr.replayableRequest.CanReplay()
}
// EncodeHTTPQueryString generates querystring for http using http extension object.
func (imr *InvokeMethodRequest) EncodeHTTPQueryString() string {
m := imr.r.GetMessage()
if m.GetHttpExtension() == nil {
return ""
}
return m.GetHttpExtension().GetQuerystring()
}
// APIVersion gets API version of InvokeMethodRequest.
func (imr *InvokeMethodRequest) APIVersion() internalv1pb.APIVersion {
return imr.r.GetVer()
}
// Metadata gets Metadata of InvokeMethodRequest.
func (imr *InvokeMethodRequest) Metadata() DaprInternalMetadata {
return imr.r.GetMetadata()
}
// Proto returns InternalInvokeRequest Proto object.
func (imr *InvokeMethodRequest) Proto() *internalv1pb.InternalInvokeRequest {
return imr.r
}
// ProtoWithData returns a copy of the internal InternalInvokeRequest Proto object with the entire data stream read into the Data property.
func (imr *InvokeMethodRequest) ProtoWithData() (*internalv1pb.InternalInvokeRequest, error) {
if imr.r == nil || imr.r.GetMessage() == nil {
return nil, errors.New("message is nil")
}
// If the data is already in-memory in the object, return the object directly.
// This doesn't copy the object, and that's fine because receivers are not expected to modify the received object.
// Only reason for cloning the object below is to make ProtoWithData concurrency-safe.
if imr.HasMessageData() {
return imr.r, nil
}
// Clone the object
m := proto.Clone(imr.r).(*internalv1pb.InternalInvokeRequest)
// Read the data and store it in the object
data, err := imr.RawDataFull()
if err != nil {
return m, err
}
m.Message.Data = &anypb.Any{
Value: data,
TypeUrl: imr.dataTypeURL, // Could be empty
}
return m, nil
}
// Actor returns actor type and id.
func (imr *InvokeMethodRequest) Actor() *internalv1pb.Actor {
return imr.r.GetActor()
}
// Message gets InvokeRequest Message object.
func (imr *InvokeMethodRequest) Message() *commonv1pb.InvokeRequest {
return imr.r.GetMessage()
}
// HasMessageData returns true if the message object contains a slice of data buffered.
func (imr *InvokeMethodRequest) HasMessageData() bool {
m := imr.r.GetMessage()
return len(m.GetData().GetValue()) > 0
}
// ResetMessageData resets the data inside the message object if present.
func (imr *InvokeMethodRequest) ResetMessageData() {
if !imr.HasMessageData() {
return
}
imr.r.GetMessage().GetData().Reset()
}
// ContentType returns the content type of the message.
func (imr *InvokeMethodRequest) ContentType() string {
m := imr.r.GetMessage()
if m == nil {
return ""
}
// If there's a proto data and that has a type URL, or if we have a dataTypeUrl in the object, then the content type is the protobuf one
if imr.dataTypeURL != "" || m.GetData().GetTypeUrl() != "" {
return ProtobufContentType
}
return m.GetContentType()
}
// RawData returns the stream body.
// Note: this method is not safe for concurrent use.
func (imr *InvokeMethodRequest) RawData() (r io.Reader) {
m := imr.r.GetMessage()
if m == nil {
return nil
}
// If the message has a data property, use that
if imr.HasMessageData() {
return bytes.NewReader(m.GetData().GetValue())
}
return imr.replayableRequest.RawData()
}
// RawDataFull returns the entire data read from the stream body.
func (imr *InvokeMethodRequest) RawDataFull() ([]byte, error) {
// If the message has a data property, use that
if imr.HasMessageData() {
return imr.r.GetMessage().GetData().GetValue(), nil
}
r := imr.RawData()
if r == nil {
return nil, nil
}
return io.ReadAll(r)
}
// GetDataObject returns the data object stored in the object
func (imr *InvokeMethodRequest) GetDataObject() any {
return imr.dataObject
}
// AddMetadata adds new metadata options to the existing set.
func (imr *InvokeMethodRequest) AddMetadata(md map[string][]string) {
if imr.r.GetMetadata() == nil {
imr.WithMetadata(md)
return
}
for key, val := range internalv1pb.MetadataToInternalMetadata(md) {
// We're only adding new values, not overwriting existing
if _, ok := imr.r.GetMetadata()[key]; !ok {
imr.r.Metadata[key] = val
}
}
}
|
mikeee/dapr
|
pkg/messaging/v1/invoke_method_request.go
|
GO
|
mit
| 10,378 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//nolint:nosnakecase
package v1
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/anypb"
commonv1pb "github.com/dapr/dapr/pkg/proto/common/v1"
internalv1pb "github.com/dapr/dapr/pkg/proto/internals/v1"
)
func TestInvokeRequest(t *testing.T) {
req := NewInvokeMethodRequest("test_method")
defer req.Close()
assert.Equal(t, internalv1pb.APIVersion_V1, req.r.GetVer())
assert.Equal(t, "test_method", req.r.GetMessage().GetMethod())
}
func TestFromInvokeRequestMessage(t *testing.T) {
t.Run("no data", func(t *testing.T) {
pb := &commonv1pb.InvokeRequest{Method: "frominvokerequestmessage"}
req := FromInvokeRequestMessage(pb)
defer req.Close()
assert.Equal(t, internalv1pb.APIVersion_V1, req.r.GetVer())
assert.Equal(t, "frominvokerequestmessage", req.r.GetMessage().GetMethod())
bData, err := io.ReadAll(req.RawData())
require.NoError(t, err)
assert.Empty(t, bData)
})
t.Run("with data", func(t *testing.T) {
pb := &commonv1pb.InvokeRequest{
Method: "frominvokerequestmessage",
Data: &anypb.Any{Value: []byte("test")},
}
req := FromInvokeRequestMessage(pb)
defer req.Close()
assert.Equal(t, internalv1pb.APIVersion_V1, req.r.GetVer())
assert.Equal(t, "frominvokerequestmessage", req.r.GetMessage().GetMethod())
bData, err := io.ReadAll(req.RawData())
require.NoError(t, err)
assert.Equal(t, "test", string(bData))
})
}
func TestInternalInvokeRequest(t *testing.T) {
t.Run("valid internal invoke request with no data", func(t *testing.T) {
m := &commonv1pb.InvokeRequest{
Method: "invoketest",
ContentType: "application/json",
Data: nil,
}
pb := internalv1pb.InternalInvokeRequest{
Ver: internalv1pb.APIVersion_V1,
Message: m,
}
ir, err := FromInternalInvokeRequest(&pb)
require.NoError(t, err)
defer ir.Close()
assert.NotNil(t, ir.r.GetMessage())
assert.Equal(t, "invoketest", ir.r.GetMessage().GetMethod())
assert.Nil(t, ir.r.GetMessage().GetData())
bData, err := io.ReadAll(ir.RawData())
require.NoError(t, err)
assert.Empty(t, bData)
})
t.Run("valid internal invoke request with data", func(t *testing.T) {
m := &commonv1pb.InvokeRequest{
Method: "invoketest",
ContentType: "application/json",
Data: &anypb.Any{Value: []byte("test")},
}
pb := internalv1pb.InternalInvokeRequest{
Ver: internalv1pb.APIVersion_V1,
Message: m,
}
ir, err := FromInternalInvokeRequest(&pb)
require.NoError(t, err)
defer ir.Close()
assert.NotNil(t, ir.r.GetMessage())
assert.Equal(t, "invoketest", ir.r.GetMessage().GetMethod())
require.NotNil(t, ir.r.GetMessage().GetData())
require.NotNil(t, ir.r.GetMessage().GetData().GetValue())
assert.Equal(t, []byte("test"), ir.r.GetMessage().GetData().GetValue())
bData, err := io.ReadAll(ir.RawData())
require.NoError(t, err)
assert.Equal(t, "test", string(bData))
})
t.Run("nil message field", func(t *testing.T) {
pb := internalv1pb.InternalInvokeRequest{
Ver: internalv1pb.APIVersion_V1,
Message: nil,
}
_, err := FromInternalInvokeRequest(&pb)
require.Error(t, err)
})
}
func TestMetadata(t *testing.T) {
t.Run("gRPC headers", func(t *testing.T) {
md := map[string][]string{
"test1": {"val1", "val2"},
"test2": {"val3", "val4"},
}
req := NewInvokeMethodRequest("test_method").
WithMetadata(md)
defer req.Close()
mdata := req.Metadata()
assert.Equal(t, "val1", mdata["test1"].GetValues()[0])
assert.Equal(t, "val2", mdata["test1"].GetValues()[1])
assert.Equal(t, "val3", mdata["test2"].GetValues()[0])
assert.Equal(t, "val4", mdata["test2"].GetValues()[1])
})
t.Run("HTTP headers", func(t *testing.T) {
headers := http.Header{}
headers.Set("Header1", "Value1")
headers.Set("Header2", "Value2")
headers.Set("Header3", "Value3")
re := NewInvokeMethodRequest("test_method").
WithHTTPHeaders(headers)
defer re.Close()
mheader := re.Metadata()
assert.Equal(t, "Value1", mheader["Header1"].GetValues()[0])
assert.Equal(t, "Value2", mheader["Header2"].GetValues()[0])
assert.Equal(t, "Value3", mheader["Header3"].GetValues()[0])
})
}
func TestData(t *testing.T) {
t.Run("contenttype is set", func(t *testing.T) {
req := NewInvokeMethodRequest("test_method").
WithRawDataString("test").
WithContentType("application/json")
defer req.Close()
contentType := req.ContentType()
bData, err := io.ReadAll(req.RawData())
require.NoError(t, err)
assert.Equal(t, "application/json", contentType)
assert.Equal(t, "test", string(bData))
})
t.Run("contenttype is unset,", func(t *testing.T) {
req := NewInvokeMethodRequest("test_method").
WithRawDataString("test")
defer req.Close()
contentType := req.ContentType()
bData, err := io.ReadAll(req.RawData())
require.NoError(t, err)
assert.Equal(t, "", req.r.GetMessage().GetContentType())
assert.Equal(t, "", contentType)
assert.Equal(t, "test", string(bData))
})
t.Run("typeurl is set but content_type is unset", func(t *testing.T) {
req := NewInvokeMethodRequest("test_method")
defer req.Close()
req.r.Message.Data = &anypb.Any{TypeUrl: "type", Value: []byte("fake")}
bData, err := io.ReadAll(req.RawData())
require.NoError(t, err)
assert.Equal(t, ProtobufContentType, req.ContentType())
assert.Equal(t, "fake", string(bData))
})
}
func TestRawData(t *testing.T) {
t.Run("message is nil", func(t *testing.T) {
req := &InvokeMethodRequest{
r: &internalv1pb.InternalInvokeRequest{},
}
r := req.RawData()
assert.Nil(t, r)
})
t.Run("return data from stream", func(t *testing.T) {
req := NewInvokeMethodRequest("test_method").
WithRawDataString("nel blu dipinto di blu")
defer req.Close()
r := req.RawData()
bData, err := io.ReadAll(r)
require.NoError(t, err)
assert.Equal(t, "nel blu dipinto di blu", string(bData))
_ = assert.Nil(t, req.Message().GetData()) ||
assert.Empty(t, req.Message().GetData().GetValue())
})
t.Run("data inside message has priority", func(t *testing.T) {
req := NewInvokeMethodRequest("test_method").
WithRawDataString("nel blu dipinto di blu")
defer req.Close()
// Override
const msg = "felice di stare lassu'"
req.Message().Data = &anypb.Any{Value: []byte(msg)}
r := req.RawData()
bData, err := io.ReadAll(r)
require.NoError(t, err)
assert.Equal(t, msg, string(bData))
_ = assert.NotNil(t, req.Message().GetData()) &&
assert.Equal(t, msg, string(req.Message().GetData().GetValue()))
})
}
func TestRawDataFull(t *testing.T) {
t.Run("message is nil", func(t *testing.T) {
req := &InvokeMethodRequest{
r: &internalv1pb.InternalInvokeRequest{},
}
data, err := req.RawDataFull()
require.NoError(t, err)
assert.Nil(t, data)
})
t.Run("return data from stream", func(t *testing.T) {
req := NewInvokeMethodRequest("test_method").
WithRawDataString("nel blu dipinto di blu")
defer req.Close()
data, err := req.RawDataFull()
require.NoError(t, err)
assert.Equal(t, "nel blu dipinto di blu", string(data))
_ = assert.Nil(t, req.Message().GetData()) ||
assert.Empty(t, req.Message().GetData().GetValue())
})
t.Run("data inside message has priority", func(t *testing.T) {
req := NewInvokeMethodRequest("test_method").
WithRawDataString("nel blu dipinto di blu")
defer req.Close()
// Override
const msg = "felice di stare lassu'"
req.Message().Data = &anypb.Any{Value: []byte(msg)}
data, err := req.RawDataFull()
require.NoError(t, err)
assert.Equal(t, msg, string(data))
_ = assert.NotNil(t, req.Message().GetData()) &&
assert.Equal(t, msg, string(req.Message().GetData().GetValue()))
})
}
func TestHTTPExtension(t *testing.T) {
req := NewInvokeMethodRequest("test_method").
WithHTTPExtension("POST", "query1=value1&query2=value2")
defer req.Close()
assert.Equal(t, commonv1pb.HTTPExtension_POST, req.Message().GetHttpExtension().GetVerb())
assert.Equal(t, "query1=value1&query2=value2", req.EncodeHTTPQueryString())
}
func TestActor(t *testing.T) {
req := NewInvokeMethodRequest("test_method").
WithActor("testActor", "1")
defer req.Close()
assert.Equal(t, "testActor", req.Actor().GetActorType())
assert.Equal(t, "1", req.Actor().GetActorId())
}
func TestRequestProto(t *testing.T) {
t.Run("byte slice", func(t *testing.T) {
m := &commonv1pb.InvokeRequest{
Method: "invoketest",
ContentType: "application/json",
Data: &anypb.Any{Value: []byte("test")},
}
pb := internalv1pb.InternalInvokeRequest{
Ver: internalv1pb.APIVersion_V1,
Message: m,
}
ir, err := FromInternalInvokeRequest(&pb)
require.NoError(t, err)
defer ir.Close()
req2 := ir.Proto()
msg := req2.GetMessage()
assert.Equal(t, "application/json", msg.GetContentType())
require.NotNil(t, msg.GetData())
require.NotNil(t, msg.GetData().GetValue())
assert.Equal(t, []byte("test"), msg.GetData().GetValue())
bData, err := io.ReadAll(ir.RawData())
require.NoError(t, err)
assert.Equal(t, []byte("test"), bData)
})
t.Run("stream", func(t *testing.T) {
m := &commonv1pb.InvokeRequest{
Method: "invoketest",
ContentType: "application/json",
}
pb := internalv1pb.InternalInvokeRequest{
Ver: internalv1pb.APIVersion_V1,
Message: m,
}
ir, err := FromInternalInvokeRequest(&pb)
require.NoError(t, err)
defer ir.Close()
ir.data = newReaderCloser(strings.NewReader("test"))
req2 := ir.Proto()
assert.Equal(t, "application/json", req2.GetMessage().GetContentType())
assert.Nil(t, req2.GetMessage().GetData())
bData, err := io.ReadAll(ir.RawData())
require.NoError(t, err)
assert.Equal(t, []byte("test"), bData)
})
}
func TestRequestProtoWithData(t *testing.T) {
t.Run("byte slice", func(t *testing.T) {
m := &commonv1pb.InvokeRequest{
Method: "invoketest",
ContentType: "application/json",
Data: &anypb.Any{Value: []byte("test")},
}
pb := internalv1pb.InternalInvokeRequest{
Ver: internalv1pb.APIVersion_V1,
Message: m,
}
ir, err := FromInternalInvokeRequest(&pb)
require.NoError(t, err)
defer ir.Close()
req2, err := ir.ProtoWithData()
require.NoError(t, err)
assert.Equal(t, "application/json", req2.GetMessage().GetContentType())
assert.Equal(t, []byte("test"), req2.GetMessage().GetData().GetValue())
})
t.Run("stream", func(t *testing.T) {
m := &commonv1pb.InvokeRequest{
Method: "invoketest",
ContentType: "application/json",
}
pb := internalv1pb.InternalInvokeRequest{
Ver: internalv1pb.APIVersion_V1,
Message: m,
}
ir, err := FromInternalInvokeRequest(&pb)
require.NoError(t, err)
defer ir.Close()
ir.data = newReaderCloser(strings.NewReader("test"))
req2, err := ir.ProtoWithData()
require.NoError(t, err)
assert.Equal(t, "application/json", req2.GetMessage().GetContentType())
assert.Equal(t, []byte("test"), req2.GetMessage().GetData().GetValue())
})
}
func TestAddHeaders(t *testing.T) {
t.Run("single value", func(t *testing.T) {
req := NewInvokeMethodRequest("test_method")
defer req.Close()
header := http.Header{}
header.Add("Dapr-Reentrant-Id", "test")
req.AddMetadata(header)
require.NotNil(t, req.r.GetMetadata())
require.NotNil(t, req.r.GetMetadata()["Dapr-Reentrant-Id"])
require.NotEmpty(t, req.r.GetMetadata()["Dapr-Reentrant-Id"].GetValues())
assert.Equal(t, "test", req.r.GetMetadata()["Dapr-Reentrant-Id"].GetValues()[0])
})
t.Run("multiple values", func(t *testing.T) {
req := NewInvokeMethodRequest("test_method")
defer req.Close()
header := http.Header{}
header.Add("Dapr-Reentrant-Id", "test")
header.Add("Dapr-Reentrant-Id", "test2")
req.AddMetadata(header)
require.NotNil(t, req.r.GetMetadata())
require.NotNil(t, req.r.GetMetadata()["Dapr-Reentrant-Id"])
require.NotEmpty(t, req.r.GetMetadata()["Dapr-Reentrant-Id"].GetValues())
assert.Equal(t, []string{"test", "test2"}, req.r.GetMetadata()["Dapr-Reentrant-Id"].GetValues())
})
t.Run("does not overwrite", func(t *testing.T) {
header := http.Header{}
header.Add("Dapr-Reentrant-Id", "test")
req := NewInvokeMethodRequest("test_method").WithHTTPHeaders(header)
defer req.Close()
header.Set("Dapr-Reentrant-Id", "test2")
req.AddMetadata(header)
require.NotNil(t, req.r.GetMetadata()["Dapr-Reentrant-Id"])
require.NotEmpty(t, req.r.GetMetadata()["Dapr-Reentrant-Id"].GetValues())
assert.Equal(t, "test", req.r.GetMetadata()["Dapr-Reentrant-Id"].GetValues()[0])
})
}
func TestWithCustomHTTPMetadata(t *testing.T) {
customMetadataKey := func(i int) string {
return fmt.Sprintf("customMetadataKey%d", i)
}
customMetadataValue := func(i int) string {
return fmt.Sprintf("customMetadataValue%d", i)
}
numMetadata := 10
md := make(map[string]string, numMetadata)
for i := 0; i < numMetadata; i++ {
md[customMetadataKey(i)] = customMetadataValue(i)
}
req := NewInvokeMethodRequest("test_method").
WithCustomHTTPMetadata(md)
defer req.Close()
imrMd := req.Metadata()
for i := 0; i < numMetadata; i++ {
val, ok := imrMd[customMetadataKey(i)]
assert.True(t, ok)
// We assume only 1 value per key as the input map can only support string -> string mapping.
assert.Equal(t, customMetadataValue(i), val.GetValues()[0])
}
}
func TestWithDataObject(t *testing.T) {
type testData struct {
Str string `json:"str"`
Int int `json:"int"`
}
const expectJSON = `{"str":"mystring","int":42}`
req := NewInvokeMethodRequest("test_method").
WithDataObject(&testData{
Str: "mystring",
Int: 42,
})
got := req.GetDataObject()
require.NotNil(t, got)
gotEnc, err := json.Marshal(got)
require.NoError(t, err)
assert.Equal(t, []byte(expectJSON), compactJSON(t, gotEnc))
data, err := req.RawDataFull()
require.NoError(t, err)
assert.Equal(t, []byte(expectJSON), compactJSON(t, data))
}
func TestRequestReplayable(t *testing.T) {
const message = "Nel mezzo del cammin di nostra vita mi ritrovai per una selva oscura, che' la diritta via era smarrita."
newReplayable := func() *InvokeMethodRequest {
return NewInvokeMethodRequest("test_method").
WithRawData(newReaderCloser(strings.NewReader(message))).
WithReplay(true)
}
t.Run("read once", func(t *testing.T) {
req := newReplayable()
defer req.Close()
require.True(t, req.CanReplay())
t.Run("first read in full", func(t *testing.T) {
read, err := io.ReadAll(req.RawData())
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
t.Run("req.data is EOF", func(t *testing.T) {
buf := make([]byte, 9)
n, err := io.ReadFull(req.data, buf)
assert.Equal(t, 0, n)
assert.Truef(t, errors.Is(err, io.EOF) || errors.Is(err, http.ErrBodyReadAfterClose), "unexpected error: %v", err)
})
t.Run("replay buffer is full", func(t *testing.T) {
assert.Len(t, message, req.replay.Len())
read, err := io.ReadAll(bytes.NewReader(req.replay.Bytes()))
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
t.Run("close request", func(t *testing.T) {
err := req.Close()
require.NoError(t, err)
assert.Nil(t, req.data)
assert.Nil(t, req.replay)
})
})
t.Run("read in full three times", func(t *testing.T) {
req := newReplayable()
defer req.Close()
t.Run("first read in full", func(t *testing.T) {
read, err := io.ReadAll(req.RawData())
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
t.Run("req.data is EOF", func(t *testing.T) {
buf := make([]byte, 9)
n, err := io.ReadFull(req.data, buf)
assert.Equal(t, 0, n)
assert.Truef(t, errors.Is(err, io.EOF) || errors.Is(err, http.ErrBodyReadAfterClose), "unexpected error: %v", err)
})
t.Run("replay buffer is full", func(t *testing.T) {
assert.Len(t, message, req.replay.Len())
read, err := io.ReadAll(bytes.NewReader(req.replay.Bytes()))
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
t.Run("second read in full", func(t *testing.T) {
read, err := io.ReadAll(req.RawData())
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
t.Run("third read in full", func(t *testing.T) {
read, err := io.ReadAll(req.RawData())
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
t.Run("close request", func(t *testing.T) {
err := req.Close()
require.NoError(t, err)
assert.Nil(t, req.data)
assert.Nil(t, req.replay)
})
})
t.Run("read in full, then partial read", func(t *testing.T) {
req := newReplayable()
defer req.Close()
t.Run("first read in full", func(t *testing.T) {
read, err := io.ReadAll(req.RawData())
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
r := req.RawData()
t.Run("second, partial read", func(t *testing.T) {
buf := make([]byte, 9)
n, err := io.ReadFull(r, buf)
require.NoError(t, err)
assert.Equal(t, 9, n)
assert.Equal(t, message[:9], string(buf))
})
t.Run("read rest", func(t *testing.T) {
read, err := io.ReadAll(r)
require.NoError(t, err)
assert.Len(t, read, len(message)-9)
// Continue from byte 9
assert.Equal(t, message[9:], string(read))
})
t.Run("second read in full", func(t *testing.T) {
read, err := req.RawDataFull()
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
t.Run("close request", func(t *testing.T) {
err := req.Close()
require.NoError(t, err)
assert.Nil(t, req.data)
assert.Nil(t, req.replay)
})
})
t.Run("partial read, then read in full", func(t *testing.T) {
req := newReplayable()
defer req.Close()
t.Run("first, partial read", func(t *testing.T) {
buf := make([]byte, 9)
n, err := io.ReadFull(req.RawData(), buf)
require.NoError(t, err)
assert.Equal(t, 9, n)
assert.Equal(t, message[:9], string(buf))
})
t.Run("replay buffer has partial data", func(t *testing.T) {
assert.Equal(t, 9, req.replay.Len())
read, err := io.ReadAll(bytes.NewReader(req.replay.Bytes()))
require.NoError(t, err)
assert.Equal(t, message[:9], string(read))
})
t.Run("second read in full", func(t *testing.T) {
read, err := io.ReadAll(req.RawData())
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
t.Run("req.data is EOF", func(t *testing.T) {
buf := make([]byte, 9)
n, err := io.ReadFull(req.data, buf)
assert.Equal(t, 0, n)
assert.Truef(t, errors.Is(err, io.EOF) || errors.Is(err, http.ErrBodyReadAfterClose), "unexpected error: %v", err)
})
t.Run("replay buffer is full", func(t *testing.T) {
assert.Len(t, message, req.replay.Len())
read, err := io.ReadAll(bytes.NewReader(req.replay.Bytes()))
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
t.Run("third read in full", func(t *testing.T) {
read, err := io.ReadAll(req.RawData())
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
t.Run("close request", func(t *testing.T) {
err := req.Close()
require.NoError(t, err)
assert.Nil(t, req.data)
assert.Nil(t, req.replay)
})
})
t.Run("get ProtoWithData twice", func(t *testing.T) {
req := newReplayable()
defer req.Close()
t.Run("first ProtoWithData request", func(t *testing.T) {
pb, err := req.ProtoWithData()
require.NoError(t, err)
require.NotNil(t, pb)
require.NotNil(t, pb.GetMessage())
require.NotNil(t, pb.GetMessage().GetData())
assert.Equal(t, message, string(pb.GetMessage().GetData().GetValue()))
})
t.Run("second ProtoWithData request", func(t *testing.T) {
pb, err := req.ProtoWithData()
require.NoError(t, err)
require.NotNil(t, pb)
require.NotNil(t, pb.GetMessage())
require.NotNil(t, pb.GetMessage().GetData())
assert.Equal(t, message, string(pb.GetMessage().GetData().GetValue()))
})
t.Run("close request", func(t *testing.T) {
err := req.Close()
require.NoError(t, err)
assert.Nil(t, req.data)
assert.Nil(t, req.replay)
})
})
}
func TestDataTypeUrl(t *testing.T) {
t.Run("preserve type URL from proto", func(t *testing.T) {
const (
message = "cerco l'estate tutto l'anno"
typeURL = "testurl"
)
pb := &commonv1pb.InvokeRequest{
Method: "frominvokerequestmessage",
Data: &anypb.Any{
Value: []byte(message),
TypeUrl: typeURL,
},
}
req := FromInvokeRequestMessage(pb).
WithContentType("text/plain") // Should be ignored
defer req.Close()
pd, err := req.ProtoWithData()
require.NoError(t, err)
require.NotNil(t, pd.GetMessage().GetData())
assert.Equal(t, message, string(pd.GetMessage().GetData().GetValue()))
assert.Equal(t, typeURL, pd.GetMessage().GetData().GetTypeUrl())
// Content type should be the protobuf one
assert.Equal(t, ProtobufContentType, req.ContentType())
})
t.Run("set type URL in message", func(t *testing.T) {
const (
message = "e all'improvviso eccola qua"
typeURL = "testurl"
)
req := NewInvokeMethodRequest("test_method").
WithContentType("text/plain"). // Should be ignored
WithRawDataString(message).
WithDataTypeURL(typeURL)
defer req.Close()
pd, err := req.ProtoWithData()
require.NoError(t, err)
require.NotNil(t, pd.GetMessage().GetData())
assert.Equal(t, message, string(pd.GetMessage().GetData().GetValue()))
assert.Equal(t, typeURL, pd.GetMessage().GetData().GetTypeUrl())
// Content type should be the protobuf one
assert.Equal(t, ProtobufContentType, req.ContentType())
})
}
func compactJSON(t *testing.T, data []byte) []byte {
out := &bytes.Buffer{}
err := json.Compact(out, data)
require.NoError(t, err)
return out.Bytes()
}
|
mikeee/dapr
|
pkg/messaging/v1/invoke_method_request_test.go
|
GO
|
mit
| 22,248 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
"bytes"
"errors"
"io"
"strings"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/metadata"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/anypb"
commonv1pb "github.com/dapr/dapr/pkg/proto/common/v1"
internalv1pb "github.com/dapr/dapr/pkg/proto/internals/v1"
)
// InvokeMethodResponse holds InternalInvokeResponse protobuf message
// and provides the helpers to manage it.
type InvokeMethodResponse struct {
replayableRequest
r *internalv1pb.InternalInvokeResponse
dataTypeURL string
}
// NewInvokeMethodResponse returns new InvokeMethodResponse object with status.
func NewInvokeMethodResponse(statusCode int32, statusMessage string, statusDetails []*anypb.Any) *InvokeMethodResponse {
return &InvokeMethodResponse{
r: &internalv1pb.InternalInvokeResponse{
Status: &internalv1pb.Status{Code: statusCode, Message: statusMessage, Details: statusDetails},
Message: &commonv1pb.InvokeResponse{},
},
}
}
// InternalInvokeResponse returns InvokeMethodResponse for InternalInvokeResponse pb to use the helpers.
func InternalInvokeResponse(pb *internalv1pb.InternalInvokeResponse) (*InvokeMethodResponse, error) {
rsp := &InvokeMethodResponse{r: pb}
if pb.GetMessage() == nil {
pb.Message = &commonv1pb.InvokeResponse{Data: nil}
}
if pb.GetHeaders() == nil {
pb.Headers = map[string]*internalv1pb.ListStringValue{}
}
return rsp, nil
}
// WithMessage sets InvokeResponse pb object to Message field.
func (imr *InvokeMethodResponse) WithMessage(pb *commonv1pb.InvokeResponse) *InvokeMethodResponse {
imr.r.Message = pb
return imr
}
// WithRawData sets message data from a readable stream.
func (imr *InvokeMethodResponse) WithRawData(data io.Reader) *InvokeMethodResponse {
imr.ResetMessageData()
imr.replayableRequest.WithRawData(data)
return imr
}
// WithRawDataBytes sets message data from a []byte.
func (imr *InvokeMethodResponse) WithRawDataBytes(data []byte) *InvokeMethodResponse {
return imr.WithRawData(bytes.NewReader(data))
}
// WithRawDataString sets message data from a string.
func (imr *InvokeMethodResponse) WithRawDataString(data string) *InvokeMethodResponse {
return imr.WithRawData(strings.NewReader(data))
}
// WithContentType sets the content type.
func (imr *InvokeMethodResponse) WithContentType(contentType string) *InvokeMethodResponse {
imr.r.Message.ContentType = contentType
return imr
}
// WithDataTypeURL sets the type_url property for the data.
// When a type_url is set, the Content-Type automatically becomes the protobuf one.
func (imr *InvokeMethodResponse) WithDataTypeURL(val string) *InvokeMethodResponse {
imr.dataTypeURL = val
return imr
}
// WithHeaders sets gRPC response header metadata.
func (imr *InvokeMethodResponse) WithHeaders(headers metadata.MD) *InvokeMethodResponse {
imr.r.Headers = internalv1pb.MetadataToInternalMetadata(headers)
return imr
}
// WithFastHTTPHeaders populates HTTP response header to gRPC header metadata.
func (imr *InvokeMethodResponse) WithHTTPHeaders(headers map[string][]string) *InvokeMethodResponse {
imr.r.Headers = internalv1pb.MetadataToInternalMetadata(headers)
return imr
}
// WithFastHTTPHeaders populates fasthttp response header to gRPC header metadata.
func (imr *InvokeMethodResponse) WithFastHTTPHeaders(header *fasthttp.ResponseHeader) *InvokeMethodResponse {
md := internalv1pb.FastHTTPHeadersToInternalMetadata(header)
if len(md) > 0 {
imr.r.Headers = md
}
return imr
}
// WithTrailers sets Trailer in internal InvokeMethodResponse.
func (imr *InvokeMethodResponse) WithTrailers(trailer metadata.MD) *InvokeMethodResponse {
imr.r.Trailers = internalv1pb.MetadataToInternalMetadata(trailer)
return imr
}
// WithReplay enables replaying for the data stream.
func (imr *InvokeMethodResponse) WithReplay(enabled bool) *InvokeMethodResponse {
// If the object has data in-memory, WithReplay is a nop
if !imr.HasMessageData() {
imr.replayableRequest.SetReplay(enabled)
}
return imr
}
// CanReplay returns true if the data stream can be replayed.
func (imr *InvokeMethodResponse) CanReplay() bool {
// We can replay if:
// - The object has data in-memory
// - The request is replayable
return imr.HasMessageData() || imr.replayableRequest.CanReplay()
}
// Status gets Response status.
func (imr *InvokeMethodResponse) Status() *internalv1pb.Status {
if imr.r == nil {
return nil
}
return imr.r.GetStatus()
}
// IsHTTPResponse returns true if response status code is http response status.
func (imr *InvokeMethodResponse) IsHTTPResponse() bool {
if imr.r == nil {
return false
}
// gRPC status code <= 15 - https://github.com/grpc/grpc/blob/master/doc/statuscodes.md
// HTTP status code >= 100 - https://tools.ietf.org/html/rfc2616#section-10
return imr.r.GetStatus().GetCode() >= 100
}
// Proto returns the internal InvokeMethodResponse Proto object.
func (imr *InvokeMethodResponse) Proto() *internalv1pb.InternalInvokeResponse {
return imr.r
}
// ProtoWithData returns a copy of the internal InternalInvokeResponse Proto object with the entire data stream read into the Data property.
func (imr *InvokeMethodResponse) ProtoWithData() (*internalv1pb.InternalInvokeResponse, error) {
if imr.r == nil {
return nil, errors.New("message is nil")
}
// If the data is already in-memory in the object, return the object directly.
// This doesn't copy the object, and that's fine because receivers are not expected to modify the received object.
// Only reason for cloning the object below is to make ProtoWithData concurrency-safe.
if imr.HasMessageData() {
return imr.r, nil
}
// Clone the object
m := proto.Clone(imr.r).(*internalv1pb.InternalInvokeResponse)
// Read the data and store it in the object
data, err := imr.RawDataFull()
if err != nil || len(data) == 0 {
return m, err
}
m.Message.Data = &anypb.Any{
Value: data,
TypeUrl: imr.dataTypeURL, // Could be empty
}
return m, nil
}
// Headers gets Headers metadata.
func (imr *InvokeMethodResponse) Headers() DaprInternalMetadata {
if imr.r == nil {
return nil
}
return imr.r.GetHeaders()
}
// Trailers gets Trailers metadata.
func (imr *InvokeMethodResponse) Trailers() DaprInternalMetadata {
if imr.r == nil {
return nil
}
return imr.r.GetTrailers()
}
// Message returns message field in InvokeMethodResponse.
func (imr *InvokeMethodResponse) Message() *commonv1pb.InvokeResponse {
if imr.r == nil {
return nil
}
return imr.r.GetMessage()
}
// HasMessageData returns true if the message object contains a slice of data buffered.
func (imr *InvokeMethodResponse) HasMessageData() bool {
m := imr.r.GetMessage()
return len(m.GetData().GetValue()) > 0
}
// ResetMessageData resets the data inside the message object if present.
func (imr *InvokeMethodResponse) ResetMessageData() {
if !imr.HasMessageData() {
return
}
imr.r.GetMessage().GetData().Reset()
}
// ContentType returns the content type of the message.
func (imr *InvokeMethodResponse) ContentType() string {
m := imr.r.GetMessage()
if m == nil {
return ""
}
contentType := m.GetContentType()
// If there's a proto data and that has a type URL, or if we have a dataTypeUrl in the object, then the content type is the protobuf one
if imr.dataTypeURL != "" || m.GetData().GetTypeUrl() != "" {
return ProtobufContentType
}
return contentType
}
// RawData returns the stream body.
func (imr *InvokeMethodResponse) RawData() (r io.Reader) {
// If the message has a data property, use that
if imr.HasMessageData() {
// HasMessageData() guarantees that the `imr.r.Message` and `imr.r.Message.Data` is not nil
return bytes.NewReader(imr.r.GetMessage().GetData().GetValue())
}
return imr.replayableRequest.RawData()
}
// RawDataFull returns the entire data read from the stream body.
func (imr *InvokeMethodResponse) RawDataFull() ([]byte, error) {
// If the message has a data property, use that
if imr.HasMessageData() {
return imr.r.GetMessage().GetData().GetValue(), nil
}
r := imr.RawData()
if r == nil {
return nil, nil
}
return io.ReadAll(r)
}
|
mikeee/dapr
|
pkg/messaging/v1/invoke_method_response.go
|
GO
|
mit
| 8,659 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
"bytes"
"io"
"net/http"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
"google.golang.org/protobuf/types/known/anypb"
commonv1pb "github.com/dapr/dapr/pkg/proto/common/v1"
internalv1pb "github.com/dapr/dapr/pkg/proto/internals/v1"
)
func TestInvocationResponse(t *testing.T) {
resp := NewInvokeMethodResponse(0, "OK", nil)
defer resp.Close()
assert.Equal(t, int32(0), resp.r.GetStatus().GetCode())
assert.Equal(t, "OK", resp.r.GetStatus().GetMessage())
assert.NotNil(t, resp.r.GetMessage())
}
func TestInternalInvocationResponse(t *testing.T) {
t.Run("valid internal invoke response with no data", func(t *testing.T) {
m := &commonv1pb.InvokeResponse{
Data: nil,
ContentType: "application/json",
}
pb := internalv1pb.InternalInvokeResponse{
Status: &internalv1pb.Status{Code: 0},
Message: m,
}
ir, err := InternalInvokeResponse(&pb)
require.NoError(t, err)
defer ir.Close()
assert.NotNil(t, ir.r.GetMessage())
assert.Equal(t, int32(0), ir.r.GetStatus().GetCode())
assert.Nil(t, ir.r.GetMessage().GetData())
bData, err := io.ReadAll(ir.RawData())
require.NoError(t, err)
assert.Empty(t, bData)
})
t.Run("valid internal invoke response with data", func(t *testing.T) {
m := &commonv1pb.InvokeResponse{
Data: &anypb.Any{Value: []byte("test")},
ContentType: "application/json",
}
pb := internalv1pb.InternalInvokeResponse{
Status: &internalv1pb.Status{Code: 0},
Message: m,
}
ir, err := InternalInvokeResponse(&pb)
require.NoError(t, err)
defer ir.Close()
assert.NotNil(t, ir.r.GetMessage())
assert.Equal(t, int32(0), ir.r.GetStatus().GetCode())
require.NotNil(t, ir.r.GetMessage().GetData())
require.NotNil(t, ir.r.GetMessage().GetData().GetValue())
assert.Equal(t, []byte("test"), ir.r.GetMessage().GetData().GetValue())
bData, err := io.ReadAll(ir.RawData())
require.NoError(t, err)
assert.Equal(t, "test", string(bData))
})
t.Run("Message is nil", func(t *testing.T) {
pb := internalv1pb.InternalInvokeResponse{
Status: &internalv1pb.Status{Code: 0},
Message: nil,
}
ir, err := InternalInvokeResponse(&pb)
require.NoError(t, err)
defer ir.Close()
assert.NotNil(t, ir.r.GetMessage())
assert.Nil(t, ir.r.GetMessage().GetData())
})
}
func TestResponseData(t *testing.T) {
t.Run("contenttype is set", func(t *testing.T) {
resp := NewInvokeMethodResponse(0, "OK", nil).
WithRawDataString("test").
WithContentType("application/json")
defer resp.Close()
bData, err := io.ReadAll(resp.RawData())
require.NoError(t, err)
contentType := resp.r.GetMessage().GetContentType()
assert.Equal(t, "application/json", contentType)
assert.Equal(t, "test", string(bData))
})
t.Run("contenttype is unset", func(t *testing.T) {
resp := NewInvokeMethodResponse(0, "OK", nil).
WithRawDataString("test")
defer resp.Close()
contentType := resp.ContentType()
bData, err := io.ReadAll(resp.RawData())
require.NoError(t, err)
assert.Equal(t, "", resp.r.GetMessage().GetContentType())
assert.Equal(t, "", contentType)
assert.Equal(t, "test", string(bData))
})
t.Run("typeurl is set but content_type is unset", func(t *testing.T) {
s := &commonv1pb.StateItem{Key: "custom_key"}
b, err := anypb.New(s)
require.NoError(t, err)
resp := NewInvokeMethodResponse(0, "OK", nil)
defer resp.Close()
resp.r.Message.Data = b
contentType := resp.ContentType()
bData, err := io.ReadAll(resp.RawData())
require.NoError(t, err)
assert.Equal(t, ProtobufContentType, contentType)
assert.Equal(t, b.GetValue(), bData)
})
}
func TestResponseRawData(t *testing.T) {
t.Run("message is nil", func(t *testing.T) {
req := &InvokeMethodResponse{
r: &internalv1pb.InternalInvokeResponse{},
}
r := req.RawData()
bData, err := io.ReadAll(r)
require.NoError(t, err)
assert.Empty(t, bData)
})
t.Run("return data from stream", func(t *testing.T) {
req := NewInvokeMethodResponse(0, "OK", nil).
WithRawDataString("nel blu dipinto di blu")
defer req.Close()
r := req.RawData()
bData, err := io.ReadAll(r)
require.NoError(t, err)
assert.Equal(t, "nel blu dipinto di blu", string(bData))
_ = assert.Nil(t, req.Message().GetData()) ||
assert.Empty(t, req.Message().GetData().GetValue())
})
t.Run("data inside message has priority", func(t *testing.T) {
req := NewInvokeMethodResponse(0, "OK", nil).
WithRawDataString("nel blu dipinto di blu")
defer req.Close()
// Override
const msg = "felice di stare lassu'"
req.Message().Data = &anypb.Any{Value: []byte(msg)}
r := req.RawData()
bData, err := io.ReadAll(r)
require.NoError(t, err)
assert.Equal(t, msg, string(bData))
_ = assert.NotNil(t, req.Message().GetData()) &&
assert.Equal(t, msg, string(req.Message().GetData().GetValue()))
})
}
func TestResponseRawDataFull(t *testing.T) {
t.Run("message is nil", func(t *testing.T) {
req := &InvokeMethodResponse{
r: &internalv1pb.InternalInvokeResponse{},
}
data, err := req.RawDataFull()
require.NoError(t, err)
assert.Empty(t, data)
})
t.Run("return data from stream", func(t *testing.T) {
req := NewInvokeMethodResponse(0, "OK", nil).
WithRawDataString("nel blu dipinto di blu")
defer req.Close()
data, err := req.RawDataFull()
require.NoError(t, err)
assert.Equal(t, "nel blu dipinto di blu", string(data))
_ = assert.Nil(t, req.Message().GetData()) ||
assert.Empty(t, req.Message().GetData().GetValue())
})
t.Run("data inside message has priority", func(t *testing.T) {
req := NewInvokeMethodResponse(0, "OK", nil).
WithRawDataString("nel blu dipinto di blu")
defer req.Close()
// Override
const msg = "felice di stare lassu'"
req.Message().Data = &anypb.Any{Value: []byte(msg)}
data, err := req.RawDataFull()
require.NoError(t, err)
assert.Equal(t, msg, string(data))
_ = assert.NotNil(t, req.Message().GetData()) &&
assert.Equal(t, msg, string(req.Message().GetData().GetValue()))
})
}
func TestResponseProto(t *testing.T) {
t.Run("byte slice", func(t *testing.T) {
m := &commonv1pb.InvokeResponse{
Data: &anypb.Any{Value: []byte("test")},
ContentType: "application/json",
}
pb := internalv1pb.InternalInvokeResponse{
Status: &internalv1pb.Status{Code: 0},
Message: m,
}
ir, err := InternalInvokeResponse(&pb)
require.NoError(t, err)
defer ir.Close()
req2 := ir.Proto()
msg := req2.GetMessage()
assert.Equal(t, "application/json", msg.GetContentType())
require.NotNil(t, msg.GetData())
require.NotNil(t, msg.GetData().GetValue())
assert.Equal(t, []byte("test"), msg.GetData().GetValue())
bData, err := io.ReadAll(ir.RawData())
require.NoError(t, err)
assert.Equal(t, []byte("test"), bData)
})
t.Run("stream", func(t *testing.T) {
m := &commonv1pb.InvokeResponse{
ContentType: "application/json",
}
pb := internalv1pb.InternalInvokeResponse{
Status: &internalv1pb.Status{Code: 0},
Message: m,
}
ir, err := InternalInvokeResponse(&pb)
require.NoError(t, err)
defer ir.Close()
ir.data = io.NopCloser(strings.NewReader("test"))
req2 := ir.Proto()
assert.Equal(t, "application/json", req2.GetMessage().GetContentType())
assert.Nil(t, req2.GetMessage().GetData())
bData, err := io.ReadAll(ir.RawData())
require.NoError(t, err)
assert.Equal(t, []byte("test"), bData)
})
}
func TestResponseProtoWithData(t *testing.T) {
t.Run("not return error when status exist with empty message", func(t *testing.T) {
pb := internalv1pb.InternalInvokeResponse{
Status: &internalv1pb.Status{Code: int32(codes.Unimplemented), Message: "method unimplemented"},
Message: &commonv1pb.InvokeResponse{},
}
ir, err := InternalInvokeResponse(&pb)
require.NoError(t, err)
defer ir.Close()
_, err = ir.ProtoWithData()
require.NoError(t, err)
})
t.Run("byte slice", func(t *testing.T) {
m := &commonv1pb.InvokeResponse{
Data: &anypb.Any{Value: []byte("test")},
ContentType: "application/json",
}
pb := internalv1pb.InternalInvokeResponse{
Status: &internalv1pb.Status{Code: 0},
Message: m,
}
ir, err := InternalInvokeResponse(&pb)
require.NoError(t, err)
defer ir.Close()
req2, err := ir.ProtoWithData()
require.NoError(t, err)
assert.Equal(t, "application/json", req2.GetMessage().GetContentType())
assert.Equal(t, []byte("test"), req2.GetMessage().GetData().GetValue())
})
t.Run("stream", func(t *testing.T) {
m := &commonv1pb.InvokeResponse{
ContentType: "application/json",
}
pb := internalv1pb.InternalInvokeResponse{
Status: &internalv1pb.Status{Code: 0},
Message: m,
}
ir, err := InternalInvokeResponse(&pb)
require.NoError(t, err)
defer ir.Close()
ir.data = io.NopCloser(strings.NewReader("test"))
req2, err := ir.ProtoWithData()
require.NoError(t, err)
assert.Equal(t, "application/json", req2.GetMessage().GetContentType())
assert.Equal(t, []byte("test"), req2.GetMessage().GetData().GetValue())
})
}
func TestResponseHeader(t *testing.T) {
t.Run("gRPC headers", func(t *testing.T) {
md := map[string][]string{
"test1": {"val1", "val2"},
"test2": {"val3", "val4"},
}
imr := NewInvokeMethodResponse(0, "OK", nil).
WithHeaders(md)
defer imr.Close()
mheader := imr.Headers()
assert.Equal(t, "val1", mheader["test1"].GetValues()[0])
assert.Equal(t, "val2", mheader["test1"].GetValues()[1])
assert.Equal(t, "val3", mheader["test2"].GetValues()[0])
assert.Equal(t, "val4", mheader["test2"].GetValues()[1])
})
t.Run("HTTP headers", func(t *testing.T) {
headers := http.Header{}
headers.Set("Header1", "Value1")
headers.Set("Header2", "Value2")
headers.Set("Header3", "Value3")
headers.Add("Multi", "foo")
headers.Add("Multi", "bar")
imr := NewInvokeMethodResponse(0, "OK", nil).
WithHTTPHeaders(headers)
defer imr.Close()
mheader := imr.Headers()
require.NotEmpty(t, mheader)
require.NotEmpty(t, mheader["Header1"])
assert.Equal(t, "Value1", mheader["Header1"].GetValues()[0])
require.NotEmpty(t, mheader["Header2"])
assert.Equal(t, "Value2", mheader["Header2"].GetValues()[0])
require.NotEmpty(t, mheader["Header3"])
assert.Equal(t, "Value3", mheader["Header3"].GetValues()[0])
require.NotEmpty(t, mheader["Multi"])
assert.Equal(t, []string{"foo", "bar"}, mheader["Multi"].GetValues())
})
}
func TestResponseTrailer(t *testing.T) {
md := map[string][]string{
"test1": {"val1", "val2"},
"test2": {"val3", "val4"},
}
resp := NewInvokeMethodResponse(0, "OK", nil).
WithTrailers(md)
defer resp.Close()
mheader := resp.Trailers()
assert.Equal(t, "val1", mheader["test1"].GetValues()[0])
assert.Equal(t, "val2", mheader["test1"].GetValues()[1])
assert.Equal(t, "val3", mheader["test2"].GetValues()[0])
assert.Equal(t, "val4", mheader["test2"].GetValues()[1])
}
func TestIsHTTPResponse(t *testing.T) {
t.Run("gRPC response status", func(t *testing.T) {
imr := NewInvokeMethodResponse(int32(codes.OK), "OK", nil)
defer imr.Close()
assert.False(t, imr.IsHTTPResponse())
})
t.Run("HTTP response status", func(t *testing.T) {
imr := NewInvokeMethodResponse(http.StatusOK, "OK", nil)
defer imr.Close()
assert.True(t, imr.IsHTTPResponse())
})
}
func TestResponseReplayable(t *testing.T) {
const message = "Nel mezzo del cammin di nostra vita mi ritrovai per una selva oscura, che' la diritta via era smarrita."
newReplayable := func() *InvokeMethodResponse {
m := &commonv1pb.InvokeResponse{
Data: &anypb.Any{Value: []byte("test")},
ContentType: "application/json",
}
pb := internalv1pb.InternalInvokeResponse{
Status: &internalv1pb.Status{Code: 0},
Message: m,
}
res, _ := InternalInvokeResponse(&pb)
return res.
WithRawDataString(message).
WithReplay(true)
}
t.Run("read once", func(t *testing.T) {
res := newReplayable()
defer res.Close()
require.True(t, res.CanReplay())
t.Run("first read in full", func(t *testing.T) {
read, err := io.ReadAll(res.RawData())
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
t.Run("req.data is EOF", func(t *testing.T) {
buf := make([]byte, 9)
n, err := io.ReadFull(res.data, buf)
assert.Equal(t, 0, n)
require.ErrorIs(t, err, io.EOF)
})
t.Run("replay buffer is full", func(t *testing.T) {
assert.Len(t, message, res.replay.Len())
read, err := io.ReadAll(bytes.NewReader(res.replay.Bytes()))
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
t.Run("close response", func(t *testing.T) {
err := res.Close()
require.NoError(t, err)
assert.Nil(t, res.data)
assert.Nil(t, res.replay)
})
})
t.Run("read in full three times", func(t *testing.T) {
res := newReplayable()
defer res.Close()
t.Run("first read in full", func(t *testing.T) {
read, err := io.ReadAll(res.RawData())
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
t.Run("req.data is EOF", func(t *testing.T) {
buf := make([]byte, 9)
n, err := io.ReadFull(res.data, buf)
assert.Equal(t, 0, n)
require.ErrorIs(t, err, io.EOF)
})
t.Run("replay buffer is full", func(t *testing.T) {
assert.Len(t, message, res.replay.Len())
read, err := io.ReadAll(bytes.NewReader(res.replay.Bytes()))
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
t.Run("second read in full", func(t *testing.T) {
read, err := io.ReadAll(res.RawData())
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
t.Run("third read in full", func(t *testing.T) {
read, err := io.ReadAll(res.RawData())
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
t.Run("close response", func(t *testing.T) {
err := res.Close()
require.NoError(t, err)
assert.Nil(t, res.data)
assert.Nil(t, res.replay)
})
})
t.Run("read in full, then partial read", func(t *testing.T) {
res := newReplayable()
defer res.Close()
t.Run("first read in full", func(t *testing.T) {
read, err := io.ReadAll(res.RawData())
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
r := res.RawData()
t.Run("second, partial read", func(t *testing.T) {
buf := make([]byte, 9)
n, err := io.ReadFull(r, buf)
require.NoError(t, err)
assert.Equal(t, 9, n)
assert.Equal(t, message[:9], string(buf))
})
t.Run("read rest", func(t *testing.T) {
read, err := io.ReadAll(r)
require.NoError(t, err)
assert.Len(t, read, len(message)-9)
// Continue from byte 9
assert.Equal(t, message[9:], string(read))
})
t.Run("second read in full", func(t *testing.T) {
read, err := res.RawDataFull()
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
t.Run("close response", func(t *testing.T) {
err := res.Close()
require.NoError(t, err)
assert.Nil(t, res.data)
assert.Nil(t, res.replay)
})
})
t.Run("partial read, then read in full", func(t *testing.T) {
res := newReplayable()
defer res.Close()
t.Run("first, partial read", func(t *testing.T) {
buf := make([]byte, 9)
n, err := io.ReadFull(res.RawData(), buf)
require.NoError(t, err)
assert.Equal(t, 9, n)
assert.Equal(t, message[:9], string(buf))
})
t.Run("replay buffer has partial data", func(t *testing.T) {
assert.Equal(t, 9, res.replay.Len())
read, err := io.ReadAll(bytes.NewReader(res.replay.Bytes()))
require.NoError(t, err)
assert.Equal(t, message[:9], string(read))
})
t.Run("second read in full", func(t *testing.T) {
read, err := io.ReadAll(res.RawData())
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
t.Run("req.data is EOF", func(t *testing.T) {
buf := make([]byte, 9)
n, err := io.ReadFull(res.data, buf)
assert.Equal(t, 0, n)
require.ErrorIs(t, err, io.EOF)
})
t.Run("replay buffer is full", func(t *testing.T) {
assert.Len(t, message, res.replay.Len())
read, err := io.ReadAll(bytes.NewReader(res.replay.Bytes()))
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
t.Run("third read in full", func(t *testing.T) {
read, err := io.ReadAll(res.RawData())
require.NoError(t, err)
assert.Equal(t, message, string(read))
})
t.Run("close response", func(t *testing.T) {
err := res.Close()
require.NoError(t, err)
assert.Nil(t, res.data)
assert.Nil(t, res.replay)
})
})
t.Run("get ProtoWithData twice", func(t *testing.T) {
res := newReplayable()
defer res.Close()
t.Run("first ProtoWithData response", func(t *testing.T) {
pb, err := res.ProtoWithData()
require.NoError(t, err)
assert.NotNil(t, pb)
assert.NotNil(t, pb.GetMessage())
assert.NotNil(t, pb.GetMessage().GetData())
assert.Equal(t, message, string(pb.GetMessage().GetData().GetValue()))
})
t.Run("second ProtoWithData response", func(t *testing.T) {
pb, err := res.ProtoWithData()
require.NoError(t, err)
assert.NotNil(t, pb)
assert.NotNil(t, pb.GetMessage())
assert.NotNil(t, pb.GetMessage().GetData())
assert.Equal(t, message, string(pb.GetMessage().GetData().GetValue()))
})
t.Run("close response", func(t *testing.T) {
err := res.Close()
require.NoError(t, err)
assert.Nil(t, res.data)
assert.Nil(t, res.replay)
})
})
}
|
mikeee/dapr
|
pkg/messaging/v1/invoke_method_response_test.go
|
GO
|
mit
| 17,943 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
"context"
)
// DirectMessaging is the API interface for invoking a remote app.
type DirectMessaging interface {
Invoke(ctx context.Context, targetAppID string, req *InvokeMethodRequest) (*InvokeMethodResponse, error)
}
|
mikeee/dapr
|
pkg/messaging/v1/messaging.go
|
GO
|
mit
| 804 |
/*
Copyright 2022 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
"bytes"
"io"
"sync"
"github.com/dapr/kit/byteslicepool"
streamutils "github.com/dapr/kit/streams"
)
// Minimum capacity for the slices is 2KB
const minByteSliceCapacity = 2 << 10
// Contain pools of *bytes.Buffer and []byte objects.
// Used to reduce the number of allocations in replayableRequest for buffers and relieve pressure on the GC.
var (
bufPool = sync.Pool{New: newBuffer}
bsPool = byteslicepool.NewByteSlicePool(minByteSliceCapacity)
)
func newBuffer() any {
return new(bytes.Buffer)
}
// replayableRequest is implemented by InvokeMethodRequest and InvokeMethodResponse
type replayableRequest struct {
data io.Reader
replay *bytes.Buffer
lock sync.Mutex
currentTeeReader *streamutils.TeeReadCloser
currentData []byte
}
// WithRawData sets message data.
func (rr *replayableRequest) WithRawData(data io.Reader) {
rr.lock.Lock()
defer rr.lock.Unlock()
if rr.replay != nil {
// We are panicking here because we can't return errors
// This is just to catch issues during development however, and will never happen at runtime
panic("WithRawData cannot be invoked after replaying has been enabled")
}
rr.data = data
}
// SetReplay enables replaying for the data stream.
func (rr *replayableRequest) SetReplay(enabled bool) {
rr.lock.Lock()
defer rr.lock.Unlock()
if !enabled {
rr.closeReplay()
} else if rr.replay == nil {
rr.replay = bufPool.Get().(*bytes.Buffer)
rr.replay.Reset()
}
}
// CanReplay returns true if the data stream can be replayed.
func (rr *replayableRequest) CanReplay() bool {
return rr.replay != nil
}
// RawData returns the stream body.
func (rr *replayableRequest) RawData() (r io.Reader) {
rr.lock.Lock()
defer rr.lock.Unlock()
// If there's a previous TeeReadCloser, stop it so readers won't add more data into its replay buffer
if rr.currentTeeReader != nil {
_ = rr.currentTeeReader.Stop()
}
if rr.data == nil {
// If there's no data, and there's never been, just return a reader with no data
r = bytes.NewReader(nil)
} else if rr.replay != nil {
// If there's replaying enabled, we need to create a new TeeReadCloser
// We need to copy the data read insofar from the reply buffer because the buffer becomes invalid after new data is written into the it, then reset the buffer
l := rr.replay.Len()
// Get a new byte slice from the pool if we don't have one, and ensure it has enough capacity
if rr.currentData == nil {
rr.currentData = bsPool.Get(l)
}
rr.currentData = bsPool.Resize(rr.currentData, l)
// Copy the data from the replay buffer into the byte slice
copy(rr.currentData[0:l], rr.replay.Bytes())
rr.replay.Reset()
// Create a new TeeReadCloser that reads from the previously-read data and then the data not yet processed
// The TeeReadCloser also keeps all the data it reads into the replay buffer
mr := streamutils.NewMultiReaderCloser(
bytes.NewReader(rr.currentData[0:l]),
rr.data,
)
rr.currentTeeReader = streamutils.NewTeeReadCloser(mr, rr.replay)
r = rr.currentTeeReader
} else {
// No replay enabled
r = rr.data
}
return r
}
func (rr *replayableRequest) closeReplay() {
// Return the buffer and byte slice to the pools if we got one
if rr.replay != nil {
bufPool.Put(rr.replay)
rr.replay = nil
}
if rr.currentData != nil {
bsPool.Put(rr.currentData)
rr.currentData = nil
}
}
// Close the data stream and replay buffers.
// It's safe to call Close multiple times on the same object.
func (rr *replayableRequest) Close() (err error) {
rr.lock.Lock()
defer rr.lock.Unlock()
rr.closeReplay()
if rr.data != nil {
if rc, ok := rr.data.(io.Closer); ok {
err = rc.Close()
if err != nil {
return err
}
}
rr.data = nil
}
return nil
}
|
mikeee/dapr
|
pkg/messaging/v1/replayable_request.go
|
GO
|
mit
| 4,355 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
"bytes"
"crypto/rand"
"errors"
"io"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestReplayableRequest(t *testing.T) {
// Test with a 100KB message
message := make([]byte, 100<<10)
_, err := io.ReadFull(rand.Reader, message)
require.NoError(t, err)
newReplayable := func() *replayableRequest {
rr := &replayableRequest{}
rr.WithRawData(newReaderCloser(bytes.NewReader(message)))
rr.SetReplay(true)
return rr
}
t.Run("read once", func(t *testing.T) {
rr := newReplayable()
defer rr.Close()
t.Run("first read in full", func(t *testing.T) {
read, err := io.ReadAll(rr.RawData())
require.NoError(t, err)
assert.Equal(t, message, read)
})
t.Run("rr.data is EOF", func(t *testing.T) {
buf := make([]byte, 9)
n, err := io.ReadFull(rr.data, buf)
assert.Equal(t, 0, n)
assert.Truef(t, errors.Is(err, io.EOF) || errors.Is(err, http.ErrBodyReadAfterClose), "unexpected error: %v", err)
})
t.Run("replay buffer is full", func(t *testing.T) {
assert.Len(t, message, rr.replay.Len())
read, err := io.ReadAll(bytes.NewReader(rr.replay.Bytes()))
require.NoError(t, err)
assert.Equal(t, message, read)
})
t.Run("close rr", func(t *testing.T) {
err := rr.Close()
require.NoError(t, err)
assert.Nil(t, rr.data)
assert.Nil(t, rr.replay)
})
})
t.Run("read in full three times", func(t *testing.T) {
rr := newReplayable()
defer rr.Close()
t.Run("first read in full", func(t *testing.T) {
read, err := io.ReadAll(rr.RawData())
require.NoError(t, err)
assert.Equal(t, message, read)
})
t.Run("rr.data is EOF", func(t *testing.T) {
buf := make([]byte, 9)
n, err := io.ReadFull(rr.data, buf)
assert.Equal(t, 0, n)
assert.Truef(t, errors.Is(err, io.EOF) || errors.Is(err, http.ErrBodyReadAfterClose), "unexpected error: %v", err)
})
t.Run("replay buffer is full", func(t *testing.T) {
assert.Len(t, message, rr.replay.Len())
read, err := io.ReadAll(bytes.NewReader(rr.replay.Bytes()))
require.NoError(t, err)
assert.Equal(t, message, read)
})
t.Run("second read in full", func(t *testing.T) {
read, err := io.ReadAll(rr.RawData())
require.NoError(t, err)
assert.Equal(t, message, read)
})
t.Run("third read in full", func(t *testing.T) {
read, err := io.ReadAll(rr.RawData())
require.NoError(t, err)
assert.Equal(t, message, read)
})
t.Run("close rr", func(t *testing.T) {
err := rr.Close()
require.NoError(t, err)
assert.Nil(t, rr.data)
assert.Nil(t, rr.replay)
})
})
t.Run("read in full, then partial read", func(t *testing.T) {
rr := newReplayable()
defer rr.Close()
t.Run("first read in full", func(t *testing.T) {
read, err := io.ReadAll(rr.RawData())
require.NoError(t, err)
assert.Equal(t, message, read)
})
// Read minByteSliceCapacity + 100
// This is more than the default size of the replay buffer
partial := minByteSliceCapacity + 100
r := rr.RawData()
t.Run("second, partial read", func(t *testing.T) {
buf := make([]byte, partial)
n, err := io.ReadFull(r, buf)
require.NoError(t, err)
assert.Equal(t, partial, n)
assert.Equal(t, message[:partial], buf)
})
t.Run("read rest", func(t *testing.T) {
read, err := io.ReadAll(r)
require.NoError(t, err)
assert.Len(t, read, len(message)-partial)
// Continue from byte "partial"
assert.Equal(t, message[partial:], read)
})
t.Run("second read in full", func(t *testing.T) {
read, err := io.ReadAll(rr.RawData())
require.NoError(t, err)
assert.Equal(t, message, read)
})
t.Run("close rr", func(t *testing.T) {
err := rr.Close()
require.NoError(t, err)
assert.Nil(t, rr.data)
assert.Nil(t, rr.replay)
})
})
t.Run("partial read, then read in full", func(t *testing.T) {
rr := newReplayable()
defer rr.Close()
// Read minByteSliceCapacity + 100
// This is more than the default size of the replay buffer
partial := minByteSliceCapacity + 100
t.Run("first, partial read", func(t *testing.T) {
buf := make([]byte, partial)
n, err := io.ReadFull(rr.RawData(), buf)
require.NoError(t, err)
assert.Equal(t, partial, n)
assert.Equal(t, message[:partial], buf)
})
t.Run("replay buffer has partial data", func(t *testing.T) {
assert.Equal(t, partial, rr.replay.Len())
read, err := io.ReadAll(bytes.NewReader(rr.replay.Bytes()))
require.NoError(t, err)
assert.Equal(t, message[:partial], read)
})
t.Run("second read in full", func(t *testing.T) {
read, err := io.ReadAll(rr.RawData())
require.NoError(t, err)
assert.Equal(t, message, read)
})
t.Run("rr.data is EOF", func(t *testing.T) {
buf := make([]byte, partial)
n, err := io.ReadFull(rr.data, buf)
assert.Equal(t, 0, n)
assert.Truef(t, errors.Is(err, io.EOF) || errors.Is(err, http.ErrBodyReadAfterClose), "unexpected error: %v", err)
})
t.Run("replay buffer is full", func(t *testing.T) {
assert.Len(t, message, rr.replay.Len())
read, err := io.ReadAll(bytes.NewReader(rr.replay.Bytes()))
require.NoError(t, err)
assert.Equal(t, message, read)
})
t.Run("third read in full", func(t *testing.T) {
read, err := io.ReadAll(rr.RawData())
require.NoError(t, err)
assert.Equal(t, message, read)
})
t.Run("close rr", func(t *testing.T) {
err := rr.Close()
require.NoError(t, err)
assert.Nil(t, rr.data)
assert.Nil(t, rr.replay)
})
})
}
// readerCloser is a io.Reader that can be closed. Once the stream is closed, reading from it returns an error.
type readerCloser struct {
r io.Reader
closed bool
}
func newReaderCloser(r io.Reader) *readerCloser {
return &readerCloser{
r: r,
closed: false,
}
}
func (b *readerCloser) Read(p []byte) (n int, err error) {
if b.closed {
// Use http.ErrBodyReadAfterClose which is the error returned by http.Response.Body
return 0, http.ErrBodyReadAfterClose
}
return b.r.Read(p)
}
func (b *readerCloser) Close() error {
b.closed = true
return nil
}
|
mikeee/dapr
|
pkg/messaging/v1/replayable_request_test.go
|
GO
|
mit
| 6,647 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
"context"
"encoding/base64"
"net/http"
"strconv"
"strings"
"sync"
"go.opentelemetry.io/otel/trace"
epb "google.golang.org/genproto/googleapis/rpc/errdetails"
spb "google.golang.org/genproto/googleapis/rpc/status"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
grpcStatus "google.golang.org/grpc/status"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/reflect/protoreflect"
diag "github.com/dapr/dapr/pkg/diagnostics"
diagUtils "github.com/dapr/dapr/pkg/diagnostics/utils"
internalv1pb "github.com/dapr/dapr/pkg/proto/internals/v1"
)
const (
// Maximum size, in bytes, for the buffer used by CallLocalStream: 2KB.
StreamBufferSize = 2 << 10
// GRPCContentType is the MIME media type for grpc.
GRPCContentType = "application/grpc"
// JSONContentType is the MIME media type for JSON.
JSONContentType = "application/json"
// ProtobufContentType is the MIME media type for Protobuf.
ProtobufContentType = "application/x-protobuf"
// OctetStreamContentType is the MIME media type for arbitrary binary data.
OctetStreamContentType = "application/octet-stream"
// ContentTypeHeader is the header key of content-type.
ContentTypeHeader = "content-type"
// ContentLengthHeader is the header key of content-length.
ContentLengthHeader = "content-length"
// DaprHeaderPrefix is the prefix if metadata is defined by non user-defined http headers.
DaprHeaderPrefix = "dapr-"
// gRPCBinaryMetadata is the suffix of grpc metadata binary value.
gRPCBinaryMetadataSuffix = "-bin"
// W3C trace correlation headers.
traceparentHeader = "traceparent"
tracestateHeader = "tracestate"
tracebinMetadata = "grpc-trace-bin"
// DestinationIDHeader is the header carrying the value of the invoked app id.
DestinationIDHeader = "destination-app-id"
// ErrorInfo metadata value is limited to 64 chars
// https://github.com/googleapis/googleapis/blob/master/google/rpc/error_details.proto#L126
maxMetadataValueLen = 63
// ErrorInfo metadata for HTTP response.
errorInfoDomain = "dapr.io"
errorInfoHTTPCodeMetadata = "http.code"
errorInfoHTTPErrorMetadata = "http.error_message"
CallerIDHeader = DaprHeaderPrefix + "caller-app-id"
CalleeIDHeader = DaprHeaderPrefix + "callee-app-id"
)
// BufPool is a pool of *[]byte used by direct messaging (for sending on both the server and client). Their size is fixed at StreamBufferSize.
var BufPool = sync.Pool{
New: func() any {
// Return a pointer here
// See https://github.com/dominikh/go-tools/issues/1336 for explanation
b := make([]byte, StreamBufferSize)
return &b
},
}
// DaprInternalMetadata is the metadata type to transfer HTTP header and gRPC metadata
// from user app to Dapr.
type DaprInternalMetadata map[string]*internalv1pb.ListStringValue
// IsJSONContentType returns true if contentType is the mime media type for JSON.
func IsJSONContentType(contentType string) bool {
return strings.HasPrefix(strings.ToLower(contentType), JSONContentType)
}
// isPermanentHTTPHeader checks whether hdr belongs to the list of
// permanent request headers maintained by IANA.
// http://www.iana.org/assignments/message-headers/message-headers.xml
func isPermanentHTTPHeader(hdr string) bool {
switch hdr {
case
"Accept",
"Accept-Charset",
"Accept-Language",
"Accept-Ranges",
// Connection-specific header fields such as Connection and Keep-Alive are prohibited in HTTP/2.
// See https://tools.ietf.org/html/rfc7540#section-8.1.2.2.
"Connection",
"Keep-Alive",
"Proxy-Connection",
"Transfer-Encoding",
"Upgrade",
"Cache-Control",
"Content-Type",
// Remove content-length header since it represents http1.1 payload size,
// not the sum of the h2 DATA frame payload lengths.
// See https://httpwg.org/specs/rfc7540.html#malformed.
"Content-Length",
"Cookie",
"Date",
"Expect",
"From",
"Host",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Schedule-Tag-Match",
"If-Unmodified-Since",
"Max-Forwards",
"Origin",
"Pragma",
"Referer",
"Via",
"Warning":
return true
}
return false
}
// InternalMetadataToGrpcMetadata converts internal metadata map to gRPC metadata.
func InternalMetadataToGrpcMetadata(ctx context.Context, internalMD DaprInternalMetadata, httpHeaderConversion bool) metadata.MD {
var traceparentValue, tracestateValue, grpctracebinValue string
md := metadata.MD{}
for k, listVal := range internalMD {
keyName := strings.ToLower(k)
// get both the trace headers for HTTP/GRPC and continue
switch keyName {
case traceparentHeader:
traceparentValue = listVal.GetValues()[0]
continue
case tracestateHeader:
tracestateValue = listVal.GetValues()[0]
continue
case tracebinMetadata:
grpctracebinValue = listVal.GetValues()[0]
continue
case DestinationIDHeader:
continue
}
if httpHeaderConversion && isPermanentHTTPHeader(k) {
keyName = DaprHeaderPrefix + keyName
}
if strings.HasSuffix(k, gRPCBinaryMetadataSuffix) {
// decoded base64 encoded key binary
for _, val := range listVal.GetValues() {
decoded, err := base64.StdEncoding.DecodeString(val)
if err == nil {
md.Append(keyName, string(decoded))
}
}
} else {
md.Append(keyName, listVal.GetValues()...)
}
}
if IsGRPCProtocol(internalMD) {
processGRPCToGRPCTraceHeader(ctx, md, grpctracebinValue)
} else {
// if HTTP protocol, then pass HTTP traceparent and HTTP tracestate header values, attach it in grpc-trace-bin header
processHTTPToGRPCTraceHeader(ctx, md, traceparentValue, tracestateValue)
}
return md
}
// IsGRPCProtocol checks if metadata is originated from gRPC API.
func IsGRPCProtocol(internalMD DaprInternalMetadata) bool {
originContentType := ""
if val, ok := internalMD[ContentTypeHeader]; ok {
originContentType = val.GetValues()[0]
}
return strings.HasPrefix(originContentType, GRPCContentType)
}
func ReservedGRPCMetadataToDaprPrefixHeader(key string) string {
// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
if key == ":method" || key == ":scheme" || key == ":path" || key == ":authority" {
return DaprHeaderPrefix + key[1:]
}
if strings.HasPrefix(key, "grpc-") {
return DaprHeaderPrefix + key
}
return key
}
// InternalMetadataToHTTPHeader converts internal metadata pb to HTTP headers.
func InternalMetadataToHTTPHeader(ctx context.Context, internalMD DaprInternalMetadata, setHeader func(string, string)) {
var traceparentValue, tracestateValue, grpctracebinValue string
for k, listVal := range internalMD {
if len(listVal.GetValues()) == 0 {
continue
}
keyName := strings.ToLower(k)
// get both the trace headers for HTTP/GRPC and continue
switch keyName {
case traceparentHeader:
traceparentValue = listVal.GetValues()[0]
continue
case tracestateHeader:
tracestateValue = listVal.GetValues()[0]
continue
case tracebinMetadata:
grpctracebinValue = listVal.GetValues()[0]
continue
case DestinationIDHeader:
continue
}
if strings.HasSuffix(keyName, gRPCBinaryMetadataSuffix) || keyName == ContentTypeHeader {
continue
}
for _, v := range listVal.GetValues() {
setHeader(ReservedGRPCMetadataToDaprPrefixHeader(keyName), v)
}
}
if IsGRPCProtocol(internalMD) {
// if grpcProtocol, then get grpc-trace-bin value, and attach it in HTTP traceparent and HTTP tracestate header
processGRPCToHTTPTraceHeaders(ctx, grpctracebinValue, setHeader)
} else {
processHTTPToHTTPTraceHeaders(ctx, traceparentValue, tracestateValue, setHeader)
}
}
// HTTPStatusFromCode converts a gRPC error code into the corresponding HTTP response status.
// https://github.com/grpc-ecosystem/grpc-gateway/blob/master/runtime/errors.go#L15
// See: https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
func HTTPStatusFromCode(code codes.Code) int {
switch code {
case codes.OK:
return http.StatusOK
case codes.Canceled:
return http.StatusRequestTimeout
case codes.Unknown:
return http.StatusInternalServerError
case codes.InvalidArgument:
return http.StatusBadRequest
case codes.DeadlineExceeded:
return http.StatusGatewayTimeout
case codes.NotFound:
return http.StatusNotFound
case codes.AlreadyExists:
return http.StatusConflict
case codes.PermissionDenied:
return http.StatusForbidden
case codes.Unauthenticated:
return http.StatusUnauthorized
case codes.ResourceExhausted:
return http.StatusTooManyRequests
case codes.FailedPrecondition:
// Note, this deliberately doesn't translate to the similarly named '412 Precondition Failed' HTTP response status.
return http.StatusBadRequest
case codes.Aborted:
return http.StatusConflict
case codes.OutOfRange:
return http.StatusBadRequest
case codes.Unimplemented:
return http.StatusNotImplemented
case codes.Internal:
return http.StatusInternalServerError
case codes.Unavailable:
return http.StatusServiceUnavailable
case codes.DataLoss:
return http.StatusInternalServerError
}
return http.StatusInternalServerError
}
// CodeFromHTTPStatus converts http status code to gRPC status code
// See: https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md
func CodeFromHTTPStatus(httpStatusCode int) codes.Code {
switch httpStatusCode {
case http.StatusRequestTimeout:
return codes.Canceled
case http.StatusInternalServerError:
return codes.Unknown
case http.StatusBadRequest:
return codes.Internal
case http.StatusGatewayTimeout:
return codes.DeadlineExceeded
case http.StatusNotFound:
return codes.NotFound
case http.StatusConflict:
return codes.AlreadyExists
case http.StatusForbidden:
return codes.PermissionDenied
case http.StatusUnauthorized:
return codes.Unauthenticated
case http.StatusTooManyRequests:
return codes.ResourceExhausted
case http.StatusNotImplemented:
return codes.Unimplemented
case http.StatusServiceUnavailable:
return codes.Unavailable
}
if httpStatusCode >= 200 && httpStatusCode < 300 {
return codes.OK
}
return codes.Unknown
}
// ErrorFromHTTPResponseCode converts http response code to gRPC status error.
func ErrorFromHTTPResponseCode(code int, detail string) error {
grpcCode := CodeFromHTTPStatus(code)
if grpcCode == codes.OK {
return nil
}
httpStatusText := http.StatusText(code)
respStatus := grpcStatus.New(grpcCode, httpStatusText)
// Truncate detail string longer than 64 characters
if len(detail) >= maxMetadataValueLen {
detail = detail[:maxMetadataValueLen]
}
resps, err := respStatus.WithDetails(
&epb.ErrorInfo{
Reason: httpStatusText,
Domain: errorInfoDomain,
Metadata: map[string]string{
errorInfoHTTPCodeMetadata: strconv.Itoa(code),
errorInfoHTTPErrorMetadata: detail,
},
},
)
if err != nil {
resps = respStatus
}
return resps.Err()
}
// ErrorFromInternalStatus converts internal status to gRPC status error.
func ErrorFromInternalStatus(internalStatus *internalv1pb.Status) error {
respStatus := &spb.Status{
Code: internalStatus.GetCode(),
Message: internalStatus.GetMessage(),
Details: internalStatus.GetDetails(),
}
return grpcStatus.ErrorProto(respStatus)
}
func processGRPCToHTTPTraceHeaders(ctx context.Context, traceContext string, setHeader func(string, string)) {
// attach grpc-trace-bin value in traceparent and tracestate header
decoded, _ := base64.StdEncoding.DecodeString(traceContext)
sc, ok := diagUtils.SpanContextFromBinary(decoded)
if !ok {
span := diagUtils.SpanFromContext(ctx)
sc = span.SpanContext()
}
diag.SpanContextToHTTPHeaders(sc, setHeader)
}
func processHTTPToHTTPTraceHeaders(ctx context.Context, traceparentValue, traceStateValue string, setHeader func(string, string)) {
if traceparentValue == "" {
span := diagUtils.SpanFromContext(ctx)
diag.SpanContextToHTTPHeaders(span.SpanContext(), setHeader)
} else {
setHeader(traceparentHeader, traceparentValue)
if traceStateValue != "" {
setHeader(tracestateHeader, traceStateValue)
}
}
}
func processHTTPToGRPCTraceHeader(ctx context.Context, md metadata.MD, traceparentValue, traceStateValue string) {
var sc trace.SpanContext
var ok bool
if sc, ok = diag.SpanContextFromW3CString(traceparentValue); ok {
ts := diag.TraceStateFromW3CString(traceStateValue)
sc = sc.WithTraceState(*ts)
} else {
span := diagUtils.SpanFromContext(ctx)
sc = span.SpanContext()
}
// Workaround for lack of grpc-trace-bin support in OpenTelemetry (unlike OpenCensus), tracking issue https://github.com/open-telemetry/opentelemetry-specification/issues/639
// grpc-dotnet client adheres to OpenTelemetry Spec which only supports http based traceparent header in gRPC path
// TODO : Remove this workaround fix once grpc-dotnet supports grpc-trace-bin header. Tracking issue https://github.com/dapr/dapr/issues/1827
diag.SpanContextToHTTPHeaders(sc, func(header, value string) {
md.Set(header, value)
})
md.Set(tracebinMetadata, string(diagUtils.BinaryFromSpanContext(sc)))
}
func processGRPCToGRPCTraceHeader(ctx context.Context, md metadata.MD, grpctracebinValue string) {
if grpctracebinValue == "" {
span := diagUtils.SpanFromContext(ctx)
sc := span.SpanContext()
// Workaround for lack of grpc-trace-bin support in OpenTelemetry (unlike OpenCensus), tracking issue https://github.com/open-telemetry/opentelemetry-specification/issues/639
// grpc-dotnet client adheres to OpenTelemetry Spec which only supports http based traceparent header in gRPC path
// TODO : Remove this workaround fix once grpc-dotnet supports grpc-trace-bin header. Tracking issue https://github.com/dapr/dapr/issues/1827
diag.SpanContextToHTTPHeaders(sc, func(header, value string) {
md.Set(header, value)
})
md.Set(tracebinMetadata, string(diagUtils.BinaryFromSpanContext(sc)))
} else {
decoded, err := base64.StdEncoding.DecodeString(grpctracebinValue)
if err == nil {
// Workaround for lack of grpc-trace-bin support in OpenTelemetry (unlike OpenCensus), tracking issue https://github.com/open-telemetry/opentelemetry-specification/issues/639
// grpc-dotnet client adheres to OpenTelemetry Spec which only supports http based traceparent header in gRPC path
// TODO : Remove this workaround fix once grpc-dotnet supports grpc-trace-bin header. Tracking issue https://github.com/dapr/dapr/issues/1827
if sc, ok := diagUtils.SpanContextFromBinary(decoded); ok {
diag.SpanContextToHTTPHeaders(sc, func(header, value string) {
md.Set(header, value)
})
}
md.Set(tracebinMetadata, string(decoded))
}
}
}
// ProtobufToJSON serializes Protobuf message to json format.
func ProtobufToJSON(message protoreflect.ProtoMessage) ([]byte, error) {
marshaler := protojson.MarshalOptions{
Indent: "",
UseProtoNames: false,
EmitUnpopulated: false,
}
return marshaler.Marshal(message)
}
// WithCustomGRPCMetadata applies a metadata map to the outgoing context metadata.
func WithCustomGRPCMetadata(ctx context.Context, md map[string]string) context.Context {
for k, v := range md {
if strings.EqualFold(k, ContentTypeHeader) ||
strings.EqualFold(k, ContentLengthHeader) {
// There is no use of the original payload's content-length because
// the entire data is already in the cloud event.
continue
}
// Uppercase keys will be converted to lowercase.
ctx = metadata.AppendToOutgoingContext(ctx, k, v)
}
return ctx
}
|
mikeee/dapr
|
pkg/messaging/v1/util.go
|
GO
|
mit
| 15,945 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
"context"
"encoding/base64"
"fmt"
"sort"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
epb "google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
internalv1pb "github.com/dapr/dapr/pkg/proto/internals/v1"
)
func TestInternalMetadataToHTTPHeader(t *testing.T) {
testValue := &internalv1pb.ListStringValue{
Values: []string{"fakeValue"},
}
fakeMetadata := map[string]*internalv1pb.ListStringValue{
"custom-header": testValue,
":method": testValue,
":scheme": testValue,
":path": testValue,
":authority": testValue,
"grpc-timeout": testValue,
"content-type": testValue, // skip
"grpc-trace-bin": testValue,
}
expectedKeyNames := []string{"custom-header", "dapr-method", "dapr-scheme", "dapr-path", "dapr-authority", "dapr-grpc-timeout"}
savedHeaderKeyNames := []string{}
ctx := context.Background()
InternalMetadataToHTTPHeader(ctx, fakeMetadata, func(k, v string) {
savedHeaderKeyNames = append(savedHeaderKeyNames, k)
})
sort.Strings(expectedKeyNames)
sort.Strings(savedHeaderKeyNames)
assert.Equal(t, expectedKeyNames, savedHeaderKeyNames)
}
func TestIsJSONContentType(t *testing.T) {
contentTypeTests := []struct {
in string
out bool
}{
{"application/json", true},
{"text/plains; charset=utf-8", false},
{"application/json; charset=utf-8", true},
}
for _, tt := range contentTypeTests {
t.Run(tt.in, func(t *testing.T) {
assert.Equal(t, tt.out, IsJSONContentType(tt.in))
})
}
}
func TestInternalMetadataToGrpcMetadata(t *testing.T) {
httpHeaders := map[string]*internalv1pb.ListStringValue{
"Host": {
Values: []string{"localhost"},
},
"Content-Type": {
Values: []string{"application/json"},
},
"Content-Length": {
Values: []string{"2000"},
},
"Connection": {
Values: []string{"keep-alive"},
},
"Keep-Alive": {
Values: []string{"timeout=5", "max=1000"},
},
"Proxy-Connection": {
Values: []string{"keep-alive"},
},
"Transfer-Encoding": {
Values: []string{"gzip", "chunked"},
},
"Upgrade": {
Values: []string{"WebSocket"},
},
"Accept-Encoding": {
Values: []string{"gzip, deflate"},
},
"User-Agent": {
Values: []string{"Go-http-client/1.1"},
},
}
ctx := context.Background()
t.Run("without http header conversion for http headers", func(t *testing.T) {
convertedMD := InternalMetadataToGrpcMetadata(ctx, httpHeaders, false)
// always trace header is returned
assert.Equal(t, 11, convertedMD.Len())
testHeaders := []struct {
key string
expected string
}{
{"host", "localhost"},
{"connection", "keep-alive"},
{"content-length", "2000"},
{"content-type", "application/json"},
{"keep-alive", "timeout=5"},
{"proxy-connection", "keep-alive"},
{"transfer-encoding", "gzip"},
{"upgrade", "WebSocket"},
{"accept-encoding", "gzip, deflate"},
{"user-agent", "Go-http-client/1.1"},
}
for _, ht := range testHeaders {
assert.Equal(t, ht.expected, convertedMD[ht.key][0])
}
})
t.Run("with http header conversion for http headers", func(t *testing.T) {
convertedMD := InternalMetadataToGrpcMetadata(ctx, httpHeaders, true)
// always trace header is returned
assert.Equal(t, 11, convertedMD.Len())
testHeaders := []struct {
key string
expected string
}{
{"dapr-host", "localhost"},
{"dapr-connection", "keep-alive"},
{"dapr-content-length", "2000"},
{"dapr-content-type", "application/json"},
{"dapr-keep-alive", "timeout=5"},
{"dapr-proxy-connection", "keep-alive"},
{"dapr-transfer-encoding", "gzip"},
{"dapr-upgrade", "WebSocket"},
{"accept-encoding", "gzip, deflate"},
{"user-agent", "Go-http-client/1.1"},
}
for _, ht := range testHeaders {
assert.Equal(t, ht.expected, convertedMD[ht.key][0])
}
})
keyBinValue := []byte{100, 50}
keyBinEncodedValue := base64.StdEncoding.EncodeToString(keyBinValue)
traceBinValue := []byte{10, 30, 50, 60}
traceBinValueEncodedValue := base64.StdEncoding.EncodeToString(traceBinValue)
grpcMetadata := map[string]*internalv1pb.ListStringValue{
"content-type": {
Values: []string{"application/grpc"},
},
":authority": {
Values: []string{"localhost"},
},
"grpc-timeout": {
Values: []string{"1S"},
},
"grpc-encoding": {
Values: []string{"gzip, deflate"},
},
"authorization": {
Values: []string{"bearer token"},
},
"grpc-trace-bin": {
Values: []string{traceBinValueEncodedValue},
},
"my-metadata": {
Values: []string{"value1", "value2", "value3"},
},
"key-bin": {
Values: []string{keyBinEncodedValue, keyBinEncodedValue},
},
}
t.Run("with grpc header conversion for grpc headers", func(t *testing.T) {
convertedMD := InternalMetadataToGrpcMetadata(ctx, grpcMetadata, true)
assert.Equal(t, 8, convertedMD.Len())
assert.Equal(t, "localhost", convertedMD[":authority"][0])
assert.Equal(t, "1S", convertedMD["grpc-timeout"][0])
assert.Equal(t, "gzip, deflate", convertedMD["grpc-encoding"][0])
assert.Equal(t, "bearer token", convertedMD["authorization"][0])
_, ok := convertedMD["grpc-trace-bin"]
assert.True(t, ok)
assert.Equal(t, "value1", convertedMD["my-metadata"][0])
assert.Equal(t, "value2", convertedMD["my-metadata"][1])
assert.Equal(t, "value3", convertedMD["my-metadata"][2])
assert.Equal(t, string(keyBinValue), convertedMD["key-bin"][0])
assert.Equal(t, string(keyBinValue), convertedMD["key-bin"][1])
assert.Equal(t, string(traceBinValue), convertedMD["grpc-trace-bin"][0])
})
}
func TestErrorFromHTTPResponseCode(t *testing.T) {
t.Run("OK", func(t *testing.T) {
// act
err := ErrorFromHTTPResponseCode(200, "OK")
// assert
require.NoError(t, err)
})
t.Run("Created", func(t *testing.T) {
// act
err := ErrorFromHTTPResponseCode(201, "Created")
// assert
require.NoError(t, err)
})
t.Run("NotFound", func(t *testing.T) {
// act
err := ErrorFromHTTPResponseCode(404, "Not Found")
// assert
s, ok := status.FromError(err)
assert.True(t, ok)
assert.Equal(t, codes.NotFound, s.Code())
assert.Equal(t, "Not Found", s.Message())
errInfo := (s.Details()[0]).(*epb.ErrorInfo)
assert.Equal(t, "404", errInfo.GetMetadata()[errorInfoHTTPCodeMetadata])
assert.Equal(t, "Not Found", errInfo.GetMetadata()[errorInfoHTTPErrorMetadata])
})
t.Run("Internal Server Error", func(t *testing.T) {
// act
err := ErrorFromHTTPResponseCode(500, "HTTPExtensions is not given")
// assert
s, ok := status.FromError(err)
assert.True(t, ok)
assert.Equal(t, codes.Unknown, s.Code())
assert.Equal(t, "Internal Server Error", s.Message())
errInfo := (s.Details()[0]).(*epb.ErrorInfo)
assert.Equal(t, "500", errInfo.GetMetadata()[errorInfoHTTPCodeMetadata])
assert.Equal(t, "HTTPExtensions is not given", errInfo.GetMetadata()[errorInfoHTTPErrorMetadata])
})
t.Run("Truncate error message", func(t *testing.T) {
longMessage := strings.Repeat("test", 30)
// act
err := ErrorFromHTTPResponseCode(500, longMessage)
// assert
s, _ := status.FromError(err)
errInfo := (s.Details()[0]).(*epb.ErrorInfo)
assert.Len(t, errInfo.GetMetadata()[errorInfoHTTPErrorMetadata], 63)
})
}
func TestErrorFromInternalStatus(t *testing.T) {
expected := status.New(codes.Internal, "Internal Service Error")
expected.WithDetails(
&epb.DebugInfo{
StackEntries: []string{
"first stack",
"second stack",
},
},
)
internal := &internalv1pb.Status{
Code: expected.Proto().GetCode(),
Message: expected.Proto().GetMessage(),
Details: expected.Proto().GetDetails(),
}
expected.Message()
// act
statusError := ErrorFromInternalStatus(internal)
// assert
actual, ok := status.FromError(statusError)
assert.True(t, ok)
assert.Equal(t, expected.Code(), actual.Code())
assert.Equal(t, expected.Message(), actual.Message())
assert.Equal(t, expected.Details(), actual.Details())
}
func TestProtobufToJSON(t *testing.T) {
tpb := &epb.DebugInfo{
StackEntries: []string{
"first stack",
"second stack",
},
}
jsonBody, err := ProtobufToJSON(tpb)
require.NoError(t, err)
t.Log(string(jsonBody))
// protojson produces different indentation space based on OS
// For linux
comp1 := string(jsonBody) == "{\"stackEntries\":[\"first stack\",\"second stack\"]}"
// For mac and windows
comp2 := string(jsonBody) == "{\"stackEntries\":[\"first stack\", \"second stack\"]}"
assert.True(t, comp1 || comp2)
}
func TestWithCustomGrpcMetadata(t *testing.T) {
customMetadataKey := func(i int) string {
return fmt.Sprintf("customMetadataKey%d", i)
}
customMetadataValue := func(i int) string {
return fmt.Sprintf("customMetadataValue%d", i)
}
numMetadata := 10
md := make(map[string]string, numMetadata)
for i := 0; i < numMetadata; i++ {
md[customMetadataKey(i)] = customMetadataValue(i)
}
ctx := context.Background()
ctx = WithCustomGRPCMetadata(ctx, md)
ctxMd, ok := metadata.FromOutgoingContext(ctx)
assert.True(t, ok)
for i := 0; i < numMetadata; i++ {
val, ok := ctxMd[strings.ToLower(customMetadataKey(i))]
assert.True(t, ok)
// We assume only 1 value per key as the input map can only support string -> string mapping.
assert.Equal(t, customMetadataValue(i), val[0])
}
}
|
mikeee/dapr
|
pkg/messaging/v1/util_test.go
|
GO
|
mit
| 9,942 |
package metrics
import (
"context"
"errors"
"fmt"
"net/http"
"time"
ocprom "contrib.go.opencensus.io/exporter/prometheus"
prom "github.com/prometheus/client_golang/prometheus"
"github.com/dapr/kit/logger"
)
const (
// DefaultMetricNamespace is the prefix of metric name.
DefaultMetricNamespace = "dapr"
defaultMetricsPath = "/"
)
// Exporter is the interface for metrics exporters.
type Exporter interface {
// Run initializes metrics exporter
Run(context.Context) error
// Options returns Exporter options
Options() *Options
}
// NewExporter creates new MetricsExporter instance.
func NewExporter(logger logger.Logger, namespace string) Exporter {
return NewExporterWithOptions(logger, namespace, DefaultMetricOptions())
}
// NewExporterWithOptions creates new MetricsExporter instance with options.
func NewExporterWithOptions(logger logger.Logger, namespace string, options *Options) Exporter {
// TODO: support multiple exporters
return &promMetricsExporter{
exporter: &exporter{
namespace: namespace,
options: options,
logger: logger,
},
}
}
// exporter is the base struct.
type exporter struct {
namespace string
options *Options
logger logger.Logger
}
// Options returns current metric exporter options.
func (m *exporter) Options() *Options {
return m.options
}
// promMetricsExporter is prometheus metric exporter.
type promMetricsExporter struct {
*exporter
ocExporter *ocprom.Exporter
server *http.Server
}
// Run initializes and runs the opencensus exporter.
func (m *promMetricsExporter) Run(ctx context.Context) error {
if !m.exporter.Options().MetricsEnabled {
// Block until context is cancelled.
<-ctx.Done()
return nil
}
var err error
if m.ocExporter, err = ocprom.NewExporter(ocprom.Options{
Namespace: m.namespace,
Registry: prom.DefaultRegisterer.(*prom.Registry),
}); err != nil {
return fmt.Errorf("failed to create Prometheus exporter: %w", err)
}
// start metrics server
return m.startMetricServer(ctx)
}
// startMetricServer starts metrics server.
func (m *promMetricsExporter) startMetricServer(ctx context.Context) error {
if !m.exporter.Options().MetricsEnabled {
// skip if metrics is not enabled
return nil
}
addr := fmt.Sprintf("%s:%d", m.options.MetricsListenAddress(), m.options.MetricsPort())
if m.ocExporter == nil {
return errors.New("exporter was not initialized")
}
m.exporter.logger.Infof("metrics server started on %s%s", addr, defaultMetricsPath)
mux := http.NewServeMux()
mux.Handle(defaultMetricsPath, m.ocExporter)
m.server = &http.Server{
Addr: addr,
Handler: mux,
ReadTimeout: time.Second * 10,
}
errCh := make(chan error)
go func() {
if err := m.server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
errCh <- fmt.Errorf("failed to run metrics server: %v", err)
return
}
errCh <- nil
}()
var err error
select {
case <-ctx.Done():
case err = <-errCh:
close(errCh)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
return errors.Join(m.server.Shutdown(ctx), err, <-errCh)
}
|
mikeee/dapr
|
pkg/metrics/exporter.go
|
GO
|
mit
| 3,141 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package metrics
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/kit/logger"
)
func TestMetricsExporter(t *testing.T) {
logger := logger.NewLogger("test.logger")
t.Run("returns default options", func(t *testing.T) {
e := NewExporter(logger, "test")
op := e.Options()
assert.Equal(t, DefaultMetricOptions(), op)
})
t.Run("return error if exporter is not initialized", func(t *testing.T) {
e := &promMetricsExporter{
exporter: &exporter{
namespace: "test",
options: DefaultMetricOptions(),
logger: logger,
},
}
require.Error(t, e.startMetricServer(context.Background()))
})
t.Run("skip starting metric server but wait for context cancellation", func(t *testing.T) {
e := NewExporter(logger, "test")
e.Options().MetricsEnabled = false
ctx, cancel := context.WithCancel(context.Background())
errCh := make(chan error)
go func() {
errCh <- e.Run(ctx)
}()
cancel()
select {
case err := <-errCh:
require.NoError(t, err)
case <-time.After(time.Second):
t.Error("expected metrics Run() to return in time when context is cancelled")
}
})
}
|
mikeee/dapr
|
pkg/metrics/exporter_test.go
|
GO
|
mit
| 1,758 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package metrics
import (
"strconv"
)
const (
defaultMetricsPort = "9090"
defaultMetricsAddress = "0.0.0.0"
defaultMetricsEnabled = true
)
// Options defines the sets of options for exporting metrics.
type Options struct {
// MetricsEnabled indicates whether a metrics server should be started.
MetricsEnabled bool
// Port to start metrics server on.
Port string
// ListenAddress is the address that the metrics server listens on.
ListenAddress string
}
func DefaultMetricOptions() *Options {
return &Options{
Port: defaultMetricsPort,
MetricsEnabled: defaultMetricsEnabled,
ListenAddress: defaultMetricsAddress,
}
}
// MetricsPort gets metrics port.
func (o *Options) MetricsPort() uint64 {
port, err := strconv.ParseUint(o.Port, 10, 64)
if err != nil {
// Use default metrics port as a fallback
port, _ = strconv.ParseUint(defaultMetricsPort, 10, 64)
}
return port
}
// MetricsListenAddress gets metrics listen address.
func (o *Options) MetricsListenAddress() string {
return o.ListenAddress
}
// AttachCmdFlags attaches metrics options to command flags.
func (o *Options) AttachCmdFlags(
stringVar func(p *string, name string, value string, usage string),
boolVar func(p *bool, name string, value bool, usage string),
) {
stringVar(
&o.Port,
"metrics-port",
defaultMetricsPort,
"The port for the metrics server")
stringVar(
&o.ListenAddress,
"metrics-listen-address",
defaultMetricsAddress,
"The address for the metrics server")
boolVar(
&o.MetricsEnabled,
"enable-metrics",
defaultMetricsEnabled,
"Enable prometheus metric")
}
// AttachCmdFlag attaches single metrics option to command flags.
func (o *Options) AttachCmdFlag(
stringVar func(p *string, name string, value string, usage string),
) {
stringVar(
&o.Port,
"metrics-port",
defaultMetricsPort,
"The port for the metrics server")
stringVar(
&o.ListenAddress,
"metrics-listen-address",
defaultMetricsAddress,
"The address for the metrics server")
}
|
mikeee/dapr
|
pkg/metrics/options.go
|
GO
|
mit
| 2,570 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package metrics
import (
"strconv"
"testing"
"github.com/stretchr/testify/assert"
)
func TestOptions(t *testing.T) {
t.Run("default options", func(t *testing.T) {
o := DefaultMetricOptions()
assert.Equal(t, defaultMetricsPort, o.Port)
assert.Equal(t, defaultMetricsEnabled, o.MetricsEnabled)
})
t.Run("attaching metrics related cmd flags", func(t *testing.T) {
o := DefaultMetricOptions()
metricsPortAsserted := false
testStringVarFn := func(p *string, name string, value string, usage string) {
if name == "metrics-port" && value == defaultMetricsPort {
metricsPortAsserted = true
}
}
metricsEnabledAsserted := false
testBoolVarFn := func(p *bool, name string, value bool, usage string) {
if name == "enable-metrics" && value == defaultMetricsEnabled {
metricsEnabledAsserted = true
}
}
o.AttachCmdFlags(testStringVarFn, testBoolVarFn)
// assert
assert.True(t, metricsPortAsserted)
assert.True(t, metricsEnabledAsserted)
})
t.Run("parse valid port", func(t *testing.T) {
o := Options{
Port: "1010",
MetricsEnabled: false,
}
assert.Equal(t, uint64(1010), o.MetricsPort())
})
t.Run("return default port if port is invalid", func(t *testing.T) {
o := Options{
Port: "invalid",
MetricsEnabled: false,
}
defaultPort, _ := strconv.ParseUint(defaultMetricsPort, 10, 64)
assert.Equal(t, defaultPort, o.MetricsPort())
})
t.Run("attaching single metrics related cmd flag", func(t *testing.T) {
o := DefaultMetricOptions()
metricsPortAsserted := false
testStringVarFn := func(p *string, name string, value string, usage string) {
if name == "metrics-port" && value == defaultMetricsPort {
metricsPortAsserted = true
}
}
o.AttachCmdFlag(testStringVarFn)
// assert
assert.True(t, metricsPortAsserted)
})
}
|
mikeee/dapr
|
pkg/metrics/options_test.go
|
GO
|
mit
| 2,403 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package http
import (
"sync"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/config"
"github.com/dapr/dapr/pkg/middleware"
"github.com/dapr/dapr/pkg/middleware/store"
"github.com/dapr/kit/logger"
)
var log = logger.NewLogger("dapr.middleware.http")
// HTTP returns HTTP middleware pipelines. These pipelines dynamically update
// the middleware chain when a component is added or removed from the store.
// Callers need only build a Pipeline once for a given spec.
type HTTP struct {
lock sync.RWMutex
store *store.Store[middleware.HTTP]
pipelines []*pipeline
}
// Spec is a specification for a creating a middleware.
type Spec struct {
Component compapi.Component
Implementation middleware.HTTP
}
// New returns a new HTTP middleware store.
func New() *HTTP {
return &HTTP{
store: store.New[middleware.HTTP]("http"),
}
}
// Add adds a middleware to the store.
func (h *HTTP) Add(spec Spec) {
h.store.Add(store.Item[middleware.HTTP]{
Metadata: store.Metadata{
Name: spec.Component.Name,
Type: spec.Component.Spec.Type,
Version: spec.Component.Spec.Version,
},
Middleware: spec.Implementation,
})
for _, p := range h.pipelines {
p.buildChain()
}
}
// Remove removes a middleware from the store.
func (h *HTTP) Remove(name string) {
h.store.Remove(name)
for _, p := range h.pipelines {
p.buildChain()
}
}
// BuildPipelineFromSpec builds a middleware pipeline from a spec. The returned
// Pipeline will dynamically update handlers when middleware components are
// added or removed from the store.
func (h *HTTP) BuildPipelineFromSpec(name string, spec *config.PipelineSpec) middleware.HTTP {
h.lock.Lock()
defer h.lock.Unlock()
p := newPipeline(name, h.store, spec)
h.pipelines = append(h.pipelines, p)
return p.http()
}
|
mikeee/dapr
|
pkg/middleware/http/http.go
|
GO
|
mit
| 2,394 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package http
import (
nethttp "net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/dapr/dapr/pkg/config"
)
func TestHTTP(t *testing.T) {
t.Run("if chain already built, should use chain", func(t *testing.T) {
middle1 := newTestMiddle("test")
middle2 := newTestMiddle("test2")
h := New()
h.Add(Spec{
Component: middle1.comp,
Implementation: middle1.item.Middleware,
})
h.Add(Spec{
Component: middle2.comp,
Implementation: middle2.item.Middleware,
})
var invoked int
root := nethttp.HandlerFunc(func(nethttp.ResponseWriter, *nethttp.Request) { invoked++ })
handler := h.BuildPipelineFromSpec("test", &config.PipelineSpec{Handlers: []config.HandlerSpec{
{Name: "test", Type: "middleware.http.fakemw", Version: "v1"},
{Name: "test2", Type: "middleware.http.fakemw", Version: ""},
}})(root)
assert.Equal(t, 0, invoked)
assert.Equal(t, int32(0), middle1.invoked.Load())
assert.Equal(t, int32(0), middle2.invoked.Load())
handler.ServeHTTP(nil, nil)
assert.Equal(t, 1, invoked)
assert.Equal(t, int32(1), middle1.invoked.Load())
assert.Equal(t, int32(1), middle2.invoked.Load())
})
t.Run("if chain is added after, should use chain", func(t *testing.T) {
middle1 := newTestMiddle("test")
middle2 := newTestMiddle("test2")
h := New()
var invoked int
root := nethttp.HandlerFunc(func(nethttp.ResponseWriter, *nethttp.Request) { invoked++ })
handler := h.BuildPipelineFromSpec("test", &config.PipelineSpec{Handlers: []config.HandlerSpec{
{Name: "test", Type: "middleware.http.fakemw", Version: "v1"},
{Name: "test2", Type: "middleware.http.fakemw", Version: ""},
}})(root)
assert.Equal(t, 0, invoked)
assert.Equal(t, int32(0), middle1.invoked.Load())
assert.Equal(t, int32(0), middle2.invoked.Load())
handler.ServeHTTP(nil, nil)
assert.Equal(t, 1, invoked)
assert.Equal(t, int32(0), middle1.invoked.Load())
assert.Equal(t, int32(0), middle2.invoked.Load())
h.Add(Spec{
Component: middle1.comp,
Implementation: middle1.item.Middleware,
})
h.Add(Spec{
Component: middle2.comp,
Implementation: middle2.item.Middleware,
})
handler.ServeHTTP(nil, nil)
assert.Equal(t, 2, invoked)
assert.Equal(t, int32(1), middle1.invoked.Load())
assert.Equal(t, int32(1), middle2.invoked.Load())
})
t.Run("if chains are added and removed, chain should be updated", func(t *testing.T) {
middle1 := newTestMiddle("test")
middle2 := newTestMiddle("test2")
h := New()
h.Add(Spec{
Component: middle1.comp,
Implementation: middle1.item.Middleware,
})
var invoked int
root := nethttp.HandlerFunc(func(nethttp.ResponseWriter, *nethttp.Request) { invoked++ })
handler := h.BuildPipelineFromSpec("test", &config.PipelineSpec{Handlers: []config.HandlerSpec{
{Name: "test", Type: "middleware.http.fakemw", Version: "v1"},
{Name: "test2", Type: "middleware.http.fakemw", Version: ""},
}})(root)
assert.Equal(t, 0, invoked)
assert.Equal(t, int32(0), middle1.invoked.Load())
assert.Equal(t, int32(0), middle2.invoked.Load())
handler.ServeHTTP(nil, nil)
assert.Equal(t, 1, invoked)
assert.Equal(t, int32(1), middle1.invoked.Load())
assert.Equal(t, int32(0), middle2.invoked.Load())
h.Add(Spec{
Component: middle2.comp,
Implementation: middle2.item.Middleware,
})
handler.ServeHTTP(nil, nil)
assert.Equal(t, 2, invoked)
assert.Equal(t, int32(2), middle1.invoked.Load())
assert.Equal(t, int32(1), middle2.invoked.Load())
h.Remove("test3")
handler.ServeHTTP(nil, nil)
assert.Equal(t, 3, invoked)
assert.Equal(t, int32(3), middle1.invoked.Load())
assert.Equal(t, int32(2), middle2.invoked.Load())
h.Remove("test")
handler.ServeHTTP(nil, nil)
assert.Equal(t, 4, invoked)
assert.Equal(t, int32(3), middle1.invoked.Load())
assert.Equal(t, int32(3), middle2.invoked.Load())
h.Remove("test2")
handler.ServeHTTP(nil, nil)
assert.Equal(t, 5, invoked)
assert.Equal(t, int32(3), middle1.invoked.Load())
assert.Equal(t, int32(3), middle2.invoked.Load())
h.Add(Spec{
Component: middle1.comp,
Implementation: middle1.item.Middleware,
})
h.Add(Spec{
Component: middle2.comp,
Implementation: middle2.item.Middleware,
})
handler.ServeHTTP(nil, nil)
assert.Equal(t, 6, invoked)
assert.Equal(t, int32(4), middle1.invoked.Load())
assert.Equal(t, int32(4), middle2.invoked.Load())
})
}
|
mikeee/dapr
|
pkg/middleware/http/http_test.go
|
GO
|
mit
| 4,994 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package http
import (
"net/http"
"sync"
"github.com/dapr/dapr/pkg/config"
"github.com/dapr/dapr/pkg/middleware"
"github.com/dapr/dapr/pkg/middleware/store"
)
// pipeline manages a single HTTP middleware pipeline for a single HTTP
// Pipeline Spec.
type pipeline struct {
lock sync.RWMutex
name string
spec *config.PipelineSpec
store *store.Store[middleware.HTTP]
root http.Handler
chain http.Handler
}
// newPipeline creates a new HTTP Middleware Pipeline.
func newPipeline(
name string,
store *store.Store[middleware.HTTP],
spec *config.PipelineSpec,
) *pipeline {
return &pipeline{
name: name,
spec: spec,
store: store,
}
}
// http returns a dynamic HTTP middleware. The chained handler will dynamically
// instrument the HTTP middlewares as they are added, updated and removed from
// the store. Consumers must call `buildChain` for the handler changes to take
// effect.
// The pipeline root handler will be set once the middleware is invoked.
func (p *pipeline) http() middleware.HTTP {
return func(root http.Handler) http.Handler {
p.lock.Lock()
p.root = root
p.lock.Unlock()
p.buildChain()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p.lock.RLock()
next := p.chain
p.lock.RUnlock()
next.ServeHTTP(w, r)
})
}
}
// buildChain builds and updates the middleware chain from root using the set
// spec. Any middlewares which are not currently loaded are skipped.
func (p *pipeline) buildChain() {
p.lock.Lock()
defer p.lock.Unlock()
// If no spec or no handlers defined, use root.
if p.spec == nil || len(p.spec.Handlers) == 0 {
p.chain = p.root
return
}
log.Infof("Building pipeline %s", p.name)
next := p.root
for i := len(p.spec.Handlers) - 1; i >= 0; i-- {
handler, ok := p.store.Get(store.Metadata{
Name: p.spec.Handlers[i].Name,
Type: p.spec.Handlers[i].Type,
Version: p.spec.Handlers[i].Version,
})
if !ok {
continue
}
next = handler(next)
}
p.chain = next
}
|
mikeee/dapr
|
pkg/middleware/http/pipeline.go
|
GO
|
mit
| 2,562 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package http
import (
nethttp "net/http"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/config"
"github.com/dapr/dapr/pkg/middleware"
"github.com/dapr/dapr/pkg/middleware/store"
)
func TestPipeline_http(t *testing.T) {
t.Run("if chain already built, should use chain", func(t *testing.T) {
store := store.New[middleware.HTTP]("test")
middle1 := newTestMiddle("test")
middle2 := newTestMiddle("test2")
store.Add(middle1.item)
store.Add(middle2.item)
p := newPipeline("test", store, &config.PipelineSpec{Handlers: []config.HandlerSpec{
{Name: "test", Type: "middleware.http.fakemw", Version: "v1"},
{Name: "test2", Type: "middleware.http.fakemw", Version: ""},
}})
var invoked int
root := nethttp.HandlerFunc(func(nethttp.ResponseWriter, *nethttp.Request) { invoked++ })
handler := p.http()(root)
assert.Equal(t, 0, invoked)
assert.Equal(t, int32(0), middle1.invoked.Load())
assert.Equal(t, int32(0), middle2.invoked.Load())
handler.ServeHTTP(nil, nil)
assert.Equal(t, 1, invoked)
assert.Equal(t, int32(1), middle1.invoked.Load())
assert.Equal(t, int32(1), middle2.invoked.Load())
})
t.Run("if chain is added after, should use chain", func(t *testing.T) {
store := store.New[middleware.HTTP]("test")
middle1 := newTestMiddle("test")
middle2 := newTestMiddle("test2")
p := newPipeline("test", store, &config.PipelineSpec{Handlers: []config.HandlerSpec{
{Name: "test", Type: "middleware.http.fakemw", Version: "v1"},
{Name: "test2", Type: "middleware.http.fakemw", Version: ""},
}})
var invoked int
root := nethttp.HandlerFunc(func(nethttp.ResponseWriter, *nethttp.Request) { invoked++ })
handler := p.http()(root)
assert.Equal(t, 0, invoked)
assert.Equal(t, int32(0), middle1.invoked.Load())
assert.Equal(t, int32(0), middle2.invoked.Load())
handler.ServeHTTP(nil, nil)
assert.Equal(t, 1, invoked)
assert.Equal(t, int32(0), middle1.invoked.Load())
assert.Equal(t, int32(0), middle2.invoked.Load())
store.Add(middle1.item)
store.Add(middle2.item)
p.buildChain()
handler.ServeHTTP(nil, nil)
assert.Equal(t, 2, invoked)
assert.Equal(t, int32(1), middle1.invoked.Load())
assert.Equal(t, int32(1), middle2.invoked.Load())
})
t.Run("if chains are added and removed, chain should be updated", func(t *testing.T) {
store := store.New[middleware.HTTP]("test")
middle1 := newTestMiddle("test")
middle2 := newTestMiddle("test2")
store.Add(middle1.item)
p := newPipeline("test", store, &config.PipelineSpec{Handlers: []config.HandlerSpec{
{Name: "test", Type: "middleware.http.fakemw", Version: "v1"},
{Name: "test2", Type: "middleware.http.fakemw", Version: ""},
}})
var invoked int
root := nethttp.HandlerFunc(func(nethttp.ResponseWriter, *nethttp.Request) { invoked++ })
handler := p.http()(root)
assert.Equal(t, 0, invoked)
assert.Equal(t, int32(0), middle1.invoked.Load())
assert.Equal(t, int32(0), middle2.invoked.Load())
handler.ServeHTTP(nil, nil)
assert.Equal(t, 1, invoked)
assert.Equal(t, int32(1), middle1.invoked.Load())
assert.Equal(t, int32(0), middle2.invoked.Load())
store.Add(middle2.item)
p.buildChain()
handler.ServeHTTP(nil, nil)
assert.Equal(t, 2, invoked)
assert.Equal(t, int32(2), middle1.invoked.Load())
assert.Equal(t, int32(1), middle2.invoked.Load())
store.Remove("test3")
p.buildChain()
handler.ServeHTTP(nil, nil)
assert.Equal(t, 3, invoked)
assert.Equal(t, int32(3), middle1.invoked.Load())
assert.Equal(t, int32(2), middle2.invoked.Load())
store.Remove("test")
p.buildChain()
handler.ServeHTTP(nil, nil)
assert.Equal(t, 4, invoked)
assert.Equal(t, int32(3), middle1.invoked.Load())
assert.Equal(t, int32(3), middle2.invoked.Load())
store.Remove("test2")
p.buildChain()
handler.ServeHTTP(nil, nil)
assert.Equal(t, 5, invoked)
assert.Equal(t, int32(3), middle1.invoked.Load())
assert.Equal(t, int32(3), middle2.invoked.Load())
store.Add(middle1.item)
store.Add(middle2.item)
p.buildChain()
handler.ServeHTTP(nil, nil)
assert.Equal(t, 6, invoked)
assert.Equal(t, int32(4), middle1.invoked.Load())
assert.Equal(t, int32(4), middle2.invoked.Load())
})
}
func TestPipeline_buildChain(t *testing.T) {
t.Run("if spec is nil, chain should be nil", func(t *testing.T) {
store := store.New[middleware.HTTP]("test")
p := newPipeline("test", store, nil)
p.chain = nethttp.HandlerFunc(func(nethttp.ResponseWriter, *nethttp.Request) {})
assert.NotNil(t, p.chain)
p.buildChain()
assert.Nil(t, p.chain)
})
t.Run("if spec handlers is empty, chain should be nil", func(t *testing.T) {
store := store.New[middleware.HTTP]("test")
p := newPipeline("test", store, &config.PipelineSpec{Handlers: nil})
p.chain = nethttp.HandlerFunc(func(nethttp.ResponseWriter, *nethttp.Request) {})
assert.NotNil(t, p.chain)
p.buildChain()
assert.Nil(t, p.chain)
p = newPipeline("test", store, &config.PipelineSpec{Handlers: []config.HandlerSpec{}})
p.chain = nethttp.HandlerFunc(func(nethttp.ResponseWriter, *nethttp.Request) {})
assert.NotNil(t, p.chain)
p.buildChain()
assert.Nil(t, p.chain)
})
t.Run("if spec references handler that does not exist, chain should just be root", func(t *testing.T) {
store := store.New[middleware.HTTP]("test")
p := newPipeline("test", store, &config.PipelineSpec{Handlers: []config.HandlerSpec{
{Name: "test", Type: "middleware.http.fakemw", Version: "v1"},
}})
var called bool
p.root = nethttp.HandlerFunc(func(nethttp.ResponseWriter, *nethttp.Request) { called = true })
assert.Nil(t, p.chain)
p.buildChain()
assert.NotNil(t, p.chain)
assert.False(t, called)
p.chain.ServeHTTP(nil, nil)
assert.True(t, called)
})
t.Run("if spec references multiple handlers that does not exist, chain should just be root", func(t *testing.T) {
store := store.New[middleware.HTTP]("test")
p := newPipeline("test", store, &config.PipelineSpec{Handlers: []config.HandlerSpec{
{Name: "test", Type: "middleware.http.fakemw", Version: "v1"},
{Name: "test2", Type: "middleware.http.fakemw", Version: ""},
}})
var called bool
p.root = nethttp.HandlerFunc(func(nethttp.ResponseWriter, *nethttp.Request) { called = true })
assert.Nil(t, p.chain)
p.buildChain()
assert.NotNil(t, p.chain)
assert.False(t, called)
p.chain.ServeHTTP(nil, nil)
assert.True(t, called)
})
t.Run("if spec references handler that does exist, chain should include middleware", func(t *testing.T) {
store := store.New[middleware.HTTP]("test")
middle := newTestMiddle("test")
store.Add(middle.item)
p := newPipeline("test", store, &config.PipelineSpec{Handlers: []config.HandlerSpec{
{Name: "test", Type: "middleware.http.fakemw", Version: "v1"},
}})
var invoked int
p.root = nethttp.HandlerFunc(func(nethttp.ResponseWriter, *nethttp.Request) { invoked++ })
assert.Nil(t, p.chain)
p.buildChain()
assert.NotNil(t, p.chain)
assert.Equal(t, 0, invoked)
p.chain.ServeHTTP(nil, nil)
assert.Equal(t, 1, invoked)
assert.Equal(t, int32(1), middle.invoked.Load())
p.chain.ServeHTTP(nil, nil)
assert.Equal(t, 2, invoked)
assert.Equal(t, int32(2), middle.invoked.Load())
})
t.Run("if spec references multiple handlers that exist, chain should include middlewares", func(t *testing.T) {
store := store.New[middleware.HTTP]("test")
middle1 := newTestMiddle("test")
middle2 := newTestMiddle("test2")
store.Add(middle1.item)
store.Add(middle2.item)
p := newPipeline("test", store, &config.PipelineSpec{Handlers: []config.HandlerSpec{
{Name: "test", Type: "middleware.http.fakemw", Version: "v1"},
{Name: "test2", Type: "middleware.http.fakemw", Version: "v1"},
}})
var invoked int
p.root = nethttp.HandlerFunc(func(nethttp.ResponseWriter, *nethttp.Request) { invoked++ })
p.buildChain()
assert.Equal(t, 0, invoked)
p.chain.ServeHTTP(nil, nil)
assert.Equal(t, 1, invoked)
assert.Equal(t, int32(1), middle1.invoked.Load())
assert.Equal(t, int32(1), middle2.invoked.Load())
p.chain.ServeHTTP(nil, nil)
assert.Equal(t, 2, invoked)
assert.Equal(t, int32(2), middle1.invoked.Load())
assert.Equal(t, int32(2), middle2.invoked.Load())
})
t.Run("if spec references handler that doesn't exist, it shouldn't be used", func(t *testing.T) {
store := store.New[middleware.HTTP]("test")
middle1 := newTestMiddle("test")
middle2 := newTestMiddle("test2")
store.Add(middle1.item)
p := newPipeline("test", store, &config.PipelineSpec{Handlers: []config.HandlerSpec{
{Name: "test", Type: "middleware.http.fakemw", Version: "v1"},
{Name: "test2", Type: "middleware.http.fakemw", Version: "v1"},
}})
var invoked int
p.root = nethttp.HandlerFunc(func(nethttp.ResponseWriter, *nethttp.Request) { invoked++ })
p.buildChain()
assert.Equal(t, 0, invoked)
p.chain.ServeHTTP(nil, nil)
assert.Equal(t, 1, invoked)
assert.Equal(t, int32(1), middle1.invoked.Load())
assert.Equal(t, int32(0), middle2.invoked.Load())
p.chain.ServeHTTP(nil, nil)
assert.Equal(t, 2, invoked)
assert.Equal(t, int32(2), middle1.invoked.Load())
assert.Equal(t, int32(0), middle2.invoked.Load())
})
t.Run("if spec defaults version, should still be called", func(t *testing.T) {
store := store.New[middleware.HTTP]("test")
middle1 := newTestMiddle("test")
middle2 := newTestMiddle("test2")
store.Add(middle1.item)
store.Add(middle2.item)
p := newPipeline("test", store, &config.PipelineSpec{Handlers: []config.HandlerSpec{
{Name: "test", Type: "middleware.http.fakemw", Version: "v1"},
{Name: "test2", Type: "middleware.http.fakemw", Version: ""},
}})
var invoked int
p.root = nethttp.HandlerFunc(func(nethttp.ResponseWriter, *nethttp.Request) { invoked++ })
p.buildChain()
assert.Equal(t, 0, invoked)
p.chain.ServeHTTP(nil, nil)
assert.Equal(t, 1, invoked)
assert.Equal(t, int32(1), middle1.invoked.Load())
assert.Equal(t, int32(1), middle2.invoked.Load())
p.chain.ServeHTTP(nil, nil)
assert.Equal(t, 2, invoked)
assert.Equal(t, int32(2), middle1.invoked.Load())
assert.Equal(t, int32(2), middle2.invoked.Load())
})
t.Run("if spec references different type, shouldn't be used", func(t *testing.T) {
store := store.New[middleware.HTTP]("test")
middle1 := newTestMiddle("test")
middle2 := newTestMiddle("test2")
store.Add(middle1.item)
store.Add(middle2.item)
p := newPipeline("test", store, &config.PipelineSpec{Handlers: []config.HandlerSpec{
{Name: "test", Type: "middleware.http.fakemw", Version: "v1"},
{Name: "test2", Type: "middleware.http.notfakemw", Version: "v1"},
}})
var invoked int
p.root = nethttp.HandlerFunc(func(nethttp.ResponseWriter, *nethttp.Request) { invoked++ })
p.buildChain()
assert.Equal(t, 0, invoked)
p.chain.ServeHTTP(nil, nil)
assert.Equal(t, 1, invoked)
assert.Equal(t, int32(1), middle1.invoked.Load())
assert.Equal(t, int32(0), middle2.invoked.Load())
p.chain.ServeHTTP(nil, nil)
assert.Equal(t, 2, invoked)
assert.Equal(t, int32(2), middle1.invoked.Load())
assert.Equal(t, int32(0), middle2.invoked.Load())
})
t.Run("if spec references different name, shouldn't be used", func(t *testing.T) {
store := store.New[middleware.HTTP]("test")
middle1 := newTestMiddle("test")
middle2 := newTestMiddle("test2")
store.Add(middle1.item)
store.Add(middle2.item)
p := newPipeline("test", store, &config.PipelineSpec{Handlers: []config.HandlerSpec{
{Name: "test", Type: "middleware.http.fakemw", Version: "v1"},
{Name: "nottest2", Type: "middleware.http.fakemw", Version: "v1"},
}})
var invoked int
p.root = nethttp.HandlerFunc(func(nethttp.ResponseWriter, *nethttp.Request) { invoked++ })
p.buildChain()
assert.Equal(t, 0, invoked)
p.chain.ServeHTTP(nil, nil)
assert.Equal(t, 1, invoked)
assert.Equal(t, int32(1), middle1.invoked.Load())
assert.Equal(t, int32(0), middle2.invoked.Load())
p.chain.ServeHTTP(nil, nil)
assert.Equal(t, 2, invoked)
assert.Equal(t, int32(2), middle1.invoked.Load())
assert.Equal(t, int32(0), middle2.invoked.Load())
})
}
type testmiddle struct {
item store.Item[middleware.HTTP]
comp compapi.Component
invoked atomic.Int32
wait chan struct{}
}
func newTestMiddle(name string) *testmiddle {
tm := &testmiddle{
comp: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: name},
Spec: compapi.ComponentSpec{
Type: "middleware.http.fakemw",
Version: "v1",
},
},
}
tm.wait = make(chan struct{})
close(tm.wait)
tm.item = store.Item[middleware.HTTP]{
Metadata: store.Metadata{
Name: name,
Type: "middleware.http.fakemw",
Version: "v1",
},
Middleware: func(next nethttp.Handler) nethttp.Handler {
return nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) {
<-tm.wait
tm.invoked.Add(1)
next.ServeHTTP(w, r)
})
},
}
return tm
}
|
mikeee/dapr
|
pkg/middleware/http/pipeline_test.go
|
GO
|
mit
| 13,580 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package middleware
import (
"net/http"
)
// HTTP is a middleware for the middleware.http Component type.
type HTTP func(http.Handler) http.Handler
// Middleware is a generic Middleware type.
type Middleware interface {
HTTP
}
|
mikeee/dapr
|
pkg/middleware/middleware.go
|
GO
|
mit
| 792 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package store
import (
"sync"
"github.com/dapr/dapr/pkg/middleware"
"github.com/dapr/kit/logger"
)
// Store provides a dynamic dictionary to loaded Component Middleware
// implementations.
type Store[T middleware.Middleware] struct {
log logger.Logger
lock sync.RWMutex
// loaded is the set of currently loaded middlewares, mapped by name to
// middleware implementation.
loaded map[string]Item[T]
}
// Metadata is the metadata associated with a middleware.
type Metadata struct {
Name string
Type string
Version string
}
// Item is a single middleware in the store. It holds the middleware
// implementation and the metadata associated with it.
type Item[T middleware.Middleware] struct {
Metadata
Middleware T
}
func New[T middleware.Middleware](kind string) *Store[T] {
return &Store[T]{
log: logger.NewLogger("dapr.middleware." + kind),
loaded: make(map[string]Item[T]),
}
}
// Add adds a middleware to the store.
func (s *Store[T]) Add(item Item[T]) {
s.lock.Lock()
defer s.lock.Unlock()
s.log.Infof("Adding %s/%s %s middleware", item.Type, item.Version, item.Name)
if len(item.Version) == 0 {
item.Version = "v1"
}
s.loaded[item.Name] = item
}
// Get returns a middleware from the store.
func (s *Store[T]) Get(m Metadata) (T, bool) {
s.lock.RLock()
defer s.lock.RUnlock()
version := m.Version
if len(version) == 0 {
version = "v1"
}
l, ok := s.loaded[m.Name]
if !ok || m.Type != l.Type || version != l.Version {
return nil, false
}
return l.Middleware, ok
}
// Remove removes a middleware from the store.
func (s *Store[T]) Remove(name string) {
s.lock.Lock()
defer s.lock.Unlock()
m, ok := s.loaded[name]
if ok {
s.log.Infof("Removing %s/%s %s middleware", m.Type, m.Version, m.Name)
}
delete(s.loaded, name)
}
|
mikeee/dapr
|
pkg/middleware/store/store.go
|
GO
|
mit
| 2,348 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package store
import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/dapr/dapr/pkg/middleware"
)
func TestStore(t *testing.T) {
s := New[middleware.HTTP]("test")
assert.Empty(t, s.loaded)
item := Item[middleware.HTTP]{
Metadata: Metadata{
Name: "test",
Type: "middleware",
Version: "v2",
},
Middleware: func(http.Handler) http.Handler { return nil },
}
t.Run("can add middleware", func(t *testing.T) {
s.Add(item)
assert.Len(t, s.loaded, 1)
assert.Equal(t, "test", s.loaded["test"].Name)
assert.Equal(t, "middleware", s.loaded["test"].Type)
assert.Equal(t, "v2", s.loaded["test"].Version)
})
t.Run("stored middlewares default to v1", func(t *testing.T) {
item.Name = "test2"
item.Version = ""
s.Add(item)
assert.Len(t, s.loaded, 2)
assert.Equal(t, "v1", s.loaded["test2"].Version)
})
t.Run("can get middleware", func(t *testing.T) {
m, ok := s.Get(Metadata{Name: "test", Type: "middleware", Version: "v2"})
assert.True(t, ok)
assert.NotNil(t, m)
})
t.Run("can get middleware defaults to v1", func(t *testing.T) {
m, ok := s.Get(Metadata{Name: "test2", Type: "middleware"})
assert.True(t, ok)
assert.NotNil(t, m)
})
t.Run("returns false if middleware not found", func(t *testing.T) {
_, ok := s.Get(Metadata{Name: "test3", Type: "middleware"})
assert.False(t, ok)
})
t.Run("returns false if version mismatch", func(t *testing.T) {
_, ok := s.Get(Metadata{Name: "test", Type: "middleware", Version: "v1"})
assert.False(t, ok)
})
t.Run("returns false if defaulted version mismatch", func(t *testing.T) {
m, ok := s.Get(Metadata{Name: "test", Type: "middleware", Version: ""})
assert.False(t, ok)
assert.Nil(t, m)
})
t.Run("returns false if type mismatch", func(t *testing.T) {
_, ok := s.Get(Metadata{Name: "test", Type: "other", Version: "v2"})
assert.False(t, ok)
})
t.Run("removing midllware that doesn't exist is a noop", func(t *testing.T) {
s.Remove("test3")
assert.Len(t, s.loaded, 2)
})
t.Run("can remove middleware", func(t *testing.T) {
s.Remove("test")
assert.Len(t, s.loaded, 1)
m, ok := s.Get(Metadata{Name: "test", Type: "middleware", Version: "v2"})
assert.False(t, ok)
assert.Nil(t, m)
s.Remove("test2")
assert.Empty(t, s.loaded)
m, ok = s.Get(Metadata{Name: "test2", Type: "middleware"})
assert.False(t, ok)
assert.Nil(t, m)
})
}
|
mikeee/dapr
|
pkg/middleware/store/store_test.go
|
GO
|
mit
| 2,968 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package modes
// DaprMode is the runtime mode for Dapr.
type DaprMode string
const (
// KubernetesMode is a Kubernetes Dapr mode.
KubernetesMode DaprMode = "kubernetes"
// StandaloneMode is a Standalone Dapr mode.
StandaloneMode DaprMode = "standalone"
)
|
mikeee/dapr
|
pkg/modes/modes.go
|
GO
|
mit
| 822 |
/*
Copyright 2022 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package nethttpadaptor
import (
"fmt"
"io"
"net"
"net/http"
"strconv"
chi "github.com/go-chi/chi/v5"
"github.com/valyala/fasthttp"
diagUtils "github.com/dapr/dapr/pkg/diagnostics/utils"
"github.com/dapr/kit/logger"
)
var log = logger.NewLogger("dapr.nethttpadaptor")
// NewNetHTTPHandlerFunc wraps a fasthttp.RequestHandler in a http.HandlerFunc.
func NewNetHTTPHandlerFunc(h fasthttp.RequestHandler) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c := fasthttp.RequestCtx{}
remoteIP := net.ParseIP(r.RemoteAddr)
remoteAddr := net.IPAddr{
IP: remoteIP,
Zone: "",
}
c.Init(&fasthttp.Request{}, &remoteAddr, nil)
if r.Body != nil {
reqBody, err := io.ReadAll(r.Body)
if err != nil {
msg := fmt.Sprintf("error reading request body: %v", err)
log.Errorf(msg)
http.Error(w, msg, http.StatusBadRequest)
return
}
c.Request.SetBody(reqBody)
}
// Disable path normalization because we do not use a router after the fasthttp adapter
c.Request.URI().DisablePathNormalizing = true
c.Request.URI().SetQueryString(r.URL.RawQuery)
c.Request.URI().SetPath(r.URL.Path)
c.Request.URI().SetScheme(r.URL.Scheme)
c.Request.SetHost(r.Host)
c.Request.Header.SetMethod(r.Method)
c.Request.Header.Set("Proto", r.Proto)
major := strconv.Itoa(r.ProtoMajor)
minor := strconv.Itoa(r.ProtoMinor)
c.Request.Header.Set("Protomajor", major)
c.Request.Header.Set("Protominor", minor)
c.Request.Header.SetContentType(r.Header.Get("Content-Type"))
c.Request.Header.SetContentLength(int(r.ContentLength))
c.Request.Header.SetReferer(r.Referer())
c.Request.Header.SetUserAgent(r.UserAgent())
for _, cookie := range r.Cookies() {
c.Request.Header.SetCookie(cookie.Name, cookie.Value)
}
for k, v := range r.Header {
for _, i := range v {
c.Request.Header.Add(k, i)
}
}
// Ensure user values are propagated if the context is a fasthttp.RequestCtx already
if reqCtx, ok := r.Context().(*fasthttp.RequestCtx); ok {
reqCtx.VisitUserValuesAll(func(k any, v any) {
c.SetUserValue(k, v)
})
}
// Likewise, if the context is a chi context, propagate the values
if chiCtx := chi.RouteContext(r.Context()); chiCtx != nil {
for i, k := range chiCtx.URLParams.Keys {
c.SetUserValueBytes([]byte(k), chiCtx.URLParams.Values[i])
}
}
// Propagate the context
span := diagUtils.SpanFromContext(r.Context())
if span != nil {
diagUtils.AddSpanToFasthttpContext(&c, span)
}
// Invoke the handler
h(&c)
c.Response.Header.VisitAll(func(k []byte, v []byte) {
w.Header().Add(string(k), string(v))
})
status := c.Response.StatusCode()
w.WriteHeader(status)
c.Response.BodyWriteTo(w)
})
}
|
mikeee/dapr
|
pkg/nethttpadaptor/nethttpadaptor.go
|
GO
|
mit
| 3,313 |
/*
Copyright 2022 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package nethttpadaptor
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/valyala/fasthttp"
)
func TestNewNetHTTPHandlerFuncRequests(t *testing.T) {
tests := []struct {
name string
inputRequestFactory func() *http.Request
evaluateFactory func(t *testing.T) func(ctx *fasthttp.RequestCtx)
}{
{
"Get method is handled",
func() *http.Request {
return httptest.NewRequest(http.MethodGet, "http://localhost:8080/test", nil)
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
assert.Equal(t, http.MethodGet, string(ctx.Method()))
}
},
},
{
"Post method is handled",
func() *http.Request {
return httptest.NewRequest(http.MethodPost, "http://localhost:8080/test", nil)
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
assert.Equal(t, http.MethodPost, string(ctx.Method()))
}
},
},
{
"Put method is handled",
func() *http.Request {
return httptest.NewRequest(http.MethodPut, "http://localhost:8080/test", nil)
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
assert.Equal(t, http.MethodPut, string(ctx.Method()))
}
},
},
{
"Options method is handled",
func() *http.Request {
return httptest.NewRequest(http.MethodOptions, "http://localhost:8080/test", nil)
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
assert.Equal(t, http.MethodOptions, string(ctx.Method()))
}
},
},
{
"Patch method is handled",
func() *http.Request {
return httptest.NewRequest(http.MethodPatch, "http://localhost:8080/test", nil)
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
assert.Equal(t, http.MethodPatch, string(ctx.Method()))
}
},
},
{
"Delete method is handled",
func() *http.Request {
return httptest.NewRequest(http.MethodDelete, "http://localhost:8080/test", nil)
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
assert.Equal(t, http.MethodDelete, string(ctx.Method()))
}
},
},
{
"Host is handled",
func() *http.Request {
return httptest.NewRequest(http.MethodGet, "http://localhost:8080/test", nil)
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
assert.Equal(t, "localhost:8080", string(ctx.Host()))
}
},
},
{
"Path is handled",
func() *http.Request {
return httptest.NewRequest(http.MethodGet, "http://localhost:8080/test/sub", nil)
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
assert.Equal(t, "/test/sub", string(ctx.Path()))
}
},
},
{
"Body is handled",
func() *http.Request {
body := strings.NewReader("test body!")
return httptest.NewRequest(http.MethodGet, "http://localhost:8080/test/sub", body)
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
assert.Equal(t, "test body!", string(ctx.Request.Body()))
}
},
},
{
"Querystring is handled",
func() *http.Request {
return httptest.NewRequest(http.MethodGet, "http://localhost:8080/test/sub?alice=bob&version=0.1.2", nil)
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
assert.Equal(t, "alice=bob&version=0.1.2", string(ctx.Request.URI().QueryString()))
}
},
},
{
"Headers are handled",
func() *http.Request {
req := httptest.NewRequest(http.MethodGet, "http://localhost:8080/test/sub?alice=bob&version=0.1.2", nil)
req.Header.Add("testHeaderKey1", "testHeaderValue1")
req.Header.Add("testHeaderKey2", "testHeaderValue2")
req.Header.Add("testHeaderKey3", "testHeaderValue3")
return req
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
var header1Found bool
var header2Found bool
var header3Found bool
ctx.Request.Header.VisitAll(func(k []byte, v []byte) {
switch string(k) {
case "Testheaderkey1":
header1Found = true
case "Testheaderkey2":
header2Found = true
case "Testheaderkey3":
header3Found = true
}
})
assert.True(t, header1Found, "header1Found should be true but is false")
assert.True(t, header2Found, "header2Found should be true but is false")
assert.True(t, header3Found, "header3Found should be true but is false")
}
},
},
{
"Duplicate headers are handled",
func() *http.Request {
req := httptest.NewRequest(http.MethodGet, "http://localhost:8080/test/sub?alice=bob&version=0.1.2", nil)
req.Header.Add("testHeaderKey1", "testHeaderValue1")
req.Header.Add("testHeaderKey1", "testHeaderValue2")
req.Header.Add("testHeaderKey1", "testHeaderValue3")
return req
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
var headerValue1Found bool
var headerValue2Found bool
var headerValue3Found bool
ctx.Request.Header.VisitAll(func(k []byte, v []byte) {
if string(k) == "Testheaderkey1" {
switch string(v) {
case "testHeaderValue1":
headerValue1Found = true
case "testHeaderValue2":
headerValue2Found = true
case "testHeaderValue3":
headerValue3Found = true
}
}
})
assert.True(t, headerValue1Found, "headerValue1Found should be true but is false")
assert.True(t, headerValue2Found, "headerValue2Found should be true but is false")
assert.True(t, headerValue3Found, "headerValue3Found should be true but is false")
}
},
},
{
"Scheme is handled",
func() *http.Request {
return httptest.NewRequest(http.MethodGet, "https://localhost:8080", nil)
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
assert.Equal(t, "https", string(ctx.Request.URI().Scheme()))
}
},
},
{
"Content-Type is handled",
func() *http.Request {
req := httptest.NewRequest(http.MethodGet, "https://localhost:8080", nil)
req.Header.Add("Content-Type", "application/json")
return req
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
assert.Equal(t, "application/json", string(ctx.Request.Header.ContentType()))
}
},
},
{
"Content-Type with boundary is handled",
func() *http.Request {
req := httptest.NewRequest(http.MethodGet, "https://localhost:8080", nil)
req.Header.Add("Content-Type", "multipart/form-data; boundary=test-boundary")
return req
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
assert.Equal(t, "multipart/form-data; boundary=test-boundary", string(ctx.Request.Header.ContentType()))
}
},
},
{
"User-Agent is handled",
func() *http.Request {
req := httptest.NewRequest(http.MethodGet, "https://localhost:8080", nil)
req.Header.Add("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36")
return req
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
assert.Equal(t, "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36", string(ctx.Request.Header.UserAgent()))
}
},
},
{
"Referer is handled",
func() *http.Request {
req := httptest.NewRequest(http.MethodGet, "https://localhost:8080", nil)
req.Header.Add("Referer", "testReferer")
return req
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
assert.Equal(t, "testReferer", string(ctx.Request.Header.Referer()))
}
},
},
{
"BasicAuth is handled",
func() *http.Request {
req := httptest.NewRequest(http.MethodGet, "https://localhost:8080", nil)
req.Header.Add("Authorization", "Basic YWxhZGRpbjpvcGVuc2VzYW1l") // b64(aladdin:opensesame)
return req
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
var basicAuth string
ctx.Request.Header.VisitAll(func(k []byte, v []byte) {
if string(k) == "Authorization" {
basicAuth = string(v)
}
})
assert.Equal(t, "Basic YWxhZGRpbjpvcGVuc2VzYW1l", basicAuth)
}
},
},
{
"RemoteAddr is handled",
func() *http.Request {
req := httptest.NewRequest(http.MethodGet, "https://localhost:8080", nil)
req.RemoteAddr = "1.1.1.1"
return req
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
assert.Equal(t, "1.1.1.1", ctx.RemoteAddr().String())
}
},
},
{
"nil body is handled",
func() *http.Request {
req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://localhost:8080", nil)
return req
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
assert.Empty(t, ctx.Request.Body())
}
},
},
{
"proto headers are handled",
func() *http.Request {
req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://localhost:8080", nil)
return req
},
func(t *testing.T) func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
var major, minor string
ctx.Request.Header.VisitAll(func(k []byte, v []byte) {
if strings.EqualFold(string(k), "protomajor") {
major = string(v)
}
if strings.EqualFold(string(k), "protominor") {
minor = string(v)
}
})
assert.Equal(t, "1", major)
assert.Equal(t, "1", minor)
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := tt.inputRequestFactory()
handler := NewNetHTTPHandlerFunc(tt.evaluateFactory(t))
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
})
}
}
func TestNewNetHTTPHandlerFuncResponses(t *testing.T) {
tests := []struct {
name string
inputHandlerFactory func() fasthttp.RequestHandler
inputRequestFactory func() *http.Request
evaluate func(t *testing.T, res *http.Response)
}{
{
"200 status code is handled",
func() fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
ctx.SetStatusCode(200)
}
},
func() *http.Request {
return httptest.NewRequest(http.MethodGet, "http://localhost:8080/test", nil)
},
func(t *testing.T, res *http.Response) {
assert.Equal(t, 200, res.StatusCode)
},
},
{
"500 status code is handled",
func() fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
ctx.SetStatusCode(500)
}
},
func() *http.Request {
return httptest.NewRequest(http.MethodGet, "http://localhost:8080/test", nil)
},
func(t *testing.T, res *http.Response) {
assert.Equal(t, 500, res.StatusCode)
},
},
{
"400 status code is handled",
func() fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
ctx.SetStatusCode(400)
}
},
func() *http.Request {
return httptest.NewRequest(http.MethodGet, "http://localhost:8080/test", nil)
},
func(t *testing.T, res *http.Response) {
assert.Equal(t, 400, res.StatusCode)
},
},
{
"Body is handled",
func() fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
ctx.Response.SetBodyString("test body!")
}
},
func() *http.Request {
return httptest.NewRequest(http.MethodGet, "http://localhost:8080/test", nil)
},
func(t *testing.T, res *http.Response) {
body, _ := io.ReadAll(res.Body)
assert.Equal(t, "test body!", string(body))
},
},
{
"Single headers are handled",
func() fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
ctx.Response.Header.SetContentType("application/json")
}
},
func() *http.Request {
return httptest.NewRequest(http.MethodGet, "http://localhost:8080/test", nil)
},
func(t *testing.T, res *http.Response) {
key := res.Header.Get("Content-Type")
assert.Equal(t, "application/json", key)
},
},
{
"Duplicate headers are handled",
func() fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
ctx.Response.Header.Add("X-Transfer-Encoding", "chunked")
ctx.Response.Header.Add("X-Transfer-Encoding", "compress")
ctx.Response.Header.Add("X-Transfer-Encoding", "deflate")
ctx.Response.Header.Add("X-Transfer-Encoding", "gzip")
}
},
func() *http.Request {
return httptest.NewRequest(http.MethodGet, "http://localhost:8080/test", nil)
},
func(t *testing.T, res *http.Response) {
encodings := res.TransferEncoding // TODO: How to set this property?
if encodings == nil {
encodings = res.Header["X-Transfer-Encoding"]
}
var chunked, compress, deflate, gzip bool
for _, encoding := range encodings {
switch encoding {
case "chunked":
chunked = true
case "compress":
compress = true
case "deflate":
deflate = true
case "gzip":
gzip = true
}
}
assert.True(t, chunked, "expected chunked to be true but was false")
assert.True(t, compress, "expected compress to be true but was false")
assert.True(t, deflate, "expected deflate to be true but was false")
assert.True(t, gzip, "expected gzip to be true but was false")
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
handler := tt.inputHandlerFactory()
request := tt.inputRequestFactory()
newNetHTTPHandler := NewNetHTTPHandlerFunc(handler)
w := httptest.NewRecorder()
newNetHTTPHandler.ServeHTTP(w, request)
res := w.Result()
defer res.Body.Close()
tt.evaluate(t, res)
})
}
}
|
mikeee/dapr
|
pkg/nethttpadaptor/nethttpadaptor_test.go
|
GO
|
mit
| 14,810 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package api
import (
"context"
"errors"
"fmt"
"net"
"strconv"
"sync"
"sync/atomic"
"google.golang.org/grpc"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
componentsapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
httpendpointsapi "github.com/dapr/dapr/pkg/apis/httpEndpoint/v1alpha1"
subapi "github.com/dapr/dapr/pkg/apis/subscriptions/v2alpha1"
"github.com/dapr/dapr/pkg/operator/api/informer"
operatorv1pb "github.com/dapr/dapr/pkg/proto/operator/v1"
"github.com/dapr/dapr/pkg/security"
"github.com/dapr/kit/concurrency"
"github.com/dapr/kit/logger"
)
const (
APIVersionV1alpha1 = "dapr.io/v1alpha1"
APIVersionV2alpha1 = "dapr.io/v2alpha1"
kubernetesSecretStore = "kubernetes"
)
var log = logger.NewLogger("dapr.operator.api")
type Options struct {
Client client.Client
Cache cache.Cache
Security security.Provider
Port int
ListenAddress string
}
// Server runs the Dapr API server for components and configurations.
type Server interface {
Run(context.Context) error
Ready(context.Context) error
OnSubscriptionUpdated(context.Context, operatorv1pb.ResourceEventType, *subapi.Subscription)
OnHTTPEndpointUpdated(context.Context, *httpendpointsapi.HTTPEndpoint)
}
type apiServer struct {
operatorv1pb.UnimplementedOperatorServer
Client client.Client
sec security.Provider
port string
listenAddress string
compInformer informer.Interface[componentsapi.Component]
endpointLock sync.Mutex
allEndpointsUpdateChan map[string]chan *httpendpointsapi.HTTPEndpoint
allSubscriptionUpdateChan map[string]chan *SubscriptionUpdateEvent
connLock sync.Mutex
readyCh chan struct{}
running atomic.Bool
}
// NewAPIServer returns a new API server.
func NewAPIServer(opts Options) Server {
return &apiServer{
Client: opts.Client,
compInformer: informer.New[componentsapi.Component](informer.Options{
Cache: opts.Cache,
}),
sec: opts.Security,
port: strconv.Itoa(opts.Port),
listenAddress: opts.ListenAddress,
allEndpointsUpdateChan: make(map[string]chan *httpendpointsapi.HTTPEndpoint),
allSubscriptionUpdateChan: make(map[string]chan *SubscriptionUpdateEvent),
readyCh: make(chan struct{}),
}
}
// Run starts a new gRPC server.
func (a *apiServer) Run(ctx context.Context) error {
if !a.running.CompareAndSwap(false, true) {
return errors.New("api server already running")
}
log.Infof("Starting gRPC server on %s:%s", a.listenAddress, a.port)
sec, err := a.sec.Handler(ctx)
if err != nil {
return err
}
s := grpc.NewServer(sec.GRPCServerOptionMTLS())
operatorv1pb.RegisterOperatorServer(s, a)
lis, err := net.Listen("tcp", fmt.Sprintf("%s:%s", a.listenAddress, a.port))
if err != nil {
return fmt.Errorf("error starting tcp listener: %w", err)
}
close(a.readyCh)
return concurrency.NewRunnerManager(
a.compInformer.Run,
func(ctx context.Context) error {
if err := s.Serve(lis); err != nil {
return fmt.Errorf("gRPC server error: %w", err)
}
return nil
},
func(ctx context.Context) error {
// Block until context is done
<-ctx.Done()
a.connLock.Lock()
for key, ch := range a.allSubscriptionUpdateChan {
close(ch)
delete(a.allSubscriptionUpdateChan, key)
}
a.connLock.Unlock()
s.GracefulStop()
return nil
},
).Run(ctx)
}
func (a *apiServer) Ready(ctx context.Context) error {
select {
case <-a.readyCh:
return nil
case <-ctx.Done():
return errors.New("timeout waiting for api server to be ready")
}
}
|
mikeee/dapr
|
pkg/operator/api/api.go
|
GO
|
mit
| 4,263 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package api
import (
"context"
"encoding/base64"
"encoding/json"
"sync/atomic"
"testing"
"time"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/yaml"
commonapi "github.com/dapr/dapr/pkg/apis/common"
componentsapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
httpendpointapi "github.com/dapr/dapr/pkg/apis/httpEndpoint/v1alpha1"
resiliencyapi "github.com/dapr/dapr/pkg/apis/resiliency/v1alpha1"
subscriptionsapiV2alpha1 "github.com/dapr/dapr/pkg/apis/subscriptions/v2alpha1"
"github.com/dapr/dapr/pkg/client/clientset/versioned/scheme"
"github.com/dapr/dapr/pkg/operator/api/informer"
informerfake "github.com/dapr/dapr/pkg/operator/api/informer/fake"
operatorv1pb "github.com/dapr/dapr/pkg/proto/operator/v1"
"github.com/dapr/kit/crypto/test"
)
type mockComponentUpdateServer struct {
grpc.ServerStream
Calls atomic.Int64
ctx context.Context
}
func (m *mockComponentUpdateServer) Send(*operatorv1pb.ComponentUpdateEvent) error {
m.Calls.Add(1)
return nil
}
func (m *mockComponentUpdateServer) Context() context.Context {
return m.ctx
}
type mockHTTPEndpointUpdateServer struct {
grpc.ServerStream
Calls atomic.Int64
ctx context.Context
}
func (m *mockHTTPEndpointUpdateServer) Send(*operatorv1pb.HTTPEndpointUpdateEvent) error {
m.Calls.Add(1)
return nil
}
func (m *mockHTTPEndpointUpdateServer) Context() context.Context {
return m.ctx
}
func TestProcessComponentSecrets(t *testing.T) {
t.Run("secret ref exists, not kubernetes secret store, no error", func(t *testing.T) {
c := componentsapi.Component{
Spec: componentsapi.ComponentSpec{
Metadata: []commonapi.NameValuePair{
{
Name: "test1",
SecretKeyRef: commonapi.SecretKeyRef{
Name: "secret1",
Key: "key1",
},
},
},
},
Auth: componentsapi.Auth{
SecretStore: "secretstore",
},
}
err := processComponentSecrets(context.Background(), &c, "default", nil)
require.NoError(t, err)
})
t.Run("secret ref exists, kubernetes secret store, secret extracted", func(t *testing.T) {
c := componentsapi.Component{
Spec: componentsapi.ComponentSpec{
Metadata: []commonapi.NameValuePair{
{
Name: "test1",
SecretKeyRef: commonapi.SecretKeyRef{
Name: "secret1",
Key: "key1",
},
},
},
},
Auth: componentsapi.Auth{
SecretStore: kubernetesSecretStore,
},
}
s := runtime.NewScheme()
err := scheme.AddToScheme(s)
require.NoError(t, err)
err = corev1.AddToScheme(s)
require.NoError(t, err)
client := fake.NewClientBuilder().
WithScheme(s).
WithObjects(&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret1",
Namespace: "default",
},
Data: map[string][]byte{
"key1": []byte("value1"),
},
}).
Build()
err = processComponentSecrets(context.Background(), &c, "default", client)
require.NoError(t, err)
enc := base64.StdEncoding.EncodeToString([]byte("value1"))
jsonEnc, _ := json.Marshal(enc)
assert.Equal(t, jsonEnc, c.Spec.Metadata[0].Value.Raw)
})
t.Run("secret ref exists, default kubernetes secret store, secret extracted", func(t *testing.T) {
c := componentsapi.Component{
Spec: componentsapi.ComponentSpec{
Metadata: []commonapi.NameValuePair{
{
Name: "test1",
SecretKeyRef: commonapi.SecretKeyRef{
Name: "secret1",
Key: "key1",
},
},
},
},
Auth: componentsapi.Auth{
SecretStore: "",
},
}
s := runtime.NewScheme()
err := scheme.AddToScheme(s)
require.NoError(t, err)
err = corev1.AddToScheme(s)
require.NoError(t, err)
client := fake.NewClientBuilder().
WithScheme(s).
WithObjects(&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret1",
Namespace: "default",
},
Data: map[string][]byte{
"key1": []byte("value1"),
},
}).
Build()
err = processComponentSecrets(context.Background(), &c, "default", client)
require.NoError(t, err)
enc := base64.StdEncoding.EncodeToString([]byte("value1"))
jsonEnc, _ := json.Marshal(enc)
assert.Equal(t, jsonEnc, c.Spec.Metadata[0].Value.Raw)
})
}
func TestComponentUpdate(t *testing.T) {
appID := spiffeid.RequireFromString("spiffe://example.org/ns/ns1/app1")
serverID := spiffeid.RequireFromString("spiffe://example.org/ns/dapr-system/dapr-operator")
pki := test.GenPKI(t, test.PKIOptions{
LeafID: serverID,
ClientID: appID,
})
t.Run("expect error if requesting for different namespace", func(t *testing.T) {
s := runtime.NewScheme()
err := scheme.AddToScheme(s)
require.NoError(t, err)
err = corev1.AddToScheme(s)
require.NoError(t, err)
client := fake.NewClientBuilder().
WithScheme(s).Build()
mockSidecar := &mockComponentUpdateServer{ctx: pki.ClientGRPCCtx(t)}
api := NewAPIServer(Options{Client: client}).(*apiServer)
// Start sidecar update loop
err = api.ComponentUpdate(&operatorv1pb.ComponentUpdateRequest{
Namespace: "ns2",
}, mockSidecar)
require.Error(t, err)
status, ok := status.FromError(err)
require.True(t, ok)
assert.Equal(t, codes.PermissionDenied, status.Code())
assert.Equal(t, int64(0), mockSidecar.Calls.Load())
})
t.Run("skip sidecar update if namespace doesn't match", func(t *testing.T) {
c := componentsapi.Component{
ObjectMeta: metav1.ObjectMeta{
Namespace: "ns2",
},
Spec: componentsapi.ComponentSpec{},
}
fakeInformer := informerfake.New[componentsapi.Component]().
WithWatchUpdates(func(context.Context, string) (<-chan *informer.Event[componentsapi.Component], error) {
ch := make(chan *informer.Event[componentsapi.Component])
go func() {
ch <- &informer.Event[componentsapi.Component]{
Manifest: c,
Type: operatorv1pb.ResourceEventType_CREATED,
}
close(ch)
}()
return ch, nil
})
s := runtime.NewScheme()
err := scheme.AddToScheme(s)
require.NoError(t, err)
err = corev1.AddToScheme(s)
require.NoError(t, err)
client := fake.NewClientBuilder().
WithScheme(s).Build()
mockSidecar := &mockComponentUpdateServer{ctx: pki.ClientGRPCCtx(t)}
api := NewAPIServer(Options{Client: client}).(*apiServer)
api.compInformer = fakeInformer
// Start sidecar update loop
require.NoError(t, api.ComponentUpdate(&operatorv1pb.ComponentUpdateRequest{
Namespace: "ns1",
}, mockSidecar))
assert.Equal(t, int64(0), mockSidecar.Calls.Load())
})
t.Run("sidecar is updated when component namespace is a match", func(t *testing.T) {
c := componentsapi.Component{
ObjectMeta: metav1.ObjectMeta{
Namespace: "ns1",
},
Spec: componentsapi.ComponentSpec{},
}
fakeInformer := informerfake.New[componentsapi.Component]().
WithWatchUpdates(func(context.Context, string) (<-chan *informer.Event[componentsapi.Component], error) {
ch := make(chan *informer.Event[componentsapi.Component])
go func() {
ch <- &informer.Event[componentsapi.Component]{
Manifest: c,
Type: operatorv1pb.ResourceEventType_CREATED,
}
close(ch)
}()
return ch, nil
})
s := runtime.NewScheme()
err := scheme.AddToScheme(s)
require.NoError(t, err)
err = corev1.AddToScheme(s)
require.NoError(t, err)
client := fake.NewClientBuilder().
WithScheme(s).Build()
mockSidecar := &mockComponentUpdateServer{ctx: pki.ClientGRPCCtx(t)}
api := NewAPIServer(Options{Client: client}).(*apiServer)
api.compInformer = fakeInformer
// Start sidecar update loop
api.ComponentUpdate(&operatorv1pb.ComponentUpdateRequest{
Namespace: "ns1",
}, mockSidecar)
assert.Equal(t, int64(1), mockSidecar.Calls.Load())
})
}
func TestHTTPEndpointUpdate(t *testing.T) {
appID := spiffeid.RequireFromString("spiffe://example.org/ns/ns1/app1")
serverID := spiffeid.RequireFromString("spiffe://example.org/ns/dapr-system/dapr-operator")
pki := test.GenPKI(t, test.PKIOptions{
LeafID: serverID,
ClientID: appID,
})
s := runtime.NewScheme()
err := scheme.AddToScheme(s)
require.NoError(t, err)
err = corev1.AddToScheme(s)
require.NoError(t, err)
client := fake.NewClientBuilder().
WithScheme(s).Build()
mockSidecar := &mockHTTPEndpointUpdateServer{ctx: pki.ClientGRPCCtx(t)}
api := NewAPIServer(Options{Client: client}).(*apiServer)
t.Run("expect error if requesting for different namespace", func(t *testing.T) {
// Start sidecar update loop
err := api.HTTPEndpointUpdate(&operatorv1pb.HTTPEndpointUpdateRequest{
Namespace: "ns2",
}, mockSidecar)
require.Error(t, err)
status, ok := status.FromError(err)
require.True(t, ok)
assert.Equal(t, codes.PermissionDenied, status.Code())
assert.Equal(t, int64(0), mockSidecar.Calls.Load())
})
t.Run("skip sidecar update if namespace doesn't match", func(t *testing.T) {
go func() {
assert.Eventually(t, func() bool {
api.endpointLock.Lock()
defer api.endpointLock.Unlock()
return len(api.allEndpointsUpdateChan) == 1
}, time.Second, 10*time.Millisecond)
api.endpointLock.Lock()
defer api.endpointLock.Unlock()
for key := range api.allEndpointsUpdateChan {
api.allEndpointsUpdateChan[key] <- &httpendpointapi.HTTPEndpoint{
ObjectMeta: metav1.ObjectMeta{
Namespace: "ns2",
},
Spec: httpendpointapi.HTTPEndpointSpec{},
}
close(api.allEndpointsUpdateChan[key])
}
}()
// Start sidecar update loop
require.NoError(t, api.HTTPEndpointUpdate(&operatorv1pb.HTTPEndpointUpdateRequest{
Namespace: "ns1",
}, mockSidecar))
assert.Equal(t, int64(0), mockSidecar.Calls.Load())
})
t.Run("sidecar is updated when endpoint namespace is a match", func(t *testing.T) {
go func() {
assert.Eventually(t, func() bool {
api.endpointLock.Lock()
defer api.endpointLock.Unlock()
return len(api.allEndpointsUpdateChan) == 1
}, time.Second, 10*time.Millisecond)
api.endpointLock.Lock()
defer api.endpointLock.Unlock()
for key := range api.allEndpointsUpdateChan {
api.allEndpointsUpdateChan[key] <- &httpendpointapi.HTTPEndpoint{
ObjectMeta: metav1.ObjectMeta{
Namespace: "ns1",
},
Spec: httpendpointapi.HTTPEndpointSpec{},
}
close(api.allEndpointsUpdateChan[key])
}
}()
// Start sidecar update loop
require.NoError(t, api.HTTPEndpointUpdate(&operatorv1pb.HTTPEndpointUpdateRequest{
Namespace: "ns1",
}, mockSidecar))
assert.Equal(t, int64(1), mockSidecar.Calls.Load())
})
}
func TestListScopes(t *testing.T) {
appID := spiffeid.RequireFromString("spiffe://example.org/ns/namespace-a/app1")
serverID := spiffeid.RequireFromString("spiffe://example.org/ns/dapr-system/dapr-operator")
pki := test.GenPKI(t, test.PKIOptions{
LeafID: serverID,
ClientID: appID,
})
t.Run("list components scoping", func(t *testing.T) {
av, kind := componentsapi.SchemeGroupVersion.WithKind("Component").ToAPIVersionAndKind()
typeMeta := metav1.TypeMeta{
Kind: kind,
APIVersion: av,
}
comp1 := &componentsapi.Component{
TypeMeta: typeMeta,
ObjectMeta: metav1.ObjectMeta{
Name: "obj1",
Namespace: "namespace-a",
},
}
comp2 := &componentsapi.Component{
TypeMeta: typeMeta,
ObjectMeta: metav1.ObjectMeta{
Name: "obj2",
Namespace: "namespace-a",
},
Scoped: commonapi.Scoped{Scopes: []string{"app1", "app2"}},
}
comp3 := &componentsapi.Component{
TypeMeta: typeMeta,
ObjectMeta: metav1.ObjectMeta{
Name: "obj3",
Namespace: "namespace-a",
},
Scoped: commonapi.Scoped{Scopes: []string{"notapp1", "app2"}},
}
s := runtime.NewScheme()
err := scheme.AddToScheme(s)
require.NoError(t, err)
err = componentsapi.AddToScheme(s)
require.NoError(t, err)
cl := fake.NewClientBuilder().
WithScheme(s).
WithObjects(comp1, comp2, comp3).
Build()
api := NewAPIServer(Options{Client: cl}).(*apiServer)
res, err := api.ListComponents(pki.ClientGRPCCtx(t), &operatorv1pb.ListComponentsRequest{
PodName: "foo",
Namespace: "namespace-a",
})
require.NoError(t, err)
require.Len(t, res.GetComponents(), 2)
var exp [][]byte
var b []byte
b, err = json.Marshal(comp1)
require.NoError(t, err)
exp = append(exp, b)
b, err = json.Marshal(comp2)
require.NoError(t, err)
exp = append(exp, b)
assert.ElementsMatch(t, exp, res.GetComponents())
})
}
func TestListsNamespaced(t *testing.T) {
appID := spiffeid.RequireFromString("spiffe://example.org/ns/namespace-a/app1")
serverID := spiffeid.RequireFromString("spiffe://example.org/ns/dapr-system/dapr-operator")
pki := test.GenPKI(t, test.PKIOptions{
LeafID: serverID,
ClientID: appID,
})
t.Run("list components namespace scoping", func(t *testing.T) {
s := runtime.NewScheme()
err := scheme.AddToScheme(s)
require.NoError(t, err)
err = componentsapi.AddToScheme(s)
require.NoError(t, err)
av, kind := componentsapi.SchemeGroupVersion.WithKind("Component").ToAPIVersionAndKind()
typeMeta := metav1.TypeMeta{
Kind: kind,
APIVersion: av,
}
cl := fake.NewClientBuilder().
WithScheme(s).
WithObjects(&componentsapi.Component{
TypeMeta: typeMeta,
ObjectMeta: metav1.ObjectMeta{
Name: "obj1",
Namespace: "namespace-a",
},
}, &componentsapi.Component{
TypeMeta: typeMeta,
ObjectMeta: metav1.ObjectMeta{
Name: "obj2",
Namespace: "namespace-b",
},
}).
Build()
api := NewAPIServer(Options{Client: cl}).(*apiServer)
res, err := api.ListComponents(pki.ClientGRPCCtx(t), &operatorv1pb.ListComponentsRequest{
PodName: "foo",
Namespace: "namespace-a",
})
require.NoError(t, err)
assert.Len(t, res.GetComponents(), 1)
var sub resiliencyapi.Resiliency
require.NoError(t, yaml.Unmarshal(res.GetComponents()[0], &sub))
assert.Equal(t, "obj1", sub.Name)
assert.Equal(t, "namespace-a", sub.Namespace)
res, err = api.ListComponents(pki.ClientGRPCCtx(t), &operatorv1pb.ListComponentsRequest{
PodName: "foo",
Namespace: "namespace-c",
})
require.Error(t, err)
assert.Empty(t, res.GetComponents())
})
t.Run("list subscriptions namespace scoping", func(t *testing.T) {
s := runtime.NewScheme()
err := scheme.AddToScheme(s)
require.NoError(t, err)
err = subscriptionsapiV2alpha1.AddToScheme(s)
require.NoError(t, err)
av, kind := subscriptionsapiV2alpha1.SchemeGroupVersion.WithKind("Subscription").ToAPIVersionAndKind()
typeMeta := metav1.TypeMeta{
Kind: kind,
APIVersion: av,
}
client := fake.NewClientBuilder().
WithScheme(s).
WithObjects(&subscriptionsapiV2alpha1.Subscription{
TypeMeta: typeMeta,
ObjectMeta: metav1.ObjectMeta{
Name: "sub1",
Namespace: "namespace-a",
},
}, &subscriptionsapiV2alpha1.Subscription{
TypeMeta: typeMeta,
ObjectMeta: metav1.ObjectMeta{
Name: "sub2",
Namespace: "namespace-b",
},
}).
Build()
api := NewAPIServer(Options{Client: client}).(*apiServer)
res, err := api.ListSubscriptionsV2(pki.ClientGRPCCtx(t), &operatorv1pb.ListSubscriptionsRequest{
PodName: "foo",
Namespace: "namespace-a",
})
require.NoError(t, err)
assert.Len(t, res.GetSubscriptions(), 1)
var sub subscriptionsapiV2alpha1.Subscription
err = yaml.Unmarshal(res.GetSubscriptions()[0], &sub)
require.NoError(t, err)
assert.Equal(t, "sub1", sub.Name)
assert.Equal(t, "namespace-a", sub.Namespace)
res, err = api.ListSubscriptionsV2(context.TODO(), &operatorv1pb.ListSubscriptionsRequest{
PodName: "baz",
Namespace: "namespace-c",
})
require.Error(t, err)
assert.Empty(t, res.GetSubscriptions())
})
t.Run("list resiliencies namespace scoping", func(t *testing.T) {
s := runtime.NewScheme()
err := scheme.AddToScheme(s)
require.NoError(t, err)
err = resiliencyapi.AddToScheme(s)
require.NoError(t, err)
av, kind := resiliencyapi.SchemeGroupVersion.WithKind("Resiliency").ToAPIVersionAndKind()
typeMeta := metav1.TypeMeta{
Kind: kind,
APIVersion: av,
}
client := fake.NewClientBuilder().
WithScheme(s).
WithObjects(&resiliencyapi.Resiliency{
TypeMeta: typeMeta,
ObjectMeta: metav1.ObjectMeta{
Name: "obj1",
Namespace: "namespace-a",
},
}, &resiliencyapi.Resiliency{
TypeMeta: typeMeta,
ObjectMeta: metav1.ObjectMeta{
Name: "obj2",
Namespace: "namespace-b",
},
}).
Build()
api := NewAPIServer(Options{Client: client}).(*apiServer)
res, err := api.ListResiliency(pki.ClientGRPCCtx(t), &operatorv1pb.ListResiliencyRequest{
Namespace: "namespace-a",
})
require.NoError(t, err)
assert.Len(t, res.GetResiliencies(), 1)
var sub resiliencyapi.Resiliency
err = yaml.Unmarshal(res.GetResiliencies()[0], &sub)
require.NoError(t, err)
assert.Equal(t, "obj1", sub.Name)
assert.Equal(t, "namespace-a", sub.Namespace)
res, err = api.ListResiliency(pki.ClientGRPCCtx(t), &operatorv1pb.ListResiliencyRequest{
Namespace: "namespace-c",
})
require.Error(t, err)
assert.Empty(t, res.GetResiliencies())
})
t.Run("list http endpoints namespace scoping", func(t *testing.T) {
s := runtime.NewScheme()
err := scheme.AddToScheme(s)
require.NoError(t, err)
err = httpendpointapi.AddToScheme(s)
require.NoError(t, err)
av, kind := httpendpointapi.SchemeGroupVersion.WithKind("HTTPEndpoint").ToAPIVersionAndKind()
typeMeta := metav1.TypeMeta{
Kind: kind,
APIVersion: av,
}
client := fake.NewClientBuilder().
WithScheme(s).
WithObjects(&httpendpointapi.HTTPEndpoint{
TypeMeta: typeMeta,
ObjectMeta: metav1.ObjectMeta{
Name: "obj1",
Namespace: "namespace-a",
},
}, &httpendpointapi.HTTPEndpoint{
TypeMeta: typeMeta,
ObjectMeta: metav1.ObjectMeta{
Name: "obj2",
Namespace: "namespace-b",
},
}).
Build()
api := NewAPIServer(Options{Client: client}).(*apiServer)
res, err := api.ListHTTPEndpoints(pki.ClientGRPCCtx(t), &operatorv1pb.ListHTTPEndpointsRequest{
Namespace: "namespace-a",
})
require.NoError(t, err)
assert.Len(t, res.GetHttpEndpoints(), 1)
var endpoint httpendpointapi.HTTPEndpoint
err = yaml.Unmarshal(res.GetHttpEndpoints()[0], &endpoint)
require.NoError(t, err)
assert.Equal(t, "obj1", endpoint.Name)
assert.Equal(t, "namespace-a", endpoint.Namespace)
res, err = api.ListHTTPEndpoints(context.TODO(), &operatorv1pb.ListHTTPEndpointsRequest{
Namespace: "namespace-c",
})
require.Error(t, err)
assert.Empty(t, res.GetHttpEndpoints())
})
}
func TestProcessHTTPEndpointSecrets(t *testing.T) {
e := httpendpointapi.HTTPEndpoint{
Spec: httpendpointapi.HTTPEndpointSpec{
BaseURL: "http://test.com/",
Headers: []commonapi.NameValuePair{
{
Name: "test1",
SecretKeyRef: commonapi.SecretKeyRef{
Name: "secret1",
Key: "key1",
},
},
},
},
Auth: httpendpointapi.Auth{
SecretStore: "secretstore",
},
}
t.Run("secret ref exists, not kubernetes secret store, no error", func(t *testing.T) {
err := processHTTPEndpointSecrets(context.Background(), &e, "default", nil)
require.NoError(t, err)
})
t.Run("secret ref exists, kubernetes secret store, secret extracted", func(t *testing.T) {
e.Auth.SecretStore = kubernetesSecretStore
s := runtime.NewScheme()
err := scheme.AddToScheme(s)
require.NoError(t, err)
err = corev1.AddToScheme(s)
require.NoError(t, err)
client := fake.NewClientBuilder().
WithScheme(s).
WithObjects(&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret1",
Namespace: "default",
},
Data: map[string][]byte{
"key1": []byte("value1"),
},
}).
Build()
require.NoError(t, processHTTPEndpointSecrets(context.Background(), &e, "default", client))
enc := base64.StdEncoding.EncodeToString([]byte("value1"))
jsonEnc, err := json.Marshal(enc)
require.NoError(t, err)
assert.Equal(t, jsonEnc, e.Spec.Headers[0].Value.Raw)
})
t.Run("secret ref exists, default kubernetes secret store, secret extracted", func(t *testing.T) {
e.Auth.SecretStore = ""
s := runtime.NewScheme()
err := scheme.AddToScheme(s)
require.NoError(t, err)
err = corev1.AddToScheme(s)
require.NoError(t, err)
client := fake.NewClientBuilder().
WithScheme(s).
WithObjects(&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret1",
Namespace: "default",
},
Data: map[string][]byte{
"key1": []byte("value1"),
},
}).
Build()
require.NoError(t, processHTTPEndpointSecrets(context.Background(), &e, "default", client))
enc := base64.StdEncoding.EncodeToString([]byte("value1"))
jsonEnc, err := json.Marshal(enc)
require.NoError(t, err)
assert.Equal(t, jsonEnc, e.Spec.Headers[0].Value.Raw)
})
}
func Test_Ready(t *testing.T) {
tests := map[string]struct {
readyCh func() chan struct{}
ctx func() context.Context
expErr bool
}{
"if readyCh is closed, then expect no error": {
readyCh: func() chan struct{} {
ch := make(chan struct{})
close(ch)
return ch
},
ctx: context.Background,
expErr: false,
},
"if context is cancelled, then expect error": {
readyCh: func() chan struct{} {
ch := make(chan struct{})
return ch
},
ctx: func() context.Context {
ctx, cancel := context.WithCancel(context.Background())
cancel()
return ctx
},
expErr: true,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
err := (&apiServer{readyCh: test.readyCh()}).Ready(test.ctx())
assert.Equal(t, test.expErr, err != nil, err)
})
}
}
|
mikeee/dapr
|
pkg/operator/api/api_test.go
|
GO
|
mit
| 22,491 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package authz
import (
"context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/dapr/dapr/pkg/security/spiffe"
)
// Request ensures that the requesting identity resides in the same
// namespace as that of the requested namespace.
func Request(ctx context.Context, namespace string) (*spiffe.Parsed, error) {
id, ok, err := spiffe.FromGRPCContext(ctx)
if err != nil || !ok {
return nil, status.New(codes.PermissionDenied, "failed to determine identity").Err()
}
if len(namespace) == 0 || id.Namespace() != namespace {
return nil, status.New(codes.PermissionDenied, "identity does not match requested namespace").Err()
}
return id, nil
}
|
mikeee/dapr
|
pkg/operator/api/authz/authz.go
|
GO
|
mit
| 1,245 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package authz
import (
"context"
"testing"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/dapr/dapr/pkg/security/spiffe"
"github.com/dapr/kit/crypto/test"
)
func Test_Request(t *testing.T) {
appID := spiffeid.RequireFromString("spiffe://example.org/ns/ns1/app1")
serverID := spiffeid.RequireFromString("spiffe://example.org/ns/dapr-system/dapr-operator")
pki := test.GenPKI(t, test.PKIOptions{LeafID: serverID, ClientID: appID})
t.Run("no auth context should error", func(t *testing.T) {
id, err := Request(context.Background(), "ns1")
require.Error(t, err)
assert.Equal(t, codes.PermissionDenied, status.Code(err))
assert.Nil(t, id)
})
t.Run("different namespace should error", func(t *testing.T) {
id, err := Request(pki.ClientGRPCCtx(t), "ns2")
require.Error(t, err)
assert.Equal(t, codes.PermissionDenied, status.Code(err))
assert.Nil(t, id)
})
t.Run("empty namespace should error", func(t *testing.T) {
id, err := Request(pki.ClientGRPCCtx(t), "")
require.Error(t, err)
assert.Equal(t, codes.PermissionDenied, status.Code(err))
assert.Nil(t, id)
})
t.Run("invalid SPIFFE path should error", func(t *testing.T) {
appID := spiffeid.RequireFromString("spiffe://example.org/foo/bar")
pki2 := test.GenPKI(t, test.PKIOptions{LeafID: serverID, ClientID: appID})
id, err := Request(pki2.ClientGRPCCtx(t), "ns1")
require.Error(t, err)
assert.Equal(t, codes.PermissionDenied, status.Code(err))
assert.Nil(t, id)
})
t.Run("same namespace should no error", func(t *testing.T) {
ctx := pki.ClientGRPCCtx(t)
id, err := Request(ctx, "ns1")
require.NoError(t, err)
expID, err := spiffe.FromStrings(
spiffeid.RequireTrustDomainFromString("example.org"),
"ns1", "app1")
require.NoError(t, err)
assert.Equal(t, expID, id)
})
}
|
mikeee/dapr
|
pkg/operator/api/authz/authz_test.go
|
GO
|
mit
| 2,504 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package api
import (
"context"
b64 "encoding/base64"
"encoding/json"
"fmt"
"sync"
corev1 "k8s.io/api/core/v1"
v1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
commonapi "github.com/dapr/dapr/pkg/apis/common"
componentsapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
httpendpointsapi "github.com/dapr/dapr/pkg/apis/httpEndpoint/v1alpha1"
"github.com/dapr/dapr/pkg/operator/api/authz"
operatorv1pb "github.com/dapr/dapr/pkg/proto/operator/v1"
"github.com/dapr/dapr/utils"
)
type ComponentUpdateEvent struct {
Component *componentsapi.Component
EventType operatorv1pb.ResourceEventType
}
// ComponentUpdate updates Dapr sidecars whenever a component in the cluster is modified.
// TODO: @joshvanl: Authorize pod name and namespace matches the SPIFFE ID of
// the caller.
func (a *apiServer) ComponentUpdate(in *operatorv1pb.ComponentUpdateRequest, srv operatorv1pb.Operator_ComponentUpdateServer) error { //nolint:nosnakecase
log.Info("sidecar connected for component updates")
ch, err := a.compInformer.WatchUpdates(srv.Context(), in.GetNamespace())
if err != nil {
return err
}
updateComponentFunc := func(ctx context.Context, t operatorv1pb.ResourceEventType, c *componentsapi.Component) {
if c.Namespace != in.GetNamespace() {
return
}
err := processComponentSecrets(ctx, c, in.GetNamespace(), a.Client)
if err != nil {
log.Warnf("error processing component %s secrets from pod %s/%s: %s", c.Name, in.GetNamespace(), in.GetPodName(), err)
return
}
b, err := json.Marshal(&c)
if err != nil {
log.Warnf("error serializing component %s (%s) from pod %s/%s: %s", c.GetName(), c.Spec.Type, in.GetNamespace(), in.GetPodName(), err)
return
}
err = srv.Send(&operatorv1pb.ComponentUpdateEvent{
Component: b,
Type: t,
})
if err != nil {
log.Warnf("error updating sidecar with component %s (%s) from pod %s/%s: %s", c.GetName(), c.Spec.Type, in.GetNamespace(), in.GetPodName(), err)
return
}
log.Debugf("updated sidecar with component %s %s (%s) from pod %s/%s", t.String(), c.GetName(), c.Spec.Type, in.GetNamespace(), in.GetPodName())
}
var wg sync.WaitGroup
defer wg.Wait()
for {
select {
case <-srv.Context().Done():
return nil
case event, ok := <-ch:
if !ok {
return nil
}
updateComponentFunc(srv.Context(), event.Type, &event.Manifest)
}
}
}
// ListComponents returns a list of Dapr components.
func (a *apiServer) ListComponents(ctx context.Context, in *operatorv1pb.ListComponentsRequest) (*operatorv1pb.ListComponentResponse, error) {
id, err := authz.Request(ctx, in.GetNamespace())
if err != nil {
return nil, err
}
var components componentsapi.ComponentList
if err := a.Client.List(ctx, &components, &client.ListOptions{
Namespace: in.GetNamespace(),
}); err != nil {
return nil, fmt.Errorf("error getting components: %w", err)
}
resp := &operatorv1pb.ListComponentResponse{
Components: [][]byte{},
}
appID := id.AppID()
for i := range components.Items {
if !(len(components.Items[i].Scopes) == 0 || utils.Contains(components.Items[i].Scopes, appID)) {
continue
}
c := components.Items[i] // Make a copy since we will refer to this as a reference in this loop.
err := processComponentSecrets(ctx, &c, in.GetNamespace(), a.Client)
if err != nil {
log.Warnf("error processing component %s secrets from pod %s/%s: %s", c.Name, in.GetNamespace(), in.GetPodName(), err)
return &operatorv1pb.ListComponentResponse{}, err
}
b, err := json.Marshal(&c)
if err != nil {
log.Warnf("error marshalling component %s from pod %s/%s: %s", c.Name, in.GetNamespace(), in.GetPodName(), err)
continue
}
resp.Components = append(resp.GetComponents(), b)
}
return resp, nil
}
func processComponentSecrets(ctx context.Context, component *componentsapi.Component, namespace string, kubeClient client.Client) error {
for i, m := range component.Spec.Metadata {
if m.SecretKeyRef.Name != "" && (component.Auth.SecretStore == kubernetesSecretStore || component.Auth.SecretStore == "") {
var secret corev1.Secret
err := kubeClient.Get(ctx, types.NamespacedName{
Name: m.SecretKeyRef.Name,
Namespace: namespace,
}, &secret)
if err != nil {
return err
}
key := m.SecretKeyRef.Key
if key == "" {
key = m.SecretKeyRef.Name
}
val, ok := secret.Data[key]
if ok {
enc := b64.StdEncoding.EncodeToString(val)
jsonEnc, err := json.Marshal(enc)
if err != nil {
return err
}
component.Spec.Metadata[i].Value = commonapi.DynamicValue{
JSON: v1.JSON{
Raw: jsonEnc,
},
}
}
}
}
return nil
}
func pairNeedsSecretExtraction(ref commonapi.SecretKeyRef, auth httpendpointsapi.Auth) bool {
return ref.Name != "" && (auth.SecretStore == kubernetesSecretStore || auth.SecretStore == "")
}
func getSecret(ctx context.Context, name, namespace string, ref commonapi.SecretKeyRef, kubeClient client.Client) (commonapi.DynamicValue, error) {
var secret corev1.Secret
err := kubeClient.Get(ctx, types.NamespacedName{
Name: name,
Namespace: namespace,
}, &secret)
if err != nil {
return commonapi.DynamicValue{}, err
}
key := ref.Key
if key == "" {
key = ref.Name
}
val, ok := secret.Data[key]
if ok {
enc := b64.StdEncoding.EncodeToString(val)
jsonEnc, err := json.Marshal(enc)
if err != nil {
return commonapi.DynamicValue{}, err
}
return commonapi.DynamicValue{
JSON: v1.JSON{
Raw: jsonEnc,
},
}, nil
}
return commonapi.DynamicValue{}, nil
}
|
mikeee/dapr
|
pkg/operator/api/components.go
|
GO
|
mit
| 6,201 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package api
import (
"context"
"encoding/json"
"fmt"
"k8s.io/apimachinery/pkg/types"
configurationapi "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1"
"github.com/dapr/dapr/pkg/operator/api/authz"
operatorv1pb "github.com/dapr/dapr/pkg/proto/operator/v1"
)
// GetConfiguration returns a Dapr configuration.
func (a *apiServer) GetConfiguration(ctx context.Context, in *operatorv1pb.GetConfigurationRequest) (*operatorv1pb.GetConfigurationResponse, error) {
if _, err := authz.Request(ctx, in.GetNamespace()); err != nil {
return nil, err
}
key := types.NamespacedName{Namespace: in.GetNamespace(), Name: in.GetName()}
var config configurationapi.Configuration
if err := a.Client.Get(ctx, key, &config); err != nil {
return nil, fmt.Errorf("error getting configuration %s/%s: %w", in.GetNamespace(), in.GetName(), err)
}
b, err := json.Marshal(&config)
if err != nil {
return nil, fmt.Errorf("error marshalling configuration: %w", err)
}
return &operatorv1pb.GetConfigurationResponse{
Configuration: b,
}, nil
}
|
mikeee/dapr
|
pkg/operator/api/configurations.go
|
GO
|
mit
| 1,609 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package api
import (
"context"
"encoding/json"
"fmt"
"sync"
"github.com/google/uuid"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
httpendpointsapi "github.com/dapr/dapr/pkg/apis/httpEndpoint/v1alpha1"
"github.com/dapr/dapr/pkg/operator/api/authz"
operatorv1pb "github.com/dapr/dapr/pkg/proto/operator/v1"
)
func (a *apiServer) OnHTTPEndpointUpdated(ctx context.Context, endpoint *httpendpointsapi.HTTPEndpoint) {
a.endpointLock.Lock()
for _, endpointUpdateChan := range a.allEndpointsUpdateChan {
go func(endpointUpdateChan chan *httpendpointsapi.HTTPEndpoint) {
endpointUpdateChan <- endpoint
}(endpointUpdateChan)
}
a.endpointLock.Unlock()
}
func processHTTPEndpointSecrets(ctx context.Context, endpoint *httpendpointsapi.HTTPEndpoint, namespace string, kubeClient client.Client) error {
for i, header := range endpoint.Spec.Headers {
if pairNeedsSecretExtraction(header.SecretKeyRef, endpoint.Auth) {
v, err := getSecret(ctx, header.SecretKeyRef.Name, namespace, header.SecretKeyRef, kubeClient)
if err != nil {
return err
}
endpoint.Spec.Headers[i].Value = v
}
}
if endpoint.HasTLSClientCertSecret() && pairNeedsSecretExtraction(*endpoint.Spec.ClientTLS.Certificate.SecretKeyRef, endpoint.Auth) {
v, err := getSecret(ctx, endpoint.Spec.ClientTLS.Certificate.SecretKeyRef.Name, namespace, *endpoint.Spec.ClientTLS.Certificate.SecretKeyRef, kubeClient)
if err != nil {
return err
}
endpoint.Spec.ClientTLS.Certificate.Value = &v
}
if endpoint.HasTLSPrivateKeySecret() && pairNeedsSecretExtraction(*endpoint.Spec.ClientTLS.PrivateKey.SecretKeyRef, endpoint.Auth) {
v, err := getSecret(ctx, endpoint.Spec.ClientTLS.PrivateKey.SecretKeyRef.Name, namespace, *endpoint.Spec.ClientTLS.PrivateKey.SecretKeyRef, kubeClient)
if err != nil {
return err
}
endpoint.Spec.ClientTLS.PrivateKey.Value = &v
}
if endpoint.HasTLSRootCASecret() && pairNeedsSecretExtraction(*endpoint.Spec.ClientTLS.RootCA.SecretKeyRef, endpoint.Auth) {
v, err := getSecret(ctx, endpoint.Spec.ClientTLS.RootCA.SecretKeyRef.Name, namespace, *endpoint.Spec.ClientTLS.RootCA.SecretKeyRef, kubeClient)
if err != nil {
return err
}
endpoint.Spec.ClientTLS.RootCA.Value = &v
}
return nil
}
// GetHTTPEndpoint returns a specified http endpoint object.
func (a *apiServer) GetHTTPEndpoint(ctx context.Context, in *operatorv1pb.GetResiliencyRequest) (*operatorv1pb.GetHTTPEndpointResponse, error) {
if _, err := authz.Request(ctx, in.GetNamespace()); err != nil {
return nil, err
}
key := types.NamespacedName{Namespace: in.GetNamespace(), Name: in.GetName()}
var endpointConfig httpendpointsapi.HTTPEndpoint
if err := a.Client.Get(ctx, key, &endpointConfig); err != nil {
return nil, fmt.Errorf("error getting http endpoint: %w", err)
}
b, err := json.Marshal(&endpointConfig)
if err != nil {
return nil, fmt.Errorf("error marshalling http endpoint: %w", err)
}
return &operatorv1pb.GetHTTPEndpointResponse{
HttpEndpoint: b,
}, nil
}
// ListHTTPEndpoints gets the list of applied http endpoints.
func (a *apiServer) ListHTTPEndpoints(ctx context.Context, in *operatorv1pb.ListHTTPEndpointsRequest) (*operatorv1pb.ListHTTPEndpointsResponse, error) {
if _, err := authz.Request(ctx, in.GetNamespace()); err != nil {
return nil, err
}
resp := &operatorv1pb.ListHTTPEndpointsResponse{
HttpEndpoints: [][]byte{},
}
var endpoints httpendpointsapi.HTTPEndpointList
if err := a.Client.List(ctx, &endpoints, &client.ListOptions{
Namespace: in.GetNamespace(),
}); err != nil {
return nil, fmt.Errorf("error listing http endpoints: %w", err)
}
for i, item := range endpoints.Items {
e := endpoints.Items[i]
err := processHTTPEndpointSecrets(ctx, &e, item.Namespace, a.Client)
if err != nil {
log.Warnf("error processing secrets for http endpoint '%s/%s': %s", item.Namespace, item.Name, err)
return &operatorv1pb.ListHTTPEndpointsResponse{}, err
}
b, err := json.Marshal(e)
if err != nil {
log.Warnf("Error unmarshalling http endpoints: %s", err)
continue
}
resp.HttpEndpoints = append(resp.GetHttpEndpoints(), b)
}
return resp, nil
}
// HTTPEndpointUpdate updates Dapr sidecars whenever an http endpoint in the cluster is modified.
func (a *apiServer) HTTPEndpointUpdate(in *operatorv1pb.HTTPEndpointUpdateRequest, srv operatorv1pb.Operator_HTTPEndpointUpdateServer) error { //nolint:nosnakecase
if _, err := authz.Request(srv.Context(), in.GetNamespace()); err != nil {
return err
}
log.Info("sidecar connected for http endpoint updates")
keyObj, err := uuid.NewRandom()
if err != nil {
return err
}
key := keyObj.String()
a.endpointLock.Lock()
a.allEndpointsUpdateChan[key] = make(chan *httpendpointsapi.HTTPEndpoint, 1)
updateChan := a.allEndpointsUpdateChan[key]
a.endpointLock.Unlock()
defer func() {
a.endpointLock.Lock()
defer a.endpointLock.Unlock()
delete(a.allEndpointsUpdateChan, key)
}()
updateHTTPEndpointFunc := func(ctx context.Context, e *httpendpointsapi.HTTPEndpoint) {
if e.Namespace != in.GetNamespace() {
return
}
err := processHTTPEndpointSecrets(ctx, e, in.GetNamespace(), a.Client)
if err != nil {
log.Warnf("error processing http endpoint %s secrets from pod %s/%s: %s", e.Name, in.GetNamespace(), in.GetPodName(), err)
return
}
b, err := json.Marshal(&e)
if err != nil {
log.Warnf("error serializing http endpoint %s from pod %s/%s: %s", e.GetName(), in.GetNamespace(), in.GetPodName(), err)
return
}
err = srv.Send(&operatorv1pb.HTTPEndpointUpdateEvent{
HttpEndpoints: b,
})
if err != nil {
log.Warnf("error updating sidecar with http endpoint %s from pod %s/%s: %s", e.GetName(), in.GetNamespace(), in.GetPodName(), err)
return
}
log.Infof("updated sidecar with http endpoint %s from pod %s/%s", e.GetName(), in.GetNamespace(), in.GetPodName())
}
var wg sync.WaitGroup
defer wg.Wait()
for {
select {
case <-srv.Context().Done():
return nil
case c, ok := <-updateChan:
if !ok {
return nil
}
wg.Add(1)
go func() {
defer wg.Done()
updateHTTPEndpointFunc(srv.Context(), c)
}()
}
}
}
|
mikeee/dapr
|
pkg/operator/api/httpendpoints.go
|
GO
|
mit
| 6,744 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fake
import (
"context"
"github.com/dapr/dapr/pkg/operator/api/informer"
"github.com/dapr/dapr/pkg/runtime/meta"
)
type Fake[T meta.Resource] struct {
runFn func(context.Context) error
watchUpdatesFn func(context.Context, string) (<-chan *informer.Event[T], error)
}
func New[T meta.Resource]() *Fake[T] {
return &Fake[T]{
runFn: func(context.Context) error {
return nil
},
watchUpdatesFn: func(context.Context, string) (<-chan *informer.Event[T], error) {
return nil, nil
},
}
}
func (f *Fake[T]) WithRun(fn func(context.Context) error) *Fake[T] {
f.runFn = fn
return f
}
func (f *Fake[T]) WithWatchUpdates(fn func(context.Context, string) (<-chan *informer.Event[T], error)) *Fake[T] {
f.watchUpdatesFn = fn
return f
}
func (f *Fake[T]) Run(ctx context.Context) error {
return f.runFn(ctx)
}
func (f *Fake[T]) WatchUpdates(ctx context.Context, namespace string) (<-chan *informer.Event[T], error) {
return f.watchUpdatesFn(ctx, namespace)
}
|
mikeee/dapr
|
pkg/operator/api/informer/fake/fake.go
|
GO
|
mit
| 1,556 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fake
import (
"testing"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/operator/api/informer"
)
func Test_Fake(t *testing.T) {
var _ informer.Interface[compapi.Component] = New[compapi.Component]()
}
|
mikeee/dapr
|
pkg/operator/api/informer/fake/fake_test.go
|
GO
|
mit
| 815 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package informer
import (
"context"
operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1"
"github.com/dapr/dapr/pkg/runtime/meta"
"github.com/dapr/dapr/pkg/security/spiffe"
"github.com/dapr/dapr/utils"
)
type handler[T meta.Resource] struct {
i *informer[T]
batchCh <-chan *informerEvent[T]
appCh chan<- *Event[T]
id *spiffe.Parsed
}
func (h *handler[T]) loop(ctx context.Context) {
defer close(h.appCh)
for {
select {
case <-ctx.Done():
return
case <-h.i.closeCh:
return
case event := <-h.batchCh:
env, ok := h.appEventFromEvent(event)
if !ok {
continue
}
select {
case <-ctx.Done():
case <-h.i.closeCh:
case h.appCh <- env:
}
}
}
}
func (h *handler[T]) appEventFromEvent(event *informerEvent[T]) (*Event[T], bool) {
if event.newObj.Manifest.GetNamespace() != h.id.Namespace() {
return nil, false
}
// Handle case where scope is removed from manifest through update.
var appInOld bool
if event.oldObj != nil {
manifest := *event.oldObj
appInOld = len(manifest.GetScopes()) == 0 || utils.Contains(manifest.GetScopes(), h.id.AppID())
}
newManifest := event.newObj.Manifest
var appInNew bool
if len(newManifest.GetScopes()) == 0 || utils.Contains(newManifest.GetScopes(), h.id.AppID()) {
appInNew = true
}
if !appInNew {
if !appInOld {
return nil, false
}
return &Event[T]{
Manifest: *event.oldObj,
Type: operatorv1.ResourceEventType_DELETED,
}, true
}
env := event.newObj
if !appInOld && env.Type == operatorv1.ResourceEventType_UPDATED {
env.Type = operatorv1.ResourceEventType_CREATED
}
return env, true
}
|
mikeee/dapr
|
pkg/operator/api/informer/handler.go
|
GO
|
mit
| 2,198 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package informer
import (
"context"
"testing"
"time"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/dapr/dapr/pkg/apis/common"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1"
"github.com/dapr/dapr/pkg/security/spiffe"
)
func Test_loop(t *testing.T) {
t.Run("if context is done, return", func(t *testing.T) {
done := make(chan struct{})
h := &handler[compapi.Component]{
i: &informer[compapi.Component]{closeCh: make(chan struct{})},
batchCh: make(chan *informerEvent[compapi.Component]),
appCh: make(chan *Event[compapi.Component]),
}
ctx, cancel := context.WithCancel(context.Background())
go func() {
h.loop(ctx)
close(done)
}()
cancel()
select {
case <-done:
case <-time.After(time.Second):
assert.Fail(t, "expected loop to return")
}
})
t.Run("if closeCh is closed, return", func(t *testing.T) {
done := make(chan struct{})
closeCh := make(chan struct{})
h := &handler[compapi.Component]{
i: &informer[compapi.Component]{closeCh: closeCh},
batchCh: make(chan *informerEvent[compapi.Component]),
appCh: make(chan *Event[compapi.Component]),
}
go func() {
h.loop(context.Background())
close(done)
}()
close(closeCh)
select {
case <-done:
case <-time.After(time.Second):
assert.Fail(t, "expected loop to return")
}
})
t.Run("expect to receive events in order until close", func(t *testing.T) {
done := make(chan struct{})
closeCh := make(chan struct{})
batchCh := make(chan *informerEvent[compapi.Component], 10)
appCh := make(chan *Event[compapi.Component], 10)
td, err := spiffeid.TrustDomainFromString("example.org")
require.NoError(t, err)
id, err := spiffe.FromStrings(td, "myns", "myapp")
require.NoError(t, err)
h := &handler[compapi.Component]{
i: &informer[compapi.Component]{closeCh: closeCh},
batchCh: batchCh,
appCh: appCh,
id: id,
}
go func() {
h.loop(context.Background())
close(done)
}()
batchCh <- &informerEvent[compapi.Component]{
newObj: &Event[compapi.Component]{
Manifest: compapi.Component{ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: "myns"}},
Type: operatorv1.ResourceEventType_CREATED,
},
}
batchCh <- &informerEvent[compapi.Component]{
newObj: &Event[compapi.Component]{
Manifest: compapi.Component{ObjectMeta: metav1.ObjectMeta{Name: "comp2", Namespace: "notmyns"}},
Type: operatorv1.ResourceEventType_CREATED,
},
}
batchCh <- &informerEvent[compapi.Component]{
newObj: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "comp3", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"notmyapp"}},
},
Type: operatorv1.ResourceEventType_CREATED,
},
}
batchCh <- &informerEvent[compapi.Component]{
oldObj: &compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: "myns"},
},
newObj: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"notmyapp", "myapp"}},
},
Type: operatorv1.ResourceEventType_UPDATED,
},
}
batchCh <- &informerEvent[compapi.Component]{
oldObj: &compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"notmyapp", "myapp"}},
},
newObj: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"notmyapp"}},
},
Type: operatorv1.ResourceEventType_UPDATED,
},
}
batchCh <- &informerEvent[compapi.Component]{
oldObj: &compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"notmyapp"}},
},
newObj: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"notmyapp", "myapp"}},
},
Type: operatorv1.ResourceEventType_UPDATED,
},
}
batchCh <- &informerEvent[compapi.Component]{
newObj: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"notmyapp", "myapp"}},
},
Type: operatorv1.ResourceEventType_DELETED,
},
}
for _, exp := range []*Event[compapi.Component]{
{
Manifest: compapi.Component{ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: "myns"}},
Type: operatorv1.ResourceEventType_CREATED,
},
{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"notmyapp", "myapp"}},
},
Type: operatorv1.ResourceEventType_UPDATED,
},
{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"notmyapp", "myapp"}},
},
Type: operatorv1.ResourceEventType_DELETED,
},
{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"notmyapp", "myapp"}},
},
Type: operatorv1.ResourceEventType_CREATED,
},
{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"notmyapp", "myapp"}},
},
Type: operatorv1.ResourceEventType_DELETED,
},
} {
select {
case actual := <-appCh:
assert.Equal(t, exp, actual)
case <-time.After(time.Second):
assert.Fail(t, "expected to receive event")
}
}
close(closeCh)
select {
case <-done:
case <-time.After(time.Second):
assert.Fail(t, "expected loop to return")
}
})
}
func Test_appEventFromEvent(t *testing.T) {
tests := map[string]struct {
event *informerEvent[compapi.Component]
expEvent *Event[compapi.Component]
expOK bool
}{
"if manifest in different namespace, return false": {
event: &informerEvent[compapi.Component]{
oldObj: &compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"notmyapp"}},
},
newObj: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "notmyns"},
},
Type: operatorv1.ResourceEventType_UPDATED,
},
},
expEvent: nil,
expOK: false,
},
"if manifest in same namespace, return event": {
event: &informerEvent[compapi.Component]{
newObj: &Event[compapi.Component]{
Manifest: compapi.Component{ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"}},
Type: operatorv1.ResourceEventType_CREATED,
},
},
expEvent: &Event[compapi.Component]{
Manifest: compapi.Component{ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"}},
Type: operatorv1.ResourceEventType_CREATED,
},
expOK: true,
},
"if manifest in scope, return event": {
event: &informerEvent[compapi.Component]{
newObj: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"anotherappid", "myapp"}},
},
Type: operatorv1.ResourceEventType_CREATED,
},
},
expEvent: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"anotherappid", "myapp"}},
},
Type: operatorv1.ResourceEventType_CREATED,
},
expOK: true,
},
"if manifest not in scope, don't return event": {
event: &informerEvent[compapi.Component]{
newObj: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"anotherappid", "notmyapp"}},
},
Type: operatorv1.ResourceEventType_CREATED,
},
},
expEvent: nil,
expOK: false,
},
"if manifest in both manifests, return new object": {
event: &informerEvent[compapi.Component]{
oldObj: &compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"myapp"}},
},
newObj: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"myapp", "notmyapp"}},
},
Type: operatorv1.ResourceEventType_UPDATED,
},
},
expEvent: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"myapp", "notmyapp"}},
},
Type: operatorv1.ResourceEventType_UPDATED,
},
expOK: true,
},
"if manifest in old scope but not new, return delete event": {
event: &informerEvent[compapi.Component]{
oldObj: &compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"myapp"}},
},
newObj: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"notmyapp"}},
},
Type: operatorv1.ResourceEventType_UPDATED,
},
},
expEvent: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"myapp"}},
},
Type: operatorv1.ResourceEventType_DELETED,
},
expOK: true,
},
"if manifest in both manifests (empty), return new object": {
event: &informerEvent[compapi.Component]{
oldObj: &compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"myapp"}},
},
newObj: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
},
Type: operatorv1.ResourceEventType_UPDATED,
},
},
expEvent: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
},
Type: operatorv1.ResourceEventType_UPDATED,
},
expOK: true,
},
"if manifest in old scope but not new (empty), return delete event": {
event: &informerEvent[compapi.Component]{
oldObj: &compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
},
newObj: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"notmyapp"}},
},
Type: operatorv1.ResourceEventType_UPDATED,
},
},
expEvent: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
},
Type: operatorv1.ResourceEventType_DELETED,
},
expOK: true,
},
"if manifest not in old but in new scope, return created": {
event: &informerEvent[compapi.Component]{
oldObj: &compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"notmyapp"}},
},
newObj: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"myapp", "notmyapp"}},
},
Type: operatorv1.ResourceEventType_UPDATED,
},
},
expEvent: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"myapp", "notmyapp"}},
},
Type: operatorv1.ResourceEventType_CREATED,
},
expOK: true,
},
"if manifest not in old but in new scope (empty), return created": {
event: &informerEvent[compapi.Component]{
oldObj: &compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
Scoped: common.Scoped{Scopes: []string{"notmyapp"}},
},
newObj: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
},
Type: operatorv1.ResourceEventType_UPDATED,
},
},
expEvent: &Event[compapi.Component]{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "myns"},
},
Type: operatorv1.ResourceEventType_CREATED,
},
expOK: true,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
td, err := spiffeid.TrustDomainFromString("example.org")
require.NoError(t, err)
id, err := spiffe.FromStrings(td, "myns", "myapp")
require.NoError(t, err)
h := &handler[compapi.Component]{
id: id,
}
actual, ok := h.appEventFromEvent(test.event)
assert.Equal(t, test.expOK, ok)
assert.Equal(t, test.expEvent, actual)
})
}
}
|
mikeee/dapr
|
pkg/operator/api/informer/handler_test.go
|
GO
|
mit
| 14,208 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package informer
import (
"context"
"fmt"
"strings"
"sync"
"sync/atomic"
"k8s.io/client-go/tools/cache"
ctrlcache "sigs.k8s.io/controller-runtime/pkg/cache"
"github.com/dapr/dapr/pkg/operator/api/authz"
operatorv1 "github.com/dapr/dapr/pkg/proto/operator/v1"
"github.com/dapr/dapr/pkg/runtime/meta"
"github.com/dapr/kit/events/batcher"
"github.com/dapr/kit/logger"
)
type Options struct {
Cache ctrlcache.Cache
}
// Interface is an interface for syncing Kubernetes manifests.
type Interface[T meta.Resource] interface {
Run(context.Context) error
WatchUpdates(context.Context, string) (<-chan *Event[T], error)
}
// Event is a Kubernetes manifest event, containing the manifest and the event
// type.
type Event[T meta.Resource] struct {
Manifest T
Type operatorv1.ResourceEventType
}
type informer[T meta.Resource] struct {
cache ctrlcache.Cache
lock sync.Mutex
batcher *batcher.Batcher[int, *informerEvent[T]]
batchID atomic.Uint32
log logger.Logger
closeCh chan struct{}
wg sync.WaitGroup
}
type informerEvent[T meta.Resource] struct {
newObj *Event[T]
oldObj *T
}
func New[T meta.Resource](opts Options) Interface[T] {
var zero T
return &informer[T]{
log: logger.NewLogger("dapr.operator.informer." + strings.ToLower(zero.Kind())),
batcher: batcher.New[int, *informerEvent[T]](0),
cache: opts.Cache,
closeCh: make(chan struct{}),
}
}
func (i *informer[T]) Run(ctx context.Context) error {
var zero T
informer, err := i.cache.GetInformer(ctx, zero.ClientObject())
if err != nil {
return fmt.Errorf("unable to get setup %s informer: %w", zero.Kind(), err)
}
_, err = informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj any) {
i.handleEvent(ctx, nil, obj, operatorv1.ResourceEventType_CREATED)
},
UpdateFunc: func(oldObj, newObj any) {
i.handleEvent(ctx, oldObj, newObj, operatorv1.ResourceEventType_UPDATED)
},
DeleteFunc: func(obj any) {
i.handleEvent(ctx, nil, obj, operatorv1.ResourceEventType_DELETED)
},
})
if err != nil {
return fmt.Errorf("unable to add %s informer event handler: %w", zero.Kind(), err)
}
<-ctx.Done()
close(i.closeCh)
i.batcher.Close()
i.wg.Wait()
return nil
}
func (i *informer[T]) WatchUpdates(ctx context.Context, ns string) (<-chan *Event[T], error) {
id, err := authz.Request(ctx, ns)
if err != nil {
return nil, err
}
batchCh := make(chan *informerEvent[T], 10)
appCh := make(chan *Event[T], 10)
i.batcher.Subscribe(ctx, batchCh)
i.wg.Add(1)
go func() {
defer i.wg.Done()
(&handler[T]{
i: i,
appCh: appCh,
batchCh: batchCh,
id: id,
}).loop(ctx)
}()
return appCh, nil
}
func (i *informer[T]) handleEvent(ctx context.Context, oldObj, newObj any, eventType operatorv1.ResourceEventType) {
i.lock.Lock()
defer i.lock.Unlock()
newT, ok := i.anyToT(newObj)
if !ok {
return
}
event := &informerEvent[T]{
newObj: &Event[T]{
Manifest: newT,
Type: eventType,
},
}
if oldObj != nil {
oldT, ok := i.anyToT(oldObj)
if !ok {
return
}
event.oldObj = &oldT
}
i.batcher.Batch(int(i.batchID.Load()), event)
i.batchID.Add(1)
}
func (i *informer[T]) anyToT(obj any) (T, bool) {
switch objT := obj.(type) {
case *T:
return *objT, true
case T:
return objT, true
case cache.DeletedFinalStateUnknown:
return i.anyToT(obj.(cache.DeletedFinalStateUnknown).Obj)
default:
i.log.Errorf("unexpected type %T", obj)
var zero T
return zero, false
}
}
|
mikeee/dapr
|
pkg/operator/api/informer/informer.go
|
GO
|
mit
| 4,057 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package informer
import (
"context"
"testing"
"time"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/cache"
"github.com/dapr/dapr/pkg/apis/common"
compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
subapi "github.com/dapr/dapr/pkg/apis/subscriptions/v2alpha1"
"github.com/dapr/dapr/pkg/proto/operator/v1"
"github.com/dapr/kit/crypto/test"
)
func Test_WatchUpdates(t *testing.T) {
t.Run("bad authz should error", func(t *testing.T) {
appID := spiffeid.RequireFromString("spiffe://example.org/ns/ns1/app1")
serverID := spiffeid.RequireFromString("spiffe://example.org/ns/dapr-system/dapr-operator")
pki := test.GenPKI(t, test.PKIOptions{LeafID: serverID, ClientID: appID})
i := New[compapi.Component](Options{}).(*informer[compapi.Component])
appCh, err := i.WatchUpdates(pki.ClientGRPCCtx(t), "ns2")
require.Error(t, err)
assert.Equal(t, codes.PermissionDenied, status.Code(err))
assert.Nil(t, appCh)
appCh, err = i.WatchUpdates(context.Background(), "ns2")
require.Error(t, err)
assert.Equal(t, codes.PermissionDenied, status.Code(err))
assert.Nil(t, appCh)
})
t.Run("should receive app events on batch events in order", func(t *testing.T) {
appID := spiffeid.RequireFromString("spiffe://example.org/ns/ns1/app1")
serverID := spiffeid.RequireFromString("spiffe://example.org/ns/dapr-system/dapr-operator")
pki := test.GenPKI(t, test.PKIOptions{LeafID: serverID, ClientID: appID})
i := New[compapi.Component](Options{}).(*informer[compapi.Component])
t.Cleanup(func() { close(i.closeCh) })
appCh1, err := i.WatchUpdates(pki.ClientGRPCCtx(t), "ns1")
require.NoError(t, err)
appCh2, err := i.WatchUpdates(pki.ClientGRPCCtx(t), "ns1")
require.NoError(t, err)
i.handleEvent(context.Background(),
&compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: "ns1"},
},
&compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: "ns1"},
Spec: compapi.ComponentSpec{Type: "bindings.redis"},
},
operator.ResourceEventType_UPDATED,
)
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Equal(c, 1, int(i.batchID.Load()))
}, 5*time.Second, 100*time.Millisecond)
i.handleEvent(context.Background(),
&compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: "ns1"},
Spec: compapi.ComponentSpec{Type: "bindings.redis"},
},
&compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: "ns1"},
Scoped: common.Scoped{Scopes: []string{"notapp1"}},
},
operator.ResourceEventType_UPDATED,
)
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Equal(c, 2, int(i.batchID.Load()))
}, 5*time.Second, 100*time.Millisecond)
i.handleEvent(context.Background(),
nil,
&compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "comp2", Namespace: "ns1"},
},
operator.ResourceEventType_CREATED,
)
require.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Equal(c, 3, int(i.batchID.Load()))
}, 5*time.Second, 100*time.Millisecond)
for _, appCh := range []<-chan *Event[compapi.Component]{appCh1, appCh2} {
for _, exp := range []*Event[compapi.Component]{
{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: "ns1"},
Spec: compapi.ComponentSpec{Type: "bindings.redis"},
},
Type: operator.ResourceEventType_UPDATED,
},
{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "comp1", Namespace: "ns1"},
Spec: compapi.ComponentSpec{Type: "bindings.redis"},
},
Type: operator.ResourceEventType_DELETED,
},
{
Manifest: compapi.Component{
ObjectMeta: metav1.ObjectMeta{Name: "comp2", Namespace: "ns1"},
},
Type: operator.ResourceEventType_CREATED,
},
} {
select {
case event := <-appCh:
assert.Equal(t, exp, event)
case <-time.After(time.Second):
assert.Fail(t, "timeout waiting for app event")
}
}
}
})
}
func Test_anyToT(t *testing.T) {
tests := map[string]struct {
obj any
expT compapi.Component
expOK bool
}{
"type *T ok": {
obj: new(compapi.Component),
expT: compapi.Component{},
expOK: true,
},
"type T ok": {
obj: compapi.Component{},
expT: compapi.Component{},
expOK: true,
},
"type cache.DeletedFinalStateUnknown(*T) ok": {
obj: cache.DeletedFinalStateUnknown{Obj: new(compapi.Component)},
expT: compapi.Component{},
expOK: true,
},
"type cache.DeletedFinalStateUnknown(T) ok": {
obj: cache.DeletedFinalStateUnknown{Obj: compapi.Component{}},
expT: compapi.Component{},
expOK: true,
},
"type cache.DeletedFinalStateUnknown(not_T) not ok": {
obj: cache.DeletedFinalStateUnknown{Obj: new(subapi.Subscription)},
expT: compapi.Component{},
expOK: false,
},
"type different, not ok": {
obj: new(subapi.Subscription),
expT: compapi.Component{},
expOK: false,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
i := New[compapi.Component](Options{}).(*informer[compapi.Component])
got, ok := i.anyToT(test.obj)
assert.Equal(t, test.expOK, ok)
assert.Equal(t, test.expT, got)
})
}
}
|
mikeee/dapr
|
pkg/operator/api/informer/informer_test.go
|
GO
|
mit
| 6,046 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package api
import (
"context"
"encoding/json"
"fmt"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
resiliencyapi "github.com/dapr/dapr/pkg/apis/resiliency/v1alpha1"
"github.com/dapr/dapr/pkg/operator/api/authz"
operatorv1pb "github.com/dapr/dapr/pkg/proto/operator/v1"
)
// GetResiliency returns a specified resiliency object.
func (a *apiServer) GetResiliency(ctx context.Context, in *operatorv1pb.GetResiliencyRequest) (*operatorv1pb.GetResiliencyResponse, error) {
if _, err := authz.Request(ctx, in.GetNamespace()); err != nil {
return nil, err
}
key := types.NamespacedName{Namespace: in.GetNamespace(), Name: in.GetName()}
var resiliencyConfig resiliencyapi.Resiliency
if err := a.Client.Get(ctx, key, &resiliencyConfig); err != nil {
return nil, fmt.Errorf("error getting resiliency: %w", err)
}
b, err := json.Marshal(&resiliencyConfig)
if err != nil {
return nil, fmt.Errorf("error marshalling resiliency: %w", err)
}
return &operatorv1pb.GetResiliencyResponse{
Resiliency: b,
}, nil
}
// ListResiliency gets the list of applied resiliencies.
func (a *apiServer) ListResiliency(ctx context.Context, in *operatorv1pb.ListResiliencyRequest) (*operatorv1pb.ListResiliencyResponse, error) {
if _, err := authz.Request(ctx, in.GetNamespace()); err != nil {
return nil, err
}
resp := &operatorv1pb.ListResiliencyResponse{
Resiliencies: [][]byte{},
}
var resiliencies resiliencyapi.ResiliencyList
if err := a.Client.List(ctx, &resiliencies, &client.ListOptions{
Namespace: in.GetNamespace(),
}); err != nil {
return nil, fmt.Errorf("error listing resiliencies: %w", err)
}
for _, item := range resiliencies.Items {
b, err := json.Marshal(item)
if err != nil {
log.Warnf("Error unmarshalling resiliency: %s", err)
continue
}
resp.Resiliencies = append(resp.GetResiliencies(), b)
}
return resp, nil
}
|
mikeee/dapr
|
pkg/operator/api/resiliencies.go
|
GO
|
mit
| 2,462 |
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package api
import (
"context"
"encoding/json"
"fmt"
"sync"
"github.com/google/uuid"
"google.golang.org/protobuf/types/known/emptypb"
"sigs.k8s.io/controller-runtime/pkg/client"
subapi "github.com/dapr/dapr/pkg/apis/subscriptions/v2alpha1"
"github.com/dapr/dapr/pkg/operator/api/authz"
operatorv1pb "github.com/dapr/dapr/pkg/proto/operator/v1"
)
type SubscriptionUpdateEvent struct {
Subscription *subapi.Subscription
EventType operatorv1pb.ResourceEventType
}
func (a *apiServer) OnSubscriptionUpdated(ctx context.Context, eventType operatorv1pb.ResourceEventType, subscription *subapi.Subscription) {
a.connLock.Lock()
var wg sync.WaitGroup
wg.Add(len(a.allSubscriptionUpdateChan))
for _, connUpdateChan := range a.allSubscriptionUpdateChan {
go func(connUpdateChan chan *SubscriptionUpdateEvent) {
defer wg.Done()
select {
case connUpdateChan <- &SubscriptionUpdateEvent{
Subscription: subscription,
EventType: eventType,
}:
case <-ctx.Done():
}
}(connUpdateChan)
}
wg.Wait()
a.connLock.Unlock()
}
// ListSubscriptions returns a list of Dapr pub/sub subscriptions.
func (a *apiServer) ListSubscriptions(ctx context.Context, in *emptypb.Empty) (*operatorv1pb.ListSubscriptionsResponse, error) {
return a.ListSubscriptionsV2(ctx, &operatorv1pb.ListSubscriptionsRequest{})
}
// ListSubscriptionsV2 returns a list of Dapr pub/sub subscriptions. Use ListSubscriptionsRequest to expose pod info.
func (a *apiServer) ListSubscriptionsV2(ctx context.Context, in *operatorv1pb.ListSubscriptionsRequest) (*operatorv1pb.ListSubscriptionsResponse, error) {
if _, err := authz.Request(ctx, in.GetNamespace()); err != nil {
return nil, err
}
resp := &operatorv1pb.ListSubscriptionsResponse{
Subscriptions: [][]byte{},
}
// Only the latest/storage version needs to be returned.
var subsV2alpha1 subapi.SubscriptionList
if err := a.Client.List(ctx, &subsV2alpha1, &client.ListOptions{
Namespace: in.GetNamespace(),
}); err != nil {
return nil, fmt.Errorf("error getting subscriptions: %w", err)
}
for i := range subsV2alpha1.Items {
s := subsV2alpha1.Items[i] // Make a copy since we will refer to this as a reference in this loop.
if s.APIVersion() != APIVersionV2alpha1 {
continue
}
b, err := json.Marshal(&s)
if err != nil {
log.Warnf("error marshalling subscription for pod %s/%s: %s", in.GetNamespace(), in.GetPodName(), err)
continue
}
resp.Subscriptions = append(resp.GetSubscriptions(), b)
}
return resp, nil
}
func (a *apiServer) SubscriptionUpdate(in *operatorv1pb.SubscriptionUpdateRequest, srv operatorv1pb.Operator_SubscriptionUpdateServer) error { //nolint:nosnakecase
if _, err := authz.Request(srv.Context(), in.GetNamespace()); err != nil {
return err
}
log.Info("sidecar connected for subscription updates")
keyObj, err := uuid.NewRandom()
if err != nil {
return err
}
key := keyObj.String()
a.connLock.Lock()
updateChan := make(chan *SubscriptionUpdateEvent)
a.allSubscriptionUpdateChan[key] = updateChan
a.connLock.Unlock()
defer func() {
a.connLock.Lock()
defer a.connLock.Unlock()
delete(a.allSubscriptionUpdateChan, key)
}()
updateSubscriptionFunc := func(ctx context.Context, t operatorv1pb.ResourceEventType, sub *subapi.Subscription) {
if sub.Namespace != in.GetNamespace() {
return
}
b, err := json.Marshal(&sub)
if err != nil {
log.Warnf("error serializing subscription %s for pod %s/%s: %s", sub.GetName(), in.GetNamespace(), in.GetPodName(), err)
return
}
err = srv.Send(&operatorv1pb.SubscriptionUpdateEvent{
Subscription: b,
Type: t,
})
if err != nil {
log.Warnf("error updating sidecar with subscroption %s to pod %s/%s: %s", sub.GetName(), in.GetNamespace(), in.GetPodName(), err)
return
}
log.Debugf("updated sidecar with subscription %s %s to pod %s/%s", t.String(), sub.GetName(), in.GetNamespace(), in.GetPodName())
}
var wg sync.WaitGroup
defer wg.Wait()
for {
select {
case <-srv.Context().Done():
return nil
case c, ok := <-updateChan:
if !ok {
return nil
}
wg.Add(1)
go func() {
defer wg.Done()
updateSubscriptionFunc(srv.Context(), c.EventType, c.Subscription)
}()
}
}
}
|
mikeee/dapr
|
pkg/operator/api/subscriptions.go
|
GO
|
mit
| 4,796 |
package cache
import (
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/rand"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
operatormeta "github.com/dapr/dapr/pkg/operator/meta"
)
var (
// create pseudo-unique name for empty resources
randomName = "dapr-dev-null" + rand.String(20)
deployDevNull = &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{Name: randomName, Namespace: randomName},
}
stsDevNull = &appsv1.StatefulSet{
ObjectMeta: metav1.ObjectMeta{Name: randomName, Namespace: randomName},
}
podDevNull = &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{Name: randomName, Namespace: randomName},
}
podEmptyStatus = corev1.PodStatus{}
podEmptySpec = corev1.PodSpec{}
deployEmptyStatus = appsv1.DeploymentStatus{}
stsEmptyStatus = appsv1.StatefulSetStatus{}
)
// GetFilteredCache creates a cache that slims down resources to the minimum that is needed for processing and also acts
// as a sinkhole for deployment/statefulsets/pods that are not going to be processed but that cannot be filtered by labels
// to limit what items end up in the cache. The following is removed/clear from the resources:
// - pods -> managed fields, status (we care for spec to find out containers, the rests are set to empty)
// - deploy/sts -> template.spec, status, managedfields (we only care about template/metadata except for injector deployment)
func GetFilteredCache(namespace string, podSelector labels.Selector) cache.NewCacheFunc {
return func(config *rest.Config, opts cache.Options) (cache.Cache, error) {
// The only pods we are interested are in watchdog. we don't need to
// list/watch pods that we are almost sure have dapr sidecar already.
opts.ByObject = getTransformerFunctions(podSelector)
if len(namespace) > 0 {
opts.DefaultNamespaces = map[string]cache.Config{
namespace: {},
}
}
return cache.New(config, opts)
}
}
// getTransformerFunctions creates transformers that are called by the DeltaFifo before they are inserted in the cache
// the transformations here try to reduce size of objects, and for some others objects that we don't care about (non-dapr)
// we set all these objects to store a single one, a sort of sinkhole
func getTransformerFunctions(podSelector labels.Selector) map[client.Object]cache.ByObject {
return map[client.Object]cache.ByObject{
&corev1.Pod{}: {
Label: podSelector,
Transform: func(i any) (any, error) {
obj, ok := i.(*corev1.Pod)
if !ok { // probably deletedfinalstateunknown
return i, nil
}
if operatormeta.IsAnnotatedForDapr(obj.ObjectMeta.GetAnnotations()) && !operatormeta.IsSidecarPresent(obj.ObjectMeta.GetLabels()) {
objClone := obj.DeepCopy()
objClone.ObjectMeta.ManagedFields = []metav1.ManagedFieldsEntry{}
objClone.Status = podEmptyStatus
return objClone, nil
}
return podDevNull, nil
},
},
&appsv1.Deployment{}: {
Transform: func(i any) (any, error) {
obj, ok := i.(*appsv1.Deployment)
if !ok {
return i, nil
}
// store injector deployment as is
if obj.GetLabels()["app"] == operatormeta.SidecarInjectorDeploymentName {
return i, nil
}
// slim down dapr deployments and sinkhole non-dapr ones
if operatormeta.IsAnnotatedForDapr(obj.Spec.Template.ObjectMeta.GetAnnotations()) {
// keep metadata but remove the rest
objClone := obj.DeepCopy()
objClone.ObjectMeta.ManagedFields = []metav1.ManagedFieldsEntry{}
objClone.Spec.Template.Spec = podEmptySpec
objClone.Status = deployEmptyStatus
return objClone, nil
}
return deployDevNull, nil
},
},
&appsv1.StatefulSet{}: {
Transform: func(i any) (any, error) {
obj, ok := i.(*appsv1.StatefulSet)
if !ok {
return i, nil
}
if operatormeta.IsAnnotatedForDapr(obj.Spec.Template.ObjectMeta.GetAnnotations()) {
// keep metadata but remove the rest
objClone := obj.DeepCopy()
objClone.ObjectMeta.ManagedFields = []metav1.ManagedFieldsEntry{}
objClone.Spec.Template.Spec = podEmptySpec
objClone.Status = stsEmptyStatus
return objClone, nil
}
return stsDevNull, nil
},
},
}
}
|
mikeee/dapr
|
pkg/operator/cache/cache.go
|
GO
|
mit
| 4,340 |
package cache
import (
"testing"
"github.com/stretchr/testify/require"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/kubernetes/scheme"
kcache "k8s.io/client-go/tools/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
injectorConsts "github.com/dapr/dapr/pkg/injector/consts"
operatormeta "github.com/dapr/dapr/pkg/operator/meta"
"github.com/dapr/dapr/pkg/operator/testobjects"
)
// convertToByGVK exposed/modified from sigs.k8s.io/controller-runtime/pkg/cache/cache.go:427
func convertToByGVK[T any](byObject map[client.Object]T) (map[schema.GroupVersionKind]T, error) {
byGVK := map[schema.GroupVersionKind]T{}
for object, value := range byObject {
gvk, err := apiutil.GVKForObject(object, scheme.Scheme)
if err != nil {
return nil, err
}
byGVK[gvk] = value
}
return byGVK, nil
}
func getObjectTransformer(t *testing.T, o client.Object) kcache.TransformFunc {
transformers := getTransformerFunctions(nil)
transformerByGVK, err := convertToByGVK(transformers)
require.NoError(t, err)
gvk, err := apiutil.GVKForObject(o, scheme.Scheme)
require.NoError(t, err)
podTransformer, ok := transformerByGVK[gvk]
require.True(t, ok)
return podTransformer.Transform
}
func getNewTestStore() kcache.Store {
return kcache.NewStore(func(obj any) (string, error) {
o := obj.(client.Object)
return o.GetNamespace() + "/" + o.GetName(), nil
})
}
func Test_podTransformer(t *testing.T) {
podTransformer := getObjectTransformer(t, &corev1.Pod{})
t.Run("allDapr", func(t *testing.T) {
store := getNewTestStore()
pods := []corev1.Pod{
testobjects.GetPod("test", "true", testobjects.NameNamespace("pod1", "ns1")),
testobjects.GetPod("test", "true", testobjects.NameNamespace("pod2", "ns2")),
testobjects.GetPod("test", "true", testobjects.NameNamespace("pod3", "ns3")),
}
for i := range pods {
p := pods[i]
obj, err := podTransformer(&p)
require.NoError(t, err)
require.NoError(t, store.Add(obj))
}
require.Len(t, store.List(), len(pods))
})
t.Run("noDaprPodsShouldCoalesceAllToOne", func(t *testing.T) {
store := getNewTestStore()
pods := []corev1.Pod{
testobjects.GetPod("test", "no", testobjects.NameNamespace("pod1", "ns1")),
testobjects.GetPod("test", "no", testobjects.NameNamespace("pod2", "ns2")),
testobjects.GetPod("test", "no", testobjects.NameNamespace("pod3", "ns3")),
}
for i := range pods {
p := pods[i]
obj, err := podTransformer(&p)
require.NoError(t, err)
require.NoError(t, store.Add(obj))
}
require.Len(t, store.List(), 1)
})
t.Run("someInjectedPodsShouldBeCoalesced", func(t *testing.T) {
store := getNewTestStore()
pods := []corev1.Pod{
testobjects.GetPod("test", "true", testobjects.NameNamespace("pod1", "ns1"),
testobjects.AddLabels(map[string]string{injectorConsts.SidecarInjectedLabel: "true"})),
testobjects.GetPod("test", "true", testobjects.NameNamespace("pod2", "ns2")),
testobjects.GetPod("test", "no", testobjects.NameNamespace("pod3", "ns3")),
}
for i := range pods {
p := pods[i]
obj, err := podTransformer(&p)
require.NoError(t, err)
require.NoError(t, store.Add(obj))
}
require.Len(t, store.List(), 2)
})
}
func Test_deployTransformer(t *testing.T) {
deployTransformer := getObjectTransformer(t, &appsv1.Deployment{})
t.Run("allDapr", func(t *testing.T) {
store := getNewTestStore()
deployments := []appsv1.Deployment{
testobjects.GetDeployment("test", "true", testobjects.NameNamespace("pod1", "ns1")),
testobjects.GetDeployment("test", "true", testobjects.NameNamespace("pod2", "ns2")),
testobjects.GetDeployment("test", "true", testobjects.NameNamespace("pod3", "ns3")),
}
for i := range deployments {
p := deployments[i]
obj, err := deployTransformer(&p)
require.NoError(t, err)
require.NoError(t, store.Add(obj))
}
require.Len(t, store.List(), len(deployments))
depObj, ok, err := store.Get(&appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Name: "pod1", Namespace: "ns1"}})
require.NoError(t, err)
require.True(t, ok)
dep := depObj.(*appsv1.Deployment)
require.Equal(t, dep.Status, deployEmptyStatus)
require.Equal(t, dep.Spec.Template.Spec, podEmptySpec)
})
t.Run("allNonDapr", func(t *testing.T) {
store := getNewTestStore()
deployments := []appsv1.Deployment{
testobjects.GetDeployment("test", "false", testobjects.NameNamespace("pod1", "ns1")),
testobjects.GetDeployment("test", "false", testobjects.NameNamespace("pod2", "ns2")),
testobjects.GetDeployment("test", "false", testobjects.NameNamespace("pod3", "ns3")),
}
for i := range deployments {
p := deployments[i]
obj, err := deployTransformer(&p)
require.NoError(t, err)
require.NoError(t, store.Add(obj))
}
require.Len(t, store.List(), 1)
})
t.Run("allNonDaprPlusInjectorDeployment", func(t *testing.T) {
store := getNewTestStore()
deployments := []appsv1.Deployment{
testobjects.GetDeployment("test", "false", testobjects.NameNamespace("pod1", "ns1")),
testobjects.GetDeployment("test", "false", testobjects.NameNamespace("pod2", "ns2")),
testobjects.GetDeployment("test", "false", testobjects.NameNamespace("pod3", "ns3")),
testobjects.GetDeployment("test", "false", testobjects.NameNamespace(operatormeta.SidecarInjectorDeploymentName, "dapr-system"),
testobjects.AddLabels(map[string]string{"app": operatormeta.SidecarInjectorDeploymentName})),
}
for i := range deployments {
p := deployments[i]
obj, err := deployTransformer(&p)
require.NoError(t, err)
require.NoError(t, store.Add(obj))
}
require.Len(t, store.List(), 2)
})
}
func Test_stsTransformer(t *testing.T) {
stsTransformer := getObjectTransformer(t, &appsv1.StatefulSet{})
t.Run("allDapr", func(t *testing.T) {
store := getNewTestStore()
statefulsets := []appsv1.StatefulSet{
testobjects.GetStatefulSet("test", "true", testobjects.NameNamespace("pod1", "ns1")),
testobjects.GetStatefulSet("test", "true", testobjects.NameNamespace("pod2", "ns2")),
testobjects.GetStatefulSet("test", "true", testobjects.NameNamespace("pod3", "ns3")),
}
for i := range statefulsets {
p := statefulsets[i]
obj, err := stsTransformer(&p)
require.NoError(t, err)
require.NoError(t, store.Add(obj))
}
require.Len(t, store.List(), len(statefulsets))
depObj, ok, err := store.Get(&appsv1.StatefulSet{ObjectMeta: metav1.ObjectMeta{Name: "pod1", Namespace: "ns1"}})
require.NoError(t, err)
require.True(t, ok)
sts := depObj.(*appsv1.StatefulSet)
require.Equal(t, sts.Status, stsEmptyStatus)
require.Equal(t, sts.Spec.Template.Spec, podEmptySpec)
})
t.Run("allNonDapr", func(t *testing.T) {
store := getNewTestStore()
statefulsets := []appsv1.StatefulSet{
testobjects.GetStatefulSet("test", "false", testobjects.NameNamespace("pod1", "ns1")),
testobjects.GetStatefulSet("test", "false", testobjects.NameNamespace("pod2", "ns2")),
testobjects.GetStatefulSet("test", "false", testobjects.NameNamespace("pod3", "ns3")),
}
for i := range statefulsets {
p := statefulsets[i]
obj, err := stsTransformer(&p)
require.NoError(t, err)
require.NoError(t, store.Add(obj))
}
require.Len(t, store.List(), 1)
})
}
|
mikeee/dapr
|
pkg/operator/cache/cache_test.go
|
GO
|
mit
| 7,379 |
package client
import (
"context"
"time"
grpcMiddleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpcRetry "github.com/grpc-ecosystem/go-grpc-middleware/retry"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"google.golang.org/grpc"
diag "github.com/dapr/dapr/pkg/diagnostics"
operatorv1pb "github.com/dapr/dapr/pkg/proto/operator/v1"
"github.com/dapr/dapr/pkg/security"
)
const (
dialTimeout = 30 * time.Second
)
// GetOperatorClient returns a new k8s operator client and the underlying connection.
// If a cert chain is given, a TLS connection will be established.
func GetOperatorClient(ctx context.Context, address string, sec security.Handler) (operatorv1pb.OperatorClient, *grpc.ClientConn, error) {
unaryClientInterceptor := grpcRetry.UnaryClientInterceptor()
if diag.DefaultGRPCMonitoring.IsEnabled() {
unaryClientInterceptor = grpcMiddleware.ChainUnaryClient(
unaryClientInterceptor,
diag.DefaultGRPCMonitoring.UnaryClientInterceptor(),
)
}
operatorID, err := spiffeid.FromSegments(sec.ControlPlaneTrustDomain(), "ns", sec.ControlPlaneNamespace(), "dapr-operator")
if err != nil {
return nil, nil, err
}
opts := []grpc.DialOption{
grpc.WithUnaryInterceptor(unaryClientInterceptor),
sec.GRPCDialOptionMTLS(operatorID), grpc.WithReturnConnectionError(),
}
ctx, cancel := context.WithTimeout(ctx, dialTimeout)
defer cancel()
conn, err := grpc.DialContext(ctx, address, opts...)
if err != nil {
return nil, nil, err
}
return operatorv1pb.NewOperatorClient(conn), conn, nil
}
|
mikeee/dapr
|
pkg/operator/client/client.go
|
GO
|
mit
| 1,531 |
package operator
import (
"context"
"fmt"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/dapr/dapr/pkg/apis/configuration/v1alpha1"
"github.com/dapr/dapr/pkg/security"
)
// Config returns an operator config options.
type Config struct {
MTLSEnabled bool
ControlPlaneTrustDomain string
SentryAddress string
}
// LoadConfiguration loads the Kubernetes configuration and returns an Operator Config.
func LoadConfiguration(ctx context.Context, name string, restConfig *rest.Config) (*Config, error) {
scheme, err := buildScheme(Options{})
if err != nil {
return nil, err
}
client, err := client.New(restConfig, client.Options{Scheme: scheme})
if err != nil {
return nil, fmt.Errorf("could not get Kubernetes API client: %w", err)
}
namespace, err := security.CurrentNamespaceOrError()
if err != nil {
return nil, err
}
var conf v1alpha1.Configuration
key := types.NamespacedName{
Namespace: namespace,
Name: name,
}
if err := client.Get(ctx, key, &conf); err != nil {
return nil, err
}
return &Config{
MTLSEnabled: conf.Spec.MTLSSpec.GetEnabled(),
ControlPlaneTrustDomain: conf.Spec.MTLSSpec.ControlPlaneTrustDomain,
SentryAddress: conf.Spec.MTLSSpec.SentryAddress,
}, nil
}
|
mikeee/dapr
|
pkg/operator/config.go
|
GO
|
mit
| 1,337 |
package handlers
import (
"context"
"strconv"
"github.com/argoproj/argo-rollouts/pkg/apis/rollouts"
argov1alpha1 "github.com/argoproj/argo-rollouts/pkg/apis/rollouts/v1alpha1"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"github.com/dapr/dapr/pkg/injector/annotations"
"github.com/dapr/dapr/pkg/operator/meta"
"github.com/dapr/dapr/pkg/operator/monitoring"
"github.com/dapr/dapr/pkg/validation"
"github.com/dapr/kit/logger"
"github.com/dapr/kit/utils"
)
const (
daprSidecarHTTPPortName = "dapr-http"
daprSidecarAPIGRPCPortName = "dapr-grpc"
daprSidecarInternalGRPCPortName = "dapr-internal"
daprSidecarMetricsPortName = "dapr-metrics"
daprSidecarHTTPPort = 3500
daprSidecarAPIGRPCPort = 50001
daprSidecarInternalGRPCPort = 50002
defaultMetricsEnabled = true
defaultMetricsPort = 9090
clusterIPNone = "None"
daprServiceOwnerField = ".metadata.controller"
annotationPrometheusProbe = "prometheus.io/probe"
annotationPrometheusScrape = "prometheus.io/scrape"
annotationPrometheusPort = "prometheus.io/port"
annotationPrometheusPath = "prometheus.io/path"
)
var log = logger.NewLogger("dapr.operator.handlers")
var defaultOptions = &Options{
ArgoRolloutServiceReconcilerEnabled: false,
}
type Options struct {
ArgoRolloutServiceReconcilerEnabled bool
}
// DaprHandler handles the lifetime for Dapr CRDs.
type DaprHandler struct {
mgr ctrl.Manager
client.Client
Scheme *runtime.Scheme
argoRolloutServiceReconcilerEnabled bool
}
type Reconciler struct {
*DaprHandler
newWrapper func() ObjectWrapper
}
// NewDaprHandler returns a new Dapr handler.
// This is a reconciler that watches all Deployment and StatefulSet resources and ensures that a matching Service resource is deployed to allow Dapr sidecar-to-sidecar communication and access to other ports.
func NewDaprHandler(mgr ctrl.Manager) *DaprHandler {
return NewDaprHandlerWithOptions(mgr, defaultOptions)
}
// NewDaprHandlerWithOptions returns a new Dapr handler with options.
func NewDaprHandlerWithOptions(mgr ctrl.Manager, opts *Options) *DaprHandler {
return &DaprHandler{
mgr: mgr,
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
argoRolloutServiceReconcilerEnabled: opts.ArgoRolloutServiceReconcilerEnabled,
}
}
// Init allows for various startup tasks.
func (h *DaprHandler) Init(ctx context.Context) error {
err := h.mgr.GetFieldIndexer().IndexField(
ctx,
&corev1.Service{},
daprServiceOwnerField,
func(rawObj client.Object) []string {
svc := rawObj.(*corev1.Service)
owner := metaV1.GetControllerOf(svc)
if h.isReconciled(owner) {
return []string{owner.Name}
}
return nil
},
)
if err != nil {
return err
}
err = ctrl.NewControllerManagedBy(h.mgr).
For(&appsv1.Deployment{}).
Owns(&corev1.Service{}).
WithOptions(controller.Options{
MaxConcurrentReconciles: 100,
}).
Complete(&Reconciler{
DaprHandler: h,
newWrapper: func() ObjectWrapper {
return &DeploymentWrapper{}
},
})
if err != nil {
return err
}
err = ctrl.NewControllerManagedBy(h.mgr).
For(&appsv1.StatefulSet{}).
Owns(&corev1.Service{}).
WithOptions(controller.Options{
MaxConcurrentReconciles: 100,
}).
Complete(&Reconciler{
DaprHandler: h,
newWrapper: func() ObjectWrapper {
return &StatefulSetWrapper{}
},
})
if err != nil {
return err
}
if h.argoRolloutServiceReconcilerEnabled {
err = ctrl.NewControllerManagedBy(h.mgr).
For(&argov1alpha1.Rollout{}).
Owns(&corev1.Service{}).
WithOptions(controller.Options{
MaxConcurrentReconciles: 100,
}).
Complete(&Reconciler{
DaprHandler: h,
newWrapper: func() ObjectWrapper {
return &RolloutWrapper{}
},
})
if err != nil {
return err
}
}
return nil
}
func (h *DaprHandler) daprServiceName(appID string) string {
return appID + "-dapr"
}
// Reconcile the expected services for Deployment and StatefulSet resources annotated for Dapr.
func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
// var wrapper appsv1.Deployment | appsv1.StatefulSet
wrapper := r.newWrapper()
expectedService := false
err := r.Get(ctx, req.NamespacedName, wrapper.GetObject())
if err != nil {
if apierrors.IsNotFound(err) {
log.Debugf("deployment has be deleted, %s", req.NamespacedName)
} else {
log.Errorf("unable to get deployment, %s, err: %s", req.NamespacedName, err)
return ctrl.Result{}, err
}
} else {
if wrapper.GetObject().GetDeletionTimestamp() != nil {
log.Debugf("deployment is being deleted, %s", req.NamespacedName)
return ctrl.Result{}, nil
}
expectedService = r.isAnnotatedForDapr(wrapper)
}
if expectedService {
err := r.ensureDaprServicePresent(ctx, req.Namespace, wrapper)
if err != nil {
log.Errorf("failed to ensure dapr service present, err: %v", err)
return ctrl.Result{Requeue: true}, err
}
}
return ctrl.Result{}, nil
}
func (h *DaprHandler) ensureDaprServicePresent(ctx context.Context, namespace string, wrapper ObjectWrapper) error {
appID := h.getAppID(wrapper)
err := validation.ValidateKubernetesAppID(appID)
if err != nil {
return err
}
daprSvcName := types.NamespacedName{
Namespace: namespace,
Name: h.daprServiceName(appID),
}
var daprSvc corev1.Service
err = h.Get(ctx, daprSvcName, &daprSvc)
if err != nil {
if apierrors.IsNotFound(err) {
log.Debugf("no service for wrapper found, wrapper: %s/%s", namespace, daprSvcName.Name)
return h.createDaprService(ctx, daprSvcName, wrapper)
}
log.Errorf("unable to get service, %s, err: %s", daprSvcName, err)
return err
}
err = h.patchDaprService(ctx, daprSvcName, wrapper, daprSvc)
if err != nil {
log.Errorf("unable to update service, %s, err: %s", daprSvcName, err)
return err
}
return nil
}
func (h *DaprHandler) patchDaprService(ctx context.Context, expectedService types.NamespacedName, wrapper ObjectWrapper, daprSvc corev1.Service) error {
appID := h.getAppID(wrapper)
service := h.createDaprServiceValues(ctx, expectedService, wrapper, appID)
err := ctrl.SetControllerReference(wrapper.GetObject(), service, h.Scheme)
if err != nil {
return err
}
service.ObjectMeta.ResourceVersion = daprSvc.ObjectMeta.ResourceVersion
err = h.Update(ctx, service)
if err != nil {
return err
}
monitoring.RecordServiceUpdatedCount(appID)
return nil
}
func (h *DaprHandler) createDaprService(ctx context.Context, expectedService types.NamespacedName, wrapper ObjectWrapper) error {
appID := h.getAppID(wrapper)
service := h.createDaprServiceValues(ctx, expectedService, wrapper, appID)
err := ctrl.SetControllerReference(wrapper.GetObject(), service, h.Scheme)
if err != nil {
return err
}
err = h.Create(ctx, service)
if err != nil {
log.Errorf("unable to create Dapr service for wrapper, service: %s, err: %s", expectedService, err)
return err
}
log.Debugf("created service: %s", expectedService)
monitoring.RecordServiceCreatedCount(appID)
return nil
}
func (h *DaprHandler) createDaprServiceValues(ctx context.Context, expectedService types.NamespacedName, wrapper ObjectWrapper, appID string) *corev1.Service {
enableMetrics := h.getEnableMetrics(wrapper)
metricsPort := h.getMetricsPort(wrapper)
log.Debugf("enableMetrics: %v", enableMetrics)
annotationsMap := map[string]string{
annotations.KeyAppID: appID,
}
if enableMetrics {
annotationsMap[annotationPrometheusProbe] = "true"
annotationsMap[annotationPrometheusScrape] = "true" // WARN: deprecated as of v1.7 please use prometheus.io/probe instead.
annotationsMap[annotationPrometheusPort] = strconv.Itoa(metricsPort)
annotationsMap[annotationPrometheusPath] = "/"
}
return &corev1.Service{
ObjectMeta: metaV1.ObjectMeta{
Name: expectedService.Name,
Namespace: expectedService.Namespace,
Labels: map[string]string{annotations.KeyEnabled: "true"},
Annotations: annotationsMap,
},
Spec: corev1.ServiceSpec{
Selector: wrapper.GetMatchLabels(),
ClusterIP: clusterIPNone,
Ports: []corev1.ServicePort{
{
Protocol: corev1.ProtocolTCP,
Port: 80,
TargetPort: intstr.FromInt(daprSidecarHTTPPort),
Name: daprSidecarHTTPPortName,
},
{
Protocol: corev1.ProtocolTCP,
Port: int32(daprSidecarAPIGRPCPort),
TargetPort: intstr.FromInt(daprSidecarAPIGRPCPort),
Name: daprSidecarAPIGRPCPortName,
},
{
Protocol: corev1.ProtocolTCP,
Port: int32(daprSidecarInternalGRPCPort),
TargetPort: intstr.FromInt(daprSidecarInternalGRPCPort),
Name: daprSidecarInternalGRPCPortName,
},
{
Protocol: corev1.ProtocolTCP,
Port: int32(metricsPort),
TargetPort: intstr.FromInt(metricsPort),
Name: daprSidecarMetricsPortName,
},
},
},
}
}
func (h *DaprHandler) getAppID(wrapper ObjectWrapper) string {
annotationsMap := wrapper.GetTemplateAnnotations()
return annotationsMap[annotations.KeyAppID]
}
func (h *DaprHandler) isAnnotatedForDapr(wrapper ObjectWrapper) bool {
return meta.IsAnnotatedForDapr(wrapper.GetTemplateAnnotations())
}
func (h *DaprHandler) getEnableMetrics(wrapper ObjectWrapper) bool {
annotationsMap := wrapper.GetTemplateAnnotations()
enableMetrics := defaultMetricsEnabled
if val := annotationsMap[annotations.KeyEnableMetrics]; val != "" {
enableMetrics = utils.IsTruthy(val)
}
return enableMetrics
}
func (h *DaprHandler) getMetricsPort(wrapper ObjectWrapper) int {
annotationsMap := wrapper.GetTemplateAnnotations()
metricsPort := defaultMetricsPort
if val := annotationsMap[annotations.KeyMetricsPort]; val != "" {
if v, err := strconv.Atoi(val); err == nil {
metricsPort = v
}
}
return metricsPort
}
func (h *DaprHandler) isReconciled(owner *metaV1.OwnerReference) bool {
if owner == nil {
return false
}
switch owner.APIVersion {
case appsv1.SchemeGroupVersion.String():
return owner.Kind == "Deployment" || owner.Kind == "StatefulSet"
case argov1alpha1.SchemeGroupVersion.String():
return h.argoRolloutServiceReconcilerEnabled && owner.Kind == rollouts.RolloutKind
}
return false
}
|
mikeee/dapr
|
pkg/operator/handlers/dapr_handler.go
|
GO
|
mit
| 10,671 |
package handlers
import (
"context"
"reflect"
"testing"
argov1alpha1 "github.com/argoproj/argo-rollouts/pkg/apis/rollouts/v1alpha1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"github.com/dapr/dapr/pkg/injector/annotations"
"github.com/dapr/dapr/pkg/operator/testobjects"
dapr_testing "github.com/dapr/dapr/pkg/testing"
)
func TestNewDaprHandler(t *testing.T) {
d := getTestDaprHandler()
assert.NotNil(t, d)
}
func TestGetAppID(t *testing.T) {
testDaprHandler := getTestDaprHandler()
t.Run("WithValidId", func(t *testing.T) {
// Arrange
expected := "test_id"
deployment := getDeployment(expected, "true")
// Act
got := testDaprHandler.getAppID(deployment)
// Assert
assert.Equal(t, expected, got)
})
t.Run("WithEmptyId", func(t *testing.T) {
// Arrange
expected := ""
deployment := getDeployment(expected, "true")
// Act
got := testDaprHandler.getAppID(deployment)
// Assert
assert.Equal(t, expected, got)
})
}
func TestIsAnnotatedForDapr(t *testing.T) {
testDaprHandler := getTestDaprHandler()
t.Run("Enabled", func(t *testing.T) {
// Arrange
expected := "true"
deployment := getDeployment("test_id", expected)
// Act
got := testDaprHandler.isAnnotatedForDapr(deployment)
// Assert
assert.True(t, got)
})
t.Run("Disabled", func(t *testing.T) {
// Arrange
expected := "false"
deployment := getDeployment("test_id", expected)
// Act
got := testDaprHandler.isAnnotatedForDapr(deployment)
// Assert
assert.False(t, got)
})
t.Run("Invalid", func(t *testing.T) {
// Arrange
expected := "0"
deployment := getDeployment("test_id", expected)
// Act
got := testDaprHandler.isAnnotatedForDapr(deployment)
// Assert
assert.False(t, got)
})
}
func TestDaprService(t *testing.T) {
t.Run("invalid empty app id", func(t *testing.T) {
d := getDeployment("", "true")
err := getTestDaprHandler().ensureDaprServicePresent(context.TODO(), "default", d)
require.Error(t, err)
})
t.Run("invalid char app id", func(t *testing.T) {
d := getDeployment("myapp@", "true")
err := getTestDaprHandler().ensureDaprServicePresent(context.TODO(), "default", d)
require.Error(t, err)
})
}
func TestCreateDaprServiceAppIDAndMetricsSettings(t *testing.T) {
testDaprHandler := getTestDaprHandler()
ctx := context.Background()
myDaprService := types.NamespacedName{
Namespace: "test",
Name: "test",
}
deployment := getDeployment("test", "true")
deployment.GetTemplateAnnotations()[annotations.KeyMetricsPort] = "12345"
service := testDaprHandler.createDaprServiceValues(ctx, myDaprService, deployment, "test")
require.NotNil(t, service)
assert.Equal(t, "test", service.ObjectMeta.Annotations[annotations.KeyAppID])
assert.Equal(t, "true", service.ObjectMeta.Annotations["prometheus.io/scrape"])
assert.Equal(t, "12345", service.ObjectMeta.Annotations["prometheus.io/port"])
assert.Equal(t, "/", service.ObjectMeta.Annotations["prometheus.io/path"])
deployment.GetTemplateAnnotations()[annotations.KeyEnableMetrics] = "false"
service = testDaprHandler.createDaprServiceValues(ctx, myDaprService, deployment, "test")
require.NotNil(t, service)
assert.Equal(t, "test", service.ObjectMeta.Annotations[annotations.KeyAppID])
assert.Equal(t, "", service.ObjectMeta.Annotations["prometheus.io/scrape"])
assert.Equal(t, "", service.ObjectMeta.Annotations["prometheus.io/port"])
assert.Equal(t, "", service.ObjectMeta.Annotations["prometheus.io/path"])
}
func TestPatchDaprService(t *testing.T) {
testDaprHandler := getTestDaprHandler()
s := runtime.NewScheme()
err := scheme.AddToScheme(s)
require.NoError(t, err)
testDaprHandler.Scheme = s
cli := fake.NewClientBuilder().WithScheme(s).Build()
testDaprHandler.Client = cli
ctx := context.Background()
myDaprService := types.NamespacedName{
Namespace: "test",
Name: "test",
}
deployment := getDeployment("test", "true")
err = testDaprHandler.createDaprService(ctx, myDaprService, deployment)
require.NoError(t, err)
var actualService corev1.Service
err = cli.Get(ctx, myDaprService, &actualService)
require.NoError(t, err)
assert.Equal(t, "test", actualService.ObjectMeta.Annotations[annotations.KeyAppID])
assert.Equal(t, "true", actualService.ObjectMeta.Annotations["prometheus.io/scrape"])
assert.Equal(t, "/", actualService.ObjectMeta.Annotations["prometheus.io/path"])
assert.Len(t, actualService.OwnerReferences, 1)
assert.Equal(t, "Deployment", actualService.OwnerReferences[0].Kind)
assert.Equal(t, "app", actualService.OwnerReferences[0].Name)
err = testDaprHandler.patchDaprService(ctx, myDaprService, deployment, actualService)
require.NoError(t, err)
err = cli.Get(ctx, myDaprService, &actualService)
require.NoError(t, err)
assert.Equal(t, "test", actualService.ObjectMeta.Annotations[annotations.KeyAppID])
assert.Equal(t, "true", actualService.ObjectMeta.Annotations["prometheus.io/scrape"])
assert.Equal(t, "/", actualService.ObjectMeta.Annotations["prometheus.io/path"])
assert.Len(t, actualService.OwnerReferences, 1)
assert.Equal(t, "Deployment", actualService.OwnerReferences[0].Kind)
assert.Equal(t, "app", actualService.OwnerReferences[0].Name)
}
func TestGetMetricsPort(t *testing.T) {
testDaprHandler := getTestDaprHandler()
t.Run("metrics port override", func(t *testing.T) {
// Arrange
deployment := getDeploymentWithMetricsPortAnnotation("test_id", "true", "5050")
// Act
p := testDaprHandler.getMetricsPort(deployment)
// Assert
assert.Equal(t, 5050, p)
})
t.Run("invalid metrics port override", func(t *testing.T) {
// Arrange
deployment := getDeploymentWithMetricsPortAnnotation("test_id", "true", "abc")
// Act
p := testDaprHandler.getMetricsPort(deployment)
// Assert
assert.Equal(t, defaultMetricsPort, p)
})
t.Run("no metrics port override", func(t *testing.T) {
// Arrange
deployment := getDeployment("test_id", "true")
// Act
p := testDaprHandler.getMetricsPort(deployment)
// Assert
assert.Equal(t, defaultMetricsPort, p)
})
}
func TestWrapper(t *testing.T) {
deploymentWrapper := getDeployment("test_id", "true")
statefulsetWrapper := getStatefulSet("test_id", "true")
rolloutWrapper := getRollout("test_id", "true")
t.Run("get match label from wrapper", func(t *testing.T) {
assert.Equal(t, "test", deploymentWrapper.GetMatchLabels()["app"])
assert.Equal(t, "test", statefulsetWrapper.GetMatchLabels()["app"])
assert.Equal(t, "test", rolloutWrapper.GetMatchLabels()["app"])
})
t.Run("get annotations from wrapper", func(t *testing.T) {
assert.Equal(t, "test_id", deploymentWrapper.GetTemplateAnnotations()[annotations.KeyAppID])
assert.Equal(t, "test_id", statefulsetWrapper.GetTemplateAnnotations()[annotations.KeyAppID])
assert.Equal(t, "test_id", rolloutWrapper.GetTemplateAnnotations()[annotations.KeyAppID])
})
t.Run("get object from wrapper", func(t *testing.T) {
assert.Equal(t, reflect.TypeOf(deploymentWrapper.GetObject()), reflect.TypeOf(&appsv1.Deployment{}))
assert.Equal(t, reflect.TypeOf(statefulsetWrapper.GetObject()), reflect.TypeOf(&appsv1.StatefulSet{}))
assert.Equal(t, reflect.TypeOf(rolloutWrapper.GetObject()), reflect.TypeOf(&argov1alpha1.Rollout{}))
assert.NotEqual(t, reflect.TypeOf(statefulsetWrapper.GetObject()), reflect.TypeOf(&appsv1.Deployment{}))
assert.NotEqual(t, reflect.TypeOf(deploymentWrapper.GetObject()), reflect.TypeOf(&appsv1.StatefulSet{}))
assert.NotEqual(t, reflect.TypeOf(rolloutWrapper.GetObject()), reflect.TypeOf(&appsv1.Deployment{}))
})
}
func TestInit(t *testing.T) {
mgr := dapr_testing.NewMockManager()
_ = scheme.AddToScheme(mgr.GetScheme())
_ = argov1alpha1.AddToScheme(mgr.GetScheme())
handler := NewDaprHandlerWithOptions(mgr, &Options{
ArgoRolloutServiceReconcilerEnabled: true,
})
t.Run("test init dapr handler", func(t *testing.T) {
assert.NotNil(t, handler)
err := handler.Init(context.Background())
require.NoError(t, err)
assert.Len(t, mgr.GetRunnables(), 3)
srv := &corev1.Service{}
val := mgr.GetIndexerFunc(&corev1.Service{})(srv)
assert.Nil(t, val)
trueA := true
srv = &corev1.Service{
ObjectMeta: metaV1.ObjectMeta{
OwnerReferences: []metaV1.OwnerReference{
{
Name: "TestName",
Controller: &trueA,
APIVersion: "apps/v1",
Kind: "Deployment",
},
},
},
}
val = mgr.GetIndexerFunc(&corev1.Service{})(srv)
assert.Equal(t, []string{"TestName"}, val)
})
t.Run("test wrapper", func(t *testing.T) {
deploymentCtl := mgr.GetRunnables()[0]
statefulsetCtl := mgr.GetRunnables()[1]
rolloutCtl := mgr.GetRunnables()[2]
// the runnable is sigs.k8s.io/controller-runtime/pkg/internal/controller.Controller
reconciler := reflect.Indirect(reflect.ValueOf(deploymentCtl)).FieldByName("Do").Interface().(*Reconciler)
wrapper := reconciler.newWrapper()
assert.NotNil(t, wrapper)
assert.Equal(t, reflect.TypeOf(&appsv1.Deployment{}), reflect.TypeOf(wrapper.GetObject()))
reconciler = reflect.Indirect(reflect.ValueOf(statefulsetCtl)).FieldByName("Do").Interface().(*Reconciler)
wrapper = reconciler.newWrapper()
assert.NotNil(t, wrapper)
assert.Equal(t, reflect.TypeOf(&appsv1.StatefulSet{}), reflect.TypeOf(wrapper.GetObject()))
reconciler = reflect.Indirect(reflect.ValueOf(rolloutCtl)).FieldByName("Do").Interface().(*Reconciler)
wrapper = reconciler.newWrapper()
assert.NotNil(t, wrapper)
assert.Equal(t, reflect.TypeOf(&argov1alpha1.Rollout{}), reflect.TypeOf(wrapper.GetObject()))
})
}
func getDeploymentWithMetricsPortAnnotation(daprID string, daprEnabled string, metricsPort string) ObjectWrapper {
d := getDeployment(daprID, daprEnabled)
d.GetTemplateAnnotations()[annotations.KeyMetricsPort] = metricsPort
return d
}
func getDeployment(appID string, daprEnabled string) ObjectWrapper {
return &DeploymentWrapper{testobjects.GetDeployment(appID, daprEnabled)}
}
func getStatefulSet(appID string, daprEnabled string) ObjectWrapper {
return &StatefulSetWrapper{testobjects.GetStatefulSet(appID, daprEnabled)}
}
func getRollout(appID string, daprEnabled string) ObjectWrapper {
metadata := metaV1.ObjectMeta{
Name: "app",
Labels: map[string]string{"app": "test_app"},
Annotations: map[string]string{
annotations.KeyAppID: appID,
annotations.KeyEnabled: daprEnabled,
annotations.KeyEnableMetrics: "true",
},
}
podTemplateSpec := corev1.PodTemplateSpec{
ObjectMeta: metadata,
}
rollout := argov1alpha1.Rollout{
ObjectMeta: metaV1.ObjectMeta{
Name: "app",
},
Spec: argov1alpha1.RolloutSpec{
Template: podTemplateSpec,
Selector: &metaV1.LabelSelector{
MatchLabels: map[string]string{
"app": "test",
},
},
},
}
return &RolloutWrapper{
rollout,
}
}
func getTestDaprHandler() *DaprHandler {
return &DaprHandler{}
}
|
mikeee/dapr
|
pkg/operator/handlers/dapr_handler_test.go
|
GO
|
mit
| 11,134 |
package handlers
import (
argov1alpha1 "github.com/argoproj/argo-rollouts/pkg/apis/rollouts/v1alpha1"
appsv1 "k8s.io/api/apps/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)
type ObjectWrapper interface {
GetMatchLabels() map[string]string
GetTemplateAnnotations() map[string]string
GetObject() client.Object
}
type DeploymentWrapper struct {
appsv1.Deployment
}
func (d *DeploymentWrapper) GetMatchLabels() map[string]string {
return d.Spec.Selector.MatchLabels
}
func (d *DeploymentWrapper) GetTemplateAnnotations() map[string]string {
return d.Spec.Template.ObjectMeta.Annotations
}
func (d *DeploymentWrapper) GetObject() client.Object {
return &d.Deployment
}
type StatefulSetWrapper struct {
appsv1.StatefulSet
}
func (s *StatefulSetWrapper) GetMatchLabels() map[string]string {
return s.Spec.Selector.MatchLabels
}
func (s *StatefulSetWrapper) GetTemplateAnnotations() map[string]string {
return s.Spec.Template.ObjectMeta.Annotations
}
func (s *StatefulSetWrapper) GetObject() client.Object {
return &s.StatefulSet
}
type RolloutWrapper struct {
argov1alpha1.Rollout
}
func (r *RolloutWrapper) GetMatchLabels() map[string]string {
return r.Spec.Selector.MatchLabels
}
func (r *RolloutWrapper) GetTemplateAnnotations() map[string]string {
return r.Spec.Template.ObjectMeta.Annotations
}
func (r *RolloutWrapper) GetObject() client.Object {
return &r.Rollout
}
|
mikeee/dapr
|
pkg/operator/handlers/wrappers.go
|
GO
|
mit
| 1,401 |
package meta
const (
WatchdogPatchedLabel = "dapr.io/watchdog-patched"
SidecarInjectorDeploymentName = "dapr-sidecar-injector"
)
|
mikeee/dapr
|
pkg/operator/meta/consts.go
|
GO
|
mit
| 133 |
package meta
import (
"github.com/dapr/dapr/pkg/injector/annotations"
injectorConsts "github.com/dapr/dapr/pkg/injector/consts"
"github.com/dapr/kit/utils"
)
// IsAnnotatedForDapr whether the dapr enabled annotation is present and true.
func IsAnnotatedForDapr(a map[string]string) bool {
return utils.IsTruthy(a[annotations.KeyEnabled])
}
// IsSidecarPresent whether the daprd sidecar is present, either because injector added it or because the user did.
func IsSidecarPresent(labels map[string]string) bool {
if _, ok := labels[injectorConsts.SidecarInjectedLabel]; ok {
return true
}
if _, ok := labels[WatchdogPatchedLabel]; ok {
return true
}
return false
}
|
mikeee/dapr
|
pkg/operator/meta/meta.go
|
GO
|
mit
| 679 |
package meta
import (
"testing"
injectorConsts "github.com/dapr/dapr/pkg/injector/consts"
)
func TestIsSidecarPresent(t *testing.T) {
tests := []struct {
name string
labels map[string]string
want bool
}{
{
name: "notPresentLabelsEmpty",
want: false,
},
{
name: "notPresent",
labels: map[string]string{"app": "my-app"},
want: false,
},
{
name: "presentInjected",
labels: map[string]string{injectorConsts.SidecarInjectedLabel: "yes"},
want: true,
},
{
name: "presentPatched",
labels: map[string]string{WatchdogPatchedLabel: "yes"},
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := IsSidecarPresent(tt.labels); got != tt.want {
t.Errorf("IsSidecarPresent() = %v, want %v", got, tt.want)
}
})
}
}
|
mikeee/dapr
|
pkg/operator/meta/meta_test.go
|
GO
|
mit
| 829 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package monitoring
import (
"context"
"go.opencensus.io/stats"
"go.opencensus.io/stats/view"
"go.opencensus.io/tag"
diagUtils "github.com/dapr/dapr/pkg/diagnostics/utils"
)
const (
appID = "app_id"
)
var (
serviceCreatedTotal = stats.Int64(
"operator/service_created_total",
"The total number of dapr services created.",
stats.UnitDimensionless)
serviceDeletedTotal = stats.Int64(
"operator/service_deleted_total",
"The total number of dapr services deleted.",
stats.UnitDimensionless)
serviceUpdatedTotal = stats.Int64(
"operator/service_updated_total",
"The total number of dapr services updated.",
stats.UnitDimensionless)
// appIDKey is a tag key for App ID.
appIDKey = tag.MustNewKey(appID)
)
// RecordServiceCreatedCount records the number of dapr service created.
func RecordServiceCreatedCount(appID string) {
stats.RecordWithTags(context.Background(), diagUtils.WithTags(serviceCreatedTotal.Name(), appIDKey, appID), serviceCreatedTotal.M(1))
}
// RecordServiceDeletedCount records the number of dapr service deleted.
func RecordServiceDeletedCount(appID string) {
stats.RecordWithTags(context.Background(), diagUtils.WithTags(serviceDeletedTotal.Name(), appIDKey, appID), serviceDeletedTotal.M(1))
}
// RecordServiceUpdatedCount records the number of dapr service updated.
func RecordServiceUpdatedCount(appID string) {
stats.RecordWithTags(context.Background(), diagUtils.WithTags(serviceUpdatedTotal.Name(), appIDKey, appID), serviceUpdatedTotal.M(1))
}
// InitMetrics initialize the operator service metrics.
func InitMetrics() error {
err := view.Register(
diagUtils.NewMeasureView(serviceCreatedTotal, []tag.Key{appIDKey}, view.Count()),
diagUtils.NewMeasureView(serviceDeletedTotal, []tag.Key{appIDKey}, view.Count()),
diagUtils.NewMeasureView(serviceUpdatedTotal, []tag.Key{appIDKey}, view.Count()),
)
return err
}
|
mikeee/dapr
|
pkg/operator/monitoring/metrics.go
|
GO
|
mit
| 2,445 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package operator
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"time"
argov1alpha1 "github.com/argoproj/argo-rollouts/pkg/apis/rollouts/v1alpha1"
"github.com/go-logr/logr"
apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
ctrl "sigs.k8s.io/controller-runtime"
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
"sigs.k8s.io/controller-runtime/pkg/webhook"
componentsapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
configurationapi "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1"
httpendpointsapi "github.com/dapr/dapr/pkg/apis/httpEndpoint/v1alpha1"
resiliencyapi "github.com/dapr/dapr/pkg/apis/resiliency/v1alpha1"
subscriptionsapiV1alpha1 "github.com/dapr/dapr/pkg/apis/subscriptions/v1alpha1"
subapi "github.com/dapr/dapr/pkg/apis/subscriptions/v2alpha1"
"github.com/dapr/dapr/pkg/health"
"github.com/dapr/dapr/pkg/modes"
"github.com/dapr/dapr/pkg/operator/api"
operatorcache "github.com/dapr/dapr/pkg/operator/cache"
"github.com/dapr/dapr/pkg/operator/handlers"
operatorv1pb "github.com/dapr/dapr/pkg/proto/operator/v1"
"github.com/dapr/dapr/pkg/security"
"github.com/dapr/kit/concurrency"
"github.com/dapr/kit/logger"
"github.com/dapr/kit/ptr"
)
var log = logger.NewLogger("dapr.operator")
// Operator is an Dapr Kubernetes Operator for managing components and sidecar lifecycle.
type Operator interface {
Run(ctx context.Context) error
}
// Options contains the options for `NewOperator`.
type Options struct {
Config string
LeaderElection bool
WatchdogEnabled bool
WatchdogInterval time.Duration
WatchdogMaxRestartsPerMin int
WatchNamespace string
ServiceReconcilerEnabled bool
ArgoRolloutServiceReconcilerEnabled bool
WatchdogCanPatchPodLabels bool
TrustAnchorsFile string
APIPort int
APIListenAddress string
HealthzPort int
HealthzListenAddress string
WebhookServerPort int
WebhookServerListenAddress string
}
type operator struct {
apiServer api.Server
config *Config
mgr ctrl.Manager
secProvider security.Provider
healthzPort int
healthzListenAddress string
}
// NewOperator returns a new Dapr Operator.
func NewOperator(ctx context.Context, opts Options) (Operator, error) {
conf, err := ctrl.GetConfig()
if err != nil {
return nil, fmt.Errorf("unable to get controller runtime configuration, err: %s", err)
}
config, err := LoadConfiguration(ctx, opts.Config, conf)
if err != nil {
return nil, fmt.Errorf("unable to load configuration, config: %s, err: %w", opts.Config, err)
}
secProvider, err := security.New(ctx, security.Options{
SentryAddress: config.SentryAddress,
ControlPlaneTrustDomain: config.ControlPlaneTrustDomain,
ControlPlaneNamespace: security.CurrentNamespace(),
TrustAnchorsFile: &opts.TrustAnchorsFile,
AppID: "dapr-operator",
// mTLS is always enabled for the operator.
MTLSEnabled: true,
Mode: modes.KubernetesMode,
})
if err != nil {
return nil, err
}
watchdogPodSelector := getSideCarInjectedNotExistsSelector()
scheme, err := buildScheme(opts)
if err != nil {
return nil, fmt.Errorf("failed to build operator scheme: %w", err)
}
mgr, err := ctrl.NewManager(conf, ctrl.Options{
Logger: logr.Discard(),
Scheme: scheme,
WebhookServer: webhook.NewServer(webhook.Options{
Host: opts.WebhookServerListenAddress,
Port: opts.WebhookServerPort,
TLSOpts: []func(*tls.Config){
func(tlsConfig *tls.Config) {
sec, sErr := secProvider.Handler(ctx)
// Error here means that the context has been cancelled before security
// is ready.
if sErr != nil {
return
}
*tlsConfig = *sec.TLSServerConfigNoClientAuth()
},
},
}),
HealthProbeBindAddress: "0",
Metrics: metricsserver.Options{
BindAddress: "0",
},
LeaderElection: opts.LeaderElection,
LeaderElectionID: "operator.dapr.io",
NewCache: operatorcache.GetFilteredCache(opts.WatchNamespace, watchdogPodSelector),
LeaderElectionReleaseOnCancel: true,
})
if err != nil {
return nil, fmt.Errorf("unable to start manager: %w", err)
}
mgrClient := mgr.GetClient()
if opts.WatchdogEnabled {
if !opts.LeaderElection {
log.Warn("Leadership election is forcibly enabled when the Dapr Watchdog is enabled")
}
wd := &DaprWatchdog{
client: mgrClient,
interval: opts.WatchdogInterval,
maxRestartsPerMin: opts.WatchdogMaxRestartsPerMin,
canPatchPodLabels: opts.WatchdogCanPatchPodLabels,
podSelector: watchdogPodSelector,
}
if err := mgr.Add(wd); err != nil {
return nil, fmt.Errorf("unable to add watchdog controller: %w", err)
}
} else {
log.Infof("Dapr Watchdog is not enabled")
}
if opts.ServiceReconcilerEnabled {
daprHandler := handlers.NewDaprHandlerWithOptions(mgr, &handlers.Options{ArgoRolloutServiceReconcilerEnabled: opts.ArgoRolloutServiceReconcilerEnabled})
if err := daprHandler.Init(ctx); err != nil {
return nil, fmt.Errorf("unable to initialize handler: %w", err)
}
}
return &operator{
mgr: mgr,
secProvider: secProvider,
config: config,
healthzPort: opts.HealthzPort,
healthzListenAddress: opts.HealthzListenAddress,
apiServer: api.NewAPIServer(api.Options{
Client: mgr.GetClient(),
Cache: mgr.GetCache(),
Security: secProvider,
Port: opts.APIPort,
}),
}, nil
}
func (o *operator) syncHTTPEndpoint(ctx context.Context) func(obj interface{}) {
return func(obj interface{}) {
e, ok := obj.(*httpendpointsapi.HTTPEndpoint)
if ok {
log.Debugf("Observed http endpoint to be synced: %s/%s", e.Namespace, e.Name)
o.apiServer.OnHTTPEndpointUpdated(ctx, e)
}
}
}
func (o *operator) syncSubscription(ctx context.Context, eventType operatorv1pb.ResourceEventType) func(obj interface{}) {
return func(obj interface{}) {
var s *subapi.Subscription
switch o := obj.(type) {
case *subapi.Subscription:
s = o
case cache.DeletedFinalStateUnknown:
s = o.Obj.(*subapi.Subscription)
}
if s != nil {
log.Debugf("Observed Subscription to be synced: %s/%s", s.Namespace, s.Name)
o.apiServer.OnSubscriptionUpdated(ctx, eventType, s)
}
}
}
func (o *operator) Run(ctx context.Context) error {
log.Info("Dapr Operator is starting")
healthzServer := health.NewServer(health.Options{
Log: log,
Targets: ptr.Of(5),
})
/*
Make sure to set `ENABLE_WEBHOOKS=false` when we run locally.
*/
enableConversionWebhooks := !strings.EqualFold(os.Getenv("ENABLE_WEBHOOKS"), "false")
if enableConversionWebhooks {
err := ctrl.NewWebhookManagedBy(o.mgr).
For(&subscriptionsapiV1alpha1.Subscription{}).
Complete()
if err != nil {
return fmt.Errorf("unable to create webhook Subscriptions v1alpha1: %w", err)
}
err = ctrl.NewWebhookManagedBy(o.mgr).
For(&subapi.Subscription{}).
Complete()
if err != nil {
return fmt.Errorf("unable to create webhook Subscriptions v2alpha1: %w", err)
}
}
caBundleCh := make(chan []byte)
runner := concurrency.NewRunnerManager(
o.secProvider.Run,
func(ctx context.Context) error {
// Wait for webhook certificates to be ready before starting the manager.
_, rErr := o.secProvider.Handler(ctx)
if rErr != nil {
return rErr
}
healthzServer.Ready()
return o.mgr.Start(ctx)
},
func(ctx context.Context) error {
// start healthz server
if rErr := healthzServer.Run(ctx, o.healthzListenAddress, o.healthzPort); rErr != nil {
return fmt.Errorf("failed to start healthz server: %w", rErr)
}
return nil
},
func(ctx context.Context) error {
if rErr := o.apiServer.Ready(ctx); rErr != nil {
return fmt.Errorf("API server did not become ready in time: %w", rErr)
}
healthzServer.Ready()
log.Infof("Dapr Operator started")
<-ctx.Done()
return nil
},
func(ctx context.Context) error {
if !enableConversionWebhooks {
healthzServer.Ready()
<-ctx.Done()
return nil
}
sec, rErr := o.secProvider.Handler(ctx)
if rErr != nil {
return rErr
}
sec.WatchTrustAnchors(ctx, caBundleCh)
return nil
},
func(ctx context.Context) error {
if !enableConversionWebhooks {
healthzServer.Ready()
<-ctx.Done()
return nil
}
sec, rErr := o.secProvider.Handler(ctx)
if rErr != nil {
return rErr
}
caBundle, rErr := sec.CurrentTrustAnchors(ctx)
if rErr != nil {
return rErr
}
for {
rErr = o.patchConversionWebhooksInCRDs(ctx, caBundle, o.mgr.GetConfig(), "subscriptions.dapr.io")
if rErr != nil {
return rErr
}
healthzServer.Ready()
select {
case caBundle = <-caBundleCh:
case <-ctx.Done():
return nil
}
}
},
func(ctx context.Context) error {
log.Info("Starting API server")
rErr := o.apiServer.Run(ctx)
if rErr != nil {
return fmt.Errorf("failed to start API server: %w", rErr)
}
return nil
},
func(ctx context.Context) error {
if !o.mgr.GetCache().WaitForCacheSync(ctx) {
return errors.New("failed to wait for cache sync")
}
httpEndpointInformer, rErr := o.mgr.GetCache().GetInformer(ctx, &httpendpointsapi.HTTPEndpoint{})
if rErr != nil {
return fmt.Errorf("unable to get http endpoint informer: %w", rErr)
}
_, rErr = httpEndpointInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: o.syncHTTPEndpoint(ctx),
UpdateFunc: func(_, newObj interface{}) {
o.syncHTTPEndpoint(ctx)(newObj)
},
})
if rErr != nil {
return fmt.Errorf("unable to add http endpoint informer event handler: %w", rErr)
}
healthzServer.Ready()
<-ctx.Done()
return nil
},
func(ctx context.Context) error {
if !o.mgr.GetCache().WaitForCacheSync(ctx) {
return errors.New("failed to wait for cache sync")
}
subscriptionInformer, rErr := o.mgr.GetCache().GetInformer(ctx, new(subapi.Subscription))
if rErr != nil {
return fmt.Errorf("unable to get setup subscriptions informer: %w", rErr)
}
_, rErr = subscriptionInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: o.syncSubscription(ctx, operatorv1pb.ResourceEventType_CREATED),
UpdateFunc: func(_, newObj interface{}) {
o.syncSubscription(ctx, operatorv1pb.ResourceEventType_UPDATED)(newObj)
},
DeleteFunc: o.syncSubscription(ctx, operatorv1pb.ResourceEventType_DELETED),
})
if rErr != nil {
return fmt.Errorf("unable to add subscriptions informer event handler: %w", rErr)
}
healthzServer.Ready()
<-ctx.Done()
return nil
},
)
return runner.Run(ctx)
}
// Patches the conversion webhooks in the specified CRDs to set the TLS configuration (including namespace and CA bundle)
func (o *operator) patchConversionWebhooksInCRDs(ctx context.Context, caBundle []byte, conf *rest.Config, crdNames ...string) error {
clientSet, err := apiextensionsclient.NewForConfig(conf)
if err != nil {
return fmt.Errorf("could not get API extension client: %v", err)
}
crdClient := clientSet.ApiextensionsV1().CustomResourceDefinitions()
for _, crdName := range crdNames {
crd, err := crdClient.Get(ctx, crdName, v1.GetOptions{})
if err != nil {
return fmt.Errorf("could not get CRD %q: %v", crdName, err)
}
if crd == nil ||
crd.Spec.Conversion == nil ||
crd.Spec.Conversion.Webhook == nil ||
crd.Spec.Conversion.Webhook.ClientConfig == nil {
return fmt.Errorf("crd %q does not have an existing webhook client config. Applying resources of this type will fail", crdName)
}
if crd.Spec.Conversion.Webhook.ClientConfig.Service != nil &&
crd.Spec.Conversion.Webhook.ClientConfig.Service.Namespace == security.CurrentNamespace() &&
crd.Spec.Conversion.Webhook.ClientConfig.CABundle != nil &&
bytes.Equal(crd.Spec.Conversion.Webhook.ClientConfig.CABundle, caBundle) {
log.Infof("Conversion webhook for %q is up to date", crdName)
continue
}
// This code mimics:
// kubectl patch crd "subscriptions.dapr.io" --type='json' -p [{'op': 'replace', 'path': '/spec/conversion/webhook/clientConfig/service/namespace', 'value':'${namespace}'},{'op': 'add', 'path': '/spec/conversion/webhook/clientConfig/caBundle', 'value':'${caBundle}'}]"
type patchValue struct {
Op string `json:"op"`
Path string `json:"path"`
Value interface{} `json:"value"`
}
payload := []patchValue{{
Op: "replace",
Path: "/spec/conversion/webhook/clientConfig/service/namespace",
Value: security.CurrentNamespace(),
}, {
Op: "replace",
Path: "/spec/conversion/webhook/clientConfig/caBundle",
Value: caBundle,
}}
payloadJSON, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("could not marshal webhook spec: %w", err)
}
if _, err := crdClient.Patch(ctx, crdName, types.JSONPatchType, payloadJSON, v1.PatchOptions{}); err != nil {
return fmt.Errorf("failed to patch webhook in CRD %q: %v", crdName, err)
}
log.Infof("Successfully patched webhook in CRD %q", crdName)
}
return nil
}
func buildScheme(opts Options) (*runtime.Scheme, error) {
builders := []func(*runtime.Scheme) error{
clientgoscheme.AddToScheme,
componentsapi.AddToScheme,
configurationapi.AddToScheme,
resiliencyapi.AddToScheme,
httpendpointsapi.AddToScheme,
subscriptionsapiV1alpha1.AddToScheme,
subapi.AddToScheme,
}
if opts.ArgoRolloutServiceReconcilerEnabled {
builders = append(builders, argov1alpha1.AddToScheme)
}
errs := make([]error, len(builders))
scheme := runtime.NewScheme()
for i, builder := range builders {
errs[i] = builder(scheme)
}
return scheme, errors.Join(errs...)
}
|
mikeee/dapr
|
pkg/operator/operator.go
|
GO
|
mit
| 14,779 |
package testobjects
import (
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/dapr/dapr/pkg/injector/annotations"
)
type resourceOpts struct {
name string
namespace string
additionalLabels map[string]string
additionalAnnotations map[string]string
}
func (r resourceOpts) updateMetadata(m *metaV1.ObjectMeta) {
if len(r.additionalLabels) != 0 {
if m.Labels == nil {
m.Labels = make(map[string]string, len(r.additionalLabels))
}
for k, v := range r.additionalLabels {
m.Labels[k] = v
}
}
if len(r.additionalAnnotations) != 0 {
if m.Annotations == nil {
m.Annotations = make(map[string]string, len(r.additionalAnnotations))
}
for k, v := range r.additionalAnnotations {
m.Annotations[k] = v
}
}
}
type resourceOptsFunc func(o *resourceOpts)
func NameNamespace(name, namespace string) resourceOptsFunc {
return func(o *resourceOpts) {
o.name = name
o.namespace = namespace
}
}
func AddLabels(l map[string]string) resourceOptsFunc {
return func(o *resourceOpts) {
o.additionalLabels = l
}
}
func AddAnnotations(a map[string]string) resourceOptsFunc {
return func(o *resourceOpts) {
o.additionalAnnotations = a
}
}
func getPodMetadata(appID string, daprEnabled string) metaV1.ObjectMeta {
return metaV1.ObjectMeta{
Name: "app",
Labels: map[string]string{"app": "test_app"},
Annotations: map[string]string{
annotations.KeyAppID: appID,
annotations.KeyEnabled: daprEnabled,
annotations.KeyEnableMetrics: "true",
},
}
}
func GetPod(appID string, daprEnabled string, withOpts ...resourceOptsFunc) corev1.Pod {
// Arrange
pod := corev1.Pod{
ObjectMeta: getPodMetadata(appID, daprEnabled),
}
opts := getOptsOrDefaults(withOpts)
opts.updateMetadata(&pod.ObjectMeta)
pod.Name = opts.name
pod.Namespace = opts.namespace
return pod
}
func getOptsOrDefaults(withOpts []resourceOptsFunc) resourceOpts {
opts := resourceOpts{
name: "app",
namespace: "test",
}
for _, o := range withOpts {
o(&opts)
}
return opts
}
func GetDeployment(appID string, daprEnabled string, withOpts ...resourceOptsFunc) appsv1.Deployment {
podTemplateSpec := corev1.PodTemplateSpec{
ObjectMeta: getPodMetadata(appID, daprEnabled),
}
opts := getOptsOrDefaults(withOpts)
deployment := appsv1.Deployment{
ObjectMeta: metaV1.ObjectMeta{
Name: opts.name,
Namespace: opts.namespace,
},
Spec: appsv1.DeploymentSpec{
Template: podTemplateSpec,
Selector: &metaV1.LabelSelector{
MatchLabels: map[string]string{
"app": "test",
},
},
},
}
opts.updateMetadata(&deployment.ObjectMeta)
return deployment
}
func GetStatefulSet(appID string, daprEnabled string, withOpts ...resourceOptsFunc) appsv1.StatefulSet {
podTemplateSpec := corev1.PodTemplateSpec{
ObjectMeta: getPodMetadata(appID, daprEnabled),
}
opts := getOptsOrDefaults(withOpts)
statefulset := appsv1.StatefulSet{
ObjectMeta: metaV1.ObjectMeta{
Name: opts.name,
Namespace: opts.namespace,
},
Spec: appsv1.StatefulSetSpec{
Template: podTemplateSpec,
Selector: &metaV1.LabelSelector{
MatchLabels: map[string]string{
"app": "test",
},
},
},
}
opts.updateMetadata(&statefulset.ObjectMeta)
return statefulset
}
|
mikeee/dapr
|
pkg/operator/testobjects/apps.go
|
GO
|
mit
| 3,345 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.