hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 0,
"code_window": [
"// IsIPv6Proxy check the addresses slice and returns true for all addresses are valid IPv6 address\n",
"// for all other cases it returns false\n",
"func IsIPv6Proxy(ipAddrs []string) bool {\n",
"\tresult := false\n",
"\tfor i := 0; i < len(ipAddrs); i++ {\n",
"\t\taddr := net.ParseIP(ipAddrs[i])\n",
"\t\tif addr == nil {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pilot/pkg/util/network/ip.go",
"type": "replace",
"edit_start_line_idx": 146
} | // Copyright Istio 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 network
import (
"context"
"fmt"
"net"
"strings"
"testing"
)
// The test may run on a system with localhost = 127.0.0.1 or ::1, so we
// determine that value and use it in the "expected" results for the test
// cases in TestResolveAddr(). Need to wrap IPv6 addresses in square
// brackets.
func determineLocalHostIPString(t *testing.T) string {
ips, err := net.LookupIP("localhost")
if err != nil || len(ips) == 0 {
t.Fatalf("Test setup failure - unable to determine IP of localhost: %v", err)
}
var ret string
for _, ip := range ips {
if ip.To4() == nil {
ret = fmt.Sprintf("[%s]", ip.String())
} else {
return ip.String()
}
}
return ret
}
func MockLookupIPAddr(_ context.Context, _ string) ([]net.IPAddr, error) {
ret := []net.IPAddr{
{IP: net.ParseIP("2001:db8::68")},
{IP: net.IPv4(1, 2, 3, 4)},
{IP: net.IPv4(1, 2, 3, 5)},
}
return ret, nil
}
func MockLookupIPAddrIPv6(_ context.Context, _ string) ([]net.IPAddr, error) {
ret := []net.IPAddr{
{IP: net.ParseIP("2001:db8::68")},
}
return ret, nil
}
func TestResolveAddr(t *testing.T) {
localIP := determineLocalHostIPString(t)
testCases := []struct {
name string
input string
expected string
errStr string
lookup func(ctx context.Context, addr string) ([]net.IPAddr, error)
}{
{
name: "Host by name",
input: "localhost:9080",
expected: fmt.Sprintf("%s:9080", localIP),
errStr: "",
lookup: nil,
},
{
name: "Host by name w/brackets",
input: "[localhost]:9080",
expected: fmt.Sprintf("%s:9080", localIP),
errStr: "",
lookup: nil,
},
{
name: "Host by IPv4",
input: "127.0.0.1:9080",
expected: "127.0.0.1:9080",
errStr: "",
lookup: nil,
},
{
name: "Host by IPv6",
input: "[::1]:9080",
expected: "[::1]:9080",
errStr: "",
lookup: nil,
},
{
name: "Bad IPv4",
input: "127.0.0.1.1:9080",
expected: "",
errStr: "lookup failed for IP address: lookup 127.0.0.1.1: no such host",
lookup: nil,
},
{
name: "Bad IPv6",
input: "[2001:db8::bad::1]:9080",
expected: "",
errStr: "lookup failed for IP address: lookup 2001:db8::bad::1: no such host",
lookup: nil,
},
{
name: "Empty host",
input: "",
expected: "",
errStr: ErrResolveNoAddress.Error(),
lookup: nil,
},
{
name: "IPv6 missing brackets",
input: "2001:db8::20:9080",
expected: "",
errStr: "address 2001:db8::20:9080: too many colons in address",
lookup: nil,
},
{
name: "Colon, but no port",
input: "localhost:",
expected: fmt.Sprintf("%s:", localIP),
errStr: "",
lookup: nil,
},
{
name: "Missing port",
input: "localhost",
expected: "",
errStr: "address localhost: missing port in address",
lookup: nil,
},
{
name: "Missing host",
input: ":9080",
expected: "",
errStr: "lookup failed for IP address: lookup : no such host",
lookup: nil,
},
{
name: "Host by name - non local",
input: "www.foo.com:9080",
expected: "1.2.3.4:9080",
errStr: "",
lookup: MockLookupIPAddr,
},
{
name: "Host by name - non local 0 IPv6 only address",
input: "www.foo.com:9080",
expected: "[2001:db8::68]:9080",
errStr: "",
lookup: MockLookupIPAddrIPv6,
},
}
for _, tc := range testCases {
actual, err := ResolveAddr(tc.input, tc.lookup)
if err != nil {
if tc.errStr == "" {
t.Errorf("[%s] expected success, but saw error: %v", tc.name, err)
} else if err.Error() != tc.errStr {
if strings.Contains(err.Error(), "Temporary failure in name resolution") {
t.Logf("[%s] expected error %q, got %q", tc.name, tc.errStr, err.Error())
continue
}
t.Errorf("[%s] expected error %q, got %q", tc.name, tc.errStr, err.Error())
}
} else {
if tc.errStr != "" {
t.Errorf("[%s] no error seen, but expected failure: %s", tc.name, tc.errStr)
} else if actual != tc.expected {
t.Errorf("[%s] expected address %q, got %q", tc.name, tc.expected, actual)
}
}
}
}
func TestIsIPv6Proxy(t *testing.T) {
tests := []struct {
name string
addrs []string
expected bool
}{
{
name: "ipv4 only",
addrs: []string{"1.1.1.1", "127.0.0.1", "2.2.2.2"},
expected: false,
},
{
name: "ipv6 only",
addrs: []string{"1111:2222::1", "::1", "2222:3333::1"},
expected: true,
},
{
name: "mixed ipv4 and ipv6",
addrs: []string{"1111:2222::1", "::1", "127.0.0.1", "2.2.2.2", "2222:3333::1"},
expected: true,
},
}
for _, tt := range tests {
result := IsIPv6Proxy(tt.addrs)
if result != tt.expected {
t.Errorf("Test %s failed, expected: %t got: %t", tt.name, tt.expected, result)
}
}
}
| pilot/pkg/util/network/ip_test.go | 1 | https://github.com/istio/istio/commit/4542cda6c9973317abeb28a6de4876587c644f23 | [
0.9990806579589844,
0.10816033184528351,
0.00016782546299509704,
0.00023636026890017092,
0.28014183044433594
] |
{
"id": 0,
"code_window": [
"// IsIPv6Proxy check the addresses slice and returns true for all addresses are valid IPv6 address\n",
"// for all other cases it returns false\n",
"func IsIPv6Proxy(ipAddrs []string) bool {\n",
"\tresult := false\n",
"\tfor i := 0; i < len(ipAddrs); i++ {\n",
"\t\taddr := net.ParseIP(ipAddrs[i])\n",
"\t\tif addr == nil {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pilot/pkg/util/network/ip.go",
"type": "replace",
"edit_start_line_idx": 146
} | // Copyright Istio 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 controllers
import (
"fmt"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/cache"
"istio.io/istio/pkg/config"
"istio.io/istio/pkg/config/schema/collections"
istiolog "istio.io/pkg/log"
)
var log = istiolog.RegisterScope("controllers", "common controller logic", 0)
// Object is a union of runtime + meta objects. Essentially every k8s object meets this interface.
// and certainly all that we care about.
type Object interface {
metav1.Object
runtime.Object
}
// UnstructuredToGVR extracts the GVR of an unstructured resource. This is useful when using dynamic
// clients.
func UnstructuredToGVR(u unstructured.Unstructured) (schema.GroupVersionResource, error) {
res := schema.GroupVersionResource{}
gv, err := schema.ParseGroupVersion(u.GetAPIVersion())
if err != nil {
return res, err
}
gk := config.GroupVersionKind{
Group: gv.Group,
Version: gv.Version,
Kind: u.GetKind(),
}
found, ok := collections.All.FindByGroupVersionKind(gk)
if !ok {
return res, fmt.Errorf("unknown gvk: %v", gk)
}
return schema.GroupVersionResource{
Group: gk.Group,
Version: gk.Version,
Resource: found.Resource().Plural(),
}, nil
}
// ObjectToGVR extracts the GVR of an unstructured resource. This is useful when using dynamic
// clients.
func ObjectToGVR(u Object) (schema.GroupVersionResource, error) {
kGvk := u.GetObjectKind().GroupVersionKind()
gk := config.GroupVersionKind{
Group: kGvk.Group,
Version: kGvk.Version,
Kind: kGvk.Kind,
}
found, ok := collections.All.FindByGroupVersionKind(gk)
if !ok {
return schema.GroupVersionResource{}, fmt.Errorf("unknown gvk: %v", gk)
}
return schema.GroupVersionResource{
Group: gk.Group,
Version: gk.Version,
Resource: found.Resource().Plural(),
}, nil
}
// EnqueueForParentHandler returns a handler that will enqueue the parent (by ownerRef) resource
func EnqueueForParentHandler(q Queue, kind config.GroupVersionKind) func(obj Object) {
handler := func(obj Object) {
for _, ref := range obj.GetOwnerReferences() {
refGV, err := schema.ParseGroupVersion(ref.APIVersion)
if err != nil {
log.Errorf("could not parse OwnerReference api version %q: %v", ref.APIVersion, err)
continue
}
if refGV == kind.Kubernetes().GroupVersion() {
// We found a parent we care about, add it to the queue
q.Add(types.NamespacedName{
Namespace: obj.GetNamespace(),
Name: obj.GetName(),
})
}
}
}
return handler
}
// ObjectHandler returns a handler that will act on the latest version of an object
// This means Add/Update/Delete are all handled the same and are just used to trigger reconciling.
func ObjectHandler(handler func(o Object)) cache.ResourceEventHandler {
h := func(obj interface{}) {
o := extractObject(obj)
if o == nil {
return
}
handler(o)
}
return cache.ResourceEventHandlerFuncs{
AddFunc: h,
UpdateFunc: func(oldObj, newObj interface{}) {
h(newObj)
},
DeleteFunc: h,
}
}
// FilteredObjectHandler returns a handler that will act on the latest version of an object
// This means Add/Update/Delete are all handled the same and are just used to trigger reconciling.
// If filters are set, returning 'false' will exclude the event. For Add and Deletes, the filter will be based
// on the new or old item. For updates, the item will be handled if either the new or the old object is updated.
func FilteredObjectHandler(handler func(o Object), filter func(o Object) bool) cache.ResourceEventHandler {
return filteredObjectHandler(handler, false, filter)
}
// FilteredObjectSpecHandler returns a handler that will act on the latest version of an object
// This means Add/Update/Delete are all handled the same and are just used to trigger reconciling.
// Unlike FilteredObjectHandler, the handler is only trigger when the resource spec changes (ie resourceVersion)
// If filters are set, returning 'false' will exclude the event. For Add and Deletes, the filter will be based
// on the new or old item. For updates, the item will be handled if either the new or the old object is updated.
func FilteredObjectSpecHandler(handler func(o Object), filter func(o Object) bool) cache.ResourceEventHandler {
return filteredObjectHandler(handler, true, filter)
}
func filteredObjectHandler(handler func(o Object), onlyIncludeSpecChanges bool, filter func(o Object) bool) cache.ResourceEventHandler {
single := func(obj interface{}) {
o := extractObject(obj)
if o == nil {
return
}
if !filter(o) {
return
}
handler(o)
}
return cache.ResourceEventHandlerFuncs{
AddFunc: single,
UpdateFunc: func(oldInterface, newInterace interface{}) {
oldObj := extractObject(oldInterface)
if oldObj == nil {
return
}
newObj := extractObject(newInterace)
if newObj == nil {
return
}
if onlyIncludeSpecChanges && oldObj.GetResourceVersion() == newObj.GetResourceVersion() {
return
}
newer := filter(newObj)
older := filter(oldObj)
if !newer && !older {
return
}
handler(newObj)
},
DeleteFunc: single,
}
}
func extractObject(obj interface{}) Object {
o, ok := obj.(Object)
if !ok {
tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
log.Errorf("couldn't get object from tombstone %+v", obj)
return nil
}
o, ok = tombstone.Obj.(Object)
if !ok {
log.Errorf("tombstone contained object that is not an object %+v", obj)
return nil
}
}
return o
}
// IgnoreNotFound returns nil on NotFound errors.
// All other values that are not NotFound errors or nil are returned unmodified.
func IgnoreNotFound(err error) error {
if apierrors.IsNotFound(err) {
return nil
}
return err
}
| pkg/kube/controllers/common.go | 0 | https://github.com/istio/istio/commit/4542cda6c9973317abeb28a6de4876587c644f23 | [
0.0003313828492537141,
0.00017922540428116918,
0.00016211271577049047,
0.00016827252693474293,
0.00003527666922309436
] |
{
"id": 0,
"code_window": [
"// IsIPv6Proxy check the addresses slice and returns true for all addresses are valid IPv6 address\n",
"// for all other cases it returns false\n",
"func IsIPv6Proxy(ipAddrs []string) bool {\n",
"\tresult := false\n",
"\tfor i := 0; i < len(ipAddrs); i++ {\n",
"\t\taddr := net.ParseIP(ipAddrs[i])\n",
"\t\tif addr == nil {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pilot/pkg/util/network/ip.go",
"type": "replace",
"edit_start_line_idx": 146
} | # External Services
By default Istio-enabled services are unable to access services and URLs outside of the cluster. Pods use <i>iptables</i> to transparently redirect all outbound traffic to the sidecar proxy, which only handles intra-cluster destinations.
See [the Egress Task](https://istio.io/docs/tasks/traffic-management/egress/) for
information on configuring Istio to contact external services.
This directory contains samples showing how to enable pods to contact a few well
known services.
If Istio is not configured to allow pods to contact external services, the pods will
see errors such as 404s, HTTPS connection problems, and TCP connection problems. If
ServiceEntries are misconfigured pods may see problems with server names.
## Try it out
After an operator runs `kubectl create -f aptget.yaml` pods will be able to
succeed with `apt-get update` and `apt-get install`.
After an operator runs `kubectl create -f github.yaml` pods will be able to
succeed with `git clone https://github.com/fortio/fortio.git`.
Running `kubectl create -f pypi.yaml` allows pods to update Python libraries using `pip`.
It is not a best practice to enable pods to update libraries dynamically.
We are providing these samples
because they have proven to be helpful with interactive troubleshooting. Security minded clusters should only allow traffic to service dependencies such as cloud
services.
### Enable communication by default
Note that [this note](https://istio.io/docs/tasks/traffic-management/egress/#install-istio-with-access-to-all-external-services-by-default) shows how to configure Istio to contact services by default. The technique
discussed there does not allow HTTP on port 80 or SSH on port 22. These examples will
allow external communication for ports 80 and 22.
| samples/external/README.md | 0 | https://github.com/istio/istio/commit/4542cda6c9973317abeb28a6de4876587c644f23 | [
0.0001687120966380462,
0.0001666185853537172,
0.00016569999570492655,
0.00016603112453594804,
0.000001217649241880281
] |
{
"id": 0,
"code_window": [
"// IsIPv6Proxy check the addresses slice and returns true for all addresses are valid IPv6 address\n",
"// for all other cases it returns false\n",
"func IsIPv6Proxy(ipAddrs []string) bool {\n",
"\tresult := false\n",
"\tfor i := 0; i < len(ipAddrs); i++ {\n",
"\t\taddr := net.ParseIP(ipAddrs[i])\n",
"\t\tif addr == nil {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pilot/pkg/util/network/ip.go",
"type": "replace",
"edit_start_line_idx": 146
} | // Copyright 2019 Google LLC.
//
// 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.
//
syntax = "proto3";
package google.type;
option go_package = "google.golang.org/genproto/googleapis/type/dayofweek;dayofweek";
option java_multiple_files = true;
option java_outer_classname = "DayOfWeekProto";
option java_package = "com.google.type";
option objc_class_prefix = "GTP";
// Represents a day of week.
enum DayOfWeek {
// The unspecified day-of-week.
DAY_OF_WEEK_UNSPECIFIED = 0;
// The day-of-week of Monday.
MONDAY = 1;
// The day-of-week of Tuesday.
TUESDAY = 2;
// The day-of-week of Wednesday.
WEDNESDAY = 3;
// The day-of-week of Thursday.
THURSDAY = 4;
// The day-of-week of Friday.
FRIDAY = 5;
// The day-of-week of Saturday.
SATURDAY = 6;
// The day-of-week of Sunday.
SUNDAY = 7;
}
| common-protos/google/type/dayofweek.proto | 0 | https://github.com/istio/istio/commit/4542cda6c9973317abeb28a6de4876587c644f23 | [
0.0001754482218530029,
0.0001707028568489477,
0.00016551461885683239,
0.00016962288646027446,
0.000003403222308406839
] |
{
"id": 1,
"code_window": [
"\t\t\t// Should not happen, invalid IP in proxy's IPAddresses slice should have been caught earlier,\n",
"\t\t\t// skip it to prevent a panic.\n",
"\t\t\tcontinue\n",
"\t\t}\n",
"\n",
"\t\t// need to check that a proxy can have an IPv6 address but configuration is not configured K8s for dual-stack support.\n",
"\t\t// In this case an ipv6 link local address will appear, but not one that is routable to with K8s\n",
"\t\tif addr.To4() == nil && addr.To16() != nil && !addr.IsLinkLocalUnicast() {\n",
"\t\t\tresult = true\n",
"\t\t}\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tif addr.To4() != nil {\n",
"\t\t\treturn false\n"
],
"file_path": "pilot/pkg/util/network/ip.go",
"type": "replace",
"edit_start_line_idx": 154
} | // Copyright Istio 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 network
import (
"context"
"fmt"
"net"
"strings"
"testing"
)
// The test may run on a system with localhost = 127.0.0.1 or ::1, so we
// determine that value and use it in the "expected" results for the test
// cases in TestResolveAddr(). Need to wrap IPv6 addresses in square
// brackets.
func determineLocalHostIPString(t *testing.T) string {
ips, err := net.LookupIP("localhost")
if err != nil || len(ips) == 0 {
t.Fatalf("Test setup failure - unable to determine IP of localhost: %v", err)
}
var ret string
for _, ip := range ips {
if ip.To4() == nil {
ret = fmt.Sprintf("[%s]", ip.String())
} else {
return ip.String()
}
}
return ret
}
func MockLookupIPAddr(_ context.Context, _ string) ([]net.IPAddr, error) {
ret := []net.IPAddr{
{IP: net.ParseIP("2001:db8::68")},
{IP: net.IPv4(1, 2, 3, 4)},
{IP: net.IPv4(1, 2, 3, 5)},
}
return ret, nil
}
func MockLookupIPAddrIPv6(_ context.Context, _ string) ([]net.IPAddr, error) {
ret := []net.IPAddr{
{IP: net.ParseIP("2001:db8::68")},
}
return ret, nil
}
func TestResolveAddr(t *testing.T) {
localIP := determineLocalHostIPString(t)
testCases := []struct {
name string
input string
expected string
errStr string
lookup func(ctx context.Context, addr string) ([]net.IPAddr, error)
}{
{
name: "Host by name",
input: "localhost:9080",
expected: fmt.Sprintf("%s:9080", localIP),
errStr: "",
lookup: nil,
},
{
name: "Host by name w/brackets",
input: "[localhost]:9080",
expected: fmt.Sprintf("%s:9080", localIP),
errStr: "",
lookup: nil,
},
{
name: "Host by IPv4",
input: "127.0.0.1:9080",
expected: "127.0.0.1:9080",
errStr: "",
lookup: nil,
},
{
name: "Host by IPv6",
input: "[::1]:9080",
expected: "[::1]:9080",
errStr: "",
lookup: nil,
},
{
name: "Bad IPv4",
input: "127.0.0.1.1:9080",
expected: "",
errStr: "lookup failed for IP address: lookup 127.0.0.1.1: no such host",
lookup: nil,
},
{
name: "Bad IPv6",
input: "[2001:db8::bad::1]:9080",
expected: "",
errStr: "lookup failed for IP address: lookup 2001:db8::bad::1: no such host",
lookup: nil,
},
{
name: "Empty host",
input: "",
expected: "",
errStr: ErrResolveNoAddress.Error(),
lookup: nil,
},
{
name: "IPv6 missing brackets",
input: "2001:db8::20:9080",
expected: "",
errStr: "address 2001:db8::20:9080: too many colons in address",
lookup: nil,
},
{
name: "Colon, but no port",
input: "localhost:",
expected: fmt.Sprintf("%s:", localIP),
errStr: "",
lookup: nil,
},
{
name: "Missing port",
input: "localhost",
expected: "",
errStr: "address localhost: missing port in address",
lookup: nil,
},
{
name: "Missing host",
input: ":9080",
expected: "",
errStr: "lookup failed for IP address: lookup : no such host",
lookup: nil,
},
{
name: "Host by name - non local",
input: "www.foo.com:9080",
expected: "1.2.3.4:9080",
errStr: "",
lookup: MockLookupIPAddr,
},
{
name: "Host by name - non local 0 IPv6 only address",
input: "www.foo.com:9080",
expected: "[2001:db8::68]:9080",
errStr: "",
lookup: MockLookupIPAddrIPv6,
},
}
for _, tc := range testCases {
actual, err := ResolveAddr(tc.input, tc.lookup)
if err != nil {
if tc.errStr == "" {
t.Errorf("[%s] expected success, but saw error: %v", tc.name, err)
} else if err.Error() != tc.errStr {
if strings.Contains(err.Error(), "Temporary failure in name resolution") {
t.Logf("[%s] expected error %q, got %q", tc.name, tc.errStr, err.Error())
continue
}
t.Errorf("[%s] expected error %q, got %q", tc.name, tc.errStr, err.Error())
}
} else {
if tc.errStr != "" {
t.Errorf("[%s] no error seen, but expected failure: %s", tc.name, tc.errStr)
} else if actual != tc.expected {
t.Errorf("[%s] expected address %q, got %q", tc.name, tc.expected, actual)
}
}
}
}
func TestIsIPv6Proxy(t *testing.T) {
tests := []struct {
name string
addrs []string
expected bool
}{
{
name: "ipv4 only",
addrs: []string{"1.1.1.1", "127.0.0.1", "2.2.2.2"},
expected: false,
},
{
name: "ipv6 only",
addrs: []string{"1111:2222::1", "::1", "2222:3333::1"},
expected: true,
},
{
name: "mixed ipv4 and ipv6",
addrs: []string{"1111:2222::1", "::1", "127.0.0.1", "2.2.2.2", "2222:3333::1"},
expected: true,
},
}
for _, tt := range tests {
result := IsIPv6Proxy(tt.addrs)
if result != tt.expected {
t.Errorf("Test %s failed, expected: %t got: %t", tt.name, tt.expected, result)
}
}
}
| pilot/pkg/util/network/ip_test.go | 1 | https://github.com/istio/istio/commit/4542cda6c9973317abeb28a6de4876587c644f23 | [
0.022251561284065247,
0.0023869574069976807,
0.00016124463581945747,
0.000170158629771322,
0.004882922396063805
] |
{
"id": 1,
"code_window": [
"\t\t\t// Should not happen, invalid IP in proxy's IPAddresses slice should have been caught earlier,\n",
"\t\t\t// skip it to prevent a panic.\n",
"\t\t\tcontinue\n",
"\t\t}\n",
"\n",
"\t\t// need to check that a proxy can have an IPv6 address but configuration is not configured K8s for dual-stack support.\n",
"\t\t// In this case an ipv6 link local address will appear, but not one that is routable to with K8s\n",
"\t\tif addr.To4() == nil && addr.To16() != nil && !addr.IsLinkLocalUnicast() {\n",
"\t\t\tresult = true\n",
"\t\t}\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tif addr.To4() != nil {\n",
"\t\t\treturn false\n"
],
"file_path": "pilot/pkg/util/network/ip.go",
"type": "replace",
"edit_start_line_idx": 154
} | Mozilla Public License, version 2.0
1. Definitions
1.1. “Contributor”
means each individual or legal entity that creates, contributes to the
creation of, or owns Covered Software.
1.2. “Contributor Version”
means the combination of the Contributions of others (if any) used by a
Contributor and that particular Contributor’s Contribution.
1.3. “Contribution”
means Covered Software of a particular Contributor.
1.4. “Covered Software”
means Source Code Form to which the initial Contributor has attached the
notice in Exhibit A, the Executable Form of such Source Code Form, and
Modifications of such Source Code Form, in each case including portions
thereof.
1.5. “Incompatible With Secondary Licenses”
means
a. that the initial Contributor has attached the notice described in
Exhibit B to the Covered Software; or
b. that the Covered Software was made available under the terms of version
1.1 or earlier of the License, but not also under the terms of a
Secondary License.
1.6. “Executable Form”
means any form of the work other than Source Code Form.
1.7. “Larger Work”
means a work that combines Covered Software with other material, in a separate
file or files, that is not Covered Software.
1.8. “License”
means this document.
1.9. “Licensable”
means having the right to grant, to the maximum extent possible, whether at the
time of the initial grant or subsequently, any and all of the rights conveyed by
this License.
1.10. “Modifications”
means any of the following:
a. any file in Source Code Form that results from an addition to, deletion
from, or modification of the contents of Covered Software; or
b. any new file in Source Code Form that contains any Covered Software.
1.11. “Patent Claims” of a Contributor
means any patent claim(s), including without limitation, method, process,
and apparatus claims, in any patent Licensable by such Contributor that
would be infringed, but for the grant of the License, by the making,
using, selling, offering for sale, having made, import, or transfer of
either its Contributions or its Contributor Version.
1.12. “Secondary License”
means either the GNU General Public License, Version 2.0, the GNU Lesser
General Public License, Version 2.1, the GNU Affero General Public
License, Version 3.0, or any later versions of those licenses.
1.13. “Source Code Form”
means the form of the work preferred for making modifications.
1.14. “You” (or “Your”)
means an individual or a legal entity exercising rights under this
License. For legal entities, “You” includes any entity that controls, is
controlled by, or is under common control with You. For purposes of this
definition, “control” means (a) the power, direct or indirect, to cause
the direction or management of such entity, whether by contract or
otherwise, or (b) ownership of more than fifty percent (50%) of the
outstanding shares or beneficial ownership of such entity.
2. License Grants and Conditions
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
a. under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or as
part of a Larger Work; and
b. under Patent Claims of such Contributor to make, use, sell, offer for
sale, have made, import, and otherwise transfer either its Contributions
or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution become
effective for each Contribution on the date the Contributor first distributes
such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under this
License. No additional rights or licenses will be implied from the distribution
or licensing of Covered Software under this License. Notwithstanding Section
2.1(b) above, no patent license is granted by a Contributor:
a. for any code that a Contributor has removed from Covered Software; or
b. for infringements caused by: (i) Your and any other third party’s
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
c. under Patent Claims infringed by Covered Software in the absence of its
Contributions.
This License does not grant any rights in the trademarks, service marks, or
logos of any Contributor (except as may be necessary to comply with the
notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this License
(see Section 10.2) or under the terms of a Secondary License (if permitted
under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its Contributions
are its original creation(s) or it has sufficient rights to grant the
rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under applicable
copyright doctrines of fair use, fair dealing, or other equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
Section 2.1.
3. Responsibilities
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under the
terms of this License. You must inform recipients that the Source Code Form
of the Covered Software is governed by the terms of this License, and how
they can obtain a copy of this License. You may not attempt to alter or
restrict the recipients’ rights in the Source Code Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
a. such Covered Software must also be made available in Source Code Form,
as described in Section 3.1, and You must inform recipients of the
Executable Form how they can obtain a copy of such Source Code Form by
reasonable means in a timely manner, at a charge no more than the cost
of distribution to the recipient; and
b. You may distribute such Executable Form under the terms of this License,
or sublicense it under different terms, provided that the license for
the Executable Form does not attempt to limit or alter the recipients’
rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for the
Covered Software. If the Larger Work is a combination of Covered Software
with a work governed by one or more Secondary Licenses, and the Covered
Software is not Incompatible With Secondary Licenses, this License permits
You to additionally distribute such Covered Software under the terms of
such Secondary License(s), so that the recipient of the Larger Work may, at
their option, further distribute the Covered Software under the terms of
either this License or such Secondary License(s).
3.4. Notices
You may not remove or alter the substance of any license notices (including
copyright notices, patent notices, disclaimers of warranty, or limitations
of liability) contained within the Source Code Form of the Covered
Software, except that You may alter any license notices to the extent
required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on behalf
of any Contributor. You must make it absolutely clear that any such
warranty, support, indemnity, or liability obligation is offered by You
alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this License
with respect to some or all of the Covered Software due to statute, judicial
order, or regulation then You must: (a) comply with the terms of this License
to the maximum extent possible; and (b) describe the limitations and the code
they affect. Such description must be placed in a text file included with all
distributions of the Covered Software under this License. Except to the
extent prohibited by statute or regulation, such description must be
sufficiently detailed for a recipient of ordinary skill to be able to
understand it.
5. Termination
5.1. The rights granted under this License will terminate automatically if You
fail to comply with any of its terms. However, if You become compliant,
then the rights granted under this License from a particular Contributor
are reinstated (a) provisionally, unless and until such Contributor
explicitly and finally terminates Your grants, and (b) on an ongoing basis,
if such Contributor fails to notify You of the non-compliance by some
reasonable means prior to 60 days after You have come back into compliance.
Moreover, Your grants from a particular Contributor are reinstated on an
ongoing basis if such Contributor notifies You of the non-compliance by
some reasonable means, this is the first time You have received notice of
non-compliance with this License from such Contributor, and You become
compliant prior to 30 days after Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions, counter-claims,
and cross-claims) alleging that a Contributor Version directly or
indirectly infringes any patent, then the rights granted to You by any and
all Contributors for the Covered Software under Section 2.1 of this License
shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
license agreements (excluding distributors and resellers) which have been
validly granted by You or Your distributors under this License prior to
termination shall survive termination.
6. Disclaimer of Warranty
Covered Software is provided under this License on an “as is” basis, without
warranty of any kind, either expressed, implied, or statutory, including,
without limitation, warranties that the Covered Software is free of defects,
merchantable, fit for a particular purpose or non-infringing. The entire
risk as to the quality and performance of the Covered Software is with You.
Should any Covered Software prove defective in any respect, You (not any
Contributor) assume the cost of any necessary servicing, repair, or
correction. This disclaimer of warranty constitutes an essential part of this
License. No use of any Covered Software is authorized under this License
except under this disclaimer.
7. Limitation of Liability
Under no circumstances and under no legal theory, whether tort (including
negligence), contract, or otherwise, shall any Contributor, or anyone who
distributes Covered Software as permitted above, be liable to You for any
direct, indirect, special, incidental, or consequential damages of any
character including, without limitation, damages for lost profits, loss of
goodwill, work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses, even if such party shall have been
informed of the possibility of such damages. This limitation of liability
shall not apply to liability for death or personal injury resulting from such
party’s negligence to the extent applicable law prohibits such limitation.
Some jurisdictions do not allow the exclusion or limitation of incidental or
consequential damages, so this exclusion and limitation may not apply to You.
8. Litigation
Any litigation relating to this License may be brought only in the courts of
a jurisdiction where the defendant maintains its principal place of business
and such litigation shall be governed by laws of that jurisdiction, without
reference to its conflict-of-law provisions. Nothing in this Section shall
prevent a party’s ability to bring cross-claims or counter-claims.
9. Miscellaneous
This License represents the complete agreement concerning the subject matter
hereof. If any provision of this License is held to be unenforceable, such
provision shall be reformed only to the extent necessary to make it
enforceable. Any law or regulation which provides that the language of a
contract shall be construed against the drafter shall not be used to construe
this License against a Contributor.
10. Versions of the License
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version of
the License under which You originally received the Covered Software, or
under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a modified
version of this License if you rename the license and remove any
references to the name of the license steward (except to note that such
modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular file, then
You may include the notice in a location (such as a LICENSE file in a relevant
directory) where a recipient would be likely to look for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - “Incompatible With Secondary Licenses” Notice
This Source Code Form is “Incompatible
With Secondary Licenses”, as defined by
the Mozilla Public License, v. 2.0.
| licenses/github.com/hashicorp/hcl/LICENSE | 0 | https://github.com/istio/istio/commit/4542cda6c9973317abeb28a6de4876587c644f23 | [
0.00018087661010213196,
0.0001771541137713939,
0.00017292075790464878,
0.00017675112758297473,
0.0000018697210180107504
] |
{
"id": 1,
"code_window": [
"\t\t\t// Should not happen, invalid IP in proxy's IPAddresses slice should have been caught earlier,\n",
"\t\t\t// skip it to prevent a panic.\n",
"\t\t\tcontinue\n",
"\t\t}\n",
"\n",
"\t\t// need to check that a proxy can have an IPv6 address but configuration is not configured K8s for dual-stack support.\n",
"\t\t// In this case an ipv6 link local address will appear, but not one that is routable to with K8s\n",
"\t\tif addr.To4() == nil && addr.To16() != nil && !addr.IsLinkLocalUnicast() {\n",
"\t\t\tresult = true\n",
"\t\t}\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tif addr.To4() != nil {\n",
"\t\t\treturn false\n"
],
"file_path": "pilot/pkg/util/network/ip.go",
"type": "replace",
"edit_start_line_idx": 154
} | // Copyright Istio 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 wasm
import (
"archive/tar"
"compress/gzip"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"path/filepath"
"strings"
"github.com/google/go-containerregistry/pkg/authn"
"github.com/google/go-containerregistry/pkg/name"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/google/go-containerregistry/pkg/v1/types"
"github.com/hashicorp/go-multierror"
)
// This file implements the fetcher of "Wasm Image Specification" compatible container images.
// The spec is here https://github.com/solo-io/wasm/blob/master/spec/README.md.
// Basically, this supports fetching and unpackaging three types of container images containing a Wasm binary.
var errWasmOCIImageDigestMismatch = errors.New("fetched image's digest does not match the expected one")
type ImageFetcherOption struct {
Username string
Password string
// TODO(mathetake) Add signature verification stuff.
Insecure bool
}
func (o *ImageFetcherOption) useDefaultKeyChain() bool {
return o.Username == "" || o.Password == ""
}
type ImageFetcher struct {
fetchOpts []remote.Option
}
func NewImageFetcher(ctx context.Context, opt ImageFetcherOption) *ImageFetcher {
fetchOpts := make([]remote.Option, 0, 2)
// TODO(mathetake): have "Anonymous" option?
if opt.useDefaultKeyChain() {
// Note that default key chain reads the docker config from DOCKER_CONFIG
// so must set the envvar when reaching this branch is expected.
fetchOpts = append(fetchOpts, remote.WithAuthFromKeychain(authn.DefaultKeychain))
} else {
fetchOpts = append(fetchOpts, remote.WithAuth(&authn.Basic{Username: opt.Username}))
}
if opt.Insecure {
t := remote.DefaultTransport.Clone()
t.TLSClientConfig = &tls.Config{
InsecureSkipVerify: opt.Insecure, //nolint: gosec
}
fetchOpts = append(fetchOpts, remote.WithTransport(t))
}
return &ImageFetcher{
fetchOpts: append(fetchOpts, remote.WithContext(ctx)),
}
}
// Fetch is the entrypoint for fetching Wasm binary from Wasm Image Specification compatible images.
func (o *ImageFetcher) Fetch(url, expManifestDigest string) (ret []byte, actualDigest string, err error) {
ref, err := o.parseReference(url)
if err != nil {
err = fmt.Errorf("could not parse url in image reference: %v", err)
return
}
// Fetch image.
img, err := remote.Image(ref, o.fetchOpts...)
if err != nil {
err = fmt.Errorf("could not fetch image: %v", err)
return
}
// Check Manifest's digest if expManifestDigest is not empty.
d, _ := img.Digest()
if expManifestDigest != "" && d.Hex != expManifestDigest {
err = fmt.Errorf("%w: got %s, but want %s", errWasmOCIImageDigestMismatch, d.Hex, expManifestDigest)
return
}
actualDigest = d.Hex
manifest, err := img.Manifest()
if err != nil {
err = fmt.Errorf("could not retrieve manifest: %v", err)
return
}
if manifest.MediaType == types.DockerManifestSchema2 {
// This case, assume we have docker images with "application/vnd.docker.distribution.manifest.v2+json"
// as the manifest media type. Note that the media type of manifest is Docker specific and
// all OCI images would have an empty string in .MediaType field.
ret, err = extractDockerImage(img)
if err != nil {
err = fmt.Errorf("could not extract Wasm file from the image as Docker container %v", err)
return
}
return
}
// We try to parse it as the "compat" variant image with a single "application/vnd.oci.image.layer.v1.tar+gzip" layer.
ret, errCompat := extractOCIStandardImage(img)
if errCompat == nil {
return
}
// Otherwise, we try to parse it as the *oci* variant image with custom artifact media types.
ret, errOCI := extractOCIArtifactImage(img)
if errOCI == nil {
return
}
// We failed to parse the image in any format, so wrap the errors and return.
err = fmt.Errorf("the given image is in invalid format as an OCI image: %v",
multierror.Append(err,
fmt.Errorf("could not parse as compat variant: %v", errCompat),
fmt.Errorf("could not parse as oci variant: %v", errOCI),
),
)
return
}
func (o *ImageFetcher) parseReference(url string) (name.Reference, error) {
ref, err := name.ParseReference(url)
if err != nil {
return nil, err
}
// fallback to http based request, inspired by [helm](https://github.com/helm/helm/blob/12f1bc0acdeb675a8c50a78462ed3917fb7b2e37/pkg/registry/client.go#L594)
// only deal with https fallback instead of attributing all other type of errors to URL parsing error
_, err = remote.Get(ref, o.fetchOpts...)
if err != nil && strings.Contains(err.Error(), "server gave HTTP response") {
wasmLog.Infof("fetch with plain text from %s", url)
return name.ParseReference(url, name.Insecure)
}
return ref, nil
}
// extractDockerImage extracts the Wasm binary from the
// *compat* variant Wasm image with the standard Docker media type: application/vnd.docker.image.rootfs.diff.tar.gzip.
// https://github.com/solo-io/wasm/blob/master/spec/spec-compat.md#specification
func extractDockerImage(img v1.Image) ([]byte, error) {
layers, err := img.Layers()
if err != nil {
return nil, fmt.Errorf("could not fetch layers: %v", err)
}
// The image must be single-layered.
if len(layers) != 1 {
return nil, fmt.Errorf("number of layers must be 1 but got %d", len(layers))
}
layer := layers[0]
mt, err := layer.MediaType()
if err != nil {
return nil, fmt.Errorf("could not get media type: %v", err)
}
// Media type must be application/vnd.docker.image.rootfs.diff.tar.gzip.
if mt != types.DockerLayer {
return nil, fmt.Errorf("invalid media type %s (expect %s)", mt, types.DockerLayer)
}
r, err := layer.Compressed()
if err != nil {
return nil, fmt.Errorf("could not get layer content: %v", err)
}
defer r.Close()
ret, err := extractWasmPluginBinary(r)
if err != nil {
return nil, fmt.Errorf("could not extract wasm binary: %v", err)
}
return ret, nil
}
// extractOCIStandardImage extracts the Wasm binary from the
// *compat* variant Wasm image with the standard OCI media type: application/vnd.oci.image.layer.v1.tar+gzip.
// https://github.com/solo-io/wasm/blob/master/spec/spec-compat.md#specification
func extractOCIStandardImage(img v1.Image) ([]byte, error) {
layers, err := img.Layers()
if err != nil {
return nil, fmt.Errorf("could not fetch layers: %v", err)
}
// The image must be single-layered.
if len(layers) != 1 {
return nil, fmt.Errorf("number of layers must be 1 but got %d", len(layers))
}
layer := layers[0]
mt, err := layer.MediaType()
if err != nil {
return nil, fmt.Errorf("could not get media type: %v", err)
}
// Check if the layer is "application/vnd.oci.image.layer.v1.tar+gzip".
if types.OCILayer != mt {
return nil, fmt.Errorf("invalid media type %s (expect %s)", mt, types.OCILayer)
}
r, err := layer.Compressed()
if err != nil {
return nil, fmt.Errorf("could not get layer content: %v", err)
}
defer r.Close()
ret, err := extractWasmPluginBinary(r)
if err != nil {
return nil, fmt.Errorf("could not extract wasm binary: %v", err)
}
return ret, nil
}
// Extracts the Wasm plugin binary named "plugin.wasm" in a given reader for tar.gz.
// This is only used for *compat* variant.
func extractWasmPluginBinary(r io.Reader) ([]byte, error) {
gr, err := gzip.NewReader(r)
if err != nil {
return nil, fmt.Errorf("failed to parse layer as tar.gz: %v", err)
}
// The target file name for Wasm binary.
// https://github.com/solo-io/wasm/blob/master/spec/spec-compat.md#specification
const wasmPluginFileName = "plugin.wasm"
// Search for the file walking through the archive.
tr := tar.NewReader(gr)
for {
h, err := tr.Next()
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
ret := make([]byte, h.Size)
if filepath.Base(h.Name) == wasmPluginFileName {
_, err := io.ReadFull(tr, ret)
if err != nil {
return nil, fmt.Errorf("failed to read %s: %v", wasmPluginFileName, err)
}
return ret, nil
}
}
return nil, fmt.Errorf("%s not found in the archive", wasmPluginFileName)
}
// extractOCIArtifactImage extracts the Wasm binary from the
// *oci* variant Wasm image: https://github.com/solo-io/wasm/blob/master/spec/spec.md#format
func extractOCIArtifactImage(img v1.Image) ([]byte, error) {
layers, err := img.Layers()
if err != nil {
return nil, fmt.Errorf("could not fetch layers: %v", err)
}
// The image must be two-layered.
if len(layers) != 2 {
return nil, fmt.Errorf("number of layers must be 2 but got %d", len(layers))
}
// The layer type of the Wasm binary itself in *oci* variant.
const wasmLayerMediaType = "application/vnd.module.wasm.content.layer.v1+wasm"
// Find the target layer walking through the layers.
var layer v1.Layer
for _, l := range layers {
mt, err := l.MediaType()
if err != nil {
return nil, fmt.Errorf("could not retrieve the media type: %v", err)
}
if mt == wasmLayerMediaType {
layer = l
break
}
}
if layer == nil {
return nil, fmt.Errorf("could not find the layer of type %s", wasmLayerMediaType)
}
// Somehow go-containerregistry recognizes custom artifact layers as compressed ones,
// while the Solo's Wasm layer is actually uncompressed and therefore
// the content itself is a raw Wasm binary. So using "Uncompressed()" here result in errors
// since internally it tries to umcompress it as gzipped blob.
r, err := layer.Compressed()
if err != nil {
return nil, fmt.Errorf("could not get layer content: %v", err)
}
defer r.Close()
// Just read it since the content is already a raw Wasm binary as mentioned above.
ret, err := io.ReadAll(r)
if err != nil {
return nil, fmt.Errorf("could not extract wasm binary: %v", err)
}
return ret, nil
}
| pkg/wasm/imagefetcher.go | 0 | https://github.com/istio/istio/commit/4542cda6c9973317abeb28a6de4876587c644f23 | [
0.000203429110115394,
0.00017254370322916657,
0.00016681493434589356,
0.00017122685676440597,
0.000006343384029605659
] |
{
"id": 1,
"code_window": [
"\t\t\t// Should not happen, invalid IP in proxy's IPAddresses slice should have been caught earlier,\n",
"\t\t\t// skip it to prevent a panic.\n",
"\t\t\tcontinue\n",
"\t\t}\n",
"\n",
"\t\t// need to check that a proxy can have an IPv6 address but configuration is not configured K8s for dual-stack support.\n",
"\t\t// In this case an ipv6 link local address will appear, but not one that is routable to with K8s\n",
"\t\tif addr.To4() == nil && addr.To16() != nil && !addr.IsLinkLocalUnicast() {\n",
"\t\t\tresult = true\n",
"\t\t}\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tif addr.To4() != nil {\n",
"\t\t\treturn false\n"
],
"file_path": "pilot/pkg/util/network/ip.go",
"type": "replace",
"edit_start_line_idx": 154
} | apiVersion: release-notes/v2
kind: feature
area: networking
releaseNotes:
- |
**Added** authorization of clients when connecting to Istiod over XDS.
| releasenotes/notes/xds-authz.yaml | 0 | https://github.com/istio/istio/commit/4542cda6c9973317abeb28a6de4876587c644f23 | [
0.00017142633441835642,
0.00017142633441835642,
0.00017142633441835642,
0.00017142633441835642,
0
] |
{
"id": 2,
"code_window": [
"\t\t}\n",
"\t}\n",
"\treturn result\n",
"}"
],
"labels": [
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\treturn true\n"
],
"file_path": "pilot/pkg/util/network/ip.go",
"type": "replace",
"edit_start_line_idx": 161
} | // Copyright Istio 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 network
import (
"context"
"fmt"
"net"
"time"
"istio.io/pkg/log"
)
// Network-related utility functions
const (
waitInterval = 100 * time.Millisecond
waitTimeout = 2 * time.Minute
)
type lookupIPAddrType = func(ctx context.Context, addr string) ([]net.IPAddr, error)
// ErrResolveNoAddress error occurs when IP address resolution is attempted,
// but no address was provided.
var ErrResolveNoAddress = fmt.Errorf("no address specified")
// GetPrivateIPs blocks until private IP addresses are available, or a timeout is reached.
func GetPrivateIPs(ctx context.Context) ([]string, bool) {
if _, ok := ctx.Deadline(); !ok {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, waitTimeout)
defer cancel()
}
for {
select {
case <-ctx.Done():
return getPrivateIPsIfAvailable()
default:
addr, ok := getPrivateIPsIfAvailable()
if ok {
return addr, true
}
time.Sleep(waitInterval)
}
}
}
// Returns all the private IP addresses
func getPrivateIPsIfAvailable() ([]string, bool) {
ok := true
ipAddresses := make([]string, 0)
ifaces, _ := net.Interfaces()
for _, iface := range ifaces {
if iface.Flags&net.FlagUp == 0 {
continue // interface down
}
if iface.Flags&net.FlagLoopback != 0 {
continue // loopback interface
}
addrs, _ := iface.Addrs()
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if ip == nil || ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
continue
}
if ip.IsUnspecified() {
ok = false
continue
}
ipAddresses = append(ipAddresses, ip.String())
}
}
return ipAddresses, ok
}
// ResolveAddr resolves an authority address to an IP address. Incoming
// addr can be an IP address or hostname. If addr is an IPv6 address, the IP
// part must be enclosed in square brackets.
//
// LookupIPAddr() may return multiple IP addresses, of which this function returns
// the first IPv4 entry. To use this function in an IPv6 only environment, either
// provide an IPv6 address or ensure the hostname resolves to only IPv6 addresses.
func ResolveAddr(addr string, lookupIPAddr ...lookupIPAddrType) (string, error) {
if addr == "" {
return "", ErrResolveNoAddress
}
host, port, err := net.SplitHostPort(addr)
if err != nil {
return "", err
}
log.Infof("Attempting to lookup address: %s", host)
defer log.Infof("Finished lookup of address: %s", host)
// lookup the udp address with a timeout of 15 seconds.
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
var addrs []net.IPAddr
var lookupErr error
if (len(lookupIPAddr) > 0) && (lookupIPAddr[0] != nil) {
// if there are more than one lookup function, ignore all but first
addrs, lookupErr = lookupIPAddr[0](ctx, host)
} else {
addrs, lookupErr = net.DefaultResolver.LookupIPAddr(ctx, host)
}
if lookupErr != nil || len(addrs) == 0 {
return "", fmt.Errorf("lookup failed for IP address: %w", lookupErr)
}
var resolvedAddr string
for _, address := range addrs {
ip := address.IP
if ip.To4() == nil {
resolvedAddr = fmt.Sprintf("[%s]:%s", ip, port)
} else {
resolvedAddr = fmt.Sprintf("%s:%s", ip, port)
break
}
}
log.Infof("Addr resolved to: %s", resolvedAddr)
return resolvedAddr, nil
}
// IsIPv6Proxy check the addresses slice and returns true for all addresses are valid IPv6 address
// for all other cases it returns false
func IsIPv6Proxy(ipAddrs []string) bool {
result := false
for i := 0; i < len(ipAddrs); i++ {
addr := net.ParseIP(ipAddrs[i])
if addr == nil {
// Should not happen, invalid IP in proxy's IPAddresses slice should have been caught earlier,
// skip it to prevent a panic.
continue
}
// need to check that a proxy can have an IPv6 address but configuration is not configured K8s for dual-stack support.
// In this case an ipv6 link local address will appear, but not one that is routable to with K8s
if addr.To4() == nil && addr.To16() != nil && !addr.IsLinkLocalUnicast() {
result = true
}
}
return result
}
| pilot/pkg/util/network/ip.go | 1 | https://github.com/istio/istio/commit/4542cda6c9973317abeb28a6de4876587c644f23 | [
0.018366284668445587,
0.0015158700989559293,
0.0001645575393922627,
0.00017637173004914075,
0.004279403015971184
] |
{
"id": 2,
"code_window": [
"\t\t}\n",
"\t}\n",
"\treturn result\n",
"}"
],
"labels": [
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\treturn true\n"
],
"file_path": "pilot/pkg/util/network/ip.go",
"type": "replace",
"edit_start_line_idx": 161
} | {
"httpRequest": {
"requestMethod": "GET",
"requestUrl": "http://srv.{{ .EchoNamespace }}.svc.cluster.local/",
"status": 200,
"protocol": "http"
},
"labels": {
"source_app": "clt-{{ .ClusterName }}",
"destination_canonical_service": "srv",
"destination_workload": "srv-v1",
"destination_service_host": "srv.{{ .EchoNamespace }}.svc.cluster.local",
"destination_app": "srv",
"source_canonical_service": "clt-{{ .ClusterName }}",
"destination_principal": "spiffe://{{ .TrustDomain }}/ns/{{ .EchoNamespace }}/sa/default",
"destination_namespace": "{{ .EchoNamespace }}",
"destination_canonical_revision": "v1",
"source_workload": "clt-{{ .ClusterName }}-v1",
"source_namespace": "{{ .EchoNamespace }}",
"destination_service_name": "srv",
"destination_version": "v1",
"log_sampled": "true",
"mesh_uid": "proj-test-mesh",
"protocol": "http",
"requested_server_name": "outbound_.80_._.srv.{{ .EchoNamespace }}.svc.cluster.local",
"response_details": "via_upstream",
"response_flag": "-",
"route_name": "default",
"service_authentication_policy": "MUTUAL_TLS",
"source_version": "v1",
"upstream_cluster": "inbound|8888||",
"source_principal": "spiffe://{{ .TrustDomain }}/ns/{{ .EchoNamespace }}/sa/default",
"source_canonical_revision": "v1",
"dry_run_result": "AuthzDenied"
},
"trace_sampled":true
}
| tests/integration/telemetry/stackdriver/testdata/security_authz_dry_run/server_access_log_deny_no_policy.json.tmpl | 0 | https://github.com/istio/istio/commit/4542cda6c9973317abeb28a6de4876587c644f23 | [
0.00017214458785019815,
0.00017074731294997036,
0.00016894086729735136,
0.00017095188377425075,
0.0000013461298067340977
] |
{
"id": 2,
"code_window": [
"\t\t}\n",
"\t}\n",
"\treturn result\n",
"}"
],
"labels": [
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\treturn true\n"
],
"file_path": "pilot/pkg/util/network/ip.go",
"type": "replace",
"edit_start_line_idx": 161
} | apiVersion: apps/v1
kind: Deployment
metadata:
creationTimestamp: null
name: hello
spec:
replicas: 7
selector:
matchLabels:
app: hello
tier: backend
track: stable
strategy: {}
template:
metadata:
annotations:
prometheus.io/path: /stats/prometheus
prometheus.io/port: "15020"
prometheus.io/scrape: "true"
proxy.istio.io/config: '{ "holdApplicationUntilProxyStarts": false }'
sidecar.istio.io/status: '{"initContainers":["istio-init"],"containers":["istio-proxy"],"volumes":["istio-envoy","istio-data","istio-podinfo","istio-token","istiod-ca-cert"],"imagePullSecrets":null,"revision":"default"}'
creationTimestamp: null
labels:
app: hello
security.istio.io/tlsMode: istio
service.istio.io/canonical-name: hello
service.istio.io/canonical-revision: latest
tier: backend
track: stable
spec:
containers:
- args:
- proxy
- sidecar
- --domain
- $(POD_NAMESPACE).svc.cluster.local
- --proxyLogLevel=warning
- --proxyComponentLogLevel=misc:error
- --log_output_level=default:info
- --concurrency
- "2"
env:
- name: JWT_POLICY
value: third-party-jwt
- name: PILOT_CERT_PROVIDER
value: istiod
- name: CA_ADDR
value: istiod.istio-system.svc:15012
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: INSTANCE_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
- name: SERVICE_ACCOUNT
valueFrom:
fieldRef:
fieldPath: spec.serviceAccountName
- name: HOST_IP
valueFrom:
fieldRef:
fieldPath: status.hostIP
- name: PROXY_CONFIG
value: |
{"holdApplicationUntilProxyStarts":false}
- name: ISTIO_META_POD_PORTS
value: |-
[
{"name":"http","containerPort":80}
,{"name":"http","containerPort":90}
]
- name: ISTIO_META_APP_CONTAINERS
value: hello,world
- name: ISTIO_META_CLUSTER_ID
value: Kubernetes
- name: ISTIO_META_INTERCEPTION_MODE
value: REDIRECT
- name: ISTIO_META_WORKLOAD_NAME
value: hello
- name: ISTIO_META_OWNER
value: kubernetes://apis/apps/v1/namespaces/default/deployments/hello
- name: ISTIO_META_MESH_ID
value: cluster.local
- name: TRUST_DOMAIN
value: cluster.local
- name: ISTIO_KUBE_APP_PROBERS
value: '{"/app-health/hello/livez":{"httpGet":{"port":80}},"/app-health/hello/readyz":{"httpGet":{"port":3333}},"/app-health/world/livez":{"httpGet":{"port":90}}}'
image: gcr.io/istio-testing/proxyv2:latest
lifecycle:
postStart:
exec:
command:
- pilot-agent
- wait
name: istio-proxy
ports:
- containerPort: 15090
name: http-envoy-prom
protocol: TCP
readinessProbe:
failureThreshold: 30
httpGet:
path: /healthz/ready
port: 15021
initialDelaySeconds: 1
periodSeconds: 2
timeoutSeconds: 3
resources:
limits:
cpu: "2"
memory: 1Gi
requests:
cpu: 100m
memory: 128Mi
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
privileged: false
readOnlyRootFilesystem: true
runAsGroup: 1337
runAsNonRoot: true
runAsUser: 1337
volumeMounts:
- mountPath: /var/run/secrets/istio
name: istiod-ca-cert
- mountPath: /var/lib/istio/data
name: istio-data
- mountPath: /etc/istio/proxy
name: istio-envoy
- mountPath: /var/run/secrets/tokens
name: istio-token
- mountPath: /etc/istio/pod
name: istio-podinfo
- image: fake.docker.io/google-samples/hello-go-gke:1.0
livenessProbe:
httpGet:
path: /app-health/hello/livez
port: 15020
name: hello
ports:
- containerPort: 80
name: http
readinessProbe:
httpGet:
path: /app-health/hello/readyz
port: 15020
resources: {}
- image: fake.docker.io/google-samples/hello-go-gke:1.0
livenessProbe:
httpGet:
path: /app-health/world/livez
port: 15020
name: world
ports:
- containerPort: 90
name: http
readinessProbe:
exec:
command:
- cat
- /tmp/healthy
resources: {}
initContainers:
- args:
- istio-iptables
- -p
- "15001"
- -z
- "15006"
- -u
- "1337"
- -m
- REDIRECT
- -i
- '*'
- -x
- ""
- -b
- '*'
- -d
- 15090,15021,15020
image: gcr.io/istio-testing/proxyv2:latest
name: istio-init
resources:
limits:
cpu: "2"
memory: 1Gi
requests:
cpu: 100m
memory: 128Mi
securityContext:
allowPrivilegeEscalation: false
capabilities:
add:
- NET_ADMIN
- NET_RAW
drop:
- ALL
privileged: false
readOnlyRootFilesystem: false
runAsGroup: 0
runAsNonRoot: false
runAsUser: 0
securityContext:
fsGroup: 1337
volumes:
- emptyDir:
medium: Memory
name: istio-envoy
- emptyDir: {}
name: istio-data
- downwardAPI:
items:
- fieldRef:
fieldPath: metadata.labels
path: labels
- fieldRef:
fieldPath: metadata.annotations
path: annotations
name: istio-podinfo
- name: istio-token
projected:
sources:
- serviceAccountToken:
audience: istio-ca
expirationSeconds: 43200
path: istio-token
- configMap:
name: istio-ca-root-cert
name: istiod-ca-cert
status: {}
---
| pkg/kube/inject/testdata/inject/hello-probes-noProxyHoldApplication-ProxyConfig.yaml.injected | 0 | https://github.com/istio/istio/commit/4542cda6c9973317abeb28a6de4876587c644f23 | [
0.0001833066053222865,
0.00017096035298891366,
0.00016567250713706017,
0.0001704189635347575,
0.0000036482958876149496
] |
{
"id": 2,
"code_window": [
"\t\t}\n",
"\t}\n",
"\treturn result\n",
"}"
],
"labels": [
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\treturn true\n"
],
"file_path": "pilot/pkg/util/network/ip.go",
"type": "replace",
"edit_start_line_idx": 161
} | // Copyright Istio 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 processlog
import (
"strings"
"time"
"istio.io/istio/tools/bug-report/pkg/config"
"istio.io/istio/tools/bug-report/pkg/util/match"
)
const (
levelFatal = "fatal"
levelError = "error"
levelWarn = "warn"
levelInfo = "info"
levelDebug = "debug"
levelTrace = "trace"
)
// Stats represents log statistics.
type Stats struct {
numFatals int
numErrors int
numWarnings int
}
// Importance returns an integer that indicates the importance of the log, based on the given Stats in s.
// Larger numbers are more important.
func (s *Stats) Importance() int {
if s == nil {
return 0
}
return 1000*s.numFatals + 100*s.numErrors + 10*s.numWarnings
}
// Process processes logStr based on the supplied config and returns the processed log along with statistics on it.
func Process(config *config.BugReportConfig, logStr string) (string, *Stats) {
out := getTimeRange(logStr, config.StartTime, config.EndTime)
return out, getStats(config, out)
}
// getTimeRange returns the log lines that fall inside the start to end time range, inclusive.
func getTimeRange(logStr string, start, end time.Time) string {
var sb strings.Builder
write := false
for _, l := range strings.Split(logStr, "\n") {
t, _, _, valid := processLogLine(l)
if valid {
write = false
if (t.Equal(start) || t.After(start)) && (t.Equal(end) || t.Before(end)) {
write = true
}
}
if write {
sb.WriteString(l)
sb.WriteString("\n")
}
}
return sb.String()
}
// getStats returns statistics for the given log string.
func getStats(config *config.BugReportConfig, logStr string) *Stats {
out := &Stats{}
for _, l := range strings.Split(logStr, "\n") {
_, level, text, valid := processLogLine(l)
if !valid {
continue
}
switch level {
case levelFatal, levelError, levelWarn:
if match.MatchesGlobs(text, config.IgnoredErrors) {
continue
}
switch level {
case levelFatal:
out.numFatals++
case levelError:
out.numErrors++
case levelWarn:
out.numWarnings++
}
default:
}
}
return out
}
func processLogLine(line string) (timeStamp *time.Time, level string, text string, valid bool) {
lv := strings.Split(line, "\t")
if len(lv) < 3 {
return nil, "", "", false
}
ts, err := time.Parse(time.RFC3339Nano, lv[0])
if err != nil {
return nil, "", "", false
}
timeStamp = &ts
switch lv[1] {
case levelFatal, levelError, levelWarn, levelInfo, levelDebug, levelTrace:
level = lv[1]
default:
return nil, "", "", false
}
text = strings.Join(lv[2:], "\t")
valid = true
return
}
| tools/bug-report/pkg/processlog/processlog.go | 0 | https://github.com/istio/istio/commit/4542cda6c9973317abeb28a6de4876587c644f23 | [
0.000199902307940647,
0.00017674989067018032,
0.00016710101044736803,
0.00017323232896160334,
0.000010777033821796067
] |
{
"id": 3,
"code_window": [
"\t\t{\n",
"\t\t\tname: \"mixed ipv4 and ipv6\",\n",
"\t\t\taddrs: []string{\"1111:2222::1\", \"::1\", \"127.0.0.1\", \"2.2.2.2\", \"2222:3333::1\"},\n",
"\t\t\texpected: true,\n",
"\t\t},\n",
"\t}\n",
"\tfor _, tt := range tests {\n",
"\t\tresult := IsIPv6Proxy(tt.addrs)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\texpected: false,\n"
],
"file_path": "pilot/pkg/util/network/ip_test.go",
"type": "replace",
"edit_start_line_idx": 204
} | // Copyright Istio 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 network
import (
"context"
"fmt"
"net"
"time"
"istio.io/pkg/log"
)
// Network-related utility functions
const (
waitInterval = 100 * time.Millisecond
waitTimeout = 2 * time.Minute
)
type lookupIPAddrType = func(ctx context.Context, addr string) ([]net.IPAddr, error)
// ErrResolveNoAddress error occurs when IP address resolution is attempted,
// but no address was provided.
var ErrResolveNoAddress = fmt.Errorf("no address specified")
// GetPrivateIPs blocks until private IP addresses are available, or a timeout is reached.
func GetPrivateIPs(ctx context.Context) ([]string, bool) {
if _, ok := ctx.Deadline(); !ok {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, waitTimeout)
defer cancel()
}
for {
select {
case <-ctx.Done():
return getPrivateIPsIfAvailable()
default:
addr, ok := getPrivateIPsIfAvailable()
if ok {
return addr, true
}
time.Sleep(waitInterval)
}
}
}
// Returns all the private IP addresses
func getPrivateIPsIfAvailable() ([]string, bool) {
ok := true
ipAddresses := make([]string, 0)
ifaces, _ := net.Interfaces()
for _, iface := range ifaces {
if iface.Flags&net.FlagUp == 0 {
continue // interface down
}
if iface.Flags&net.FlagLoopback != 0 {
continue // loopback interface
}
addrs, _ := iface.Addrs()
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if ip == nil || ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
continue
}
if ip.IsUnspecified() {
ok = false
continue
}
ipAddresses = append(ipAddresses, ip.String())
}
}
return ipAddresses, ok
}
// ResolveAddr resolves an authority address to an IP address. Incoming
// addr can be an IP address or hostname. If addr is an IPv6 address, the IP
// part must be enclosed in square brackets.
//
// LookupIPAddr() may return multiple IP addresses, of which this function returns
// the first IPv4 entry. To use this function in an IPv6 only environment, either
// provide an IPv6 address or ensure the hostname resolves to only IPv6 addresses.
func ResolveAddr(addr string, lookupIPAddr ...lookupIPAddrType) (string, error) {
if addr == "" {
return "", ErrResolveNoAddress
}
host, port, err := net.SplitHostPort(addr)
if err != nil {
return "", err
}
log.Infof("Attempting to lookup address: %s", host)
defer log.Infof("Finished lookup of address: %s", host)
// lookup the udp address with a timeout of 15 seconds.
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
var addrs []net.IPAddr
var lookupErr error
if (len(lookupIPAddr) > 0) && (lookupIPAddr[0] != nil) {
// if there are more than one lookup function, ignore all but first
addrs, lookupErr = lookupIPAddr[0](ctx, host)
} else {
addrs, lookupErr = net.DefaultResolver.LookupIPAddr(ctx, host)
}
if lookupErr != nil || len(addrs) == 0 {
return "", fmt.Errorf("lookup failed for IP address: %w", lookupErr)
}
var resolvedAddr string
for _, address := range addrs {
ip := address.IP
if ip.To4() == nil {
resolvedAddr = fmt.Sprintf("[%s]:%s", ip, port)
} else {
resolvedAddr = fmt.Sprintf("%s:%s", ip, port)
break
}
}
log.Infof("Addr resolved to: %s", resolvedAddr)
return resolvedAddr, nil
}
// IsIPv6Proxy check the addresses slice and returns true for all addresses are valid IPv6 address
// for all other cases it returns false
func IsIPv6Proxy(ipAddrs []string) bool {
result := false
for i := 0; i < len(ipAddrs); i++ {
addr := net.ParseIP(ipAddrs[i])
if addr == nil {
// Should not happen, invalid IP in proxy's IPAddresses slice should have been caught earlier,
// skip it to prevent a panic.
continue
}
// need to check that a proxy can have an IPv6 address but configuration is not configured K8s for dual-stack support.
// In this case an ipv6 link local address will appear, but not one that is routable to with K8s
if addr.To4() == nil && addr.To16() != nil && !addr.IsLinkLocalUnicast() {
result = true
}
}
return result
}
| pilot/pkg/util/network/ip.go | 1 | https://github.com/istio/istio/commit/4542cda6c9973317abeb28a6de4876587c644f23 | [
0.886383056640625,
0.1039307713508606,
0.00016403522749897093,
0.002778808819130063,
0.27209874987602234
] |
{
"id": 3,
"code_window": [
"\t\t{\n",
"\t\t\tname: \"mixed ipv4 and ipv6\",\n",
"\t\t\taddrs: []string{\"1111:2222::1\", \"::1\", \"127.0.0.1\", \"2.2.2.2\", \"2222:3333::1\"},\n",
"\t\t\texpected: true,\n",
"\t\t},\n",
"\t}\n",
"\tfor _, tt := range tests {\n",
"\t\tresult := IsIPv6Proxy(tt.addrs)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\texpected: false,\n"
],
"file_path": "pilot/pkg/util/network/ip_test.go",
"type": "replace",
"edit_start_line_idx": 204
} | {{- if .Values.global.defaultPodDisruptionBudget.enabled }}
{{ $gateway := index .Values "gateways" "istio-ingressgateway" }}
apiVersion: policy/v1beta1
kind: PodDisruptionBudget
metadata:
name: {{ $gateway.name }}
namespace: {{ .Release.Namespace }}
labels:
{{ $gateway.labels | toYaml | trim | indent 4 }}
release: {{ .Release.Name }}
istio.io/rev: {{ .Values.revision | default "default" }}
install.operator.istio.io/owning-resource: {{ .Values.ownerName | default "unknown" }}
operator.istio.io/component: "IngressGateways"
spec:
minAvailable: 1
selector:
matchLabels:
{{ $gateway.labels | toYaml | trim | indent 6 }}
{{- end }}
| manifests/charts/gateways/istio-ingress/templates/poddisruptionbudget.yaml | 0 | https://github.com/istio/istio/commit/4542cda6c9973317abeb28a6de4876587c644f23 | [
0.00017804349772632122,
0.00017294577264692634,
0.00016784804756753147,
0.00017294577264692634,
0.000005097725079394877
] |
{
"id": 3,
"code_window": [
"\t\t{\n",
"\t\t\tname: \"mixed ipv4 and ipv6\",\n",
"\t\t\taddrs: []string{\"1111:2222::1\", \"::1\", \"127.0.0.1\", \"2.2.2.2\", \"2222:3333::1\"},\n",
"\t\t\texpected: true,\n",
"\t\t},\n",
"\t}\n",
"\tfor _, tt := range tests {\n",
"\t\tresult := IsIPv6Proxy(tt.addrs)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\texpected: false,\n"
],
"file_path": "pilot/pkg/util/network/ip_test.go",
"type": "replace",
"edit_start_line_idx": 204
} | // Copyright Istio 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 configdump
import (
"encoding/json"
"fmt"
"reflect"
"sort"
"strings"
"text/tabwriter"
listener "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3"
route "github.com/envoyproxy/go-control-plane/envoy/config/route/v3"
httpConn "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3"
tcp "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/tcp_proxy/v3"
"github.com/envoyproxy/go-control-plane/pkg/wellknown"
"sigs.k8s.io/yaml"
protio "istio.io/istio/istioctl/pkg/util/proto"
"istio.io/istio/pilot/pkg/networking/util"
v3 "istio.io/istio/pilot/pkg/xds/v3"
)
const (
// HTTPListener identifies a listener as being of HTTP type by the presence of an HTTP connection manager filter
HTTPListener = wellknown.HTTPConnectionManager
// TCPListener identifies a listener as being of TCP type by the presence of TCP proxy filter
TCPListener = wellknown.TCPProxy
)
// ListenerFilter is used to pass filter information into listener based config writer print functions
type ListenerFilter struct {
Address string
Port uint32
Type string
Verbose bool
}
// Verify returns true if the passed listener matches the filter fields
func (l *ListenerFilter) Verify(listener *listener.Listener) bool {
if l.Address == "" && l.Port == 0 && l.Type == "" {
return true
}
if l.Address != "" && !strings.EqualFold(retrieveListenerAddress(listener), l.Address) {
return false
}
if l.Port != 0 && retrieveListenerPort(listener) != l.Port {
return false
}
if l.Type != "" && !strings.EqualFold(retrieveListenerType(listener), l.Type) {
return false
}
return true
}
func getFilterChains(l *listener.Listener) []*listener.FilterChain {
res := l.FilterChains
if l.DefaultFilterChain != nil {
res = append(res, l.DefaultFilterChain)
}
return res
}
// retrieveListenerType classifies a Listener as HTTP|TCP|HTTP+TCP|UNKNOWN
func retrieveListenerType(l *listener.Listener) string {
nHTTP := 0
nTCP := 0
for _, filterChain := range getFilterChains(l) {
for _, filter := range filterChain.GetFilters() {
if filter.Name == HTTPListener {
nHTTP++
} else if filter.Name == TCPListener {
if !strings.Contains(string(filter.GetTypedConfig().GetValue()), util.BlackHoleCluster) {
nTCP++
}
}
}
}
if nHTTP > 0 {
if nTCP == 0 {
return "HTTP"
}
return "HTTP+TCP"
} else if nTCP > 0 {
return "TCP"
}
return "UNKNOWN"
}
func retrieveListenerAddress(l *listener.Listener) string {
sockAddr := l.Address.GetSocketAddress()
if sockAddr != nil {
return sockAddr.Address
}
pipe := l.Address.GetPipe()
if pipe != nil {
return pipe.Path
}
return ""
}
func retrieveListenerPort(l *listener.Listener) uint32 {
return l.Address.GetSocketAddress().GetPortValue()
}
// PrintListenerSummary prints a summary of the relevant listeners in the config dump to the ConfigWriter stdout
func (c *ConfigWriter) PrintListenerSummary(filter ListenerFilter) error {
w, listeners, err := c.setupListenerConfigWriter()
if err != nil {
return err
}
verifiedListeners := make([]*listener.Listener, 0, len(listeners))
for _, l := range listeners {
if filter.Verify(l) {
verifiedListeners = append(verifiedListeners, l)
}
}
// Sort by port, addr, type
sort.Slice(verifiedListeners, func(i, j int) bool {
iPort := retrieveListenerPort(verifiedListeners[i])
jPort := retrieveListenerPort(verifiedListeners[j])
if iPort != jPort {
return iPort < jPort
}
iAddr := retrieveListenerAddress(verifiedListeners[i])
jAddr := retrieveListenerAddress(verifiedListeners[j])
if iAddr != jAddr {
return iAddr < jAddr
}
iType := retrieveListenerType(verifiedListeners[i])
jType := retrieveListenerType(verifiedListeners[j])
return iType < jType
})
if filter.Verbose {
fmt.Fprintln(w, "ADDRESS\tPORT\tMATCH\tDESTINATION")
} else {
fmt.Fprintln(w, "ADDRESS\tPORT\tTYPE")
}
for _, l := range verifiedListeners {
address := retrieveListenerAddress(l)
port := retrieveListenerPort(l)
if filter.Verbose {
matches := retrieveListenerMatches(l)
sort.Slice(matches, func(i, j int) bool {
return matches[i].destination > matches[j].destination
})
for _, match := range matches {
fmt.Fprintf(w, "%v\t%v\t%v\t%v\n", address, port, match.match, match.destination)
}
} else {
listenerType := retrieveListenerType(l)
fmt.Fprintf(w, "%v\t%v\t%v\n", address, port, listenerType)
}
}
return w.Flush()
}
type filterchain struct {
match string
destination string
}
var (
plaintextHTTPALPNs = []string{"http/1.0", "http/1.1", "h2c"}
istioHTTPPlaintext = []string{"istio", "istio-http/1.0", "istio-http/1.1", "istio-h2"}
httpTLS = []string{"http/1.0", "http/1.1", "h2c", "istio-http/1.0", "istio-http/1.1", "istio-h2"}
tcpTLS = []string{"istio-peer-exchange", "istio"}
protDescrs = map[string][]string{
"App: HTTP TLS": httpTLS,
"App: Istio HTTP Plain": istioHTTPPlaintext,
"App: TCP TLS": tcpTLS,
"App: HTTP": plaintextHTTPALPNs,
}
)
func retrieveListenerMatches(l *listener.Listener) []filterchain {
fChains := getFilterChains(l)
resp := make([]filterchain, 0, len(fChains))
for _, filterChain := range fChains {
match := filterChain.FilterChainMatch
if match == nil {
match = &listener.FilterChainMatch{}
}
// filterChaince also has SuffixLen, SourceType, SourcePrefixRanges which are not rendered.
descrs := []string{}
if len(match.ServerNames) > 0 {
descrs = append(descrs, fmt.Sprintf("SNI: %s", strings.Join(match.ServerNames, ",")))
}
if len(match.TransportProtocol) > 0 {
descrs = append(descrs, fmt.Sprintf("Trans: %s", match.TransportProtocol))
}
if len(match.ApplicationProtocols) > 0 {
found := false
for protDescr, protocols := range protDescrs {
if reflect.DeepEqual(match.ApplicationProtocols, protocols) {
found = true
descrs = append(descrs, protDescr)
break
}
}
if !found {
descrs = append(descrs, fmt.Sprintf("App: %s", strings.Join(match.ApplicationProtocols, ",")))
}
}
port := ""
if match.DestinationPort != nil {
port = fmt.Sprintf(":%d", match.DestinationPort.GetValue())
}
if len(match.PrefixRanges) > 0 {
pf := []string{}
for _, p := range match.PrefixRanges {
pf = append(pf, fmt.Sprintf("%s/%d", p.AddressPrefix, p.GetPrefixLen().GetValue()))
}
descrs = append(descrs, fmt.Sprintf("Addr: %s%s", strings.Join(pf, ","), port))
} else if port != "" {
descrs = append(descrs, fmt.Sprintf("Addr: *%s", port))
}
if len(descrs) == 0 {
descrs = []string{"ALL"}
}
fc := filterchain{
destination: getFilterType(filterChain.GetFilters()),
match: strings.Join(descrs, "; "),
}
resp = append(resp, fc)
}
return resp
}
func getFilterType(filters []*listener.Filter) string {
for _, filter := range filters {
if filter.Name == HTTPListener {
httpProxy := &httpConn.HttpConnectionManager{}
// Allow Unmarshal to work even if Envoy and istioctl are different
filter.GetTypedConfig().TypeUrl = "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager"
err := filter.GetTypedConfig().UnmarshalTo(httpProxy)
if err != nil {
return err.Error()
}
if httpProxy.GetRouteConfig() != nil {
return describeRouteConfig(httpProxy.GetRouteConfig())
}
if httpProxy.GetRds().GetRouteConfigName() != "" {
return fmt.Sprintf("Route: %s", httpProxy.GetRds().GetRouteConfigName())
}
return "HTTP"
} else if filter.Name == TCPListener {
if !strings.Contains(string(filter.GetTypedConfig().GetValue()), util.BlackHoleCluster) {
tcpProxy := &tcp.TcpProxy{}
// Allow Unmarshal to work even if Envoy and istioctl are different
filter.GetTypedConfig().TypeUrl = "type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy"
err := filter.GetTypedConfig().UnmarshalTo(tcpProxy)
if err != nil {
return err.Error()
}
if strings.Contains(tcpProxy.GetCluster(), "Cluster") {
return tcpProxy.GetCluster()
}
return fmt.Sprintf("Cluster: %s", tcpProxy.GetCluster())
}
}
}
return "Non-HTTP/Non-TCP"
}
func describeRouteConfig(route *route.RouteConfiguration) string {
if cluster := getMatchAllCluster(route); cluster != "" {
return cluster
}
vhosts := []string{}
for _, vh := range route.GetVirtualHosts() {
if describeDomains(vh) == "" {
vhosts = append(vhosts, describeRoutes(vh))
} else {
vhosts = append(vhosts, fmt.Sprintf("%s %s", describeDomains(vh), describeRoutes(vh)))
}
}
return fmt.Sprintf("Inline Route: %s", strings.Join(vhosts, "; "))
}
// If this is a route that matches everything and forwards to a cluster, just report the cluster.
func getMatchAllCluster(er *route.RouteConfiguration) string {
if len(er.GetVirtualHosts()) != 1 {
return ""
}
vh := er.GetVirtualHosts()[0]
if !reflect.DeepEqual(vh.Domains, []string{"*"}) {
return ""
}
if len(vh.GetRoutes()) != 1 {
return ""
}
r := vh.GetRoutes()[0]
if r.GetMatch().GetPrefix() != "/" {
return ""
}
a, ok := r.GetAction().(*route.Route_Route)
if !ok {
return ""
}
cl, ok := a.Route.ClusterSpecifier.(*route.RouteAction_Cluster)
if !ok {
return ""
}
if strings.Contains(cl.Cluster, "Cluster") {
return cl.Cluster
}
return fmt.Sprintf("Cluster: %s", cl.Cluster)
}
func describeDomains(vh *route.VirtualHost) string {
if len(vh.GetDomains()) == 1 && vh.GetDomains()[0] == "*" {
return ""
}
return strings.Join(vh.GetDomains(), "/")
}
func describeRoutes(vh *route.VirtualHost) string {
routes := make([]string, 0, len(vh.GetRoutes()))
for _, route := range vh.GetRoutes() {
routes = append(routes, describeMatch(route.GetMatch()))
}
return strings.Join(routes, ", ")
}
func describeMatch(match *route.RouteMatch) string {
conds := []string{}
if match.GetPrefix() != "" {
conds = append(conds, fmt.Sprintf("%s*", match.GetPrefix()))
}
if match.GetPath() != "" {
conds = append(conds, match.GetPath())
}
if match.GetSafeRegex() != nil {
conds = append(conds, fmt.Sprintf("regex %s", match.GetSafeRegex().Regex))
}
// Ignore headers
return strings.Join(conds, " ")
}
// PrintListenerDump prints the relevant listeners in the config dump to the ConfigWriter stdout
func (c *ConfigWriter) PrintListenerDump(filter ListenerFilter, outputFormat string) error {
_, listeners, err := c.setupListenerConfigWriter()
if err != nil {
return err
}
filteredListeners := protio.MessageSlice{}
for _, listener := range listeners {
if filter.Verify(listener) {
filteredListeners = append(filteredListeners, listener)
}
}
out, err := json.MarshalIndent(filteredListeners, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal listeners: %v", err)
}
if outputFormat == "yaml" {
if out, err = yaml.JSONToYAML(out); err != nil {
return err
}
}
fmt.Fprintln(c.Stdout, string(out))
return nil
}
func (c *ConfigWriter) setupListenerConfigWriter() (*tabwriter.Writer, []*listener.Listener, error) {
listeners, err := c.retrieveSortedListenerSlice()
if err != nil {
return nil, nil, err
}
w := new(tabwriter.Writer).Init(c.Stdout, 0, 8, 1, ' ', 0)
return w, listeners, nil
}
func (c *ConfigWriter) retrieveSortedListenerSlice() ([]*listener.Listener, error) {
if c.configDump == nil {
return nil, fmt.Errorf("config writer has not been primed")
}
listenerDump, err := c.configDump.GetListenerConfigDump()
if err != nil {
return nil, fmt.Errorf("listener dump: %v", err)
}
listeners := make([]*listener.Listener, 0)
for _, l := range listenerDump.DynamicListeners {
if l.ActiveState != nil && l.ActiveState.Listener != nil {
listenerTyped := &listener.Listener{}
// Support v2 or v3 in config dump. See ads.go:RequestedTypes for more info.
l.ActiveState.Listener.TypeUrl = v3.ListenerType
err = l.ActiveState.Listener.UnmarshalTo(listenerTyped)
if err != nil {
return nil, fmt.Errorf("unmarshal listener: %v", err)
}
listeners = append(listeners, listenerTyped)
}
}
for _, l := range listenerDump.StaticListeners {
if l.Listener != nil {
listenerTyped := &listener.Listener{}
// Support v2 or v3 in config dump. See ads.go:RequestedTypes for more info.
l.Listener.TypeUrl = v3.ListenerType
err = l.Listener.UnmarshalTo(listenerTyped)
if err != nil {
return nil, fmt.Errorf("unmarshal listener: %v", err)
}
listeners = append(listeners, listenerTyped)
}
}
if len(listeners) == 0 {
return nil, fmt.Errorf("no listeners found")
}
return listeners, nil
}
| istioctl/pkg/writer/envoy/configdump/listener.go | 0 | https://github.com/istio/istio/commit/4542cda6c9973317abeb28a6de4876587c644f23 | [
0.15683233737945557,
0.004373274277895689,
0.0001632159692235291,
0.00017438866780139506,
0.02333594672381878
] |
{
"id": 3,
"code_window": [
"\t\t{\n",
"\t\t\tname: \"mixed ipv4 and ipv6\",\n",
"\t\t\taddrs: []string{\"1111:2222::1\", \"::1\", \"127.0.0.1\", \"2.2.2.2\", \"2222:3333::1\"},\n",
"\t\t\texpected: true,\n",
"\t\t},\n",
"\t}\n",
"\tfor _, tt := range tests {\n",
"\t\tresult := IsIPv6Proxy(tt.addrs)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\texpected: false,\n"
],
"file_path": "pilot/pkg/util/network/ip_test.go",
"type": "replace",
"edit_start_line_idx": 204
} | apiVersion: release-notes/v2
kind: bug-fix
area: telemetry
issue: [34395]
releaseNotes:
- |
**Fixed** an issue with WorkloadGroup and WorkloadEntry labeling of canonical revision.
| releasenotes/notes/fix-workload-group-labels.yaml | 0 | https://github.com/istio/istio/commit/4542cda6c9973317abeb28a6de4876587c644f23 | [
0.000172652376932092,
0.000172652376932092,
0.000172652376932092,
0.000172652376932092,
0
] |
{
"id": 0,
"code_window": [
"\t\t\t dir1 arg1\n",
"\t\t\t dir2 arg2 arg3\n",
"\t\t\t dir3`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\tif val := d.Val(); val != \"\" {\n",
"\t\tt.Fatalf(\"Val(): Should return empty string when no token loaded; got '%s'\", val)\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 29
} | // Copyright 2015 Matthew Holt and The Caddy 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 caddyfile
import (
"io"
"log"
"reflect"
"strings"
"testing"
)
func TestDispenser_Val_Next(t *testing.T) {
input := `host:port
dir1 arg1
dir2 arg2 arg3
dir3`
d := newTestDispenser(input)
if val := d.Val(); val != "" {
t.Fatalf("Val(): Should return empty string when no token loaded; got '%s'", val)
}
assertNext := func(shouldLoad bool, expectedCursor int, expectedVal string) {
if loaded := d.Next(); loaded != shouldLoad {
t.Errorf("Next(): Expected %v but got %v instead (val '%s')", shouldLoad, loaded, d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("Expected cursor to be %d, but was %d", expectedCursor, d.cursor)
}
if d.nesting != 0 {
t.Errorf("Nesting should be 0, was %d instead", d.nesting)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNext(true, 0, "host:port")
assertNext(true, 1, "dir1")
assertNext(true, 2, "arg1")
assertNext(true, 3, "dir2")
assertNext(true, 4, "arg2")
assertNext(true, 5, "arg3")
assertNext(true, 6, "dir3")
// Note: This next test simply asserts existing behavior.
// If desired, we may wish to empty the token value after
// reading past the EOF. Open an issue if you want this change.
assertNext(false, 6, "dir3")
}
func TestDispenser_NextArg(t *testing.T) {
input := `dir1 arg1
dir2 arg2 arg3
dir3`
d := newTestDispenser(input)
assertNext := func(shouldLoad bool, expectedVal string, expectedCursor int) {
if d.Next() != shouldLoad {
t.Errorf("Next(): Should load token but got false instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("Next(): Expected cursor to be at %d, but it was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNextArg := func(expectedVal string, loadAnother bool, expectedCursor int) {
if !d.NextArg() {
t.Error("NextArg(): Should load next argument but got false instead")
}
if d.cursor != expectedCursor {
t.Errorf("NextArg(): Expected cursor to be at %d, but it was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
if !loadAnother {
if d.NextArg() {
t.Fatalf("NextArg(): Should NOT load another argument, but got true instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("NextArg(): Expected cursor to remain at %d, but it was %d", expectedCursor, d.cursor)
}
}
}
assertNext(true, "dir1", 0)
assertNextArg("arg1", false, 1)
assertNext(true, "dir2", 2)
assertNextArg("arg2", true, 3)
assertNextArg("arg3", false, 4)
assertNext(true, "dir3", 5)
assertNext(false, "dir3", 5)
}
func TestDispenser_NextLine(t *testing.T) {
input := `host:port
dir1 arg1
dir2 arg2 arg3`
d := newTestDispenser(input)
assertNextLine := func(shouldLoad bool, expectedVal string, expectedCursor int) {
if d.NextLine() != shouldLoad {
t.Errorf("NextLine(): Should load token but got false instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("NextLine(): Expected cursor to be %d, instead was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNextLine(true, "host:port", 0)
assertNextLine(true, "dir1", 1)
assertNextLine(false, "dir1", 1)
d.Next() // arg1
assertNextLine(true, "dir2", 3)
assertNextLine(false, "dir2", 3)
d.Next() // arg2
assertNextLine(false, "arg2", 4)
d.Next() // arg3
assertNextLine(false, "arg3", 5)
}
func TestDispenser_NextBlock(t *testing.T) {
input := `foobar1 {
sub1 arg1
sub2
}
foobar2 {
}`
d := newTestDispenser(input)
assertNextBlock := func(shouldLoad bool, expectedCursor, expectedNesting int) {
if loaded := d.NextBlock(0); loaded != shouldLoad {
t.Errorf("NextBlock(): Should return %v but got %v", shouldLoad, loaded)
}
if d.cursor != expectedCursor {
t.Errorf("NextBlock(): Expected cursor to be %d, was %d", expectedCursor, d.cursor)
}
if d.nesting != expectedNesting {
t.Errorf("NextBlock(): Nesting should be %d, not %d", expectedNesting, d.nesting)
}
}
assertNextBlock(false, -1, 0)
d.Next() // foobar1
assertNextBlock(true, 2, 1)
assertNextBlock(true, 3, 1)
assertNextBlock(true, 4, 1)
assertNextBlock(false, 5, 0)
d.Next() // foobar2
assertNextBlock(false, 8, 0) // empty block is as if it didn't exist
}
func TestDispenser_Args(t *testing.T) {
var s1, s2, s3 string
input := `dir1 arg1 arg2 arg3
dir2 arg4 arg5
dir3 arg6 arg7
dir4`
d := newTestDispenser(input)
d.Next() // dir1
// As many strings as arguments
if all := d.Args(&s1, &s2, &s3); !all {
t.Error("Args(): Expected true, got false")
}
if s1 != "arg1" {
t.Errorf("Args(): Expected s1 to be 'arg1', got '%s'", s1)
}
if s2 != "arg2" {
t.Errorf("Args(): Expected s2 to be 'arg2', got '%s'", s2)
}
if s3 != "arg3" {
t.Errorf("Args(): Expected s3 to be 'arg3', got '%s'", s3)
}
d.Next() // dir2
// More strings than arguments
if all := d.Args(&s1, &s2, &s3); all {
t.Error("Args(): Expected false, got true")
}
if s1 != "arg4" {
t.Errorf("Args(): Expected s1 to be 'arg4', got '%s'", s1)
}
if s2 != "arg5" {
t.Errorf("Args(): Expected s2 to be 'arg5', got '%s'", s2)
}
if s3 != "arg3" {
t.Errorf("Args(): Expected s3 to be unchanged ('arg3'), instead got '%s'", s3)
}
// (quick cursor check just for kicks and giggles)
if d.cursor != 6 {
t.Errorf("Cursor should be 6, but is %d", d.cursor)
}
d.Next() // dir3
// More arguments than strings
if all := d.Args(&s1); !all {
t.Error("Args(): Expected true, got false")
}
if s1 != "arg6" {
t.Errorf("Args(): Expected s1 to be 'arg6', got '%s'", s1)
}
d.Next() // dir4
// No arguments or strings
if all := d.Args(); !all {
t.Error("Args(): Expected true, got false")
}
// No arguments but at least one string
if all := d.Args(&s1); all {
t.Error("Args(): Expected false, got true")
}
}
func TestDispenser_RemainingArgs(t *testing.T) {
input := `dir1 arg1 arg2 arg3
dir2 arg4 arg5
dir3 arg6 { arg7
dir4`
d := newTestDispenser(input)
d.Next() // dir1
args := d.RemainingArgs()
if expected := []string{"arg1", "arg2", "arg3"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // dir2
args = d.RemainingArgs()
if expected := []string{"arg4", "arg5"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // dir3
args = d.RemainingArgs()
if expected := []string{"arg6"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // {
d.Next() // arg7
d.Next() // dir4
args = d.RemainingArgs()
if len(args) != 0 {
t.Errorf("RemainingArgs(): Expected %v, got %v", []string{}, args)
}
}
func TestDispenser_ArgErr_Err(t *testing.T) {
input := `dir1 {
}
dir2 arg1 arg2`
d := newTestDispenser(input)
d.cursor = 1 // {
if err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), "{") {
t.Errorf("ArgErr(): Expected an error message with { in it, but got '%v'", err)
}
d.cursor = 5 // arg2
if err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), "arg2") {
t.Errorf("ArgErr(): Expected an error message with 'arg2' in it; got '%v'", err)
}
err := d.Err("foobar")
if err == nil {
t.Fatalf("Err(): Expected an error, got nil")
}
if !strings.Contains(err.Error(), "Testfile:3") {
t.Errorf("Expected error message with filename:line in it; got '%v'", err)
}
if !strings.Contains(err.Error(), "foobar") {
t.Errorf("Expected error message with custom message in it ('foobar'); got '%v'", err)
}
}
func newTestDispenser(input string) *Dispenser {
tokens, err := allTokens("Testfile", []byte(input))
if err != nil && err != io.EOF {
log.Fatalf("getting all tokens from input: %v", err)
}
return NewDispenser(tokens)
}
| caddyconfig/caddyfile/dispenser_test.go | 1 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.9982616305351257,
0.6039419174194336,
0.0001696249091764912,
0.9566398859024048,
0.4445126950740814
] |
{
"id": 0,
"code_window": [
"\t\t\t dir1 arg1\n",
"\t\t\t dir2 arg2 arg3\n",
"\t\t\t dir3`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\tif val := d.Val(); val != \"\" {\n",
"\t\tt.Fatalf(\"Val(): Should return empty string when no token loaded; got '%s'\", val)\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 29
} | // Copyright 2015 Light Code Labs, LLC
//
// 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 caddyfile
import (
"log"
"strings"
"testing"
)
type lexerTestCase struct {
input string
expected []Token
}
func TestLexer(t *testing.T) {
testCases := []lexerTestCase{
{
input: `host:123`,
expected: []Token{
{Line: 1, Text: "host:123"},
},
},
{
input: `host:123
directive`,
expected: []Token{
{Line: 1, Text: "host:123"},
{Line: 3, Text: "directive"},
},
},
{
input: `host:123 {
directive
}`,
expected: []Token{
{Line: 1, Text: "host:123"},
{Line: 1, Text: "{"},
{Line: 2, Text: "directive"},
{Line: 3, Text: "}"},
},
},
{
input: `host:123 { directive }`,
expected: []Token{
{Line: 1, Text: "host:123"},
{Line: 1, Text: "{"},
{Line: 1, Text: "directive"},
{Line: 1, Text: "}"},
},
},
{
input: `host:123 {
#comment
directive
# comment
foobar # another comment
}`,
expected: []Token{
{Line: 1, Text: "host:123"},
{Line: 1, Text: "{"},
{Line: 3, Text: "directive"},
{Line: 5, Text: "foobar"},
{Line: 6, Text: "}"},
},
},
{
input: `a "quoted value" b
foobar`,
expected: []Token{
{Line: 1, Text: "a"},
{Line: 1, Text: "quoted value"},
{Line: 1, Text: "b"},
{Line: 2, Text: "foobar"},
},
},
{
input: `A "quoted \"value\" inside" B`,
expected: []Token{
{Line: 1, Text: "A"},
{Line: 1, Text: `quoted "value" inside`},
{Line: 1, Text: "B"},
},
},
{
input: "An escaped \"newline\\\ninside\" quotes",
expected: []Token{
{Line: 1, Text: "An"},
{Line: 1, Text: "escaped"},
{Line: 1, Text: "newline\\\ninside"},
{Line: 2, Text: "quotes"},
},
},
{
input: "An escaped newline\\\noutside quotes",
expected: []Token{
{Line: 1, Text: "An"},
{Line: 1, Text: "escaped"},
{Line: 1, Text: "newline"},
{Line: 1, Text: "outside"},
{Line: 1, Text: "quotes"},
},
},
{
input: "line1\\\nescaped\nline2\nline3",
expected: []Token{
{Line: 1, Text: "line1"},
{Line: 1, Text: "escaped"},
{Line: 3, Text: "line2"},
{Line: 4, Text: "line3"},
},
},
{
input: "line1\\\nescaped1\\\nescaped2\nline4\nline5",
expected: []Token{
{Line: 1, Text: "line1"},
{Line: 1, Text: "escaped1"},
{Line: 1, Text: "escaped2"},
{Line: 4, Text: "line4"},
{Line: 5, Text: "line5"},
},
},
{
input: `"unescapable\ in quotes"`,
expected: []Token{
{Line: 1, Text: `unescapable\ in quotes`},
},
},
{
input: `"don't\escape"`,
expected: []Token{
{Line: 1, Text: `don't\escape`},
},
},
{
input: `"don't\\escape"`,
expected: []Token{
{Line: 1, Text: `don't\\escape`},
},
},
{
input: `un\escapable`,
expected: []Token{
{Line: 1, Text: `un\escapable`},
},
},
{
input: `A "quoted value with line
break inside" {
foobar
}`,
expected: []Token{
{Line: 1, Text: "A"},
{Line: 1, Text: "quoted value with line\n\t\t\t\t\tbreak inside"},
{Line: 2, Text: "{"},
{Line: 3, Text: "foobar"},
{Line: 4, Text: "}"},
},
},
{
input: `"C:\php\php-cgi.exe"`,
expected: []Token{
{Line: 1, Text: `C:\php\php-cgi.exe`},
},
},
{
input: `empty "" string`,
expected: []Token{
{Line: 1, Text: `empty`},
{Line: 1, Text: ``},
{Line: 1, Text: `string`},
},
},
{
input: "skip those\r\nCR characters",
expected: []Token{
{Line: 1, Text: "skip"},
{Line: 1, Text: "those"},
{Line: 2, Text: "CR"},
{Line: 2, Text: "characters"},
},
},
{
input: "\xEF\xBB\xBF:8080", // test with leading byte order mark
expected: []Token{
{Line: 1, Text: ":8080"},
},
},
}
for i, testCase := range testCases {
actual := tokenize(testCase.input)
lexerCompare(t, i, testCase.expected, actual)
}
}
func tokenize(input string) (tokens []Token) {
l := lexer{}
if err := l.load(strings.NewReader(input)); err != nil {
log.Printf("[ERROR] load failed: %v", err)
}
for l.next() {
tokens = append(tokens, l.token)
}
return
}
func lexerCompare(t *testing.T, n int, expected, actual []Token) {
if len(expected) != len(actual) {
t.Errorf("Test case %d: expected %d token(s) but got %d", n, len(expected), len(actual))
}
for i := 0; i < len(actual) && i < len(expected); i++ {
if actual[i].Line != expected[i].Line {
t.Errorf("Test case %d token %d ('%s'): expected line %d but was line %d",
n, i, expected[i].Text, expected[i].Line, actual[i].Line)
break
}
if actual[i].Text != expected[i].Text {
t.Errorf("Test case %d token %d: expected text '%s' but was '%s'",
n, i, expected[i].Text, actual[i].Text)
break
}
}
}
| caddyconfig/caddyfile/lexer_test.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.0037381877191364765,
0.0003489418886601925,
0.000163783595780842,
0.00017041616956703365,
0.0007123856921680272
] |
{
"id": 0,
"code_window": [
"\t\t\t dir1 arg1\n",
"\t\t\t dir2 arg2 arg3\n",
"\t\t\t dir3`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\tif val := d.Val(); val != \"\" {\n",
"\t\tt.Fatalf(\"Val(): Should return empty string when no token loaded; got '%s'\", val)\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 29
} | glob2.host0 {
dir2 arg1
}
| caddyconfig/caddyfile/testdata/import_glob2.txt | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.0009544588392600417,
0.0009544588392600417,
0.0009544588392600417,
0.0009544588392600417,
0
] |
{
"id": 0,
"code_window": [
"\t\t\t dir1 arg1\n",
"\t\t\t dir2 arg2 arg3\n",
"\t\t\t dir3`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\tif val := d.Val(); val != \"\" {\n",
"\t\tt.Fatalf(\"Val(): Should return empty string when no token loaded; got '%s'\", val)\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 29
} | // Copyright 2015 Matthew Holt and The Caddy 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 caddytls
import (
"crypto/rand"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"sync"
"time"
"github.com/caddyserver/caddy/v2"
)
// SessionTicketService configures and manages TLS session tickets.
type SessionTicketService struct {
// KeySource is the method by which Caddy produces or obtains
// TLS session ticket keys (STEKs). By default, Caddy generates
// them internally using a secure pseudorandom source.
KeySource json.RawMessage `json:"key_source,omitempty" caddy:"namespace=tls.stek inline_key=provider"`
// How often Caddy rotates STEKs. Default: 12h.
RotationInterval caddy.Duration `json:"rotation_interval,omitempty"`
// The maximum number of keys to keep in rotation. Default: 4.
MaxKeys int `json:"max_keys,omitempty"`
// Disables STEK rotation.
DisableRotation bool `json:"disable_rotation,omitempty"`
// Disables TLS session resumption by tickets.
Disabled bool `json:"disabled,omitempty"`
keySource STEKProvider
configs map[*tls.Config]struct{}
stopChan chan struct{}
currentKeys [][32]byte
mu *sync.Mutex
}
func (s *SessionTicketService) provision(ctx caddy.Context) error {
s.configs = make(map[*tls.Config]struct{})
s.mu = new(sync.Mutex)
// establish sane defaults
if s.RotationInterval == 0 {
s.RotationInterval = caddy.Duration(defaultSTEKRotationInterval)
}
if s.MaxKeys <= 0 {
s.MaxKeys = defaultMaxSTEKs
}
if s.KeySource == nil {
s.KeySource = json.RawMessage(`{"provider":"standard"}`)
}
// load the STEK module, which will provide keys
val, err := ctx.LoadModule(s, "KeySource")
if err != nil {
return fmt.Errorf("loading TLS session ticket ephemeral keys provider module: %s", err)
}
s.keySource = val.(STEKProvider)
// if session tickets or just rotation are
// disabled, no need to start service
if s.Disabled || s.DisableRotation {
return nil
}
// start the STEK module; this ensures we have
// a starting key before any config needs one
return s.start()
}
// start loads the starting STEKs and spawns a goroutine
// which loops to rotate the STEKs, which continues until
// stop() is called. If start() was already called, this
// is a no-op.
func (s *SessionTicketService) start() error {
if s.stopChan != nil {
return nil
}
s.stopChan = make(chan struct{})
// initializing the key source gives us our
// initial key(s) to start with; if successful,
// we need to be sure to call Next() so that
// the key source can know when it is done
initialKeys, err := s.keySource.Initialize(s)
if err != nil {
return fmt.Errorf("setting STEK module configuration: %v", err)
}
s.mu.Lock()
s.currentKeys = initialKeys
s.mu.Unlock()
// keep the keys rotated
go s.stayUpdated()
return nil
}
// stayUpdated is a blocking function which rotates
// the keys whenever new ones are sent. It reads
// from keysChan until s.stop() is called.
func (s *SessionTicketService) stayUpdated() {
// this call is essential when Initialize()
// returns without error, because the stop
// channel is the only way the key source
// will know when to clean up
keysChan := s.keySource.Next(s.stopChan)
for {
select {
case newKeys := <-keysChan:
s.mu.Lock()
s.currentKeys = newKeys
configs := s.configs
s.mu.Unlock()
for cfg := range configs {
cfg.SetSessionTicketKeys(newKeys)
}
case <-s.stopChan:
return
}
}
}
// stop terminates the key rotation goroutine.
func (s *SessionTicketService) stop() {
if s.stopChan != nil {
close(s.stopChan)
}
}
// register sets the session ticket keys on cfg
// and keeps them updated. Any values registered
// must be unregistered, or they will not be
// garbage-collected. s.start() must have been
// called first. If session tickets are disabled
// or if ticket key rotation is disabled, this
// function is a no-op.
func (s *SessionTicketService) register(cfg *tls.Config) {
if s.Disabled || s.DisableRotation {
return
}
s.mu.Lock()
cfg.SetSessionTicketKeys(s.currentKeys)
s.configs[cfg] = struct{}{}
s.mu.Unlock()
}
// unregister stops session key management on cfg and
// removes the internal stored reference to cfg. If
// session tickets are disabled or if ticket key rotation
// is disabled, this function is a no-op.
func (s *SessionTicketService) unregister(cfg *tls.Config) {
if s.Disabled || s.DisableRotation {
return
}
s.mu.Lock()
delete(s.configs, cfg)
s.mu.Unlock()
}
// RotateSTEKs rotates the keys in keys by producing a new key and eliding
// the oldest one. The new slice of keys is returned.
func (s SessionTicketService) RotateSTEKs(keys [][32]byte) ([][32]byte, error) {
// produce a new key
newKey, err := s.generateSTEK()
if err != nil {
return nil, fmt.Errorf("generating STEK: %v", err)
}
// we need to prepend this new key to the list of
// keys so that it is preferred, but we need to be
// careful that we do not grow the slice larger
// than MaxKeys, otherwise we'll be storing one
// more key in memory than we expect; so be sure
// that the slice does not grow beyond the limit
// even for a brief period of time, since there's
// no guarantee when that extra allocation will
// be overwritten; this is why we first trim the
// length to one less the max, THEN prepend the
// new key
if len(keys) >= s.MaxKeys {
keys[len(keys)-1] = [32]byte{} // zero-out memory of oldest key
keys = keys[:s.MaxKeys-1] // trim length of slice
}
keys = append([][32]byte{newKey}, keys...) // prepend new key
return keys, nil
}
// generateSTEK generates key material suitable for use as a
// session ticket ephemeral key.
func (s *SessionTicketService) generateSTEK() ([32]byte, error) {
var newTicketKey [32]byte
_, err := io.ReadFull(rand.Reader, newTicketKey[:])
return newTicketKey, err
}
// STEKProvider is a type that can provide session ticket ephemeral
// keys (STEKs).
type STEKProvider interface {
// Initialize provides the STEK configuration to the STEK
// module so that it can obtain and manage keys accordingly.
// It returns the initial key(s) to use. Implementations can
// rely on Next() being called if Initialize() returns
// without error, so that it may know when it is done.
Initialize(config *SessionTicketService) ([][32]byte, error)
// Next returns the channel through which the next session
// ticket keys will be transmitted until doneChan is closed.
// Keys should be sent on keysChan as they are updated.
// When doneChan is closed, any resources allocated in
// Initialize() must be cleaned up.
Next(doneChan <-chan struct{}) (keysChan <-chan [][32]byte)
}
const (
defaultSTEKRotationInterval = 12 * time.Hour
defaultMaxSTEKs = 4
)
| modules/caddytls/sessiontickets.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.0010390556417405605,
0.0002090233756462112,
0.00016246337327174842,
0.00017389332060702145,
0.00017313820717390627
] |
{
"id": 1,
"code_window": [
"\tinput := `dir1 arg1\n",
"\t\t\t dir2 arg2 arg3\n",
"\t\t\t dir3`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\tassertNext := func(shouldLoad bool, expectedVal string, expectedCursor int) {\n",
"\t\tif d.Next() != shouldLoad {\n",
"\t\t\tt.Errorf(\"Next(): Should load token but got false instead (val: '%s')\", d.Val())\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 67
} | // Copyright 2015 Matthew Holt and The Caddy 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 caddyfile
import (
"io"
"log"
"reflect"
"strings"
"testing"
)
func TestDispenser_Val_Next(t *testing.T) {
input := `host:port
dir1 arg1
dir2 arg2 arg3
dir3`
d := newTestDispenser(input)
if val := d.Val(); val != "" {
t.Fatalf("Val(): Should return empty string when no token loaded; got '%s'", val)
}
assertNext := func(shouldLoad bool, expectedCursor int, expectedVal string) {
if loaded := d.Next(); loaded != shouldLoad {
t.Errorf("Next(): Expected %v but got %v instead (val '%s')", shouldLoad, loaded, d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("Expected cursor to be %d, but was %d", expectedCursor, d.cursor)
}
if d.nesting != 0 {
t.Errorf("Nesting should be 0, was %d instead", d.nesting)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNext(true, 0, "host:port")
assertNext(true, 1, "dir1")
assertNext(true, 2, "arg1")
assertNext(true, 3, "dir2")
assertNext(true, 4, "arg2")
assertNext(true, 5, "arg3")
assertNext(true, 6, "dir3")
// Note: This next test simply asserts existing behavior.
// If desired, we may wish to empty the token value after
// reading past the EOF. Open an issue if you want this change.
assertNext(false, 6, "dir3")
}
func TestDispenser_NextArg(t *testing.T) {
input := `dir1 arg1
dir2 arg2 arg3
dir3`
d := newTestDispenser(input)
assertNext := func(shouldLoad bool, expectedVal string, expectedCursor int) {
if d.Next() != shouldLoad {
t.Errorf("Next(): Should load token but got false instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("Next(): Expected cursor to be at %d, but it was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNextArg := func(expectedVal string, loadAnother bool, expectedCursor int) {
if !d.NextArg() {
t.Error("NextArg(): Should load next argument but got false instead")
}
if d.cursor != expectedCursor {
t.Errorf("NextArg(): Expected cursor to be at %d, but it was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
if !loadAnother {
if d.NextArg() {
t.Fatalf("NextArg(): Should NOT load another argument, but got true instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("NextArg(): Expected cursor to remain at %d, but it was %d", expectedCursor, d.cursor)
}
}
}
assertNext(true, "dir1", 0)
assertNextArg("arg1", false, 1)
assertNext(true, "dir2", 2)
assertNextArg("arg2", true, 3)
assertNextArg("arg3", false, 4)
assertNext(true, "dir3", 5)
assertNext(false, "dir3", 5)
}
func TestDispenser_NextLine(t *testing.T) {
input := `host:port
dir1 arg1
dir2 arg2 arg3`
d := newTestDispenser(input)
assertNextLine := func(shouldLoad bool, expectedVal string, expectedCursor int) {
if d.NextLine() != shouldLoad {
t.Errorf("NextLine(): Should load token but got false instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("NextLine(): Expected cursor to be %d, instead was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNextLine(true, "host:port", 0)
assertNextLine(true, "dir1", 1)
assertNextLine(false, "dir1", 1)
d.Next() // arg1
assertNextLine(true, "dir2", 3)
assertNextLine(false, "dir2", 3)
d.Next() // arg2
assertNextLine(false, "arg2", 4)
d.Next() // arg3
assertNextLine(false, "arg3", 5)
}
func TestDispenser_NextBlock(t *testing.T) {
input := `foobar1 {
sub1 arg1
sub2
}
foobar2 {
}`
d := newTestDispenser(input)
assertNextBlock := func(shouldLoad bool, expectedCursor, expectedNesting int) {
if loaded := d.NextBlock(0); loaded != shouldLoad {
t.Errorf("NextBlock(): Should return %v but got %v", shouldLoad, loaded)
}
if d.cursor != expectedCursor {
t.Errorf("NextBlock(): Expected cursor to be %d, was %d", expectedCursor, d.cursor)
}
if d.nesting != expectedNesting {
t.Errorf("NextBlock(): Nesting should be %d, not %d", expectedNesting, d.nesting)
}
}
assertNextBlock(false, -1, 0)
d.Next() // foobar1
assertNextBlock(true, 2, 1)
assertNextBlock(true, 3, 1)
assertNextBlock(true, 4, 1)
assertNextBlock(false, 5, 0)
d.Next() // foobar2
assertNextBlock(false, 8, 0) // empty block is as if it didn't exist
}
func TestDispenser_Args(t *testing.T) {
var s1, s2, s3 string
input := `dir1 arg1 arg2 arg3
dir2 arg4 arg5
dir3 arg6 arg7
dir4`
d := newTestDispenser(input)
d.Next() // dir1
// As many strings as arguments
if all := d.Args(&s1, &s2, &s3); !all {
t.Error("Args(): Expected true, got false")
}
if s1 != "arg1" {
t.Errorf("Args(): Expected s1 to be 'arg1', got '%s'", s1)
}
if s2 != "arg2" {
t.Errorf("Args(): Expected s2 to be 'arg2', got '%s'", s2)
}
if s3 != "arg3" {
t.Errorf("Args(): Expected s3 to be 'arg3', got '%s'", s3)
}
d.Next() // dir2
// More strings than arguments
if all := d.Args(&s1, &s2, &s3); all {
t.Error("Args(): Expected false, got true")
}
if s1 != "arg4" {
t.Errorf("Args(): Expected s1 to be 'arg4', got '%s'", s1)
}
if s2 != "arg5" {
t.Errorf("Args(): Expected s2 to be 'arg5', got '%s'", s2)
}
if s3 != "arg3" {
t.Errorf("Args(): Expected s3 to be unchanged ('arg3'), instead got '%s'", s3)
}
// (quick cursor check just for kicks and giggles)
if d.cursor != 6 {
t.Errorf("Cursor should be 6, but is %d", d.cursor)
}
d.Next() // dir3
// More arguments than strings
if all := d.Args(&s1); !all {
t.Error("Args(): Expected true, got false")
}
if s1 != "arg6" {
t.Errorf("Args(): Expected s1 to be 'arg6', got '%s'", s1)
}
d.Next() // dir4
// No arguments or strings
if all := d.Args(); !all {
t.Error("Args(): Expected true, got false")
}
// No arguments but at least one string
if all := d.Args(&s1); all {
t.Error("Args(): Expected false, got true")
}
}
func TestDispenser_RemainingArgs(t *testing.T) {
input := `dir1 arg1 arg2 arg3
dir2 arg4 arg5
dir3 arg6 { arg7
dir4`
d := newTestDispenser(input)
d.Next() // dir1
args := d.RemainingArgs()
if expected := []string{"arg1", "arg2", "arg3"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // dir2
args = d.RemainingArgs()
if expected := []string{"arg4", "arg5"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // dir3
args = d.RemainingArgs()
if expected := []string{"arg6"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // {
d.Next() // arg7
d.Next() // dir4
args = d.RemainingArgs()
if len(args) != 0 {
t.Errorf("RemainingArgs(): Expected %v, got %v", []string{}, args)
}
}
func TestDispenser_ArgErr_Err(t *testing.T) {
input := `dir1 {
}
dir2 arg1 arg2`
d := newTestDispenser(input)
d.cursor = 1 // {
if err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), "{") {
t.Errorf("ArgErr(): Expected an error message with { in it, but got '%v'", err)
}
d.cursor = 5 // arg2
if err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), "arg2") {
t.Errorf("ArgErr(): Expected an error message with 'arg2' in it; got '%v'", err)
}
err := d.Err("foobar")
if err == nil {
t.Fatalf("Err(): Expected an error, got nil")
}
if !strings.Contains(err.Error(), "Testfile:3") {
t.Errorf("Expected error message with filename:line in it; got '%v'", err)
}
if !strings.Contains(err.Error(), "foobar") {
t.Errorf("Expected error message with custom message in it ('foobar'); got '%v'", err)
}
}
func newTestDispenser(input string) *Dispenser {
tokens, err := allTokens("Testfile", []byte(input))
if err != nil && err != io.EOF {
log.Fatalf("getting all tokens from input: %v", err)
}
return NewDispenser(tokens)
}
| caddyconfig/caddyfile/dispenser_test.go | 1 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.9992119073867798,
0.5477715134620667,
0.00016849281382746994,
0.8031792640686035,
0.4437408745288849
] |
{
"id": 1,
"code_window": [
"\tinput := `dir1 arg1\n",
"\t\t\t dir2 arg2 arg3\n",
"\t\t\t dir3`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\tassertNext := func(shouldLoad bool, expectedVal string, expectedCursor int) {\n",
"\t\tif d.Next() != shouldLoad {\n",
"\t\t\tt.Errorf(\"Next(): Should load token but got false instead (val: '%s')\", d.Val())\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 67
} | // Copyright 2015 Matthew Holt and The Caddy 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 standardstek
import (
"log"
"sync"
"time"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/modules/caddytls"
)
func init() {
caddy.RegisterModule(standardSTEKProvider{})
}
type standardSTEKProvider struct {
stekConfig *caddytls.SessionTicketService
timer *time.Timer
}
// CaddyModule returns the Caddy module information.
func (standardSTEKProvider) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "tls.stek.standard",
New: func() caddy.Module { return new(standardSTEKProvider) },
}
}
// Initialize sets the configuration for s and returns the starting keys.
func (s *standardSTEKProvider) Initialize(config *caddytls.SessionTicketService) ([][32]byte, error) {
// keep a reference to the config; we'll need it when rotating keys
s.stekConfig = config
itvl := time.Duration(s.stekConfig.RotationInterval)
mutex.Lock()
defer mutex.Unlock()
// if this is our first rotation or we are overdue
// for one, perform a rotation immediately; otherwise,
// we assume that the keys are non-empty and fresh
since := time.Since(lastRotation)
if lastRotation.IsZero() || since > itvl {
var err error
keys, err = s.stekConfig.RotateSTEKs(keys)
if err != nil {
return nil, err
}
since = 0 // since this is overdue or is the first rotation, use full interval
lastRotation = time.Now()
}
// create timer for the remaining time on the interval;
// this timer is cleaned up only when Next() returns
s.timer = time.NewTimer(itvl - since)
return keys, nil
}
// Next returns a channel which transmits the latest session ticket keys.
func (s *standardSTEKProvider) Next(doneChan <-chan struct{}) <-chan [][32]byte {
keysChan := make(chan [][32]byte)
go s.rotate(doneChan, keysChan)
return keysChan
}
// rotate rotates keys on a regular basis, sending each updated set of
// keys down keysChan, until doneChan is closed.
func (s *standardSTEKProvider) rotate(doneChan <-chan struct{}, keysChan chan<- [][32]byte) {
for {
select {
case now := <-s.timer.C:
// copy the slice header to avoid races
mutex.RLock()
keysCopy := keys
mutex.RUnlock()
// generate a new key, rotating old ones
var err error
keysCopy, err = s.stekConfig.RotateSTEKs(keysCopy)
if err != nil {
// TODO: improve this handling
log.Printf("[ERROR] Generating STEK: %v", err)
continue
}
// replace keys slice with updated value and
// record the timestamp of rotation
mutex.Lock()
keys = keysCopy
lastRotation = now
mutex.Unlock()
// send the updated keys to the service
keysChan <- keysCopy
// timer channel is already drained, so reset directly (see godoc)
s.timer.Reset(time.Duration(s.stekConfig.RotationInterval))
case <-doneChan:
// again, see godocs for why timer is stopped this way
if !s.timer.Stop() {
<-s.timer.C
}
return
}
}
}
var (
lastRotation time.Time
keys [][32]byte
mutex sync.RWMutex // protects keys and lastRotation
)
// Interface guard
var _ caddytls.STEKProvider = (*standardSTEKProvider)(nil)
| modules/caddytls/standardstek/stek.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.0014388408744707704,
0.0002618190774228424,
0.00016161173698492348,
0.0001719709689496085,
0.00032647792249917984
] |
{
"id": 1,
"code_window": [
"\tinput := `dir1 arg1\n",
"\t\t\t dir2 arg2 arg3\n",
"\t\t\t dir3`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\tassertNext := func(shouldLoad bool, expectedVal string, expectedCursor int) {\n",
"\t\tif d.Next() != shouldLoad {\n",
"\t\t\tt.Errorf(\"Next(): Should load token but got false instead (val: '%s')\", d.Val())\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 67
} | // Copyright 2015 Matthew Holt and The Caddy 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 caddy
import (
"reflect"
"testing"
)
func TestSplitNetworkAddress(t *testing.T) {
for i, tc := range []struct {
input string
expectNetwork string
expectHost string
expectPort string
expectErr bool
}{
{
input: "",
expectErr: true,
},
{
input: "foo",
expectErr: true,
},
{
input: "foo:1234",
expectHost: "foo",
expectPort: "1234",
},
{
input: "foo:1234-5678",
expectHost: "foo",
expectPort: "1234-5678",
},
{
input: "udp/foo:1234",
expectNetwork: "udp",
expectHost: "foo",
expectPort: "1234",
},
{
input: "tcp6/foo:1234-5678",
expectNetwork: "tcp6",
expectHost: "foo",
expectPort: "1234-5678",
},
{
input: "udp/",
expectNetwork: "udp",
expectErr: true,
},
{
input: "unix//foo/bar",
expectNetwork: "unix",
expectHost: "/foo/bar",
},
{
input: "unixgram//foo/bar",
expectNetwork: "unixgram",
expectHost: "/foo/bar",
},
{
input: "unixpacket//foo/bar",
expectNetwork: "unixpacket",
expectHost: "/foo/bar",
},
} {
actualNetwork, actualHost, actualPort, err := SplitNetworkAddress(tc.input)
if tc.expectErr && err == nil {
t.Errorf("Test %d: Expected error but got: %v", i, err)
}
if !tc.expectErr && err != nil {
t.Errorf("Test %d: Expected no error but got: %v", i, err)
}
if actualNetwork != tc.expectNetwork {
t.Errorf("Test %d: Expected network '%s' but got '%s'", i, tc.expectNetwork, actualNetwork)
}
if actualHost != tc.expectHost {
t.Errorf("Test %d: Expected host '%s' but got '%s'", i, tc.expectHost, actualHost)
}
if actualPort != tc.expectPort {
t.Errorf("Test %d: Expected port '%s' but got '%s'", i, tc.expectPort, actualPort)
}
}
}
func TestJoinNetworkAddress(t *testing.T) {
for i, tc := range []struct {
network, host, port string
expect string
}{
{
network: "", host: "", port: "",
expect: "",
},
{
network: "tcp", host: "", port: "",
expect: "tcp/",
},
{
network: "", host: "foo", port: "",
expect: "foo",
},
{
network: "", host: "", port: "1234",
expect: ":1234",
},
{
network: "", host: "", port: "1234-5678",
expect: ":1234-5678",
},
{
network: "", host: "foo", port: "1234",
expect: "foo:1234",
},
{
network: "udp", host: "foo", port: "1234",
expect: "udp/foo:1234",
},
{
network: "udp", host: "", port: "1234",
expect: "udp/:1234",
},
{
network: "unix", host: "/foo/bar", port: "",
expect: "unix//foo/bar",
},
{
network: "", host: "::1", port: "1234",
expect: "[::1]:1234",
},
} {
actual := JoinNetworkAddress(tc.network, tc.host, tc.port)
if actual != tc.expect {
t.Errorf("Test %d: Expected '%s' but got '%s'", i, tc.expect, actual)
}
}
}
func TestParseNetworkAddress(t *testing.T) {
for i, tc := range []struct {
input string
expectAddr ParsedAddress
expectErr bool
}{
{
input: "",
expectErr: true,
},
{
input: ":",
expectErr: true,
},
{
input: ":1234",
expectAddr: ParsedAddress{
Network: "tcp",
Host: "",
StartPort: 1234,
EndPort: 1234,
},
},
{
input: "tcp/:1234",
expectAddr: ParsedAddress{
Network: "tcp",
Host: "",
StartPort: 1234,
EndPort: 1234,
},
},
{
input: "tcp6/:1234",
expectAddr: ParsedAddress{
Network: "tcp6",
Host: "",
StartPort: 1234,
EndPort: 1234,
},
},
{
input: "tcp4/localhost:1234",
expectAddr: ParsedAddress{
Network: "tcp4",
Host: "localhost",
StartPort: 1234,
EndPort: 1234,
},
},
{
input: "unix//foo/bar",
expectAddr: ParsedAddress{
Network: "unix",
Host: "/foo/bar",
},
},
{
input: "localhost:1234-1234",
expectAddr: ParsedAddress{
Network: "tcp",
Host: "localhost",
StartPort: 1234,
EndPort: 1234,
},
},
{
input: "localhost:2-1",
expectErr: true,
},
{
input: "localhost:0",
expectAddr: ParsedAddress{
Network: "tcp",
Host: "localhost",
StartPort: 0,
EndPort: 0,
},
},
{
input: "localhost:1-999999999999",
expectErr: true,
},
} {
actualAddr, err := ParseNetworkAddress(tc.input)
if tc.expectErr && err == nil {
t.Errorf("Test %d: Expected error but got: %v", i, err)
}
if !tc.expectErr && err != nil {
t.Errorf("Test %d: Expected no error but got: %v", i, err)
}
if actualAddr.Network != tc.expectAddr.Network {
t.Errorf("Test %d: Expected network '%v' but got '%v'", i, tc.expectAddr, actualAddr)
}
if !reflect.DeepEqual(tc.expectAddr, actualAddr) {
t.Errorf("Test %d: Expected addresses %v but got %v", i, tc.expectAddr, actualAddr)
}
}
}
func TestJoinHostPort(t *testing.T) {
for i, tc := range []struct {
pa ParsedAddress
offset uint
expect string
}{
{
pa: ParsedAddress{
Network: "tcp",
Host: "localhost",
StartPort: 1234,
EndPort: 1234,
},
expect: "localhost:1234",
},
{
pa: ParsedAddress{
Network: "tcp",
Host: "localhost",
StartPort: 1234,
EndPort: 1235,
},
expect: "localhost:1234",
},
{
pa: ParsedAddress{
Network: "tcp",
Host: "localhost",
StartPort: 1234,
EndPort: 1235,
},
offset: 1,
expect: "localhost:1235",
},
{
pa: ParsedAddress{
Network: "unix",
Host: "/run/php/php7.3-fpm.sock",
},
expect: "/run/php/php7.3-fpm.sock",
},
} {
actual := tc.pa.JoinHostPort(tc.offset)
if actual != tc.expect {
t.Errorf("Test %d: Expected '%s' but got '%s'", i, tc.expect, actual)
}
}
}
| listeners_test.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.004489816725254059,
0.0003714192134793848,
0.00016375113045796752,
0.00017364544328302145,
0.0007970307487994432
] |
{
"id": 1,
"code_window": [
"\tinput := `dir1 arg1\n",
"\t\t\t dir2 arg2 arg3\n",
"\t\t\t dir3`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\tassertNext := func(shouldLoad bool, expectedVal string, expectedCursor int) {\n",
"\t\tif d.Next() != shouldLoad {\n",
"\t\t\tt.Errorf(\"Next(): Should load token but got false instead (val: '%s')\", d.Val())\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 67
} | // Copyright 2015 Matthew Holt and The Caddy 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 fileserver
const defaultBrowseTemplate = `<!DOCTYPE html>
<html>
<head>
<title>{{html .Name}}</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* { padding: 0; margin: 0; }
body {
font-family: sans-serif;
text-rendering: optimizespeed;
background-color: #ffffff;
}
a {
color: #006ed3;
text-decoration: none;
}
a:hover,
h1 a:hover {
color: #319cff;
}
header,
#summary {
padding-left: 5%;
padding-right: 5%;
}
th:first-child,
td:first-child {
width: 5%;
}
th:last-child,
td:last-child {
width: 5%;
}
header {
padding-top: 25px;
padding-bottom: 15px;
background-color: #f2f2f2;
}
h1 {
font-size: 20px;
font-weight: normal;
white-space: nowrap;
overflow-x: hidden;
text-overflow: ellipsis;
color: #999;
}
h1 a {
color: #000;
margin: 0 4px;
}
h1 a:hover {
text-decoration: underline;
}
h1 a:first-child {
margin: 0;
}
main {
display: block;
}
.meta {
font-size: 12px;
font-family: Verdana, sans-serif;
border-bottom: 1px solid #9C9C9C;
padding-top: 10px;
padding-bottom: 10px;
}
.meta-item {
margin-right: 1em;
}
#filter {
padding: 4px;
border: 1px solid #CCC;
}
table {
width: 100%;
border-collapse: collapse;
}
tr {
border-bottom: 1px dashed #dadada;
}
tbody tr:hover {
background-color: #ffffec;
}
th,
td {
text-align: left;
padding: 10px 0;
}
th {
padding-top: 15px;
padding-bottom: 15px;
font-size: 16px;
white-space: nowrap;
}
th a {
color: black;
}
th svg {
vertical-align: middle;
}
td {
white-space: nowrap;
font-size: 14px;
}
td:nth-child(2) {
width: 80%;
}
td:nth-child(3),
th:nth-child(3) {
padding: 0 20px 0 20px;
}
th:nth-child(4),
td:nth-child(4) {
text-align: right;
}
td:nth-child(2) svg {
position: absolute;
}
td .name,
td .goup {
margin-left: 1.75em;
word-break: break-all;
overflow-wrap: break-word;
white-space: pre-wrap;
}
.icon {
margin-right: 5px;
}
.icon.sort {
display: inline-block;
width: 1em;
height: 1em;
position: relative;
top: .2em;
}
.icon.sort .top {
position: absolute;
left: 0;
top: -1px;
}
.icon.sort .bottom {
position: absolute;
bottom: -1px;
left: 0;
}
footer {
padding: 40px 20px;
font-size: 12px;
text-align: center;
}
@media (max-width: 600px) {
.hideable {
display: none;
}
td:nth-child(2) {
width: auto;
}
th:nth-child(3),
td:nth-child(3) {
padding-right: 5%;
text-align: right;
}
h1 {
color: #000;
}
h1 a {
margin: 0;
}
#filter {
max-width: 100px;
}
}
</style>
</head>
<body onload='initFilter()'>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="0" width="0" style="position: absolute;">
<defs>
<!-- Folder -->
<g id="folder" fill-rule="nonzero" fill="none">
<path d="M285.22 37.55h-142.6L110.9 0H31.7C14.25 0 0 16.9 0 37.55v75.1h316.92V75.1c0-20.65-14.26-37.55-31.7-37.55z" fill="#FFA000"/>
<path d="M285.22 36H31.7C14.25 36 0 50.28 0 67.74v158.7c0 17.47 14.26 31.75 31.7 31.75H285.2c17.44 0 31.7-14.3 31.7-31.75V67.75c0-17.47-14.26-31.75-31.7-31.75z" fill="#FFCA28"/>
</g>
<g id="folder-shortcut" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="folder-shortcut-group" fill-rule="nonzero">
<g id="folder-shortcut-shape">
<path d="M285.224876,37.5486902 L142.612438,37.5486902 L110.920785,0 L31.6916529,0 C14.2612438,0 0,16.8969106 0,37.5486902 L0,112.646071 L316.916529,112.646071 L316.916529,75.0973805 C316.916529,54.4456008 302.655285,37.5486902 285.224876,37.5486902 Z" id="Shape" fill="#FFA000"></path>
<path d="M285.224876,36 L31.6916529,36 C14.2612438,36 0,50.2838568 0,67.7419039 L0,226.451424 C0,243.909471 14.2612438,258.193328 31.6916529,258.193328 L285.224876,258.193328 C302.655285,258.193328 316.916529,243.909471 316.916529,226.451424 L316.916529,67.7419039 C316.916529,50.2838568 302.655285,36 285.224876,36 Z" id="Shape" fill="#FFCA28"></path>
</g>
<path d="M126.154134,250.559184 C126.850974,251.883673 127.300549,253.006122 127.772602,254.106122 C128.469442,255.206122 128.919016,256.104082 129.638335,257.002041 C130.559962,258.326531 131.728855,259 133.100057,259 C134.493737,259 135.415364,258.55102 136.112204,257.67551 C136.809044,257.002041 137.258619,255.902041 137.258619,254.577551 C137.258619,253.904082 137.258619,252.804082 137.033832,251.457143 C136.786566,249.908163 136.561779,249.032653 136.561779,248.583673 C136.089726,242.814286 135.864939,237.920408 135.864939,233.273469 C135.864939,225.057143 136.786566,217.514286 138.180246,210.846939 C139.798713,204.202041 141.889234,198.634694 144.429328,193.763265 C147.216689,188.869388 150.678411,184.873469 154.836973,181.326531 C158.995535,177.779592 163.626149,174.883673 168.481552,172.661224 C173.336954,170.438776 179.113983,168.665306 185.587852,167.340816 C192.061722,166.218367 198.760378,165.342857 205.481514,164.669388 C212.18017,164.220408 219.598146,163.995918 228.162535,163.995918 L246.055591,163.995918 L246.055591,195.514286 C246.055591,197.736735 246.752431,199.510204 248.370899,201.059184 C250.214153,202.608163 252.079886,203.506122 254.372715,203.506122 C256.463236,203.506122 258.531277,202.608163 260.172223,201.059184 L326.102289,137.797959 C327.720757,136.24898 328.642384,134.47551 328.642384,132.253061 C328.642384,130.030612 327.720757,128.257143 326.102289,126.708163 L260.172223,63.4469388 C258.553756,61.8979592 256.463236,61 254.395194,61 C252.079886,61 250.236632,61.8979592 248.393377,63.4469388 C246.77491,64.9959184 246.07807,66.7693878 246.07807,68.9918367 L246.07807,100.510204 L228.162535,100.510204 C166.863084,100.510204 129.166282,117.167347 115.274437,150.459184 C110.666301,161.54898 108.350993,175.310204 108.350993,191.742857 C108.350993,205.279592 113.903236,223.912245 124.760454,247.438776 C125.00772,248.112245 125.457294,249.010204 126.154134,250.559184 Z" id="Shape" fill="#FFFFFF" transform="translate(218.496689, 160.000000) scale(-1, 1) translate(-218.496689, -160.000000) "></path>
</g>
</g>
<!-- File -->
<g id="file" stroke="#000" stroke-width="25" fill="#FFF" fill-rule="evenodd" stroke-linecap="round" stroke-linejoin="round">
<path d="M13 24.12v274.76c0 6.16 5.87 11.12 13.17 11.12H239c7.3 0 13.17-4.96 13.17-11.12V136.15S132.6 13 128.37 13H26.17C18.87 13 13 17.96 13 24.12z"/>
<path d="M129.37 13L129 113.9c0 10.58 7.26 19.1 16.27 19.1H249L129.37 13z"/>
</g>
<g id="file-shortcut" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="file-shortcut-group" transform="translate(13.000000, 13.000000)">
<g id="file-shortcut-shape" stroke="#000000" stroke-width="25" fill="#FFFFFF" stroke-linecap="round" stroke-linejoin="round">
<path d="M0,11.1214886 L0,285.878477 C0,292.039924 5.87498876,296.999983 13.1728373,296.999983 L225.997983,296.999983 C233.295974,296.999983 239.17082,292.039942 239.17082,285.878477 L239.17082,123.145388 C239.17082,123.145388 119.58541,2.84217094e-14 115.369423,2.84217094e-14 L13.1728576,2.84217094e-14 C5.87500907,-1.71479982e-05 0,4.96022995 0,11.1214886 Z" id="rect1171"></path>
<path d="M116.37005,0 L116,100.904964 C116,111.483663 123.258008,120 132.273377,120 L236,120 L116.37005,0 L116.37005,0 Z" id="rect1794"></path>
</g>
<path d="M47.803141,294.093878 C48.4999811,295.177551 48.9495553,296.095918 49.4216083,296.995918 C50.1184484,297.895918 50.5680227,298.630612 51.2873415,299.365306 C52.2089688,300.44898 53.3778619,301 54.7490634,301 C56.1427436,301 57.0643709,300.632653 57.761211,299.916327 C58.4580511,299.365306 58.9076254,298.465306 58.9076254,297.381633 C58.9076254,296.830612 58.9076254,295.930612 58.6828382,294.828571 C58.4355724,293.561224 58.2107852,292.844898 58.2107852,292.477551 C57.7387323,287.757143 57.5139451,283.753061 57.5139451,279.95102 C57.5139451,273.228571 58.4355724,267.057143 59.8292526,261.602041 C61.44772,256.165306 63.5382403,251.610204 66.0783349,247.62449 C68.8656954,243.620408 72.3274172,240.35102 76.4859792,237.44898 C80.6445412,234.546939 85.2751561,232.177551 90.1305582,230.359184 C94.9859603,228.540816 100.76299,227.089796 107.236859,226.006122 C113.710728,225.087755 120.409385,224.371429 127.13052,223.820408 C133.829177,223.453061 141.247152,223.269388 149.811542,223.269388 L167.704598,223.269388 L167.704598,249.057143 C167.704598,250.87551 168.401438,252.326531 170.019905,253.593878 C171.86316,254.861224 173.728893,255.595918 176.021722,255.595918 C178.112242,255.595918 180.180284,254.861224 181.82123,253.593878 L247.751296,201.834694 C249.369763,200.567347 250.291391,199.116327 250.291391,197.297959 C250.291391,195.479592 249.369763,194.028571 247.751296,192.761224 L181.82123,141.002041 C180.202763,139.734694 178.112242,139 176.044201,139 C173.728893,139 171.885639,139.734694 170.042384,141.002041 C168.423917,142.269388 167.727077,143.720408 167.727077,145.538776 L167.727077,171.326531 L149.811542,171.326531 C88.5120908,171.326531 50.8152886,184.955102 36.9234437,212.193878 C32.3153075,221.267347 30,232.526531 30,245.971429 C30,257.046939 35.5522422,272.291837 46.4094607,291.540816 C46.6567266,292.091837 47.1063009,292.826531 47.803141,294.093878 Z" id="Shape-Copy" fill="#000000" fill-rule="nonzero" transform="translate(140.145695, 220.000000) scale(-1, 1) translate(-140.145695, -220.000000) "></path>
</g>
</g>
<!-- Up arrow -->
<g id="up-arrow" transform="translate(-279.22 -208.12)">
<path transform="matrix(.22413 0 0 .12089 335.67 164.35)" stroke-width="0" d="m-194.17 412.01h-28.827-28.827l14.414-24.965 14.414-24.965 14.414 24.965z"/>
</g>
<!-- Down arrow -->
<g id="down-arrow" transform="translate(-279.22 -208.12)">
<path transform="matrix(.22413 0 0 -.12089 335.67 257.93)" stroke-width="0" d="m-194.17 412.01h-28.827-28.827l14.414-24.965 14.414-24.965 14.414 24.965z"/>
</g>
</defs>
</svg>
<header>
<h1>
{{range $i, $crumb := .Breadcrumbs}}<a href="{{html $crumb.Link}}">{{html $crumb.Text}}</a>{{if ne $i 0}}/{{end}}{{end}}
</h1>
</header>
<main>
<div class="meta">
<div id="summary">
<span class="meta-item"><b>{{.NumDirs}}</b> director{{if eq 1 .NumDirs}}y{{else}}ies{{end}}</span>
<span class="meta-item"><b>{{.NumFiles}}</b> file{{if ne 1 .NumFiles}}s{{end}}</span>
{{- if ne 0 .ItemsLimitedTo}}
<span class="meta-item">(of which only <b>{{.ItemsLimitedTo}}</b> are displayed)</span>
{{- end}}
<span class="meta-item"><input type="text" placeholder="filter" id="filter" onkeyup='filter()'></span>
</div>
</div>
<div class="listing">
<table aria-describedby="summary">
<thead>
<tr>
<th></th>
<th>
{{- if and (eq .Sort "namedirfirst") (ne .Order "desc")}}
<a href="?sort=namedirfirst&order=desc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}" class="icon"><svg width="1em" height=".5em" version="1.1" viewBox="0 0 12.922194 6.0358899"><use xlink:href="#up-arrow"></use></svg></a>
{{- else if and (eq .Sort "namedirfirst") (ne .Order "asc")}}
<a href="?sort=namedirfirst&order=asc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}" class="icon"><svg width="1em" height=".5em" version="1.1" viewBox="0 0 12.922194 6.0358899"><use xlink:href="#down-arrow"></use></svg></a>
{{- else}}
<a href="?sort=namedirfirst&order=asc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}" class="icon sort"><svg class="top" width="1em" height=".5em" version="1.1" viewBox="0 0 12.922194 6.0358899"><use xlink:href="#up-arrow"></use></svg><svg class="bottom" width="1em" height=".5em" version="1.1" viewBox="0 0 12.922194 6.0358899"><use xlink:href="#down-arrow"></use></svg></a>
{{- end}}
{{- if and (eq .Sort "name") (ne .Order "desc")}}
<a href="?sort=name&order=desc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}">Name <svg width="1em" height=".5em" version="1.1" viewBox="0 0 12.922194 6.0358899"><use xlink:href="#up-arrow"></use></svg></a>
{{- else if and (eq .Sort "name") (ne .Order "asc")}}
<a href="?sort=name&order=asc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}">Name <svg width="1em" height=".5em" version="1.1" viewBox="0 0 12.922194 6.0358899"><use xlink:href="#down-arrow"></use></svg></a>
{{- else}}
<a href="?sort=name&order=asc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}">Name</a>
{{- end}}
</th>
<th>
{{- if and (eq .Sort "size") (ne .Order "desc")}}
<a href="?sort=size&order=desc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}">Size <svg width="1em" height=".5em" version="1.1" viewBox="0 0 12.922194 6.0358899"><use xlink:href="#up-arrow"></use></svg></a>
{{- else if and (eq .Sort "size") (ne .Order "asc")}}
<a href="?sort=size&order=asc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}">Size <svg width="1em" height=".5em" version="1.1" viewBox="0 0 12.922194 6.0358899"><use xlink:href="#down-arrow"></use></svg></a>
{{- else}}
<a href="?sort=size&order=asc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}">Size</a>
{{- end}}
</th>
<th class="hideable">
{{- if and (eq .Sort "time") (ne .Order "desc")}}
<a href="?sort=time&order=desc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}">Modified <svg width="1em" height=".5em" version="1.1" viewBox="0 0 12.922194 6.0358899"><use xlink:href="#up-arrow"></use></svg></a>
{{- else if and (eq .Sort "time") (ne .Order "asc")}}
<a href="?sort=time&order=asc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}">Modified <svg width="1em" height=".5em" version="1.1" viewBox="0 0 12.922194 6.0358899"><use xlink:href="#down-arrow"></use></svg></a>
{{- else}}
<a href="?sort=time&order=asc{{if ne 0 .ItemsLimitedTo}}&limit={{.ItemsLimitedTo}}{{end}}">Modified</a>
{{- end}}
</th>
<th class="hideable"></th>
</tr>
</thead>
<tbody>
{{- if .CanGoUp}}
<tr>
<td></td>
<td>
<a href="..">
<span class="goup">Go up</span>
</a>
</td>
<td>—</td>
<td class="hideable">—</td>
<td class="hideable"></td>
</tr>
{{- end}}
{{- range .Items}}
<tr class="file">
<td></td>
<td>
<a href="{{html .URL}}">
{{- if .IsDir}}
<svg width="1.5em" height="1em" version="1.1" viewBox="0 0 317 259"><use xlink:href="#folder{{if .IsSymlink}}-shortcut{{end}}"></use></svg>
{{- else}}
<svg width="1.5em" height="1em" version="1.1" viewBox="0 0 265 323"><use xlink:href="#file{{if .IsSymlink}}-shortcut{{end}}"></use></svg>
{{- end}}
<span class="name">{{html .Name}}</span>
</a>
</td>
{{- if .IsDir}}
<td data-order="-1">—</td>
{{- else}}
<td data-order="{{.Size}}">{{.HumanSize}}</td>
{{- end}}
<td class="hideable"><time datetime="{{.HumanModTime "2006-01-02T15:04:05Z"}}">{{.HumanModTime "01/02/2006 03:04:05 PM -07:00"}}</time></td>
<td class="hideable"></td>
</tr>
{{- end}}
</tbody>
</table>
</div>
</main>
<footer>
Served with <a rel="noopener noreferrer" href="https://caddyserver.com">Caddy</a>
</footer>
<script>
var filterEl = document.getElementById('filter');
filterEl.focus();
function initFilter() {
if (!filterEl.value) {
var filterParam = new URL(window.location.href).searchParams.get('filter');
if (filterParam) {
filterEl.value = filterParam;
}
}
filter();
}
function filter() {
var q = filterEl.value.trim().toLowerCase();
var elems = document.querySelectorAll('tr.file');
elems.forEach(function(el) {
if (!q) {
el.style.display = '';
return;
}
var nameEl = el.querySelector('.name');
var nameVal = nameEl.textContent.trim().toLowerCase();
if (nameVal.indexOf(q) !== -1) {
el.style.display = '';
} else {
el.style.display = 'none';
}
});
}
function localizeDatetime(e, index, ar) {
if (e.textContent === undefined) {
return;
}
var d = new Date(e.getAttribute('datetime'));
if (isNaN(d)) {
d = new Date(e.textContent);
if (isNaN(d)) {
return;
}
}
e.textContent = d.toLocaleString([], {day: "2-digit", month: "2-digit", year: "numeric", hour: "2-digit", minute: "2-digit", second: "2-digit"});
}
var timeList = Array.prototype.slice.call(document.getElementsByTagName("time"));
timeList.forEach(localizeDatetime);
</script>
</body>
</html>`
| modules/caddyhttp/fileserver/browsetpl.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.0002856815990526229,
0.00017839664360508323,
0.00016521300130989403,
0.00017370637215208262,
0.000023724562197458
] |
{
"id": 2,
"code_window": [
"\n",
"func TestDispenser_NextLine(t *testing.T) {\n",
"\tinput := `host:port\n",
"\t\t\t dir1 arg1\n",
"\t\t\t dir2 arg2 arg3`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\tassertNextLine := func(shouldLoad bool, expectedVal string, expectedCursor int) {\n",
"\t\tif d.NextLine() != shouldLoad {\n",
"\t\t\tt.Errorf(\"NextLine(): Should load token but got false instead (val: '%s')\", d.Val())\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 114
} | // Copyright 2015 Matthew Holt and The Caddy 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 caddyfile
import (
"io"
"log"
"reflect"
"strings"
"testing"
)
func TestDispenser_Val_Next(t *testing.T) {
input := `host:port
dir1 arg1
dir2 arg2 arg3
dir3`
d := newTestDispenser(input)
if val := d.Val(); val != "" {
t.Fatalf("Val(): Should return empty string when no token loaded; got '%s'", val)
}
assertNext := func(shouldLoad bool, expectedCursor int, expectedVal string) {
if loaded := d.Next(); loaded != shouldLoad {
t.Errorf("Next(): Expected %v but got %v instead (val '%s')", shouldLoad, loaded, d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("Expected cursor to be %d, but was %d", expectedCursor, d.cursor)
}
if d.nesting != 0 {
t.Errorf("Nesting should be 0, was %d instead", d.nesting)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNext(true, 0, "host:port")
assertNext(true, 1, "dir1")
assertNext(true, 2, "arg1")
assertNext(true, 3, "dir2")
assertNext(true, 4, "arg2")
assertNext(true, 5, "arg3")
assertNext(true, 6, "dir3")
// Note: This next test simply asserts existing behavior.
// If desired, we may wish to empty the token value after
// reading past the EOF. Open an issue if you want this change.
assertNext(false, 6, "dir3")
}
func TestDispenser_NextArg(t *testing.T) {
input := `dir1 arg1
dir2 arg2 arg3
dir3`
d := newTestDispenser(input)
assertNext := func(shouldLoad bool, expectedVal string, expectedCursor int) {
if d.Next() != shouldLoad {
t.Errorf("Next(): Should load token but got false instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("Next(): Expected cursor to be at %d, but it was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNextArg := func(expectedVal string, loadAnother bool, expectedCursor int) {
if !d.NextArg() {
t.Error("NextArg(): Should load next argument but got false instead")
}
if d.cursor != expectedCursor {
t.Errorf("NextArg(): Expected cursor to be at %d, but it was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
if !loadAnother {
if d.NextArg() {
t.Fatalf("NextArg(): Should NOT load another argument, but got true instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("NextArg(): Expected cursor to remain at %d, but it was %d", expectedCursor, d.cursor)
}
}
}
assertNext(true, "dir1", 0)
assertNextArg("arg1", false, 1)
assertNext(true, "dir2", 2)
assertNextArg("arg2", true, 3)
assertNextArg("arg3", false, 4)
assertNext(true, "dir3", 5)
assertNext(false, "dir3", 5)
}
func TestDispenser_NextLine(t *testing.T) {
input := `host:port
dir1 arg1
dir2 arg2 arg3`
d := newTestDispenser(input)
assertNextLine := func(shouldLoad bool, expectedVal string, expectedCursor int) {
if d.NextLine() != shouldLoad {
t.Errorf("NextLine(): Should load token but got false instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("NextLine(): Expected cursor to be %d, instead was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNextLine(true, "host:port", 0)
assertNextLine(true, "dir1", 1)
assertNextLine(false, "dir1", 1)
d.Next() // arg1
assertNextLine(true, "dir2", 3)
assertNextLine(false, "dir2", 3)
d.Next() // arg2
assertNextLine(false, "arg2", 4)
d.Next() // arg3
assertNextLine(false, "arg3", 5)
}
func TestDispenser_NextBlock(t *testing.T) {
input := `foobar1 {
sub1 arg1
sub2
}
foobar2 {
}`
d := newTestDispenser(input)
assertNextBlock := func(shouldLoad bool, expectedCursor, expectedNesting int) {
if loaded := d.NextBlock(0); loaded != shouldLoad {
t.Errorf("NextBlock(): Should return %v but got %v", shouldLoad, loaded)
}
if d.cursor != expectedCursor {
t.Errorf("NextBlock(): Expected cursor to be %d, was %d", expectedCursor, d.cursor)
}
if d.nesting != expectedNesting {
t.Errorf("NextBlock(): Nesting should be %d, not %d", expectedNesting, d.nesting)
}
}
assertNextBlock(false, -1, 0)
d.Next() // foobar1
assertNextBlock(true, 2, 1)
assertNextBlock(true, 3, 1)
assertNextBlock(true, 4, 1)
assertNextBlock(false, 5, 0)
d.Next() // foobar2
assertNextBlock(false, 8, 0) // empty block is as if it didn't exist
}
func TestDispenser_Args(t *testing.T) {
var s1, s2, s3 string
input := `dir1 arg1 arg2 arg3
dir2 arg4 arg5
dir3 arg6 arg7
dir4`
d := newTestDispenser(input)
d.Next() // dir1
// As many strings as arguments
if all := d.Args(&s1, &s2, &s3); !all {
t.Error("Args(): Expected true, got false")
}
if s1 != "arg1" {
t.Errorf("Args(): Expected s1 to be 'arg1', got '%s'", s1)
}
if s2 != "arg2" {
t.Errorf("Args(): Expected s2 to be 'arg2', got '%s'", s2)
}
if s3 != "arg3" {
t.Errorf("Args(): Expected s3 to be 'arg3', got '%s'", s3)
}
d.Next() // dir2
// More strings than arguments
if all := d.Args(&s1, &s2, &s3); all {
t.Error("Args(): Expected false, got true")
}
if s1 != "arg4" {
t.Errorf("Args(): Expected s1 to be 'arg4', got '%s'", s1)
}
if s2 != "arg5" {
t.Errorf("Args(): Expected s2 to be 'arg5', got '%s'", s2)
}
if s3 != "arg3" {
t.Errorf("Args(): Expected s3 to be unchanged ('arg3'), instead got '%s'", s3)
}
// (quick cursor check just for kicks and giggles)
if d.cursor != 6 {
t.Errorf("Cursor should be 6, but is %d", d.cursor)
}
d.Next() // dir3
// More arguments than strings
if all := d.Args(&s1); !all {
t.Error("Args(): Expected true, got false")
}
if s1 != "arg6" {
t.Errorf("Args(): Expected s1 to be 'arg6', got '%s'", s1)
}
d.Next() // dir4
// No arguments or strings
if all := d.Args(); !all {
t.Error("Args(): Expected true, got false")
}
// No arguments but at least one string
if all := d.Args(&s1); all {
t.Error("Args(): Expected false, got true")
}
}
func TestDispenser_RemainingArgs(t *testing.T) {
input := `dir1 arg1 arg2 arg3
dir2 arg4 arg5
dir3 arg6 { arg7
dir4`
d := newTestDispenser(input)
d.Next() // dir1
args := d.RemainingArgs()
if expected := []string{"arg1", "arg2", "arg3"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // dir2
args = d.RemainingArgs()
if expected := []string{"arg4", "arg5"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // dir3
args = d.RemainingArgs()
if expected := []string{"arg6"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // {
d.Next() // arg7
d.Next() // dir4
args = d.RemainingArgs()
if len(args) != 0 {
t.Errorf("RemainingArgs(): Expected %v, got %v", []string{}, args)
}
}
func TestDispenser_ArgErr_Err(t *testing.T) {
input := `dir1 {
}
dir2 arg1 arg2`
d := newTestDispenser(input)
d.cursor = 1 // {
if err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), "{") {
t.Errorf("ArgErr(): Expected an error message with { in it, but got '%v'", err)
}
d.cursor = 5 // arg2
if err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), "arg2") {
t.Errorf("ArgErr(): Expected an error message with 'arg2' in it; got '%v'", err)
}
err := d.Err("foobar")
if err == nil {
t.Fatalf("Err(): Expected an error, got nil")
}
if !strings.Contains(err.Error(), "Testfile:3") {
t.Errorf("Expected error message with filename:line in it; got '%v'", err)
}
if !strings.Contains(err.Error(), "foobar") {
t.Errorf("Expected error message with custom message in it ('foobar'); got '%v'", err)
}
}
func newTestDispenser(input string) *Dispenser {
tokens, err := allTokens("Testfile", []byte(input))
if err != nil && err != io.EOF {
log.Fatalf("getting all tokens from input: %v", err)
}
return NewDispenser(tokens)
}
| caddyconfig/caddyfile/dispenser_test.go | 1 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.9987924098968506,
0.3799893856048584,
0.00016687570314388722,
0.05650155991315842,
0.435997873544693
] |
{
"id": 2,
"code_window": [
"\n",
"func TestDispenser_NextLine(t *testing.T) {\n",
"\tinput := `host:port\n",
"\t\t\t dir1 arg1\n",
"\t\t\t dir2 arg2 arg3`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\tassertNextLine := func(shouldLoad bool, expectedVal string, expectedCursor int) {\n",
"\t\tif d.NextLine() != shouldLoad {\n",
"\t\t\tt.Errorf(\"NextLine(): Should load token but got false instead (val: '%s')\", d.Val())\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 114
} | // Copyright 2015 Matthew Holt and The Caddy 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 caddypki
import (
"crypto/x509"
"fmt"
"time"
"go.uber.org/zap"
)
func (p *PKI) maintenance() {
ticker := time.NewTicker(10 * time.Minute) // TODO: make configurable
defer ticker.Stop()
for {
select {
case <-ticker.C:
p.renewCerts()
case <-p.ctx.Done():
return
}
}
}
func (p *PKI) renewCerts() {
for _, ca := range p.CAs {
err := p.renewCertsForCA(ca)
if err != nil {
p.log.Error("renewing intermediate certificates",
zap.Error(err),
zap.String("ca", ca.id))
}
}
}
func (p *PKI) renewCertsForCA(ca *CA) error {
ca.mu.Lock()
defer ca.mu.Unlock()
log := p.log.With(zap.String("ca", ca.id))
// only maintain the root if it's not manually provided in the config
if ca.Root == nil {
if needsRenewal(ca.root) {
// TODO: implement root renewal (use same key)
log.Warn("root certificate expiring soon (FIXME: ROOT RENEWAL NOT YET IMPLEMENTED)",
zap.Duration("time_remaining", time.Until(ca.inter.NotAfter)),
)
}
}
// only maintain the intermediate if it's not manually provided in the config
if ca.Intermediate == nil {
if needsRenewal(ca.inter) {
log.Info("intermediate expires soon; renewing",
zap.Duration("time_remaining", time.Until(ca.inter.NotAfter)),
)
rootCert, rootKey, err := ca.loadOrGenRoot()
if err != nil {
return fmt.Errorf("loading root key: %v", err)
}
interCert, interKey, err := ca.genIntermediate(rootCert, rootKey)
if err != nil {
return fmt.Errorf("generating new certificate: %v", err)
}
ca.inter, ca.interKey = interCert, interKey
log.Info("renewed intermediate",
zap.Time("new_expiration", ca.inter.NotAfter),
)
}
}
return nil
}
func needsRenewal(cert *x509.Certificate) bool {
lifetime := cert.NotAfter.Sub(cert.NotBefore)
renewalWindow := time.Duration(float64(lifetime) * renewalWindowRatio)
renewalWindowStart := cert.NotAfter.Add(-renewalWindow)
return time.Now().After(renewalWindowStart)
}
const renewalWindowRatio = 0.2 // TODO: make configurable
| modules/caddypki/maintain.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.000177055160747841,
0.00017088954336941242,
0.00016631939797662199,
0.00016953355225268751,
0.000003239725174353225
] |
{
"id": 2,
"code_window": [
"\n",
"func TestDispenser_NextLine(t *testing.T) {\n",
"\tinput := `host:port\n",
"\t\t\t dir1 arg1\n",
"\t\t\t dir2 arg2 arg3`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\tassertNextLine := func(shouldLoad bool, expectedVal string, expectedCursor int) {\n",
"\t\tif d.NextLine() != shouldLoad {\n",
"\t\t\tt.Errorf(\"NextLine(): Should load token but got false instead (val: '%s')\", d.Val())\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 114
} | // Copyright 2015 Matthew Holt and The Caddy 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 caddy
import (
"fmt"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
)
// NewReplacer returns a new Replacer.
func NewReplacer() *Replacer {
rep := &Replacer{
static: make(map[string]interface{}),
}
rep.providers = []ReplacerFunc{
globalDefaultReplacements,
rep.fromStatic,
}
return rep
}
// Replacer can replace values in strings.
// A default/empty Replacer is not valid;
// use NewReplacer to make one.
type Replacer struct {
providers []ReplacerFunc
static map[string]interface{}
}
// Map adds mapFunc to the list of value providers.
// mapFunc will be executed only at replace-time.
func (r *Replacer) Map(mapFunc ReplacerFunc) {
r.providers = append(r.providers, mapFunc)
}
// Set sets a custom variable to a static value.
func (r *Replacer) Set(variable string, value interface{}) {
r.static[variable] = value
}
// Get gets a value from the replacer. It returns
// the value and whether the variable was known.
func (r *Replacer) Get(variable string) (interface{}, bool) {
for _, mapFunc := range r.providers {
if val, ok := mapFunc(variable); ok {
return val, true
}
}
return nil, false
}
// Delete removes a variable with a static value
// that was created using Set.
func (r *Replacer) Delete(variable string) {
delete(r.static, variable)
}
// fromStatic provides values from r.static.
func (r *Replacer) fromStatic(key string) (interface{}, bool) {
val, ok := r.static[key]
return val, ok
}
// ReplaceOrErr is like ReplaceAll, but any placeholders
// that are empty or not recognized will cause an error to
// be returned.
func (r *Replacer) ReplaceOrErr(input string, errOnEmpty, errOnUnknown bool) (string, error) {
return r.replace(input, "", false, errOnEmpty, errOnUnknown, nil)
}
// ReplaceKnown is like ReplaceAll but only replaces
// placeholders that are known (recognized). Unrecognized
// placeholders will remain in the output.
func (r *Replacer) ReplaceKnown(input, empty string) string {
out, _ := r.replace(input, empty, false, false, false, nil)
return out
}
// ReplaceAll efficiently replaces placeholders in input with
// their values. All placeholders are replaced in the output
// whether they are recognized or not. Values that are empty
// string will be substituted with empty.
func (r *Replacer) ReplaceAll(input, empty string) string {
out, _ := r.replace(input, empty, true, false, false, nil)
return out
}
// ReplaceFunc is the same as ReplaceAll, but calls f for every
// replacement to be made, in case f wants to change or inspect
// the replacement.
func (r *Replacer) ReplaceFunc(input string, f ReplacementFunc) (string, error) {
return r.replace(input, "", true, false, false, f)
}
func (r *Replacer) replace(input, empty string,
treatUnknownAsEmpty, errOnEmpty, errOnUnknown bool,
f ReplacementFunc) (string, error) {
if !strings.Contains(input, string(phOpen)) {
return input, nil
}
var sb strings.Builder
// it is reasonable to assume that the output
// will be approximately as long as the input
sb.Grow(len(input))
// iterate the input to find each placeholder
var lastWriteCursor int
scan:
for i := 0; i < len(input); i++ {
// check for escaped braces
if i > 0 && input[i-1] == phEscape && (input[i] == phClose || input[i] == phOpen) {
sb.WriteString(input[lastWriteCursor : i-1])
lastWriteCursor = i
continue
}
if input[i] != phOpen {
continue
}
// find the end of the placeholder
end := strings.Index(input[i:], string(phClose)) + i
if end < i {
continue
}
// if necessary look for the first closing brace that is not escaped
for end > 0 && end < len(input)-1 && input[end-1] == phEscape {
nextEnd := strings.Index(input[end+1:], string(phClose))
if nextEnd < 0 {
continue scan
}
end += nextEnd + 1
}
// write the substring from the last cursor to this point
sb.WriteString(input[lastWriteCursor:i])
// trim opening bracket
key := input[i+1 : end]
// try to get a value for this key, handle empty values accordingly
val, found := r.Get(key)
if !found {
// placeholder is unknown (unrecognized); handle accordingly
if errOnUnknown {
return "", fmt.Errorf("unrecognized placeholder %s%s%s",
string(phOpen), key, string(phClose))
} else if !treatUnknownAsEmpty {
// if treatUnknownAsEmpty is true, we'll handle an empty
// val later; so only continue otherwise
lastWriteCursor = i
continue
}
}
// apply any transformations
if f != nil {
var err error
val, err = f(key, val)
if err != nil {
return "", err
}
}
// convert val to a string as efficiently as possible
valStr := toString(val)
// write the value; if it's empty, either return
// an error or write a default value
if valStr == "" {
if errOnEmpty {
return "", fmt.Errorf("evaluated placeholder %s%s%s is empty",
string(phOpen), key, string(phClose))
} else if empty != "" {
sb.WriteString(empty)
}
} else {
sb.WriteString(valStr)
}
// advance cursor to end of placeholder
i = end
lastWriteCursor = i + 1
}
// flush any unwritten remainder
sb.WriteString(input[lastWriteCursor:])
return sb.String(), nil
}
func toString(val interface{}) string {
switch v := val.(type) {
case nil:
return ""
case string:
return v
case fmt.Stringer:
return v.String()
case byte:
return string(v)
case []byte:
return string(v)
case []rune:
return string(v)
case int:
return strconv.Itoa(v)
case int32:
return strconv.Itoa(int(v))
case int64:
return strconv.Itoa(int(v))
case uint:
return strconv.Itoa(int(v))
case uint32:
return strconv.Itoa(int(v))
case uint64:
return strconv.Itoa(int(v))
case float32:
return strconv.FormatFloat(float64(v), 'f', -1, 32)
case float64:
return strconv.FormatFloat(v, 'f', -1, 64)
case bool:
if v {
return "true"
}
return "false"
default:
return fmt.Sprintf("%+v", v)
}
}
// ReplacerFunc is a function that returns a replacement
// for the given key along with true if the function is able
// to service that key (even if the value is blank). If the
// function does not recognize the key, false should be
// returned.
type ReplacerFunc func(key string) (interface{}, bool)
func globalDefaultReplacements(key string) (interface{}, bool) {
// check environment variable
const envPrefix = "env."
if strings.HasPrefix(key, envPrefix) {
return os.Getenv(key[len(envPrefix):]), true
}
switch key {
case "system.hostname":
// OK if there is an error; just return empty string
name, _ := os.Hostname()
return name, true
case "system.slash":
return string(filepath.Separator), true
case "system.os":
return runtime.GOOS, true
case "system.arch":
return runtime.GOARCH, true
case "time.now.common_log":
return nowFunc().Format("02/Jan/2006:15:04:05 -0700"), true
case "time.now.year":
return strconv.Itoa(nowFunc().Year()), true
}
return nil, false
}
// ReplacementFunc is a function that is called when a
// replacement is being performed. It receives the
// variable (i.e. placeholder name) and the value that
// will be the replacement, and returns the value that
// will actually be the replacement, or an error. Note
// that errors are sometimes ignored by replacers.
type ReplacementFunc func(variable string, val interface{}) (interface{}, error)
// nowFunc is a variable so tests can change it
// in order to obtain a deterministic time.
var nowFunc = time.Now
// ReplacerCtxKey is the context key for a replacer.
const ReplacerCtxKey CtxKey = "replacer"
const phOpen, phClose, phEscape = '{', '}', '\\'
| replacer.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.0011617966229096055,
0.00029213723610155284,
0.00016260736447293311,
0.00017196052067447454,
0.00022711876954417676
] |
{
"id": 2,
"code_window": [
"\n",
"func TestDispenser_NextLine(t *testing.T) {\n",
"\tinput := `host:port\n",
"\t\t\t dir1 arg1\n",
"\t\t\t dir2 arg2 arg3`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\tassertNextLine := func(shouldLoad bool, expectedVal string, expectedCursor int) {\n",
"\t\tif d.NextLine() != shouldLoad {\n",
"\t\t\tt.Errorf(\"NextLine(): Should load token but got false instead (val: '%s')\", d.Val())\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 114
} | // Copyright 2015 Matthew Holt and The Caddy 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.
// Copyright 2015 Light Code Labs, LLC
//
// 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 templates
import (
"bytes"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"testing"
"time"
)
func TestMarkdown(t *testing.T) {
context := getContextOrFail(t)
for i, test := range []struct {
body string
expect template.HTML
}{
{
body: "- str1\n- str2\n",
expect: "<ul>\n<li>str1</li>\n<li>str2</li>\n</ul>\n",
},
} {
result, err := context.funcMarkdown(test.body)
if result != test.expect {
t.Errorf("Test %d: expected '%s' but got '%s'", i, test.expect, result)
}
if err != nil {
t.Errorf("Test %d: got error: %v", i, result)
}
}
}
func TestCookie(t *testing.T) {
for i, test := range []struct {
cookie *http.Cookie
cookieName string
expect string
}{
{
// happy path
cookie: &http.Cookie{Name: "cookieName", Value: "cookieValue"},
cookieName: "cookieName",
expect: "cookieValue",
},
{
// try to get a non-existing cookie
cookie: &http.Cookie{Name: "cookieName", Value: "cookieValue"},
cookieName: "notExisting",
expect: "",
},
{
// partial name match
cookie: &http.Cookie{Name: "cookie", Value: "cookieValue"},
cookieName: "cook",
expect: "",
},
{
// cookie with optional fields
cookie: &http.Cookie{Name: "cookie", Value: "cookieValue", Path: "/path", Domain: "https://localhost", Expires: (time.Now().Add(10 * time.Minute)), MaxAge: 120},
cookieName: "cookie",
expect: "cookieValue",
},
} {
context := getContextOrFail(t)
context.Req.AddCookie(test.cookie)
actual := context.Cookie(test.cookieName)
if actual != test.expect {
t.Errorf("Test %d: Expected cookie value '%s' but got '%s' for cookie with name '%s'",
i, test.expect, actual, test.cookieName)
}
}
}
func TestCookieMultipleCookies(t *testing.T) {
context := getContextOrFail(t)
cookieNameBase, cookieValueBase := "cookieName", "cookieValue"
for i := 0; i < 10; i++ {
context.Req.AddCookie(&http.Cookie{
Name: fmt.Sprintf("%s%d", cookieNameBase, i),
Value: fmt.Sprintf("%s%d", cookieValueBase, i),
})
}
for i := 0; i < 10; i++ {
expectedCookieVal := fmt.Sprintf("%s%d", cookieValueBase, i)
actualCookieVal := context.Cookie(fmt.Sprintf("%s%d", cookieNameBase, i))
if actualCookieVal != expectedCookieVal {
t.Errorf("Expected cookie value %s, found %s", expectedCookieVal, actualCookieVal)
}
}
}
func TestIP(t *testing.T) {
context := getContextOrFail(t)
for i, test := range []struct {
inputRemoteAddr string
expect string
}{
{"1.1.1.1:1111", "1.1.1.1"},
{"1.1.1.1", "1.1.1.1"},
{"[::1]:11", "::1"},
{"[2001:db8:a0b:12f0::1]", "[2001:db8:a0b:12f0::1]"},
{`[fe80:1::3%eth0]:44`, `fe80:1::3%eth0`},
} {
context.Req.RemoteAddr = test.inputRemoteAddr
if actual := context.RemoteIP(); actual != test.expect {
t.Errorf("Test %d: Expected %s but got %s", i, test.expect, actual)
}
}
}
func TestStripHTML(t *testing.T) {
context := getContextOrFail(t)
for i, test := range []struct {
input string
expect string
}{
{
// no tags
input: `h1`,
expect: `h1`,
},
{
// happy path
input: `<h1>h1</h1>`,
expect: `h1`,
},
{
// tag in quotes
input: `<h1">">h1</h1>`,
expect: `h1`,
},
{
// multiple tags
input: `<h1><b>h1</b></h1>`,
expect: `h1`,
},
{
// tags not closed
input: `<h1`,
expect: `<h1`,
},
{
// false start
input: `<h1<b>hi`,
expect: `<h1hi`,
},
} {
actual := context.funcStripHTML(test.input)
if actual != test.expect {
t.Errorf("Test %d: Expected %s, found %s. Input was StripHTML(%s)", i, test.expect, actual, test.input)
}
}
}
func TestFileListing(t *testing.T) {
for i, test := range []struct {
fileNames []string
inputBase string
shouldErr bool
verifyErr func(error) bool
}{
{
// directory and files exist
fileNames: []string{"file1", "file2"},
shouldErr: false,
},
{
// directory exists, no files
fileNames: []string{},
shouldErr: false,
},
{
// file or directory does not exist
fileNames: nil,
inputBase: "doesNotExist",
shouldErr: true,
verifyErr: os.IsNotExist,
},
{
// directory and files exist, but path to a file
fileNames: []string{"file1", "file2"},
inputBase: "file1",
shouldErr: true,
verifyErr: func(err error) bool {
return strings.HasSuffix(err.Error(), "is not a directory")
},
},
{
// try to escape Context Root
fileNames: nil,
inputBase: filepath.Join("..", "..", "..", "..", "..", "etc"),
shouldErr: true,
verifyErr: os.IsNotExist,
},
} {
context := getContextOrFail(t)
var dirPath string
var err error
// create files for test case
if test.fileNames != nil {
dirPath, err = ioutil.TempDir(fmt.Sprintf("%s", context.Root), "caddy_ctxtest")
if err != nil {
t.Fatalf("Test %d: Expected no error creating directory, got: '%s'", i, err.Error())
}
for _, name := range test.fileNames {
absFilePath := filepath.Join(dirPath, name)
if err = ioutil.WriteFile(absFilePath, []byte(""), os.ModePerm); err != nil {
os.RemoveAll(dirPath)
t.Fatalf("Test %d: Expected no error creating file, got: '%s'", i, err.Error())
}
}
}
// perform test
input := filepath.ToSlash(filepath.Join(filepath.Base(dirPath), test.inputBase))
actual, err := context.funcListFiles(input)
if err != nil {
if !test.shouldErr {
t.Errorf("Test %d: Expected no error, got: '%s'", i, err)
} else if !test.verifyErr(err) {
t.Errorf("Test %d: Could not verify error content, got: '%s'", i, err)
}
} else if test.shouldErr {
t.Errorf("Test %d: Expected error but had none", i)
} else {
numFiles := len(test.fileNames)
// reflect.DeepEqual does not consider two empty slices to be equal
if numFiles == 0 && len(actual) != 0 {
t.Errorf("Test %d: Expected files %v, got: %v",
i, test.fileNames, actual)
} else {
sort.Strings(actual)
if numFiles > 0 && !reflect.DeepEqual(test.fileNames, actual) {
t.Errorf("Test %d: Expected files %v, got: %v",
i, test.fileNames, actual)
}
}
}
if dirPath != "" {
if err := os.RemoveAll(dirPath); err != nil && !os.IsNotExist(err) {
t.Fatalf("Test %d: Expected no error removing temporary test directory, got: %v", i, err)
}
}
}
}
func getContextOrFail(t *testing.T) templateContext {
context, err := initTestContext()
if err != nil {
t.Fatalf("failed to prepare test context: %v", err)
}
return context
}
func initTestContext() (templateContext, error) {
body := bytes.NewBufferString("request body")
request, err := http.NewRequest("GET", "https://example.com/foo/bar", body)
if err != nil {
return templateContext{}, err
}
return templateContext{
Root: http.Dir(os.TempDir()),
Req: request,
RespHeader: tplWrappedHeader{make(http.Header)},
}, nil
}
| modules/caddyhttp/templates/tplcontext_test.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.0009175390005111694,
0.00023451070592273027,
0.00016726393369026482,
0.00017210454097948968,
0.0001648131583351642
] |
{
"id": 3,
"code_window": [
"\t\t\t \tsub1 arg1\n",
"\t\t\t \tsub2\n",
"\t\t\t }\n",
"\t\t\t foobar2 {\n",
"\t\t\t }`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\tassertNextBlock := func(shouldLoad bool, expectedCursor, expectedNesting int) {\n",
"\t\tif loaded := d.NextBlock(0); loaded != shouldLoad {\n",
"\t\t\tt.Errorf(\"NextBlock(): Should return %v but got %v\", shouldLoad, loaded)\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 147
} | // Copyright 2015 Matthew Holt and The Caddy 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 caddyfile
import (
"io"
"log"
"reflect"
"strings"
"testing"
)
func TestDispenser_Val_Next(t *testing.T) {
input := `host:port
dir1 arg1
dir2 arg2 arg3
dir3`
d := newTestDispenser(input)
if val := d.Val(); val != "" {
t.Fatalf("Val(): Should return empty string when no token loaded; got '%s'", val)
}
assertNext := func(shouldLoad bool, expectedCursor int, expectedVal string) {
if loaded := d.Next(); loaded != shouldLoad {
t.Errorf("Next(): Expected %v but got %v instead (val '%s')", shouldLoad, loaded, d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("Expected cursor to be %d, but was %d", expectedCursor, d.cursor)
}
if d.nesting != 0 {
t.Errorf("Nesting should be 0, was %d instead", d.nesting)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNext(true, 0, "host:port")
assertNext(true, 1, "dir1")
assertNext(true, 2, "arg1")
assertNext(true, 3, "dir2")
assertNext(true, 4, "arg2")
assertNext(true, 5, "arg3")
assertNext(true, 6, "dir3")
// Note: This next test simply asserts existing behavior.
// If desired, we may wish to empty the token value after
// reading past the EOF. Open an issue if you want this change.
assertNext(false, 6, "dir3")
}
func TestDispenser_NextArg(t *testing.T) {
input := `dir1 arg1
dir2 arg2 arg3
dir3`
d := newTestDispenser(input)
assertNext := func(shouldLoad bool, expectedVal string, expectedCursor int) {
if d.Next() != shouldLoad {
t.Errorf("Next(): Should load token but got false instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("Next(): Expected cursor to be at %d, but it was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNextArg := func(expectedVal string, loadAnother bool, expectedCursor int) {
if !d.NextArg() {
t.Error("NextArg(): Should load next argument but got false instead")
}
if d.cursor != expectedCursor {
t.Errorf("NextArg(): Expected cursor to be at %d, but it was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
if !loadAnother {
if d.NextArg() {
t.Fatalf("NextArg(): Should NOT load another argument, but got true instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("NextArg(): Expected cursor to remain at %d, but it was %d", expectedCursor, d.cursor)
}
}
}
assertNext(true, "dir1", 0)
assertNextArg("arg1", false, 1)
assertNext(true, "dir2", 2)
assertNextArg("arg2", true, 3)
assertNextArg("arg3", false, 4)
assertNext(true, "dir3", 5)
assertNext(false, "dir3", 5)
}
func TestDispenser_NextLine(t *testing.T) {
input := `host:port
dir1 arg1
dir2 arg2 arg3`
d := newTestDispenser(input)
assertNextLine := func(shouldLoad bool, expectedVal string, expectedCursor int) {
if d.NextLine() != shouldLoad {
t.Errorf("NextLine(): Should load token but got false instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("NextLine(): Expected cursor to be %d, instead was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNextLine(true, "host:port", 0)
assertNextLine(true, "dir1", 1)
assertNextLine(false, "dir1", 1)
d.Next() // arg1
assertNextLine(true, "dir2", 3)
assertNextLine(false, "dir2", 3)
d.Next() // arg2
assertNextLine(false, "arg2", 4)
d.Next() // arg3
assertNextLine(false, "arg3", 5)
}
func TestDispenser_NextBlock(t *testing.T) {
input := `foobar1 {
sub1 arg1
sub2
}
foobar2 {
}`
d := newTestDispenser(input)
assertNextBlock := func(shouldLoad bool, expectedCursor, expectedNesting int) {
if loaded := d.NextBlock(0); loaded != shouldLoad {
t.Errorf("NextBlock(): Should return %v but got %v", shouldLoad, loaded)
}
if d.cursor != expectedCursor {
t.Errorf("NextBlock(): Expected cursor to be %d, was %d", expectedCursor, d.cursor)
}
if d.nesting != expectedNesting {
t.Errorf("NextBlock(): Nesting should be %d, not %d", expectedNesting, d.nesting)
}
}
assertNextBlock(false, -1, 0)
d.Next() // foobar1
assertNextBlock(true, 2, 1)
assertNextBlock(true, 3, 1)
assertNextBlock(true, 4, 1)
assertNextBlock(false, 5, 0)
d.Next() // foobar2
assertNextBlock(false, 8, 0) // empty block is as if it didn't exist
}
func TestDispenser_Args(t *testing.T) {
var s1, s2, s3 string
input := `dir1 arg1 arg2 arg3
dir2 arg4 arg5
dir3 arg6 arg7
dir4`
d := newTestDispenser(input)
d.Next() // dir1
// As many strings as arguments
if all := d.Args(&s1, &s2, &s3); !all {
t.Error("Args(): Expected true, got false")
}
if s1 != "arg1" {
t.Errorf("Args(): Expected s1 to be 'arg1', got '%s'", s1)
}
if s2 != "arg2" {
t.Errorf("Args(): Expected s2 to be 'arg2', got '%s'", s2)
}
if s3 != "arg3" {
t.Errorf("Args(): Expected s3 to be 'arg3', got '%s'", s3)
}
d.Next() // dir2
// More strings than arguments
if all := d.Args(&s1, &s2, &s3); all {
t.Error("Args(): Expected false, got true")
}
if s1 != "arg4" {
t.Errorf("Args(): Expected s1 to be 'arg4', got '%s'", s1)
}
if s2 != "arg5" {
t.Errorf("Args(): Expected s2 to be 'arg5', got '%s'", s2)
}
if s3 != "arg3" {
t.Errorf("Args(): Expected s3 to be unchanged ('arg3'), instead got '%s'", s3)
}
// (quick cursor check just for kicks and giggles)
if d.cursor != 6 {
t.Errorf("Cursor should be 6, but is %d", d.cursor)
}
d.Next() // dir3
// More arguments than strings
if all := d.Args(&s1); !all {
t.Error("Args(): Expected true, got false")
}
if s1 != "arg6" {
t.Errorf("Args(): Expected s1 to be 'arg6', got '%s'", s1)
}
d.Next() // dir4
// No arguments or strings
if all := d.Args(); !all {
t.Error("Args(): Expected true, got false")
}
// No arguments but at least one string
if all := d.Args(&s1); all {
t.Error("Args(): Expected false, got true")
}
}
func TestDispenser_RemainingArgs(t *testing.T) {
input := `dir1 arg1 arg2 arg3
dir2 arg4 arg5
dir3 arg6 { arg7
dir4`
d := newTestDispenser(input)
d.Next() // dir1
args := d.RemainingArgs()
if expected := []string{"arg1", "arg2", "arg3"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // dir2
args = d.RemainingArgs()
if expected := []string{"arg4", "arg5"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // dir3
args = d.RemainingArgs()
if expected := []string{"arg6"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // {
d.Next() // arg7
d.Next() // dir4
args = d.RemainingArgs()
if len(args) != 0 {
t.Errorf("RemainingArgs(): Expected %v, got %v", []string{}, args)
}
}
func TestDispenser_ArgErr_Err(t *testing.T) {
input := `dir1 {
}
dir2 arg1 arg2`
d := newTestDispenser(input)
d.cursor = 1 // {
if err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), "{") {
t.Errorf("ArgErr(): Expected an error message with { in it, but got '%v'", err)
}
d.cursor = 5 // arg2
if err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), "arg2") {
t.Errorf("ArgErr(): Expected an error message with 'arg2' in it; got '%v'", err)
}
err := d.Err("foobar")
if err == nil {
t.Fatalf("Err(): Expected an error, got nil")
}
if !strings.Contains(err.Error(), "Testfile:3") {
t.Errorf("Expected error message with filename:line in it; got '%v'", err)
}
if !strings.Contains(err.Error(), "foobar") {
t.Errorf("Expected error message with custom message in it ('foobar'); got '%v'", err)
}
}
func newTestDispenser(input string) *Dispenser {
tokens, err := allTokens("Testfile", []byte(input))
if err != nil && err != io.EOF {
log.Fatalf("getting all tokens from input: %v", err)
}
return NewDispenser(tokens)
}
| caddyconfig/caddyfile/dispenser_test.go | 1 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.9978912472724915,
0.44099161028862,
0.0001693233789410442,
0.022120868787169456,
0.4732700288295746
] |
{
"id": 3,
"code_window": [
"\t\t\t \tsub1 arg1\n",
"\t\t\t \tsub2\n",
"\t\t\t }\n",
"\t\t\t foobar2 {\n",
"\t\t\t }`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\tassertNextBlock := func(shouldLoad bool, expectedCursor, expectedNesting int) {\n",
"\t\tif loaded := d.NextBlock(0); loaded != shouldLoad {\n",
"\t\t\tt.Errorf(\"NextBlock(): Should return %v but got %v\", shouldLoad, loaded)\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 147
} | // Copyright 2015 Matthew Holt and The Caddy 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 reverseproxy
import (
"context"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"regexp"
"strconv"
"time"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"go.uber.org/zap"
)
// HealthChecks configures active and passive health checks.
type HealthChecks struct {
// Active health checks run in the background on a timer. To
// minimally enable active health checks, set either path or
// port (or both).
Active *ActiveHealthChecks `json:"active,omitempty"`
// Passive health checks monitor proxied requests for errors or timeouts.
// To minimally enable passive health checks, specify at least an empty
// config object.
Passive *PassiveHealthChecks `json:"passive,omitempty"`
}
// ActiveHealthChecks holds configuration related to active
// health checks (that is, health checks which occur in a
// background goroutine independently).
type ActiveHealthChecks struct {
// The URI path to use for health checks.
Path string `json:"path,omitempty"`
// The port to use (if different from the upstream's dial
// address) for health checks.
Port int `json:"port,omitempty"`
// HTTP headers to set on health check requests.
Headers http.Header `json:"headers,omitempty"`
// How frequently to perform active health checks (default 30s).
Interval caddy.Duration `json:"interval,omitempty"`
// How long to wait for a response from a backend before
// considering it unhealthy (default 5s).
Timeout caddy.Duration `json:"timeout,omitempty"`
// The maximum response body to download from the backend
// during a health check.
MaxSize int64 `json:"max_size,omitempty"`
// The HTTP status code to expect from a healthy backend.
ExpectStatus int `json:"expect_status,omitempty"`
// A regular expression against which to match the response
// body of a healthy backend.
ExpectBody string `json:"expect_body,omitempty"`
stopChan chan struct{}
httpClient *http.Client
bodyRegexp *regexp.Regexp
logger *zap.Logger
}
// PassiveHealthChecks holds configuration related to passive
// health checks (that is, health checks which occur during
// the normal flow of request proxying).
type PassiveHealthChecks struct {
// How long to remember a failed request to a backend. A duration > 0
// enables passive health checking. Default is 0.
FailDuration caddy.Duration `json:"fail_duration,omitempty"`
// The number of failed requests within the FailDuration window to
// consider a backend as "down". Must be >= 1; default is 1. Requires
// that FailDuration be > 0.
MaxFails int `json:"max_fails,omitempty"`
// Limits the number of simultaneous requests to a backend by
// marking the backend as "down" if it has this many concurrent
// requests or more.
UnhealthyRequestCount int `json:"unhealthy_request_count,omitempty"`
// Count the request as failed if the response comes back with
// one of these status codes.
UnhealthyStatus []int `json:"unhealthy_status,omitempty"`
// Count the request as failed if the response takes at least this
// long to receive.
UnhealthyLatency caddy.Duration `json:"unhealthy_latency,omitempty"`
logger *zap.Logger
}
// CircuitBreaker is a type that can act as an early-warning
// system for the health checker when backends are getting
// overloaded.
type CircuitBreaker interface {
OK() bool
RecordMetric(statusCode int, latency time.Duration)
}
// activeHealthChecker runs active health checks on a
// regular basis and blocks until
// h.HealthChecks.Active.stopChan is closed.
func (h *Handler) activeHealthChecker() {
ticker := time.NewTicker(time.Duration(h.HealthChecks.Active.Interval))
h.doActiveHealthCheckForAllHosts()
for {
select {
case <-ticker.C:
h.doActiveHealthCheckForAllHosts()
case <-h.HealthChecks.Active.stopChan:
// TODO: consider using a Context for cancellation instead
ticker.Stop()
return
}
}
}
// doActiveHealthCheckForAllHosts immediately performs a
// health checks for all upstream hosts configured by h.
func (h *Handler) doActiveHealthCheckForAllHosts() {
for _, upstream := range h.Upstreams {
go func(upstream *Upstream) {
networkAddr := upstream.Dial
addr, err := caddy.ParseNetworkAddress(networkAddr)
if err != nil {
h.HealthChecks.Active.logger.Error("bad network address",
zap.String("address", networkAddr),
zap.Error(err),
)
return
}
if addr.PortRangeSize() != 1 {
h.HealthChecks.Active.logger.Error("multiple addresses (upstream must map to only one address)",
zap.String("address", networkAddr),
)
return
}
hostAddr := addr.JoinHostPort(0)
if addr.IsUnixNetwork() {
// this will be used as the Host portion of a http.Request URL, and
// paths to socket files would produce an error when creating URL,
// so use a fake Host value instead; unix sockets are usually local
hostAddr = "localhost"
}
err = h.doActiveHealthCheck(DialInfo{Network: addr.Network, Address: hostAddr}, hostAddr, upstream.Host)
if err != nil {
h.HealthChecks.Active.logger.Error("active health check failed",
zap.String("address", networkAddr),
zap.Error(err),
)
}
}(upstream)
}
}
// doActiveHealthCheck performs a health check to host which
// can be reached at address hostAddr. The actual address for
// the request will be built according to active health checker
// config. The health status of the host will be updated
// according to whether it passes the health check. An error is
// returned only if the health check fails to occur or if marking
// the host's health status fails.
func (h *Handler) doActiveHealthCheck(dialInfo DialInfo, hostAddr string, host Host) error {
// create the URL for the request that acts as a health check
scheme := "http"
if ht, ok := h.Transport.(*http.Transport); ok && ht.TLSClientConfig != nil {
// this is kind of a hacky way to know if we should use HTTPS, but whatever
scheme = "https"
}
u := &url.URL{
Scheme: scheme,
Host: hostAddr,
Path: h.HealthChecks.Active.Path,
}
// adjust the port, if configured to be different
if h.HealthChecks.Active.Port != 0 {
portStr := strconv.Itoa(h.HealthChecks.Active.Port)
host, _, err := net.SplitHostPort(hostAddr)
if err != nil {
host = hostAddr
}
u.Host = net.JoinHostPort(host, portStr)
}
// attach dialing information to this request - TODO: use caddy.Context's context
// so it can be canceled on config reload
ctx := context.Background()
ctx = context.WithValue(ctx, caddy.ReplacerCtxKey, caddy.NewReplacer())
ctx = context.WithValue(ctx, caddyhttp.VarsCtxKey, map[string]interface{}{
dialInfoVarKey: dialInfo,
})
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return fmt.Errorf("making request: %v", err)
}
for key, hdrs := range h.HealthChecks.Active.Headers {
req.Header[key] = hdrs
}
// do the request, being careful to tame the response body
resp, err := h.HealthChecks.Active.httpClient.Do(req)
if err != nil {
h.HealthChecks.Active.logger.Info("HTTP request failed",
zap.String("host", hostAddr),
zap.Error(err),
)
_, err2 := host.SetHealthy(false)
if err2 != nil {
return fmt.Errorf("marking unhealthy: %v", err2)
}
return nil
}
var body io.Reader = resp.Body
if h.HealthChecks.Active.MaxSize > 0 {
body = io.LimitReader(body, h.HealthChecks.Active.MaxSize)
}
defer func() {
// drain any remaining body so connection could be re-used
io.Copy(ioutil.Discard, body)
resp.Body.Close()
}()
// if status code is outside criteria, mark down
if h.HealthChecks.Active.ExpectStatus > 0 {
if !caddyhttp.StatusCodeMatches(resp.StatusCode, h.HealthChecks.Active.ExpectStatus) {
h.HealthChecks.Active.logger.Info("unexpected status code",
zap.Int("status_code", resp.StatusCode),
zap.String("host", hostAddr),
)
_, err := host.SetHealthy(false)
if err != nil {
return fmt.Errorf("marking unhealthy: %v", err)
}
return nil
}
} else if resp.StatusCode < 200 || resp.StatusCode >= 400 {
h.HealthChecks.Active.logger.Info("status code out of tolerances",
zap.Int("status_code", resp.StatusCode),
zap.String("host", hostAddr),
)
_, err := host.SetHealthy(false)
if err != nil {
return fmt.Errorf("marking unhealthy: %v", err)
}
return nil
}
// if body does not match regex, mark down
if h.HealthChecks.Active.bodyRegexp != nil {
bodyBytes, err := ioutil.ReadAll(body)
if err != nil {
h.HealthChecks.Active.logger.Info("failed to read response body",
zap.String("host", hostAddr),
zap.Error(err),
)
_, err := host.SetHealthy(false)
if err != nil {
return fmt.Errorf("marking unhealthy: %v", err)
}
return nil
}
if !h.HealthChecks.Active.bodyRegexp.Match(bodyBytes) {
h.HealthChecks.Active.logger.Info("response body failed expectations",
zap.String("host", hostAddr),
)
_, err := host.SetHealthy(false)
if err != nil {
return fmt.Errorf("marking unhealthy: %v", err)
}
return nil
}
}
// passed health check parameters, so mark as healthy
swapped, err := host.SetHealthy(true)
if swapped {
h.HealthChecks.Active.logger.Info("host is up",
zap.String("host", hostAddr),
)
}
if err != nil {
return fmt.Errorf("marking healthy: %v", err)
}
return nil
}
// countFailure is used with passive health checks. It
// remembers 1 failure for upstream for the configured
// duration. If passive health checks are disabled or
// failure expiry is 0, this is a no-op.
func (h *Handler) countFailure(upstream *Upstream) {
// only count failures if passive health checking is enabled
// and if failures are configured have a non-zero expiry
if h.HealthChecks == nil || h.HealthChecks.Passive == nil {
return
}
failDuration := time.Duration(h.HealthChecks.Passive.FailDuration)
if failDuration == 0 {
return
}
// count failure immediately
err := upstream.Host.CountFail(1)
if err != nil {
h.HealthChecks.Passive.logger.Error("could not count failure",
zap.String("host", upstream.Dial),
zap.Error(err),
)
}
// forget it later
go func(host Host, failDuration time.Duration) {
time.Sleep(failDuration)
err := host.CountFail(-1)
if err != nil {
h.HealthChecks.Passive.logger.Error("could not forget failure",
zap.String("host", upstream.Dial),
zap.Error(err),
)
}
}(upstream.Host, failDuration)
}
| modules/caddyhttp/reverseproxy/healthchecks.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.00031678707455284894,
0.000174353554029949,
0.00016304470773320645,
0.00016992099699564278,
0.00002467240483383648
] |
{
"id": 3,
"code_window": [
"\t\t\t \tsub1 arg1\n",
"\t\t\t \tsub2\n",
"\t\t\t }\n",
"\t\t\t foobar2 {\n",
"\t\t\t }`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\tassertNextBlock := func(shouldLoad bool, expectedCursor, expectedNesting int) {\n",
"\t\tif loaded := d.NextBlock(0); loaded != shouldLoad {\n",
"\t\t\tt.Errorf(\"NextBlock(): Should return %v but got %v\", shouldLoad, loaded)\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 147
} | // Copyright 2015 Matthew Holt and The Caddy 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 rewrite
import (
"net/http"
"testing"
"github.com/caddyserver/caddy/v2"
)
func TestRewrite(t *testing.T) {
repl := caddy.NewReplacer()
for i, tc := range []struct {
input, expect *http.Request
rule Rewrite
}{
{
input: newRequest(t, "GET", "/"),
expect: newRequest(t, "GET", "/"),
},
{
rule: Rewrite{Method: "GET", URI: "/"},
input: newRequest(t, "GET", "/"),
expect: newRequest(t, "GET", "/"),
},
{
rule: Rewrite{Method: "POST"},
input: newRequest(t, "GET", "/"),
expect: newRequest(t, "POST", "/"),
},
{
rule: Rewrite{URI: "/foo"},
input: newRequest(t, "GET", "/"),
expect: newRequest(t, "GET", "/foo"),
},
{
rule: Rewrite{URI: "/foo"},
input: newRequest(t, "GET", "/bar"),
expect: newRequest(t, "GET", "/foo"),
},
{
rule: Rewrite{URI: "foo"},
input: newRequest(t, "GET", "/"),
expect: newRequest(t, "GET", "foo"),
},
{
rule: Rewrite{URI: "/foo{http.request.uri.path}"},
input: newRequest(t, "GET", "/bar"),
expect: newRequest(t, "GET", "/foo/bar"),
},
{
rule: Rewrite{URI: "/index.php?p={http.request.uri.path}"},
input: newRequest(t, "GET", "/foo/bar"),
expect: newRequest(t, "GET", "/index.php?p=%2Ffoo%2Fbar"),
},
{
rule: Rewrite{URI: "?a=b&{http.request.uri.query}"},
input: newRequest(t, "GET", "/"),
expect: newRequest(t, "GET", "/?a=b"),
},
{
rule: Rewrite{URI: "/?c=d"},
input: newRequest(t, "GET", "/"),
expect: newRequest(t, "GET", "/?c=d"),
},
{
rule: Rewrite{URI: "/?c=d"},
input: newRequest(t, "GET", "/?a=b"),
expect: newRequest(t, "GET", "/?c=d"),
},
{
rule: Rewrite{URI: "?c=d"},
input: newRequest(t, "GET", "/foo"),
expect: newRequest(t, "GET", "/foo?c=d"),
},
{
rule: Rewrite{URI: "/?c=d"},
input: newRequest(t, "GET", "/foo"),
expect: newRequest(t, "GET", "/?c=d"),
},
{
rule: Rewrite{URI: "/?{http.request.uri.query}&c=d"},
input: newRequest(t, "GET", "/"),
expect: newRequest(t, "GET", "/?c=d"),
},
{
rule: Rewrite{URI: "/foo?{http.request.uri.query}&c=d"},
input: newRequest(t, "GET", "/"),
expect: newRequest(t, "GET", "/foo?c=d"),
},
{
rule: Rewrite{URI: "?{http.request.uri.query}&c=d"},
input: newRequest(t, "GET", "/foo"),
expect: newRequest(t, "GET", "/foo?c=d"),
},
{
rule: Rewrite{URI: "{http.request.uri.path}?{http.request.uri.query}&c=d"},
input: newRequest(t, "GET", "/foo"),
expect: newRequest(t, "GET", "/foo?c=d"),
},
{
rule: Rewrite{URI: "{http.request.uri.path}?{http.request.uri.query}&c=d"},
input: newRequest(t, "GET", "/foo"),
expect: newRequest(t, "GET", "/foo?c=d"),
},
{
rule: Rewrite{URI: "/index.php?{http.request.uri.query}&c=d"},
input: newRequest(t, "GET", "/foo"),
expect: newRequest(t, "GET", "/index.php?c=d"),
},
{
rule: Rewrite{URI: "?a=b&c=d"},
input: newRequest(t, "GET", "/foo"),
expect: newRequest(t, "GET", "/foo?a=b&c=d"),
},
{
rule: Rewrite{URI: "/index.php?{http.request.uri.query}&c=d"},
input: newRequest(t, "GET", "/?a=b"),
expect: newRequest(t, "GET", "/index.php?a=b&c=d"),
},
{
rule: Rewrite{URI: "/index.php?c=d&{http.request.uri.query}"},
input: newRequest(t, "GET", "/?a=b"),
expect: newRequest(t, "GET", "/index.php?c=d&a=b"),
},
{
rule: Rewrite{URI: "/index.php?{http.request.uri.query}&p={http.request.uri.path}"},
input: newRequest(t, "GET", "/foo/bar?a=b"),
expect: newRequest(t, "GET", "/index.php?a=b&p=%2Ffoo%2Fbar"),
},
{
rule: Rewrite{URI: "{http.request.uri.path}?"},
input: newRequest(t, "GET", "/foo/bar?a=b&c=d"),
expect: newRequest(t, "GET", "/foo/bar"),
},
{
rule: Rewrite{URI: "?qs={http.request.uri.query}"},
input: newRequest(t, "GET", "/foo?a=b&c=d"),
expect: newRequest(t, "GET", "/foo?qs=a%3Db%26c%3Dd"),
},
{
rule: Rewrite{URI: "/foo?{http.request.uri.query}#frag"},
input: newRequest(t, "GET", "/foo/bar?a=b"),
expect: newRequest(t, "GET", "/foo?a=b#frag"),
},
{
rule: Rewrite{URI: "/foo{http.request.uri}"},
input: newRequest(t, "GET", "/bar?a=b"),
expect: newRequest(t, "GET", "/foo/bar?a=b"),
},
{
rule: Rewrite{URI: "/foo{http.request.uri}"},
input: newRequest(t, "GET", "/bar"),
expect: newRequest(t, "GET", "/foo/bar"),
},
{
rule: Rewrite{URI: "/foo{http.request.uri}?c=d"},
input: newRequest(t, "GET", "/bar?a=b"),
expect: newRequest(t, "GET", "/foo/bar?c=d"),
},
{
rule: Rewrite{URI: "/foo{http.request.uri}?{http.request.uri.query}&c=d"},
input: newRequest(t, "GET", "/bar?a=b"),
expect: newRequest(t, "GET", "/foo/bar?a=b&c=d"),
},
{
rule: Rewrite{URI: "{http.request.uri}"},
input: newRequest(t, "GET", "/bar?a=b"),
expect: newRequest(t, "GET", "/bar?a=b"),
},
{
rule: Rewrite{URI: "{http.request.uri.path}bar?c=d"},
input: newRequest(t, "GET", "/foo/?a=b"),
expect: newRequest(t, "GET", "/foo/bar?c=d"),
},
{
rule: Rewrite{StripPathPrefix: "/prefix"},
input: newRequest(t, "GET", "/foo/bar"),
expect: newRequest(t, "GET", "/foo/bar"),
},
{
rule: Rewrite{StripPathPrefix: "/prefix"},
input: newRequest(t, "GET", "/prefix/foo/bar"),
expect: newRequest(t, "GET", "/foo/bar"),
},
{
rule: Rewrite{StripPathPrefix: "/prefix"},
input: newRequest(t, "GET", "/foo/prefix/bar"),
expect: newRequest(t, "GET", "/foo/prefix/bar"),
},
{
rule: Rewrite{StripPathSuffix: "/suffix"},
input: newRequest(t, "GET", "/foo/bar"),
expect: newRequest(t, "GET", "/foo/bar"),
},
{
rule: Rewrite{StripPathSuffix: "suffix"},
input: newRequest(t, "GET", "/foo/bar/suffix"),
expect: newRequest(t, "GET", "/foo/bar/"),
},
{
rule: Rewrite{StripPathSuffix: "/suffix"},
input: newRequest(t, "GET", "/foo/suffix/bar"),
expect: newRequest(t, "GET", "/foo/suffix/bar"),
},
{
rule: Rewrite{URISubstring: []replacer{{Find: "findme", Replace: "replaced"}}},
input: newRequest(t, "GET", "/foo/bar"),
expect: newRequest(t, "GET", "/foo/bar"),
},
{
rule: Rewrite{URISubstring: []replacer{{Find: "findme", Replace: "replaced"}}},
input: newRequest(t, "GET", "/foo/findme/bar"),
expect: newRequest(t, "GET", "/foo/replaced/bar"),
},
} {
// copy the original input just enough so that we can
// compare it after the rewrite to see if it changed
originalInput := &http.Request{
Method: tc.input.Method,
RequestURI: tc.input.RequestURI,
URL: &*tc.input.URL,
}
// populate the replacer just enough for our tests
repl.Set("http.request.uri", tc.input.RequestURI)
repl.Set("http.request.uri.path", tc.input.URL.Path)
repl.Set("http.request.uri.query", tc.input.URL.RawQuery)
changed := tc.rule.rewrite(tc.input, repl, nil)
if expected, actual := !reqEqual(originalInput, tc.input), changed; expected != actual {
t.Errorf("Test %d: Expected changed=%t but was %t", i, expected, actual)
}
if expected, actual := tc.expect.Method, tc.input.Method; expected != actual {
t.Errorf("Test %d: Expected Method='%s' but got '%s'", i, expected, actual)
}
if expected, actual := tc.expect.RequestURI, tc.input.RequestURI; expected != actual {
t.Errorf("Test %d: Expected RequestURI='%s' but got '%s'", i, expected, actual)
}
if expected, actual := tc.expect.URL.String(), tc.input.URL.String(); expected != actual {
t.Errorf("Test %d: Expected URL='%s' but got '%s'", i, expected, actual)
}
if expected, actual := tc.expect.URL.RequestURI(), tc.input.URL.RequestURI(); expected != actual {
t.Errorf("Test %d: Expected URL.RequestURI()='%s' but got '%s'", i, expected, actual)
}
if expected, actual := tc.expect.URL.Fragment, tc.input.URL.Fragment; expected != actual {
t.Errorf("Test %d: Expected URL.Fragment='%s' but got '%s'", i, expected, actual)
}
}
}
func newRequest(t *testing.T, method, uri string) *http.Request {
req, err := http.NewRequest(method, uri, nil)
if err != nil {
t.Fatalf("error creating request: %v", err)
}
req.RequestURI = req.URL.RequestURI() // simulate incoming request
return req
}
// reqEqual if r1 and r2 are equal enough for our purposes.
func reqEqual(r1, r2 *http.Request) bool {
if r1.Method != r2.Method {
return false
}
if r1.RequestURI != r2.RequestURI {
return false
}
if (r1.URL == nil && r2.URL != nil) || (r1.URL != nil && r2.URL == nil) {
return false
}
if r1.URL == nil && r2.URL == nil {
return true
}
return r1.URL.Scheme == r2.URL.Scheme &&
r1.URL.Host == r2.URL.Host &&
r1.URL.Path == r2.URL.Path &&
r1.URL.RawPath == r2.URL.RawPath &&
r1.URL.RawQuery == r2.URL.RawQuery &&
r1.URL.Fragment == r2.URL.Fragment
}
| modules/caddyhttp/rewrite/rewrite_test.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.0002812864549923688,
0.00017594483506400138,
0.0001647116878302768,
0.00016980226791929454,
0.000023752721972414292
] |
{
"id": 3,
"code_window": [
"\t\t\t \tsub1 arg1\n",
"\t\t\t \tsub2\n",
"\t\t\t }\n",
"\t\t\t foobar2 {\n",
"\t\t\t }`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\tassertNextBlock := func(shouldLoad bool, expectedCursor, expectedNesting int) {\n",
"\t\tif loaded := d.NextBlock(0); loaded != shouldLoad {\n",
"\t\t\tt.Errorf(\"NextBlock(): Should return %v but got %v\", shouldLoad, loaded)\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 147
} | // Copyright 2015 Matthew Holt and The Caddy 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 caddycmd
import (
"bytes"
"crypto/rand"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"os/exec"
"reflect"
"runtime"
"runtime/debug"
"sort"
"strings"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"go.uber.org/zap"
)
func cmdStart(fl Flags) (int, error) {
startCmdConfigFlag := fl.String("config")
startCmdConfigAdapterFlag := fl.String("adapter")
startCmdWatchFlag := fl.Bool("watch")
// open a listener to which the child process will connect when
// it is ready to confirm that it has successfully started
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return caddy.ExitCodeFailedStartup,
fmt.Errorf("opening listener for success confirmation: %v", err)
}
defer ln.Close()
// craft the command with a pingback address and with a
// pipe for its stdin, so we can tell it our confirmation
// code that we expect so that some random port scan at
// the most unfortunate time won't fool us into thinking
// the child succeeded (i.e. the alternative is to just
// wait for any connection on our listener, but better to
// ensure it's the process we're expecting - we can be
// sure by giving it some random bytes and having it echo
// them back to us)
cmd := exec.Command(os.Args[0], "run", "--pingback", ln.Addr().String())
if startCmdConfigFlag != "" {
cmd.Args = append(cmd.Args, "--config", startCmdConfigFlag)
}
if startCmdConfigAdapterFlag != "" {
cmd.Args = append(cmd.Args, "--adapter", startCmdConfigAdapterFlag)
}
if startCmdWatchFlag {
cmd.Args = append(cmd.Args, "--watch")
}
stdinpipe, err := cmd.StdinPipe()
if err != nil {
return caddy.ExitCodeFailedStartup,
fmt.Errorf("creating stdin pipe: %v", err)
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// generate the random bytes we'll send to the child process
expect := make([]byte, 32)
_, err = rand.Read(expect)
if err != nil {
return caddy.ExitCodeFailedStartup, fmt.Errorf("generating random confirmation bytes: %v", err)
}
// begin writing the confirmation bytes to the child's
// stdin; use a goroutine since the child hasn't been
// started yet, and writing synchronously would result
// in a deadlock
go func() {
stdinpipe.Write(expect)
stdinpipe.Close()
}()
// start the process
err = cmd.Start()
if err != nil {
return caddy.ExitCodeFailedStartup, fmt.Errorf("starting caddy process: %v", err)
}
// there are two ways we know we're done: either
// the process will connect to our listener, or
// it will exit with an error
success, exit := make(chan struct{}), make(chan error)
// in one goroutine, we await the success of the child process
go func() {
for {
conn, err := ln.Accept()
if err != nil {
if !strings.Contains(err.Error(), "use of closed network connection") {
log.Println(err)
}
break
}
err = handlePingbackConn(conn, expect)
if err == nil {
close(success)
break
}
log.Println(err)
}
}()
// in another goroutine, we await the failure of the child process
go func() {
err := cmd.Wait() // don't send on this line! Wait blocks, but send starts before it unblocks
exit <- err // sending on separate line ensures select won't trigger until after Wait unblocks
}()
// when one of the goroutines unblocks, we're done and can exit
select {
case <-success:
fmt.Printf("Successfully started Caddy (pid=%d) - Caddy is running in the background\n", cmd.Process.Pid)
case err := <-exit:
return caddy.ExitCodeFailedStartup,
fmt.Errorf("caddy process exited with error: %v", err)
}
return caddy.ExitCodeSuccess, nil
}
func cmdRun(fl Flags) (int, error) {
runCmdConfigFlag := fl.String("config")
runCmdConfigAdapterFlag := fl.String("adapter")
runCmdResumeFlag := fl.Bool("resume")
runCmdPrintEnvFlag := fl.Bool("environ")
runCmdWatchFlag := fl.Bool("watch")
runCmdPingbackFlag := fl.String("pingback")
// if we are supposed to print the environment, do that first
if runCmdPrintEnvFlag {
printEnvironment()
}
// TODO: This is TEMPORARY, until the RCs
moveStorage()
// load the config, depending on flags
var config []byte
var err error
if runCmdResumeFlag {
config, err = ioutil.ReadFile(caddy.ConfigAutosavePath)
if os.IsNotExist(err) {
// not a bad error; just can't resume if autosave file doesn't exist
caddy.Log().Info("no autosave file exists", zap.String("autosave_file", caddy.ConfigAutosavePath))
runCmdResumeFlag = false
} else if err != nil {
return caddy.ExitCodeFailedStartup, err
} else {
caddy.Log().Info("resuming from last configuration", zap.String("autosave_file", caddy.ConfigAutosavePath))
}
}
// we don't use 'else' here since this value might have been changed in 'if' block; i.e. not mutually exclusive
var configFile string
if !runCmdResumeFlag {
config, configFile, err = loadConfig(runCmdConfigFlag, runCmdConfigAdapterFlag)
if err != nil {
return caddy.ExitCodeFailedStartup, err
}
}
// run the initial config
err = caddy.Load(config, true)
if err != nil {
return caddy.ExitCodeFailedStartup, fmt.Errorf("loading initial config: %v", err)
}
caddy.Log().Info("serving initial configuration")
// if we are to report to another process the successful start
// of the server, do so now by echoing back contents of stdin
if runCmdPingbackFlag != "" {
confirmationBytes, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return caddy.ExitCodeFailedStartup,
fmt.Errorf("reading confirmation bytes from stdin: %v", err)
}
conn, err := net.Dial("tcp", runCmdPingbackFlag)
if err != nil {
return caddy.ExitCodeFailedStartup,
fmt.Errorf("dialing confirmation address: %v", err)
}
defer conn.Close()
_, err = conn.Write(confirmationBytes)
if err != nil {
return caddy.ExitCodeFailedStartup,
fmt.Errorf("writing confirmation bytes to %s: %v", runCmdPingbackFlag, err)
}
}
// if enabled, reload config file automatically on changes
// (this better only be used in dev!)
if runCmdWatchFlag {
go watchConfigFile(configFile, runCmdConfigAdapterFlag)
}
// warn if the environment does not provide enough information about the disk
hasXDG := os.Getenv("XDG_DATA_HOME") != "" &&
os.Getenv("XDG_CONFIG_HOME") != "" &&
os.Getenv("XDG_CACHE_HOME") != ""
switch runtime.GOOS {
case "windows":
if os.Getenv("HOME") == "" && os.Getenv("USERPROFILE") == "" && !hasXDG {
caddy.Log().Warn("neither HOME nor USERPROFILE environment variables are set - please fix; some assets might be stored in ./caddy")
}
case "plan9":
if os.Getenv("home") == "" && !hasXDG {
caddy.Log().Warn("$home environment variable is empty - please fix; some assets might be stored in ./caddy")
}
default:
if os.Getenv("HOME") == "" && !hasXDG {
caddy.Log().Warn("$HOME environment variable is empty - please fix; some assets might be stored in ./caddy")
}
}
select {}
}
func cmdStop(fl Flags) (int, error) {
stopCmdAddrFlag := fl.String("address")
adminAddr := caddy.DefaultAdminListen
if stopCmdAddrFlag != "" {
adminAddr = stopCmdAddrFlag
}
stopEndpoint := fmt.Sprintf("http://%s/stop", adminAddr)
req, err := http.NewRequest(http.MethodPost, stopEndpoint, nil)
if err != nil {
return caddy.ExitCodeFailedStartup, fmt.Errorf("making request: %v", err)
}
req.Header.Set("Origin", adminAddr)
err = apiRequest(req)
if err != nil {
caddy.Log().Warn("failed using API to stop instance",
zap.String("endpoint", stopEndpoint),
zap.Error(err),
)
return caddy.ExitCodeFailedStartup, err
}
return caddy.ExitCodeSuccess, nil
}
func cmdReload(fl Flags) (int, error) {
reloadCmdConfigFlag := fl.String("config")
reloadCmdConfigAdapterFlag := fl.String("adapter")
reloadCmdAddrFlag := fl.String("address")
// get the config in caddy's native format
config, configFile, err := loadConfig(reloadCmdConfigFlag, reloadCmdConfigAdapterFlag)
if err != nil {
return caddy.ExitCodeFailedStartup, err
}
if configFile == "" {
return caddy.ExitCodeFailedStartup, fmt.Errorf("no config file to load")
}
// get the address of the admin listener and craft endpoint URL
adminAddr := reloadCmdAddrFlag
if adminAddr == "" && len(config) > 0 {
var tmpStruct struct {
Admin caddy.AdminConfig `json:"admin"`
}
err = json.Unmarshal(config, &tmpStruct)
if err != nil {
return caddy.ExitCodeFailedStartup,
fmt.Errorf("unmarshaling admin listener address from config: %v", err)
}
adminAddr = tmpStruct.Admin.Listen
}
if adminAddr == "" {
adminAddr = caddy.DefaultAdminListen
}
loadEndpoint := fmt.Sprintf("http://%s/load", adminAddr)
// prepare the request to update the configuration
req, err := http.NewRequest(http.MethodPost, loadEndpoint, bytes.NewReader(config))
if err != nil {
return caddy.ExitCodeFailedStartup, fmt.Errorf("making request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Origin", adminAddr)
err = apiRequest(req)
if err != nil {
return caddy.ExitCodeFailedStartup, fmt.Errorf("sending configuration to instance: %v", err)
}
return caddy.ExitCodeSuccess, nil
}
func cmdVersion(_ Flags) (int, error) {
goModule := caddy.GoModule()
fmt.Print(goModule.Version)
if goModule.Sum != "" {
// a build with a known version will also have a checksum
fmt.Printf(" %s", goModule.Sum)
}
if goModule.Replace != nil {
fmt.Printf(" => %s", goModule.Replace.Path)
if goModule.Replace.Version != "" {
fmt.Printf(" %s", goModule.Replace.Version)
}
}
fmt.Println()
return caddy.ExitCodeSuccess, nil
}
func cmdBuildInfo(fl Flags) (int, error) {
bi, ok := debug.ReadBuildInfo()
if !ok {
return caddy.ExitCodeFailedStartup, fmt.Errorf("no build information")
}
fmt.Printf("path: %s\n", bi.Path)
fmt.Printf("main: %s %s %s\n", bi.Main.Path, bi.Main.Version, bi.Main.Sum)
fmt.Println("dependencies:")
for _, goMod := range bi.Deps {
fmt.Printf("%s %s %s", goMod.Path, goMod.Version, goMod.Sum)
if goMod.Replace != nil {
fmt.Printf(" => %s %s %s", goMod.Replace.Path, goMod.Replace.Version, goMod.Replace.Sum)
}
fmt.Println()
}
return caddy.ExitCodeSuccess, nil
}
func cmdListModules(fl Flags) (int, error) {
versions := fl.Bool("versions")
bi, ok := debug.ReadBuildInfo()
if !ok || !versions {
// if there's no build information,
// just print out the modules
for _, m := range caddy.Modules() {
fmt.Println(m)
}
return caddy.ExitCodeSuccess, nil
}
for _, modID := range caddy.Modules() {
modInfo, err := caddy.GetModule(modID)
if err != nil {
// that's weird
fmt.Println(modID)
continue
}
// to get the Caddy plugin's version info, we need to know
// the package that the Caddy module's value comes from; we
// can use reflection but we need a non-pointer value (I'm
// not sure why), and since New() should return a pointer
// value, we need to dereference it first
iface := interface{}(modInfo.New())
if rv := reflect.ValueOf(iface); rv.Kind() == reflect.Ptr {
iface = reflect.New(reflect.TypeOf(iface).Elem()).Elem().Interface()
}
modPkgPath := reflect.TypeOf(iface).PkgPath()
// now we find the Go module that the Caddy module's package
// belongs to; we assume the Caddy module package path will
// be prefixed by its Go module path, and we will choose the
// longest matching prefix in case there are nested modules
var matched *debug.Module
for _, dep := range bi.Deps {
if strings.HasPrefix(modPkgPath, dep.Path) {
if matched == nil || len(dep.Path) > len(matched.Path) {
matched = dep
}
}
}
// if we could find no matching module, just print out
// the module ID instead
if matched == nil {
fmt.Println(modID)
continue
}
fmt.Printf("%s %s\n", modID, matched.Version)
}
return caddy.ExitCodeSuccess, nil
}
func cmdEnviron(_ Flags) (int, error) {
printEnvironment()
return caddy.ExitCodeSuccess, nil
}
func cmdAdaptConfig(fl Flags) (int, error) {
adaptCmdInputFlag := fl.String("config")
adaptCmdAdapterFlag := fl.String("adapter")
adaptCmdPrettyFlag := fl.Bool("pretty")
adaptCmdValidateFlag := fl.Bool("validate")
// if no input file was specified, try a default
// Caddyfile if the Caddyfile adapter is plugged in
if adaptCmdInputFlag == "" && caddyconfig.GetAdapter("caddyfile") != nil {
_, err := os.Stat("Caddyfile")
if err == nil {
// default Caddyfile exists
adaptCmdInputFlag = "Caddyfile"
caddy.Log().Info("using adjacent Caddyfile")
} else if !os.IsNotExist(err) {
// default Caddyfile exists, but error accessing it
return caddy.ExitCodeFailedStartup, fmt.Errorf("accessing default Caddyfile: %v", err)
}
}
if adaptCmdInputFlag == "" {
return caddy.ExitCodeFailedStartup,
fmt.Errorf("input file required when there is no Caddyfile in current directory (use --config flag)")
}
if adaptCmdAdapterFlag == "" {
return caddy.ExitCodeFailedStartup,
fmt.Errorf("adapter name is required (use --adapt flag or leave unspecified for default)")
}
cfgAdapter := caddyconfig.GetAdapter(adaptCmdAdapterFlag)
if cfgAdapter == nil {
return caddy.ExitCodeFailedStartup,
fmt.Errorf("unrecognized config adapter: %s", adaptCmdAdapterFlag)
}
input, err := ioutil.ReadFile(adaptCmdInputFlag)
if err != nil {
return caddy.ExitCodeFailedStartup,
fmt.Errorf("reading input file: %v", err)
}
opts := make(map[string]interface{})
if adaptCmdPrettyFlag {
opts["pretty"] = "true"
}
opts["filename"] = adaptCmdInputFlag
adaptedConfig, warnings, err := cfgAdapter.Adapt(input, opts)
if err != nil {
return caddy.ExitCodeFailedStartup, err
}
// print warnings to stderr
for _, warn := range warnings {
msg := warn.Message
if warn.Directive != "" {
msg = fmt.Sprintf("%s: %s", warn.Directive, warn.Message)
}
fmt.Fprintf(os.Stderr, "[WARNING][%s] %s:%d: %s\n", adaptCmdAdapterFlag, warn.File, warn.Line, msg)
}
// print result to stdout
fmt.Println(string(adaptedConfig))
// validate output if requested
if adaptCmdValidateFlag {
var cfg *caddy.Config
err = json.Unmarshal(adaptedConfig, &cfg)
if err != nil {
return caddy.ExitCodeFailedStartup, fmt.Errorf("decoding config: %v", err)
}
err = caddy.Validate(cfg)
if err != nil {
return caddy.ExitCodeFailedStartup, fmt.Errorf("validation: %v", err)
}
}
return caddy.ExitCodeSuccess, nil
}
func cmdValidateConfig(fl Flags) (int, error) {
validateCmdConfigFlag := fl.String("config")
validateCmdAdapterFlag := fl.String("adapter")
input, _, err := loadConfig(validateCmdConfigFlag, validateCmdAdapterFlag)
if err != nil {
return caddy.ExitCodeFailedStartup, err
}
input = caddy.RemoveMetaFields(input)
var cfg *caddy.Config
err = json.Unmarshal(input, &cfg)
if err != nil {
return caddy.ExitCodeFailedStartup, fmt.Errorf("decoding config: %v", err)
}
err = caddy.Validate(cfg)
if err != nil {
return caddy.ExitCodeFailedStartup, err
}
fmt.Println("Valid configuration")
return caddy.ExitCodeSuccess, nil
}
func cmdFmt(fl Flags) (int, error) {
formatCmdConfigFile := fl.Arg(0)
if formatCmdConfigFile == "" {
formatCmdConfigFile = "Caddyfile"
}
overwrite := fl.Bool("overwrite")
input, err := ioutil.ReadFile(formatCmdConfigFile)
if err != nil {
return caddy.ExitCodeFailedStartup,
fmt.Errorf("reading input file: %v", err)
}
output := caddyfile.Format(input)
if overwrite {
err = ioutil.WriteFile(formatCmdConfigFile, output, 0644)
if err != nil {
return caddy.ExitCodeFailedStartup, nil
}
} else {
fmt.Print(string(output))
}
return caddy.ExitCodeSuccess, nil
}
func cmdHelp(fl Flags) (int, error) {
const fullDocs = `Full documentation is available at:
https://caddyserver.com/docs/command-line`
args := fl.Args()
if len(args) == 0 {
s := `Caddy is an extensible server platform.
usage:
caddy <command> [<args...>]
commands:
`
keys := make([]string, 0, len(commands))
for k := range commands {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
cmd := commands[k]
short := strings.TrimSuffix(cmd.Short, ".")
s += fmt.Sprintf(" %-15s %s\n", cmd.Name, short)
}
s += "\nUse 'caddy help <command>' for more information about a command.\n"
s += "\n" + fullDocs + "\n"
fmt.Print(s)
return caddy.ExitCodeSuccess, nil
} else if len(args) > 1 {
return caddy.ExitCodeFailedStartup, fmt.Errorf("can only give help with one command")
}
subcommand, ok := commands[args[0]]
if !ok {
return caddy.ExitCodeFailedStartup, fmt.Errorf("unknown command: %s", args[0])
}
helpText := strings.TrimSpace(subcommand.Long)
if helpText == "" {
helpText = subcommand.Short
if !strings.HasSuffix(helpText, ".") {
helpText += "."
}
}
result := fmt.Sprintf("%s\n\nusage:\n caddy %s %s\n",
helpText,
subcommand.Name,
strings.TrimSpace(subcommand.Usage),
)
if help := flagHelp(subcommand.Flags); help != "" {
result += fmt.Sprintf("\nflags:\n%s", help)
}
result += "\n" + fullDocs + "\n"
fmt.Print(result)
return caddy.ExitCodeSuccess, nil
}
func apiRequest(req *http.Request) error {
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("performing request: %v", err)
}
defer resp.Body.Close()
// if it didn't work, let the user know
if resp.StatusCode >= 400 {
respBody, err := ioutil.ReadAll(io.LimitReader(resp.Body, 1024*10))
if err != nil {
return fmt.Errorf("HTTP %d: reading error message: %v", resp.StatusCode, err)
}
return fmt.Errorf("caddy responded with error: HTTP %d: %s", resp.StatusCode, respBody)
}
return nil
}
| cmd/commandfuncs.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.0018266532570123672,
0.00026865498512052,
0.00016004341887310147,
0.0001716800034046173,
0.00035108780139125884
] |
{
"id": 4,
"code_window": [
"\tinput := `dir1 arg1 arg2 arg3\n",
"\t\t\t dir2 arg4 arg5\n",
"\t\t\t dir3 arg6 arg7\n",
"\t\t\t dir4`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\td.Next() // dir1\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 177
} | // Copyright 2015 Matthew Holt and The Caddy 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 caddyfile
import (
"io"
"log"
"reflect"
"strings"
"testing"
)
func TestDispenser_Val_Next(t *testing.T) {
input := `host:port
dir1 arg1
dir2 arg2 arg3
dir3`
d := newTestDispenser(input)
if val := d.Val(); val != "" {
t.Fatalf("Val(): Should return empty string when no token loaded; got '%s'", val)
}
assertNext := func(shouldLoad bool, expectedCursor int, expectedVal string) {
if loaded := d.Next(); loaded != shouldLoad {
t.Errorf("Next(): Expected %v but got %v instead (val '%s')", shouldLoad, loaded, d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("Expected cursor to be %d, but was %d", expectedCursor, d.cursor)
}
if d.nesting != 0 {
t.Errorf("Nesting should be 0, was %d instead", d.nesting)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNext(true, 0, "host:port")
assertNext(true, 1, "dir1")
assertNext(true, 2, "arg1")
assertNext(true, 3, "dir2")
assertNext(true, 4, "arg2")
assertNext(true, 5, "arg3")
assertNext(true, 6, "dir3")
// Note: This next test simply asserts existing behavior.
// If desired, we may wish to empty the token value after
// reading past the EOF. Open an issue if you want this change.
assertNext(false, 6, "dir3")
}
func TestDispenser_NextArg(t *testing.T) {
input := `dir1 arg1
dir2 arg2 arg3
dir3`
d := newTestDispenser(input)
assertNext := func(shouldLoad bool, expectedVal string, expectedCursor int) {
if d.Next() != shouldLoad {
t.Errorf("Next(): Should load token but got false instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("Next(): Expected cursor to be at %d, but it was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNextArg := func(expectedVal string, loadAnother bool, expectedCursor int) {
if !d.NextArg() {
t.Error("NextArg(): Should load next argument but got false instead")
}
if d.cursor != expectedCursor {
t.Errorf("NextArg(): Expected cursor to be at %d, but it was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
if !loadAnother {
if d.NextArg() {
t.Fatalf("NextArg(): Should NOT load another argument, but got true instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("NextArg(): Expected cursor to remain at %d, but it was %d", expectedCursor, d.cursor)
}
}
}
assertNext(true, "dir1", 0)
assertNextArg("arg1", false, 1)
assertNext(true, "dir2", 2)
assertNextArg("arg2", true, 3)
assertNextArg("arg3", false, 4)
assertNext(true, "dir3", 5)
assertNext(false, "dir3", 5)
}
func TestDispenser_NextLine(t *testing.T) {
input := `host:port
dir1 arg1
dir2 arg2 arg3`
d := newTestDispenser(input)
assertNextLine := func(shouldLoad bool, expectedVal string, expectedCursor int) {
if d.NextLine() != shouldLoad {
t.Errorf("NextLine(): Should load token but got false instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("NextLine(): Expected cursor to be %d, instead was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNextLine(true, "host:port", 0)
assertNextLine(true, "dir1", 1)
assertNextLine(false, "dir1", 1)
d.Next() // arg1
assertNextLine(true, "dir2", 3)
assertNextLine(false, "dir2", 3)
d.Next() // arg2
assertNextLine(false, "arg2", 4)
d.Next() // arg3
assertNextLine(false, "arg3", 5)
}
func TestDispenser_NextBlock(t *testing.T) {
input := `foobar1 {
sub1 arg1
sub2
}
foobar2 {
}`
d := newTestDispenser(input)
assertNextBlock := func(shouldLoad bool, expectedCursor, expectedNesting int) {
if loaded := d.NextBlock(0); loaded != shouldLoad {
t.Errorf("NextBlock(): Should return %v but got %v", shouldLoad, loaded)
}
if d.cursor != expectedCursor {
t.Errorf("NextBlock(): Expected cursor to be %d, was %d", expectedCursor, d.cursor)
}
if d.nesting != expectedNesting {
t.Errorf("NextBlock(): Nesting should be %d, not %d", expectedNesting, d.nesting)
}
}
assertNextBlock(false, -1, 0)
d.Next() // foobar1
assertNextBlock(true, 2, 1)
assertNextBlock(true, 3, 1)
assertNextBlock(true, 4, 1)
assertNextBlock(false, 5, 0)
d.Next() // foobar2
assertNextBlock(false, 8, 0) // empty block is as if it didn't exist
}
func TestDispenser_Args(t *testing.T) {
var s1, s2, s3 string
input := `dir1 arg1 arg2 arg3
dir2 arg4 arg5
dir3 arg6 arg7
dir4`
d := newTestDispenser(input)
d.Next() // dir1
// As many strings as arguments
if all := d.Args(&s1, &s2, &s3); !all {
t.Error("Args(): Expected true, got false")
}
if s1 != "arg1" {
t.Errorf("Args(): Expected s1 to be 'arg1', got '%s'", s1)
}
if s2 != "arg2" {
t.Errorf("Args(): Expected s2 to be 'arg2', got '%s'", s2)
}
if s3 != "arg3" {
t.Errorf("Args(): Expected s3 to be 'arg3', got '%s'", s3)
}
d.Next() // dir2
// More strings than arguments
if all := d.Args(&s1, &s2, &s3); all {
t.Error("Args(): Expected false, got true")
}
if s1 != "arg4" {
t.Errorf("Args(): Expected s1 to be 'arg4', got '%s'", s1)
}
if s2 != "arg5" {
t.Errorf("Args(): Expected s2 to be 'arg5', got '%s'", s2)
}
if s3 != "arg3" {
t.Errorf("Args(): Expected s3 to be unchanged ('arg3'), instead got '%s'", s3)
}
// (quick cursor check just for kicks and giggles)
if d.cursor != 6 {
t.Errorf("Cursor should be 6, but is %d", d.cursor)
}
d.Next() // dir3
// More arguments than strings
if all := d.Args(&s1); !all {
t.Error("Args(): Expected true, got false")
}
if s1 != "arg6" {
t.Errorf("Args(): Expected s1 to be 'arg6', got '%s'", s1)
}
d.Next() // dir4
// No arguments or strings
if all := d.Args(); !all {
t.Error("Args(): Expected true, got false")
}
// No arguments but at least one string
if all := d.Args(&s1); all {
t.Error("Args(): Expected false, got true")
}
}
func TestDispenser_RemainingArgs(t *testing.T) {
input := `dir1 arg1 arg2 arg3
dir2 arg4 arg5
dir3 arg6 { arg7
dir4`
d := newTestDispenser(input)
d.Next() // dir1
args := d.RemainingArgs()
if expected := []string{"arg1", "arg2", "arg3"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // dir2
args = d.RemainingArgs()
if expected := []string{"arg4", "arg5"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // dir3
args = d.RemainingArgs()
if expected := []string{"arg6"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // {
d.Next() // arg7
d.Next() // dir4
args = d.RemainingArgs()
if len(args) != 0 {
t.Errorf("RemainingArgs(): Expected %v, got %v", []string{}, args)
}
}
func TestDispenser_ArgErr_Err(t *testing.T) {
input := `dir1 {
}
dir2 arg1 arg2`
d := newTestDispenser(input)
d.cursor = 1 // {
if err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), "{") {
t.Errorf("ArgErr(): Expected an error message with { in it, but got '%v'", err)
}
d.cursor = 5 // arg2
if err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), "arg2") {
t.Errorf("ArgErr(): Expected an error message with 'arg2' in it; got '%v'", err)
}
err := d.Err("foobar")
if err == nil {
t.Fatalf("Err(): Expected an error, got nil")
}
if !strings.Contains(err.Error(), "Testfile:3") {
t.Errorf("Expected error message with filename:line in it; got '%v'", err)
}
if !strings.Contains(err.Error(), "foobar") {
t.Errorf("Expected error message with custom message in it ('foobar'); got '%v'", err)
}
}
func newTestDispenser(input string) *Dispenser {
tokens, err := allTokens("Testfile", []byte(input))
if err != nil && err != io.EOF {
log.Fatalf("getting all tokens from input: %v", err)
}
return NewDispenser(tokens)
}
| caddyconfig/caddyfile/dispenser_test.go | 1 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.9979797005653381,
0.48943641781806946,
0.00016753256204538047,
0.3777558207511902,
0.468761146068573
] |
{
"id": 4,
"code_window": [
"\tinput := `dir1 arg1 arg2 arg3\n",
"\t\t\t dir2 arg4 arg5\n",
"\t\t\t dir3 arg6 arg7\n",
"\t\t\t dir4`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\td.Next() // dir1\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 177
} | // Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp
import (
"bytes"
"encoding/json"
"io"
weakrand "math/rand"
"net"
"net/http"
"strconv"
"time"
"github.com/caddyserver/caddy/v2"
)
func init() {
weakrand.Seed(time.Now().UnixNano())
err := caddy.RegisterModule(tlsPlaceholderWrapper{})
if err != nil {
caddy.Log().Fatal(err.Error())
}
}
// RequestMatcher is a type that can match to a request.
// A route matcher MUST NOT modify the request, with the
// only exception being its context.
type RequestMatcher interface {
Match(*http.Request) bool
}
// Handler is like http.Handler except ServeHTTP may return an error.
//
// If any handler encounters an error, it should be returned for proper
// handling. Return values should be propagated down the middleware chain
// by returning it unchanged. Returned errors should not be re-wrapped
// if they are already HandlerError values.
type Handler interface {
ServeHTTP(http.ResponseWriter, *http.Request) error
}
// HandlerFunc is a convenience type like http.HandlerFunc.
type HandlerFunc func(http.ResponseWriter, *http.Request) error
// ServeHTTP implements the Handler interface.
func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
return f(w, r)
}
// Middleware chains one Handler to the next by being passed
// the next Handler in the chain.
type Middleware func(Handler) Handler
// MiddlewareHandler is like Handler except it takes as a third
// argument the next handler in the chain. The next handler will
// never be nil, but may be a no-op handler if this is the last
// handler in the chain. Handlers which act as middleware should
// call the next handler's ServeHTTP method so as to propagate
// the request down the chain properly. Handlers which act as
// responders (content origins) need not invoke the next handler,
// since the last handler in the chain should be the first to
// write the response.
type MiddlewareHandler interface {
ServeHTTP(http.ResponseWriter, *http.Request, Handler) error
}
// emptyHandler is used as a no-op handler.
var emptyHandler Handler = HandlerFunc(func(http.ResponseWriter, *http.Request) error { return nil })
// An implicit suffix middleware that, if reached, sets the StatusCode to the
// error stored in the ErrorCtxKey. This is to prevent situations where the
// Error chain does not actually handle the error (for instance, it matches only
// on some errors). See #3053
var errorEmptyHandler Handler = HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
httpError := r.Context().Value(ErrorCtxKey)
if handlerError, ok := httpError.(HandlerError); ok {
w.WriteHeader(handlerError.StatusCode)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
return nil
})
// WeakString is a type that unmarshals any JSON value
// as a string literal, with the following exceptions:
//
// 1. actual string values are decoded as strings; and
// 2. null is decoded as empty string;
//
// and provides methods for getting the value as various
// primitive types. However, using this type removes any
// type safety as far as deserializing JSON is concerned.
type WeakString string
// UnmarshalJSON satisfies json.Unmarshaler according to
// this type's documentation.
func (ws *WeakString) UnmarshalJSON(b []byte) error {
if len(b) == 0 {
return io.EOF
}
if b[0] == byte('"') && b[len(b)-1] == byte('"') {
var s string
err := json.Unmarshal(b, &s)
if err != nil {
return err
}
*ws = WeakString(s)
return nil
}
if bytes.Equal(b, []byte("null")) {
return nil
}
*ws = WeakString(b)
return nil
}
// MarshalJSON marshals was a boolean if true or false,
// a number if an integer, or a string otherwise.
func (ws WeakString) MarshalJSON() ([]byte, error) {
if ws == "true" {
return []byte("true"), nil
}
if ws == "false" {
return []byte("false"), nil
}
if num, err := strconv.Atoi(string(ws)); err == nil {
return json.Marshal(num)
}
return json.Marshal(string(ws))
}
// Int returns ws as an integer. If ws is not an
// integer, 0 is returned.
func (ws WeakString) Int() int {
num, _ := strconv.Atoi(string(ws))
return num
}
// Float64 returns ws as a float64. If ws is not a
// float value, the zero value is returned.
func (ws WeakString) Float64() float64 {
num, _ := strconv.ParseFloat(string(ws), 64)
return num
}
// Bool returns ws as a boolean. If ws is not a
// boolean, false is returned.
func (ws WeakString) Bool() bool {
return string(ws) == "true"
}
// String returns ws as a string.
func (ws WeakString) String() string {
return string(ws)
}
// CopyHeader copies HTTP headers by completely
// replacing dest with src. (This allows deletions
// to be propagated, assuming src started as a
// consistent copy of dest.)
func CopyHeader(dest, src http.Header) {
for field := range dest {
delete(dest, field)
}
for field, val := range src {
dest[field] = val
}
}
// StatusCodeMatches returns true if a real HTTP status code matches
// the configured status code, which may be either a real HTTP status
// code or an integer representing a class of codes (e.g. 4 for all
// 4xx statuses).
func StatusCodeMatches(actual, configured int) bool {
if actual == configured {
return true
}
if configured < 100 &&
actual >= configured*100 &&
actual < (configured+1)*100 {
return true
}
return false
}
// tlsPlaceholderWrapper is a no-op listener wrapper that marks
// where the TLS listener should be in a chain of listener wrappers.
// It should only be used if another listener wrapper must be placed
// in front of the TLS handshake.
type tlsPlaceholderWrapper struct{}
func (tlsPlaceholderWrapper) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "caddy.listeners.tls",
New: func() caddy.Module { return new(tlsPlaceholderWrapper) },
}
}
func (tlsPlaceholderWrapper) WrapListener(ln net.Listener) net.Listener { return ln }
const (
// DefaultHTTPPort is the default port for HTTP.
DefaultHTTPPort = 80
// DefaultHTTPSPort is the default port for HTTPS.
DefaultHTTPSPort = 443
)
// Interface guard
var _ caddy.ListenerWrapper = (*tlsPlaceholderWrapper)(nil)
| modules/caddyhttp/caddyhttp.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.001639421796426177,
0.00024549299268983305,
0.00016542816592846066,
0.00017259657033719122,
0.0002983807062264532
] |
{
"id": 4,
"code_window": [
"\tinput := `dir1 arg1 arg2 arg3\n",
"\t\t\t dir2 arg4 arg5\n",
"\t\t\t dir3 arg6 arg7\n",
"\t\t\t dir4`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\td.Next() // dir1\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 177
} | dir2 arg1 arg2
dir3 | caddyconfig/caddyfile/testdata/import_test1.txt | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.0047867801040410995,
0.0047867801040410995,
0.0047867801040410995,
0.0047867801040410995,
0
] |
{
"id": 4,
"code_window": [
"\tinput := `dir1 arg1 arg2 arg3\n",
"\t\t\t dir2 arg4 arg5\n",
"\t\t\t dir3 arg6 arg7\n",
"\t\t\t dir4`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\td.Next() // dir1\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 177
} | package standard
import (
// standard Caddy HTTP app modules
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/caddyauth"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode/gzip"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode/zstd"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/fileserver"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/requestbody"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy/fastcgi"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/templates"
)
| modules/caddyhttp/standard/imports.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.00016557445633225143,
0.00016274891095235944,
0.00015992336557246745,
0.00016274891095235944,
0.0000028255453798919916
] |
{
"id": 5,
"code_window": [
"func TestDispenser_RemainingArgs(t *testing.T) {\n",
"\tinput := `dir1 arg1 arg2 arg3\n",
"\t\t\t dir2 arg4 arg5\n",
"\t\t\t dir3 arg6 { arg7\n",
"\t\t\t dir4`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\td.Next() // dir1\n",
"\n",
"\targs := d.RemainingArgs()\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 244
} | // Copyright 2015 Matthew Holt and The Caddy 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 caddyfile
import (
"io"
"log"
"reflect"
"strings"
"testing"
)
func TestDispenser_Val_Next(t *testing.T) {
input := `host:port
dir1 arg1
dir2 arg2 arg3
dir3`
d := newTestDispenser(input)
if val := d.Val(); val != "" {
t.Fatalf("Val(): Should return empty string when no token loaded; got '%s'", val)
}
assertNext := func(shouldLoad bool, expectedCursor int, expectedVal string) {
if loaded := d.Next(); loaded != shouldLoad {
t.Errorf("Next(): Expected %v but got %v instead (val '%s')", shouldLoad, loaded, d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("Expected cursor to be %d, but was %d", expectedCursor, d.cursor)
}
if d.nesting != 0 {
t.Errorf("Nesting should be 0, was %d instead", d.nesting)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNext(true, 0, "host:port")
assertNext(true, 1, "dir1")
assertNext(true, 2, "arg1")
assertNext(true, 3, "dir2")
assertNext(true, 4, "arg2")
assertNext(true, 5, "arg3")
assertNext(true, 6, "dir3")
// Note: This next test simply asserts existing behavior.
// If desired, we may wish to empty the token value after
// reading past the EOF. Open an issue if you want this change.
assertNext(false, 6, "dir3")
}
func TestDispenser_NextArg(t *testing.T) {
input := `dir1 arg1
dir2 arg2 arg3
dir3`
d := newTestDispenser(input)
assertNext := func(shouldLoad bool, expectedVal string, expectedCursor int) {
if d.Next() != shouldLoad {
t.Errorf("Next(): Should load token but got false instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("Next(): Expected cursor to be at %d, but it was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNextArg := func(expectedVal string, loadAnother bool, expectedCursor int) {
if !d.NextArg() {
t.Error("NextArg(): Should load next argument but got false instead")
}
if d.cursor != expectedCursor {
t.Errorf("NextArg(): Expected cursor to be at %d, but it was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
if !loadAnother {
if d.NextArg() {
t.Fatalf("NextArg(): Should NOT load another argument, but got true instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("NextArg(): Expected cursor to remain at %d, but it was %d", expectedCursor, d.cursor)
}
}
}
assertNext(true, "dir1", 0)
assertNextArg("arg1", false, 1)
assertNext(true, "dir2", 2)
assertNextArg("arg2", true, 3)
assertNextArg("arg3", false, 4)
assertNext(true, "dir3", 5)
assertNext(false, "dir3", 5)
}
func TestDispenser_NextLine(t *testing.T) {
input := `host:port
dir1 arg1
dir2 arg2 arg3`
d := newTestDispenser(input)
assertNextLine := func(shouldLoad bool, expectedVal string, expectedCursor int) {
if d.NextLine() != shouldLoad {
t.Errorf("NextLine(): Should load token but got false instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("NextLine(): Expected cursor to be %d, instead was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNextLine(true, "host:port", 0)
assertNextLine(true, "dir1", 1)
assertNextLine(false, "dir1", 1)
d.Next() // arg1
assertNextLine(true, "dir2", 3)
assertNextLine(false, "dir2", 3)
d.Next() // arg2
assertNextLine(false, "arg2", 4)
d.Next() // arg3
assertNextLine(false, "arg3", 5)
}
func TestDispenser_NextBlock(t *testing.T) {
input := `foobar1 {
sub1 arg1
sub2
}
foobar2 {
}`
d := newTestDispenser(input)
assertNextBlock := func(shouldLoad bool, expectedCursor, expectedNesting int) {
if loaded := d.NextBlock(0); loaded != shouldLoad {
t.Errorf("NextBlock(): Should return %v but got %v", shouldLoad, loaded)
}
if d.cursor != expectedCursor {
t.Errorf("NextBlock(): Expected cursor to be %d, was %d", expectedCursor, d.cursor)
}
if d.nesting != expectedNesting {
t.Errorf("NextBlock(): Nesting should be %d, not %d", expectedNesting, d.nesting)
}
}
assertNextBlock(false, -1, 0)
d.Next() // foobar1
assertNextBlock(true, 2, 1)
assertNextBlock(true, 3, 1)
assertNextBlock(true, 4, 1)
assertNextBlock(false, 5, 0)
d.Next() // foobar2
assertNextBlock(false, 8, 0) // empty block is as if it didn't exist
}
func TestDispenser_Args(t *testing.T) {
var s1, s2, s3 string
input := `dir1 arg1 arg2 arg3
dir2 arg4 arg5
dir3 arg6 arg7
dir4`
d := newTestDispenser(input)
d.Next() // dir1
// As many strings as arguments
if all := d.Args(&s1, &s2, &s3); !all {
t.Error("Args(): Expected true, got false")
}
if s1 != "arg1" {
t.Errorf("Args(): Expected s1 to be 'arg1', got '%s'", s1)
}
if s2 != "arg2" {
t.Errorf("Args(): Expected s2 to be 'arg2', got '%s'", s2)
}
if s3 != "arg3" {
t.Errorf("Args(): Expected s3 to be 'arg3', got '%s'", s3)
}
d.Next() // dir2
// More strings than arguments
if all := d.Args(&s1, &s2, &s3); all {
t.Error("Args(): Expected false, got true")
}
if s1 != "arg4" {
t.Errorf("Args(): Expected s1 to be 'arg4', got '%s'", s1)
}
if s2 != "arg5" {
t.Errorf("Args(): Expected s2 to be 'arg5', got '%s'", s2)
}
if s3 != "arg3" {
t.Errorf("Args(): Expected s3 to be unchanged ('arg3'), instead got '%s'", s3)
}
// (quick cursor check just for kicks and giggles)
if d.cursor != 6 {
t.Errorf("Cursor should be 6, but is %d", d.cursor)
}
d.Next() // dir3
// More arguments than strings
if all := d.Args(&s1); !all {
t.Error("Args(): Expected true, got false")
}
if s1 != "arg6" {
t.Errorf("Args(): Expected s1 to be 'arg6', got '%s'", s1)
}
d.Next() // dir4
// No arguments or strings
if all := d.Args(); !all {
t.Error("Args(): Expected true, got false")
}
// No arguments but at least one string
if all := d.Args(&s1); all {
t.Error("Args(): Expected false, got true")
}
}
func TestDispenser_RemainingArgs(t *testing.T) {
input := `dir1 arg1 arg2 arg3
dir2 arg4 arg5
dir3 arg6 { arg7
dir4`
d := newTestDispenser(input)
d.Next() // dir1
args := d.RemainingArgs()
if expected := []string{"arg1", "arg2", "arg3"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // dir2
args = d.RemainingArgs()
if expected := []string{"arg4", "arg5"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // dir3
args = d.RemainingArgs()
if expected := []string{"arg6"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // {
d.Next() // arg7
d.Next() // dir4
args = d.RemainingArgs()
if len(args) != 0 {
t.Errorf("RemainingArgs(): Expected %v, got %v", []string{}, args)
}
}
func TestDispenser_ArgErr_Err(t *testing.T) {
input := `dir1 {
}
dir2 arg1 arg2`
d := newTestDispenser(input)
d.cursor = 1 // {
if err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), "{") {
t.Errorf("ArgErr(): Expected an error message with { in it, but got '%v'", err)
}
d.cursor = 5 // arg2
if err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), "arg2") {
t.Errorf("ArgErr(): Expected an error message with 'arg2' in it; got '%v'", err)
}
err := d.Err("foobar")
if err == nil {
t.Fatalf("Err(): Expected an error, got nil")
}
if !strings.Contains(err.Error(), "Testfile:3") {
t.Errorf("Expected error message with filename:line in it; got '%v'", err)
}
if !strings.Contains(err.Error(), "foobar") {
t.Errorf("Expected error message with custom message in it ('foobar'); got '%v'", err)
}
}
func newTestDispenser(input string) *Dispenser {
tokens, err := allTokens("Testfile", []byte(input))
if err != nil && err != io.EOF {
log.Fatalf("getting all tokens from input: %v", err)
}
return NewDispenser(tokens)
}
| caddyconfig/caddyfile/dispenser_test.go | 1 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.9973378777503967,
0.5270541310310364,
0.00016707615577615798,
0.8483844995498657,
0.4731508195400238
] |
{
"id": 5,
"code_window": [
"func TestDispenser_RemainingArgs(t *testing.T) {\n",
"\tinput := `dir1 arg1 arg2 arg3\n",
"\t\t\t dir2 arg4 arg5\n",
"\t\t\t dir3 arg6 { arg7\n",
"\t\t\t dir4`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\td.Next() // dir1\n",
"\n",
"\targs := d.RemainingArgs()\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 244
} | // Copyright 2015 Matthew Holt and The Caddy 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 logging
import (
"net"
"github.com/caddyserver/caddy/v2"
"go.uber.org/zap/zapcore"
)
func init() {
caddy.RegisterModule(DeleteFilter{})
caddy.RegisterModule(IPMaskFilter{})
}
// LogFieldFilter can filter (or manipulate)
// a field in a log entry. If delete is true,
// out will be ignored and the field will be
// removed from the output.
type LogFieldFilter interface {
Filter(zapcore.Field) zapcore.Field
}
// DeleteFilter is a Caddy log field filter that
// deletes the field.
type DeleteFilter struct{}
// CaddyModule returns the Caddy module information.
func (DeleteFilter) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "caddy.logging.encoders.filter.delete",
New: func() caddy.Module { return new(DeleteFilter) },
}
}
// Filter filters the input field.
func (DeleteFilter) Filter(in zapcore.Field) zapcore.Field {
in.Type = zapcore.SkipType
return in
}
// IPMaskFilter is a Caddy log field filter that
// masks IP addresses.
type IPMaskFilter struct {
// The IPv4 range in CIDR notation.
IPv4CIDR int `json:"ipv4_cidr,omitempty"`
// The IPv6 range in CIDR notation.
IPv6CIDR int `json:"ipv6_cidr,omitempty"`
}
// CaddyModule returns the Caddy module information.
func (IPMaskFilter) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "caddy.logging.encoders.filter.ip_mask",
New: func() caddy.Module { return new(IPMaskFilter) },
}
}
// Filter filters the input field.
func (m IPMaskFilter) Filter(in zapcore.Field) zapcore.Field {
host, port, err := net.SplitHostPort(in.String)
if err != nil {
host = in.String // assume whole thing was IP address
}
ipAddr := net.ParseIP(host)
if ipAddr == nil {
return in
}
bitLen := 32
cidrPrefix := m.IPv4CIDR
if ipAddr.To16() != nil {
bitLen = 128
cidrPrefix = m.IPv6CIDR
}
mask := net.CIDRMask(cidrPrefix, bitLen)
masked := ipAddr.Mask(mask)
if port == "" {
in.String = masked.String()
} else {
in.String = net.JoinHostPort(masked.String(), port)
}
return in
}
| modules/logging/filters.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.00025741499848663807,
0.00018644830561242998,
0.00016427063383162022,
0.00017378240590915084,
0.000029921571695012972
] |
{
"id": 5,
"code_window": [
"func TestDispenser_RemainingArgs(t *testing.T) {\n",
"\tinput := `dir1 arg1 arg2 arg3\n",
"\t\t\t dir2 arg4 arg5\n",
"\t\t\t dir3 arg6 { arg7\n",
"\t\t\t dir4`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\td.Next() // dir1\n",
"\n",
"\targs := d.RemainingArgs()\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 244
} | // Copyright 2015 Matthew Holt and The Caddy 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 caddy
import (
"encoding/json"
"io"
)
func ExampleContext_LoadModule() {
// this whole first part is just setting up for the example;
// note the struct tags - very important; we specify inline_key
// because that is the only way to know the module name
var ctx Context
myStruct := &struct {
// This godoc comment will appear in module documentation.
GuestModuleRaw json.RawMessage `json:"guest_module,omitempty" caddy:"namespace=example inline_key=name"`
// this is where the decoded module will be stored; in this
// example, we pretend we need an io.Writer but it can be
// any interface type that is useful to you
guestModule io.Writer
}{
GuestModuleRaw: json.RawMessage(`{"name":"module_name","foo":"bar"}`),
}
// if a guest module is provided, we can load it easily
if myStruct.GuestModuleRaw != nil {
mod, err := ctx.LoadModule(myStruct, "GuestModuleRaw")
if err != nil {
// you'd want to actually handle the error here
// return fmt.Errorf("loading guest module: %v", err)
}
// mod contains the loaded and provisioned module,
// it is now ready for us to use
myStruct.guestModule = mod.(io.Writer)
}
// use myStruct.guestModule from now on
}
func ExampleContext_LoadModule_array() {
// this whole first part is just setting up for the example;
// note the struct tags - very important; we specify inline_key
// because that is the only way to know the module name
var ctx Context
myStruct := &struct {
// This godoc comment will appear in module documentation.
GuestModulesRaw []json.RawMessage `json:"guest_modules,omitempty" caddy:"namespace=example inline_key=name"`
// this is where the decoded module will be stored; in this
// example, we pretend we need an io.Writer but it can be
// any interface type that is useful to you
guestModules []io.Writer
}{
GuestModulesRaw: []json.RawMessage{
json.RawMessage(`{"name":"module1_name","foo":"bar1"}`),
json.RawMessage(`{"name":"module2_name","foo":"bar2"}`),
},
}
// since our input is []json.RawMessage, the output will be []interface{}
mods, err := ctx.LoadModule(myStruct, "GuestModulesRaw")
if err != nil {
// you'd want to actually handle the error here
// return fmt.Errorf("loading guest modules: %v", err)
}
for _, mod := range mods.([]interface{}) {
myStruct.guestModules = append(myStruct.guestModules, mod.(io.Writer))
}
// use myStruct.guestModules from now on
}
func ExampleContext_LoadModule_map() {
// this whole first part is just setting up for the example;
// note the struct tags - very important; we don't specify
// inline_key because the map key is the module name
var ctx Context
myStruct := &struct {
// This godoc comment will appear in module documentation.
GuestModulesRaw ModuleMap `json:"guest_modules,omitempty" caddy:"namespace=example"`
// this is where the decoded module will be stored; in this
// example, we pretend we need an io.Writer but it can be
// any interface type that is useful to you
guestModules map[string]io.Writer
}{
GuestModulesRaw: ModuleMap{
"module1_name": json.RawMessage(`{"foo":"bar1"}`),
"module2_name": json.RawMessage(`{"foo":"bar2"}`),
},
}
// since our input is map[string]json.RawMessage, the output will be map[string]interface{}
mods, err := ctx.LoadModule(myStruct, "GuestModulesRaw")
if err != nil {
// you'd want to actually handle the error here
// return fmt.Errorf("loading guest modules: %v", err)
}
for modName, mod := range mods.(map[string]interface{}) {
myStruct.guestModules[modName] = mod.(io.Writer)
}
// use myStruct.guestModules from now on
}
| context_test.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.00017848493007477373,
0.00017116348317358643,
0.00016551572480238974,
0.00016892887651920319,
0.0000048523093028052244
] |
{
"id": 5,
"code_window": [
"func TestDispenser_RemainingArgs(t *testing.T) {\n",
"\tinput := `dir1 arg1 arg2 arg3\n",
"\t\t\t dir2 arg4 arg5\n",
"\t\t\t dir3 arg6 { arg7\n",
"\t\t\t dir4`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\td.Next() // dir1\n",
"\n",
"\targs := d.RemainingArgs()\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 244
} | // Copyright 2015 Matthew Holt and The Caddy 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 caddytls
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/certmagic"
"github.com/go-acme/lego/v3/challenge"
"go.uber.org/zap"
)
// AutomationConfig designates configuration for the
// construction and use of ACME clients.
type AutomationConfig struct {
// The list of automation policies. The first matching
// policy will be applied for a given certificate/name.
Policies []*AutomationPolicy `json:"policies,omitempty"`
// On-Demand TLS defers certificate operations to the
// moment they are needed, e.g. during a TLS handshake.
// Useful when you don't know all the hostnames up front.
// Caddy was the first web server to deploy this technology.
OnDemand *OnDemandConfig `json:"on_demand,omitempty"`
// Caddy staples OCSP (and caches the response) for all
// qualifying certificates by default. This setting
// changes how often it scans responses for freshness,
// and updates them if they are getting stale.
OCSPCheckInterval caddy.Duration `json:"ocsp_interval,omitempty"`
// Every so often, Caddy will scan all loaded, managed
// certificates for expiration. This setting changes how
// frequently the scan for expiring certificates is
// performed. If your certificate lifetimes are very
// short (less than ~24 hours), you should set this to
// a low value.
RenewCheckInterval caddy.Duration `json:"renew_interval,omitempty"`
defaultAutomationPolicy *AutomationPolicy
}
// AutomationPolicy designates the policy for automating the
// management (obtaining, renewal, and revocation) of managed
// TLS certificates.
//
// An AutomationPolicy value is not valid until it has been
// provisioned; use the `AddAutomationPolicy()` method on the
// TLS app to properly provision a new policy.
type AutomationPolicy struct {
// Which subjects (hostnames or IP addresses) this policy applies to.
Subjects []string `json:"subjects,omitempty"`
// The module that will issue certificates. Default: acme
IssuerRaw json.RawMessage `json:"issuer,omitempty" caddy:"namespace=tls.issuance inline_key=module"`
// If true, certificates will be requested with MustStaple. Not all
// CAs support this, and there are potentially serious consequences
// of enabling this feature without proper threat modeling.
MustStaple bool `json:"must_staple,omitempty"`
// How long before a certificate's expiration to try renewing it,
// as a function of its total lifetime. As a general and conservative
// rule, it is a good idea to renew a certificate when it has about
// 1/3 of its total lifetime remaining. This utilizes the majority
// of the certificate's lifetime while still saving time to
// troubleshoot problems. However, for extremely short-lived certs,
// you may wish to increase the ratio to ~1/2.
RenewalWindowRatio float64 `json:"renewal_window_ratio,omitempty"`
// The type of key to generate for certificates.
// Supported values: `ed25519`, `p256`, `p384`, `rsa2048`, `rsa4096`.
KeyType string `json:"key_type,omitempty"`
// Optionally configure a separate storage module associated with this
// manager, instead of using Caddy's global/default-configured storage.
StorageRaw json.RawMessage `json:"storage,omitempty" caddy:"namespace=caddy.storage inline_key=module"`
// If true, certificates will be managed "on demand"; that is, during
// TLS handshakes or when needed, as opposed to at startup or config
// load.
OnDemand bool `json:"on_demand,omitempty"`
// Issuer stores the decoded issuer parameters. This is only
// used to populate an underlying certmagic.Config's Issuer
// field; it is not referenced thereafter.
Issuer certmagic.Issuer `json:"-"`
magic *certmagic.Config
storage certmagic.Storage
}
// Provision sets up ap and builds its underlying CertMagic config.
func (ap *AutomationPolicy) Provision(tlsApp *TLS) error {
// policy-specific storage implementation
if ap.StorageRaw != nil {
val, err := tlsApp.ctx.LoadModule(ap, "StorageRaw")
if err != nil {
return fmt.Errorf("loading TLS storage module: %v", err)
}
cmStorage, err := val.(caddy.StorageConverter).CertMagicStorage()
if err != nil {
return fmt.Errorf("creating TLS storage configuration: %v", err)
}
ap.storage = cmStorage
}
var ond *certmagic.OnDemandConfig
if ap.OnDemand {
ond = &certmagic.OnDemandConfig{
DecisionFunc: func(name string) error {
// if an "ask" endpoint was defined, consult it first
if tlsApp.Automation != nil &&
tlsApp.Automation.OnDemand != nil &&
tlsApp.Automation.OnDemand.Ask != "" {
err := onDemandAskRequest(tlsApp.Automation.OnDemand.Ask, name)
if err != nil {
return err
}
}
// check the rate limiter last because
// doing so makes a reservation
if !onDemandRateLimiter.Allow() {
return fmt.Errorf("on-demand rate limit exceeded")
}
return nil
},
}
}
// if this automation policy has no Issuer defined, and
// none of the subjects qualify for a public certificate,
// set the issuer to internal so that these names can all
// get certificates; critically, we can only do this if an
// issuer is not explictly configured (IssuerRaw, vs. just
// Issuer) AND if the list of subjects is non-empty
if ap.IssuerRaw == nil && len(ap.Subjects) > 0 {
var anyPublic bool
for _, s := range ap.Subjects {
if certmagic.SubjectQualifiesForPublicCert(s) {
anyPublic = true
break
}
}
if !anyPublic {
tlsApp.logger.Info("setting internal issuer for automation policy that has only internal subjects but no issuer configured",
zap.Strings("subjects", ap.Subjects))
ap.IssuerRaw = json.RawMessage(`{"module":"internal"}`)
}
}
// load and provision any explicitly-configured issuer module
if ap.IssuerRaw != nil {
val, err := tlsApp.ctx.LoadModule(ap, "IssuerRaw")
if err != nil {
return fmt.Errorf("loading TLS automation management module: %s", err)
}
ap.Issuer = val.(certmagic.Issuer)
}
keyType := ap.KeyType
if keyType != "" {
var err error
keyType, err = caddy.NewReplacer().ReplaceOrErr(ap.KeyType, true, true)
if err != nil {
return fmt.Errorf("invalid key type %s: %s", ap.KeyType, err)
}
if _, ok := supportedCertKeyTypes[keyType]; !ok {
return fmt.Errorf("unrecognized key type: %s", keyType)
}
}
keySource := certmagic.StandardKeyGenerator{
KeyType: supportedCertKeyTypes[keyType],
}
storage := ap.storage
if storage == nil {
storage = tlsApp.ctx.Storage()
}
template := certmagic.Config{
MustStaple: ap.MustStaple,
RenewalWindowRatio: ap.RenewalWindowRatio,
KeySource: keySource,
OnDemand: ond,
Storage: storage,
Issuer: ap.Issuer, // if nil, certmagic.New() will create one
}
if rev, ok := ap.Issuer.(certmagic.Revoker); ok {
template.Revoker = rev
}
ap.magic = certmagic.New(tlsApp.certCache, template)
// sometimes issuers may need the parent certmagic.Config in
// order to function properly (for example, ACMEIssuer needs
// access to the correct storage and cache so it can solve
// ACME challenges -- it's an annoying, inelegant circular
// dependency that I don't know how to resolve nicely!)
if annoying, ok := ap.Issuer.(ConfigSetter); ok {
annoying.SetConfig(ap.magic)
}
return nil
}
// ChallengesConfig configures the ACME challenges.
type ChallengesConfig struct {
// HTTP configures the ACME HTTP challenge. This
// challenge is enabled and used automatically
// and by default.
HTTP *HTTPChallengeConfig `json:"http,omitempty"`
// TLSALPN configures the ACME TLS-ALPN challenge.
// This challenge is enabled and used automatically
// and by default.
TLSALPN *TLSALPNChallengeConfig `json:"tls-alpn,omitempty"`
// Configures the ACME DNS challenge. Because this
// challenge typically requires credentials for
// interfacing with a DNS provider, this challenge is
// not enabled by default. This is the only challenge
// type which does not require a direct connection
// to Caddy from an external server.
DNSRaw json.RawMessage `json:"dns,omitempty" caddy:"namespace=tls.dns inline_key=provider"`
DNS challenge.Provider `json:"-"`
}
// HTTPChallengeConfig configures the ACME HTTP challenge.
type HTTPChallengeConfig struct {
// If true, the HTTP challenge will be disabled.
Disabled bool `json:"disabled,omitempty"`
// An alternate port on which to service this
// challenge. Note that the HTTP challenge port is
// hard-coded into the spec and cannot be changed,
// so you would have to forward packets from the
// standard HTTP challenge port to this one.
AlternatePort int `json:"alternate_port,omitempty"`
}
// TLSALPNChallengeConfig configures the ACME TLS-ALPN challenge.
type TLSALPNChallengeConfig struct {
// If true, the TLS-ALPN challenge will be disabled.
Disabled bool `json:"disabled,omitempty"`
// An alternate port on which to service this
// challenge. Note that the TLS-ALPN challenge port
// is hard-coded into the spec and cannot be changed,
// so you would have to forward packets from the
// standard TLS-ALPN challenge port to this one.
AlternatePort int `json:"alternate_port,omitempty"`
}
// OnDemandConfig configures on-demand TLS, for obtaining
// needed certificates at handshake-time. Because this
// feature can easily be abused, you should set up rate
// limits and/or an internal endpoint that Caddy can
// "ask" if it should be allowed to manage certificates
// for a given hostname.
type OnDemandConfig struct {
// An optional rate limit to throttle the
// issuance of certificates from handshakes.
RateLimit *RateLimit `json:"rate_limit,omitempty"`
// If Caddy needs to obtain or renew a certificate
// during a TLS handshake, it will perform a quick
// HTTP request to this URL to check if it should be
// allowed to try to get a certificate for the name
// in the "domain" query string parameter, like so:
// `?domain=example.com`. The endpoint must return a
// 200 OK status if a certificate is allowed;
// anything else will cause it to be denied.
// Redirects are not followed.
Ask string `json:"ask,omitempty"`
}
// RateLimit specifies an interval with optional burst size.
type RateLimit struct {
// A duration value. A certificate may be obtained 'burst'
// times during this interval.
Interval caddy.Duration `json:"interval,omitempty"`
// How many times during an interval a certificate can be obtained.
Burst int `json:"burst,omitempty"`
}
// ConfigSetter is implemented by certmagic.Issuers that
// need access to a parent certmagic.Config as part of
// their provisioning phase. For example, the ACMEIssuer
// requires a config so it can access storage and the
// cache to solve ACME challenges.
type ConfigSetter interface {
SetConfig(cfg *certmagic.Config)
}
// These perpetual values are used for on-demand TLS.
var (
onDemandRateLimiter = certmagic.NewRateLimiter(0, 0)
onDemandAskClient = &http.Client{
Timeout: 10 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return fmt.Errorf("following http redirects is not allowed")
},
}
)
| modules/caddytls/automation.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.0003050102386623621,
0.0001763783220667392,
0.00016234366921707988,
0.00017197248234879225,
0.000023711467292741872
] |
{
"id": 6,
"code_window": [
"func TestDispenser_ArgErr_Err(t *testing.T) {\n",
"\tinput := `dir1 {\n",
"\t\t\t }\n",
"\t\t\t dir2 arg1 arg2`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\td.cursor = 1 // {\n",
"\n",
"\tif err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), \"{\") {\n",
"\t\tt.Errorf(\"ArgErr(): Expected an error message with { in it, but got '%v'\", err)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 281
} | // Copyright 2015 Matthew Holt and The Caddy 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 caddyfile
import (
"io"
"log"
"reflect"
"strings"
"testing"
)
func TestDispenser_Val_Next(t *testing.T) {
input := `host:port
dir1 arg1
dir2 arg2 arg3
dir3`
d := newTestDispenser(input)
if val := d.Val(); val != "" {
t.Fatalf("Val(): Should return empty string when no token loaded; got '%s'", val)
}
assertNext := func(shouldLoad bool, expectedCursor int, expectedVal string) {
if loaded := d.Next(); loaded != shouldLoad {
t.Errorf("Next(): Expected %v but got %v instead (val '%s')", shouldLoad, loaded, d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("Expected cursor to be %d, but was %d", expectedCursor, d.cursor)
}
if d.nesting != 0 {
t.Errorf("Nesting should be 0, was %d instead", d.nesting)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNext(true, 0, "host:port")
assertNext(true, 1, "dir1")
assertNext(true, 2, "arg1")
assertNext(true, 3, "dir2")
assertNext(true, 4, "arg2")
assertNext(true, 5, "arg3")
assertNext(true, 6, "dir3")
// Note: This next test simply asserts existing behavior.
// If desired, we may wish to empty the token value after
// reading past the EOF. Open an issue if you want this change.
assertNext(false, 6, "dir3")
}
func TestDispenser_NextArg(t *testing.T) {
input := `dir1 arg1
dir2 arg2 arg3
dir3`
d := newTestDispenser(input)
assertNext := func(shouldLoad bool, expectedVal string, expectedCursor int) {
if d.Next() != shouldLoad {
t.Errorf("Next(): Should load token but got false instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("Next(): Expected cursor to be at %d, but it was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNextArg := func(expectedVal string, loadAnother bool, expectedCursor int) {
if !d.NextArg() {
t.Error("NextArg(): Should load next argument but got false instead")
}
if d.cursor != expectedCursor {
t.Errorf("NextArg(): Expected cursor to be at %d, but it was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
if !loadAnother {
if d.NextArg() {
t.Fatalf("NextArg(): Should NOT load another argument, but got true instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("NextArg(): Expected cursor to remain at %d, but it was %d", expectedCursor, d.cursor)
}
}
}
assertNext(true, "dir1", 0)
assertNextArg("arg1", false, 1)
assertNext(true, "dir2", 2)
assertNextArg("arg2", true, 3)
assertNextArg("arg3", false, 4)
assertNext(true, "dir3", 5)
assertNext(false, "dir3", 5)
}
func TestDispenser_NextLine(t *testing.T) {
input := `host:port
dir1 arg1
dir2 arg2 arg3`
d := newTestDispenser(input)
assertNextLine := func(shouldLoad bool, expectedVal string, expectedCursor int) {
if d.NextLine() != shouldLoad {
t.Errorf("NextLine(): Should load token but got false instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("NextLine(): Expected cursor to be %d, instead was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNextLine(true, "host:port", 0)
assertNextLine(true, "dir1", 1)
assertNextLine(false, "dir1", 1)
d.Next() // arg1
assertNextLine(true, "dir2", 3)
assertNextLine(false, "dir2", 3)
d.Next() // arg2
assertNextLine(false, "arg2", 4)
d.Next() // arg3
assertNextLine(false, "arg3", 5)
}
func TestDispenser_NextBlock(t *testing.T) {
input := `foobar1 {
sub1 arg1
sub2
}
foobar2 {
}`
d := newTestDispenser(input)
assertNextBlock := func(shouldLoad bool, expectedCursor, expectedNesting int) {
if loaded := d.NextBlock(0); loaded != shouldLoad {
t.Errorf("NextBlock(): Should return %v but got %v", shouldLoad, loaded)
}
if d.cursor != expectedCursor {
t.Errorf("NextBlock(): Expected cursor to be %d, was %d", expectedCursor, d.cursor)
}
if d.nesting != expectedNesting {
t.Errorf("NextBlock(): Nesting should be %d, not %d", expectedNesting, d.nesting)
}
}
assertNextBlock(false, -1, 0)
d.Next() // foobar1
assertNextBlock(true, 2, 1)
assertNextBlock(true, 3, 1)
assertNextBlock(true, 4, 1)
assertNextBlock(false, 5, 0)
d.Next() // foobar2
assertNextBlock(false, 8, 0) // empty block is as if it didn't exist
}
func TestDispenser_Args(t *testing.T) {
var s1, s2, s3 string
input := `dir1 arg1 arg2 arg3
dir2 arg4 arg5
dir3 arg6 arg7
dir4`
d := newTestDispenser(input)
d.Next() // dir1
// As many strings as arguments
if all := d.Args(&s1, &s2, &s3); !all {
t.Error("Args(): Expected true, got false")
}
if s1 != "arg1" {
t.Errorf("Args(): Expected s1 to be 'arg1', got '%s'", s1)
}
if s2 != "arg2" {
t.Errorf("Args(): Expected s2 to be 'arg2', got '%s'", s2)
}
if s3 != "arg3" {
t.Errorf("Args(): Expected s3 to be 'arg3', got '%s'", s3)
}
d.Next() // dir2
// More strings than arguments
if all := d.Args(&s1, &s2, &s3); all {
t.Error("Args(): Expected false, got true")
}
if s1 != "arg4" {
t.Errorf("Args(): Expected s1 to be 'arg4', got '%s'", s1)
}
if s2 != "arg5" {
t.Errorf("Args(): Expected s2 to be 'arg5', got '%s'", s2)
}
if s3 != "arg3" {
t.Errorf("Args(): Expected s3 to be unchanged ('arg3'), instead got '%s'", s3)
}
// (quick cursor check just for kicks and giggles)
if d.cursor != 6 {
t.Errorf("Cursor should be 6, but is %d", d.cursor)
}
d.Next() // dir3
// More arguments than strings
if all := d.Args(&s1); !all {
t.Error("Args(): Expected true, got false")
}
if s1 != "arg6" {
t.Errorf("Args(): Expected s1 to be 'arg6', got '%s'", s1)
}
d.Next() // dir4
// No arguments or strings
if all := d.Args(); !all {
t.Error("Args(): Expected true, got false")
}
// No arguments but at least one string
if all := d.Args(&s1); all {
t.Error("Args(): Expected false, got true")
}
}
func TestDispenser_RemainingArgs(t *testing.T) {
input := `dir1 arg1 arg2 arg3
dir2 arg4 arg5
dir3 arg6 { arg7
dir4`
d := newTestDispenser(input)
d.Next() // dir1
args := d.RemainingArgs()
if expected := []string{"arg1", "arg2", "arg3"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // dir2
args = d.RemainingArgs()
if expected := []string{"arg4", "arg5"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // dir3
args = d.RemainingArgs()
if expected := []string{"arg6"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // {
d.Next() // arg7
d.Next() // dir4
args = d.RemainingArgs()
if len(args) != 0 {
t.Errorf("RemainingArgs(): Expected %v, got %v", []string{}, args)
}
}
func TestDispenser_ArgErr_Err(t *testing.T) {
input := `dir1 {
}
dir2 arg1 arg2`
d := newTestDispenser(input)
d.cursor = 1 // {
if err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), "{") {
t.Errorf("ArgErr(): Expected an error message with { in it, but got '%v'", err)
}
d.cursor = 5 // arg2
if err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), "arg2") {
t.Errorf("ArgErr(): Expected an error message with 'arg2' in it; got '%v'", err)
}
err := d.Err("foobar")
if err == nil {
t.Fatalf("Err(): Expected an error, got nil")
}
if !strings.Contains(err.Error(), "Testfile:3") {
t.Errorf("Expected error message with filename:line in it; got '%v'", err)
}
if !strings.Contains(err.Error(), "foobar") {
t.Errorf("Expected error message with custom message in it ('foobar'); got '%v'", err)
}
}
func newTestDispenser(input string) *Dispenser {
tokens, err := allTokens("Testfile", []byte(input))
if err != nil && err != io.EOF {
log.Fatalf("getting all tokens from input: %v", err)
}
return NewDispenser(tokens)
}
| caddyconfig/caddyfile/dispenser_test.go | 1 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.9980025887489319,
0.5556043386459351,
0.0001664898154558614,
0.7815530300140381,
0.44446611404418945
] |
{
"id": 6,
"code_window": [
"func TestDispenser_ArgErr_Err(t *testing.T) {\n",
"\tinput := `dir1 {\n",
"\t\t\t }\n",
"\t\t\t dir2 arg1 arg2`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\td.cursor = 1 // {\n",
"\n",
"\tif err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), \"{\") {\n",
"\t\tt.Errorf(\"ArgErr(): Expected an error message with { in it, but got '%v'\", err)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 281
} | // Copyright 2015 Matthew Holt and The Caddy 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 logging
import (
"time"
"go.uber.org/zap/buffer"
"go.uber.org/zap/zapcore"
)
// nopEncoder is a zapcore.Encoder that does nothing.
type nopEncoder struct{}
// AddArray is part of the zapcore.ObjectEncoder interface.
// Array elements do not get filtered.
func (nopEncoder) AddArray(key string, marshaler zapcore.ArrayMarshaler) error { return nil }
// AddObject is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddObject(key string, marshaler zapcore.ObjectMarshaler) error { return nil }
// AddBinary is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddBinary(key string, value []byte) {}
// AddByteString is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddByteString(key string, value []byte) {}
// AddBool is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddBool(key string, value bool) {}
// AddComplex128 is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddComplex128(key string, value complex128) {}
// AddComplex64 is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddComplex64(key string, value complex64) {}
// AddDuration is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddDuration(key string, value time.Duration) {}
// AddFloat64 is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddFloat64(key string, value float64) {}
// AddFloat32 is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddFloat32(key string, value float32) {}
// AddInt is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddInt(key string, value int) {}
// AddInt64 is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddInt64(key string, value int64) {}
// AddInt32 is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddInt32(key string, value int32) {}
// AddInt16 is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddInt16(key string, value int16) {}
// AddInt8 is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddInt8(key string, value int8) {}
// AddString is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddString(key, value string) {}
// AddTime is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddTime(key string, value time.Time) {}
// AddUint is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddUint(key string, value uint) {}
// AddUint64 is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddUint64(key string, value uint64) {}
// AddUint32 is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddUint32(key string, value uint32) {}
// AddUint16 is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddUint16(key string, value uint16) {}
// AddUint8 is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddUint8(key string, value uint8) {}
// AddUintptr is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddUintptr(key string, value uintptr) {}
// AddReflected is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddReflected(key string, value interface{}) error { return nil }
// OpenNamespace is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) OpenNamespace(key string) {}
// Clone is part of the zapcore.ObjectEncoder interface.
// We don't use it as of Oct 2019 (v2 beta 7), I'm not
// really sure what it'd be useful for in our case.
func (ne nopEncoder) Clone() zapcore.Encoder { return ne }
// EncodeEntry partially implements the zapcore.Encoder interface.
func (nopEncoder) EncodeEntry(ent zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) {
return bufferpool.Get(), nil
}
// Interface guard
var _ zapcore.Encoder = (*nopEncoder)(nil)
| modules/logging/nopencoder.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.00017732262494973838,
0.00016677286475896835,
0.0001608400052646175,
0.0001642526185605675,
0.000005406895070336759
] |
{
"id": 6,
"code_window": [
"func TestDispenser_ArgErr_Err(t *testing.T) {\n",
"\tinput := `dir1 {\n",
"\t\t\t }\n",
"\t\t\t dir2 arg1 arg2`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\td.cursor = 1 // {\n",
"\n",
"\tif err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), \"{\") {\n",
"\t\tt.Errorf(\"ArgErr(): Expected an error message with { in it, but got '%v'\", err)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 281
} | name: Release
on:
push:
tags:
- 'v*.*.*'
jobs:
release:
name: Release
strategy:
matrix:
os: [ ubuntu-latest ]
go-version: [ 1.14.x ]
runs-on: ${{ matrix.os }}
steps:
- name: Install Go
uses: actions/setup-go@v1
with:
go-version: ${{ matrix.go-version }}
- name: Checkout code
uses: actions/checkout@v2
# So GoReleaser can generate the changelog properly
- name: Unshallowify the repo clone
run: git fetch --prune --unshallow
- name: Print Go version and environment
id: vars
run: |
printf "Using go at: $(which go)\n"
printf "Go version: $(go version)\n"
printf "\n\nGo environment:\n\n"
go env
printf "\n\nSystem environment:\n\n"
env
# https://github.community/t5/GitHub-Actions/How-to-get-just-the-tag-name/m-p/32167/highlight/true#M1027
- name: Get the version
id: get_version
run: echo "::set-output name=version_tag::${GITHUB_REF/refs\/tags\//}"
# GoReleaser will take care of publishing those artifacts into the release
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v1
with:
version: latest
args: release --rm-dist
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAG: ${{ steps.vars.outputs.version_tag }}
| .github/workflows/release.yml | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.00017669677617959678,
0.00017526639567222446,
0.00017225838382728398,
0.00017564883455634117,
0.000001430222710041562
] |
{
"id": 6,
"code_window": [
"func TestDispenser_ArgErr_Err(t *testing.T) {\n",
"\tinput := `dir1 {\n",
"\t\t\t }\n",
"\t\t\t dir2 arg1 arg2`\n",
"\td := newTestDispenser(input)\n",
"\n",
"\td.cursor = 1 // {\n",
"\n",
"\tif err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), \"{\") {\n",
"\t\tt.Errorf(\"ArgErr(): Expected an error message with { in it, but got '%v'\", err)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\td := NewTestDispenser(input)\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 281
} | package standard
import (
// standard Caddy modules
_ "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/standard"
_ "github.com/caddyserver/caddy/v2/modules/caddypki"
_ "github.com/caddyserver/caddy/v2/modules/caddytls"
_ "github.com/caddyserver/caddy/v2/modules/caddytls/distributedstek"
_ "github.com/caddyserver/caddy/v2/modules/caddytls/standardstek"
_ "github.com/caddyserver/caddy/v2/modules/filestorage"
_ "github.com/caddyserver/caddy/v2/modules/logging"
)
| modules/standard/import.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.0001684851013123989,
0.00016829799278639257,
0.00016811088426038623,
0.00016829799278639257,
1.8710852600634098e-7
] |
{
"id": 7,
"code_window": [
"\t\tt.Errorf(\"Expected error message with custom message in it ('foobar'); got '%v'\", err)\n",
"\t}\n",
"}\n",
"\n",
"func newTestDispenser(input string) *Dispenser {\n",
"\ttokens, err := allTokens(\"Testfile\", []byte(input))\n",
"\tif err != nil && err != io.EOF {\n",
"\t\tlog.Fatalf(\"getting all tokens from input: %v\", err)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"// NewTestDispenser parses input into tokens and creates a new\n",
"// Disenser for test purposes only; any errors are fatal.\n",
"func NewTestDispenser(input string) *Dispenser {\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 309
} | // Copyright 2015 Matthew Holt and The Caddy 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 caddyfile
import (
"io"
"log"
"reflect"
"strings"
"testing"
)
func TestDispenser_Val_Next(t *testing.T) {
input := `host:port
dir1 arg1
dir2 arg2 arg3
dir3`
d := newTestDispenser(input)
if val := d.Val(); val != "" {
t.Fatalf("Val(): Should return empty string when no token loaded; got '%s'", val)
}
assertNext := func(shouldLoad bool, expectedCursor int, expectedVal string) {
if loaded := d.Next(); loaded != shouldLoad {
t.Errorf("Next(): Expected %v but got %v instead (val '%s')", shouldLoad, loaded, d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("Expected cursor to be %d, but was %d", expectedCursor, d.cursor)
}
if d.nesting != 0 {
t.Errorf("Nesting should be 0, was %d instead", d.nesting)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNext(true, 0, "host:port")
assertNext(true, 1, "dir1")
assertNext(true, 2, "arg1")
assertNext(true, 3, "dir2")
assertNext(true, 4, "arg2")
assertNext(true, 5, "arg3")
assertNext(true, 6, "dir3")
// Note: This next test simply asserts existing behavior.
// If desired, we may wish to empty the token value after
// reading past the EOF. Open an issue if you want this change.
assertNext(false, 6, "dir3")
}
func TestDispenser_NextArg(t *testing.T) {
input := `dir1 arg1
dir2 arg2 arg3
dir3`
d := newTestDispenser(input)
assertNext := func(shouldLoad bool, expectedVal string, expectedCursor int) {
if d.Next() != shouldLoad {
t.Errorf("Next(): Should load token but got false instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("Next(): Expected cursor to be at %d, but it was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNextArg := func(expectedVal string, loadAnother bool, expectedCursor int) {
if !d.NextArg() {
t.Error("NextArg(): Should load next argument but got false instead")
}
if d.cursor != expectedCursor {
t.Errorf("NextArg(): Expected cursor to be at %d, but it was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
if !loadAnother {
if d.NextArg() {
t.Fatalf("NextArg(): Should NOT load another argument, but got true instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("NextArg(): Expected cursor to remain at %d, but it was %d", expectedCursor, d.cursor)
}
}
}
assertNext(true, "dir1", 0)
assertNextArg("arg1", false, 1)
assertNext(true, "dir2", 2)
assertNextArg("arg2", true, 3)
assertNextArg("arg3", false, 4)
assertNext(true, "dir3", 5)
assertNext(false, "dir3", 5)
}
func TestDispenser_NextLine(t *testing.T) {
input := `host:port
dir1 arg1
dir2 arg2 arg3`
d := newTestDispenser(input)
assertNextLine := func(shouldLoad bool, expectedVal string, expectedCursor int) {
if d.NextLine() != shouldLoad {
t.Errorf("NextLine(): Should load token but got false instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("NextLine(): Expected cursor to be %d, instead was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNextLine(true, "host:port", 0)
assertNextLine(true, "dir1", 1)
assertNextLine(false, "dir1", 1)
d.Next() // arg1
assertNextLine(true, "dir2", 3)
assertNextLine(false, "dir2", 3)
d.Next() // arg2
assertNextLine(false, "arg2", 4)
d.Next() // arg3
assertNextLine(false, "arg3", 5)
}
func TestDispenser_NextBlock(t *testing.T) {
input := `foobar1 {
sub1 arg1
sub2
}
foobar2 {
}`
d := newTestDispenser(input)
assertNextBlock := func(shouldLoad bool, expectedCursor, expectedNesting int) {
if loaded := d.NextBlock(0); loaded != shouldLoad {
t.Errorf("NextBlock(): Should return %v but got %v", shouldLoad, loaded)
}
if d.cursor != expectedCursor {
t.Errorf("NextBlock(): Expected cursor to be %d, was %d", expectedCursor, d.cursor)
}
if d.nesting != expectedNesting {
t.Errorf("NextBlock(): Nesting should be %d, not %d", expectedNesting, d.nesting)
}
}
assertNextBlock(false, -1, 0)
d.Next() // foobar1
assertNextBlock(true, 2, 1)
assertNextBlock(true, 3, 1)
assertNextBlock(true, 4, 1)
assertNextBlock(false, 5, 0)
d.Next() // foobar2
assertNextBlock(false, 8, 0) // empty block is as if it didn't exist
}
func TestDispenser_Args(t *testing.T) {
var s1, s2, s3 string
input := `dir1 arg1 arg2 arg3
dir2 arg4 arg5
dir3 arg6 arg7
dir4`
d := newTestDispenser(input)
d.Next() // dir1
// As many strings as arguments
if all := d.Args(&s1, &s2, &s3); !all {
t.Error("Args(): Expected true, got false")
}
if s1 != "arg1" {
t.Errorf("Args(): Expected s1 to be 'arg1', got '%s'", s1)
}
if s2 != "arg2" {
t.Errorf("Args(): Expected s2 to be 'arg2', got '%s'", s2)
}
if s3 != "arg3" {
t.Errorf("Args(): Expected s3 to be 'arg3', got '%s'", s3)
}
d.Next() // dir2
// More strings than arguments
if all := d.Args(&s1, &s2, &s3); all {
t.Error("Args(): Expected false, got true")
}
if s1 != "arg4" {
t.Errorf("Args(): Expected s1 to be 'arg4', got '%s'", s1)
}
if s2 != "arg5" {
t.Errorf("Args(): Expected s2 to be 'arg5', got '%s'", s2)
}
if s3 != "arg3" {
t.Errorf("Args(): Expected s3 to be unchanged ('arg3'), instead got '%s'", s3)
}
// (quick cursor check just for kicks and giggles)
if d.cursor != 6 {
t.Errorf("Cursor should be 6, but is %d", d.cursor)
}
d.Next() // dir3
// More arguments than strings
if all := d.Args(&s1); !all {
t.Error("Args(): Expected true, got false")
}
if s1 != "arg6" {
t.Errorf("Args(): Expected s1 to be 'arg6', got '%s'", s1)
}
d.Next() // dir4
// No arguments or strings
if all := d.Args(); !all {
t.Error("Args(): Expected true, got false")
}
// No arguments but at least one string
if all := d.Args(&s1); all {
t.Error("Args(): Expected false, got true")
}
}
func TestDispenser_RemainingArgs(t *testing.T) {
input := `dir1 arg1 arg2 arg3
dir2 arg4 arg5
dir3 arg6 { arg7
dir4`
d := newTestDispenser(input)
d.Next() // dir1
args := d.RemainingArgs()
if expected := []string{"arg1", "arg2", "arg3"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // dir2
args = d.RemainingArgs()
if expected := []string{"arg4", "arg5"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // dir3
args = d.RemainingArgs()
if expected := []string{"arg6"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // {
d.Next() // arg7
d.Next() // dir4
args = d.RemainingArgs()
if len(args) != 0 {
t.Errorf("RemainingArgs(): Expected %v, got %v", []string{}, args)
}
}
func TestDispenser_ArgErr_Err(t *testing.T) {
input := `dir1 {
}
dir2 arg1 arg2`
d := newTestDispenser(input)
d.cursor = 1 // {
if err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), "{") {
t.Errorf("ArgErr(): Expected an error message with { in it, but got '%v'", err)
}
d.cursor = 5 // arg2
if err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), "arg2") {
t.Errorf("ArgErr(): Expected an error message with 'arg2' in it; got '%v'", err)
}
err := d.Err("foobar")
if err == nil {
t.Fatalf("Err(): Expected an error, got nil")
}
if !strings.Contains(err.Error(), "Testfile:3") {
t.Errorf("Expected error message with filename:line in it; got '%v'", err)
}
if !strings.Contains(err.Error(), "foobar") {
t.Errorf("Expected error message with custom message in it ('foobar'); got '%v'", err)
}
}
func newTestDispenser(input string) *Dispenser {
tokens, err := allTokens("Testfile", []byte(input))
if err != nil && err != io.EOF {
log.Fatalf("getting all tokens from input: %v", err)
}
return NewDispenser(tokens)
}
| caddyconfig/caddyfile/dispenser_test.go | 1 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.9991080164909363,
0.2873474359512329,
0.00016686346498318017,
0.00018931600789073855,
0.44585683941841125
] |
{
"id": 7,
"code_window": [
"\t\tt.Errorf(\"Expected error message with custom message in it ('foobar'); got '%v'\", err)\n",
"\t}\n",
"}\n",
"\n",
"func newTestDispenser(input string) *Dispenser {\n",
"\ttokens, err := allTokens(\"Testfile\", []byte(input))\n",
"\tif err != nil && err != io.EOF {\n",
"\t\tlog.Fatalf(\"getting all tokens from input: %v\", err)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"// NewTestDispenser parses input into tokens and creates a new\n",
"// Disenser for test purposes only; any errors are fatal.\n",
"func NewTestDispenser(input string) *Dispenser {\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 309
} | // Copyright 2015 Matthew Holt and The Caddy 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 standardstek
import (
"log"
"sync"
"time"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/modules/caddytls"
)
func init() {
caddy.RegisterModule(standardSTEKProvider{})
}
type standardSTEKProvider struct {
stekConfig *caddytls.SessionTicketService
timer *time.Timer
}
// CaddyModule returns the Caddy module information.
func (standardSTEKProvider) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "tls.stek.standard",
New: func() caddy.Module { return new(standardSTEKProvider) },
}
}
// Initialize sets the configuration for s and returns the starting keys.
func (s *standardSTEKProvider) Initialize(config *caddytls.SessionTicketService) ([][32]byte, error) {
// keep a reference to the config; we'll need it when rotating keys
s.stekConfig = config
itvl := time.Duration(s.stekConfig.RotationInterval)
mutex.Lock()
defer mutex.Unlock()
// if this is our first rotation or we are overdue
// for one, perform a rotation immediately; otherwise,
// we assume that the keys are non-empty and fresh
since := time.Since(lastRotation)
if lastRotation.IsZero() || since > itvl {
var err error
keys, err = s.stekConfig.RotateSTEKs(keys)
if err != nil {
return nil, err
}
since = 0 // since this is overdue or is the first rotation, use full interval
lastRotation = time.Now()
}
// create timer for the remaining time on the interval;
// this timer is cleaned up only when Next() returns
s.timer = time.NewTimer(itvl - since)
return keys, nil
}
// Next returns a channel which transmits the latest session ticket keys.
func (s *standardSTEKProvider) Next(doneChan <-chan struct{}) <-chan [][32]byte {
keysChan := make(chan [][32]byte)
go s.rotate(doneChan, keysChan)
return keysChan
}
// rotate rotates keys on a regular basis, sending each updated set of
// keys down keysChan, until doneChan is closed.
func (s *standardSTEKProvider) rotate(doneChan <-chan struct{}, keysChan chan<- [][32]byte) {
for {
select {
case now := <-s.timer.C:
// copy the slice header to avoid races
mutex.RLock()
keysCopy := keys
mutex.RUnlock()
// generate a new key, rotating old ones
var err error
keysCopy, err = s.stekConfig.RotateSTEKs(keysCopy)
if err != nil {
// TODO: improve this handling
log.Printf("[ERROR] Generating STEK: %v", err)
continue
}
// replace keys slice with updated value and
// record the timestamp of rotation
mutex.Lock()
keys = keysCopy
lastRotation = now
mutex.Unlock()
// send the updated keys to the service
keysChan <- keysCopy
// timer channel is already drained, so reset directly (see godoc)
s.timer.Reset(time.Duration(s.stekConfig.RotationInterval))
case <-doneChan:
// again, see godocs for why timer is stopped this way
if !s.timer.Stop() {
<-s.timer.C
}
return
}
}
}
var (
lastRotation time.Time
keys [][32]byte
mutex sync.RWMutex // protects keys and lastRotation
)
// Interface guard
var _ caddytls.STEKProvider = (*standardSTEKProvider)(nil)
| modules/caddytls/standardstek/stek.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.0006883711903356016,
0.00020846245752181858,
0.00016188489098567516,
0.00017043383559212089,
0.00013323588063940406
] |
{
"id": 7,
"code_window": [
"\t\tt.Errorf(\"Expected error message with custom message in it ('foobar'); got '%v'\", err)\n",
"\t}\n",
"}\n",
"\n",
"func newTestDispenser(input string) *Dispenser {\n",
"\ttokens, err := allTokens(\"Testfile\", []byte(input))\n",
"\tif err != nil && err != io.EOF {\n",
"\t\tlog.Fatalf(\"getting all tokens from input: %v\", err)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"// NewTestDispenser parses input into tokens and creates a new\n",
"// Disenser for test purposes only; any errors are fatal.\n",
"func NewTestDispenser(input string) *Dispenser {\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 309
} | _gitignore/
*.log
Caddyfile
!caddyfile/
# artifacts from pprof tooling
*.prof
*.test
# build artifacts
cmd/caddy/caddy
cmd/caddy/caddy.exe
# mac specific
.DS_Store
# go modules
vendor
# goreleaser artifacts
dist
caddy-build
caddy-dist | .gitignore | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.00017056918295565993,
0.00016814192349556834,
0.00016577458882238716,
0.00016808202781248838,
0.0000019578430965339066
] |
{
"id": 7,
"code_window": [
"\t\tt.Errorf(\"Expected error message with custom message in it ('foobar'); got '%v'\", err)\n",
"\t}\n",
"}\n",
"\n",
"func newTestDispenser(input string) *Dispenser {\n",
"\ttokens, err := allTokens(\"Testfile\", []byte(input))\n",
"\tif err != nil && err != io.EOF {\n",
"\t\tlog.Fatalf(\"getting all tokens from input: %v\", err)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"// NewTestDispenser parses input into tokens and creates a new\n",
"// Disenser for test purposes only; any errors are fatal.\n",
"func NewTestDispenser(input string) *Dispenser {\n"
],
"file_path": "caddyconfig/caddyfile/dispenser_test.go",
"type": "replace",
"edit_start_line_idx": 309
} | // Copyright 2015 Light Code Labs, LLC
//
// 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 caddyfile
import (
"bufio"
"io"
"unicode"
)
type (
// lexer is a utility which can get values, token by
// token, from a Reader. A token is a word, and tokens
// are separated by whitespace. A word can be enclosed
// in quotes if it contains whitespace.
lexer struct {
reader *bufio.Reader
token Token
line int
skippedLines int
}
// Token represents a single parsable unit.
Token struct {
File string
Line int
Text string
}
)
// load prepares the lexer to scan an input for tokens.
// It discards any leading byte order mark.
func (l *lexer) load(input io.Reader) error {
l.reader = bufio.NewReader(input)
l.line = 1
// discard byte order mark, if present
firstCh, _, err := l.reader.ReadRune()
if err != nil {
return err
}
if firstCh != 0xFEFF {
err := l.reader.UnreadRune()
if err != nil {
return err
}
}
return nil
}
// next loads the next token into the lexer.
// A token is delimited by whitespace, unless
// the token starts with a quotes character (")
// in which case the token goes until the closing
// quotes (the enclosing quotes are not included).
// Inside quoted strings, quotes may be escaped
// with a preceding \ character. No other chars
// may be escaped. The rest of the line is skipped
// if a "#" character is read in. Returns true if
// a token was loaded; false otherwise.
func (l *lexer) next() bool {
var val []rune
var comment, quoted, escaped bool
makeToken := func() bool {
l.token.Text = string(val)
return true
}
for {
ch, _, err := l.reader.ReadRune()
if err != nil {
if len(val) > 0 {
return makeToken()
}
if err == io.EOF {
return false
}
panic(err)
}
if !escaped && ch == '\\' {
escaped = true
continue
}
if quoted {
if escaped {
// all is literal in quoted area,
// so only escape quotes
if ch != '"' {
val = append(val, '\\')
}
escaped = false
} else {
if ch == '"' {
return makeToken()
}
}
if ch == '\n' {
l.line += 1 + l.skippedLines
l.skippedLines = 0
}
val = append(val, ch)
continue
}
if unicode.IsSpace(ch) {
if ch == '\r' {
continue
}
if ch == '\n' {
if escaped {
l.skippedLines++
escaped = false
} else {
l.line += 1 + l.skippedLines
l.skippedLines = 0
}
comment = false
}
if len(val) > 0 {
return makeToken()
}
continue
}
if ch == '#' {
comment = true
}
if comment {
continue
}
if len(val) == 0 {
l.token = Token{Line: l.line}
if ch == '"' {
quoted = true
continue
}
}
if escaped {
val = append(val, '\\')
escaped = false
}
val = append(val, ch)
}
}
| caddyconfig/caddyfile/lexer.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.0033982768654823303,
0.00051294662989676,
0.00016906768723856658,
0.00017888615548145026,
0.0008069584728218615
] |
{
"id": 8,
"code_window": [
"}\n",
"\n",
"func testParser(input string) parser {\n",
"\treturn parser{Dispenser: newTestDispenser(input)}\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\treturn parser{Dispenser: NewTestDispenser(input)}\n"
],
"file_path": "caddyconfig/caddyfile/parse_test.go",
"type": "replace",
"edit_start_line_idx": 672
} | // Copyright 2015 Matthew Holt and The Caddy 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 caddyfile
import (
"io"
"log"
"reflect"
"strings"
"testing"
)
func TestDispenser_Val_Next(t *testing.T) {
input := `host:port
dir1 arg1
dir2 arg2 arg3
dir3`
d := newTestDispenser(input)
if val := d.Val(); val != "" {
t.Fatalf("Val(): Should return empty string when no token loaded; got '%s'", val)
}
assertNext := func(shouldLoad bool, expectedCursor int, expectedVal string) {
if loaded := d.Next(); loaded != shouldLoad {
t.Errorf("Next(): Expected %v but got %v instead (val '%s')", shouldLoad, loaded, d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("Expected cursor to be %d, but was %d", expectedCursor, d.cursor)
}
if d.nesting != 0 {
t.Errorf("Nesting should be 0, was %d instead", d.nesting)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNext(true, 0, "host:port")
assertNext(true, 1, "dir1")
assertNext(true, 2, "arg1")
assertNext(true, 3, "dir2")
assertNext(true, 4, "arg2")
assertNext(true, 5, "arg3")
assertNext(true, 6, "dir3")
// Note: This next test simply asserts existing behavior.
// If desired, we may wish to empty the token value after
// reading past the EOF. Open an issue if you want this change.
assertNext(false, 6, "dir3")
}
func TestDispenser_NextArg(t *testing.T) {
input := `dir1 arg1
dir2 arg2 arg3
dir3`
d := newTestDispenser(input)
assertNext := func(shouldLoad bool, expectedVal string, expectedCursor int) {
if d.Next() != shouldLoad {
t.Errorf("Next(): Should load token but got false instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("Next(): Expected cursor to be at %d, but it was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNextArg := func(expectedVal string, loadAnother bool, expectedCursor int) {
if !d.NextArg() {
t.Error("NextArg(): Should load next argument but got false instead")
}
if d.cursor != expectedCursor {
t.Errorf("NextArg(): Expected cursor to be at %d, but it was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
if !loadAnother {
if d.NextArg() {
t.Fatalf("NextArg(): Should NOT load another argument, but got true instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("NextArg(): Expected cursor to remain at %d, but it was %d", expectedCursor, d.cursor)
}
}
}
assertNext(true, "dir1", 0)
assertNextArg("arg1", false, 1)
assertNext(true, "dir2", 2)
assertNextArg("arg2", true, 3)
assertNextArg("arg3", false, 4)
assertNext(true, "dir3", 5)
assertNext(false, "dir3", 5)
}
func TestDispenser_NextLine(t *testing.T) {
input := `host:port
dir1 arg1
dir2 arg2 arg3`
d := newTestDispenser(input)
assertNextLine := func(shouldLoad bool, expectedVal string, expectedCursor int) {
if d.NextLine() != shouldLoad {
t.Errorf("NextLine(): Should load token but got false instead (val: '%s')", d.Val())
}
if d.cursor != expectedCursor {
t.Errorf("NextLine(): Expected cursor to be %d, instead was %d", expectedCursor, d.cursor)
}
if val := d.Val(); val != expectedVal {
t.Errorf("Val(): Expected '%s' but got '%s'", expectedVal, val)
}
}
assertNextLine(true, "host:port", 0)
assertNextLine(true, "dir1", 1)
assertNextLine(false, "dir1", 1)
d.Next() // arg1
assertNextLine(true, "dir2", 3)
assertNextLine(false, "dir2", 3)
d.Next() // arg2
assertNextLine(false, "arg2", 4)
d.Next() // arg3
assertNextLine(false, "arg3", 5)
}
func TestDispenser_NextBlock(t *testing.T) {
input := `foobar1 {
sub1 arg1
sub2
}
foobar2 {
}`
d := newTestDispenser(input)
assertNextBlock := func(shouldLoad bool, expectedCursor, expectedNesting int) {
if loaded := d.NextBlock(0); loaded != shouldLoad {
t.Errorf("NextBlock(): Should return %v but got %v", shouldLoad, loaded)
}
if d.cursor != expectedCursor {
t.Errorf("NextBlock(): Expected cursor to be %d, was %d", expectedCursor, d.cursor)
}
if d.nesting != expectedNesting {
t.Errorf("NextBlock(): Nesting should be %d, not %d", expectedNesting, d.nesting)
}
}
assertNextBlock(false, -1, 0)
d.Next() // foobar1
assertNextBlock(true, 2, 1)
assertNextBlock(true, 3, 1)
assertNextBlock(true, 4, 1)
assertNextBlock(false, 5, 0)
d.Next() // foobar2
assertNextBlock(false, 8, 0) // empty block is as if it didn't exist
}
func TestDispenser_Args(t *testing.T) {
var s1, s2, s3 string
input := `dir1 arg1 arg2 arg3
dir2 arg4 arg5
dir3 arg6 arg7
dir4`
d := newTestDispenser(input)
d.Next() // dir1
// As many strings as arguments
if all := d.Args(&s1, &s2, &s3); !all {
t.Error("Args(): Expected true, got false")
}
if s1 != "arg1" {
t.Errorf("Args(): Expected s1 to be 'arg1', got '%s'", s1)
}
if s2 != "arg2" {
t.Errorf("Args(): Expected s2 to be 'arg2', got '%s'", s2)
}
if s3 != "arg3" {
t.Errorf("Args(): Expected s3 to be 'arg3', got '%s'", s3)
}
d.Next() // dir2
// More strings than arguments
if all := d.Args(&s1, &s2, &s3); all {
t.Error("Args(): Expected false, got true")
}
if s1 != "arg4" {
t.Errorf("Args(): Expected s1 to be 'arg4', got '%s'", s1)
}
if s2 != "arg5" {
t.Errorf("Args(): Expected s2 to be 'arg5', got '%s'", s2)
}
if s3 != "arg3" {
t.Errorf("Args(): Expected s3 to be unchanged ('arg3'), instead got '%s'", s3)
}
// (quick cursor check just for kicks and giggles)
if d.cursor != 6 {
t.Errorf("Cursor should be 6, but is %d", d.cursor)
}
d.Next() // dir3
// More arguments than strings
if all := d.Args(&s1); !all {
t.Error("Args(): Expected true, got false")
}
if s1 != "arg6" {
t.Errorf("Args(): Expected s1 to be 'arg6', got '%s'", s1)
}
d.Next() // dir4
// No arguments or strings
if all := d.Args(); !all {
t.Error("Args(): Expected true, got false")
}
// No arguments but at least one string
if all := d.Args(&s1); all {
t.Error("Args(): Expected false, got true")
}
}
func TestDispenser_RemainingArgs(t *testing.T) {
input := `dir1 arg1 arg2 arg3
dir2 arg4 arg5
dir3 arg6 { arg7
dir4`
d := newTestDispenser(input)
d.Next() // dir1
args := d.RemainingArgs()
if expected := []string{"arg1", "arg2", "arg3"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // dir2
args = d.RemainingArgs()
if expected := []string{"arg4", "arg5"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // dir3
args = d.RemainingArgs()
if expected := []string{"arg6"}; !reflect.DeepEqual(args, expected) {
t.Errorf("RemainingArgs(): Expected %v, got %v", expected, args)
}
d.Next() // {
d.Next() // arg7
d.Next() // dir4
args = d.RemainingArgs()
if len(args) != 0 {
t.Errorf("RemainingArgs(): Expected %v, got %v", []string{}, args)
}
}
func TestDispenser_ArgErr_Err(t *testing.T) {
input := `dir1 {
}
dir2 arg1 arg2`
d := newTestDispenser(input)
d.cursor = 1 // {
if err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), "{") {
t.Errorf("ArgErr(): Expected an error message with { in it, but got '%v'", err)
}
d.cursor = 5 // arg2
if err := d.ArgErr(); err == nil || !strings.Contains(err.Error(), "arg2") {
t.Errorf("ArgErr(): Expected an error message with 'arg2' in it; got '%v'", err)
}
err := d.Err("foobar")
if err == nil {
t.Fatalf("Err(): Expected an error, got nil")
}
if !strings.Contains(err.Error(), "Testfile:3") {
t.Errorf("Expected error message with filename:line in it; got '%v'", err)
}
if !strings.Contains(err.Error(), "foobar") {
t.Errorf("Expected error message with custom message in it ('foobar'); got '%v'", err)
}
}
func newTestDispenser(input string) *Dispenser {
tokens, err := allTokens("Testfile", []byte(input))
if err != nil && err != io.EOF {
log.Fatalf("getting all tokens from input: %v", err)
}
return NewDispenser(tokens)
}
| caddyconfig/caddyfile/dispenser_test.go | 1 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.26785871386528015,
0.03102928400039673,
0.00016872641572263092,
0.00017383745580445975,
0.06425442546606064
] |
{
"id": 8,
"code_window": [
"}\n",
"\n",
"func testParser(input string) parser {\n",
"\treturn parser{Dispenser: newTestDispenser(input)}\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\treturn parser{Dispenser: NewTestDispenser(input)}\n"
],
"file_path": "caddyconfig/caddyfile/parse_test.go",
"type": "replace",
"edit_start_line_idx": 672
} | // Copyright 2015 Matthew Holt and The Caddy 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 caddyfile
import (
"encoding/json"
"fmt"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig"
)
// Adapter adapts Caddyfile to Caddy JSON.
type Adapter struct {
ServerType ServerType
}
// Adapt converts the Caddyfile config in body to Caddy JSON.
func (a Adapter) Adapt(body []byte, options map[string]interface{}) ([]byte, []caddyconfig.Warning, error) {
if a.ServerType == nil {
return nil, nil, fmt.Errorf("no server type")
}
if options == nil {
options = make(map[string]interface{})
}
filename, _ := options["filename"].(string)
if filename == "" {
filename = "Caddyfile"
}
serverBlocks, err := Parse(filename, body)
if err != nil {
return nil, nil, err
}
cfg, warnings, err := a.ServerType.Setup(serverBlocks, options)
if err != nil {
return nil, warnings, err
}
marshalFunc := json.Marshal
if options["pretty"] == "true" {
marshalFunc = caddyconfig.JSONIndent
}
result, err := marshalFunc(cfg)
return result, warnings, err
}
// Unmarshaler is a type that can unmarshal
// Caddyfile tokens to set itself up for a
// JSON encoding. The goal of an unmarshaler
// is not to set itself up for actual use,
// but to set itself up for being marshaled
// into JSON. Caddyfile-unmarshaled values
// will not be used directly; they will be
// encoded as JSON and then used from that.
type Unmarshaler interface {
UnmarshalCaddyfile(d *Dispenser) error
}
// ServerType is a type that can evaluate a Caddyfile and set up a caddy config.
type ServerType interface {
// Setup takes the server blocks which
// contain tokens, as well as options
// (e.g. CLI flags) and creates a Caddy
// config, along with any warnings or
// an error.
Setup([]ServerBlock, map[string]interface{}) (*caddy.Config, []caddyconfig.Warning, error)
}
// Interface guard
var _ caddyconfig.Adapter = (*Adapter)(nil)
| caddyconfig/caddyfile/adapter.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.002182346535846591,
0.00039468531031161547,
0.0001627016463316977,
0.00017068811575882137,
0.000632055860478431
] |
{
"id": 8,
"code_window": [
"}\n",
"\n",
"func testParser(input string) parser {\n",
"\treturn parser{Dispenser: newTestDispenser(input)}\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\treturn parser{Dispenser: NewTestDispenser(input)}\n"
],
"file_path": "caddyconfig/caddyfile/parse_test.go",
"type": "replace",
"edit_start_line_idx": 672
} | // Copyright 2015 Matthew Holt and The Caddy 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 filestorage
import (
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/certmagic"
)
func init() {
caddy.RegisterModule(FileStorage{})
}
// FileStorage is a certmagic.Storage wrapper for certmagic.FileStorage.
type FileStorage struct {
Root string `json:"root,omitempty"`
}
// CaddyModule returns the Caddy module information.
func (FileStorage) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "caddy.storage.file_system",
New: func() caddy.Module { return new(FileStorage) },
}
}
// CertMagicStorage converts s to a certmagic.Storage instance.
func (s FileStorage) CertMagicStorage() (certmagic.Storage, error) {
return &certmagic.FileStorage{Path: s.Root}, nil
}
// UnmarshalCaddyfile sets up the storage module from Caddyfile tokens.
func (s *FileStorage) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
if !d.Next() {
return d.Err("expected tokens")
}
for nesting := d.Nesting(); d.NextBlock(nesting); {
if !d.NextArg() {
return d.ArgErr()
}
s.Root = d.Val()
if d.NextArg() {
return d.ArgErr()
}
}
return nil
}
// Interface guards
var (
_ caddy.StorageConverter = (*FileStorage)(nil)
_ caddyfile.Unmarshaler = (*FileStorage)(nil)
)
| modules/filestorage/filestorage.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.0002810829901136458,
0.0001874913868959993,
0.0001677747641224414,
0.00017283865599893034,
0.00003840071440208703
] |
{
"id": 8,
"code_window": [
"}\n",
"\n",
"func testParser(input string) parser {\n",
"\treturn parser{Dispenser: newTestDispenser(input)}\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\treturn parser{Dispenser: NewTestDispenser(input)}\n"
],
"file_path": "caddyconfig/caddyfile/parse_test.go",
"type": "replace",
"edit_start_line_idx": 672
} | // Copyright 2015 Matthew Holt and The Caddy 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 caddypki
import (
"crypto/x509"
"time"
"github.com/smallstep/cli/crypto/x509util"
)
func generateRoot(commonName string) (rootCrt *x509.Certificate, privateKey interface{}, err error) {
rootProfile, err := x509util.NewRootProfile(commonName)
if err != nil {
return
}
rootProfile.Subject().NotAfter = time.Now().Add(defaultRootLifetime) // TODO: make configurable
return newCert(rootProfile)
}
func generateIntermediate(commonName string, rootCrt *x509.Certificate, rootKey interface{}) (cert *x509.Certificate, privateKey interface{}, err error) {
interProfile, err := x509util.NewIntermediateProfile(commonName, rootCrt, rootKey)
if err != nil {
return
}
interProfile.Subject().NotAfter = time.Now().Add(defaultIntermediateLifetime) // TODO: make configurable
return newCert(interProfile)
}
func newCert(profile x509util.Profile) (cert *x509.Certificate, privateKey interface{}, err error) {
certBytes, err := profile.CreateCertificate()
if err != nil {
return
}
privateKey = profile.SubjectPrivateKey()
cert, err = x509.ParseCertificate(certBytes)
return
}
| modules/caddypki/certificates.go | 0 | https://github.com/caddyserver/caddy/commit/6fe04a30b102cc9aaa9d0df717c9fbb73f276139 | [
0.00018008568440563977,
0.00017439358634874225,
0.0001698495470918715,
0.00017335257143713534,
0.000004041282409161795
] |
{
"id": 0,
"code_window": [
"package status\n",
"\n",
"import (\n",
"\t\"encoding/json\"\n",
"\t\"fmt\"\n",
"\t\"strconv\"\n",
"\t\"strings\"\n",
"\t\"sync\"\n",
"\t\"time\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 17
} | // Copyright Istio 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 status
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"sync"
"time"
"github.com/gogo/protobuf/types"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/utils/clock"
"istio.io/api/meta/v1alpha1"
"istio.io/istio/pilot/pkg/features"
"istio.io/istio/pilot/pkg/model"
"istio.io/istio/pkg/config"
"istio.io/istio/pkg/config/schema/collections"
"istio.io/pkg/log"
)
var scope = log.RegisterScope("status",
"CRD distribution status debugging", 0)
type Progress struct {
AckedInstances int
TotalInstances int
}
func (p *Progress) PlusEquals(p2 Progress) {
p.TotalInstances += p2.TotalInstances
p.AckedInstances += p2.AckedInstances
}
type DistributionController struct {
configStore model.ConfigStore
mu sync.RWMutex
CurrentState map[Resource]map[string]Progress
ObservationTime map[string]time.Time
UpdateInterval time.Duration
dynamicClient dynamic.Interface
clock clock.Clock
workers WorkerQueue
StaleInterval time.Duration
cmInformer cache.SharedIndexInformer
}
func NewController(restConfig rest.Config, namespace string, cs model.ConfigStore) *DistributionController {
c := &DistributionController{
CurrentState: make(map[Resource]map[string]Progress),
ObservationTime: make(map[string]time.Time),
UpdateInterval: 200 * time.Millisecond,
StaleInterval: time.Minute,
clock: clock.RealClock{},
configStore: cs,
}
// client-go defaults to 5 QPS, with 10 Boost, which is insufficient for updating status on all the config
// in the mesh. These values can be configured using environment variables for tuning (see pilot/pkg/features)
restConfig.QPS = float32(features.StatusQPS)
restConfig.Burst = features.StatusBurst
var err error
if c.dynamicClient, err = dynamic.NewForConfig(&restConfig); err != nil {
scope.Fatalf("Could not connect to kubernetes: %s", err)
}
// configmap informer
i := informers.NewSharedInformerFactoryWithOptions(kubernetes.NewForConfigOrDie(&restConfig), 1*time.Minute,
informers.WithNamespace(namespace),
informers.WithTweakListOptions(func(listOptions *metav1.ListOptions) {
listOptions.LabelSelector = labels.Set(map[string]string{labelKey: "true"}).AsSelector().String()
})).
Core().V1().ConfigMaps()
c.cmInformer = i.Informer()
i.Informer().AddEventHandler(&DistroReportHandler{dc: c})
return c
}
func (c *DistributionController) Start(stop <-chan struct{}) {
scope.Info("Starting status leader controller")
// this will list all existing configmaps, as well as updates, right?
ctx := NewIstioContext(stop)
go c.cmInformer.Run(ctx.Done())
c.workers = NewWorkerPool(func(resource *Resource, progress *Progress) {
c.writeStatus(*resource, *progress)
}, uint(features.StatusMaxWorkers.Get()))
c.workers.Run(ctx)
// create Status Writer
t := c.clock.Tick(c.UpdateInterval)
go func() {
for {
select {
case <-ctx.Done():
return
case <-t:
staleReporters := c.writeAllStatus()
if len(staleReporters) > 0 {
c.removeStaleReporters(staleReporters)
}
}
}
}()
}
func (c *DistributionController) handleReport(d DistributionReport) {
defer c.mu.Unlock()
c.mu.Lock()
for resstr := range d.InProgressResources {
res := *ResourceFromString(resstr)
if _, ok := c.CurrentState[res]; !ok {
c.CurrentState[res] = make(map[string]Progress)
}
c.CurrentState[res][d.Reporter] = Progress{d.InProgressResources[resstr], d.DataPlaneCount}
}
c.ObservationTime[d.Reporter] = c.clock.Now()
}
func (c *DistributionController) writeAllStatus() (staleReporters []string) {
defer c.mu.RUnlock()
c.mu.RLock()
for config, fractions := range c.CurrentState {
var distributionState Progress
for reporter, w := range fractions {
// check for stale data here
if c.clock.Since(c.ObservationTime[reporter]) > c.StaleInterval {
scope.Warnf("Status reporter %s has not been heard from since %v, deleting report.",
reporter, c.ObservationTime[reporter])
staleReporters = append(staleReporters, reporter)
} else {
distributionState.PlusEquals(w)
}
}
if distributionState.TotalInstances > 0 { // this is necessary when all reports are stale.
c.queueWriteStatus(config, distributionState)
}
}
return
}
func (c *DistributionController) writeStatus(config Resource, distributionState Progress) {
schema, _ := collections.All.FindByGroupVersionResource(config.GroupVersionResource)
if schema == nil {
scope.Warnf("schema %v could not be identified", schema)
c.pruneOldVersion(config)
return
}
if !strings.HasSuffix(schema.Resource().Group(), "istio.io") {
// we don't write status for objects we don't own
return
}
current := c.configStore.Get(schema.Resource().GroupVersionKind(), config.Name, config.Namespace)
if current == nil {
scope.Warnf("config store missing entry %v, status will not update", config)
// this happens when resources are rapidly deleted, such as the validation-readiness checker
c.pruneOldVersion(config)
return
}
if config.Generation != strconv.FormatInt(current.Generation, 10) {
// this distribution report is for an old version of the object. Prune and continue.
c.pruneOldVersion(config)
return
}
// check if status needs updating
if needsReconcile, desiredStatus := ReconcileStatuses(current, distributionState, current.Generation); needsReconcile {
// technically, we should be updating probe time even when reconciling isn't needed, but
// I'm skipping that for efficiency.
current.Status = desiredStatus
_, err := c.configStore.UpdateStatus(*current)
if err != nil {
scope.Errorf("Encountered unexpected error updating status for %v, will try again later: %s", config, err)
return
}
}
}
func (c *DistributionController) pruneOldVersion(config Resource) {
defer c.mu.Unlock()
c.mu.Lock()
delete(c.CurrentState, config)
}
func (c *DistributionController) removeStaleReporters(staleReporters []string) {
defer c.mu.Unlock()
c.mu.Lock()
for key, fractions := range c.CurrentState {
for _, staleReporter := range staleReporters {
delete(fractions, staleReporter)
}
c.CurrentState[key] = fractions
}
}
func (c *DistributionController) queueWriteStatus(config Resource, state Progress) {
c.workers.Push(config, state)
}
func (c *DistributionController) configDeleted(res config.Config) {
r := ResourceFromModelConfig(res)
c.workers.Delete(*r)
}
func GetTypedStatus(in interface{}) (out v1alpha1.IstioStatus, err error) {
var statusBytes []byte
if statusBytes, err = json.Marshal(in); err == nil {
err = json.Unmarshal(statusBytes, &out)
}
return
}
func boolToConditionStatus(b bool) string {
if b {
return "True"
}
return "False"
}
func ReconcileStatuses(current *config.Config, desired Progress, generation int64) (bool, *v1alpha1.IstioStatus) {
needsReconcile := false
currentStatus, err := GetTypedStatus(current.Status)
desiredCondition := v1alpha1.IstioCondition{
Type: "Reconciled",
Status: boolToConditionStatus(desired.AckedInstances == desired.TotalInstances),
LastProbeTime: types.TimestampNow(),
LastTransitionTime: types.TimestampNow(),
Message: fmt.Sprintf("%d/%d proxies up to date.", desired.AckedInstances, desired.TotalInstances),
}
if err != nil {
// the status field is in an unexpected state.
if scope.DebugEnabled() {
scope.Debugf("Encountered unexpected status content. Overwriting status: %v", current.Status)
} else {
scope.Warn("Encountered unexpected status content. Overwriting status.")
}
currentStatus = v1alpha1.IstioStatus{
Conditions: []*v1alpha1.IstioCondition{&desiredCondition},
}
currentStatus.ObservedGeneration = generation
return true, ¤tStatus
}
var currentCondition *v1alpha1.IstioCondition
conditionIndex := -1
for i, c := range currentStatus.Conditions {
if c.Type == "Reconciled" {
currentCondition = currentStatus.Conditions[i]
conditionIndex = i
}
}
if currentCondition == nil ||
currentCondition.Message != desiredCondition.Message ||
currentCondition.Status != desiredCondition.Status {
needsReconcile = true
}
if conditionIndex > -1 {
currentStatus.Conditions[conditionIndex] = &desiredCondition
} else {
currentStatus.Conditions = append(currentStatus.Conditions, &desiredCondition)
}
currentStatus.ObservedGeneration = generation
return needsReconcile, ¤tStatus
}
type DistroReportHandler struct {
dc *DistributionController
}
func (drh *DistroReportHandler) OnAdd(obj interface{}) {
drh.HandleNew(obj)
}
func (drh *DistroReportHandler) OnUpdate(oldObj, newObj interface{}) {
drh.HandleNew(newObj)
}
func (drh *DistroReportHandler) HandleNew(obj interface{}) {
cm, ok := obj.(*v1.ConfigMap)
if !ok {
scope.Warnf("expected configmap, but received %v, discarding", obj)
return
}
rptStr := cm.Data[dataField]
scope.Debugf("using report: %s", rptStr)
dr, err := ReportFromYaml([]byte(cm.Data[dataField]))
if err != nil {
scope.Warnf("received malformed distributionReport %s, discarding: %v", cm.Name, err)
return
}
drh.dc.handleReport(dr)
}
func (drh *DistroReportHandler) OnDelete(obj interface{}) {
// TODO: what do we do here? will these ever be deleted?
}
| pilot/pkg/status/state.go | 1 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.011437910608947277,
0.0005332213477231562,
0.00016421113105025142,
0.00017028105503413826,
0.0019297761609777808
] |
{
"id": 0,
"code_window": [
"package status\n",
"\n",
"import (\n",
"\t\"encoding/json\"\n",
"\t\"fmt\"\n",
"\t\"strconv\"\n",
"\t\"strings\"\n",
"\t\"sync\"\n",
"\t\"time\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 17
} | // Copyright Istio 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 env
import (
"context"
"fmt"
"log"
"path/filepath"
"time"
"istio.io/istio/pkg/envoy"
"istio.io/pkg/env"
)
const (
liveTimeout = 10 * time.Second
waitTimeout = 3 * time.Second
)
// newEnvoy creates a new Envoy struct and starts envoy.
func (s *TestSetup) newEnvoy() (envoy.Instance, error) {
confPath := filepath.Join(IstioOut, fmt.Sprintf("config.conf.%v.yaml", s.ports.AdminPort))
log.Printf("Envoy config: in %v\n", confPath)
if err := s.CreateEnvoyConf(confPath); err != nil {
return nil, err
}
debugLevel := env.RegisterStringVar("ENVOY_DEBUG", "info", "Specifies the debug level for Envoy.").Get()
options := []envoy.Option{
envoy.ConfigPath(confPath),
envoy.DrainDuration(1 * time.Second),
}
if s.stress {
options = append(options, envoy.Concurrency(10))
} else {
// debug is far too verbose.
options = append(options,
envoy.LogLevel(debugLevel),
envoy.Concurrency(1))
}
if s.disableHotRestart {
options = append(options, envoy.DisableHotRestart(true))
} else {
options = append(options,
envoy.BaseID(uint32(s.testName)),
envoy.ParentShutdownDuration(1*time.Second),
envoy.Epoch(s.epoch))
}
if s.EnvoyParams != nil {
o, err := envoy.NewOptions(s.EnvoyParams...)
if err != nil {
return nil, err
}
options = append(options, o...)
}
/* #nosec */
// Since we are possible running in a container, the OS may be different that what we are building (we build for host OS),
// we need to use the local container's OS bin found in LOCAL_OUT
envoyPath := filepath.Join(LocalOut, "envoy")
if path, exists := env.RegisterStringVar("ENVOY_PATH", "", "Specifies the path to an Envoy binary.").Lookup(); exists {
envoyPath = path
}
i, err := envoy.New(envoy.Config{
Name: fmt.Sprintf("envoy-%d", uint32(s.testName)),
AdminPort: uint32(s.ports.AdminPort),
BinaryPath: envoyPath,
WorkingDir: s.Dir,
SkipBaseIDClose: true,
Options: options,
})
if err != nil {
return nil, err
}
return i, nil
}
// startEnvoy starts the envoy process
func startEnvoy(e envoy.Instance) error {
return e.Start(context.Background()).WaitLive().WithTimeout(liveTimeout).Do()
}
// stopEnvoy stops the envoy process
func stopEnvoy(e envoy.Instance) error {
log.Printf("stop envoy ...\n")
if e == nil {
return nil
}
err := e.ShutdownAndWait().WithTimeout(waitTimeout).Do()
if err == context.DeadlineExceeded {
return e.KillAndWait().WithTimeout(waitTimeout).Do()
}
return err
}
// removeEnvoySharedMemory removes shared memory left by Envoy
func removeEnvoySharedMemory(e envoy.Instance) {
if err := e.BaseID().Close(); err != nil {
log.Printf("failed to remove Envoy's shared memory: %s\n", err)
} else {
log.Printf("removed Envoy's shared memory\n")
}
}
| pkg/test/env/envoy.go | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.00017489401216153055,
0.00017005410336423665,
0.00016610798775218427,
0.00017036724602803588,
0.0000028314186693023657
] |
{
"id": 0,
"code_window": [
"package status\n",
"\n",
"import (\n",
"\t\"encoding/json\"\n",
"\t\"fmt\"\n",
"\t\"strconv\"\n",
"\t\"strings\"\n",
"\t\"sync\"\n",
"\t\"time\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 17
} | // Copyright Istio 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 tpath
import (
"testing"
"github.com/ghodss/yaml"
"istio.io/istio/operator/pkg/util"
)
func TestGetFromStructPath(t *testing.T) {
tests := []struct {
desc string
nodeYAML string
path string
wantYAML string
wantFound bool
wantErr string
}{
{
desc: "GetStructItem",
nodeYAML: `
a: va
b: vb
c:
d: vd
e:
f: vf
g:
h:
- i: vi
j: vj
k:
l:
m: vm
n: vn
`,
path: "c",
wantYAML: `
d: vd
e:
f: vf
`,
wantFound: true,
},
{
desc: "GetSliceEntryItem",
nodeYAML: `
a: va
b: vb
c:
d: vd
e:
f: vf
g:
h:
- i: vi
j: vj
k:
l:
m: vm
n: vm
`,
path: "g.h.0",
wantYAML: `
i: vi
j: vj
k:
l:
m: vm
n: vm
`,
wantFound: true,
},
{
desc: "GetMapEntryItem",
nodeYAML: `
a: va
b: vb
c:
d: vd
e:
f: vf
g:
h:
- i: vi
j: vj
k:
l:
m: vm
n: vm
`,
path: "g.h.0.k",
wantYAML: `
l:
m: vm
n: vm
`,
wantFound: true,
},
{
desc: "GetPathNotExists",
nodeYAML: `
a: va
b: vb
c:
d: vd
e:
f: vf
g:
h:
- i: vi
j: vj
k:
l:
m: vm
n: vm
`,
path: "c.d.e",
wantFound: false,
wantErr: "getFromStructPath path e, unsupported type string",
},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
rnode := make(map[string]interface{})
if err := yaml.Unmarshal([]byte(tt.nodeYAML), &rnode); err != nil {
t.Fatal(err)
}
GotOut, GotFound, gotErr := GetFromStructPath(rnode, tt.path)
if GotFound != tt.wantFound {
t.Fatalf("GetFromStructPath(%s): gotFound:%v, wantFound:%v", tt.desc, GotFound, tt.wantFound)
}
if gotErr, wantErr := errToString(gotErr), tt.wantErr; gotErr != wantErr {
t.Fatalf("GetFromStructPath(%s): gotErr:%s, wantErr:%s", tt.desc, gotErr, wantErr)
}
if tt.wantErr != "" || !tt.wantFound {
return
}
gotYAML := util.ToYAML(GotOut)
diff := util.YAMLDiff(gotYAML, tt.wantYAML)
if diff != "" {
t.Errorf("GetFromStructPath(%s): YAML of gotOut:\n%s\n, YAML of wantOut:\n%s\n, diff:\n%s\n", tt.desc, gotYAML, tt.wantYAML, diff)
}
})
}
}
| operator/pkg/tpath/struct_test.go | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.00017626430781092495,
0.00017192645464092493,
0.00016711806529201567,
0.00017273124831262976,
0.00000285245096165454
] |
{
"id": 0,
"code_window": [
"package status\n",
"\n",
"import (\n",
"\t\"encoding/json\"\n",
"\t\"fmt\"\n",
"\t\"strconv\"\n",
"\t\"strings\"\n",
"\t\"sync\"\n",
"\t\"time\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 17
} | apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: reviews
spec:
hosts:
- reviews
http:
- route:
- destination:
host: reviews
subset: v3
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: ratings
spec:
hosts:
- ratings
http:
- route:
- destination:
host: ratings
subset: v2-mysql-vm
---
| samples/bookinfo/networking/virtual-service-ratings-mysql-vm.yaml | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.00017210684018209577,
0.00017015403136610985,
0.00016790359222795814,
0.00017045163258444518,
0.000001728824713609356
] |
{
"id": 1,
"code_window": [
"func (c *DistributionController) configDeleted(res config.Config) {\n",
"\tr := ResourceFromModelConfig(res)\n",
"\tc.workers.Delete(*r)\n",
"}\n",
"\n",
"func GetTypedStatus(in interface{}) (out v1alpha1.IstioStatus, err error) {\n",
"\tvar statusBytes []byte\n",
"\tif statusBytes, err = json.Marshal(in); err == nil {\n",
"\t\terr = json.Unmarshal(statusBytes, &out)\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"func GetTypedStatus(in interface{}) (out *v1alpha1.IstioStatus, err error) {\n",
"\tif ret, ok := in.(*v1alpha1.IstioStatus); ok {\n",
"\t\treturn ret, nil\n"
],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 229
} | // Copyright Istio 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 status
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"sync"
"time"
"github.com/gogo/protobuf/types"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/utils/clock"
"istio.io/api/meta/v1alpha1"
"istio.io/istio/pilot/pkg/features"
"istio.io/istio/pilot/pkg/model"
"istio.io/istio/pkg/config"
"istio.io/istio/pkg/config/schema/collections"
"istio.io/pkg/log"
)
var scope = log.RegisterScope("status",
"CRD distribution status debugging", 0)
type Progress struct {
AckedInstances int
TotalInstances int
}
func (p *Progress) PlusEquals(p2 Progress) {
p.TotalInstances += p2.TotalInstances
p.AckedInstances += p2.AckedInstances
}
type DistributionController struct {
configStore model.ConfigStore
mu sync.RWMutex
CurrentState map[Resource]map[string]Progress
ObservationTime map[string]time.Time
UpdateInterval time.Duration
dynamicClient dynamic.Interface
clock clock.Clock
workers WorkerQueue
StaleInterval time.Duration
cmInformer cache.SharedIndexInformer
}
func NewController(restConfig rest.Config, namespace string, cs model.ConfigStore) *DistributionController {
c := &DistributionController{
CurrentState: make(map[Resource]map[string]Progress),
ObservationTime: make(map[string]time.Time),
UpdateInterval: 200 * time.Millisecond,
StaleInterval: time.Minute,
clock: clock.RealClock{},
configStore: cs,
}
// client-go defaults to 5 QPS, with 10 Boost, which is insufficient for updating status on all the config
// in the mesh. These values can be configured using environment variables for tuning (see pilot/pkg/features)
restConfig.QPS = float32(features.StatusQPS)
restConfig.Burst = features.StatusBurst
var err error
if c.dynamicClient, err = dynamic.NewForConfig(&restConfig); err != nil {
scope.Fatalf("Could not connect to kubernetes: %s", err)
}
// configmap informer
i := informers.NewSharedInformerFactoryWithOptions(kubernetes.NewForConfigOrDie(&restConfig), 1*time.Minute,
informers.WithNamespace(namespace),
informers.WithTweakListOptions(func(listOptions *metav1.ListOptions) {
listOptions.LabelSelector = labels.Set(map[string]string{labelKey: "true"}).AsSelector().String()
})).
Core().V1().ConfigMaps()
c.cmInformer = i.Informer()
i.Informer().AddEventHandler(&DistroReportHandler{dc: c})
return c
}
func (c *DistributionController) Start(stop <-chan struct{}) {
scope.Info("Starting status leader controller")
// this will list all existing configmaps, as well as updates, right?
ctx := NewIstioContext(stop)
go c.cmInformer.Run(ctx.Done())
c.workers = NewWorkerPool(func(resource *Resource, progress *Progress) {
c.writeStatus(*resource, *progress)
}, uint(features.StatusMaxWorkers.Get()))
c.workers.Run(ctx)
// create Status Writer
t := c.clock.Tick(c.UpdateInterval)
go func() {
for {
select {
case <-ctx.Done():
return
case <-t:
staleReporters := c.writeAllStatus()
if len(staleReporters) > 0 {
c.removeStaleReporters(staleReporters)
}
}
}
}()
}
func (c *DistributionController) handleReport(d DistributionReport) {
defer c.mu.Unlock()
c.mu.Lock()
for resstr := range d.InProgressResources {
res := *ResourceFromString(resstr)
if _, ok := c.CurrentState[res]; !ok {
c.CurrentState[res] = make(map[string]Progress)
}
c.CurrentState[res][d.Reporter] = Progress{d.InProgressResources[resstr], d.DataPlaneCount}
}
c.ObservationTime[d.Reporter] = c.clock.Now()
}
func (c *DistributionController) writeAllStatus() (staleReporters []string) {
defer c.mu.RUnlock()
c.mu.RLock()
for config, fractions := range c.CurrentState {
var distributionState Progress
for reporter, w := range fractions {
// check for stale data here
if c.clock.Since(c.ObservationTime[reporter]) > c.StaleInterval {
scope.Warnf("Status reporter %s has not been heard from since %v, deleting report.",
reporter, c.ObservationTime[reporter])
staleReporters = append(staleReporters, reporter)
} else {
distributionState.PlusEquals(w)
}
}
if distributionState.TotalInstances > 0 { // this is necessary when all reports are stale.
c.queueWriteStatus(config, distributionState)
}
}
return
}
func (c *DistributionController) writeStatus(config Resource, distributionState Progress) {
schema, _ := collections.All.FindByGroupVersionResource(config.GroupVersionResource)
if schema == nil {
scope.Warnf("schema %v could not be identified", schema)
c.pruneOldVersion(config)
return
}
if !strings.HasSuffix(schema.Resource().Group(), "istio.io") {
// we don't write status for objects we don't own
return
}
current := c.configStore.Get(schema.Resource().GroupVersionKind(), config.Name, config.Namespace)
if current == nil {
scope.Warnf("config store missing entry %v, status will not update", config)
// this happens when resources are rapidly deleted, such as the validation-readiness checker
c.pruneOldVersion(config)
return
}
if config.Generation != strconv.FormatInt(current.Generation, 10) {
// this distribution report is for an old version of the object. Prune and continue.
c.pruneOldVersion(config)
return
}
// check if status needs updating
if needsReconcile, desiredStatus := ReconcileStatuses(current, distributionState, current.Generation); needsReconcile {
// technically, we should be updating probe time even when reconciling isn't needed, but
// I'm skipping that for efficiency.
current.Status = desiredStatus
_, err := c.configStore.UpdateStatus(*current)
if err != nil {
scope.Errorf("Encountered unexpected error updating status for %v, will try again later: %s", config, err)
return
}
}
}
func (c *DistributionController) pruneOldVersion(config Resource) {
defer c.mu.Unlock()
c.mu.Lock()
delete(c.CurrentState, config)
}
func (c *DistributionController) removeStaleReporters(staleReporters []string) {
defer c.mu.Unlock()
c.mu.Lock()
for key, fractions := range c.CurrentState {
for _, staleReporter := range staleReporters {
delete(fractions, staleReporter)
}
c.CurrentState[key] = fractions
}
}
func (c *DistributionController) queueWriteStatus(config Resource, state Progress) {
c.workers.Push(config, state)
}
func (c *DistributionController) configDeleted(res config.Config) {
r := ResourceFromModelConfig(res)
c.workers.Delete(*r)
}
func GetTypedStatus(in interface{}) (out v1alpha1.IstioStatus, err error) {
var statusBytes []byte
if statusBytes, err = json.Marshal(in); err == nil {
err = json.Unmarshal(statusBytes, &out)
}
return
}
func boolToConditionStatus(b bool) string {
if b {
return "True"
}
return "False"
}
func ReconcileStatuses(current *config.Config, desired Progress, generation int64) (bool, *v1alpha1.IstioStatus) {
needsReconcile := false
currentStatus, err := GetTypedStatus(current.Status)
desiredCondition := v1alpha1.IstioCondition{
Type: "Reconciled",
Status: boolToConditionStatus(desired.AckedInstances == desired.TotalInstances),
LastProbeTime: types.TimestampNow(),
LastTransitionTime: types.TimestampNow(),
Message: fmt.Sprintf("%d/%d proxies up to date.", desired.AckedInstances, desired.TotalInstances),
}
if err != nil {
// the status field is in an unexpected state.
if scope.DebugEnabled() {
scope.Debugf("Encountered unexpected status content. Overwriting status: %v", current.Status)
} else {
scope.Warn("Encountered unexpected status content. Overwriting status.")
}
currentStatus = v1alpha1.IstioStatus{
Conditions: []*v1alpha1.IstioCondition{&desiredCondition},
}
currentStatus.ObservedGeneration = generation
return true, ¤tStatus
}
var currentCondition *v1alpha1.IstioCondition
conditionIndex := -1
for i, c := range currentStatus.Conditions {
if c.Type == "Reconciled" {
currentCondition = currentStatus.Conditions[i]
conditionIndex = i
}
}
if currentCondition == nil ||
currentCondition.Message != desiredCondition.Message ||
currentCondition.Status != desiredCondition.Status {
needsReconcile = true
}
if conditionIndex > -1 {
currentStatus.Conditions[conditionIndex] = &desiredCondition
} else {
currentStatus.Conditions = append(currentStatus.Conditions, &desiredCondition)
}
currentStatus.ObservedGeneration = generation
return needsReconcile, ¤tStatus
}
type DistroReportHandler struct {
dc *DistributionController
}
func (drh *DistroReportHandler) OnAdd(obj interface{}) {
drh.HandleNew(obj)
}
func (drh *DistroReportHandler) OnUpdate(oldObj, newObj interface{}) {
drh.HandleNew(newObj)
}
func (drh *DistroReportHandler) HandleNew(obj interface{}) {
cm, ok := obj.(*v1.ConfigMap)
if !ok {
scope.Warnf("expected configmap, but received %v, discarding", obj)
return
}
rptStr := cm.Data[dataField]
scope.Debugf("using report: %s", rptStr)
dr, err := ReportFromYaml([]byte(cm.Data[dataField]))
if err != nil {
scope.Warnf("received malformed distributionReport %s, discarding: %v", cm.Name, err)
return
}
drh.dc.handleReport(dr)
}
func (drh *DistroReportHandler) OnDelete(obj interface{}) {
// TODO: what do we do here? will these ever be deleted?
}
| pilot/pkg/status/state.go | 1 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.999243974685669,
0.09321621805429459,
0.0001666108291829005,
0.00044597277883440256,
0.28613734245300293
] |
{
"id": 1,
"code_window": [
"func (c *DistributionController) configDeleted(res config.Config) {\n",
"\tr := ResourceFromModelConfig(res)\n",
"\tc.workers.Delete(*r)\n",
"}\n",
"\n",
"func GetTypedStatus(in interface{}) (out v1alpha1.IstioStatus, err error) {\n",
"\tvar statusBytes []byte\n",
"\tif statusBytes, err = json.Marshal(in); err == nil {\n",
"\t\terr = json.Unmarshal(statusBytes, &out)\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"func GetTypedStatus(in interface{}) (out *v1alpha1.IstioStatus, err error) {\n",
"\tif ret, ok := in.(*v1alpha1.IstioStatus); ok {\n",
"\t\treturn ret, nil\n"
],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 229
} | module istio.io/istio/samples/extauthz/src
go 1.15
require (
github.com/envoyproxy/go-control-plane v0.9.7
github.com/gogo/googleapis v1.4.0
golang.org/x/net v0.0.0-20201031054903-ff519b6c9102
google.golang.org/genproto v0.0.0-20201102152239-715cce707fb0
google.golang.org/grpc v1.33.1
)
| samples/extauthz/src/go.mod | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.00017039979866240174,
0.0001691502402536571,
0.0001679006963968277,
0.0001691502402536571,
0.000001249551132787019
] |
{
"id": 1,
"code_window": [
"func (c *DistributionController) configDeleted(res config.Config) {\n",
"\tr := ResourceFromModelConfig(res)\n",
"\tc.workers.Delete(*r)\n",
"}\n",
"\n",
"func GetTypedStatus(in interface{}) (out v1alpha1.IstioStatus, err error) {\n",
"\tvar statusBytes []byte\n",
"\tif statusBytes, err = json.Marshal(in); err == nil {\n",
"\t\terr = json.Unmarshal(statusBytes, &out)\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"func GetTypedStatus(in interface{}) (out *v1alpha1.IstioStatus, err error) {\n",
"\tif ret, ok := in.(*v1alpha1.IstioStatus); ok {\n",
"\t\treturn ret, nil\n"
],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 229
} | // Copyright Istio 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 main
import (
"bufio"
"net"
"os"
"strings"
"testing"
"time"
)
// TestTcpEchoServer tests the behavior of the TCP Echo Server.
func TestTcpEchoServer(t *testing.T) {
// set up test parameters
prefix := "hello"
request := "world"
want := prefix + " " + request
// start the TCP Echo Server
os.Args = []string{"main", "9000,9001", prefix}
go main()
// wait for the TCP Echo Server to start
time.Sleep(2 * time.Second)
for _, addr := range []string{":9000", ":9001"} {
// connect to the TCP Echo Server
conn, err := net.Dial("tcp", addr)
if err != nil {
t.Fatalf("couldn't connect to the server: %v", err)
}
defer conn.Close()
// test the TCP Echo Server output
if _, err := conn.Write([]byte(request + "\n")); err != nil {
t.Fatalf("couldn't send request: %v", err)
} else {
reader := bufio.NewReader(conn)
if response, err := reader.ReadBytes(byte('\n')); err != nil {
t.Fatalf("couldn't read server response: %v", err)
} else if !strings.HasPrefix(string(response), want) {
t.Errorf("output doesn't match, wanted: %s, got: %s", want, response)
}
}
}
}
| samples/tcp-echo/src/main_test.go | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.00024135818239301443,
0.00018492071831133217,
0.000167801947100088,
0.00017350558482576162,
0.000024458680854877457
] |
{
"id": 1,
"code_window": [
"func (c *DistributionController) configDeleted(res config.Config) {\n",
"\tr := ResourceFromModelConfig(res)\n",
"\tc.workers.Delete(*r)\n",
"}\n",
"\n",
"func GetTypedStatus(in interface{}) (out v1alpha1.IstioStatus, err error) {\n",
"\tvar statusBytes []byte\n",
"\tif statusBytes, err = json.Marshal(in); err == nil {\n",
"\t\terr = json.Unmarshal(statusBytes, &out)\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"func GetTypedStatus(in interface{}) (out *v1alpha1.IstioStatus, err error) {\n",
"\tif ret, ok := in.(*v1alpha1.IstioStatus); ok {\n",
"\t\treturn ret, nil\n"
],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 229
} | #!/bin/bash
# WARNING: DO NOT EDIT, THIS FILE IS PROBABLY A COPY
#
# The original version of this file is located in the https://github.com/istio/common-files repo.
# If you're looking at this file in a different repo and want to make a change, please go to the
# common-files repo, make the change there and check it in. Then come back to this repo and run
# "make update-common".
# Copyright Istio Authors. All Rights Reserved.
#
# 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.
# This script builds and version stamps the output
VERBOSE=${VERBOSE:-"0"}
V=""
if [[ "${VERBOSE}" == "1" ]];then
V="-x"
set -x
fi
SCRIPTPATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
OUT=${1:?"output path"}
shift
set -e
BUILD_GOOS=${GOOS:-linux}
BUILD_GOARCH=${GOARCH:-amd64}
GOBINARY=${GOBINARY:-go}
GOPKG="$GOPATH/pkg"
BUILDINFO=${BUILDINFO:-""}
STATIC=${STATIC:-1}
LDFLAGS=${LDFLAGS:--extldflags -static}
GOBUILDFLAGS=${GOBUILDFLAGS:-""}
# Split GOBUILDFLAGS by spaces into an array called GOBUILDFLAGS_ARRAY.
IFS=' ' read -r -a GOBUILDFLAGS_ARRAY <<< "$GOBUILDFLAGS"
GCFLAGS=${GCFLAGS:-}
export CGO_ENABLED=0
if [[ "${STATIC}" != "1" ]];then
LDFLAGS=""
fi
# gather buildinfo if not already provided
# For a release build BUILDINFO should be produced
# at the beginning of the build and used throughout
if [[ -z ${BUILDINFO} ]];then
BUILDINFO=$(mktemp)
"${SCRIPTPATH}/report_build_info.sh" > "${BUILDINFO}"
fi
# BUILD LD_EXTRAFLAGS
LD_EXTRAFLAGS=""
while read -r line; do
LD_EXTRAFLAGS="${LD_EXTRAFLAGS} -X ${line}"
done < "${BUILDINFO}"
# verify go version before build
# NB. this was copied verbatim from Kubernetes hack
minimum_go_version=go1.13 # supported patterns: go1.x, go1.x.x (x should be a number)
IFS=" " read -ra go_version <<< "$(${GOBINARY} version)"
if [[ "${minimum_go_version}" != $(echo -e "${minimum_go_version}\n${go_version[2]}" | sort -s -t. -k 1,1 -k 2,2n -k 3,3n | head -n1) && "${go_version[2]}" != "devel" ]]; then
echo "Warning: Detected that you are using an older version of the Go compiler. Istio requires ${minimum_go_version} or greater."
fi
OPTIMIZATION_FLAGS=(-trimpath)
if [ "${DEBUG}" == "1" ]; then
OPTIMIZATION_FLAGS=()
fi
time GOOS=${BUILD_GOOS} GOARCH=${BUILD_GOARCH} ${GOBINARY} build \
${V} "${GOBUILDFLAGS_ARRAY[@]}" ${GCFLAGS:+-gcflags "${GCFLAGS}"} \
-o "${OUT}" \
"${OPTIMIZATION_FLAGS[@]}" \
-pkgdir="${GOPKG}/${BUILD_GOOS}_${BUILD_GOARCH}" \
-ldflags "${LDFLAGS} ${LD_EXTRAFLAGS}" "${@}"
| common/scripts/gobuild.sh | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.000672322406899184,
0.0002269437100039795,
0.00016739667626097798,
0.00017164813471026719,
0.00014955142978578806
] |
{
"id": 2,
"code_window": [
"\t}\n",
"\treturn\n",
"}\n",
"\n",
"func boolToConditionStatus(b bool) string {\n",
"\tif b {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\treturn nil, fmt.Errorf(\"cannot cast %t: %v to IstioStatus\", in, in)\n"
],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 234
} | // Copyright Istio 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 status
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"sync"
"time"
"github.com/gogo/protobuf/types"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/utils/clock"
"istio.io/api/meta/v1alpha1"
"istio.io/istio/pilot/pkg/features"
"istio.io/istio/pilot/pkg/model"
"istio.io/istio/pkg/config"
"istio.io/istio/pkg/config/schema/collections"
"istio.io/pkg/log"
)
var scope = log.RegisterScope("status",
"CRD distribution status debugging", 0)
type Progress struct {
AckedInstances int
TotalInstances int
}
func (p *Progress) PlusEquals(p2 Progress) {
p.TotalInstances += p2.TotalInstances
p.AckedInstances += p2.AckedInstances
}
type DistributionController struct {
configStore model.ConfigStore
mu sync.RWMutex
CurrentState map[Resource]map[string]Progress
ObservationTime map[string]time.Time
UpdateInterval time.Duration
dynamicClient dynamic.Interface
clock clock.Clock
workers WorkerQueue
StaleInterval time.Duration
cmInformer cache.SharedIndexInformer
}
func NewController(restConfig rest.Config, namespace string, cs model.ConfigStore) *DistributionController {
c := &DistributionController{
CurrentState: make(map[Resource]map[string]Progress),
ObservationTime: make(map[string]time.Time),
UpdateInterval: 200 * time.Millisecond,
StaleInterval: time.Minute,
clock: clock.RealClock{},
configStore: cs,
}
// client-go defaults to 5 QPS, with 10 Boost, which is insufficient for updating status on all the config
// in the mesh. These values can be configured using environment variables for tuning (see pilot/pkg/features)
restConfig.QPS = float32(features.StatusQPS)
restConfig.Burst = features.StatusBurst
var err error
if c.dynamicClient, err = dynamic.NewForConfig(&restConfig); err != nil {
scope.Fatalf("Could not connect to kubernetes: %s", err)
}
// configmap informer
i := informers.NewSharedInformerFactoryWithOptions(kubernetes.NewForConfigOrDie(&restConfig), 1*time.Minute,
informers.WithNamespace(namespace),
informers.WithTweakListOptions(func(listOptions *metav1.ListOptions) {
listOptions.LabelSelector = labels.Set(map[string]string{labelKey: "true"}).AsSelector().String()
})).
Core().V1().ConfigMaps()
c.cmInformer = i.Informer()
i.Informer().AddEventHandler(&DistroReportHandler{dc: c})
return c
}
func (c *DistributionController) Start(stop <-chan struct{}) {
scope.Info("Starting status leader controller")
// this will list all existing configmaps, as well as updates, right?
ctx := NewIstioContext(stop)
go c.cmInformer.Run(ctx.Done())
c.workers = NewWorkerPool(func(resource *Resource, progress *Progress) {
c.writeStatus(*resource, *progress)
}, uint(features.StatusMaxWorkers.Get()))
c.workers.Run(ctx)
// create Status Writer
t := c.clock.Tick(c.UpdateInterval)
go func() {
for {
select {
case <-ctx.Done():
return
case <-t:
staleReporters := c.writeAllStatus()
if len(staleReporters) > 0 {
c.removeStaleReporters(staleReporters)
}
}
}
}()
}
func (c *DistributionController) handleReport(d DistributionReport) {
defer c.mu.Unlock()
c.mu.Lock()
for resstr := range d.InProgressResources {
res := *ResourceFromString(resstr)
if _, ok := c.CurrentState[res]; !ok {
c.CurrentState[res] = make(map[string]Progress)
}
c.CurrentState[res][d.Reporter] = Progress{d.InProgressResources[resstr], d.DataPlaneCount}
}
c.ObservationTime[d.Reporter] = c.clock.Now()
}
func (c *DistributionController) writeAllStatus() (staleReporters []string) {
defer c.mu.RUnlock()
c.mu.RLock()
for config, fractions := range c.CurrentState {
var distributionState Progress
for reporter, w := range fractions {
// check for stale data here
if c.clock.Since(c.ObservationTime[reporter]) > c.StaleInterval {
scope.Warnf("Status reporter %s has not been heard from since %v, deleting report.",
reporter, c.ObservationTime[reporter])
staleReporters = append(staleReporters, reporter)
} else {
distributionState.PlusEquals(w)
}
}
if distributionState.TotalInstances > 0 { // this is necessary when all reports are stale.
c.queueWriteStatus(config, distributionState)
}
}
return
}
func (c *DistributionController) writeStatus(config Resource, distributionState Progress) {
schema, _ := collections.All.FindByGroupVersionResource(config.GroupVersionResource)
if schema == nil {
scope.Warnf("schema %v could not be identified", schema)
c.pruneOldVersion(config)
return
}
if !strings.HasSuffix(schema.Resource().Group(), "istio.io") {
// we don't write status for objects we don't own
return
}
current := c.configStore.Get(schema.Resource().GroupVersionKind(), config.Name, config.Namespace)
if current == nil {
scope.Warnf("config store missing entry %v, status will not update", config)
// this happens when resources are rapidly deleted, such as the validation-readiness checker
c.pruneOldVersion(config)
return
}
if config.Generation != strconv.FormatInt(current.Generation, 10) {
// this distribution report is for an old version of the object. Prune and continue.
c.pruneOldVersion(config)
return
}
// check if status needs updating
if needsReconcile, desiredStatus := ReconcileStatuses(current, distributionState, current.Generation); needsReconcile {
// technically, we should be updating probe time even when reconciling isn't needed, but
// I'm skipping that for efficiency.
current.Status = desiredStatus
_, err := c.configStore.UpdateStatus(*current)
if err != nil {
scope.Errorf("Encountered unexpected error updating status for %v, will try again later: %s", config, err)
return
}
}
}
func (c *DistributionController) pruneOldVersion(config Resource) {
defer c.mu.Unlock()
c.mu.Lock()
delete(c.CurrentState, config)
}
func (c *DistributionController) removeStaleReporters(staleReporters []string) {
defer c.mu.Unlock()
c.mu.Lock()
for key, fractions := range c.CurrentState {
for _, staleReporter := range staleReporters {
delete(fractions, staleReporter)
}
c.CurrentState[key] = fractions
}
}
func (c *DistributionController) queueWriteStatus(config Resource, state Progress) {
c.workers.Push(config, state)
}
func (c *DistributionController) configDeleted(res config.Config) {
r := ResourceFromModelConfig(res)
c.workers.Delete(*r)
}
func GetTypedStatus(in interface{}) (out v1alpha1.IstioStatus, err error) {
var statusBytes []byte
if statusBytes, err = json.Marshal(in); err == nil {
err = json.Unmarshal(statusBytes, &out)
}
return
}
func boolToConditionStatus(b bool) string {
if b {
return "True"
}
return "False"
}
func ReconcileStatuses(current *config.Config, desired Progress, generation int64) (bool, *v1alpha1.IstioStatus) {
needsReconcile := false
currentStatus, err := GetTypedStatus(current.Status)
desiredCondition := v1alpha1.IstioCondition{
Type: "Reconciled",
Status: boolToConditionStatus(desired.AckedInstances == desired.TotalInstances),
LastProbeTime: types.TimestampNow(),
LastTransitionTime: types.TimestampNow(),
Message: fmt.Sprintf("%d/%d proxies up to date.", desired.AckedInstances, desired.TotalInstances),
}
if err != nil {
// the status field is in an unexpected state.
if scope.DebugEnabled() {
scope.Debugf("Encountered unexpected status content. Overwriting status: %v", current.Status)
} else {
scope.Warn("Encountered unexpected status content. Overwriting status.")
}
currentStatus = v1alpha1.IstioStatus{
Conditions: []*v1alpha1.IstioCondition{&desiredCondition},
}
currentStatus.ObservedGeneration = generation
return true, ¤tStatus
}
var currentCondition *v1alpha1.IstioCondition
conditionIndex := -1
for i, c := range currentStatus.Conditions {
if c.Type == "Reconciled" {
currentCondition = currentStatus.Conditions[i]
conditionIndex = i
}
}
if currentCondition == nil ||
currentCondition.Message != desiredCondition.Message ||
currentCondition.Status != desiredCondition.Status {
needsReconcile = true
}
if conditionIndex > -1 {
currentStatus.Conditions[conditionIndex] = &desiredCondition
} else {
currentStatus.Conditions = append(currentStatus.Conditions, &desiredCondition)
}
currentStatus.ObservedGeneration = generation
return needsReconcile, ¤tStatus
}
type DistroReportHandler struct {
dc *DistributionController
}
func (drh *DistroReportHandler) OnAdd(obj interface{}) {
drh.HandleNew(obj)
}
func (drh *DistroReportHandler) OnUpdate(oldObj, newObj interface{}) {
drh.HandleNew(newObj)
}
func (drh *DistroReportHandler) HandleNew(obj interface{}) {
cm, ok := obj.(*v1.ConfigMap)
if !ok {
scope.Warnf("expected configmap, but received %v, discarding", obj)
return
}
rptStr := cm.Data[dataField]
scope.Debugf("using report: %s", rptStr)
dr, err := ReportFromYaml([]byte(cm.Data[dataField]))
if err != nil {
scope.Warnf("received malformed distributionReport %s, discarding: %v", cm.Name, err)
return
}
drh.dc.handleReport(dr)
}
func (drh *DistroReportHandler) OnDelete(obj interface{}) {
// TODO: what do we do here? will these ever be deleted?
}
| pilot/pkg/status/state.go | 1 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.9992343187332153,
0.062422845512628555,
0.00016882877389434725,
0.00018002971773967147,
0.23517164587974548
] |
{
"id": 2,
"code_window": [
"\t}\n",
"\treturn\n",
"}\n",
"\n",
"func boolToConditionStatus(b bool) string {\n",
"\tif b {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\treturn nil, fmt.Errorf(\"cannot cast %t: %v to IstioStatus\", in, in)\n"
],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 234
} | Copyright (c) 2012 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| licenses/gopkg.in/square/go-jose.v2/json/LICENSE | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.0001712859666440636,
0.00016943213995546103,
0.0001669046760071069,
0.00017010580631904304,
0.0000018509973642721889
] |
{
"id": 2,
"code_window": [
"\t}\n",
"\treturn\n",
"}\n",
"\n",
"func boolToConditionStatus(b bool) string {\n",
"\tif b {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\treturn nil, fmt.Errorf(\"cannot cast %t: %v to IstioStatus\", in, in)\n"
],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 234
} | apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: direct-bing-through-egress-gateway
spec:
hosts:
- bing.com
gateways:
- istio-egressgateway
- mesh
http:
- match:
- gateways:
- mesh
port: 80
route:
- destination:
host: istio-egressgateway.istio-system.svc.cluster.local
subset: bing
port:
number: 80
weight: 100
- match:
- gateways:
- istio-egressgateway
port: 80
route:
- destination:
host: bing.com
port:
number: 80
weight: 100 | tests/integration/security/sds_egress/testdata/rule-route-sidecar-to-egress-bing.yaml | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.00023392205184791237,
0.00018598116002976894,
0.00016460100596304983,
0.00017270077660214156,
0.000028017995646223426
] |
{
"id": 2,
"code_window": [
"\t}\n",
"\treturn\n",
"}\n",
"\n",
"func boolToConditionStatus(b bool) string {\n",
"\tif b {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\treturn nil, fmt.Errorf(\"cannot cast %t: %v to IstioStatus\", in, in)\n"
],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 234
} | // Copyright Istio 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 mock
import "time"
// FakeCertUtil is a mocked CertUtil for testing.
type FakeCertUtil struct {
Duration time.Duration
Err error
}
// GetWaitTime returns duration if err is nil, otherwise, it returns err.
func (f FakeCertUtil) GetWaitTime(certBytes []byte, now time.Time, minGracePeriod time.Duration) (time.Duration, error) {
if f.Err != nil {
return time.Duration(0), f.Err
}
return f.Duration, nil
}
| security/pkg/util/mock/fakecertutil.go | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.00020096851221751422,
0.00018313141481485218,
0.00017387524712830782,
0.00017884094268083572,
0.00001051446633937303
] |
{
"id": 3,
"code_window": [
"\t\t} else {\n",
"\t\t\tscope.Warn(\"Encountered unexpected status content. Overwriting status.\")\n",
"\t\t}\n",
"\t\tcurrentStatus = v1alpha1.IstioStatus{\n",
"\t\t\tConditions: []*v1alpha1.IstioCondition{&desiredCondition},\n",
"\t\t}\n",
"\t\tcurrentStatus.ObservedGeneration = generation\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tcurrentStatus = &v1alpha1.IstioStatus{\n"
],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 261
} | // Copyright Istio 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 status
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"sync"
"time"
"github.com/gogo/protobuf/types"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/utils/clock"
"istio.io/api/meta/v1alpha1"
"istio.io/istio/pilot/pkg/features"
"istio.io/istio/pilot/pkg/model"
"istio.io/istio/pkg/config"
"istio.io/istio/pkg/config/schema/collections"
"istio.io/pkg/log"
)
var scope = log.RegisterScope("status",
"CRD distribution status debugging", 0)
type Progress struct {
AckedInstances int
TotalInstances int
}
func (p *Progress) PlusEquals(p2 Progress) {
p.TotalInstances += p2.TotalInstances
p.AckedInstances += p2.AckedInstances
}
type DistributionController struct {
configStore model.ConfigStore
mu sync.RWMutex
CurrentState map[Resource]map[string]Progress
ObservationTime map[string]time.Time
UpdateInterval time.Duration
dynamicClient dynamic.Interface
clock clock.Clock
workers WorkerQueue
StaleInterval time.Duration
cmInformer cache.SharedIndexInformer
}
func NewController(restConfig rest.Config, namespace string, cs model.ConfigStore) *DistributionController {
c := &DistributionController{
CurrentState: make(map[Resource]map[string]Progress),
ObservationTime: make(map[string]time.Time),
UpdateInterval: 200 * time.Millisecond,
StaleInterval: time.Minute,
clock: clock.RealClock{},
configStore: cs,
}
// client-go defaults to 5 QPS, with 10 Boost, which is insufficient for updating status on all the config
// in the mesh. These values can be configured using environment variables for tuning (see pilot/pkg/features)
restConfig.QPS = float32(features.StatusQPS)
restConfig.Burst = features.StatusBurst
var err error
if c.dynamicClient, err = dynamic.NewForConfig(&restConfig); err != nil {
scope.Fatalf("Could not connect to kubernetes: %s", err)
}
// configmap informer
i := informers.NewSharedInformerFactoryWithOptions(kubernetes.NewForConfigOrDie(&restConfig), 1*time.Minute,
informers.WithNamespace(namespace),
informers.WithTweakListOptions(func(listOptions *metav1.ListOptions) {
listOptions.LabelSelector = labels.Set(map[string]string{labelKey: "true"}).AsSelector().String()
})).
Core().V1().ConfigMaps()
c.cmInformer = i.Informer()
i.Informer().AddEventHandler(&DistroReportHandler{dc: c})
return c
}
func (c *DistributionController) Start(stop <-chan struct{}) {
scope.Info("Starting status leader controller")
// this will list all existing configmaps, as well as updates, right?
ctx := NewIstioContext(stop)
go c.cmInformer.Run(ctx.Done())
c.workers = NewWorkerPool(func(resource *Resource, progress *Progress) {
c.writeStatus(*resource, *progress)
}, uint(features.StatusMaxWorkers.Get()))
c.workers.Run(ctx)
// create Status Writer
t := c.clock.Tick(c.UpdateInterval)
go func() {
for {
select {
case <-ctx.Done():
return
case <-t:
staleReporters := c.writeAllStatus()
if len(staleReporters) > 0 {
c.removeStaleReporters(staleReporters)
}
}
}
}()
}
func (c *DistributionController) handleReport(d DistributionReport) {
defer c.mu.Unlock()
c.mu.Lock()
for resstr := range d.InProgressResources {
res := *ResourceFromString(resstr)
if _, ok := c.CurrentState[res]; !ok {
c.CurrentState[res] = make(map[string]Progress)
}
c.CurrentState[res][d.Reporter] = Progress{d.InProgressResources[resstr], d.DataPlaneCount}
}
c.ObservationTime[d.Reporter] = c.clock.Now()
}
func (c *DistributionController) writeAllStatus() (staleReporters []string) {
defer c.mu.RUnlock()
c.mu.RLock()
for config, fractions := range c.CurrentState {
var distributionState Progress
for reporter, w := range fractions {
// check for stale data here
if c.clock.Since(c.ObservationTime[reporter]) > c.StaleInterval {
scope.Warnf("Status reporter %s has not been heard from since %v, deleting report.",
reporter, c.ObservationTime[reporter])
staleReporters = append(staleReporters, reporter)
} else {
distributionState.PlusEquals(w)
}
}
if distributionState.TotalInstances > 0 { // this is necessary when all reports are stale.
c.queueWriteStatus(config, distributionState)
}
}
return
}
func (c *DistributionController) writeStatus(config Resource, distributionState Progress) {
schema, _ := collections.All.FindByGroupVersionResource(config.GroupVersionResource)
if schema == nil {
scope.Warnf("schema %v could not be identified", schema)
c.pruneOldVersion(config)
return
}
if !strings.HasSuffix(schema.Resource().Group(), "istio.io") {
// we don't write status for objects we don't own
return
}
current := c.configStore.Get(schema.Resource().GroupVersionKind(), config.Name, config.Namespace)
if current == nil {
scope.Warnf("config store missing entry %v, status will not update", config)
// this happens when resources are rapidly deleted, such as the validation-readiness checker
c.pruneOldVersion(config)
return
}
if config.Generation != strconv.FormatInt(current.Generation, 10) {
// this distribution report is for an old version of the object. Prune and continue.
c.pruneOldVersion(config)
return
}
// check if status needs updating
if needsReconcile, desiredStatus := ReconcileStatuses(current, distributionState, current.Generation); needsReconcile {
// technically, we should be updating probe time even when reconciling isn't needed, but
// I'm skipping that for efficiency.
current.Status = desiredStatus
_, err := c.configStore.UpdateStatus(*current)
if err != nil {
scope.Errorf("Encountered unexpected error updating status for %v, will try again later: %s", config, err)
return
}
}
}
func (c *DistributionController) pruneOldVersion(config Resource) {
defer c.mu.Unlock()
c.mu.Lock()
delete(c.CurrentState, config)
}
func (c *DistributionController) removeStaleReporters(staleReporters []string) {
defer c.mu.Unlock()
c.mu.Lock()
for key, fractions := range c.CurrentState {
for _, staleReporter := range staleReporters {
delete(fractions, staleReporter)
}
c.CurrentState[key] = fractions
}
}
func (c *DistributionController) queueWriteStatus(config Resource, state Progress) {
c.workers.Push(config, state)
}
func (c *DistributionController) configDeleted(res config.Config) {
r := ResourceFromModelConfig(res)
c.workers.Delete(*r)
}
func GetTypedStatus(in interface{}) (out v1alpha1.IstioStatus, err error) {
var statusBytes []byte
if statusBytes, err = json.Marshal(in); err == nil {
err = json.Unmarshal(statusBytes, &out)
}
return
}
func boolToConditionStatus(b bool) string {
if b {
return "True"
}
return "False"
}
func ReconcileStatuses(current *config.Config, desired Progress, generation int64) (bool, *v1alpha1.IstioStatus) {
needsReconcile := false
currentStatus, err := GetTypedStatus(current.Status)
desiredCondition := v1alpha1.IstioCondition{
Type: "Reconciled",
Status: boolToConditionStatus(desired.AckedInstances == desired.TotalInstances),
LastProbeTime: types.TimestampNow(),
LastTransitionTime: types.TimestampNow(),
Message: fmt.Sprintf("%d/%d proxies up to date.", desired.AckedInstances, desired.TotalInstances),
}
if err != nil {
// the status field is in an unexpected state.
if scope.DebugEnabled() {
scope.Debugf("Encountered unexpected status content. Overwriting status: %v", current.Status)
} else {
scope.Warn("Encountered unexpected status content. Overwriting status.")
}
currentStatus = v1alpha1.IstioStatus{
Conditions: []*v1alpha1.IstioCondition{&desiredCondition},
}
currentStatus.ObservedGeneration = generation
return true, ¤tStatus
}
var currentCondition *v1alpha1.IstioCondition
conditionIndex := -1
for i, c := range currentStatus.Conditions {
if c.Type == "Reconciled" {
currentCondition = currentStatus.Conditions[i]
conditionIndex = i
}
}
if currentCondition == nil ||
currentCondition.Message != desiredCondition.Message ||
currentCondition.Status != desiredCondition.Status {
needsReconcile = true
}
if conditionIndex > -1 {
currentStatus.Conditions[conditionIndex] = &desiredCondition
} else {
currentStatus.Conditions = append(currentStatus.Conditions, &desiredCondition)
}
currentStatus.ObservedGeneration = generation
return needsReconcile, ¤tStatus
}
type DistroReportHandler struct {
dc *DistributionController
}
func (drh *DistroReportHandler) OnAdd(obj interface{}) {
drh.HandleNew(obj)
}
func (drh *DistroReportHandler) OnUpdate(oldObj, newObj interface{}) {
drh.HandleNew(newObj)
}
func (drh *DistroReportHandler) HandleNew(obj interface{}) {
cm, ok := obj.(*v1.ConfigMap)
if !ok {
scope.Warnf("expected configmap, but received %v, discarding", obj)
return
}
rptStr := cm.Data[dataField]
scope.Debugf("using report: %s", rptStr)
dr, err := ReportFromYaml([]byte(cm.Data[dataField]))
if err != nil {
scope.Warnf("received malformed distributionReport %s, discarding: %v", cm.Name, err)
return
}
drh.dc.handleReport(dr)
}
func (drh *DistroReportHandler) OnDelete(obj interface{}) {
// TODO: what do we do here? will these ever be deleted?
}
| pilot/pkg/status/state.go | 1 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.9936103224754333,
0.08951058238744736,
0.0001637330133235082,
0.00017576820391695946,
0.27601173520088196
] |
{
"id": 3,
"code_window": [
"\t\t} else {\n",
"\t\t\tscope.Warn(\"Encountered unexpected status content. Overwriting status.\")\n",
"\t\t}\n",
"\t\tcurrentStatus = v1alpha1.IstioStatus{\n",
"\t\t\tConditions: []*v1alpha1.IstioCondition{&desiredCondition},\n",
"\t\t}\n",
"\t\tcurrentStatus.ObservedGeneration = generation\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tcurrentStatus = &v1alpha1.IstioStatus{\n"
],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 261
} | LICENSE placeholder.
| licenses/helm.sh/helm/v3/pkg/chartutil/testdata/dependent-chart-with-all-in-requirements-yaml/LICENSE | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.00016978965140879154,
0.00016978965140879154,
0.00016978965140879154,
0.00016978965140879154,
0
] |
{
"id": 3,
"code_window": [
"\t\t} else {\n",
"\t\t\tscope.Warn(\"Encountered unexpected status content. Overwriting status.\")\n",
"\t\t}\n",
"\t\tcurrentStatus = v1alpha1.IstioStatus{\n",
"\t\t\tConditions: []*v1alpha1.IstioCondition{&desiredCondition},\n",
"\t\t}\n",
"\t\tcurrentStatus.ObservedGeneration = generation\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tcurrentStatus = &v1alpha1.IstioStatus{\n"
],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 261
} | -----BEGIN CERTIFICATE-----
MIIDEzCCAfugAwIBAgIUHu+RNpObSStNAQtgGqFPV70CNVEwDQYJKoZIhvcNAQEL
BQAwGDEWMBQGA1UEAwwNY2x1c3Rlci5sb2NhbDAgFw0yMDAzMTMwMDUwNTBaGA8y
MjkzMTIyNzAwNTA1MFowGDEWMBQGA1UEAwwNY2x1c3Rlci5sb2NhbDCCASIwDQYJ
KoZIhvcNAQEBBQADggEPADCCAQoCggEBAN77xnr0H71SuBEGBI0amTmlvjwcgqZF
mAw5c2pOCs3eUiJSz3tQYTRfVzaWBOrwEmn7RrQH8LJ5EVQm7Prg+aCT7koeBQyD
G/Oqk2hpX1ArCLnjwEildUOlDSg+KBNJiImRFhMb2vnlFPfzkO5TsUk01OOnQTYm
5XMzhQ0CuqX3stcAACsuKGxk3BX3r5zHmcFH4nBpbh9pb0DY2QZ+N+B6Qxe6o89q
bT8gtWYLN1b3yGhn2WGeFkQtaud36Wj2jRSxWo2PBe8xc8qDBFJOt0zHg+u0Pt7t
3mCrBIZ45FWEqX06FOupSe7HF2d7U/9pJGSZLe9iAJ/59WROlniJ7PUCAwEAAaNT
MFEwHQYDVR0OBBYEFC1YD3F9RMLaW1xMuuQN27SmXzsMMB8GA1UdIwQYMBaAFC1Y
D3F9RMLaW1xMuuQN27SmXzsMMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL
BQADggEBAGqzLzTnusoOPF+tQ4jbhcXDCMvpDCCiAQVkkaorNGMWg2ny39vm3ymc
HBhqWNNbeyZTj8hl7ffCoeUChZnIFkLO1ev3DVbLz179IP6dhqfDkuLhc/0g5Lfs
FcNedAJh5TConI+x7dH1W2opPX4hXiiJBzcpPmfttD1EYES2VH85cPp95goUJwRp
kMPAS5WiBLPv0c+0Msppe4iqxwuZZtJKRoHRDbvrHonMT1FmdOoEJ8xjeTxB8pjc
tp5dA30dGNAxB7tOrzqmIidjXjYaxZGXKoC6BViw9ISfX9WNqVdvZVMJ7XwL6gu5
Dk0yYXcMuGwMkMz+vJpypIBZAaCFES8=
-----END CERTIFICATE-----
| tests/testdata/certs/mountedcerts-server/root-cert.pem | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.0005694461287930608,
0.00039279944030568004,
0.00021615273726638407,
0.00039279944030568004,
0.00017664668848738074
] |
{
"id": 3,
"code_window": [
"\t\t} else {\n",
"\t\t\tscope.Warn(\"Encountered unexpected status content. Overwriting status.\")\n",
"\t\t}\n",
"\t\tcurrentStatus = v1alpha1.IstioStatus{\n",
"\t\t\tConditions: []*v1alpha1.IstioCondition{&desiredCondition},\n",
"\t\t}\n",
"\t\tcurrentStatus.ObservedGeneration = generation\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tcurrentStatus = &v1alpha1.IstioStatus{\n"
],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 261
} | -----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCp11Ql4QWfwXTI
DH7a76N/Se/ep72tdgl7TaCGcXyMdZr/x/ixf0e/geHuAA3PtrqXxMOt2HmccXL4
NRfacvK8kG/0iCBBAD1m+mI8aP4IKIxllJHTassB3U65qhq4sdAseMJIhgD2Fi2c
6gv64zJCwzq4VvC1lP2SEjo+QwKHS0MMCxBfNCpvIau3ZZNc3vjGfPfdgznlKWwA
KjOkB+u1EB2sodr1kU3LyHRjinxerSqtnkUb8GoeH6ooImcpyk35cQiVXH1ekR22
xhB0Ef68Kq0sR9WRQhS9Z6jggt/J39dm7H0s4LwMKNp+epYf7reYiCLTPi5ylEEz
ud3OJfslAgMBAAECggEAcLSl8KUMuGEGgCJapCrWUofcF+M0acGktSBkYBM7VXJN
s2MeU5tlH16vcOK0R5y44jH+sISw3vIiGzgQZjRVhHBM+vbCgKAKHyYUvoXl3cAa
uuYGh0edA9W6glaxeNL2lCxmsP3L8YHyLujZnlnaZpdrhhybi8QdKSvTXrHVIbXo
dkDCREK5D9NwEh5Z9wXKlHuyDc6NJTwKd65bbWIu9LPUtEgOxh/fRDKI9LAtBUo2
EAQyRsEpYIY8IqWrfs4Aa8rtk3u3tMGnyZUjqC/p2yWgBtSi1sPZvLYln9meAGwL
evophBQtYomQDU8pjdqoY1FDTmxntQMQTS55RhdgwQKBgQDg1H6Bug3+X/X85BhA
sf+cEk1/raioct8wma4EGLOQnUGoMtyNPa9XLSoy+N9xlgGxSA9L09kYGToLgsJT
yksEgXP4He8wH9SgbgAQsGs7lgsdmVCn2axV015uZAut/tzgu5gajV+ERuIh7fzK
t+TntD3M1uay9xEzrAqRZB1PHQKBgQDBYzUO/IVrEG1pQy06zsHrruLTQ6/68ac0
KWQdlJjWGhv8hWLRVl1Vly3OeK7Sqn0j463gLSV7eRvXaMsjCjTCAAP6iwhp1qUO
6yaHZySjFdUvXSjrstwn8rCTv2wO6/Ofx6IzYJe1BHeZJj8NVwmBKsO4xfb60hu3
DqTRaI71qQKBgQCk4JBpmET83+iobamvgBmgnfeBg5vk9GDi5kCsNmUwz3I/5BTD
65Gzj6abvNE4HjbdiKfXBuP0/UMI//p8siRziG/AbEtlcmJeyGx50LbC+tTp/u4c
OdBdHGXq9KlwDzByCoCQME701XquQTYaf+N5XD/aAVsrsW5HA4q4dr/brQKBgGHO
xTURLoFZy5xjZ2rIy3dh+kKTh1vKAKD3FjWHxEz045ax96qcnZP+ZCJ7EyBlLemK
65PoAX8TX6twytyr+sbrrxd2Xgj5kH2dHN16oyMAldPgsCOVUJe7vObc99AMMilr
lHObtN7OpZaFq3oZvSrg8CBxr1poDbBl7aIj2boRAoGBAMKSFNFhJfmIMb1Uf5sZ
PaM6acYfcP/2mADaunI+Wm2QVSYAuDAtQavjN9ulT7UVUAGL/7ttLvTLtZpx3ayB
e4sP95nCZArI8PM2ijy4ngr5a4RnkN6v0xx2cMjkoPFWaogJuWbmJRhNl3UESJvA
SAyyG91VOY/EqH+vjszSlQEF
-----END PRIVATE KEY-----
| tests/util/pki/k8sca.key | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.0008485046564601362,
0.0004856633022427559,
0.00016829484957270324,
0.0004401904297992587,
0.000279549858532846
] |
{
"id": 4,
"code_window": [
"\t\t\tConditions: []*v1alpha1.IstioCondition{&desiredCondition},\n",
"\t\t}\n",
"\t\tcurrentStatus.ObservedGeneration = generation\n",
"\t\treturn true, ¤tStatus\n",
"\t}\n",
"\tvar currentCondition *v1alpha1.IstioCondition\n",
"\tconditionIndex := -1\n",
"\tfor i, c := range currentStatus.Conditions {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn true, currentStatus\n"
],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 265
} | // Copyright Istio 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 status
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"sync"
"time"
"github.com/gogo/protobuf/types"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/utils/clock"
"istio.io/api/meta/v1alpha1"
"istio.io/istio/pilot/pkg/features"
"istio.io/istio/pilot/pkg/model"
"istio.io/istio/pkg/config"
"istio.io/istio/pkg/config/schema/collections"
"istio.io/pkg/log"
)
var scope = log.RegisterScope("status",
"CRD distribution status debugging", 0)
type Progress struct {
AckedInstances int
TotalInstances int
}
func (p *Progress) PlusEquals(p2 Progress) {
p.TotalInstances += p2.TotalInstances
p.AckedInstances += p2.AckedInstances
}
type DistributionController struct {
configStore model.ConfigStore
mu sync.RWMutex
CurrentState map[Resource]map[string]Progress
ObservationTime map[string]time.Time
UpdateInterval time.Duration
dynamicClient dynamic.Interface
clock clock.Clock
workers WorkerQueue
StaleInterval time.Duration
cmInformer cache.SharedIndexInformer
}
func NewController(restConfig rest.Config, namespace string, cs model.ConfigStore) *DistributionController {
c := &DistributionController{
CurrentState: make(map[Resource]map[string]Progress),
ObservationTime: make(map[string]time.Time),
UpdateInterval: 200 * time.Millisecond,
StaleInterval: time.Minute,
clock: clock.RealClock{},
configStore: cs,
}
// client-go defaults to 5 QPS, with 10 Boost, which is insufficient for updating status on all the config
// in the mesh. These values can be configured using environment variables for tuning (see pilot/pkg/features)
restConfig.QPS = float32(features.StatusQPS)
restConfig.Burst = features.StatusBurst
var err error
if c.dynamicClient, err = dynamic.NewForConfig(&restConfig); err != nil {
scope.Fatalf("Could not connect to kubernetes: %s", err)
}
// configmap informer
i := informers.NewSharedInformerFactoryWithOptions(kubernetes.NewForConfigOrDie(&restConfig), 1*time.Minute,
informers.WithNamespace(namespace),
informers.WithTweakListOptions(func(listOptions *metav1.ListOptions) {
listOptions.LabelSelector = labels.Set(map[string]string{labelKey: "true"}).AsSelector().String()
})).
Core().V1().ConfigMaps()
c.cmInformer = i.Informer()
i.Informer().AddEventHandler(&DistroReportHandler{dc: c})
return c
}
func (c *DistributionController) Start(stop <-chan struct{}) {
scope.Info("Starting status leader controller")
// this will list all existing configmaps, as well as updates, right?
ctx := NewIstioContext(stop)
go c.cmInformer.Run(ctx.Done())
c.workers = NewWorkerPool(func(resource *Resource, progress *Progress) {
c.writeStatus(*resource, *progress)
}, uint(features.StatusMaxWorkers.Get()))
c.workers.Run(ctx)
// create Status Writer
t := c.clock.Tick(c.UpdateInterval)
go func() {
for {
select {
case <-ctx.Done():
return
case <-t:
staleReporters := c.writeAllStatus()
if len(staleReporters) > 0 {
c.removeStaleReporters(staleReporters)
}
}
}
}()
}
func (c *DistributionController) handleReport(d DistributionReport) {
defer c.mu.Unlock()
c.mu.Lock()
for resstr := range d.InProgressResources {
res := *ResourceFromString(resstr)
if _, ok := c.CurrentState[res]; !ok {
c.CurrentState[res] = make(map[string]Progress)
}
c.CurrentState[res][d.Reporter] = Progress{d.InProgressResources[resstr], d.DataPlaneCount}
}
c.ObservationTime[d.Reporter] = c.clock.Now()
}
func (c *DistributionController) writeAllStatus() (staleReporters []string) {
defer c.mu.RUnlock()
c.mu.RLock()
for config, fractions := range c.CurrentState {
var distributionState Progress
for reporter, w := range fractions {
// check for stale data here
if c.clock.Since(c.ObservationTime[reporter]) > c.StaleInterval {
scope.Warnf("Status reporter %s has not been heard from since %v, deleting report.",
reporter, c.ObservationTime[reporter])
staleReporters = append(staleReporters, reporter)
} else {
distributionState.PlusEquals(w)
}
}
if distributionState.TotalInstances > 0 { // this is necessary when all reports are stale.
c.queueWriteStatus(config, distributionState)
}
}
return
}
func (c *DistributionController) writeStatus(config Resource, distributionState Progress) {
schema, _ := collections.All.FindByGroupVersionResource(config.GroupVersionResource)
if schema == nil {
scope.Warnf("schema %v could not be identified", schema)
c.pruneOldVersion(config)
return
}
if !strings.HasSuffix(schema.Resource().Group(), "istio.io") {
// we don't write status for objects we don't own
return
}
current := c.configStore.Get(schema.Resource().GroupVersionKind(), config.Name, config.Namespace)
if current == nil {
scope.Warnf("config store missing entry %v, status will not update", config)
// this happens when resources are rapidly deleted, such as the validation-readiness checker
c.pruneOldVersion(config)
return
}
if config.Generation != strconv.FormatInt(current.Generation, 10) {
// this distribution report is for an old version of the object. Prune and continue.
c.pruneOldVersion(config)
return
}
// check if status needs updating
if needsReconcile, desiredStatus := ReconcileStatuses(current, distributionState, current.Generation); needsReconcile {
// technically, we should be updating probe time even when reconciling isn't needed, but
// I'm skipping that for efficiency.
current.Status = desiredStatus
_, err := c.configStore.UpdateStatus(*current)
if err != nil {
scope.Errorf("Encountered unexpected error updating status for %v, will try again later: %s", config, err)
return
}
}
}
func (c *DistributionController) pruneOldVersion(config Resource) {
defer c.mu.Unlock()
c.mu.Lock()
delete(c.CurrentState, config)
}
func (c *DistributionController) removeStaleReporters(staleReporters []string) {
defer c.mu.Unlock()
c.mu.Lock()
for key, fractions := range c.CurrentState {
for _, staleReporter := range staleReporters {
delete(fractions, staleReporter)
}
c.CurrentState[key] = fractions
}
}
func (c *DistributionController) queueWriteStatus(config Resource, state Progress) {
c.workers.Push(config, state)
}
func (c *DistributionController) configDeleted(res config.Config) {
r := ResourceFromModelConfig(res)
c.workers.Delete(*r)
}
func GetTypedStatus(in interface{}) (out v1alpha1.IstioStatus, err error) {
var statusBytes []byte
if statusBytes, err = json.Marshal(in); err == nil {
err = json.Unmarshal(statusBytes, &out)
}
return
}
func boolToConditionStatus(b bool) string {
if b {
return "True"
}
return "False"
}
func ReconcileStatuses(current *config.Config, desired Progress, generation int64) (bool, *v1alpha1.IstioStatus) {
needsReconcile := false
currentStatus, err := GetTypedStatus(current.Status)
desiredCondition := v1alpha1.IstioCondition{
Type: "Reconciled",
Status: boolToConditionStatus(desired.AckedInstances == desired.TotalInstances),
LastProbeTime: types.TimestampNow(),
LastTransitionTime: types.TimestampNow(),
Message: fmt.Sprintf("%d/%d proxies up to date.", desired.AckedInstances, desired.TotalInstances),
}
if err != nil {
// the status field is in an unexpected state.
if scope.DebugEnabled() {
scope.Debugf("Encountered unexpected status content. Overwriting status: %v", current.Status)
} else {
scope.Warn("Encountered unexpected status content. Overwriting status.")
}
currentStatus = v1alpha1.IstioStatus{
Conditions: []*v1alpha1.IstioCondition{&desiredCondition},
}
currentStatus.ObservedGeneration = generation
return true, ¤tStatus
}
var currentCondition *v1alpha1.IstioCondition
conditionIndex := -1
for i, c := range currentStatus.Conditions {
if c.Type == "Reconciled" {
currentCondition = currentStatus.Conditions[i]
conditionIndex = i
}
}
if currentCondition == nil ||
currentCondition.Message != desiredCondition.Message ||
currentCondition.Status != desiredCondition.Status {
needsReconcile = true
}
if conditionIndex > -1 {
currentStatus.Conditions[conditionIndex] = &desiredCondition
} else {
currentStatus.Conditions = append(currentStatus.Conditions, &desiredCondition)
}
currentStatus.ObservedGeneration = generation
return needsReconcile, ¤tStatus
}
type DistroReportHandler struct {
dc *DistributionController
}
func (drh *DistroReportHandler) OnAdd(obj interface{}) {
drh.HandleNew(obj)
}
func (drh *DistroReportHandler) OnUpdate(oldObj, newObj interface{}) {
drh.HandleNew(newObj)
}
func (drh *DistroReportHandler) HandleNew(obj interface{}) {
cm, ok := obj.(*v1.ConfigMap)
if !ok {
scope.Warnf("expected configmap, but received %v, discarding", obj)
return
}
rptStr := cm.Data[dataField]
scope.Debugf("using report: %s", rptStr)
dr, err := ReportFromYaml([]byte(cm.Data[dataField]))
if err != nil {
scope.Warnf("received malformed distributionReport %s, discarding: %v", cm.Name, err)
return
}
drh.dc.handleReport(dr)
}
func (drh *DistroReportHandler) OnDelete(obj interface{}) {
// TODO: what do we do here? will these ever be deleted?
}
| pilot/pkg/status/state.go | 1 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.9991463422775269,
0.12072652578353882,
0.0001655660744290799,
0.00017839510110206902,
0.32188880443573
] |
{
"id": 4,
"code_window": [
"\t\t\tConditions: []*v1alpha1.IstioCondition{&desiredCondition},\n",
"\t\t}\n",
"\t\tcurrentStatus.ObservedGeneration = generation\n",
"\t\treturn true, ¤tStatus\n",
"\t}\n",
"\tvar currentCondition *v1alpha1.IstioCondition\n",
"\tconditionIndex := -1\n",
"\tfor i, c := range currentStatus.Conditions {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn true, currentStatus\n"
],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 265
} |
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
| licenses/k8s.io/kube-openapi/LICENSE | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.0001791153772501275,
0.00017648075299803168,
0.00017199742433149368,
0.0001763792970450595,
0.0000015772830010973848
] |
{
"id": 4,
"code_window": [
"\t\t\tConditions: []*v1alpha1.IstioCondition{&desiredCondition},\n",
"\t\t}\n",
"\t\tcurrentStatus.ObservedGeneration = generation\n",
"\t\treturn true, ¤tStatus\n",
"\t}\n",
"\tvar currentCondition *v1alpha1.IstioCondition\n",
"\tconditionIndex := -1\n",
"\tfor i, c := range currentStatus.Conditions {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn true, currentStatus\n"
],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 265
} | // Copyright Istio 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 helm
import (
"bytes"
"fmt"
"html/template"
"io/ioutil"
"path/filepath"
"sort"
"strings"
"helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/chartutil"
"helm.sh/helm/v3/pkg/engine"
"sigs.k8s.io/yaml"
"istio.io/istio/operator/pkg/util"
"istio.io/pkg/log"
)
const (
// YAMLSeparator is a separator for multi-document YAML files.
YAMLSeparator = "\n---\n"
// DefaultProfileString is the name of the default profile.
DefaultProfileString = "default"
// NotesFileNameSuffix is the file name suffix for helm notes.
// see https://helm.sh/docs/chart_template_guide/notes_files/
NotesFileNameSuffix = ".txt"
)
var (
scope = log.RegisterScope("installer", "installer", 0)
)
// TemplateFilterFunc filters templates to render by their file name
type TemplateFilterFunc func(string) bool
// TemplateRenderer defines a helm template renderer interface.
type TemplateRenderer interface {
// Run starts the renderer and should be called before using it.
Run() error
// RenderManifest renders the associated helm charts with the given values YAML string and returns the resulting
// string.
RenderManifest(values string) (string, error)
// RenderManifestFiltered filters manifests to render by template file name
RenderManifestFiltered(values string, filter TemplateFilterFunc) (string, error)
}
// NewHelmRenderer creates a new helm renderer with the given parameters and returns an interface to it.
// The format of helmBaseDir and profile strings determines the type of helm renderer returned (compiled-in, file,
// HTTP etc.)
func NewHelmRenderer(operatorDataDir, helmSubdir, componentName, namespace string) (TemplateRenderer, error) {
dir := filepath.Join(ChartsSubdirName, helmSubdir)
switch {
case operatorDataDir == "":
return NewVFSRenderer(dir, componentName, namespace), nil
default:
return NewFileTemplateRenderer(filepath.Join(operatorDataDir, dir), componentName, namespace), nil
}
}
// ReadProfileYAML reads the YAML values associated with the given profile. It uses an appropriate reader for the
// profile format (compiled-in, file, HTTP, etc.).
func ReadProfileYAML(profile, manifestsPath string) (string, error) {
var err error
var globalValues string
// Get global values from profile.
switch {
case manifestsPath == "":
if globalValues, err = LoadValuesVFS(profile); err != nil {
return "", err
}
case util.IsFilePath(profile):
if globalValues, err = readFile(profile); err != nil {
return "", err
}
default:
if globalValues, err = LoadValues(profile, manifestsPath); err != nil {
return "", fmt.Errorf("failed to read profile %v from %v: %v", profile, manifestsPath, err)
}
}
return globalValues, nil
}
// renderChart renders the given chart with the given values and returns the resulting YAML manifest string.
func renderChart(namespace, values string, chrt *chart.Chart, filterFunc TemplateFilterFunc) (string, error) {
options := chartutil.ReleaseOptions{
Name: "istio",
Namespace: namespace,
}
valuesMap := map[string]interface{}{}
if err := yaml.Unmarshal([]byte(values), &valuesMap); err != nil {
return "", fmt.Errorf("failed to unmarshal values: %v", err)
}
vals, err := chartutil.ToRenderValues(chrt, valuesMap, options, nil)
if err != nil {
return "", err
}
if filterFunc != nil {
filteredTemplates := []*chart.File{}
for _, t := range chrt.Templates {
if filterFunc(t.Name) {
filteredTemplates = append(filteredTemplates, t)
}
}
chrt.Templates = filteredTemplates
}
files, err := engine.Render(chrt, vals)
crdFiles := chrt.CRDObjects()
if err != nil {
return "", err
}
if chrt.Metadata.Name == "base" {
base, _ := valuesMap["base"].(map[string]interface{})
if enableIstioConfigCRDs, ok := base["enableIstioConfigCRDs"].(bool); ok && !enableIstioConfigCRDs {
crdFiles = []chart.CRD{}
}
}
// Create sorted array of keys to iterate over, to stabilize the order of the rendered templates
keys := make([]string, 0, len(files))
for k := range files {
if strings.HasSuffix(k, NotesFileNameSuffix) {
continue
}
keys = append(keys, k)
}
sort.Strings(keys)
var sb strings.Builder
for i := 0; i < len(keys); i++ {
f := files[keys[i]]
// add yaml separator if the rendered file doesn't have one at the end
f = strings.TrimSpace(f) + "\n"
if !strings.HasSuffix(f, YAMLSeparator) {
f += YAMLSeparator
}
_, err := sb.WriteString(f)
if err != nil {
return "", err
}
}
// Sort crd files by name to ensure stable manifest output
sort.Slice(crdFiles, func(i, j int) bool { return crdFiles[i].Name < crdFiles[j].Name })
for _, crdFile := range crdFiles {
f := string(crdFile.File.Data)
// add yaml separator if the rendered file doesn't have one at the end
f = strings.TrimSpace(f) + "\n"
if !strings.HasSuffix(f, YAMLSeparator) {
f += YAMLSeparator
}
_, err := sb.WriteString(f)
if err != nil {
return "", err
}
}
return sb.String(), nil
}
// GenerateHubTagOverlay creates an IstioOperatorSpec overlay YAML for hub and tag.
func GenerateHubTagOverlay(hub, tag string) (string, error) {
hubTagYAMLTemplate := `
spec:
hub: {{.Hub}}
tag: {{.Tag}}
`
ts := struct {
Hub string
Tag string
}{
Hub: hub,
Tag: tag,
}
return renderTemplate(hubTagYAMLTemplate, ts)
}
// helper method to render template
func renderTemplate(tmpl string, ts interface{}) (string, error) {
t, err := template.New("").Parse(tmpl)
if err != nil {
return "", err
}
buf := new(bytes.Buffer)
err = t.Execute(buf, ts)
if err != nil {
return "", err
}
return buf.String(), nil
}
// DefaultFilenameForProfile returns the profile name of the default profile for the given profile.
func DefaultFilenameForProfile(profile string) string {
switch {
case util.IsFilePath(profile):
return filepath.Join(filepath.Dir(profile), DefaultProfileFilename)
default:
return DefaultProfileString
}
}
// IsDefaultProfile reports whether the given profile is the default profile.
func IsDefaultProfile(profile string) bool {
return profile == "" || profile == DefaultProfileString || filepath.Base(profile) == DefaultProfileFilename
}
func readFile(path string) (string, error) {
b, err := ioutil.ReadFile(path)
return string(b), err
}
// GetProfileYAML returns the YAML for the given profile name, using the given profileOrPath string, which may be either
// a profile label or a file path.
func GetProfileYAML(installPackagePath, profileOrPath string) (string, error) {
if profileOrPath == "" {
profileOrPath = "default"
}
profiles, err := readProfiles(installPackagePath)
if err != nil {
return "", fmt.Errorf("failed to read profiles: %v", err)
}
// If charts are a file path and profile is a name like default, transform it to the file path.
if profiles[profileOrPath] && installPackagePath != "" {
profileOrPath = filepath.Join(installPackagePath, "profiles", profileOrPath+".yaml")
}
// This contains the IstioOperator CR.
baseCRYAML, err := ReadProfileYAML(profileOrPath, installPackagePath)
if err != nil {
return "", err
}
if !IsDefaultProfile(profileOrPath) {
// Profile definitions are relative to the default profileOrPath, so read that first.
dfn := DefaultFilenameForProfile(profileOrPath)
defaultYAML, err := ReadProfileYAML(dfn, installPackagePath)
if err != nil {
return "", err
}
baseCRYAML, err = util.OverlayIOP(defaultYAML, baseCRYAML)
if err != nil {
return "", err
}
}
return baseCRYAML, nil
}
| operator/pkg/helm/helm.go | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.0003505361673887819,
0.0001934700703714043,
0.0001673331717029214,
0.00017598587146494538,
0.00005022049663239159
] |
{
"id": 4,
"code_window": [
"\t\t\tConditions: []*v1alpha1.IstioCondition{&desiredCondition},\n",
"\t\t}\n",
"\t\tcurrentStatus.ObservedGeneration = generation\n",
"\t\treturn true, ¤tStatus\n",
"\t}\n",
"\tvar currentCondition *v1alpha1.IstioCondition\n",
"\tconditionIndex := -1\n",
"\tfor i, c := range currentStatus.Conditions {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn true, currentStatus\n"
],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 265
} | // Copyright 2018 Istio 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.
// This is a sample chained plugin that supports multiple CNI versions. It
// parses prevResult according to the cniVersion
package main
import (
"encoding/json"
"fmt"
"net"
"os"
"strconv"
"time"
"github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types"
"github.com/containernetworking/cni/pkg/types/current"
"github.com/containernetworking/cni/pkg/version"
"istio.io/api/annotation"
"istio.io/pkg/log"
)
var (
nsSetupBinDir = "/opt/cni/bin"
injectAnnotationKey = annotation.SidecarInject.Name
sidecarStatusKey = annotation.SidecarStatus.Name
interceptRuleMgrType = defInterceptRuleMgrType
loggingOptions = log.DefaultOptions()
podRetrievalMaxRetries = 30
podRetrievalInterval = 1 * time.Second
)
const ISTIOINIT = "istio-init"
// Kubernetes a K8s specific struct to hold config
type Kubernetes struct {
K8sAPIRoot string `json:"k8s_api_root"`
Kubeconfig string `json:"kubeconfig"`
InterceptRuleMgrType string `json:"intercept_type"`
NodeName string `json:"node_name"`
ExcludeNamespaces []string `json:"exclude_namespaces"`
CNIBinDir string `json:"cni_bin_dir"`
}
// PluginConf is whatever you expect your configuration json to be. This is whatever
// is passed in on stdin. Your plugin may wish to expose its functionality via
// runtime args, see CONVENTIONS.md in the CNI spec.
type PluginConf struct {
types.NetConf // You may wish to not nest this type
RuntimeConfig *struct {
// SampleConfig map[string]interface{} `json:"sample"`
} `json:"runtimeConfig"`
// This is the previous result, when called in the context of a chained
// plugin. Because this plugin supports multiple versions, we'll have to
// parse this in two passes. If your plugin is not chained, this can be
// removed (though you may wish to error if a non-chainable plugin is
// chained.
// If you need to modify the result before returning it, you will need
// to actually convert it to a concrete versioned struct.
RawPrevResult *map[string]interface{} `json:"prevResult"`
PrevResult *current.Result `json:"-"`
// Add plugin-specific flags here
LogLevel string `json:"log_level"`
Kubernetes Kubernetes `json:"kubernetes"`
}
// K8sArgs is the valid CNI_ARGS used for Kubernetes
// The field names need to match exact keys in kubelet args for unmarshalling
type K8sArgs struct {
types.CommonArgs
IP net.IP
K8S_POD_NAME types.UnmarshallableString // nolint: golint, stylecheck
K8S_POD_NAMESPACE types.UnmarshallableString // nolint: golint, stylecheck
K8S_POD_INFRA_CONTAINER_ID types.UnmarshallableString // nolint: golint, stylecheck
}
// parseConfig parses the supplied configuration (and prevResult) from stdin.
func parseConfig(stdin []byte) (*PluginConf, error) {
conf := PluginConf{}
if err := json.Unmarshal(stdin, &conf); err != nil {
return nil, fmt.Errorf("failed to parse network configuration: %v", err)
}
// Parse previous result. Remove this if your plugin is not chained.
if conf.RawPrevResult != nil {
resultBytes, err := json.Marshal(conf.RawPrevResult)
if err != nil {
return nil, fmt.Errorf("could not serialize prevResult: %v", err)
}
res, err := version.NewResult(conf.CNIVersion, resultBytes)
if err != nil {
return nil, fmt.Errorf("could not parse prevResult: %v", err)
}
conf.RawPrevResult = nil
conf.PrevResult, err = current.NewResultFromResult(res)
if err != nil {
return nil, fmt.Errorf("could not convert result to current version: %v", err)
}
}
// End previous result parsing
return &conf, nil
}
// cmdAdd is called for ADD requests
func cmdAdd(args *skel.CmdArgs) error {
conf, err := parseConfig(args.StdinData)
if err != nil {
log.Errorf("istio-cni cmdAdd parsing config %v", err)
return err
}
var loggedPrevResult interface{}
if conf.PrevResult == nil {
loggedPrevResult = "none"
} else {
loggedPrevResult = conf.PrevResult
}
log.WithLabels("version", conf.CNIVersion, "prevResult", loggedPrevResult).Info("CmdAdd config parsed")
// Determine if running under k8s by checking the CNI args
k8sArgs := K8sArgs{}
if err := types.LoadArgs(args.Args, &k8sArgs); err != nil {
return err
}
log.Infof("Getting identifiers with arguments: %s", args.Args)
log.Infof("Loaded k8s arguments: %v", k8sArgs)
if conf.Kubernetes.CNIBinDir != "" {
nsSetupBinDir = conf.Kubernetes.CNIBinDir
}
if conf.Kubernetes.InterceptRuleMgrType != "" {
interceptRuleMgrType = conf.Kubernetes.InterceptRuleMgrType
}
log.WithLabels("ContainerID", args.ContainerID, "Pod", string(k8sArgs.K8S_POD_NAME),
"Namespace", string(k8sArgs.K8S_POD_NAMESPACE), "InterceptType", interceptRuleMgrType).Info("")
// Check if the workload is running under Kubernetes.
if string(k8sArgs.K8S_POD_NAMESPACE) != "" && string(k8sArgs.K8S_POD_NAME) != "" {
excludePod := false
for _, excludeNs := range conf.Kubernetes.ExcludeNamespaces {
if string(k8sArgs.K8S_POD_NAMESPACE) == excludeNs {
excludePod = true
break
}
}
if !excludePod {
client, err := newKubeClient(*conf)
if err != nil {
return err
}
log.Debugf("Created Kubernetes client: %v", client)
var containers []string
var initContainersMap map[string]struct{}
var annotations map[string]string
var k8sErr error
for attempt := 1; attempt <= podRetrievalMaxRetries; attempt++ {
containers, initContainersMap, _, annotations, k8sErr = getKubePodInfo(client, string(k8sArgs.K8S_POD_NAME), string(k8sArgs.K8S_POD_NAMESPACE))
if k8sErr == nil {
break
}
log.WithLabels("err", k8sErr, "attempt", attempt).Warn("Waiting for pod metadata")
time.Sleep(podRetrievalInterval)
}
if k8sErr != nil {
log.WithLabels("err", k8sErr).Error("Failed to get pod data")
return k8sErr
}
// Check if istio-init container is present; in that case exclude pod
if _, present := initContainersMap[ISTIOINIT]; present {
log.WithLabels(
"pod", string(k8sArgs.K8S_POD_NAME),
"namespace", string(k8sArgs.K8S_POD_NAMESPACE)).
Info("Pod excluded due to being already injected with istio-init container")
excludePod = true
}
log.Infof("Found containers %v", containers)
if len(containers) > 1 {
log.WithLabels(
"ContainerID", args.ContainerID,
"netns", args.Netns,
"pod", string(k8sArgs.K8S_POD_NAME),
"Namespace", string(k8sArgs.K8S_POD_NAMESPACE),
"annotations", annotations).
Info("Checking annotations prior to redirect for Istio proxy")
if val, ok := annotations[injectAnnotationKey]; ok {
log.Infof("Pod %s contains inject annotation: %s", string(k8sArgs.K8S_POD_NAME), val)
if injectEnabled, err := strconv.ParseBool(val); err == nil {
if !injectEnabled {
log.Infof("Pod excluded due to inject-disabled annotation")
excludePod = true
}
}
}
if _, ok := annotations[sidecarStatusKey]; !ok {
log.Infof("Pod %s excluded due to not containing sidecar annotation", string(k8sArgs.K8S_POD_NAME))
excludePod = true
}
if !excludePod {
log.Infof("setting up redirect")
if redirect, redirErr := NewRedirect(annotations); redirErr != nil {
log.Errorf("Pod redirect failed due to bad params: %v", redirErr)
} else {
log.Infof("Redirect local ports: %v", redirect.includePorts)
// Get the constructor for the configured type of InterceptRuleMgr
interceptMgrCtor := GetInterceptRuleMgrCtor(interceptRuleMgrType)
if interceptMgrCtor == nil {
log.Errorf("Pod redirect failed due to unavailable InterceptRuleMgr of type %s",
interceptRuleMgrType)
} else {
rulesMgr := interceptMgrCtor()
if err := rulesMgr.Program(args.Netns, redirect); err != nil {
return err
}
}
}
}
}
} else {
log.Infof("Pod excluded")
}
} else {
log.Infof("No Kubernetes Data")
}
var result *current.Result
if conf.PrevResult == nil {
result = ¤t.Result{
CNIVersion: current.ImplementedSpecVersion,
}
} else {
// Pass through the result for the next plugin
result = conf.PrevResult
}
return types.PrintResult(result, conf.CNIVersion)
}
func cmdGet(args *skel.CmdArgs) error {
log.Info("cmdGet not implemented")
// TODO: implement
return fmt.Errorf("not implemented")
}
// cmdDel is called for DELETE requests
func cmdDel(args *skel.CmdArgs) error {
log.Info("istio-cni cmdDel parsing config")
conf, err := parseConfig(args.StdinData)
if err != nil {
return err
}
_ = conf
// Do your delete here
return nil
}
func main() {
loggingOptions.OutputPaths = []string{"stderr"}
loggingOptions.JSONEncoding = true
if err := log.Configure(loggingOptions); err != nil {
os.Exit(1)
}
// TODO: implement plugin version
skel.PluginMain(cmdAdd, cmdGet, cmdDel, version.All, "istio-cni")
}
| cni/cmd/istio-cni/main.go | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.00017976743401959538,
0.00017114712682086974,
0.0001638826506678015,
0.00017126098100561649,
0.000004239558620611206
] |
{
"id": 5,
"code_window": [
"\t} else {\n",
"\t\tcurrentStatus.Conditions = append(currentStatus.Conditions, &desiredCondition)\n",
"\t}\n",
"\tcurrentStatus.ObservedGeneration = generation\n",
"\treturn needsReconcile, ¤tStatus\n",
"}\n",
"\n",
"type DistroReportHandler struct {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\treturn needsReconcile, currentStatus\n"
],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 286
} | // Copyright Istio 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 status
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"sync"
"time"
"github.com/gogo/protobuf/types"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/utils/clock"
"istio.io/api/meta/v1alpha1"
"istio.io/istio/pilot/pkg/features"
"istio.io/istio/pilot/pkg/model"
"istio.io/istio/pkg/config"
"istio.io/istio/pkg/config/schema/collections"
"istio.io/pkg/log"
)
var scope = log.RegisterScope("status",
"CRD distribution status debugging", 0)
type Progress struct {
AckedInstances int
TotalInstances int
}
func (p *Progress) PlusEquals(p2 Progress) {
p.TotalInstances += p2.TotalInstances
p.AckedInstances += p2.AckedInstances
}
type DistributionController struct {
configStore model.ConfigStore
mu sync.RWMutex
CurrentState map[Resource]map[string]Progress
ObservationTime map[string]time.Time
UpdateInterval time.Duration
dynamicClient dynamic.Interface
clock clock.Clock
workers WorkerQueue
StaleInterval time.Duration
cmInformer cache.SharedIndexInformer
}
func NewController(restConfig rest.Config, namespace string, cs model.ConfigStore) *DistributionController {
c := &DistributionController{
CurrentState: make(map[Resource]map[string]Progress),
ObservationTime: make(map[string]time.Time),
UpdateInterval: 200 * time.Millisecond,
StaleInterval: time.Minute,
clock: clock.RealClock{},
configStore: cs,
}
// client-go defaults to 5 QPS, with 10 Boost, which is insufficient for updating status on all the config
// in the mesh. These values can be configured using environment variables for tuning (see pilot/pkg/features)
restConfig.QPS = float32(features.StatusQPS)
restConfig.Burst = features.StatusBurst
var err error
if c.dynamicClient, err = dynamic.NewForConfig(&restConfig); err != nil {
scope.Fatalf("Could not connect to kubernetes: %s", err)
}
// configmap informer
i := informers.NewSharedInformerFactoryWithOptions(kubernetes.NewForConfigOrDie(&restConfig), 1*time.Minute,
informers.WithNamespace(namespace),
informers.WithTweakListOptions(func(listOptions *metav1.ListOptions) {
listOptions.LabelSelector = labels.Set(map[string]string{labelKey: "true"}).AsSelector().String()
})).
Core().V1().ConfigMaps()
c.cmInformer = i.Informer()
i.Informer().AddEventHandler(&DistroReportHandler{dc: c})
return c
}
func (c *DistributionController) Start(stop <-chan struct{}) {
scope.Info("Starting status leader controller")
// this will list all existing configmaps, as well as updates, right?
ctx := NewIstioContext(stop)
go c.cmInformer.Run(ctx.Done())
c.workers = NewWorkerPool(func(resource *Resource, progress *Progress) {
c.writeStatus(*resource, *progress)
}, uint(features.StatusMaxWorkers.Get()))
c.workers.Run(ctx)
// create Status Writer
t := c.clock.Tick(c.UpdateInterval)
go func() {
for {
select {
case <-ctx.Done():
return
case <-t:
staleReporters := c.writeAllStatus()
if len(staleReporters) > 0 {
c.removeStaleReporters(staleReporters)
}
}
}
}()
}
func (c *DistributionController) handleReport(d DistributionReport) {
defer c.mu.Unlock()
c.mu.Lock()
for resstr := range d.InProgressResources {
res := *ResourceFromString(resstr)
if _, ok := c.CurrentState[res]; !ok {
c.CurrentState[res] = make(map[string]Progress)
}
c.CurrentState[res][d.Reporter] = Progress{d.InProgressResources[resstr], d.DataPlaneCount}
}
c.ObservationTime[d.Reporter] = c.clock.Now()
}
func (c *DistributionController) writeAllStatus() (staleReporters []string) {
defer c.mu.RUnlock()
c.mu.RLock()
for config, fractions := range c.CurrentState {
var distributionState Progress
for reporter, w := range fractions {
// check for stale data here
if c.clock.Since(c.ObservationTime[reporter]) > c.StaleInterval {
scope.Warnf("Status reporter %s has not been heard from since %v, deleting report.",
reporter, c.ObservationTime[reporter])
staleReporters = append(staleReporters, reporter)
} else {
distributionState.PlusEquals(w)
}
}
if distributionState.TotalInstances > 0 { // this is necessary when all reports are stale.
c.queueWriteStatus(config, distributionState)
}
}
return
}
func (c *DistributionController) writeStatus(config Resource, distributionState Progress) {
schema, _ := collections.All.FindByGroupVersionResource(config.GroupVersionResource)
if schema == nil {
scope.Warnf("schema %v could not be identified", schema)
c.pruneOldVersion(config)
return
}
if !strings.HasSuffix(schema.Resource().Group(), "istio.io") {
// we don't write status for objects we don't own
return
}
current := c.configStore.Get(schema.Resource().GroupVersionKind(), config.Name, config.Namespace)
if current == nil {
scope.Warnf("config store missing entry %v, status will not update", config)
// this happens when resources are rapidly deleted, such as the validation-readiness checker
c.pruneOldVersion(config)
return
}
if config.Generation != strconv.FormatInt(current.Generation, 10) {
// this distribution report is for an old version of the object. Prune and continue.
c.pruneOldVersion(config)
return
}
// check if status needs updating
if needsReconcile, desiredStatus := ReconcileStatuses(current, distributionState, current.Generation); needsReconcile {
// technically, we should be updating probe time even when reconciling isn't needed, but
// I'm skipping that for efficiency.
current.Status = desiredStatus
_, err := c.configStore.UpdateStatus(*current)
if err != nil {
scope.Errorf("Encountered unexpected error updating status for %v, will try again later: %s", config, err)
return
}
}
}
func (c *DistributionController) pruneOldVersion(config Resource) {
defer c.mu.Unlock()
c.mu.Lock()
delete(c.CurrentState, config)
}
func (c *DistributionController) removeStaleReporters(staleReporters []string) {
defer c.mu.Unlock()
c.mu.Lock()
for key, fractions := range c.CurrentState {
for _, staleReporter := range staleReporters {
delete(fractions, staleReporter)
}
c.CurrentState[key] = fractions
}
}
func (c *DistributionController) queueWriteStatus(config Resource, state Progress) {
c.workers.Push(config, state)
}
func (c *DistributionController) configDeleted(res config.Config) {
r := ResourceFromModelConfig(res)
c.workers.Delete(*r)
}
func GetTypedStatus(in interface{}) (out v1alpha1.IstioStatus, err error) {
var statusBytes []byte
if statusBytes, err = json.Marshal(in); err == nil {
err = json.Unmarshal(statusBytes, &out)
}
return
}
func boolToConditionStatus(b bool) string {
if b {
return "True"
}
return "False"
}
func ReconcileStatuses(current *config.Config, desired Progress, generation int64) (bool, *v1alpha1.IstioStatus) {
needsReconcile := false
currentStatus, err := GetTypedStatus(current.Status)
desiredCondition := v1alpha1.IstioCondition{
Type: "Reconciled",
Status: boolToConditionStatus(desired.AckedInstances == desired.TotalInstances),
LastProbeTime: types.TimestampNow(),
LastTransitionTime: types.TimestampNow(),
Message: fmt.Sprintf("%d/%d proxies up to date.", desired.AckedInstances, desired.TotalInstances),
}
if err != nil {
// the status field is in an unexpected state.
if scope.DebugEnabled() {
scope.Debugf("Encountered unexpected status content. Overwriting status: %v", current.Status)
} else {
scope.Warn("Encountered unexpected status content. Overwriting status.")
}
currentStatus = v1alpha1.IstioStatus{
Conditions: []*v1alpha1.IstioCondition{&desiredCondition},
}
currentStatus.ObservedGeneration = generation
return true, ¤tStatus
}
var currentCondition *v1alpha1.IstioCondition
conditionIndex := -1
for i, c := range currentStatus.Conditions {
if c.Type == "Reconciled" {
currentCondition = currentStatus.Conditions[i]
conditionIndex = i
}
}
if currentCondition == nil ||
currentCondition.Message != desiredCondition.Message ||
currentCondition.Status != desiredCondition.Status {
needsReconcile = true
}
if conditionIndex > -1 {
currentStatus.Conditions[conditionIndex] = &desiredCondition
} else {
currentStatus.Conditions = append(currentStatus.Conditions, &desiredCondition)
}
currentStatus.ObservedGeneration = generation
return needsReconcile, ¤tStatus
}
type DistroReportHandler struct {
dc *DistributionController
}
func (drh *DistroReportHandler) OnAdd(obj interface{}) {
drh.HandleNew(obj)
}
func (drh *DistroReportHandler) OnUpdate(oldObj, newObj interface{}) {
drh.HandleNew(newObj)
}
func (drh *DistroReportHandler) HandleNew(obj interface{}) {
cm, ok := obj.(*v1.ConfigMap)
if !ok {
scope.Warnf("expected configmap, but received %v, discarding", obj)
return
}
rptStr := cm.Data[dataField]
scope.Debugf("using report: %s", rptStr)
dr, err := ReportFromYaml([]byte(cm.Data[dataField]))
if err != nil {
scope.Warnf("received malformed distributionReport %s, discarding: %v", cm.Name, err)
return
}
drh.dc.handleReport(dr)
}
func (drh *DistroReportHandler) OnDelete(obj interface{}) {
// TODO: what do we do here? will these ever be deleted?
}
| pilot/pkg/status/state.go | 1 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.9989216327667236,
0.09047791361808777,
0.00016363983741030097,
0.00017527163436170667,
0.2824785113334656
] |
{
"id": 5,
"code_window": [
"\t} else {\n",
"\t\tcurrentStatus.Conditions = append(currentStatus.Conditions, &desiredCondition)\n",
"\t}\n",
"\tcurrentStatus.ObservedGeneration = generation\n",
"\treturn needsReconcile, ¤tStatus\n",
"}\n",
"\n",
"type DistroReportHandler struct {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\treturn needsReconcile, currentStatus\n"
],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 286
} | // Copyright Istio 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 label
import (
"fmt"
"regexp"
"strings"
)
// Selector is a Set of label filter expressions that get applied together to decide whether tests should be selected
// for execution or not.
type Selector struct {
// The constraints are and'ed together.
present Set
absent Set
}
var _ fmt.Stringer = Selector{}
// NewSelector returns a new selector based on the given presence/absence predicates.
func NewSelector(present []Instance, absent []Instance) Selector {
return Selector{
present: NewSet(present...),
absent: NewSet(absent...),
}
}
var userLabelRegex = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)*$`)
// ParseSelector parses and returns a new instance of Selector.
func ParseSelector(s string) (Selector, error) {
var present, absent []Instance
parts := strings.Split(s, ",")
for _, p := range parts {
if len(p) == 0 {
continue
}
var negative bool
switch p[0] {
case '-':
negative = true
p = p[1:]
case '+':
p = p[1:]
}
if !userLabelRegex.Match([]byte(p)) {
return Selector{}, fmt.Errorf("invalid label name: %q", p)
}
l := Instance(p)
if !all.contains(l) {
return Selector{}, fmt.Errorf("unknown label name: %q", p)
}
if negative {
absent = append(absent, l)
} else {
present = append(present, l)
}
}
pSet := NewSet(present...)
aSet := NewSet(absent...)
if pSet.containsAny(aSet) || aSet.containsAny(pSet) {
return Selector{}, fmt.Errorf("conflicting selector specification: %q", s)
}
return NewSelector(present, absent), nil
}
// Selects returns true, if the given label set satisfies the Selector.
func (f *Selector) Selects(inputs Set) bool {
return !inputs.containsAny(f.absent) && inputs.containsAll(f.present)
}
// Excludes returns false, if the given set of labels, even combined with new ones, could end up satisfying the Selector.
// It returns false, if Matches would never return true, even if new labels are added to the input set.
func (f *Selector) Excludes(inputs Set) bool {
return inputs.containsAny(f.absent)
}
func (f Selector) String() string {
var result string
for _, p := range f.present.All() {
if result != "" {
result += ","
}
result += "+" + string(p)
}
for _, p := range f.absent.All() {
if result != "" {
result += ","
}
result += "-" + string(p)
}
return result
}
| pkg/test/framework/label/filter.go | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.00018038693815469742,
0.00017667435167822987,
0.000171445615706034,
0.00017711854889057577,
0.0000029351983812375693
] |
{
"id": 5,
"code_window": [
"\t} else {\n",
"\t\tcurrentStatus.Conditions = append(currentStatus.Conditions, &desiredCondition)\n",
"\t}\n",
"\tcurrentStatus.ObservedGeneration = generation\n",
"\treturn needsReconcile, ¤tStatus\n",
"}\n",
"\n",
"type DistroReportHandler struct {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\treturn needsReconcile, currentStatus\n"
],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 286
} | // Copyright 2013 Prometheus Team
// 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.
syntax = "proto2";
package io.prometheus.client;
option java_package = "io.prometheus.client";
option go_package = "github.com/prometheus/client_model/go;io_prometheus_client";
message LabelPair {
optional string name = 1;
optional string value = 2;
}
enum MetricType {
COUNTER = 0;
GAUGE = 1;
SUMMARY = 2;
UNTYPED = 3;
HISTOGRAM = 4;
}
message Gauge {
optional double value = 1;
}
message Counter {
optional double value = 1;
}
message Quantile {
optional double quantile = 1;
optional double value = 2;
}
message Summary {
optional uint64 sample_count = 1;
optional double sample_sum = 2;
repeated Quantile quantile = 3;
}
message Untyped {
optional double value = 1;
}
message Histogram {
optional uint64 sample_count = 1;
optional double sample_sum = 2;
repeated Bucket bucket = 3; // Ordered in increasing order of upper_bound, +Inf bucket is optional.
}
message Bucket {
optional uint64 cumulative_count = 1; // Cumulative in increasing order.
optional double upper_bound = 2; // Inclusive.
}
message Metric {
repeated LabelPair label = 1;
optional Gauge gauge = 2;
optional Counter counter = 3;
optional Summary summary = 4;
optional Untyped untyped = 5;
optional Histogram histogram = 7;
optional int64 timestamp_ms = 6;
}
message MetricFamily {
optional string name = 1;
optional string help = 2;
optional MetricType type = 3;
repeated Metric metric = 4;
}
| common-protos/github.com/prometheus/client_model/metrics.proto | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.00018099443695973605,
0.00017556623788550496,
0.00016698760737199336,
0.00017676485003903508,
0.000004100745172763709
] |
{
"id": 5,
"code_window": [
"\t} else {\n",
"\t\tcurrentStatus.Conditions = append(currentStatus.Conditions, &desiredCondition)\n",
"\t}\n",
"\tcurrentStatus.ObservedGeneration = generation\n",
"\treturn needsReconcile, ¤tStatus\n",
"}\n",
"\n",
"type DistroReportHandler struct {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\treturn needsReconcile, currentStatus\n"
],
"file_path": "pilot/pkg/status/state.go",
"type": "replace",
"edit_start_line_idx": 286
} | // Copyright Istio 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 cmd
import (
"context"
"fmt"
"io/ioutil"
"os"
envoy_corev3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3"
xdsapi "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3"
"github.com/spf13/cobra"
"istio.io/istio/istioctl/pkg/clioptions"
"istio.io/istio/istioctl/pkg/multixds"
"istio.io/istio/istioctl/pkg/util/handlers"
"istio.io/istio/istioctl/pkg/writer/compare"
"istio.io/istio/istioctl/pkg/writer/pilot"
pilotxds "istio.io/istio/pilot/pkg/xds"
"istio.io/istio/pkg/kube"
"istio.io/pkg/log"
)
func statusCommand() *cobra.Command {
var opts clioptions.ControlPlaneOptions
statusCmd := &cobra.Command{
Use: "proxy-status [<type>/]<name>[.<namespace>]",
Short: "Retrieves the synchronization status of each Envoy in the mesh [kube only]",
Long: `
Retrieves last sent and last acknowledged xDS sync from Istiod to each Envoy in the mesh
`,
Example: ` # Retrieve sync status for all Envoys in a mesh
istioctl proxy-status
# Retrieve sync diff for a single Envoy and Istiod
istioctl proxy-status istio-egressgateway-59585c5b9c-ndc59.istio-system
# Retrieve sync diff between Istiod and one pod under a deployment
istioctl proxy-status deployment/productpage-v1
# Write proxy config-dump to file, and compare to Istio control plane
kubectl port-forward -n istio-system istio-egressgateway-59585c5b9c-ndc59 15000 &
curl localhost:15000/config_dump > cd.json
istioctl proxy-status istio-egressgateway-59585c5b9c-ndc59.istio-system --file cd.json
`,
Aliases: []string{"ps"},
Args: func(cmd *cobra.Command, args []string) error {
if (len(args) == 0) && (configDumpFile != "") {
cmd.Println(cmd.UsageString())
return fmt.Errorf("--file can only be used when pod-name is specified")
}
return nil
},
RunE: func(c *cobra.Command, args []string) error {
kubeClient, err := kubeClientWithRevision(kubeconfig, configContext, opts.Revision)
if err != nil {
return err
}
if len(args) > 0 {
podName, ns, err := handlers.InferPodInfoFromTypedResource(args[0],
handlers.HandleNamespace(namespace, defaultNamespace),
kubeClient.UtilFactory())
if err != nil {
return err
}
var envoyDump []byte
if configDumpFile != "" {
envoyDump, err = readConfigFile(configDumpFile)
} else {
path := "config_dump"
envoyDump, err = kubeClient.EnvoyDo(context.TODO(), podName, ns, "GET", path, nil)
}
if err != nil {
return err
}
path := fmt.Sprintf("/debug/config_dump?proxyID=%s.%s", podName, ns)
istiodDumps, err := kubeClient.AllDiscoveryDo(context.TODO(), istioNamespace, path)
if err != nil {
return err
}
c, err := compare.NewComparator(c.OutOrStdout(), istiodDumps, envoyDump)
if err != nil {
return err
}
return c.Diff()
}
statuses, err := kubeClient.AllDiscoveryDo(context.TODO(), istioNamespace, "/debug/syncz")
if err != nil {
return err
}
sw := pilot.StatusWriter{Writer: c.OutOrStdout()}
return sw.PrintAll(statuses)
},
}
opts.AttachControlPlaneFlags(statusCmd)
statusCmd.PersistentFlags().StringVarP(&configDumpFile, "file", "f", "",
"Envoy config dump JSON file")
return statusCmd
}
func readConfigFile(filename string) ([]byte, error) {
file := os.Stdin
if filename != "-" {
var err error
file, err = os.Open(filename)
if err != nil {
return nil, err
}
}
defer func() {
if err := file.Close(); err != nil {
log.Errorf("failed to close %s: %s", filename, err)
}
}()
data, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
return data, nil
}
func newKubeClientWithRevision(kubeconfig, configContext string, revision string) (kube.ExtendedClient, error) {
return kube.NewExtendedClient(kube.BuildClientCmd(kubeconfig, configContext), revision)
}
func newKubeClient(kubeconfig, configContext string) (kube.ExtendedClient, error) {
return newKubeClientWithRevision(kubeconfig, configContext, "")
}
func xdsStatusCommand() *cobra.Command {
var opts clioptions.ControlPlaneOptions
var centralOpts clioptions.CentralControlPlaneOptions
statusCmd := &cobra.Command{
Use: "proxy-status [<type>/]<name>[.<namespace>]",
Short: "Retrieves the synchronization status of each Envoy in the mesh",
Long: `
Retrieves last sent and last acknowledged xDS sync from Istiod to each Envoy in the mesh
`,
Example: ` # Retrieve sync status for all Envoys in a mesh
istioctl x proxy-status
# Retrieve sync diff for a single Envoy and Istiod
istioctl x proxy-status istio-egressgateway-59585c5b9c-ndc59.istio-system
# SECURITY OPTIONS
# Retrieve proxy status information directly from the control plane, using token security
# (This is the usual way to get the proxy-status with an out-of-cluster control plane.)
istioctl x ps --xds-address istio.cloudprovider.example.com:15012
# Retrieve proxy status information via Kubernetes config, using token security
# (This is the usual way to get the proxy-status with an in-cluster control plane.)
istioctl x proxy-status
# Retrieve proxy status information directly from the control plane, using RSA certificate security
# (Certificates must be obtained before this step. The --cert-dir flag lets istioctl bypass the Kubernetes API server.)
istioctl x ps --xds-address istio.example.com:15012 --cert-dir ~/.istio-certs
# Retrieve proxy status information via XDS from specific control plane in multi-control plane in-cluster configuration
# (Select a specific control plane in an in-cluster canary Istio configuration.)
istioctl x ps --xds-label istio.io/rev=default
`,
Aliases: []string{"ps"},
RunE: func(c *cobra.Command, args []string) error {
kubeClient, err := kubeClientWithRevision(kubeconfig, configContext, opts.Revision)
if err != nil {
return err
}
if len(args) > 0 {
podName, ns, err := handlers.InferPodInfoFromTypedResource(args[0],
handlers.HandleNamespace(namespace, defaultNamespace),
kubeClient.UtilFactory())
if err != nil {
return err
}
path := "config_dump"
envoyDump, err := kubeClient.EnvoyDo(context.TODO(), podName, ns, "GET", path, nil)
if err != nil {
return fmt.Errorf("could not contact sidecar: %w", err)
}
xdsRequest := xdsapi.DiscoveryRequest{
ResourceNames: []string{fmt.Sprintf("%s.%s", podName, ns)},
Node: &envoy_corev3.Node{
Id: "debug~0.0.0.0~istioctl~cluster.local",
},
TypeUrl: pilotxds.TypeDebugConfigDump,
}
xdsResponses, err := multixds.FirstRequestAndProcessXds(&xdsRequest, ¢ralOpts, istioNamespace, kubeClient)
if err != nil {
return err
}
c, err := compare.NewXdsComparator(c.OutOrStdout(), xdsResponses, envoyDump)
if err != nil {
return err
}
return c.Diff()
}
xdsRequest := xdsapi.DiscoveryRequest{
Node: &envoy_corev3.Node{
Id: "debug~0.0.0.0~istioctl~cluster.local",
},
TypeUrl: pilotxds.TypeDebugSyncronization,
}
xdsResponses, err := multixds.AllRequestAndProcessXds(&xdsRequest, ¢ralOpts, istioNamespace, kubeClient)
if err != nil {
return err
}
sw := pilot.XdsStatusWriter{Writer: c.OutOrStdout()}
return sw.PrintAll(xdsResponses)
},
}
opts.AttachControlPlaneFlags(statusCmd)
centralOpts.AttachControlPlaneFlags(statusCmd)
return statusCmd
}
| istioctl/cmd/proxystatus.go | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.00017996775568462908,
0.00017348052642773837,
0.00016524891543667763,
0.00017439163639210165,
0.0000034701713502727216
] |
{
"id": 6,
"code_window": [
"\t\"istio.io/istio/pkg/config\"\n",
")\n",
"\n",
"var statusStillPropagating = v1alpha1.IstioStatus{\n",
"\tConditions: []*v1alpha1.IstioCondition{\n",
"\t\t{\n",
"\t\t\tType: \"PassedValidation\",\n",
"\t\t\tStatus: \"True\",\n",
"\t\t\tMessage: \"just a test, here\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"var statusStillPropagating = &v1alpha1.IstioStatus{\n"
],
"file_path": "pilot/pkg/status/state_test.go",
"type": "replace",
"edit_start_line_idx": 25
} | // Copyright Istio 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 status
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"sync"
"time"
"github.com/gogo/protobuf/types"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/utils/clock"
"istio.io/api/meta/v1alpha1"
"istio.io/istio/pilot/pkg/features"
"istio.io/istio/pilot/pkg/model"
"istio.io/istio/pkg/config"
"istio.io/istio/pkg/config/schema/collections"
"istio.io/pkg/log"
)
var scope = log.RegisterScope("status",
"CRD distribution status debugging", 0)
type Progress struct {
AckedInstances int
TotalInstances int
}
func (p *Progress) PlusEquals(p2 Progress) {
p.TotalInstances += p2.TotalInstances
p.AckedInstances += p2.AckedInstances
}
type DistributionController struct {
configStore model.ConfigStore
mu sync.RWMutex
CurrentState map[Resource]map[string]Progress
ObservationTime map[string]time.Time
UpdateInterval time.Duration
dynamicClient dynamic.Interface
clock clock.Clock
workers WorkerQueue
StaleInterval time.Duration
cmInformer cache.SharedIndexInformer
}
func NewController(restConfig rest.Config, namespace string, cs model.ConfigStore) *DistributionController {
c := &DistributionController{
CurrentState: make(map[Resource]map[string]Progress),
ObservationTime: make(map[string]time.Time),
UpdateInterval: 200 * time.Millisecond,
StaleInterval: time.Minute,
clock: clock.RealClock{},
configStore: cs,
}
// client-go defaults to 5 QPS, with 10 Boost, which is insufficient for updating status on all the config
// in the mesh. These values can be configured using environment variables for tuning (see pilot/pkg/features)
restConfig.QPS = float32(features.StatusQPS)
restConfig.Burst = features.StatusBurst
var err error
if c.dynamicClient, err = dynamic.NewForConfig(&restConfig); err != nil {
scope.Fatalf("Could not connect to kubernetes: %s", err)
}
// configmap informer
i := informers.NewSharedInformerFactoryWithOptions(kubernetes.NewForConfigOrDie(&restConfig), 1*time.Minute,
informers.WithNamespace(namespace),
informers.WithTweakListOptions(func(listOptions *metav1.ListOptions) {
listOptions.LabelSelector = labels.Set(map[string]string{labelKey: "true"}).AsSelector().String()
})).
Core().V1().ConfigMaps()
c.cmInformer = i.Informer()
i.Informer().AddEventHandler(&DistroReportHandler{dc: c})
return c
}
func (c *DistributionController) Start(stop <-chan struct{}) {
scope.Info("Starting status leader controller")
// this will list all existing configmaps, as well as updates, right?
ctx := NewIstioContext(stop)
go c.cmInformer.Run(ctx.Done())
c.workers = NewWorkerPool(func(resource *Resource, progress *Progress) {
c.writeStatus(*resource, *progress)
}, uint(features.StatusMaxWorkers.Get()))
c.workers.Run(ctx)
// create Status Writer
t := c.clock.Tick(c.UpdateInterval)
go func() {
for {
select {
case <-ctx.Done():
return
case <-t:
staleReporters := c.writeAllStatus()
if len(staleReporters) > 0 {
c.removeStaleReporters(staleReporters)
}
}
}
}()
}
func (c *DistributionController) handleReport(d DistributionReport) {
defer c.mu.Unlock()
c.mu.Lock()
for resstr := range d.InProgressResources {
res := *ResourceFromString(resstr)
if _, ok := c.CurrentState[res]; !ok {
c.CurrentState[res] = make(map[string]Progress)
}
c.CurrentState[res][d.Reporter] = Progress{d.InProgressResources[resstr], d.DataPlaneCount}
}
c.ObservationTime[d.Reporter] = c.clock.Now()
}
func (c *DistributionController) writeAllStatus() (staleReporters []string) {
defer c.mu.RUnlock()
c.mu.RLock()
for config, fractions := range c.CurrentState {
var distributionState Progress
for reporter, w := range fractions {
// check for stale data here
if c.clock.Since(c.ObservationTime[reporter]) > c.StaleInterval {
scope.Warnf("Status reporter %s has not been heard from since %v, deleting report.",
reporter, c.ObservationTime[reporter])
staleReporters = append(staleReporters, reporter)
} else {
distributionState.PlusEquals(w)
}
}
if distributionState.TotalInstances > 0 { // this is necessary when all reports are stale.
c.queueWriteStatus(config, distributionState)
}
}
return
}
func (c *DistributionController) writeStatus(config Resource, distributionState Progress) {
schema, _ := collections.All.FindByGroupVersionResource(config.GroupVersionResource)
if schema == nil {
scope.Warnf("schema %v could not be identified", schema)
c.pruneOldVersion(config)
return
}
if !strings.HasSuffix(schema.Resource().Group(), "istio.io") {
// we don't write status for objects we don't own
return
}
current := c.configStore.Get(schema.Resource().GroupVersionKind(), config.Name, config.Namespace)
if current == nil {
scope.Warnf("config store missing entry %v, status will not update", config)
// this happens when resources are rapidly deleted, such as the validation-readiness checker
c.pruneOldVersion(config)
return
}
if config.Generation != strconv.FormatInt(current.Generation, 10) {
// this distribution report is for an old version of the object. Prune and continue.
c.pruneOldVersion(config)
return
}
// check if status needs updating
if needsReconcile, desiredStatus := ReconcileStatuses(current, distributionState, current.Generation); needsReconcile {
// technically, we should be updating probe time even when reconciling isn't needed, but
// I'm skipping that for efficiency.
current.Status = desiredStatus
_, err := c.configStore.UpdateStatus(*current)
if err != nil {
scope.Errorf("Encountered unexpected error updating status for %v, will try again later: %s", config, err)
return
}
}
}
func (c *DistributionController) pruneOldVersion(config Resource) {
defer c.mu.Unlock()
c.mu.Lock()
delete(c.CurrentState, config)
}
func (c *DistributionController) removeStaleReporters(staleReporters []string) {
defer c.mu.Unlock()
c.mu.Lock()
for key, fractions := range c.CurrentState {
for _, staleReporter := range staleReporters {
delete(fractions, staleReporter)
}
c.CurrentState[key] = fractions
}
}
func (c *DistributionController) queueWriteStatus(config Resource, state Progress) {
c.workers.Push(config, state)
}
func (c *DistributionController) configDeleted(res config.Config) {
r := ResourceFromModelConfig(res)
c.workers.Delete(*r)
}
func GetTypedStatus(in interface{}) (out v1alpha1.IstioStatus, err error) {
var statusBytes []byte
if statusBytes, err = json.Marshal(in); err == nil {
err = json.Unmarshal(statusBytes, &out)
}
return
}
func boolToConditionStatus(b bool) string {
if b {
return "True"
}
return "False"
}
func ReconcileStatuses(current *config.Config, desired Progress, generation int64) (bool, *v1alpha1.IstioStatus) {
needsReconcile := false
currentStatus, err := GetTypedStatus(current.Status)
desiredCondition := v1alpha1.IstioCondition{
Type: "Reconciled",
Status: boolToConditionStatus(desired.AckedInstances == desired.TotalInstances),
LastProbeTime: types.TimestampNow(),
LastTransitionTime: types.TimestampNow(),
Message: fmt.Sprintf("%d/%d proxies up to date.", desired.AckedInstances, desired.TotalInstances),
}
if err != nil {
// the status field is in an unexpected state.
if scope.DebugEnabled() {
scope.Debugf("Encountered unexpected status content. Overwriting status: %v", current.Status)
} else {
scope.Warn("Encountered unexpected status content. Overwriting status.")
}
currentStatus = v1alpha1.IstioStatus{
Conditions: []*v1alpha1.IstioCondition{&desiredCondition},
}
currentStatus.ObservedGeneration = generation
return true, ¤tStatus
}
var currentCondition *v1alpha1.IstioCondition
conditionIndex := -1
for i, c := range currentStatus.Conditions {
if c.Type == "Reconciled" {
currentCondition = currentStatus.Conditions[i]
conditionIndex = i
}
}
if currentCondition == nil ||
currentCondition.Message != desiredCondition.Message ||
currentCondition.Status != desiredCondition.Status {
needsReconcile = true
}
if conditionIndex > -1 {
currentStatus.Conditions[conditionIndex] = &desiredCondition
} else {
currentStatus.Conditions = append(currentStatus.Conditions, &desiredCondition)
}
currentStatus.ObservedGeneration = generation
return needsReconcile, ¤tStatus
}
type DistroReportHandler struct {
dc *DistributionController
}
func (drh *DistroReportHandler) OnAdd(obj interface{}) {
drh.HandleNew(obj)
}
func (drh *DistroReportHandler) OnUpdate(oldObj, newObj interface{}) {
drh.HandleNew(newObj)
}
func (drh *DistroReportHandler) HandleNew(obj interface{}) {
cm, ok := obj.(*v1.ConfigMap)
if !ok {
scope.Warnf("expected configmap, but received %v, discarding", obj)
return
}
rptStr := cm.Data[dataField]
scope.Debugf("using report: %s", rptStr)
dr, err := ReportFromYaml([]byte(cm.Data[dataField]))
if err != nil {
scope.Warnf("received malformed distributionReport %s, discarding: %v", cm.Name, err)
return
}
drh.dc.handleReport(dr)
}
func (drh *DistroReportHandler) OnDelete(obj interface{}) {
// TODO: what do we do here? will these ever be deleted?
}
| pilot/pkg/status/state.go | 1 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.013269753195345402,
0.0011745889205485582,
0.00016494462033733726,
0.0001732491800794378,
0.002952322829514742
] |
{
"id": 6,
"code_window": [
"\t\"istio.io/istio/pkg/config\"\n",
")\n",
"\n",
"var statusStillPropagating = v1alpha1.IstioStatus{\n",
"\tConditions: []*v1alpha1.IstioCondition{\n",
"\t\t{\n",
"\t\t\tType: \"PassedValidation\",\n",
"\t\t\tStatus: \"True\",\n",
"\t\t\tMessage: \"just a test, here\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"var statusStillPropagating = &v1alpha1.IstioStatus{\n"
],
"file_path": "pilot/pkg/status/state_test.go",
"type": "replace",
"edit_start_line_idx": 25
} | // Copyright Istio 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 labels
import (
"bytes"
"fmt"
"regexp"
"sort"
"github.com/hashicorp/go-multierror"
)
const (
DNS1123LabelMaxLength = 63 // Public for testing only.
dns1123LabelFmt = "[a-zA-Z0-9](?:[-a-zA-Z0-9]*[a-zA-Z0-9])?"
// a wild-card prefix is an '*', a normal DNS1123 label with a leading '*' or '*-', or a normal DNS1123 label
wildcardPrefix = `(\*|(\*|\*-)?` + dns1123LabelFmt + `)`
// Using kubernetes requirement, a valid key must be a non-empty string consist
// of alphanumeric characters, '-', '_' or '.', and must start and end with an
// alphanumeric character (e.g. 'MyValue', or 'my_value', or '12345'
qualifiedNameFmt = "(?:[A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]"
// In Kubernetes, label names can start with a DNS name followed by a '/':
dnsNamePrefixFmt = dns1123LabelFmt + `(?:\.` + dns1123LabelFmt + `)*/`
dnsNamePrefixMaxLength = 253
)
var (
tagRegexp = regexp.MustCompile("^(" + dnsNamePrefixFmt + ")?(" + qualifiedNameFmt + ")$") // label value can be an empty string
labelValueRegexp = regexp.MustCompile("^" + "(" + qualifiedNameFmt + ")?" + "$")
dns1123LabelRegexp = regexp.MustCompile("^" + dns1123LabelFmt + "$")
wildcardPrefixRegexp = regexp.MustCompile("^" + wildcardPrefix + "$")
)
// Instance is a non empty map of arbitrary strings. Each version of a service can
// be differentiated by a unique set of labels associated with the version. These
// labels are assigned to all instances of a particular service version. For
// example, lets say catalog.mystore.com has 2 versions v1 and v2. v1 instances
// could have labels gitCommit=aeiou234, region=us-east, while v2 instances could
// have labels name=kittyCat,region=us-east.
type Instance map[string]string
// SubsetOf is true if the label has identical values for the keys
func (i Instance) SubsetOf(that Instance) bool {
for k, v := range i {
if that[k] != v {
return false
}
}
return true
}
// Equals returns true if the labels are identical
func (i Instance) Equals(that Instance) bool {
if i == nil {
return that == nil
}
if that == nil {
return i == nil
}
return i.SubsetOf(that) && that.SubsetOf(i)
}
// Validate ensures tag is well-formed
func (i Instance) Validate() error {
if i == nil {
return nil
}
var errs error
for k, v := range i {
if err := validateTagKey(k); err != nil {
errs = multierror.Append(errs, err)
}
if !labelValueRegexp.MatchString(v) {
errs = multierror.Append(errs, fmt.Errorf("invalid tag value: %q", v))
}
}
return errs
}
// IsDNS1123Label tests for a string that conforms to the definition of a label in
// DNS (RFC 1123).
func IsDNS1123Label(value string) bool {
return len(value) <= DNS1123LabelMaxLength && dns1123LabelRegexp.MatchString(value)
}
// IsWildcardDNS1123Label tests for a string that conforms to the definition of a label in DNS (RFC 1123), but allows
// the wildcard label (`*`), and typical labels with a leading astrisk instead of alphabetic character (e.g. "*-foo")
func IsWildcardDNS1123Label(value string) bool {
return len(value) <= DNS1123LabelMaxLength && wildcardPrefixRegexp.MatchString(value)
}
// validateTagKey checks that a string is valid as a Kubernetes label name.
func validateTagKey(k string) error {
match := tagRegexp.FindStringSubmatch(k)
if match == nil {
return fmt.Errorf("invalid tag key: %q", k)
}
if len(match[1]) > 0 {
dnsPrefixLength := len(match[1]) - 1 // exclude the trailing / from the length
if dnsPrefixLength > dnsNamePrefixMaxLength {
return fmt.Errorf("invalid tag key: %q (DNS prefix is too long)", k)
}
}
if len(match[2]) > DNS1123LabelMaxLength {
return fmt.Errorf("invalid tag key: %q (name is too long)", k)
}
return nil
}
func (i Instance) String() string {
labels := make([]string, 0, len(i))
for k, v := range i {
if len(v) > 0 {
labels = append(labels, fmt.Sprintf("%s=%s", k, v))
} else {
labels = append(labels, k)
}
}
sort.Strings(labels)
var buffer bytes.Buffer
var first = true
for _, label := range labels {
if !first {
buffer.WriteString(",")
} else {
first = false
}
buffer.WriteString(label)
}
return buffer.String()
}
| pkg/config/labels/instance.go | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.00035209691850468516,
0.00018503188039176166,
0.00016342138405889273,
0.00017305449000559747,
0.000044286924094194546
] |
{
"id": 6,
"code_window": [
"\t\"istio.io/istio/pkg/config\"\n",
")\n",
"\n",
"var statusStillPropagating = v1alpha1.IstioStatus{\n",
"\tConditions: []*v1alpha1.IstioCondition{\n",
"\t\t{\n",
"\t\t\tType: \"PassedValidation\",\n",
"\t\t\tStatus: \"True\",\n",
"\t\t\tMessage: \"just a test, here\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"var statusStillPropagating = &v1alpha1.IstioStatus{\n"
],
"file_path": "pilot/pkg/status/state_test.go",
"type": "replace",
"edit_start_line_idx": 25
} | // Copyright Istio 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 collection
import (
"testing"
. "github.com/onsi/gomega"
)
func TestNewName(t *testing.T) {
g := NewWithT(t)
c := NewName("c1")
g.Expect(c.String()).To(Equal("c1"))
}
func TestNewName_Invalid(t *testing.T) {
g := NewWithT(t)
defer func() {
r := recover()
g.Expect(r).NotTo(BeNil())
}()
_ = NewName("/")
}
func TestName_String(t *testing.T) {
g := NewWithT(t)
c := NewName("c1")
g.Expect(c.String()).To(Equal("c1"))
}
func TestIsValidName_Valid(t *testing.T) {
data := []string{
"foo",
"9",
"b",
"a",
"_",
"a0_9",
"a0_9/fruj_",
"abc/def",
}
for _, d := range data {
t.Run(d, func(t *testing.T) {
g := NewWithT(t)
b := IsValidName(d)
g.Expect(b).To(BeTrue())
})
}
}
func TestIsValidName_Invalid(t *testing.T) {
data := []string{
"",
"/",
"/a",
"a/",
"$a/bc",
"z//a",
}
for _, d := range data {
t.Run(d, func(t *testing.T) {
g := NewWithT(t)
b := IsValidName(d)
g.Expect(b).To(BeFalse())
})
}
}
| pkg/config/schema/collection/name_test.go | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.00017683430633042008,
0.0001729348732624203,
0.00016901189519558102,
0.0001726727932691574,
0.0000026040049760922557
] |
{
"id": 6,
"code_window": [
"\t\"istio.io/istio/pkg/config\"\n",
")\n",
"\n",
"var statusStillPropagating = v1alpha1.IstioStatus{\n",
"\tConditions: []*v1alpha1.IstioCondition{\n",
"\t\t{\n",
"\t\t\tType: \"PassedValidation\",\n",
"\t\t\tStatus: \"True\",\n",
"\t\t\tMessage: \"just a test, here\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"var statusStillPropagating = &v1alpha1.IstioStatus{\n"
],
"file_path": "pilot/pkg/status/state_test.go",
"type": "replace",
"edit_start_line_idx": 25
} | // Copyright Istio 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 mock
import (
"crypto"
"crypto/x509"
"sync"
"istio.io/istio/security/pkg/pki/util"
)
// FakeKeyCertBundle is a mocked KeyCertBundle for testing.
type FakeKeyCertBundle struct {
CertBytes []byte
Cert *x509.Certificate
PrivKeyBytes []byte
PrivKey *crypto.PrivateKey
CertChainBytes []byte
RootCertBytes []byte
RootCertExpiryTimestamp float64
CACertExpiryTimestamp float64
VerificationErr error
CertOptionsErr error
mutex sync.Mutex
}
// GetAllPem returns all key/cert PEMs in KeyCertBundle together. Getting all values together avoids inconsistency.
func (b *FakeKeyCertBundle) GetAllPem() (certBytes, privKeyBytes, certChainBytes, rootCertBytes []byte) {
b.mutex.Lock()
defer b.mutex.Unlock()
return b.CertBytes, b.PrivKeyBytes, b.CertChainBytes, b.RootCertBytes
}
// GetAll returns all key/cert in KeyCertBundle together. Getting all values together avoids inconsistency.
func (b *FakeKeyCertBundle) GetAll() (cert *x509.Certificate, privKey *crypto.PrivateKey, certChainBytes,
rootCertBytes []byte) {
b.mutex.Lock()
defer b.mutex.Unlock()
return b.Cert, b.PrivKey, b.CertChainBytes, b.RootCertBytes
}
// VerifyAndSetAll returns VerificationErr if it is not nil. Otherwise, it returns all the key/certs in the bundle.
func (b *FakeKeyCertBundle) VerifyAndSetAll(certBytes, privKeyBytes, certChainBytes, rootCertBytes []byte) error {
if b.VerificationErr != nil {
return b.VerificationErr
}
b.mutex.Lock()
defer b.mutex.Unlock()
b.CertBytes = certBytes
b.PrivKeyBytes = privKeyBytes
b.CertChainBytes = certChainBytes
b.RootCertBytes = rootCertBytes
return nil
}
// GetCertChainPem returns CertChainBytes.
func (b *FakeKeyCertBundle) GetCertChainPem() []byte {
return b.CertChainBytes
}
// GetRootCertPem returns RootCertBytes.
func (b *FakeKeyCertBundle) GetRootCertPem() []byte {
return b.RootCertBytes
}
// CertOptions returns CertOptionsErr if it is not nil. Otherwise it returns an empty CertOptions.
func (b *FakeKeyCertBundle) CertOptions() (*util.CertOptions, error) {
if b.CertOptionsErr != nil {
return nil, b.CertOptionsErr
}
return &util.CertOptions{}, nil
}
// ExtractRootCertExpiryTimestamp returns the unix timestamp when the root becomes expires.
func (b *FakeKeyCertBundle) ExtractRootCertExpiryTimestamp() (float64, error) {
return b.RootCertExpiryTimestamp, nil
}
// ExtractCACertExpiryTimestamp returns the unix timestamp when the CA cert becomes expires.
func (b *FakeKeyCertBundle) ExtractCACertExpiryTimestamp() (float64, error) {
return b.CACertExpiryTimestamp, nil
}
| security/pkg/pki/util/mock/fakekeycertbundle.go | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.0038987724110484123,
0.0005456018261611462,
0.0001650446793064475,
0.00017425650730729103,
0.001117739942856133
] |
{
"id": 7,
"code_window": [
"\t\tin interface{}\n",
"\t}\n",
"\ttests := []struct {\n",
"\t\tname string\n",
"\t\targs args\n",
"\t\twantOut v1alpha1.IstioStatus\n",
"\t\twantErr bool\n",
"\t}{\n",
"\t\t{\n",
"\t\t\tname: \"Nondestructive cast\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\twantOut *v1alpha1.IstioStatus\n"
],
"file_path": "pilot/pkg/status/state_test.go",
"type": "replace",
"edit_start_line_idx": 177
} | // Copyright Istio 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 status
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"sync"
"time"
"github.com/gogo/protobuf/types"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/utils/clock"
"istio.io/api/meta/v1alpha1"
"istio.io/istio/pilot/pkg/features"
"istio.io/istio/pilot/pkg/model"
"istio.io/istio/pkg/config"
"istio.io/istio/pkg/config/schema/collections"
"istio.io/pkg/log"
)
var scope = log.RegisterScope("status",
"CRD distribution status debugging", 0)
type Progress struct {
AckedInstances int
TotalInstances int
}
func (p *Progress) PlusEquals(p2 Progress) {
p.TotalInstances += p2.TotalInstances
p.AckedInstances += p2.AckedInstances
}
type DistributionController struct {
configStore model.ConfigStore
mu sync.RWMutex
CurrentState map[Resource]map[string]Progress
ObservationTime map[string]time.Time
UpdateInterval time.Duration
dynamicClient dynamic.Interface
clock clock.Clock
workers WorkerQueue
StaleInterval time.Duration
cmInformer cache.SharedIndexInformer
}
func NewController(restConfig rest.Config, namespace string, cs model.ConfigStore) *DistributionController {
c := &DistributionController{
CurrentState: make(map[Resource]map[string]Progress),
ObservationTime: make(map[string]time.Time),
UpdateInterval: 200 * time.Millisecond,
StaleInterval: time.Minute,
clock: clock.RealClock{},
configStore: cs,
}
// client-go defaults to 5 QPS, with 10 Boost, which is insufficient for updating status on all the config
// in the mesh. These values can be configured using environment variables for tuning (see pilot/pkg/features)
restConfig.QPS = float32(features.StatusQPS)
restConfig.Burst = features.StatusBurst
var err error
if c.dynamicClient, err = dynamic.NewForConfig(&restConfig); err != nil {
scope.Fatalf("Could not connect to kubernetes: %s", err)
}
// configmap informer
i := informers.NewSharedInformerFactoryWithOptions(kubernetes.NewForConfigOrDie(&restConfig), 1*time.Minute,
informers.WithNamespace(namespace),
informers.WithTweakListOptions(func(listOptions *metav1.ListOptions) {
listOptions.LabelSelector = labels.Set(map[string]string{labelKey: "true"}).AsSelector().String()
})).
Core().V1().ConfigMaps()
c.cmInformer = i.Informer()
i.Informer().AddEventHandler(&DistroReportHandler{dc: c})
return c
}
func (c *DistributionController) Start(stop <-chan struct{}) {
scope.Info("Starting status leader controller")
// this will list all existing configmaps, as well as updates, right?
ctx := NewIstioContext(stop)
go c.cmInformer.Run(ctx.Done())
c.workers = NewWorkerPool(func(resource *Resource, progress *Progress) {
c.writeStatus(*resource, *progress)
}, uint(features.StatusMaxWorkers.Get()))
c.workers.Run(ctx)
// create Status Writer
t := c.clock.Tick(c.UpdateInterval)
go func() {
for {
select {
case <-ctx.Done():
return
case <-t:
staleReporters := c.writeAllStatus()
if len(staleReporters) > 0 {
c.removeStaleReporters(staleReporters)
}
}
}
}()
}
func (c *DistributionController) handleReport(d DistributionReport) {
defer c.mu.Unlock()
c.mu.Lock()
for resstr := range d.InProgressResources {
res := *ResourceFromString(resstr)
if _, ok := c.CurrentState[res]; !ok {
c.CurrentState[res] = make(map[string]Progress)
}
c.CurrentState[res][d.Reporter] = Progress{d.InProgressResources[resstr], d.DataPlaneCount}
}
c.ObservationTime[d.Reporter] = c.clock.Now()
}
func (c *DistributionController) writeAllStatus() (staleReporters []string) {
defer c.mu.RUnlock()
c.mu.RLock()
for config, fractions := range c.CurrentState {
var distributionState Progress
for reporter, w := range fractions {
// check for stale data here
if c.clock.Since(c.ObservationTime[reporter]) > c.StaleInterval {
scope.Warnf("Status reporter %s has not been heard from since %v, deleting report.",
reporter, c.ObservationTime[reporter])
staleReporters = append(staleReporters, reporter)
} else {
distributionState.PlusEquals(w)
}
}
if distributionState.TotalInstances > 0 { // this is necessary when all reports are stale.
c.queueWriteStatus(config, distributionState)
}
}
return
}
func (c *DistributionController) writeStatus(config Resource, distributionState Progress) {
schema, _ := collections.All.FindByGroupVersionResource(config.GroupVersionResource)
if schema == nil {
scope.Warnf("schema %v could not be identified", schema)
c.pruneOldVersion(config)
return
}
if !strings.HasSuffix(schema.Resource().Group(), "istio.io") {
// we don't write status for objects we don't own
return
}
current := c.configStore.Get(schema.Resource().GroupVersionKind(), config.Name, config.Namespace)
if current == nil {
scope.Warnf("config store missing entry %v, status will not update", config)
// this happens when resources are rapidly deleted, such as the validation-readiness checker
c.pruneOldVersion(config)
return
}
if config.Generation != strconv.FormatInt(current.Generation, 10) {
// this distribution report is for an old version of the object. Prune and continue.
c.pruneOldVersion(config)
return
}
// check if status needs updating
if needsReconcile, desiredStatus := ReconcileStatuses(current, distributionState, current.Generation); needsReconcile {
// technically, we should be updating probe time even when reconciling isn't needed, but
// I'm skipping that for efficiency.
current.Status = desiredStatus
_, err := c.configStore.UpdateStatus(*current)
if err != nil {
scope.Errorf("Encountered unexpected error updating status for %v, will try again later: %s", config, err)
return
}
}
}
func (c *DistributionController) pruneOldVersion(config Resource) {
defer c.mu.Unlock()
c.mu.Lock()
delete(c.CurrentState, config)
}
func (c *DistributionController) removeStaleReporters(staleReporters []string) {
defer c.mu.Unlock()
c.mu.Lock()
for key, fractions := range c.CurrentState {
for _, staleReporter := range staleReporters {
delete(fractions, staleReporter)
}
c.CurrentState[key] = fractions
}
}
func (c *DistributionController) queueWriteStatus(config Resource, state Progress) {
c.workers.Push(config, state)
}
func (c *DistributionController) configDeleted(res config.Config) {
r := ResourceFromModelConfig(res)
c.workers.Delete(*r)
}
func GetTypedStatus(in interface{}) (out v1alpha1.IstioStatus, err error) {
var statusBytes []byte
if statusBytes, err = json.Marshal(in); err == nil {
err = json.Unmarshal(statusBytes, &out)
}
return
}
func boolToConditionStatus(b bool) string {
if b {
return "True"
}
return "False"
}
func ReconcileStatuses(current *config.Config, desired Progress, generation int64) (bool, *v1alpha1.IstioStatus) {
needsReconcile := false
currentStatus, err := GetTypedStatus(current.Status)
desiredCondition := v1alpha1.IstioCondition{
Type: "Reconciled",
Status: boolToConditionStatus(desired.AckedInstances == desired.TotalInstances),
LastProbeTime: types.TimestampNow(),
LastTransitionTime: types.TimestampNow(),
Message: fmt.Sprintf("%d/%d proxies up to date.", desired.AckedInstances, desired.TotalInstances),
}
if err != nil {
// the status field is in an unexpected state.
if scope.DebugEnabled() {
scope.Debugf("Encountered unexpected status content. Overwriting status: %v", current.Status)
} else {
scope.Warn("Encountered unexpected status content. Overwriting status.")
}
currentStatus = v1alpha1.IstioStatus{
Conditions: []*v1alpha1.IstioCondition{&desiredCondition},
}
currentStatus.ObservedGeneration = generation
return true, ¤tStatus
}
var currentCondition *v1alpha1.IstioCondition
conditionIndex := -1
for i, c := range currentStatus.Conditions {
if c.Type == "Reconciled" {
currentCondition = currentStatus.Conditions[i]
conditionIndex = i
}
}
if currentCondition == nil ||
currentCondition.Message != desiredCondition.Message ||
currentCondition.Status != desiredCondition.Status {
needsReconcile = true
}
if conditionIndex > -1 {
currentStatus.Conditions[conditionIndex] = &desiredCondition
} else {
currentStatus.Conditions = append(currentStatus.Conditions, &desiredCondition)
}
currentStatus.ObservedGeneration = generation
return needsReconcile, ¤tStatus
}
type DistroReportHandler struct {
dc *DistributionController
}
func (drh *DistroReportHandler) OnAdd(obj interface{}) {
drh.HandleNew(obj)
}
func (drh *DistroReportHandler) OnUpdate(oldObj, newObj interface{}) {
drh.HandleNew(newObj)
}
func (drh *DistroReportHandler) HandleNew(obj interface{}) {
cm, ok := obj.(*v1.ConfigMap)
if !ok {
scope.Warnf("expected configmap, but received %v, discarding", obj)
return
}
rptStr := cm.Data[dataField]
scope.Debugf("using report: %s", rptStr)
dr, err := ReportFromYaml([]byte(cm.Data[dataField]))
if err != nil {
scope.Warnf("received malformed distributionReport %s, discarding: %v", cm.Name, err)
return
}
drh.dc.handleReport(dr)
}
func (drh *DistroReportHandler) OnDelete(obj interface{}) {
// TODO: what do we do here? will these ever be deleted?
}
| pilot/pkg/status/state.go | 1 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.028001952916383743,
0.0014914142666384578,
0.00016416040307376534,
0.00017102387209888548,
0.005204224027693272
] |
{
"id": 7,
"code_window": [
"\t\tin interface{}\n",
"\t}\n",
"\ttests := []struct {\n",
"\t\tname string\n",
"\t\targs args\n",
"\t\twantOut v1alpha1.IstioStatus\n",
"\t\twantErr bool\n",
"\t}{\n",
"\t\t{\n",
"\t\t\tname: \"Nondestructive cast\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\twantOut *v1alpha1.IstioStatus\n"
],
"file_path": "pilot/pkg/status/state_test.go",
"type": "replace",
"edit_start_line_idx": 177
} | apiVersion: install.istio.io/v1alpha1
kind: IstioOperator
spec:
values:
pilot:
traceSampling: 0.1 # override from 1.0
| operator/samples/values-pilot.yaml | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.00023379897174891084,
0.00023379897174891084,
0.00023379897174891084,
0.00023379897174891084,
0
] |
{
"id": 7,
"code_window": [
"\t\tin interface{}\n",
"\t}\n",
"\ttests := []struct {\n",
"\t\tname string\n",
"\t\targs args\n",
"\t\twantOut v1alpha1.IstioStatus\n",
"\t\twantErr bool\n",
"\t}{\n",
"\t\t{\n",
"\t\t\tname: \"Nondestructive cast\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\twantOut *v1alpha1.IstioStatus\n"
],
"file_path": "pilot/pkg/status/state_test.go",
"type": "replace",
"edit_start_line_idx": 177
} |
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
| licenses/google.golang.org/grpc/LICENSE | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.0001769824157236144,
0.00017406076949555427,
0.00016918685287237167,
0.00017410302825737745,
0.0000017169577404274605
] |
{
"id": 7,
"code_window": [
"\t\tin interface{}\n",
"\t}\n",
"\ttests := []struct {\n",
"\t\tname string\n",
"\t\targs args\n",
"\t\twantOut v1alpha1.IstioStatus\n",
"\t\twantErr bool\n",
"\t}{\n",
"\t\t{\n",
"\t\t\tname: \"Nondestructive cast\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\twantOut *v1alpha1.IstioStatus\n"
],
"file_path": "pilot/pkg/status/state_test.go",
"type": "replace",
"edit_start_line_idx": 177
} | // +build integ
// Copyright Istio 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 sdsegress
import (
"context"
"fmt"
"testing"
"time"
"istio.io/istio/pkg/test/echo/common/response"
epb "istio.io/istio/pkg/test/echo/proto"
"istio.io/istio/pkg/test/framework"
"istio.io/istio/pkg/test/framework/components/echo"
"istio.io/istio/pkg/test/framework/components/echo/echoboot"
"istio.io/istio/pkg/test/framework/components/istio"
"istio.io/istio/pkg/test/framework/components/namespace"
"istio.io/istio/pkg/test/framework/components/prometheus"
"istio.io/istio/pkg/test/util/file"
"istio.io/istio/tests/integration/security/util"
)
const (
// should be templated into YAML, and made interchangeable with other sites
externalURL = "http://bing.com"
externalReqCount = 2
egressName = "istio-egressgateway"
// paths to test configs
istioMutualTLSGatewayConfig = "testdata/istio-mutual-gateway-bing.yaml"
simpleTLSGatewayConfig = "testdata/simple-tls-gateway-bing.yaml"
)
// TestSdsEgressGatewayIstioMutual brings up an SDS enabled cluster and will ensure that the ISTIO_MUTUAL
// TLS mode allows secure communication between the egress and workloads. This test brings up an ISTIO_MUTUAL enabled
// gateway, and then, an incorrectly configured simple TLS gateway. The test will ensure that requests are routed
// securely through the egress gateway in the first case, and fail in the second case.
func TestSdsEgressGatewayIstioMutual(t *testing.T) {
// Turn it back on once issue is fixed.
t.Skip("https://github.com/istio/istio/issues/17933")
framework.NewTest(t).
Features("security.egress.mtls.sds").
Run(func(ctx framework.TestContext) {
istioCfg := istio.DefaultConfigOrFail(t, ctx)
namespace.ClaimOrFail(t, ctx, istioCfg.SystemNamespace)
ns := namespace.NewOrFail(t, ctx, namespace.Config{
Prefix: "sds-egress-gateway-workload",
Inject: true,
})
applySetupConfig(ctx, ns)
testCases := map[string]struct {
configPath string
response string
}{
"ISTIO_MUTUAL TLS mode requests are routed through egress succeed": {
configPath: istioMutualTLSGatewayConfig,
response: response.StatusCodeOK,
},
"SIMPLE TLS mode requests are routed through gateway but fail with 503": {
configPath: simpleTLSGatewayConfig,
response: response.StatusCodeUnavailable,
},
}
for name, tc := range testCases {
ctx.NewSubTest(name).
Run(func(ctx framework.TestContext) {
doIstioMutualTest(ctx, ns, tc.configPath, tc.response)
})
}
})
}
func doIstioMutualTest(
ctx framework.TestContext, ns namespace.Instance, configPath, expectedResp string) {
var client echo.Instance
echoboot.NewBuilder(ctx).
With(&client, util.EchoConfig("client", ns, false, nil, nil)).
BuildOrFail(ctx)
ctx.Config().ApplyYAMLOrFail(ctx, ns.Name(), file.AsStringOrFail(ctx, configPath))
defer ctx.Config().DeleteYAMLOrFail(ctx, ns.Name(), file.AsStringOrFail(ctx, configPath))
// give the configuration a moment to kick in
time.Sleep(time.Second * 20)
pretestReqCount := getEgressRequestCountOrFail(ctx, ns, prom)
for i := 0; i < externalReqCount; i++ {
w := client.WorkloadsOrFail(ctx)[0]
responses, err := w.ForwardEcho(context.TODO(), &epb.ForwardEchoRequest{
Url: externalURL,
Count: 1,
})
if err != nil {
ctx.Fatalf("failed to make request from echo instance to %s: %v", externalURL, err)
}
if len(responses) < 1 {
ctx.Fatalf("received no responses from request to %s", externalURL)
}
resp := responses[0]
if expectedResp != resp.Code {
ctx.Errorf("expected status %s but got %s", expectedResp, resp.Code)
}
}
// give prometheus some time to ingest the metrics
posttestReqCount := getEgressRequestCountOrFail(ctx, ns, prom)
newGatewayReqs := posttestReqCount - pretestReqCount
if newGatewayReqs != externalReqCount {
ctx.Errorf("expected %d requests routed through egress, got %d",
externalReqCount, newGatewayReqs)
}
}
// sets up the destination rule to route through egress, virtual service, and service entry
func applySetupConfig(ctx framework.TestContext, ns namespace.Instance) {
ctx.Helper()
configFiles := []string{
"testdata/destination-rule-bing.yaml",
"testdata/rule-route-sidecar-to-egress-bing.yaml",
"testdata/service-entry-bing.yaml",
}
for _, c := range configFiles {
if err := ctx.Config().ApplyYAML(ns.Name(), file.AsStringOrFail(ctx, c)); err != nil {
ctx.Fatalf("failed to apply configuration file %s; err: %v", c, err)
}
}
}
func getMetric(ctx framework.TestContext, prometheus prometheus.Instance, query string) (float64, error) {
ctx.Helper()
value, err := prometheus.WaitForQuiesce(query)
if err != nil {
return 0, fmt.Errorf("failed to retrieve metric from prom with err: %v", err)
}
metric, err := prometheus.Sum(value, nil)
if err != nil {
ctx.Logf("value: %s", value.String())
return 0, fmt.Errorf("could not find metric value: %v", err)
}
return metric, nil
}
func getEgressRequestCountOrFail(ctx framework.TestContext, ns namespace.Instance, prom prometheus.Instance) int {
query := fmt.Sprintf("istio_requests_total{destination_app=\"%s\",source_workload_namespace=\"%s\"}",
egressName, ns.Name())
ctx.Helper()
reqCount, err := getMetric(ctx, prom, query)
if err != nil {
// assume that if the request failed, it was because there was no metric ingested
// if this is not the case, the test will fail down the road regardless
// checking for error based on string match could lead to future failure
reqCount = 0
}
return int(reqCount)
}
| tests/integration/security/sds_egress/sds_istio_mutual_egress_test.go | 0 | https://github.com/istio/istio/commit/68d5c3fbf9ee2eef885997bc9f309fcdf2ebc87a | [
0.0007776697748340666,
0.0002232256520073861,
0.00016500736819580197,
0.00017275685968343168,
0.00014843032113276422
] |
{
"id": 0,
"code_window": [
"func (lr *LogReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) {\n",
"\tb := &bytes.Buffer{}\n",
"\tb.WriteString(\"******************************************************\\n\")\n",
"\tglog.V(2).Infof(b.String())\n",
"}\n",
"\n",
"func (lr *LogReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) {}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tglog.V(0).Infof(b.String())\n"
],
"file_path": "test/e2e_node/e2e_node_suite_test.go",
"type": "replace",
"edit_start_line_idx": 93
} | /*
Copyright 2016 The Kubernetes Authors All rights reserved.
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.
*/
// To run the e2e tests against one or more hosts on gce:
// $ godep go run run_e2e.go --logtostderr --v 2 --ssh-env gce --hosts <comma separated hosts>
// To run the e2e tests against one or more images on gce and provision them:
// $ godep go run run_e2e.go --logtostderr --v 2 --project <project> --zone <zone> --ssh-env gce --images <comma separated images>
package main
import (
"flag"
"fmt"
"math/rand"
"net/http"
"os"
"strings"
"time"
"k8s.io/kubernetes/test/e2e_node"
"github.com/golang/glog"
"github.com/pborman/uuid"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/compute/v1"
)
var instanceNamePrefix = flag.String("instance-name-prefix", "", "prefix for instance names")
var zone = flag.String("zone", "", "gce zone the hosts live in")
var project = flag.String("project", "", "gce project the hosts live in")
var images = flag.String("images", "", "images to test")
var hosts = flag.String("hosts", "", "hosts to test")
var cleanup = flag.Bool("cleanup", true, "If true remove files from remote hosts and delete temporary instances")
var buildOnly = flag.Bool("build-only", false, "If true, build e2e_node_test.tar.gz and exit.")
var computeService *compute.Service
type TestResult struct {
output string
err error
host string
}
func main() {
flag.Parse()
rand.Seed(time.Now().UTC().UnixNano())
if *buildOnly {
// Build the archive and exit
e2e_node.CreateTestArchive()
return
}
if *hosts == "" && *images == "" {
glog.Fatalf("Must specify one of --images or --hosts flag.")
}
if *images != "" && *zone == "" {
glog.Fatal("Must specify --zone flag")
}
if *images != "" && *project == "" {
glog.Fatal("Must specify --project flag")
}
if *instanceNamePrefix == "" {
*instanceNamePrefix = "tmp-node-e2e-" + uuid.NewUUID().String()[:8]
}
// Setup coloring
stat, _ := os.Stdout.Stat()
useColor := (stat.Mode() & os.ModeCharDevice) != 0
blue := ""
noColour := ""
if useColor {
blue = "\033[0;34m"
noColour = "\033[0m"
}
archive := e2e_node.CreateTestArchive()
defer os.Remove(archive)
results := make(chan *TestResult)
running := 0
if *images != "" {
// Setup the gce client for provisioning instances
// Getting credentials on gce jenkins is flaky, so try a couple times
var err error
for i := 0; i < 10; i++ {
var client *http.Client
client, err = google.DefaultClient(oauth2.NoContext, compute.ComputeScope)
if err != nil {
continue
}
computeService, err = compute.New(client)
if err != nil {
continue
}
time.Sleep(time.Second * 6)
}
if err != nil {
glog.Fatalf("Unable to create gcloud compute service using defaults. Make sure you are authenticated. %v", err)
}
for _, image := range strings.Split(*images, ",") {
running++
fmt.Printf("Initializing e2e tests using image %s.\n", image)
go func(image string) { results <- testImage(image, archive) }(image)
}
}
if *hosts != "" {
for _, host := range strings.Split(*hosts, ",") {
fmt.Printf("Initializing e2e tests using host %s.\n", host)
running++
go func(host string) {
results <- testHost(host, archive)
}(host)
}
}
// Wait for all tests to complete and emit the results
errCount := 0
for i := 0; i < running; i++ {
tr := <-results
host := tr.host
fmt.Printf("%s================================================================%s\n", blue, noColour)
if tr.err != nil {
errCount++
fmt.Printf("Failure Finished Host %s Test Suite\n%s\n%v\n", host, tr.output, tr.err)
} else {
fmt.Printf("Success Finished Host %s Test Suite\n%s\n", host, tr.output)
}
fmt.Printf("%s================================================================%s\n", blue, noColour)
}
// Set the exit code if there were failures
if errCount > 0 {
fmt.Printf("Failure: %d errors encountered.", errCount)
os.Exit(1)
}
}
// Run tests in archive against host
func testHost(host, archive string) *TestResult {
output, err := e2e_node.RunRemote(archive, host, *cleanup)
return &TestResult{
output: output,
err: err,
host: host,
}
}
// Provision a gce instance using image and run the tests in archive against the instance.
// Delete the instance afterward.
func testImage(image, archive string) *TestResult {
host, err := createInstance(image)
if *cleanup {
defer deleteInstance(image)
}
if err != nil {
return &TestResult{
err: fmt.Errorf("Unable to create gce instance with running docker daemon for image %s. %v", image, err),
}
}
return testHost(host, archive)
}
// Provision a gce instance using image
func createInstance(image string) (string, error) {
name := imageToInstanceName(image)
i := &compute.Instance{
Name: name,
MachineType: machineType(),
NetworkInterfaces: []*compute.NetworkInterface{
{
AccessConfigs: []*compute.AccessConfig{
{
Type: "ONE_TO_ONE_NAT",
Name: "External NAT",
},
}},
},
Disks: []*compute.AttachedDisk{
{
AutoDelete: true,
Boot: true,
Type: "PERSISTENT",
InitializeParams: &compute.AttachedDiskInitializeParams{
SourceImage: sourceImage(image),
},
},
},
}
op, err := computeService.Instances.Insert(*project, *zone, i).Do()
if err != nil {
return "", err
}
if op.Error != nil {
return "", fmt.Errorf("Could not create instance %s: %+v", name, op.Error)
}
instanceRunning := false
for i := 0; i < 30 && !instanceRunning; i++ {
if i > 0 {
time.Sleep(time.Second * 20)
}
var instance *compute.Instance
instance, err = computeService.Instances.Get(*project, *zone, name).Do()
if err != nil {
continue
}
if strings.ToUpper(instance.Status) != "RUNNING" {
err = fmt.Errorf("Instance %s not in state RUNNING, was %s.", name, instance.Status)
continue
}
var output string
output, err = e2e_node.RunSshCommand("ssh", name, "--", "sudo", "docker", "version")
if err != nil {
err = fmt.Errorf("Instance %s not running docker daemon - Command failed: %s", name, output)
continue
}
if !strings.Contains(output, "Server") {
err = fmt.Errorf("Instance %s not running docker daemon - Server not found: %s", name, output)
continue
}
instanceRunning = true
}
return name, err
}
func deleteInstance(image string) {
_, err := computeService.Instances.Delete(*project, *zone, imageToInstanceName(image)).Do()
if err != nil {
glog.Infof("Error deleting instance %s", imageToInstanceName(image))
}
}
func imageToInstanceName(image string) string {
return *instanceNamePrefix + "-" + image
}
func sourceImage(image string) string {
return fmt.Sprintf("projects/%s/global/images/%s", *project, image)
}
func machineType() string {
return fmt.Sprintf("zones/%s/machineTypes/n1-standard-1", *zone)
}
| test/e2e_node/runner/run_e2e.go | 1 | https://github.com/kubernetes/kubernetes/commit/5155df0287bd4e4a35dfc924750622243e574f84 | [
0.00017877278150990605,
0.00017277427832596004,
0.00016695672820787877,
0.00017321179620921612,
0.000002906216877818224
] |
{
"id": 0,
"code_window": [
"func (lr *LogReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) {\n",
"\tb := &bytes.Buffer{}\n",
"\tb.WriteString(\"******************************************************\\n\")\n",
"\tglog.V(2).Infof(b.String())\n",
"}\n",
"\n",
"func (lr *LogReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) {}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tglog.V(0).Infof(b.String())\n"
],
"file_path": "test/e2e_node/e2e_node_suite_test.go",
"type": "replace",
"edit_start_line_idx": 93
} | /*
Copyright 2016 The Kubernetes Authors All rights reserved.
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 unversioned
import (
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/client/restclient"
)
// The PodExpansion interface allows manually adding extra methods to the PodInterface.
type PodExpansion interface {
Bind(binding *api.Binding) error
GetLogs(name string, opts *api.PodLogOptions) *restclient.Request
}
// Bind applies the provided binding to the named pod in the current namespace (binding.Namespace is ignored).
func (c *pods) Bind(binding *api.Binding) error {
return c.client.Post().Namespace(c.ns).Resource("pods").Name(binding.Name).SubResource("binding").Body(binding).Do().Error()
}
// Get constructs a request for getting the logs for a pod
func (c *pods) GetLogs(name string, opts *api.PodLogOptions) *restclient.Request {
return c.client.Get().Namespace(c.ns).Name(name).Resource("pods").SubResource("log").VersionedParams(opts, api.ParameterCodec)
}
| pkg/client/clientset_generated/internalclientset/typed/core/unversioned/pod_expansion.go | 0 | https://github.com/kubernetes/kubernetes/commit/5155df0287bd4e4a35dfc924750622243e574f84 | [
0.00017828574345912784,
0.00017315974400844425,
0.00016410469834227115,
0.00017512428166810423,
0.000005797864105261397
] |
{
"id": 0,
"code_window": [
"func (lr *LogReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) {\n",
"\tb := &bytes.Buffer{}\n",
"\tb.WriteString(\"******************************************************\\n\")\n",
"\tglog.V(2).Infof(b.String())\n",
"}\n",
"\n",
"func (lr *LogReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) {}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tglog.V(0).Infof(b.String())\n"
],
"file_path": "test/e2e_node/e2e_node_suite_test.go",
"type": "replace",
"edit_start_line_idx": 93
} | package kernel
import (
"fmt"
"syscall"
"unsafe"
)
type KernelVersionInfo struct {
kvi string
major int
minor int
build int
}
func (k *KernelVersionInfo) String() string {
return fmt.Sprintf("%d.%d %d (%s)", k.major, k.minor, k.build, k.kvi)
}
func GetKernelVersion() (*KernelVersionInfo, error) {
var (
h syscall.Handle
dwVersion uint32
err error
)
KVI := &KernelVersionInfo{"Unknown", 0, 0, 0}
if err = syscall.RegOpenKeyEx(syscall.HKEY_LOCAL_MACHINE,
syscall.StringToUTF16Ptr(`SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\`),
0,
syscall.KEY_READ,
&h); err != nil {
return KVI, err
}
defer syscall.RegCloseKey(h)
var buf [1 << 10]uint16
var typ uint32
n := uint32(len(buf) * 2) // api expects array of bytes, not uint16
if err = syscall.RegQueryValueEx(h,
syscall.StringToUTF16Ptr("BuildLabEx"),
nil,
&typ,
(*byte)(unsafe.Pointer(&buf[0])),
&n); err != nil {
return KVI, err
}
KVI.kvi = syscall.UTF16ToString(buf[:])
// Important - docker.exe MUST be manifested for this API to return
// the correct information.
if dwVersion, err = syscall.GetVersion(); err != nil {
return KVI, err
}
KVI.major = int(dwVersion & 0xFF)
KVI.minor = int((dwVersion & 0XFF00) >> 8)
KVI.build = int((dwVersion & 0xFFFF0000) >> 16)
return KVI, nil
}
| Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/kernel/kernel_windows.go | 0 | https://github.com/kubernetes/kubernetes/commit/5155df0287bd4e4a35dfc924750622243e574f84 | [
0.001344001735560596,
0.000342656800057739,
0.00016992440214380622,
0.00017637491691857576,
0.00040880899177864194
] |
{
"id": 0,
"code_window": [
"func (lr *LogReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) {\n",
"\tb := &bytes.Buffer{}\n",
"\tb.WriteString(\"******************************************************\\n\")\n",
"\tglog.V(2).Infof(b.String())\n",
"}\n",
"\n",
"func (lr *LogReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) {}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tglog.V(0).Infof(b.String())\n"
],
"file_path": "test/e2e_node/e2e_node_suite_test.go",
"type": "replace",
"edit_start_line_idx": 93
} | // +build darwin dragonfly freebsd linux netbsd openbsd solaris
package user
import (
"io"
"os"
)
// Unix-specific path to the passwd and group formatted files.
const (
unixPasswdPath = "/etc/passwd"
unixGroupPath = "/etc/group"
)
func GetPasswdPath() (string, error) {
return unixPasswdPath, nil
}
func GetPasswd() (io.ReadCloser, error) {
return os.Open(unixPasswdPath)
}
func GetGroupPath() (string, error) {
return unixGroupPath, nil
}
func GetGroup() (io.ReadCloser, error) {
return os.Open(unixGroupPath)
}
| Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/lookup_unix.go | 0 | https://github.com/kubernetes/kubernetes/commit/5155df0287bd4e4a35dfc924750622243e574f84 | [
0.00017645684420131147,
0.00017197139095515013,
0.00016468498506583273,
0.00017337188182864338,
0.000004394550160213839
] |
{
"id": 1,
"code_window": [
"\t\tb.WriteString(fmt.Sprintf(\"apiserver output:\\n%s\\n\", e2es.apiServerCombinedOut.String()))\n",
"\t\tb.WriteString(\"-------------------------------------------------------------\\n\")\n",
"\t\tb.WriteString(fmt.Sprintf(\"etcd output:\\n%s\\n\", e2es.etcdCombinedOut.String()))\n",
"\t}\n",
"\tb.WriteString(\"******************************************************\\n\")\n",
"\tglog.V(2).Infof(b.String())\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\tglog.V(0).Infof(b.String())\n"
],
"file_path": "test/e2e_node/e2e_node_suite_test.go",
"type": "replace",
"edit_start_line_idx": 117
} | /*
Copyright 2016 The Kubernetes Authors All rights reserved.
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.
*/
// To run the e2e tests against one or more hosts on gce:
// $ godep go run run_e2e.go --logtostderr --v 2 --ssh-env gce --hosts <comma separated hosts>
// To run the e2e tests against one or more images on gce and provision them:
// $ godep go run run_e2e.go --logtostderr --v 2 --project <project> --zone <zone> --ssh-env gce --images <comma separated images>
package main
import (
"flag"
"fmt"
"math/rand"
"net/http"
"os"
"strings"
"time"
"k8s.io/kubernetes/test/e2e_node"
"github.com/golang/glog"
"github.com/pborman/uuid"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/compute/v1"
)
var instanceNamePrefix = flag.String("instance-name-prefix", "", "prefix for instance names")
var zone = flag.String("zone", "", "gce zone the hosts live in")
var project = flag.String("project", "", "gce project the hosts live in")
var images = flag.String("images", "", "images to test")
var hosts = flag.String("hosts", "", "hosts to test")
var cleanup = flag.Bool("cleanup", true, "If true remove files from remote hosts and delete temporary instances")
var buildOnly = flag.Bool("build-only", false, "If true, build e2e_node_test.tar.gz and exit.")
var computeService *compute.Service
type TestResult struct {
output string
err error
host string
}
func main() {
flag.Parse()
rand.Seed(time.Now().UTC().UnixNano())
if *buildOnly {
// Build the archive and exit
e2e_node.CreateTestArchive()
return
}
if *hosts == "" && *images == "" {
glog.Fatalf("Must specify one of --images or --hosts flag.")
}
if *images != "" && *zone == "" {
glog.Fatal("Must specify --zone flag")
}
if *images != "" && *project == "" {
glog.Fatal("Must specify --project flag")
}
if *instanceNamePrefix == "" {
*instanceNamePrefix = "tmp-node-e2e-" + uuid.NewUUID().String()[:8]
}
// Setup coloring
stat, _ := os.Stdout.Stat()
useColor := (stat.Mode() & os.ModeCharDevice) != 0
blue := ""
noColour := ""
if useColor {
blue = "\033[0;34m"
noColour = "\033[0m"
}
archive := e2e_node.CreateTestArchive()
defer os.Remove(archive)
results := make(chan *TestResult)
running := 0
if *images != "" {
// Setup the gce client for provisioning instances
// Getting credentials on gce jenkins is flaky, so try a couple times
var err error
for i := 0; i < 10; i++ {
var client *http.Client
client, err = google.DefaultClient(oauth2.NoContext, compute.ComputeScope)
if err != nil {
continue
}
computeService, err = compute.New(client)
if err != nil {
continue
}
time.Sleep(time.Second * 6)
}
if err != nil {
glog.Fatalf("Unable to create gcloud compute service using defaults. Make sure you are authenticated. %v", err)
}
for _, image := range strings.Split(*images, ",") {
running++
fmt.Printf("Initializing e2e tests using image %s.\n", image)
go func(image string) { results <- testImage(image, archive) }(image)
}
}
if *hosts != "" {
for _, host := range strings.Split(*hosts, ",") {
fmt.Printf("Initializing e2e tests using host %s.\n", host)
running++
go func(host string) {
results <- testHost(host, archive)
}(host)
}
}
// Wait for all tests to complete and emit the results
errCount := 0
for i := 0; i < running; i++ {
tr := <-results
host := tr.host
fmt.Printf("%s================================================================%s\n", blue, noColour)
if tr.err != nil {
errCount++
fmt.Printf("Failure Finished Host %s Test Suite\n%s\n%v\n", host, tr.output, tr.err)
} else {
fmt.Printf("Success Finished Host %s Test Suite\n%s\n", host, tr.output)
}
fmt.Printf("%s================================================================%s\n", blue, noColour)
}
// Set the exit code if there were failures
if errCount > 0 {
fmt.Printf("Failure: %d errors encountered.", errCount)
os.Exit(1)
}
}
// Run tests in archive against host
func testHost(host, archive string) *TestResult {
output, err := e2e_node.RunRemote(archive, host, *cleanup)
return &TestResult{
output: output,
err: err,
host: host,
}
}
// Provision a gce instance using image and run the tests in archive against the instance.
// Delete the instance afterward.
func testImage(image, archive string) *TestResult {
host, err := createInstance(image)
if *cleanup {
defer deleteInstance(image)
}
if err != nil {
return &TestResult{
err: fmt.Errorf("Unable to create gce instance with running docker daemon for image %s. %v", image, err),
}
}
return testHost(host, archive)
}
// Provision a gce instance using image
func createInstance(image string) (string, error) {
name := imageToInstanceName(image)
i := &compute.Instance{
Name: name,
MachineType: machineType(),
NetworkInterfaces: []*compute.NetworkInterface{
{
AccessConfigs: []*compute.AccessConfig{
{
Type: "ONE_TO_ONE_NAT",
Name: "External NAT",
},
}},
},
Disks: []*compute.AttachedDisk{
{
AutoDelete: true,
Boot: true,
Type: "PERSISTENT",
InitializeParams: &compute.AttachedDiskInitializeParams{
SourceImage: sourceImage(image),
},
},
},
}
op, err := computeService.Instances.Insert(*project, *zone, i).Do()
if err != nil {
return "", err
}
if op.Error != nil {
return "", fmt.Errorf("Could not create instance %s: %+v", name, op.Error)
}
instanceRunning := false
for i := 0; i < 30 && !instanceRunning; i++ {
if i > 0 {
time.Sleep(time.Second * 20)
}
var instance *compute.Instance
instance, err = computeService.Instances.Get(*project, *zone, name).Do()
if err != nil {
continue
}
if strings.ToUpper(instance.Status) != "RUNNING" {
err = fmt.Errorf("Instance %s not in state RUNNING, was %s.", name, instance.Status)
continue
}
var output string
output, err = e2e_node.RunSshCommand("ssh", name, "--", "sudo", "docker", "version")
if err != nil {
err = fmt.Errorf("Instance %s not running docker daemon - Command failed: %s", name, output)
continue
}
if !strings.Contains(output, "Server") {
err = fmt.Errorf("Instance %s not running docker daemon - Server not found: %s", name, output)
continue
}
instanceRunning = true
}
return name, err
}
func deleteInstance(image string) {
_, err := computeService.Instances.Delete(*project, *zone, imageToInstanceName(image)).Do()
if err != nil {
glog.Infof("Error deleting instance %s", imageToInstanceName(image))
}
}
func imageToInstanceName(image string) string {
return *instanceNamePrefix + "-" + image
}
func sourceImage(image string) string {
return fmt.Sprintf("projects/%s/global/images/%s", *project, image)
}
func machineType() string {
return fmt.Sprintf("zones/%s/machineTypes/n1-standard-1", *zone)
}
| test/e2e_node/runner/run_e2e.go | 1 | https://github.com/kubernetes/kubernetes/commit/5155df0287bd4e4a35dfc924750622243e574f84 | [
0.0002000838576350361,
0.00017187638150062412,
0.00016270366904791445,
0.00017134411609731615,
0.000006630066309298854
] |
{
"id": 1,
"code_window": [
"\t\tb.WriteString(fmt.Sprintf(\"apiserver output:\\n%s\\n\", e2es.apiServerCombinedOut.String()))\n",
"\t\tb.WriteString(\"-------------------------------------------------------------\\n\")\n",
"\t\tb.WriteString(fmt.Sprintf(\"etcd output:\\n%s\\n\", e2es.etcdCombinedOut.String()))\n",
"\t}\n",
"\tb.WriteString(\"******************************************************\\n\")\n",
"\tglog.V(2).Infof(b.String())\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\tglog.V(0).Infof(b.String())\n"
],
"file_path": "test/e2e_node/e2e_node_suite_test.go",
"type": "replace",
"edit_start_line_idx": 117
} | package lru
import (
"fmt"
"sync"
"github.com/hashicorp/golang-lru/simplelru"
)
const (
// Default2QRecentRatio is the ratio of the 2Q cache dedicated
// to recently added entries that have only been accessed once.
Default2QRecentRatio = 0.25
// Default2QGhostEntries is the default ratio of ghost
// entries kept to track entries recently evicted
Default2QGhostEntries = 0.50
)
// TwoQueueCache is a thread-safe fixed size 2Q cache.
// 2Q is an enhancement over the standard LRU cache
// in that it tracks both frequently and recently used
// entries separately. This avoids a burst in access to new
// entries from evicting frequently used entries. It adds some
// additional tracking overhead to the standard LRU cache, and is
// computationally about 2x the cost, and adds some metadata over
// head. The ARCCache is similar, but does not require setting any
// parameters.
type TwoQueueCache struct {
size int
recentSize int
recent *simplelru.LRU
frequent *simplelru.LRU
recentEvict *simplelru.LRU
lock sync.RWMutex
}
// New2Q creates a new TwoQueueCache using the default
// values for the parameters.
func New2Q(size int) (*TwoQueueCache, error) {
return New2QParams(size, Default2QRecentRatio, Default2QGhostEntries)
}
// New2QParams creates a new TwoQueueCache using the provided
// parameter values.
func New2QParams(size int, recentRatio float64, ghostRatio float64) (*TwoQueueCache, error) {
if size <= 0 {
return nil, fmt.Errorf("invalid size")
}
if recentRatio < 0.0 || recentRatio > 1.0 {
return nil, fmt.Errorf("invalid recent ratio")
}
if ghostRatio < 0.0 || ghostRatio > 1.0 {
return nil, fmt.Errorf("invalid ghost ratio")
}
// Determine the sub-sizes
recentSize := int(float64(size) * recentRatio)
evictSize := int(float64(size) * ghostRatio)
// Allocate the LRUs
recent, err := simplelru.NewLRU(size, nil)
if err != nil {
return nil, err
}
frequent, err := simplelru.NewLRU(size, nil)
if err != nil {
return nil, err
}
recentEvict, err := simplelru.NewLRU(evictSize, nil)
if err != nil {
return nil, err
}
// Initialize the cache
c := &TwoQueueCache{
size: size,
recentSize: recentSize,
recent: recent,
frequent: frequent,
recentEvict: recentEvict,
}
return c, nil
}
func (c *TwoQueueCache) Get(key interface{}) (interface{}, bool) {
c.lock.Lock()
defer c.lock.Unlock()
// Check if this is a frequent value
if val, ok := c.frequent.Get(key); ok {
return val, ok
}
// If the value is contained in recent, then we
// promote it to frequent
if val, ok := c.recent.Peek(key); ok {
c.recent.Remove(key)
c.frequent.Add(key, val)
return val, ok
}
// No hit
return nil, false
}
func (c *TwoQueueCache) Add(key, value interface{}) {
c.lock.Lock()
defer c.lock.Unlock()
// Check if the value is frequently used already,
// and just update the value
if c.frequent.Contains(key) {
c.frequent.Add(key, value)
return
}
// Check if the value is recently used, and promote
// the value into the frequent list
if c.recent.Contains(key) {
c.recent.Remove(key)
c.frequent.Add(key, value)
return
}
// If the value was recently evicted, add it to the
// frequently used list
if c.recentEvict.Contains(key) {
c.ensureSpace(true)
c.recentEvict.Remove(key)
c.frequent.Add(key, value)
return
}
// Add to the recently seen list
c.ensureSpace(false)
c.recent.Add(key, value)
return
}
// ensureSpace is used to ensure we have space in the cache
func (c *TwoQueueCache) ensureSpace(recentEvict bool) {
// If we have space, nothing to do
recentLen := c.recent.Len()
freqLen := c.frequent.Len()
if recentLen+freqLen < c.size {
return
}
// If the recent buffer is larger than
// the target, evict from there
if recentLen > 0 && (recentLen > c.recentSize || (recentLen == c.recentSize && !recentEvict)) {
k, _, _ := c.recent.RemoveOldest()
c.recentEvict.Add(k, nil)
return
}
// Remove from the frequent list otherwise
c.frequent.RemoveOldest()
}
func (c *TwoQueueCache) Len() int {
c.lock.RLock()
defer c.lock.RUnlock()
return c.recent.Len() + c.frequent.Len()
}
func (c *TwoQueueCache) Keys() []interface{} {
c.lock.RLock()
defer c.lock.RUnlock()
k1 := c.frequent.Keys()
k2 := c.recent.Keys()
return append(k1, k2...)
}
func (c *TwoQueueCache) Remove(key interface{}) {
c.lock.Lock()
defer c.lock.Unlock()
if c.frequent.Remove(key) {
return
}
if c.recent.Remove(key) {
return
}
if c.recentEvict.Remove(key) {
return
}
}
func (c *TwoQueueCache) Purge() {
c.lock.Lock()
defer c.lock.Unlock()
c.recent.Purge()
c.frequent.Purge()
c.recentEvict.Purge()
}
func (c *TwoQueueCache) Contains(key interface{}) bool {
c.lock.RLock()
defer c.lock.RUnlock()
return c.frequent.Contains(key) || c.recent.Contains(key)
}
func (c *TwoQueueCache) Peek(key interface{}) (interface{}, bool) {
c.lock.RLock()
defer c.lock.RUnlock()
if val, ok := c.frequent.Peek(key); ok {
return val, ok
}
return c.recent.Peek(key)
}
| Godeps/_workspace/src/github.com/hashicorp/golang-lru/2q.go | 0 | https://github.com/kubernetes/kubernetes/commit/5155df0287bd4e4a35dfc924750622243e574f84 | [
0.00022432372497860342,
0.00017460505478084087,
0.00016313770902343094,
0.00017366519023198634,
0.000011559022823348641
] |
{
"id": 1,
"code_window": [
"\t\tb.WriteString(fmt.Sprintf(\"apiserver output:\\n%s\\n\", e2es.apiServerCombinedOut.String()))\n",
"\t\tb.WriteString(\"-------------------------------------------------------------\\n\")\n",
"\t\tb.WriteString(fmt.Sprintf(\"etcd output:\\n%s\\n\", e2es.etcdCombinedOut.String()))\n",
"\t}\n",
"\tb.WriteString(\"******************************************************\\n\")\n",
"\tglog.V(2).Infof(b.String())\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\tglog.V(0).Infof(b.String())\n"
],
"file_path": "test/e2e_node/e2e_node_suite_test.go",
"type": "replace",
"edit_start_line_idx": 117
} | apiVersion: v1
kind: Service
metadata:
name: redis-slave
labels:
app: redis
role: slave
tier: backend
spec:
ports:
# the port that this service should serve on
- port: 6379
selector:
app: redis
role: slave
tier: backend
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: redis-slave
# these labels can be applied automatically
# from the labels in the pod template if not set
# labels:
# app: redis
# role: slave
# tier: backend
spec:
# this replicas value is default
# modify it according to your case
replicas: 2
# selector can be applied automatically
# from the labels in the pod template if not set
# selector:
# matchLabels:
# app: guestbook
# role: slave
# tier: backend
template:
metadata:
labels:
app: redis
role: slave
tier: backend
spec:
containers:
- name: slave
image: gcr.io/google_samples/gb-redisslave:v1
resources:
requests:
cpu: 100m
memory: 100Mi
env:
- name: GET_HOSTS_FROM
value: dns
# If your cluster config does not include a dns service, then to
# instead access an environment variable to find the master
# service's host, comment out the 'value: dns' line above, and
# uncomment the line below.
# value: env
ports:
- containerPort: 6379
| examples/guestbook/all-in-one/redis-slave.yaml | 0 | https://github.com/kubernetes/kubernetes/commit/5155df0287bd4e4a35dfc924750622243e574f84 | [
0.0001764721528161317,
0.00017415521142538637,
0.00017258324078284204,
0.00017393160669598728,
0.0000012522543784143636
] |
{
"id": 1,
"code_window": [
"\t\tb.WriteString(fmt.Sprintf(\"apiserver output:\\n%s\\n\", e2es.apiServerCombinedOut.String()))\n",
"\t\tb.WriteString(\"-------------------------------------------------------------\\n\")\n",
"\t\tb.WriteString(fmt.Sprintf(\"etcd output:\\n%s\\n\", e2es.etcdCombinedOut.String()))\n",
"\t}\n",
"\tb.WriteString(\"******************************************************\\n\")\n",
"\tglog.V(2).Infof(b.String())\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\tglog.V(0).Infof(b.String())\n"
],
"file_path": "test/e2e_node/e2e_node_suite_test.go",
"type": "replace",
"edit_start_line_idx": 117
} | /*
Copyright 2016 The Kubernetes Authors All rights reserved.
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.
*/
// This package is generated by client-gen with the default arguments.
// This package has the automatically generated typed clients.
package unversioned
| pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/doc.go | 0 | https://github.com/kubernetes/kubernetes/commit/5155df0287bd4e4a35dfc924750622243e574f84 | [
0.00017733866116032004,
0.00017575849778950214,
0.000174066168256104,
0.00017587063484825194,
0.000001338341007794952
] |
{
"id": 2,
"code_window": [
"\t\tfor _, host := range strings.Split(*hosts, \",\") {\n",
"\t\t\tfmt.Printf(\"Initializing e2e tests using host %s.\\n\", host)\n",
"\t\t\trunning++\n",
"\t\t\tgo func(host string) {\n",
"\t\t\t\tresults <- testHost(host, archive)\n",
"\t\t\t}(host)\n",
"\t\t}\n",
"\t}\n",
"\n",
"\t// Wait for all tests to complete and emit the results\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tresults <- testHost(host, archive, *cleanup)\n"
],
"file_path": "test/e2e_node/runner/run_e2e.go",
"type": "replace",
"edit_start_line_idx": 124
} | /*
Copyright 2016 The Kubernetes Authors All rights reserved.
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.
*/
// To run the e2e tests against one or more hosts on gce:
// $ godep go run run_e2e.go --logtostderr --v 2 --ssh-env gce --hosts <comma separated hosts>
// To run the e2e tests against one or more images on gce and provision them:
// $ godep go run run_e2e.go --logtostderr --v 2 --project <project> --zone <zone> --ssh-env gce --images <comma separated images>
package main
import (
"flag"
"fmt"
"math/rand"
"net/http"
"os"
"strings"
"time"
"k8s.io/kubernetes/test/e2e_node"
"github.com/golang/glog"
"github.com/pborman/uuid"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/compute/v1"
)
var instanceNamePrefix = flag.String("instance-name-prefix", "", "prefix for instance names")
var zone = flag.String("zone", "", "gce zone the hosts live in")
var project = flag.String("project", "", "gce project the hosts live in")
var images = flag.String("images", "", "images to test")
var hosts = flag.String("hosts", "", "hosts to test")
var cleanup = flag.Bool("cleanup", true, "If true remove files from remote hosts and delete temporary instances")
var buildOnly = flag.Bool("build-only", false, "If true, build e2e_node_test.tar.gz and exit.")
var computeService *compute.Service
type TestResult struct {
output string
err error
host string
}
func main() {
flag.Parse()
rand.Seed(time.Now().UTC().UnixNano())
if *buildOnly {
// Build the archive and exit
e2e_node.CreateTestArchive()
return
}
if *hosts == "" && *images == "" {
glog.Fatalf("Must specify one of --images or --hosts flag.")
}
if *images != "" && *zone == "" {
glog.Fatal("Must specify --zone flag")
}
if *images != "" && *project == "" {
glog.Fatal("Must specify --project flag")
}
if *instanceNamePrefix == "" {
*instanceNamePrefix = "tmp-node-e2e-" + uuid.NewUUID().String()[:8]
}
// Setup coloring
stat, _ := os.Stdout.Stat()
useColor := (stat.Mode() & os.ModeCharDevice) != 0
blue := ""
noColour := ""
if useColor {
blue = "\033[0;34m"
noColour = "\033[0m"
}
archive := e2e_node.CreateTestArchive()
defer os.Remove(archive)
results := make(chan *TestResult)
running := 0
if *images != "" {
// Setup the gce client for provisioning instances
// Getting credentials on gce jenkins is flaky, so try a couple times
var err error
for i := 0; i < 10; i++ {
var client *http.Client
client, err = google.DefaultClient(oauth2.NoContext, compute.ComputeScope)
if err != nil {
continue
}
computeService, err = compute.New(client)
if err != nil {
continue
}
time.Sleep(time.Second * 6)
}
if err != nil {
glog.Fatalf("Unable to create gcloud compute service using defaults. Make sure you are authenticated. %v", err)
}
for _, image := range strings.Split(*images, ",") {
running++
fmt.Printf("Initializing e2e tests using image %s.\n", image)
go func(image string) { results <- testImage(image, archive) }(image)
}
}
if *hosts != "" {
for _, host := range strings.Split(*hosts, ",") {
fmt.Printf("Initializing e2e tests using host %s.\n", host)
running++
go func(host string) {
results <- testHost(host, archive)
}(host)
}
}
// Wait for all tests to complete and emit the results
errCount := 0
for i := 0; i < running; i++ {
tr := <-results
host := tr.host
fmt.Printf("%s================================================================%s\n", blue, noColour)
if tr.err != nil {
errCount++
fmt.Printf("Failure Finished Host %s Test Suite\n%s\n%v\n", host, tr.output, tr.err)
} else {
fmt.Printf("Success Finished Host %s Test Suite\n%s\n", host, tr.output)
}
fmt.Printf("%s================================================================%s\n", blue, noColour)
}
// Set the exit code if there were failures
if errCount > 0 {
fmt.Printf("Failure: %d errors encountered.", errCount)
os.Exit(1)
}
}
// Run tests in archive against host
func testHost(host, archive string) *TestResult {
output, err := e2e_node.RunRemote(archive, host, *cleanup)
return &TestResult{
output: output,
err: err,
host: host,
}
}
// Provision a gce instance using image and run the tests in archive against the instance.
// Delete the instance afterward.
func testImage(image, archive string) *TestResult {
host, err := createInstance(image)
if *cleanup {
defer deleteInstance(image)
}
if err != nil {
return &TestResult{
err: fmt.Errorf("Unable to create gce instance with running docker daemon for image %s. %v", image, err),
}
}
return testHost(host, archive)
}
// Provision a gce instance using image
func createInstance(image string) (string, error) {
name := imageToInstanceName(image)
i := &compute.Instance{
Name: name,
MachineType: machineType(),
NetworkInterfaces: []*compute.NetworkInterface{
{
AccessConfigs: []*compute.AccessConfig{
{
Type: "ONE_TO_ONE_NAT",
Name: "External NAT",
},
}},
},
Disks: []*compute.AttachedDisk{
{
AutoDelete: true,
Boot: true,
Type: "PERSISTENT",
InitializeParams: &compute.AttachedDiskInitializeParams{
SourceImage: sourceImage(image),
},
},
},
}
op, err := computeService.Instances.Insert(*project, *zone, i).Do()
if err != nil {
return "", err
}
if op.Error != nil {
return "", fmt.Errorf("Could not create instance %s: %+v", name, op.Error)
}
instanceRunning := false
for i := 0; i < 30 && !instanceRunning; i++ {
if i > 0 {
time.Sleep(time.Second * 20)
}
var instance *compute.Instance
instance, err = computeService.Instances.Get(*project, *zone, name).Do()
if err != nil {
continue
}
if strings.ToUpper(instance.Status) != "RUNNING" {
err = fmt.Errorf("Instance %s not in state RUNNING, was %s.", name, instance.Status)
continue
}
var output string
output, err = e2e_node.RunSshCommand("ssh", name, "--", "sudo", "docker", "version")
if err != nil {
err = fmt.Errorf("Instance %s not running docker daemon - Command failed: %s", name, output)
continue
}
if !strings.Contains(output, "Server") {
err = fmt.Errorf("Instance %s not running docker daemon - Server not found: %s", name, output)
continue
}
instanceRunning = true
}
return name, err
}
func deleteInstance(image string) {
_, err := computeService.Instances.Delete(*project, *zone, imageToInstanceName(image)).Do()
if err != nil {
glog.Infof("Error deleting instance %s", imageToInstanceName(image))
}
}
func imageToInstanceName(image string) string {
return *instanceNamePrefix + "-" + image
}
func sourceImage(image string) string {
return fmt.Sprintf("projects/%s/global/images/%s", *project, image)
}
func machineType() string {
return fmt.Sprintf("zones/%s/machineTypes/n1-standard-1", *zone)
}
| test/e2e_node/runner/run_e2e.go | 1 | https://github.com/kubernetes/kubernetes/commit/5155df0287bd4e4a35dfc924750622243e574f84 | [
0.9983476400375366,
0.09975747764110565,
0.0001621386909391731,
0.0001742304884828627,
0.27466273307800293
] |
{
"id": 2,
"code_window": [
"\t\tfor _, host := range strings.Split(*hosts, \",\") {\n",
"\t\t\tfmt.Printf(\"Initializing e2e tests using host %s.\\n\", host)\n",
"\t\t\trunning++\n",
"\t\t\tgo func(host string) {\n",
"\t\t\t\tresults <- testHost(host, archive)\n",
"\t\t\t}(host)\n",
"\t\t}\n",
"\t}\n",
"\n",
"\t// Wait for all tests to complete and emit the results\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tresults <- testHost(host, archive, *cleanup)\n"
],
"file_path": "test/e2e_node/runner/run_e2e.go",
"type": "replace",
"edit_start_line_idx": 124
} | // Copyright 2015 CoreOS, Inc.
//
// 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 capnslog
import (
"fmt"
"os"
)
type PackageLogger struct {
pkg string
level LogLevel
}
const calldepth = 3
func (p *PackageLogger) internalLog(depth int, inLevel LogLevel, entries ...interface{}) {
if inLevel != CRITICAL && p.level < inLevel {
return
}
logger.Lock()
defer logger.Unlock()
if logger.formatter != nil {
logger.formatter.Format(p.pkg, inLevel, depth+1, entries...)
}
}
func (p *PackageLogger) LevelAt(l LogLevel) bool {
return p.level >= l
}
// Log a formatted string at any level between ERROR and TRACE
func (p *PackageLogger) Logf(l LogLevel, format string, args ...interface{}) {
p.internalLog(calldepth, l, fmt.Sprintf(format, args...))
}
// Log a message at any level between ERROR and TRACE
func (p *PackageLogger) Log(l LogLevel, args ...interface{}) {
p.internalLog(calldepth, l, fmt.Sprint(args...))
}
// log stdlib compatibility
func (p *PackageLogger) Println(args ...interface{}) {
p.internalLog(calldepth, INFO, fmt.Sprintln(args...))
}
func (p *PackageLogger) Printf(format string, args ...interface{}) {
p.internalLog(calldepth, INFO, fmt.Sprintf(format, args...))
}
func (p *PackageLogger) Print(args ...interface{}) {
p.internalLog(calldepth, INFO, fmt.Sprint(args...))
}
// Panic and fatal
func (p *PackageLogger) Panicf(format string, args ...interface{}) {
s := fmt.Sprintf(format, args...)
p.internalLog(calldepth, CRITICAL, s)
panic(s)
}
func (p *PackageLogger) Panic(args ...interface{}) {
s := fmt.Sprint(args...)
p.internalLog(calldepth, CRITICAL, s)
panic(s)
}
func (p *PackageLogger) Fatalf(format string, args ...interface{}) {
s := fmt.Sprintf(format, args...)
p.internalLog(calldepth, CRITICAL, s)
os.Exit(1)
}
func (p *PackageLogger) Fatal(args ...interface{}) {
s := fmt.Sprint(args...)
p.internalLog(calldepth, CRITICAL, s)
os.Exit(1)
}
// Error Functions
func (p *PackageLogger) Errorf(format string, args ...interface{}) {
p.internalLog(calldepth, ERROR, fmt.Sprintf(format, args...))
}
func (p *PackageLogger) Error(entries ...interface{}) {
p.internalLog(calldepth, ERROR, entries...)
}
// Warning Functions
func (p *PackageLogger) Warningf(format string, args ...interface{}) {
p.internalLog(calldepth, WARNING, fmt.Sprintf(format, args...))
}
func (p *PackageLogger) Warning(entries ...interface{}) {
p.internalLog(calldepth, WARNING, entries...)
}
// Notice Functions
func (p *PackageLogger) Noticef(format string, args ...interface{}) {
p.internalLog(calldepth, NOTICE, fmt.Sprintf(format, args...))
}
func (p *PackageLogger) Notice(entries ...interface{}) {
p.internalLog(calldepth, NOTICE, entries...)
}
// Info Functions
func (p *PackageLogger) Infof(format string, args ...interface{}) {
p.internalLog(calldepth, INFO, fmt.Sprintf(format, args...))
}
func (p *PackageLogger) Info(entries ...interface{}) {
p.internalLog(calldepth, INFO, entries...)
}
// Debug Functions
func (p *PackageLogger) Debugf(format string, args ...interface{}) {
p.internalLog(calldepth, DEBUG, fmt.Sprintf(format, args...))
}
func (p *PackageLogger) Debug(entries ...interface{}) {
p.internalLog(calldepth, DEBUG, entries...)
}
// Trace Functions
func (p *PackageLogger) Tracef(format string, args ...interface{}) {
p.internalLog(calldepth, TRACE, fmt.Sprintf(format, args...))
}
func (p *PackageLogger) Trace(entries ...interface{}) {
p.internalLog(calldepth, TRACE, entries...)
}
func (p *PackageLogger) Flush() {
logger.Lock()
defer logger.Unlock()
logger.formatter.Flush()
}
| Godeps/_workspace/src/github.com/coreos/pkg/capnslog/pkg_logger.go | 0 | https://github.com/kubernetes/kubernetes/commit/5155df0287bd4e4a35dfc924750622243e574f84 | [
0.0008048275485634804,
0.0002982239820994437,
0.00016262067947536707,
0.00017552022472955287,
0.00020209321519359946
] |
{
"id": 2,
"code_window": [
"\t\tfor _, host := range strings.Split(*hosts, \",\") {\n",
"\t\t\tfmt.Printf(\"Initializing e2e tests using host %s.\\n\", host)\n",
"\t\t\trunning++\n",
"\t\t\tgo func(host string) {\n",
"\t\t\t\tresults <- testHost(host, archive)\n",
"\t\t\t}(host)\n",
"\t\t}\n",
"\t}\n",
"\n",
"\t// Wait for all tests to complete and emit the results\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tresults <- testHost(host, archive, *cleanup)\n"
],
"file_path": "test/e2e_node/runner/run_e2e.go",
"type": "replace",
"edit_start_line_idx": 124
} | /*
Copyright 2014 The Kubernetes Authors All rights reserved.
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 (
"k8s.io/kubernetes/pkg/client/restclient"
"k8s.io/kubernetes/pkg/client/testing/core"
)
func (c *FakeServices) ProxyGet(scheme, name, port, path string, params map[string]string) restclient.ResponseWrapper {
return c.Fake.InvokesProxy(core.NewProxyGetAction("services", c.ns, scheme, name, port, path, params))
}
| pkg/client/typed/generated/core/v1/fake/fake_service_expansion.go | 0 | https://github.com/kubernetes/kubernetes/commit/5155df0287bd4e4a35dfc924750622243e574f84 | [
0.00017945609579328448,
0.00017715692229103297,
0.0001738208666210994,
0.0001781937899067998,
0.00000241457792071742
] |
{
"id": 2,
"code_window": [
"\t\tfor _, host := range strings.Split(*hosts, \",\") {\n",
"\t\t\tfmt.Printf(\"Initializing e2e tests using host %s.\\n\", host)\n",
"\t\t\trunning++\n",
"\t\t\tgo func(host string) {\n",
"\t\t\t\tresults <- testHost(host, archive)\n",
"\t\t\t}(host)\n",
"\t\t}\n",
"\t}\n",
"\n",
"\t// Wait for all tests to complete and emit the results\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tresults <- testHost(host, archive, *cleanup)\n"
],
"file_path": "test/e2e_node/runner/run_e2e.go",
"type": "replace",
"edit_start_line_idx": 124
} | <!-- BEGIN MUNGE: UNVERSIONED_WARNING -->
<!-- BEGIN STRIP_FOR_RELEASE -->
<img src="http://kubernetes.io/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/img/warning.png" alt="WARNING"
width="25" height="25">
<h2>PLEASE NOTE: This document applies to the HEAD of the source tree</h2>
If you are using a released version of Kubernetes, you should
refer to the docs that go with that version.
<!-- TAG RELEASE_LINK, added by the munger automatically -->
<strong>
The latest release of this document can be found
[here](http://releases.k8s.io/release-1.2/docs/getting-started-guides/mesos-docker.md).
Documentation for other releases can be found at
[releases.k8s.io](http://releases.k8s.io).
</strong>
--
<!-- END STRIP_FOR_RELEASE -->
<!-- END MUNGE: UNVERSIONED_WARNING -->
This file has moved to: http://kubernetes.github.io/docs/getting-started-guides/mesos-docker/
<!-- BEGIN MUNGE: GENERATED_ANALYTICS -->
[]()
<!-- END MUNGE: GENERATED_ANALYTICS -->
| docs/getting-started-guides/mesos-docker.md | 0 | https://github.com/kubernetes/kubernetes/commit/5155df0287bd4e4a35dfc924750622243e574f84 | [
0.0001750436786096543,
0.00017181129078380764,
0.00016664211580064148,
0.00017339510668534786,
0.000003047712425541249
] |
{
"id": 3,
"code_window": [
"\t\tos.Exit(1)\n",
"\t}\n",
"}\n",
"\n",
"// Run tests in archive against host\n",
"func testHost(host, archive string) *TestResult {\n",
"\toutput, err := e2e_node.RunRemote(archive, host, *cleanup)\n",
"\treturn &TestResult{\n",
"\t\toutput: output,\n",
"\t\terr: err,\n",
"\t\thost: host,\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"func testHost(host, archive string, deleteFiles bool) *TestResult {\n",
"\toutput, err := e2e_node.RunRemote(archive, host, deleteFiles)\n"
],
"file_path": "test/e2e_node/runner/run_e2e.go",
"type": "replace",
"edit_start_line_idx": 152
} | /*
Copyright 2016 The Kubernetes Authors All rights reserved.
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.
*/
// To run the e2e tests against one or more hosts on gce:
// $ godep go run run_e2e.go --logtostderr --v 2 --ssh-env gce --hosts <comma separated hosts>
// To run the e2e tests against one or more images on gce and provision them:
// $ godep go run run_e2e.go --logtostderr --v 2 --project <project> --zone <zone> --ssh-env gce --images <comma separated images>
package main
import (
"flag"
"fmt"
"math/rand"
"net/http"
"os"
"strings"
"time"
"k8s.io/kubernetes/test/e2e_node"
"github.com/golang/glog"
"github.com/pborman/uuid"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/compute/v1"
)
var instanceNamePrefix = flag.String("instance-name-prefix", "", "prefix for instance names")
var zone = flag.String("zone", "", "gce zone the hosts live in")
var project = flag.String("project", "", "gce project the hosts live in")
var images = flag.String("images", "", "images to test")
var hosts = flag.String("hosts", "", "hosts to test")
var cleanup = flag.Bool("cleanup", true, "If true remove files from remote hosts and delete temporary instances")
var buildOnly = flag.Bool("build-only", false, "If true, build e2e_node_test.tar.gz and exit.")
var computeService *compute.Service
type TestResult struct {
output string
err error
host string
}
func main() {
flag.Parse()
rand.Seed(time.Now().UTC().UnixNano())
if *buildOnly {
// Build the archive and exit
e2e_node.CreateTestArchive()
return
}
if *hosts == "" && *images == "" {
glog.Fatalf("Must specify one of --images or --hosts flag.")
}
if *images != "" && *zone == "" {
glog.Fatal("Must specify --zone flag")
}
if *images != "" && *project == "" {
glog.Fatal("Must specify --project flag")
}
if *instanceNamePrefix == "" {
*instanceNamePrefix = "tmp-node-e2e-" + uuid.NewUUID().String()[:8]
}
// Setup coloring
stat, _ := os.Stdout.Stat()
useColor := (stat.Mode() & os.ModeCharDevice) != 0
blue := ""
noColour := ""
if useColor {
blue = "\033[0;34m"
noColour = "\033[0m"
}
archive := e2e_node.CreateTestArchive()
defer os.Remove(archive)
results := make(chan *TestResult)
running := 0
if *images != "" {
// Setup the gce client for provisioning instances
// Getting credentials on gce jenkins is flaky, so try a couple times
var err error
for i := 0; i < 10; i++ {
var client *http.Client
client, err = google.DefaultClient(oauth2.NoContext, compute.ComputeScope)
if err != nil {
continue
}
computeService, err = compute.New(client)
if err != nil {
continue
}
time.Sleep(time.Second * 6)
}
if err != nil {
glog.Fatalf("Unable to create gcloud compute service using defaults. Make sure you are authenticated. %v", err)
}
for _, image := range strings.Split(*images, ",") {
running++
fmt.Printf("Initializing e2e tests using image %s.\n", image)
go func(image string) { results <- testImage(image, archive) }(image)
}
}
if *hosts != "" {
for _, host := range strings.Split(*hosts, ",") {
fmt.Printf("Initializing e2e tests using host %s.\n", host)
running++
go func(host string) {
results <- testHost(host, archive)
}(host)
}
}
// Wait for all tests to complete and emit the results
errCount := 0
for i := 0; i < running; i++ {
tr := <-results
host := tr.host
fmt.Printf("%s================================================================%s\n", blue, noColour)
if tr.err != nil {
errCount++
fmt.Printf("Failure Finished Host %s Test Suite\n%s\n%v\n", host, tr.output, tr.err)
} else {
fmt.Printf("Success Finished Host %s Test Suite\n%s\n", host, tr.output)
}
fmt.Printf("%s================================================================%s\n", blue, noColour)
}
// Set the exit code if there were failures
if errCount > 0 {
fmt.Printf("Failure: %d errors encountered.", errCount)
os.Exit(1)
}
}
// Run tests in archive against host
func testHost(host, archive string) *TestResult {
output, err := e2e_node.RunRemote(archive, host, *cleanup)
return &TestResult{
output: output,
err: err,
host: host,
}
}
// Provision a gce instance using image and run the tests in archive against the instance.
// Delete the instance afterward.
func testImage(image, archive string) *TestResult {
host, err := createInstance(image)
if *cleanup {
defer deleteInstance(image)
}
if err != nil {
return &TestResult{
err: fmt.Errorf("Unable to create gce instance with running docker daemon for image %s. %v", image, err),
}
}
return testHost(host, archive)
}
// Provision a gce instance using image
func createInstance(image string) (string, error) {
name := imageToInstanceName(image)
i := &compute.Instance{
Name: name,
MachineType: machineType(),
NetworkInterfaces: []*compute.NetworkInterface{
{
AccessConfigs: []*compute.AccessConfig{
{
Type: "ONE_TO_ONE_NAT",
Name: "External NAT",
},
}},
},
Disks: []*compute.AttachedDisk{
{
AutoDelete: true,
Boot: true,
Type: "PERSISTENT",
InitializeParams: &compute.AttachedDiskInitializeParams{
SourceImage: sourceImage(image),
},
},
},
}
op, err := computeService.Instances.Insert(*project, *zone, i).Do()
if err != nil {
return "", err
}
if op.Error != nil {
return "", fmt.Errorf("Could not create instance %s: %+v", name, op.Error)
}
instanceRunning := false
for i := 0; i < 30 && !instanceRunning; i++ {
if i > 0 {
time.Sleep(time.Second * 20)
}
var instance *compute.Instance
instance, err = computeService.Instances.Get(*project, *zone, name).Do()
if err != nil {
continue
}
if strings.ToUpper(instance.Status) != "RUNNING" {
err = fmt.Errorf("Instance %s not in state RUNNING, was %s.", name, instance.Status)
continue
}
var output string
output, err = e2e_node.RunSshCommand("ssh", name, "--", "sudo", "docker", "version")
if err != nil {
err = fmt.Errorf("Instance %s not running docker daemon - Command failed: %s", name, output)
continue
}
if !strings.Contains(output, "Server") {
err = fmt.Errorf("Instance %s not running docker daemon - Server not found: %s", name, output)
continue
}
instanceRunning = true
}
return name, err
}
func deleteInstance(image string) {
_, err := computeService.Instances.Delete(*project, *zone, imageToInstanceName(image)).Do()
if err != nil {
glog.Infof("Error deleting instance %s", imageToInstanceName(image))
}
}
func imageToInstanceName(image string) string {
return *instanceNamePrefix + "-" + image
}
func sourceImage(image string) string {
return fmt.Sprintf("projects/%s/global/images/%s", *project, image)
}
func machineType() string {
return fmt.Sprintf("zones/%s/machineTypes/n1-standard-1", *zone)
}
| test/e2e_node/runner/run_e2e.go | 1 | https://github.com/kubernetes/kubernetes/commit/5155df0287bd4e4a35dfc924750622243e574f84 | [
0.9989826083183289,
0.14331164956092834,
0.00016474137373734266,
0.00017649537767283618,
0.3339807093143463
] |
{
"id": 3,
"code_window": [
"\t\tos.Exit(1)\n",
"\t}\n",
"}\n",
"\n",
"// Run tests in archive against host\n",
"func testHost(host, archive string) *TestResult {\n",
"\toutput, err := e2e_node.RunRemote(archive, host, *cleanup)\n",
"\treturn &TestResult{\n",
"\t\toutput: output,\n",
"\t\terr: err,\n",
"\t\thost: host,\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"func testHost(host, archive string, deleteFiles bool) *TestResult {\n",
"\toutput, err := e2e_node.RunRemote(archive, host, deleteFiles)\n"
],
"file_path": "test/e2e_node/runner/run_e2e.go",
"type": "replace",
"edit_start_line_idx": 152
} | // Copyright 2013 The Prometheus 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 model
import (
"encoding/json"
"fmt"
"regexp"
"sort"
"strings"
)
const (
// AlertNameLabel is the name of the label containing the an alert's name.
AlertNameLabel = "alertname"
// ExportedLabelPrefix is the prefix to prepend to the label names present in
// exported metrics if a label of the same name is added by the server.
ExportedLabelPrefix = "exported_"
// MetricNameLabel is the label name indicating the metric name of a
// timeseries.
MetricNameLabel = "__name__"
// SchemeLabel is the name of the label that holds the scheme on which to
// scrape a target.
SchemeLabel = "__scheme__"
// AddressLabel is the name of the label that holds the address of
// a scrape target.
AddressLabel = "__address__"
// MetricsPathLabel is the name of the label that holds the path on which to
// scrape a target.
MetricsPathLabel = "__metrics_path__"
// ReservedLabelPrefix is a prefix which is not legal in user-supplied
// label names.
ReservedLabelPrefix = "__"
// MetaLabelPrefix is a prefix for labels that provide meta information.
// Labels with this prefix are used for intermediate label processing and
// will not be attached to time series.
MetaLabelPrefix = "__meta_"
// TmpLabelPrefix is a prefix for temporary labels as part of relabelling.
// Labels with this prefix are used for intermediate label processing and
// will not be attached to time series. This is reserved for use in
// Prometheus configuration files by users.
TmpLabelPrefix = "__tmp_"
// ParamLabelPrefix is a prefix for labels that provide URL parameters
// used to scrape a target.
ParamLabelPrefix = "__param_"
// JobLabel is the label name indicating the job from which a timeseries
// was scraped.
JobLabel = "job"
// InstanceLabel is the label name used for the instance label.
InstanceLabel = "instance"
// BucketLabel is used for the label that defines the upper bound of a
// bucket of a histogram ("le" -> "less or equal").
BucketLabel = "le"
// QuantileLabel is used for the label that defines the quantile in a
// summary.
QuantileLabel = "quantile"
)
// LabelNameRE is a regular expression matching valid label names.
var LabelNameRE = regexp.MustCompile("^[a-zA-Z_][a-zA-Z0-9_]*$")
// A LabelName is a key for a LabelSet or Metric. It has a value associated
// therewith.
type LabelName string
// UnmarshalYAML implements the yaml.Unmarshaler interface.
func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error {
var s string
if err := unmarshal(&s); err != nil {
return err
}
if !LabelNameRE.MatchString(s) {
return fmt.Errorf("%q is not a valid label name", s)
}
*ln = LabelName(s)
return nil
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (ln *LabelName) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
if !LabelNameRE.MatchString(s) {
return fmt.Errorf("%q is not a valid label name", s)
}
*ln = LabelName(s)
return nil
}
// LabelNames is a sortable LabelName slice. In implements sort.Interface.
type LabelNames []LabelName
func (l LabelNames) Len() int {
return len(l)
}
func (l LabelNames) Less(i, j int) bool {
return l[i] < l[j]
}
func (l LabelNames) Swap(i, j int) {
l[i], l[j] = l[j], l[i]
}
func (l LabelNames) String() string {
labelStrings := make([]string, 0, len(l))
for _, label := range l {
labelStrings = append(labelStrings, string(label))
}
return strings.Join(labelStrings, ", ")
}
// A LabelValue is an associated value for a LabelName.
type LabelValue string
// LabelValues is a sortable LabelValue slice. It implements sort.Interface.
type LabelValues []LabelValue
func (l LabelValues) Len() int {
return len(l)
}
func (l LabelValues) Less(i, j int) bool {
return sort.StringsAreSorted([]string{string(l[i]), string(l[j])})
}
func (l LabelValues) Swap(i, j int) {
l[i], l[j] = l[j], l[i]
}
// LabelPair pairs a name with a value.
type LabelPair struct {
Name LabelName
Value LabelValue
}
// LabelPairs is a sortable slice of LabelPair pointers. It implements
// sort.Interface.
type LabelPairs []*LabelPair
func (l LabelPairs) Len() int {
return len(l)
}
func (l LabelPairs) Less(i, j int) bool {
switch {
case l[i].Name > l[j].Name:
return false
case l[i].Name < l[j].Name:
return true
case l[i].Value > l[j].Value:
return false
case l[i].Value < l[j].Value:
return true
default:
return false
}
}
func (l LabelPairs) Swap(i, j int) {
l[i], l[j] = l[j], l[i]
}
| Godeps/_workspace/src/github.com/prometheus/common/model/labels.go | 0 | https://github.com/kubernetes/kubernetes/commit/5155df0287bd4e4a35dfc924750622243e574f84 | [
0.00018021468713413924,
0.0001739542931318283,
0.00016746883920859545,
0.00017390507855452597,
0.0000030895146210241364
] |
{
"id": 3,
"code_window": [
"\t\tos.Exit(1)\n",
"\t}\n",
"}\n",
"\n",
"// Run tests in archive against host\n",
"func testHost(host, archive string) *TestResult {\n",
"\toutput, err := e2e_node.RunRemote(archive, host, *cleanup)\n",
"\treturn &TestResult{\n",
"\t\toutput: output,\n",
"\t\terr: err,\n",
"\t\thost: host,\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"func testHost(host, archive string, deleteFiles bool) *TestResult {\n",
"\toutput, err := e2e_node.RunRemote(archive, host, deleteFiles)\n"
],
"file_path": "test/e2e_node/runner/run_e2e.go",
"type": "replace",
"edit_start_line_idx": 152
} | // Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !go1.4
package constant
import (
"math"
"math/big"
)
func ratToFloat32(x *big.Rat) (float32, bool) {
// Before 1.4, there's no Rat.Float32.
// Emulate it, albeit at the cost of
// imprecision in corner cases.
x64, exact := x.Float64()
x32 := float32(x64)
if math.IsInf(float64(x32), 0) {
exact = false
}
return x32, exact
}
| third_party/golang/go/constant/go13.go | 0 | https://github.com/kubernetes/kubernetes/commit/5155df0287bd4e4a35dfc924750622243e574f84 | [
0.0001800506579456851,
0.00017675560957286507,
0.00017449524602852762,
0.00017572093929629773,
0.0000023830743884900585
] |
{
"id": 3,
"code_window": [
"\t\tos.Exit(1)\n",
"\t}\n",
"}\n",
"\n",
"// Run tests in archive against host\n",
"func testHost(host, archive string) *TestResult {\n",
"\toutput, err := e2e_node.RunRemote(archive, host, *cleanup)\n",
"\treturn &TestResult{\n",
"\t\toutput: output,\n",
"\t\terr: err,\n",
"\t\thost: host,\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"func testHost(host, archive string, deleteFiles bool) *TestResult {\n",
"\toutput, err := e2e_node.RunRemote(archive, host, deleteFiles)\n"
],
"file_path": "test/e2e_node/runner/run_e2e.go",
"type": "replace",
"edit_start_line_idx": 152
} | /*
Copyright 2016 The Kubernetes Authors All rights reserved.
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.
*/
// This file is generated by client-gen with the default arguments.
package unversioned
import (
api "k8s.io/kubernetes/pkg/api"
extensions "k8s.io/kubernetes/pkg/apis/extensions"
watch "k8s.io/kubernetes/pkg/watch"
)
// HorizontalPodAutoscalersGetter has a method to return a HorizontalPodAutoscalerInterface.
// A group's client should implement this interface.
type HorizontalPodAutoscalersGetter interface {
HorizontalPodAutoscalers(namespace string) HorizontalPodAutoscalerInterface
}
// HorizontalPodAutoscalerInterface has methods to work with HorizontalPodAutoscaler resources.
type HorizontalPodAutoscalerInterface interface {
Create(*extensions.HorizontalPodAutoscaler) (*extensions.HorizontalPodAutoscaler, error)
Update(*extensions.HorizontalPodAutoscaler) (*extensions.HorizontalPodAutoscaler, error)
UpdateStatus(*extensions.HorizontalPodAutoscaler) (*extensions.HorizontalPodAutoscaler, error)
Delete(name string, options *api.DeleteOptions) error
DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error
Get(name string) (*extensions.HorizontalPodAutoscaler, error)
List(opts api.ListOptions) (*extensions.HorizontalPodAutoscalerList, error)
Watch(opts api.ListOptions) (watch.Interface, error)
HorizontalPodAutoscalerExpansion
}
// horizontalPodAutoscalers implements HorizontalPodAutoscalerInterface
type horizontalPodAutoscalers struct {
client *ExtensionsClient
ns string
}
// newHorizontalPodAutoscalers returns a HorizontalPodAutoscalers
func newHorizontalPodAutoscalers(c *ExtensionsClient, namespace string) *horizontalPodAutoscalers {
return &horizontalPodAutoscalers{
client: c,
ns: namespace,
}
}
// Create takes the representation of a horizontalPodAutoscaler and creates it. Returns the server's representation of the horizontalPodAutoscaler, and an error, if there is any.
func (c *horizontalPodAutoscalers) Create(horizontalPodAutoscaler *extensions.HorizontalPodAutoscaler) (result *extensions.HorizontalPodAutoscaler, err error) {
result = &extensions.HorizontalPodAutoscaler{}
err = c.client.Post().
Namespace(c.ns).
Resource("horizontalpodautoscalers").
Body(horizontalPodAutoscaler).
Do().
Into(result)
return
}
// Update takes the representation of a horizontalPodAutoscaler and updates it. Returns the server's representation of the horizontalPodAutoscaler, and an error, if there is any.
func (c *horizontalPodAutoscalers) Update(horizontalPodAutoscaler *extensions.HorizontalPodAutoscaler) (result *extensions.HorizontalPodAutoscaler, err error) {
result = &extensions.HorizontalPodAutoscaler{}
err = c.client.Put().
Namespace(c.ns).
Resource("horizontalpodautoscalers").
Name(horizontalPodAutoscaler.Name).
Body(horizontalPodAutoscaler).
Do().
Into(result)
return
}
func (c *horizontalPodAutoscalers) UpdateStatus(horizontalPodAutoscaler *extensions.HorizontalPodAutoscaler) (result *extensions.HorizontalPodAutoscaler, err error) {
result = &extensions.HorizontalPodAutoscaler{}
err = c.client.Put().
Namespace(c.ns).
Resource("horizontalpodautoscalers").
Name(horizontalPodAutoscaler.Name).
SubResource("status").
Body(horizontalPodAutoscaler).
Do().
Into(result)
return
}
// Delete takes name of the horizontalPodAutoscaler and deletes it. Returns an error if one occurs.
func (c *horizontalPodAutoscalers) Delete(name string, options *api.DeleteOptions) error {
return c.client.Delete().
Namespace(c.ns).
Resource("horizontalpodautoscalers").
Name(name).
Body(options).
Do().
Error()
}
// DeleteCollection deletes a collection of objects.
func (c *horizontalPodAutoscalers) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error {
return c.client.Delete().
Namespace(c.ns).
Resource("horizontalpodautoscalers").
VersionedParams(&listOptions, api.ParameterCodec).
Body(options).
Do().
Error()
}
// Get takes name of the horizontalPodAutoscaler, and returns the corresponding horizontalPodAutoscaler object, and an error if there is any.
func (c *horizontalPodAutoscalers) Get(name string) (result *extensions.HorizontalPodAutoscaler, err error) {
result = &extensions.HorizontalPodAutoscaler{}
err = c.client.Get().
Namespace(c.ns).
Resource("horizontalpodautoscalers").
Name(name).
Do().
Into(result)
return
}
// List takes label and field selectors, and returns the list of HorizontalPodAutoscalers that match those selectors.
func (c *horizontalPodAutoscalers) List(opts api.ListOptions) (result *extensions.HorizontalPodAutoscalerList, err error) {
result = &extensions.HorizontalPodAutoscalerList{}
err = c.client.Get().
Namespace(c.ns).
Resource("horizontalpodautoscalers").
VersionedParams(&opts, api.ParameterCodec).
Do().
Into(result)
return
}
// Watch returns a watch.Interface that watches the requested horizontalPodAutoscalers.
func (c *horizontalPodAutoscalers) Watch(opts api.ListOptions) (watch.Interface, error) {
return c.client.Get().
Prefix("watch").
Namespace(c.ns).
Resource("horizontalpodautoscalers").
VersionedParams(&opts, api.ParameterCodec).
Watch()
}
| pkg/client/typed/generated/extensions/unversioned/horizontalpodautoscaler.go | 0 | https://github.com/kubernetes/kubernetes/commit/5155df0287bd4e4a35dfc924750622243e574f84 | [
0.000187715602805838,
0.00017321572522632778,
0.00016752665396779776,
0.00017230911180377007,
0.000005188704562897328
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.