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": [
"\t\t\tt,\n",
"\t\t\tc,\n",
"\t\t\tnode,\n",
"\t\t\t\"add nodesource repository\",\n",
"\t\t\t`sudo apt install ca-certificates && curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -`,\n",
"\t\t)\n",
"\t\trequire.NoError(t, err)\n",
"\n",
"\t\terr = repeatRunE(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t`sudo apt install ca-certificates && curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -`,\n"
],
"file_path": "pkg/cmd/roachtest/tests/knex.go",
"type": "replace",
"edit_start_line_idx": 65
} | // Copyright 2021 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package tests
import (
"context"
"strings"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/cluster"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/option"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/registry"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/test"
"github.com/cockroachdb/cockroach/pkg/roachprod/install"
"github.com/stretchr/testify/require"
)
const supportedKnexTag = "2.5.1"
// This test runs one of knex's test suite against a single cockroach
// node.
func registerKnex(r registry.Registry) {
runKnex := func(
ctx context.Context,
t test.Test,
c cluster.Cluster,
) {
if c.IsLocal() {
t.Fatal("cannot be run in local mode")
}
node := c.Node(1)
t.Status("setting up cockroach")
c.Put(ctx, t.Cockroach(), "./cockroach", c.All())
c.Start(ctx, t.L(), option.DefaultStartOpts(), install.MakeClusterSettings(), c.All())
version, err := fetchCockroachVersion(ctx, t.L(), c, node[0])
require.NoError(t, err)
err = alterZoneConfigAndClusterSettings(ctx, t, version, c, node[0])
require.NoError(t, err)
err = repeatRunE(
ctx,
t,
c,
node,
"create sql database",
`./cockroach sql --insecure -e "CREATE DATABASE test"`,
)
require.NoError(t, err)
err = repeatRunE(
ctx,
t,
c,
node,
"add nodesource repository",
`sudo apt install ca-certificates && curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -`,
)
require.NoError(t, err)
err = repeatRunE(
ctx, t, c, node, "install nodejs and npm", `sudo apt-get -qq install nodejs`,
)
require.NoError(t, err)
err = repeatRunE(
ctx, t, c, node, "update npm", `sudo npm i -g npm`,
)
require.NoError(t, err)
err = repeatRunE(
ctx, t, c, node, "install mocha", `sudo npm i -g mocha`,
)
require.NoError(t, err)
err = repeatRunE(
ctx, t, c, node, "remove old knex", `sudo rm -rf /mnt/data1/knex`,
)
require.NoError(t, err)
err = repeatGitCloneE(
ctx,
t,
c,
"https://github.com/knex/knex.git",
"/mnt/data1/knex",
supportedKnexTag,
node,
)
require.NoError(t, err)
err = repeatRunE(
ctx, t, c, node, "install knex npm dependencies", `cd /mnt/data1/knex/ && npm i`,
)
require.NoError(t, err)
t.Status("running knex tests")
result, err := c.RunWithDetailsSingleNode(
ctx,
t.L(),
node,
`cd /mnt/data1/knex/ && DB='cockroachdb' npm test`,
)
rawResultsStr := result.Stdout + result.Stderr
t.L().Printf("Test Results: %s", rawResultsStr)
if err != nil {
// Ignore failures from test expecting `DELETE FROM ... USING` syntax to
// fail (https://github.com/cockroachdb/cockroach/issues/40963). We don't
// have a good way of parsing test results from javascript, so we do
// substring matching instead. This can be removed once the upstream knex
// repo updates to test with v23.1.
if !strings.Contains(rawResultsStr, "1) should handle basic delete with join") ||
!strings.Contains(rawResultsStr, "2) should handle returning") ||
strings.Contains(rawResultsStr, " 3) ") {
t.Fatal(err)
}
}
}
r.Add(registry.TestSpec{
Name: "knex",
Owner: registry.OwnerSQLFoundations,
Cluster: r.MakeClusterSpec(1),
Leases: registry.MetamorphicLeases,
NativeLibs: registry.LibGEOS,
Tags: registry.Tags(`default`, `orm`),
Run: func(ctx context.Context, t test.Test, c cluster.Cluster) {
runKnex(ctx, t, c)
},
})
}
| pkg/cmd/roachtest/tests/knex.go | 1 | https://github.com/cockroachdb/cockroach/commit/6e68bdafa7aa5b0f1e507af16bb7b272c881adce | [
0.9980396628379822,
0.07185792922973633,
0.00016648774908389896,
0.0002485583536326885,
0.24774755537509918
] |
{
"id": 0,
"code_window": [
"\t\t\tt,\n",
"\t\t\tc,\n",
"\t\t\tnode,\n",
"\t\t\t\"add nodesource repository\",\n",
"\t\t\t`sudo apt install ca-certificates && curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -`,\n",
"\t\t)\n",
"\t\trequire.NoError(t, err)\n",
"\n",
"\t\terr = repeatRunE(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t`sudo apt install ca-certificates && curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -`,\n"
],
"file_path": "pkg/cmd/roachtest/tests/knex.go",
"type": "replace",
"edit_start_line_idx": 65
} | // Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package rsg
import (
"fmt"
"testing"
)
const yaccExample = `
name:
IDENT
| unreserved_keyword
| col_name_keyword
unreserved_keyword:
ABORT
| ACTION
| ADD
| ADMIN
col_name_keyword:
ANNOTATE_TYPE
| BETWEEN
| BIGINT
| BIT
column_name: name
constraint_name: name
column_def:
column_name typename col_qual_list
{
tableDef, err := tree.NewColumnTableDef(tree.Name($1), $2.colType(), $3.colQuals())
if err != nil {
sqllex.Error(err.Error())
return 1
}
$$.val = tableDef
}
col_qual_list:
col_qual_list col_qualification
{
$$.val = append($1.colQuals(), $2.colQual())
}
| /* EMPTY */
{
$$.val = []tree.NamedColumnQualification(nil)
}
col_qualification:
CONSTRAINT constraint_name col_qualification_elem
{
$$.val = tree.NamedColumnQualification{Name: tree.Name($2), Qualification: $3.colQualElem()}
}
| col_qualification_elem
{
$$.val = tree.NamedColumnQualification{Qualification: $1.colQualElem()}
}
col_qualification_elem:
NOT NULL
{
$$.val = tree.NotNullConstraint{}
}
| NULL
{
$$.val = tree.NullConstraint{}
}
| UNIQUE
{
$$.val = tree.UniqueConstraint{}
}
| PRIMARY KEY
{
$$.val = tree.PrimaryKeyConstraint{}
}
`
func getRSG(t *testing.T) *RSG {
r, err := NewRSG(1, yaccExample, false)
if err != nil {
t.Fatal(err)
}
return r
}
func TestGenerate(t *testing.T) {
tests := []struct {
root string
depth int
repetitions int
expected []string
}{
{
root: "column_def",
depth: 20,
repetitions: 10,
expected: []string{
"BIT typename",
"ANNOTATE_TYPE typename CONSTRAINT ADD PRIMARY KEY NULL",
"ident typename PRIMARY KEY CONSTRAINT ident NULL",
"BETWEEN typename NULL",
"ADD typename",
"ABORT typename",
"ACTION typename",
"BIGINT typename",
"ident typename",
"BETWEEN typename CONSTRAINT ident UNIQUE",
},
},
}
for _, tc := range tests {
t.Run(fmt.Sprintf("%s-%d-%d", tc.root, tc.depth, tc.repetitions), func(t *testing.T) {
r := getRSG(t)
out := make([]string, tc.repetitions)
for i := range out {
out[i] = r.Generate(tc.root, tc.depth)
}
// Enable to help with writing tests.
if false {
for _, o := range out {
fmt.Printf("%q,\n", o)
}
return
}
if len(out) != len(tc.expected) {
t.Fatal("unexpected")
}
for i, o := range out {
if o != tc.expected[i] {
t.Fatalf("got %q, expected %q", o, tc.expected[i])
}
}
})
}
}
| pkg/internal/rsg/rsg_test.go | 0 | https://github.com/cockroachdb/cockroach/commit/6e68bdafa7aa5b0f1e507af16bb7b272c881adce | [
0.0002768644189927727,
0.00018084753537550569,
0.00016543619858566672,
0.00017432364984415472,
0.00002558535197749734
] |
{
"id": 0,
"code_window": [
"\t\t\tt,\n",
"\t\t\tc,\n",
"\t\t\tnode,\n",
"\t\t\t\"add nodesource repository\",\n",
"\t\t\t`sudo apt install ca-certificates && curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -`,\n",
"\t\t)\n",
"\t\trequire.NoError(t, err)\n",
"\n",
"\t\terr = repeatRunE(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t`sudo apt install ca-certificates && curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -`,\n"
],
"file_path": "pkg/cmd/roachtest/tests/knex.go",
"type": "replace",
"edit_start_line_idx": 65
} | load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
go_library(
name = "tenantsettingswatcher",
srcs = [
"doc.go",
"overrides_store.go",
"row_decoder.go",
"watcher.go",
],
importpath = "github.com/cockroachdb/cockroach/pkg/server/tenantsettingswatcher",
visibility = ["//visibility:public"],
deps = [
"//pkg/keys",
"//pkg/kv/kvclient/rangefeed",
"//pkg/kv/kvclient/rangefeed/rangefeedbuffer",
"//pkg/kv/kvclient/rangefeed/rangefeedcache",
"//pkg/kv/kvpb",
"//pkg/roachpb",
"//pkg/settings",
"//pkg/settings/cluster",
"//pkg/sql/catalog",
"//pkg/sql/catalog/descpb",
"//pkg/sql/catalog/systemschema",
"//pkg/sql/rowenc",
"//pkg/sql/rowenc/valueside",
"//pkg/sql/sem/tree",
"//pkg/sql/types",
"//pkg/util/hlc",
"//pkg/util/log",
"//pkg/util/startup",
"//pkg/util/stop",
"//pkg/util/syncutil",
"@com_github_cockroachdb_errors//:errors",
],
)
go_test(
name = "tenantsettingswatcher_test",
srcs = [
"main_test.go",
"overrides_store_test.go",
"row_decoder_test.go",
"watcher_test.go",
],
args = ["-test.timeout=295s"],
embed = [":tenantsettingswatcher"],
deps = [
"//pkg/base",
"//pkg/clusterversion",
"//pkg/kv/kvpb",
"//pkg/roachpb",
"//pkg/security/securityassets",
"//pkg/security/securitytest",
"//pkg/server",
"//pkg/settings",
"//pkg/sql",
"//pkg/sql/catalog",
"//pkg/testutils/serverutils",
"//pkg/testutils/sqlutils",
"//pkg/testutils/testcluster",
"//pkg/util/leaktest",
"//pkg/util/log",
"@com_github_stretchr_testify//require",
],
)
| pkg/server/tenantsettingswatcher/BUILD.bazel | 0 | https://github.com/cockroachdb/cockroach/commit/6e68bdafa7aa5b0f1e507af16bb7b272c881adce | [
0.00017612066585570574,
0.00017370560090057552,
0.00017086479056160897,
0.00017347763059660792,
0.000001998179641304887
] |
{
"id": 0,
"code_window": [
"\t\t\tt,\n",
"\t\t\tc,\n",
"\t\t\tnode,\n",
"\t\t\t\"add nodesource repository\",\n",
"\t\t\t`sudo apt install ca-certificates && curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -`,\n",
"\t\t)\n",
"\t\trequire.NoError(t, err)\n",
"\n",
"\t\terr = repeatRunE(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t`sudo apt install ca-certificates && curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -`,\n"
],
"file_path": "pkg/cmd/roachtest/tests/knex.go",
"type": "replace",
"edit_start_line_idx": 65
} | // Copyright 2022 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
//go:build !metamorphic_disable
// +build !metamorphic_disable
package util
import "github.com/cockroachdb/cockroach/pkg/util/envutil"
// disableMetamorphicTesting can be used to disable metamorphic tests. If it
// is set to true then metamorphic testing will not be enabled.
var disableMetamorphicTesting = envutil.EnvOrDefaultBool(DisableMetamorphicEnvVar, false)
| pkg/util/constants_metamorphic_enable.go | 0 | https://github.com/cockroachdb/cockroach/commit/6e68bdafa7aa5b0f1e507af16bb7b272c881adce | [
0.00017928335000760853,
0.0001765354536473751,
0.00017365437815897167,
0.00017666863277554512,
0.0000022999470274953637
] |
{
"id": 1,
"code_window": [
"\t\t\tctx,\n",
"\t\t\tt,\n",
"\t\t\tc,\n",
"\t\t\tnode,\n",
"\t\t\t\"add nodesource repository\",\n",
"\t\t\t`sudo apt install ca-certificates && curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -`,\n",
"\t\t)\n",
"\t\trequire.NoError(t, err)\n",
"\n",
"\t\terr = repeatRunE(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t`sudo apt install ca-certificates && curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -`,\n"
],
"file_path": "pkg/cmd/roachtest/tests/nodejs_postgres.go",
"type": "replace",
"edit_start_line_idx": 75
} | // Copyright 2021 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package tests
import (
"context"
"fmt"
"regexp"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/cluster"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/option"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/registry"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/test"
"github.com/cockroachdb/cockroach/pkg/roachprod/install"
)
var sequelizeCockroachDBReleaseTagRegex = regexp.MustCompile(`^v(?P<major>\d+)\.(?P<minor>\d+)\.(?P<point>\d+)$`)
var supportedSequelizeCockroachDBRelease = "v6.0.5"
// This test runs sequelize's full test suite against a single cockroach node.
func registerSequelize(r registry.Registry) {
runSequelize := func(
ctx context.Context,
t test.Test,
c cluster.Cluster,
) {
if c.IsLocal() {
t.Fatal("cannot be run in local mode")
}
node := c.Node(1)
t.Status("setting up cockroach")
c.Put(ctx, t.Cockroach(), "./cockroach", c.All())
c.Start(ctx, t.L(), option.DefaultStartOpts(), install.MakeClusterSettings(), c.All())
version, err := fetchCockroachVersion(ctx, t.L(), c, node[0])
if err != nil {
t.Fatal(err)
}
if err := alterZoneConfigAndClusterSettings(ctx, t, version, c, node[0]); err != nil {
t.Fatal(err)
}
t.Status("create database used by tests")
db, err := c.ConnE(ctx, t.L(), node[0])
if err != nil {
t.Fatal(err)
}
defer db.Close()
if _, err := db.ExecContext(
ctx,
`CREATE DATABASE sequelize_test`,
); err != nil {
t.Fatal(err)
}
t.Status("cloning sequelize-cockroachdb and installing prerequisites")
latestTag, err := repeatGetLatestTag(ctx, t, "cockroachdb", "sequelize-cockroachdb", sequelizeCockroachDBReleaseTagRegex)
if err != nil {
t.Fatal(err)
}
t.L().Printf("Latest sequelize-cockroachdb release is %s.", latestTag)
t.L().Printf("Supported sequelize-cockroachdb release is %s.", supportedSequelizeCockroachDBRelease)
if err := repeatRunE(
ctx, t, c, node, "update apt-get", `sudo apt-get -qq update`,
); err != nil {
t.Fatal(err)
}
if err := repeatRunE(
ctx,
t,
c,
node,
"install dependencies",
`sudo apt-get -qq install make python3 libpq-dev python-dev gcc g++ `+
`software-properties-common build-essential`,
); err != nil {
t.Fatal(err)
}
if err := repeatRunE(
ctx,
t,
c,
node,
"add nodesource repository",
`sudo apt install ca-certificates && curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -`,
); err != nil {
t.Fatal(err)
}
if err := repeatRunE(
ctx, t, c, node, "install nodejs and npm", `sudo apt-get -qq install nodejs`,
); err != nil {
t.Fatal(err)
}
if err := repeatRunE(
ctx, t, c, node, "update npm", `sudo npm i -g npm`,
); err != nil {
t.Fatal(err)
}
if err := repeatRunE(
ctx, t, c, node, "remove old sequelize", `sudo rm -rf /mnt/data1/sequelize`,
); err != nil {
t.Fatal(err)
}
if err := repeatGitCloneE(
ctx,
t,
c,
"https://github.com/cockroachdb/sequelize-cockroachdb.git",
"/mnt/data1/sequelize",
supportedSequelizeCockroachDBRelease,
node,
); err != nil {
t.Fatal(err)
}
if err := repeatRunE(
ctx, t, c, node, "install dependencies", `cd /mnt/data1/sequelize && sudo npm i`,
); err != nil {
t.Fatal(err)
}
// Version telemetry is already disabled in the sequelize-cockroachdb test suite.
t.Status("running Sequelize test suite")
result, err := c.RunWithDetailsSingleNode(ctx, t.L(), node,
fmt.Sprintf(`cd /mnt/data1/sequelize/ && npm test --crdb_version=%s`, version),
)
rawResultsStr := result.Stdout + result.Stderr
t.L().Printf("Test Results: %s", rawResultsStr)
if err != nil {
// The test suite is flaky and work is being done upstream to stabilize
// it (https://github.com/sequelize/sequelize/pull/15569). Until that's
// done, we ignore all failures from this test.
// t.Fatal(err)
t.L().Printf("ignoring failure (https://github.com/cockroachdb/cockroach/issues/108937): %s", err)
}
}
r.Add(registry.TestSpec{
Name: "sequelize",
Owner: registry.OwnerSQLFoundations,
Cluster: r.MakeClusterSpec(1),
Leases: registry.MetamorphicLeases,
NativeLibs: registry.LibGEOS,
Tags: registry.Tags(`default`, `orm`),
Run: func(ctx context.Context, t test.Test, c cluster.Cluster) {
runSequelize(ctx, t, c)
},
})
}
| pkg/cmd/roachtest/tests/sequelize.go | 1 | https://github.com/cockroachdb/cockroach/commit/6e68bdafa7aa5b0f1e507af16bb7b272c881adce | [
0.9911862015724182,
0.08687148988246918,
0.0001662491704337299,
0.0018385768635198474,
0.23308603465557098
] |
{
"id": 1,
"code_window": [
"\t\t\tctx,\n",
"\t\t\tt,\n",
"\t\t\tc,\n",
"\t\t\tnode,\n",
"\t\t\t\"add nodesource repository\",\n",
"\t\t\t`sudo apt install ca-certificates && curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -`,\n",
"\t\t)\n",
"\t\trequire.NoError(t, err)\n",
"\n",
"\t\terr = repeatRunE(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t`sudo apt install ca-certificates && curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -`,\n"
],
"file_path": "pkg/cmd/roachtest/tests/nodejs_postgres.go",
"type": "replace",
"edit_start_line_idx": 75
} | // Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package log
import (
"sort"
"github.com/cockroachdb/ttycolor"
)
type logFormatter interface {
formatterName() string
// doc is used to generate the formatter documentation.
doc() string
// formatEntry formats a logEntry into a newly allocated *buffer.
// The caller is responsible for calling putBuffer() afterwards.
formatEntry(entry logEntry) *buffer
// setOption configures the formatter with the given option.
setOption(key string, value string) error
// contentType is the MIME content-type field to use on
// transports which use this metadata.
contentType() string
}
var formatParsers = map[string]string{
"crdb-v1": "v1",
"crdb-v1-count": "v1",
"crdb-v1-tty": "v1",
"crdb-v1-tty-count": "v1",
"crdb-v2": "v2",
"crdb-v2-tty": "v2",
"json": "json",
"json-compact": "json-compact",
"json-fluent": "json",
"json-fluent-compact": "json-compact",
}
var formatters = func() map[string]func() logFormatter {
m := make(map[string]func() logFormatter)
r := func(f func() logFormatter) {
name := f().formatterName()
if _, ok := m[name]; ok {
panic("duplicate formatter name: " + name)
}
m[name] = f
}
r(func() logFormatter {
return &formatCrdbV1{showCounter: false, colorProfile: ttycolor.StderrProfile, colorProfileName: "auto"}
})
r(func() logFormatter {
return &formatCrdbV1{showCounter: false, colorProfileName: "none"}
})
r(func() logFormatter {
return &formatCrdbV1{showCounter: true, colorProfile: ttycolor.StderrProfile, colorProfileName: "auto"}
})
r(func() logFormatter {
return &formatCrdbV1{showCounter: true, colorProfileName: "none"}
})
r(func() logFormatter {
return &formatCrdbV2{colorProfileName: "none"}
})
r(func() logFormatter {
return &formatCrdbV2{colorProfile: ttycolor.StderrProfile, colorProfileName: "auto"}
})
r(func() logFormatter { return &formatJSONFull{fluentTag: true, tags: tagCompact} })
r(func() logFormatter { return &formatJSONFull{fluentTag: true, tags: tagVerbose} })
r(func() logFormatter { return &formatJSONFull{tags: tagCompact} })
r(func() logFormatter { return &formatJSONFull{tags: tagVerbose} })
return m
}()
var formatNames = func() (res []string) {
for name := range formatters {
res = append(res, name)
}
sort.Strings(res)
return res
}()
// GetFormatterDocs returns the embedded documentation for all the
// supported formats.
func GetFormatterDocs() map[string]string {
m := make(map[string]string)
for fmtName, f := range formatters {
m[fmtName] = f().doc()
}
return m
}
| pkg/util/log/formats.go | 0 | https://github.com/cockroachdb/cockroach/commit/6e68bdafa7aa5b0f1e507af16bb7b272c881adce | [
0.000246182840783149,
0.00018017775437328964,
0.0001656412350712344,
0.0001740440056892112,
0.00002248518831038382
] |
{
"id": 1,
"code_window": [
"\t\t\tctx,\n",
"\t\t\tt,\n",
"\t\t\tc,\n",
"\t\t\tnode,\n",
"\t\t\t\"add nodesource repository\",\n",
"\t\t\t`sudo apt install ca-certificates && curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -`,\n",
"\t\t)\n",
"\t\trequire.NoError(t, err)\n",
"\n",
"\t\terr = repeatRunE(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t`sudo apt install ca-certificates && curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -`,\n"
],
"file_path": "pkg/cmd/roachtest/tests/nodejs_postgres.go",
"type": "replace",
"edit_start_line_idx": 75
} | // Copyright 2017 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package tree_test
import (
"context"
"regexp"
"testing"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
_ "github.com/cockroachdb/cockroach/pkg/sql/sem/builtins"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sem/volatility"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/stretchr/testify/require"
)
// The following tests need both the type checking infrastructure and also
// all the built-in function definitions to be active.
func TestTypeCheck(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
typeMap := map[string]*types.T{
"d.t1": types.Int,
"t2": types.String,
"d.s.t3": types.Decimal,
}
mapResolver := tree.MakeTestingMapTypeResolver(typeMap)
testData := []struct {
expr string
// The expected serialized expression after type-checking. This tests both
// the serialization and that the constants are resolved to the expected
// types.
expected string
}{
{`NULL + 1`, `NULL`},
{`NULL + 1.1`, `NULL`},
{`NULL + '2006-09-23'::date`, `NULL`},
{`NULL + '1h'::interval`, `NULL`},
{`NULL || 'hello'`, `NULL`},
{`NULL || 'hello'::bytes`, `NULL`},
{`NULL::int4`, `NULL::INT4`},
{`NULL::int8`, `NULL::INT8`},
{`INTERVAL '1s'`, `'00:00:01':::INTERVAL`},
{`(1.1::decimal)::decimal`, `1.1:::DECIMAL`},
{`NULL = 1`, `NULL`},
{`1 = NULL`, `NULL`},
{`true AND NULL`, `true AND NULL`},
{`NULL OR false`, `NULL OR false`},
{`1 IN (1, 2, 3)`, `1:::INT8 IN (1:::INT8, 2:::INT8, 3:::INT8)`},
{`IF(true, 2, 3)`, `IF(true, 2:::INT8, 3:::INT8)`},
{`IF(false, 2, 3)`, `IF(false, 2:::INT8, 3:::INT8)`},
{`IF(NULL, 2, 3)`, `IF(NULL, 2:::INT8, 3:::INT8)`},
{`IF(NULL, 2, 3.0)`, `IF(NULL, 2:::DECIMAL, 3.0:::DECIMAL)`},
{`IF(true, (1, 2), (1, 3))`, `IF(true, (1:::INT8, 2:::INT8), (1:::INT8, 3:::INT8))`},
{`IFERROR(1, 1.2, '')`, `IFERROR(1:::DECIMAL, 1.2:::DECIMAL, '':::STRING)`},
{`IFERROR(NULL, 3, '')`, `IFERROR(NULL, 3:::INT8, '':::STRING)`},
{`ISERROR(123)`, `ISERROR(123:::INT8)`},
{`ISERROR(NULL)`, `ISERROR(NULL)`},
{`IFNULL(1, 2)`, `IFNULL(1:::INT8, 2:::INT8)`},
{`IFNULL(1, 2.0)`, `IFNULL(1:::DECIMAL, 2.0:::DECIMAL)`},
{`IFNULL(NULL, 2)`, `IFNULL(NULL, 2:::INT8)`},
{`IFNULL(2, NULL)`, `IFNULL(2:::INT8, NULL)`},
{`IFNULL((1, 2), (1, 3))`, `IFNULL((1:::INT8, 2:::INT8), (1:::INT8, 3:::INT8))`},
{`NULLIF(1, 2)`, `NULLIF(1:::INT8, 2:::INT8)`},
{`NULLIF(1, 2.0)`, `NULLIF(1:::DECIMAL, 2.0:::DECIMAL)`},
{`NULLIF(NULL, 2)`, `NULLIF(NULL, 2:::INT8)`},
{`NULLIF(2, NULL)`, `NULLIF(2:::INT8, NULL)`},
{`NULLIF((1, 2), (1, 3))`, `NULLIF((1:::INT8, 2:::INT8), (1:::INT8, 3:::INT8))`},
{`COALESCE(1, 2, 3, 4, 5)`, `COALESCE(1:::INT8, 2:::INT8, 3:::INT8, 4:::INT8, 5:::INT8)`},
{`COALESCE(1, 2.0)`, `COALESCE(1:::DECIMAL, 2.0:::DECIMAL)`},
{`COALESCE(NULL, 2)`, `COALESCE(NULL, 2:::INT8)`},
{`COALESCE(2, NULL)`, `COALESCE(2:::INT8, NULL)`},
{`COALESCE((1, 2), (1, 3))`, `COALESCE((1:::INT8, 2:::INT8), (1:::INT8, 3:::INT8))`},
{`true IS NULL`, `true IS NULL`},
{`true IS NOT NULL`, `true IS NOT NULL`},
{`true IS TRUE`, `true IS true`},
{`true IS NOT TRUE`, `true IS NOT true`},
{`true IS FALSE`, `true IS false`},
{`true IS NOT FALSE`, `true IS NOT false`},
{`CASE 1 WHEN 1 THEN (1, 2) ELSE (1, 3) END`, `CASE 1:::INT8 WHEN 1:::INT8 THEN (1:::INT8, 2:::INT8) ELSE (1:::INT8, 3:::INT8) END`},
{`1 BETWEEN 2 AND 3`, `1:::INT8 BETWEEN 2:::INT8 AND 3:::INT8`},
{`4 BETWEEN 2.4 AND 5.5::float`, `4:::INT8 BETWEEN 2.4:::DECIMAL AND 5.5:::FLOAT8`},
{`count(3)`, `count(3:::INT8)`},
{`ARRAY['a', 'b', 'c']`, `ARRAY['a':::STRING, 'b':::STRING, 'c':::STRING]:::STRING[]`},
{`ARRAY[1.5, 2.5, 3.5]`, `ARRAY[1.5:::DECIMAL, 2.5:::DECIMAL, 3.5:::DECIMAL]:::DECIMAL[]`},
{`ARRAY[NULL]`, `ARRAY[NULL]:::STRING[]`},
{`ARRAY[NULL]:::int[]`, `ARRAY[NULL]:::INT8[]`},
{`ARRAY[NULL, NULL]:::int[]`, `ARRAY[NULL, NULL]:::INT8[]`},
{`ARRAY[]::INT8[]`, `ARRAY[]:::INT8[]`},
{`ARRAY[]:::INT8[]`, `ARRAY[]:::INT8[]`},
{`ARRAY[1::INT, 1::FLOAT8]`, `ARRAY[1:::INT8::FLOAT8, 1.0:::FLOAT8]:::FLOAT8[]`},
{`ARRAY[(1::INT,), (1::FLOAT8,)]`, `ARRAY[(1:::INT8::FLOAT8,), (1.0:::FLOAT8,)]:::RECORD[]`},
{`1 = ANY ARRAY[1.5, 2.5, 3.5]`, `1:::DECIMAL = ANY ARRAY[1.5:::DECIMAL, 2.5:::DECIMAL, 3.5:::DECIMAL]:::DECIMAL[]`},
{`true = SOME (ARRAY[true, false])`, `true = SOME ARRAY[true, false]:::BOOL[]`},
{`1.3 = ALL ARRAY[1, 2, 3]`, `1.3:::DECIMAL = ALL ARRAY[1:::DECIMAL, 2:::DECIMAL, 3:::DECIMAL]:::DECIMAL[]`},
{`1.3 = ALL ((ARRAY[]))`, `1.3:::DECIMAL = ALL ARRAY[]:::DECIMAL[]`},
{`NULL = ALL ARRAY[1.5, 2.5, 3.5]`, `NULL`},
{`NULL = ALL ARRAY[NULL, NULL]`, `NULL`},
{`1 = ALL NULL`, `NULL`},
{`'a' = ALL current_schemas(true)`, `'a':::STRING = ALL current_schemas(true)`},
{`NULL = ALL current_schemas(true)`, `NULL = ALL current_schemas(true)`},
{`INTERVAL '1'`, `'00:00:01':::INTERVAL`},
{`DECIMAL '1.0'`, `1.0:::DECIMAL`},
{`1 + 2`, `1:::INT8 + 2:::INT8`},
{`1:::decimal + 2`, `1:::DECIMAL + 2:::DECIMAL`},
{`1:::float + 2`, `1.0:::FLOAT8 + 2.0:::FLOAT8`},
{`INTERVAL '1.5s' * 2`, `'00:00:01.5':::INTERVAL * 2:::INT8`},
{`2 * INTERVAL '1.5s'`, `2:::INT8 * '00:00:01.5':::INTERVAL`},
{`1 + $1`, `1:::INT8 + $1:::INT8`},
{`1:::DECIMAL + $1`, `1:::DECIMAL + $1:::DECIMAL`},
{`$1:::INT8`, `$1:::INT8`},
{`2::DECIMAL(10,2) + $1`, `2:::DECIMAL::DECIMAL(10,2) + $1:::DECIMAL`},
{`2::DECIMAL(10,0) + $1`, `2:::DECIMAL::DECIMAL(10) + $1:::DECIMAL`},
// Tuples with labels
{`(ROW (1) AS a)`, `((1:::INT8,) AS a)`},
{`(ROW(1:::INT8) AS a)`, `((1:::INT8,) AS a)`},
{`((1,2) AS a,b)`, `((1:::INT8, 2:::INT8) AS a, b)`},
{`((1:::INT8, 2:::INT8) AS a, b)`, `((1:::INT8, 2:::INT8) AS a, b)`},
{`(ROW (1,2) AS a,b)`, `((1:::INT8, 2:::INT8) AS a, b)`},
{`(ROW(1:::INT8, 2:::INT8) AS a, b)`, `((1:::INT8, 2:::INT8) AS a, b)`},
{
`((1,2,3) AS "One","Two","Three")`,
`((1:::INT8, 2:::INT8, 3:::INT8) AS "One", "Two", "Three")`,
},
{
`((1:::INT8, 2:::INT8, 3:::INT8) AS "One", "Two", "Three")`,
`((1:::INT8, 2:::INT8, 3:::INT8) AS "One", "Two", "Three")`,
},
{
`(ROW (1,2,3) AS "One",Two,"Three")`,
`((1:::INT8, 2:::INT8, 3:::INT8) AS "One", two, "Three")`,
},
{
`(ROW(1:::INT8, 2:::INT8, 3:::INT8) AS "One", two, "Three")`,
`((1:::INT8, 2:::INT8, 3:::INT8) AS "One", two, "Three")`,
},
// Tuples with duplicate labels are allowed, but raise error when accessed by a duplicate label name.
// This satisfies a postgres-compatible implementation of unnest(array, array...), where all columns
// have the same label (unnest).
{`((1,2) AS a,a)`, `((1:::INT8, 2:::INT8) AS a, a)`},
{`((1,2,3) AS a,a,a)`, `((1:::INT8, 2:::INT8, 3:::INT8) AS a, a, a)`},
// And tuples without labels still work as advertized
{`(ROW (1))`, `(1:::INT8,)`},
{`ROW(1:::INT8)`, `(1:::INT8,)`},
{`((1,2))`, `(1:::INT8, 2:::INT8)`},
{`(1:::INT8, 2:::INT8)`, `(1:::INT8, 2:::INT8)`},
{`(ROW (1,2))`, `(1:::INT8, 2:::INT8)`},
{`ROW(1:::INT8, 2:::INT8)`, `(1:::INT8, 2:::INT8)`},
// Regression test #74729. Correctly handle NULLs annotated as a tuple
// type.
{
`CASE WHEN true THEN ('a', 2) ELSE NULL:::RECORD END`,
`CASE WHEN true THEN ('a':::STRING, 2:::INT8) ELSE NULL END`,
},
{`((ROW (1) AS a)).a`, `1:::INT8`},
{`((('1', 2) AS a, b)).a`, `'1':::STRING`},
{`((('1', 2) AS a, b)).b`, `2:::INT8`},
{`((('1', 2) AS a, b)).@2`, `2:::INT8`},
{`(pg_get_keywords()).word`, `(pg_get_keywords()).word`},
{
`(information_schema._pg_expandarray(ARRAY[1,3])).x`,
`(information_schema._pg_expandarray(ARRAY[1:::INT8, 3:::INT8]:::INT8[])).x`,
},
{
`(information_schema._pg_expandarray(ARRAY[1:::INT8, 3:::INT8])).*`,
`information_schema._pg_expandarray(ARRAY[1:::INT8, 3:::INT8]:::INT8[])`,
},
{`((ROW (1) AS a)).*`, `((1:::INT8,) AS a)`},
{`((('1'||'', 1+1) AS a, b)).*`, `(('1':::STRING || '':::STRING, 1:::INT8 + 1:::INT8) AS a, b)`},
{`'{"x": "bar"}' -> 'x'`, `'{"x": "bar"}':::JSONB->'x':::STRING`},
{`('{"x": "bar"}') -> 'x'`, `'{"x": "bar"}':::JSONB->'x':::STRING`},
// These outputs, while bizarre looking, are correct and expected. The
// type annotation is caused by the call to tree.Serialize, which formats the
// output using the Parseable formatter which inserts type annotations
// at the end of all well-typed datums. And the second cast is caused by
// the test itself.
{`'NaN'::decimal`, `'NaN':::DECIMAL`},
{`'-NaN'::decimal`, `'NaN':::DECIMAL`},
{`'Inf'::decimal`, `'Infinity':::DECIMAL`},
{`'-Inf'::decimal`, `'-Infinity':::DECIMAL`},
// Test type checking with some types to resolve.
// Because the resolvable types right now are just aliases, the
// pre-resolution name is not going to get formatted.
{`1:::d.t1`, `1:::INT8`},
{`1:::d.s.t3 + 1.4`, `1:::DECIMAL + 1.4:::DECIMAL`},
{`1 IS OF (d.t1, t2)`, `1:::INT8 IS OF (INT8, STRING)`},
{`1::d.t1`, `1:::INT8`},
{`(('{' || 'a' ||'}')::STRING[])[1]::STRING`, `((('{':::STRING || 'a':::STRING) || '}':::STRING)::STRING[])[1:::INT8]`},
{`(('{' || '1' ||'}')::INT[])[1]`, `((('{':::STRING || '1':::STRING) || '}':::STRING)::INT8[])[1:::INT8]`},
{`(ARRAY[1, 2, 3]::int[])[2]`, `(ARRAY[1:::INT8, 2:::INT8, 3:::INT8]:::INT8[])[2:::INT8]`},
// String preference.
{`st_geomfromgeojson($1)`, `st_geomfromgeojson($1:::STRING):::GEOMETRY`},
// TSQuery and TSVector
{`'a' @@ 'b'`, `to_tsvector('a':::STRING) @@ plainto_tsquery('b':::STRING)`},
{`'a' @@ 'b':::TSQUERY`, `to_tsvector('a':::STRING) @@ '''b''':::TSQUERY`},
{`'a':::TSQUERY @@ 'b'`, `'''a''':::TSQUERY @@ to_tsvector('b':::STRING)`},
{`'a' @@ 'b':::TSVECTOR`, `'''a''':::TSQUERY @@ '''b''':::TSVECTOR`},
{`'a':::TSVECTOR @@ 'b'`, `'''a''':::TSVECTOR @@ '''b''':::TSQUERY`},
}
ctx := context.Background()
for _, d := range testData {
t.Run(d.expr, func(t *testing.T) {
expr, err := parser.ParseExpr(d.expr)
if err != nil {
t.Fatalf("%s: %v", d.expr, err)
}
semaCtx := tree.MakeSemaContext()
if err := semaCtx.Placeholders.Init(1 /* numPlaceholders */, nil /* typeHints */); err != nil {
t.Fatal(err)
}
semaCtx.TypeResolver = mapResolver
typeChecked, err := tree.TypeCheck(ctx, expr, &semaCtx, types.Any)
if err != nil {
t.Fatalf("%s: unexpected error %s", d.expr, err)
}
if s := tree.Serialize(typeChecked); s != d.expected {
t.Errorf("%s: expected %s, but found %s", d.expr, d.expected, s)
}
})
}
}
func TestTypeCheckError(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
typeMap := map[string]*types.T{
"d.t1": types.Int,
"t2": types.String,
"d.s.t3": types.Decimal,
}
mapResolver := tree.MakeTestingMapTypeResolver(typeMap)
testData := []struct {
expr string
expected string
}{
{`'1' + '2'`, `ambiguous binary operator:`},
{`'a' + 0`, `unsupported binary operator:`},
{`1.1 # 3.1`, `unsupported binary operator:`},
{`~0.1`, `unsupported unary operator:`},
{`'a' > 2`, `unsupported comparison operator:`},
{`a`, `column "a" does not exist`},
{`cos(*)`, `cannot use "*" in this context`},
{`a.*`, `cannot use "a.*" in this context`},
{`1 AND true`, `incompatible AND argument type: int`},
{`1.0 AND true`, `incompatible AND argument type: decimal`},
{`'a' OR true`, `could not parse "a" as type bool`},
{`(1, 2) OR true`, `incompatible OR argument type: tuple`},
{`NOT 1`, `incompatible NOT argument type: int`},
{`lower()`, `unknown signature: lower()`},
{`lower(1, 2)`, `unknown signature: lower(int, int)`},
{`lower(1)`, `unknown signature: lower(int)`},
{`lower('FOO') OVER ()`, `OVER specified, but lower() is neither a window function nor an aggregate function`},
{`count(1) FILTER (WHERE 1) OVER ()`, `incompatible FILTER expression type: int`},
{`CASE 'one' WHEN 1 THEN 1 WHEN 'two' THEN 2 END`, `incompatible condition type`},
{`CASE 1 WHEN 1 THEN 'one' WHEN 2 THEN 2 END`, `incompatible value type`},
{`CASE 1 WHEN 1 THEN 'one' ELSE 2 END`, `incompatible value type`},
{`(1, 2, 3) = (1, 2)`, `expected tuple (1, 2) to have a length of 3`},
{`(1, 2) = (1, 'a')`, `tuples (1, 2), (1, 'a') are not comparable at index 2: unsupported comparison operator:`},
{`1 IN ('a', 'b')`, `unsupported comparison operator: 1 IN ('a', 'b'): could not parse "a" as type int`},
{`1 IN (1, 'a')`, `unsupported comparison operator: 1 IN (1, 'a'): could not parse "a" as type int`},
{`1 = ANY 2`, `unsupported comparison operator: 1 = ANY 2: op ANY <right> requires array, tuple or subquery on right side`},
{`1 = ANY ARRAY[2, 'a']`, `unsupported comparison operator: 1 = ANY ARRAY[2, 'a']: could not parse "a" as type int`},
{`1 = ALL current_schemas(true)`, `unsupported comparison operator: <int> = ALL <string[]>`},
{`1.0 BETWEEN 2 AND 'a'`, `unsupported comparison operator: <decimal> < <string>`},
{`NULL BETWEEN 2 AND 'a'`, `unsupported comparison operator: <int> < <string>`},
{`IF(1, 2, 3)`, `incompatible IF condition type: int`},
{`IF(true, 'a', 2)`, `incompatible IF expressions: could not parse "a" as type int`},
{`IF(true, 2, 'a')`, `incompatible IF expressions: could not parse "a" as type int`},
{`IFNULL(1, 'a')`, `incompatible IFNULL expressions: could not parse "a" as type int`},
{`NULLIF(1, 'a')`, `incompatible NULLIF expressions: could not parse "a" as type int`},
{`COALESCE(1, 2, 3, 4, 'a')`, `incompatible COALESCE expressions: could not parse "a" as type int`},
{`ARRAY[]`, `cannot determine type of empty array`},
{`ANNOTATE_TYPE('a', int)`, `could not parse "a" as type int`},
{`ANNOTATE_TYPE(ANNOTATE_TYPE(1, int8), decimal)`, `incompatible type annotation for ANNOTATE_TYPE(1, INT8) as decimal, found type: int`},
{`3:::int[]`, `incompatible type annotation for 3 as int[], found type: int`},
{`B'1001'::decimal`, `invalid cast: varbit -> decimal`},
{`101.3::bit`, `invalid cast: decimal -> bit`},
{`ARRAY[1] = ARRAY['foo']`, `unsupported comparison operator: <int[]> = <string[]>`},
{`ARRAY[1]::int[] = ARRAY[1.0]::decimal[]`, `unsupported comparison operator: <int[]> = <decimal[]>`},
{`ARRAY[1] @> ARRAY['foo']`, `unsupported comparison operator: <int[]> @> <string[]>`},
{`ARRAY[1]::int[] @> ARRAY[1.0]::decimal[]`, `unsupported comparison operator: <int[]> @> <decimal[]>`},
{
`((1,2) AS a)`,
`mismatch in tuple definition: 2 expressions, 1 labels`,
},
{
`(ROW (1) AS a,b)`,
`mismatch in tuple definition: 1 expressions, 2 labels`,
},
{
`(((1,2) AS a,a)).a`,
`column reference "a" is ambiguous`,
},
{
`((ROW (1, '2') AS b,b)).b`,
`column reference "b" is ambiguous`,
},
{
`((ROW (1, '2') AS a,b)).x`,
`could not identify column "x" in tuple{int AS a, string AS b}`,
},
{
`(((1, '2') AS a,b)).x`,
`could not identify column "x" in tuple{int AS a, string AS b}`,
},
{
`(pg_get_keywords()).foo`,
`could not identify column "foo" in tuple{string AS word, string AS catcode, string AS catdesc}`,
},
{
`((1,2,3)).foo`,
`could not identify column "foo" in record data type`,
},
{
`1::d.notatype`,
`type "d.notatype" does not exist`,
},
{
`1 + 2::d.s.typ`,
`type "d.s.typ" does not exist`,
},
{`() = '03:00:00'`, `unsupported comparison operator: <tuple> = <string>`},
{`'03:00:00' > ROW()`, `unsupported comparison operator: <string> > <tuple>`},
}
ctx := context.Background()
for _, d := range testData {
t.Run(d.expr, func(t *testing.T) {
// Test with a nil and non-nil semaCtx.
t.Run("semaCtx not nil", func(t *testing.T) {
semaCtx := tree.MakeSemaContext()
semaCtx.TypeResolver = mapResolver
expr, err := parser.ParseExpr(d.expr)
if err != nil {
t.Fatalf("%s: %v", d.expr, err)
}
if _, err := tree.TypeCheck(ctx, expr, &semaCtx, types.Any); !testutils.IsError(err, regexp.QuoteMeta(d.expected)) {
t.Errorf("%s: expected %s, but found %v", d.expr, d.expected, err)
}
})
t.Run("semaCtx is nil", func(t *testing.T) {
expr, err := parser.ParseExpr(d.expr)
if err != nil {
t.Fatalf("%s: %v", d.expr, err)
}
if _, err := tree.TypeCheck(ctx, expr, nil, types.Any); !testutils.IsError(err, regexp.QuoteMeta(d.expected)) {
t.Errorf("%s: expected %s, but found %v", d.expr, d.expected, err)
}
})
})
}
}
func TestTypeCheckVolatility(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// $1 has type timestamptz.
placeholderTypes := []*types.T{types.TimestampTZ}
testCases := []struct {
expr string
volatility volatility.V
}{
{"1 + 1", volatility.Immutable},
{"random()", volatility.Volatile},
{"now()", volatility.Stable},
{"'2020-01-01 01:02:03'::timestamp", volatility.Immutable},
{"'now'::timestamp", volatility.Stable},
{"'2020-01-01 01:02:03'::timestamptz", volatility.Stable},
{"'1 hour'::interval", volatility.Immutable},
{"$1", volatility.Immutable},
// Stable cast with immutable input.
{"$1::string", volatility.Stable},
// Stable binary operator with immutable inputs.
{"$1 + '1 hour'::interval", volatility.Stable},
// Stable comparison operator with immutable inputs.
{"$1 = '2020-01-01 01:02:03'::timestamp", volatility.Stable},
}
ctx := context.Background()
semaCtx := tree.MakeSemaContext()
if err := semaCtx.Placeholders.Init(len(placeholderTypes), placeholderTypes); err != nil {
t.Fatal(err)
}
typeCheck := func(sql string) error {
expr, err := parser.ParseExpr(sql)
if err != nil {
t.Fatalf("%s: %v", sql, err)
}
_, err = tree.TypeCheck(ctx, expr, &semaCtx, types.Any)
return err
}
for _, tc := range testCases {
// First, typecheck without any restrictions.
semaCtx.Properties.Require("", 0 /* flags */)
if err := typeCheck(tc.expr); err != nil {
t.Fatalf("%s: %v", tc.expr, err)
}
semaCtx.Properties.Require("", tree.RejectVolatileFunctions)
expectErr := tc.volatility == volatility.Volatile
if err := typeCheck(tc.expr); err == nil && expectErr {
t.Fatalf("%s: should have rejected volatile function", tc.expr)
} else if err != nil && !expectErr {
t.Fatalf("%s: %v", tc.expr, err)
}
semaCtx.Properties.Require("", tree.RejectStableOperators|tree.RejectVolatileFunctions)
expectErr = tc.volatility >= volatility.Stable
if err := typeCheck(tc.expr); err == nil && expectErr {
t.Fatalf("%s: should have rejected stable operator", tc.expr)
} else if err != nil && !expectErr {
t.Fatalf("%s: %v", tc.expr, err)
}
}
}
func TestTypeCheckCollatedString(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
// Typecheck without any restrictions.
semaCtx := tree.MakeSemaContext()
semaCtx.Properties.Require("", 0 /* flags */)
// Hint a normal string type for $1.
placeholderTypes := []*types.T{types.String}
err := semaCtx.Placeholders.Init(len(placeholderTypes), placeholderTypes)
require.NoError(t, err)
// The collated string constant must be on the LHS for this test, so that
// the type-checker chooses the collated string overload first.
expr, err := parser.ParseExpr("'cat'::STRING COLLATE \"en-US-u-ks-level2\" = ($1)")
require.NoError(t, err)
typed, err := tree.TypeCheck(ctx, expr, &semaCtx, types.Any)
require.NoError(t, err)
rightTyp := typed.(*tree.ComparisonExpr).Right.(tree.TypedExpr).ResolvedType()
require.Equal(t, rightTyp.Family(), types.CollatedStringFamily)
require.Equal(t, rightTyp.Locale(), "en-US-u-ks-level2")
}
func TestTypeCheckCollatedStringNestedCaseComparison(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
semaCtx := tree.MakeSemaContext()
// The collated string constant must be on the LHS for this test, so that
// the type-checker chooses the collated string overload first.
for _, exprStr := range []string{
`CASE WHEN false THEN CASE WHEN (NOT (false)) THEN NULL END ELSE ('' COLLATE "es_ES") END >= ('' COLLATE "es_ES")`,
`CASE WHEN false THEN NULL ELSE ('' COLLATE "es_ES") END >= ('' COLLATE "es_ES")`,
`CASE WHEN false THEN ('' COLLATE "es_ES") ELSE NULL END >= ('' COLLATE "es_ES")`,
`('' COLLATE "es_ES") >= CASE WHEN false THEN CASE WHEN (NOT (false)) THEN NULL END ELSE ('' COLLATE "es_ES") END`} {
expr, err := parser.ParseExpr(exprStr)
require.NoError(t, err)
typed, err := tree.TypeCheck(ctx, expr, &semaCtx, types.Any)
require.NoError(t, err)
for _, ex := range []tree.Expr{typed.(*tree.ComparisonExpr).Left, typed.(*tree.ComparisonExpr).Right} {
typ := ex.(tree.TypedExpr).ResolvedType()
require.Equal(t, types.CollatedStringFamily, typ.Family())
require.Equal(t, "es_ES", typ.Locale())
}
}
}
func TestTypeCheckCaseExprWithPlaceholders(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// Typecheck without any restrictions.
ctx := context.Background()
semaCtx := tree.MakeSemaContext()
semaCtx.Properties.Require("", 0 /* flags */)
// Hint all int4 types.
placeholderTypes := []*types.T{types.Int4, types.Int4, types.Int4, types.Int4, types.Int4}
err := semaCtx.Placeholders.Init(len(placeholderTypes), placeholderTypes)
require.NoError(t, err)
expr, err := parser.ParseExpr("case when 1 < $1 then $2 else $3 end = $4")
require.NoError(t, err)
typed, err := tree.TypeCheck(ctx, expr, &semaCtx, types.Any)
require.NoError(t, err)
leftTyp := typed.(*tree.ComparisonExpr).Left.(tree.TypedExpr).ResolvedType()
require.Equal(t, types.Int4, leftTyp)
}
func TestTypeCheckCaseExprWithConstantsAndUnresolvedPlaceholders(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// Typecheck without any restrictions.
ctx := context.Background()
semaCtx := tree.MakeSemaContext()
semaCtx.Properties.Require("", 0 /* flags */)
// Hint all int4 types, but leave one of the THEN branches unhinted.
placeholderTypes := []*types.T{types.Int4, types.Int4, types.Int4, nil, types.Int4}
err := semaCtx.Placeholders.Init(len(placeholderTypes), placeholderTypes)
require.NoError(t, err)
expr, err := parser.ParseExpr("case when 1 < $1 then $2 when 1 < $3 then $4 else 3 end = $5")
require.NoError(t, err)
typed, err := tree.TypeCheck(ctx, expr, &semaCtx, types.Any)
require.NoError(t, err)
leftTyp := typed.(*tree.ComparisonExpr).Left.(tree.TypedExpr).ResolvedType()
require.Equal(t, types.Int4, leftTyp)
for i := 0; i < len(placeholderTypes); i++ {
pTyp, _, err := semaCtx.Placeholders.Type(tree.PlaceholderIdx(i))
require.NoError(t, err)
require.Equal(t, types.Int4, pTyp)
}
}
// Regression test for https://github.com/cockroachdb/cockroach/issues/94192.
// If an array has only nulls and placeholders, then the type-checker should
// still infer the types using the placeholder hints.
func TestTypeCheckArrayWithNullAndPlaceholder(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// Typecheck without any restrictions.
ctx := context.Background()
semaCtx := tree.MakeSemaContext()
semaCtx.Properties.Require("", 0 /* flags */)
placeholderTypes := []*types.T{types.Int}
err := semaCtx.Placeholders.Init(len(placeholderTypes), placeholderTypes)
require.NoError(t, err)
expr, err := parser.ParseExpr("array[null, $1]::int[]")
require.NoError(t, err)
typed, err := tree.TypeCheck(ctx, expr, &semaCtx, types.Any)
require.NoError(t, err)
require.Equal(t, types.IntArray, typed.ResolvedType())
pTyp, _, err := semaCtx.Placeholders.Type(tree.PlaceholderIdx(0))
require.NoError(t, err)
require.Equal(t, types.Int, pTyp)
}
| pkg/sql/sem/tree/type_check_test.go | 0 | https://github.com/cockroachdb/cockroach/commit/6e68bdafa7aa5b0f1e507af16bb7b272c881adce | [
0.004423826467245817,
0.0004463224613573402,
0.00015640966012142599,
0.00017090406618081033,
0.0007395314169116318
] |
{
"id": 1,
"code_window": [
"\t\t\tctx,\n",
"\t\t\tt,\n",
"\t\t\tc,\n",
"\t\t\tnode,\n",
"\t\t\t\"add nodesource repository\",\n",
"\t\t\t`sudo apt install ca-certificates && curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -`,\n",
"\t\t)\n",
"\t\trequire.NoError(t, err)\n",
"\n",
"\t\terr = repeatRunE(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t`sudo apt install ca-certificates && curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -`,\n"
],
"file_path": "pkg/cmd/roachtest/tests/nodejs_postgres.go",
"type": "replace",
"edit_start_line_idx": 75
} | // Copyright 2022 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package op
import (
"container/heap"
"context"
"time"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/allocator/allocatorimpl"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/allocator/storepool"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/asim/config"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/asim/state"
"github.com/cockroachdb/errors"
)
// DispatchedTicket associates a dispatched operation with a ticket id. It can
// be used to retrieve the status of a dispatched operation.
type DispatchedTicket int
// Controller manages scheduling and monitoring of reconfiguration operations
// such as relocating replicas and lease transfers. It represents a higher
// level construct than the state changer, using it internally.
type Controller interface {
// Dispatch enqueues an operation to be processed. It returns a ticket
// associated with the operation that may be used to check on the operation
// progress.
Dispatch(context.Context, time.Time, state.State, ControlledOperation) DispatchedTicket
// Tick iterates through pending operations and processes them up to the
// current tick.
Tick(context.Context, time.Time, state.State)
// Check checks the progress of the operation associated with the ticket
// given. If the ticket exists, it returns the operation and true, else
// false.
Check(DispatchedTicket) (ControlledOperation, bool)
}
type controller struct {
changer state.Changer
allocator allocatorimpl.Allocator
storePool storepool.AllocatorStorePool
settings *config.SimulationSettings
pending *priorityQueue
ticketGen DispatchedTicket
tickets map[DispatchedTicket]ControlledOperation
storeID state.StoreID
}
// NewController returns a new Controller implementation.
func NewController(
changer state.Changer,
allocator allocatorimpl.Allocator,
storePool storepool.AllocatorStorePool,
settings *config.SimulationSettings,
storeID state.StoreID,
) Controller {
return &controller{
changer: changer,
allocator: allocator,
storePool: storePool,
settings: settings,
pending: &priorityQueue{items: []*queuedOp{}},
tickets: make(map[DispatchedTicket]ControlledOperation),
storeID: storeID,
}
}
// Dispatch enqueues an operation to be processed. It returns a ticket
// associated with the operation that may be used to check on the operation
// progress.
func (c *controller) Dispatch(
ctx context.Context, tick time.Time, state state.State, co ControlledOperation,
) DispatchedTicket {
c.ticketGen++
ticket := c.ticketGen
c.tickets[ticket] = co
qop := &queuedOp{ControlledOperation: co}
heap.Push(c.pending, qop)
c.Tick(ctx, tick, state)
return ticket
}
// Tick iterates through pending operations and processes them up to the
// current tick.
func (c *controller) Tick(ctx context.Context, tick time.Time, state state.State) {
for c.pending.Len() > 0 {
i := heap.Pop(c.pending)
qop, _ := i.(*queuedOp)
nextOp := qop.ControlledOperation
// There are no more pending checks.
if nextOp.Next().After(tick) {
heap.Push(c.pending, &queuedOp{ControlledOperation: nextOp})
return
}
c.process(ctx, tick, state, nextOp)
// There are still pending checks, process and push back to pending if
// not done.
if done, _ := nextOp.Done(); !done {
heap.Push(c.pending, &queuedOp{ControlledOperation: nextOp})
}
}
}
// Check checks the progress of the operation associated with the ticket given.
// If the ticket exists, it returns the operation and true, else false.
func (c *controller) Check(ticket DispatchedTicket) (op ControlledOperation, ok bool) {
op, ok = c.tickets[ticket]
if ok {
delete(c.tickets, ticket)
}
return op, ok
}
func (c *controller) process(
ctx context.Context, tick time.Time, state state.State, co ControlledOperation,
) {
switch op := co.(type) {
case *RelocateRangeOp:
if err := c.processRelocateRange(ctx, tick, state, op); err != nil {
op.error(err)
op.done = true
op.complete = tick
}
case *TransferLeaseOp:
if err := c.processTransferLease(ctx, tick, state, op); err != nil {
op.error(err)
op.done = true
op.complete = tick
}
default:
return
}
}
func (c *controller) processRelocateRange(
ctx context.Context, tick time.Time, s state.State, ro *RelocateRangeOp,
) error {
rng := s.RangeFor(ro.key)
options := SimRelocateOneOptions{allocator: c.allocator, storePool: c.storePool, state: s}
ops, leaseTarget, err := kvserver.RelocateOne(
ctx,
rng.Descriptor(),
ro.voterTargets,
ro.nonVoterTargets,
ro.transferLeaseToFirstVoter,
&options,
)
if err != nil {
return err
}
if leaseTarget != nil {
leaseholderStore, ok := s.LeaseholderStore(rng.RangeID())
if !ok {
return errors.Newf(" Lease transfer failed to %s. cannot find leaseholder", leaseTarget.StoreID.String())
}
if leaseholderStore.StoreID() != state.StoreID(leaseTarget.StoreID) {
if ok := s.TransferLease(rng.RangeID(), state.StoreID(leaseTarget.StoreID)); !ok {
leaseholder, err := options.Leaseholder(ctx, ro.key.ToRKey())
if err != nil {
return err
}
return errors.Newf("Lease transfer failed to %s. Existing leaseholder %s", leaseTarget.StoreID.String(), leaseholder)
}
}
}
if len(ops) == 0 {
ro.complete = tick
ro.done = true
return nil
}
change := state.ReplicaChange{
RangeID: rng.RangeID(),
Author: c.storeID,
Changes: ops,
}
targets := kvserver.SynthesizeTargetsByChangeType(ops)
if len(targets.VoterAdditions) > 0 || len(targets.NonVoterAdditions) > 0 {
change.Wait = c.settings.ReplicaChangeDelayFn()(rng.Size(), true /* use range size */)
}
completeAt, ok := c.changer.Push(tick, &change)
if !ok {
return errors.Newf("tick %d: Changer did not accept op %+v", change)
}
ro.next = completeAt
return nil
}
func (c *controller) processTransferLease(
ctx context.Context, tick time.Time, s state.State, ro *TransferLeaseOp,
) error {
if store, ok := s.LeaseholderStore(ro.rangeID); ok && store.StoreID() == ro.target {
ro.done = true
ro.complete = tick
return nil
}
if !s.ValidTransfer(ro.rangeID, ro.target) {
return errors.Errorf(
"unable to transfer lease for r%d to store %d, invalid transfer.",
ro.rangeID, ro.target)
}
delay := c.settings.ReplicaChangeBaseDelay
if _, ok := c.changer.Push(tick, &state.LeaseTransferChange{
RangeID: ro.rangeID,
TransferTarget: ro.target,
Wait: c.settings.ReplicaChangeBaseDelay,
Author: c.storeID,
}); !ok {
return errors.Errorf(
"unable to transfer lease for r%d to store %d, application failed.",
ro.rangeID, ro.target)
}
ro.next = tick.Add(delay)
return nil
}
| pkg/kv/kvserver/asim/op/controller.go | 0 | https://github.com/cockroachdb/cockroach/commit/6e68bdafa7aa5b0f1e507af16bb7b272c881adce | [
0.0021929291542619467,
0.0004063548694830388,
0.00015961943427100778,
0.0001736242847982794,
0.000555741076823324
] |
{
"id": 2,
"code_window": [
"\t\t\tc,\n",
"\t\t\tnode,\n",
"\t\t\t\"add nodesource repository\",\n",
"\t\t\t`sudo apt install ca-certificates && curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -`,\n",
"\t\t); err != nil {\n",
"\t\t\tt.Fatal(err)\n",
"\t\t}\n",
"\n",
"\t\tif err := repeatRunE(\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t`sudo apt install ca-certificates && curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -`,\n"
],
"file_path": "pkg/cmd/roachtest/tests/sequelize.go",
"type": "replace",
"edit_start_line_idx": 98
} | // Copyright 2021 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package tests
import (
"context"
"fmt"
"strings"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/cluster"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/option"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/registry"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/test"
rperrors "github.com/cockroachdb/cockroach/pkg/roachprod/errors"
"github.com/cockroachdb/cockroach/pkg/roachprod/install"
"github.com/cockroachdb/errors"
"github.com/stretchr/testify/require"
)
// TODO(richardjcai): Update this to use the repo owned by brianc once
// https://github.com/brianc/node-postgres/pull/2517 is fixed.
// Currently we cannot pass certs through PG env vars, the PR fixes it.
var repoOwner = "richardjcai"
var supportedBranch = "allowing_passing_certs_through_pg_env"
func registerNodeJSPostgres(r registry.Registry) {
runNodeJSPostgres := func(
ctx context.Context,
t test.Test,
c cluster.Cluster,
) {
if c.IsLocal() {
t.Fatal("cannot be run in local mode")
}
node := c.Node(1)
t.Status("setting up cockroach")
err := c.PutE(ctx, t.L(), t.Cockroach(), "./cockroach", c.All())
require.NoError(t, err)
settings := install.MakeClusterSettings(install.SecureOption(true))
err = c.StartE(ctx, t.L(), option.DefaultStartOpts(), settings)
require.NoError(t, err)
const user = "testuser" // certs auto-generated by roachprod start --secure
err = repeatRunE(ctx, t, c, node, "create sql user",
fmt.Sprintf(
`./cockroach sql --certs-dir certs -e "CREATE USER %s CREATEDB"`, user,
))
require.NoError(t, err)
err = repeatRunE(ctx, t, c, node, "create test database",
`./cockroach sql --certs-dir certs -e "CREATE DATABASE postgres_node_test"`,
)
require.NoError(t, err)
version, err := fetchCockroachVersion(ctx, t.L(), c, node[0])
require.NoError(t, err)
err = alterZoneConfigAndClusterSettings(ctx, t, version, c, node[0])
require.NoError(t, err)
err = repeatRunE(
ctx,
t,
c,
node,
"add nodesource repository",
`sudo apt install ca-certificates && curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -`,
)
require.NoError(t, err)
err = repeatRunE(
ctx, t, c, node, "install nodejs and npm", `sudo apt-get -qq install nodejs`,
)
require.NoError(t, err)
err = repeatRunE(
ctx, t, c, node, "update npm", `sudo npm i -g npm`,
)
require.NoError(t, err)
err = repeatRunE(
ctx, t, c, node, "install yarn", `sudo npm i -g yarn`,
)
require.NoError(t, err)
err = repeatRunE(
ctx, t, c, node, "install lerna", `sudo npm i --g lerna`,
)
require.NoError(t, err)
err = repeatRunE(
ctx, t, c, node, "remove old node-postgres", `sudo rm -rf /mnt/data1/node-postgres`,
)
require.NoError(t, err)
err = repeatGitCloneE(
ctx,
t,
c,
fmt.Sprintf("https://github.com/%s/node-postgres.git", repoOwner),
"/mnt/data1/node-postgres",
supportedBranch,
node,
)
require.NoError(t, err)
// The upstream repo hasn't updated its dependencies in light of
// https://github.blog/2021-09-01-improving-git-protocol-security-github/
// so we need this configuration.
err = repeatRunE(
ctx, t, c, node, "configure git to avoid unauthenticated protocol",
`cd /mnt/data1/node-postgres && sudo git config --global url."https://github".insteadOf "git://github"`,
)
require.NoError(t, err)
err = repeatRunE(
ctx,
t,
c,
node,
"building node-postgres",
`cd /mnt/data1/node-postgres/ && sudo yarn && sudo yarn lerna bootstrap`,
)
require.NoError(t, err)
t.Status("running node-postgres tests")
result, err := c.RunWithDetailsSingleNode(ctx, t.L(), node,
fmt.Sprintf(
`cd /mnt/data1/node-postgres/ && sudo \
PGPORT=26257 PGUSER=%s PGSSLMODE=require PGDATABASE=postgres_node_test \
PGSSLCERT=$HOME/certs/client.%s.crt PGSSLKEY=$HOME/certs/client.%s.key PGSSLROOTCERT=$HOME/certs/ca.crt yarn test`,
user, user, user,
),
)
// Fatal for a roachprod or SSH error. A roachprod error is when result.Err==nil.
// Proceed for any other (command) errors
if err != nil && (result.Err == nil || errors.Is(err, rperrors.ErrSSH255)) {
t.Fatal(err)
}
rawResultsStr := result.Stdout + result.Stderr
t.L().Printf("Test Results: %s", rawResultsStr)
if err != nil {
// The one failing test is `pool size of 1` which
// fails because it does SELECT count(*) FROM pg_stat_activity which is
// not implemented in CRDB.
if strings.Contains(rawResultsStr, "1 failing") &&
// Failing tests are listed numerically, we only expect one.
// The one failing test should be "pool size of 1".
strings.Contains(rawResultsStr, "1) pool size of 1") {
err = nil
}
if err != nil {
t.Fatal(err)
}
}
}
r.Add(registry.TestSpec{
Name: "node-postgres",
Owner: registry.OwnerSQLFoundations,
Cluster: r.MakeClusterSpec(1),
Leases: registry.MetamorphicLeases,
Tags: registry.Tags(`default`, `driver`),
Run: func(ctx context.Context, t test.Test, c cluster.Cluster) {
runNodeJSPostgres(ctx, t, c)
},
})
}
| pkg/cmd/roachtest/tests/nodejs_postgres.go | 1 | https://github.com/cockroachdb/cockroach/commit/6e68bdafa7aa5b0f1e507af16bb7b272c881adce | [
0.8502434492111206,
0.050361890345811844,
0.00016637031512800604,
0.002014677971601486,
0.19406242668628693
] |
{
"id": 2,
"code_window": [
"\t\t\tc,\n",
"\t\t\tnode,\n",
"\t\t\t\"add nodesource repository\",\n",
"\t\t\t`sudo apt install ca-certificates && curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -`,\n",
"\t\t); err != nil {\n",
"\t\t\tt.Fatal(err)\n",
"\t\t}\n",
"\n",
"\t\tif err := repeatRunE(\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t`sudo apt install ca-certificates && curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -`,\n"
],
"file_path": "pkg/cmd/roachtest/tests/sequelize.go",
"type": "replace",
"edit_start_line_idx": 98
} | // Copyright 2022 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
// Package eval contains logic to evaluate tree.TypedExpr expressions as
// well as tree.UnaryOp and tree.BinaryOp operators.
package eval
| pkg/sql/sem/eval/doc.go | 0 | https://github.com/cockroachdb/cockroach/commit/6e68bdafa7aa5b0f1e507af16bb7b272c881adce | [
0.00017791555728763342,
0.00017596555699128658,
0.00017401555669493973,
0.00017596555699128658,
0.0000019500002963468432
] |
{
"id": 2,
"code_window": [
"\t\t\tc,\n",
"\t\t\tnode,\n",
"\t\t\t\"add nodesource repository\",\n",
"\t\t\t`sudo apt install ca-certificates && curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -`,\n",
"\t\t); err != nil {\n",
"\t\t\tt.Fatal(err)\n",
"\t\t}\n",
"\n",
"\t\tif err := repeatRunE(\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t`sudo apt install ca-certificates && curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -`,\n"
],
"file_path": "pkg/cmd/roachtest/tests/sequelize.go",
"type": "replace",
"edit_start_line_idx": 98
} | // Copyright 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
export * from "./text";
| pkg/ui/workspaces/db-console/src/components/text/index.ts | 0 | https://github.com/cockroachdb/cockroach/commit/6e68bdafa7aa5b0f1e507af16bb7b272c881adce | [
0.00017698545707389712,
0.00017615052638575435,
0.0001753156102495268,
0.00017615052638575435,
8.349234121851623e-7
] |
{
"id": 2,
"code_window": [
"\t\t\tc,\n",
"\t\t\tnode,\n",
"\t\t\t\"add nodesource repository\",\n",
"\t\t\t`sudo apt install ca-certificates && curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -`,\n",
"\t\t); err != nil {\n",
"\t\t\tt.Fatal(err)\n",
"\t\t}\n",
"\n",
"\t\tif err := repeatRunE(\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t`sudo apt install ca-certificates && curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -`,\n"
],
"file_path": "pkg/cmd/roachtest/tests/sequelize.go",
"type": "replace",
"edit_start_line_idx": 98
} | create-tenant tenant=5
----
# First, establish a few instances.
token-bucket-request tenant=5
instance_id: 7
----
token-bucket-request tenant=5
instance_id: 3
----
token-bucket-request tenant=5
instance_id: 5
----
token-bucket-request tenant=5
instance_id: 9
----
inspect tenant=5
----
Bucket state: ru-burst-limit=0 ru-refill-rate=100 ru-current=10000000 current-share-sum=0
Consumption: ru=0 kvru=0 reads=0 in 0 batches (0 bytes) writes=0 in 0 batches (0 bytes) pod-cpu-usage: 0 secs pgwire-egress=0 bytes external-egress=0 bytes external-ingress=0 bytes
Last update: 00:00:00.000
First active instance: 3
Instance 3: lease="foo" seq=2 shares=0.0 next-instance=5 last-update=00:00:00.000
Instance 5: lease="foo" seq=3 shares=0.0 next-instance=7 last-update=00:00:00.000
Instance 7: lease="foo" seq=1 shares=0.0 next-instance=9 last-update=00:00:00.000
Instance 9: lease="foo" seq=4 shares=0.0 next-instance=0 last-update=00:00:00.000
create-tenant tenant=13
----
token-bucket-request tenant=13
instance_id: 2
----
token-bucket-request tenant=13
instance_id: 8
----
token-bucket-request tenant=13
instance_id: 3
----
inspect tenant=13
----
Bucket state: ru-burst-limit=0 ru-refill-rate=100 ru-current=10000000 current-share-sum=0
Consumption: ru=0 kvru=0 reads=0 in 0 batches (0 bytes) writes=0 in 0 batches (0 bytes) pod-cpu-usage: 0 secs pgwire-egress=0 bytes external-egress=0 bytes external-ingress=0 bytes
Last update: 00:00:00.000
First active instance: 2
Instance 2: lease="foo" seq=5 shares=0.0 next-instance=3 last-update=00:00:00.000
Instance 3: lease="foo" seq=7 shares=0.0 next-instance=8 last-update=00:00:00.000
Instance 8: lease="foo" seq=6 shares=0.0 next-instance=0 last-update=00:00:00.000
# Set up another tenant to verify that the cleanup of one tenant does not
# affect another tenant.
# Advance the time so that all instances look stale; this will allow us to
# verify that only the expected ranges get cleaned up.
advance
5m
----
00:05:00.000
# Pretend that instance 7 died.
token-bucket-request tenant=5
instance_id: 5
next_live_instance_id: 9
----
wait-inspect tenant=5
----
Bucket state: ru-burst-limit=0 ru-refill-rate=100 ru-current=10030000 current-share-sum=0
Consumption: ru=0 kvru=0 reads=0 in 0 batches (0 bytes) writes=0 in 0 batches (0 bytes) pod-cpu-usage: 0 secs pgwire-egress=0 bytes external-egress=0 bytes external-ingress=0 bytes
Last update: 00:05:00.000
First active instance: 3
Instance 3: lease="foo" seq=2 shares=0.0 next-instance=5 last-update=00:00:00.000
Instance 5: lease="foo" seq=8 shares=0.0 next-instance=9 last-update=00:05:00.000
Instance 9: lease="foo" seq=4 shares=0.0 next-instance=0 last-update=00:00:00.000
advance
5m
----
00:10:00.000
# Pretend that the last instance died, while we are creating a new instance 8.
token-bucket-request tenant=5
instance_id: 8
next_live_instance_id: 3
----
wait-inspect tenant=5
----
Bucket state: ru-burst-limit=0 ru-refill-rate=100 ru-current=10060000 current-share-sum=0
Consumption: ru=0 kvru=0 reads=0 in 0 batches (0 bytes) writes=0 in 0 batches (0 bytes) pod-cpu-usage: 0 secs pgwire-egress=0 bytes external-egress=0 bytes external-ingress=0 bytes
Last update: 00:10:00.000
First active instance: 3
Instance 3: lease="foo" seq=2 shares=0.0 next-instance=5 last-update=00:00:00.000
Instance 5: lease="foo" seq=8 shares=0.0 next-instance=8 last-update=00:05:00.000
Instance 8: lease="foo" seq=9 shares=0.0 next-instance=0 last-update=00:10:00.000
advance
5m
----
00:15:00.000
# Pretend that instances 3 and 8 both died.
token-bucket-request tenant=5
instance_id: 5
next_live_instance_id: 5
----
wait-inspect tenant=5
----
Bucket state: ru-burst-limit=0 ru-refill-rate=100 ru-current=10090000 current-share-sum=0
Consumption: ru=0 kvru=0 reads=0 in 0 batches (0 bytes) writes=0 in 0 batches (0 bytes) pod-cpu-usage: 0 secs pgwire-egress=0 bytes external-egress=0 bytes external-ingress=0 bytes
Last update: 00:15:00.000
First active instance: 5
Instance 5: lease="foo" seq=10 shares=0.0 next-instance=0 last-update=00:15:00.000
inspect tenant=13
----
Bucket state: ru-burst-limit=0 ru-refill-rate=100 ru-current=10000000 current-share-sum=0
Consumption: ru=0 kvru=0 reads=0 in 0 batches (0 bytes) writes=0 in 0 batches (0 bytes) pod-cpu-usage: 0 secs pgwire-egress=0 bytes external-egress=0 bytes external-ingress=0 bytes
Last update: 00:00:00.000
First active instance: 2
Instance 2: lease="foo" seq=5 shares=0.0 next-instance=3 last-update=00:00:00.000
Instance 3: lease="foo" seq=7 shares=0.0 next-instance=8 last-update=00:00:00.000
Instance 8: lease="foo" seq=6 shares=0.0 next-instance=0 last-update=00:00:00.000
| pkg/ccl/multitenantccl/tenantcostserver/testdata/cleanup | 0 | https://github.com/cockroachdb/cockroach/commit/6e68bdafa7aa5b0f1e507af16bb7b272c881adce | [
0.00017779378686100245,
0.00017358092009089887,
0.00016673670324962586,
0.00017401520744897425,
0.0000029714904030697653
] |
{
"id": 3,
"code_window": [
"\t\t\tctx,\n",
"\t\t\tt,\n",
"\t\t\tc,\n",
"\t\t\tnode,\n",
"\t\t\t\"add nodesource repository\",\n",
"\t\t\t`sudo apt install ca-certificates && curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -`,\n",
"\t\t); err != nil {\n",
"\t\t\tt.Fatal(err)\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t`sudo apt install ca-certificates && curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -`,\n"
],
"file_path": "pkg/cmd/roachtest/tests/typeorm.go",
"type": "replace",
"edit_start_line_idx": 92
} | // Copyright 2021 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package tests
import (
"context"
"fmt"
"strings"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/cluster"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/option"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/registry"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/test"
rperrors "github.com/cockroachdb/cockroach/pkg/roachprod/errors"
"github.com/cockroachdb/cockroach/pkg/roachprod/install"
"github.com/cockroachdb/errors"
"github.com/stretchr/testify/require"
)
// TODO(richardjcai): Update this to use the repo owned by brianc once
// https://github.com/brianc/node-postgres/pull/2517 is fixed.
// Currently we cannot pass certs through PG env vars, the PR fixes it.
var repoOwner = "richardjcai"
var supportedBranch = "allowing_passing_certs_through_pg_env"
func registerNodeJSPostgres(r registry.Registry) {
runNodeJSPostgres := func(
ctx context.Context,
t test.Test,
c cluster.Cluster,
) {
if c.IsLocal() {
t.Fatal("cannot be run in local mode")
}
node := c.Node(1)
t.Status("setting up cockroach")
err := c.PutE(ctx, t.L(), t.Cockroach(), "./cockroach", c.All())
require.NoError(t, err)
settings := install.MakeClusterSettings(install.SecureOption(true))
err = c.StartE(ctx, t.L(), option.DefaultStartOpts(), settings)
require.NoError(t, err)
const user = "testuser" // certs auto-generated by roachprod start --secure
err = repeatRunE(ctx, t, c, node, "create sql user",
fmt.Sprintf(
`./cockroach sql --certs-dir certs -e "CREATE USER %s CREATEDB"`, user,
))
require.NoError(t, err)
err = repeatRunE(ctx, t, c, node, "create test database",
`./cockroach sql --certs-dir certs -e "CREATE DATABASE postgres_node_test"`,
)
require.NoError(t, err)
version, err := fetchCockroachVersion(ctx, t.L(), c, node[0])
require.NoError(t, err)
err = alterZoneConfigAndClusterSettings(ctx, t, version, c, node[0])
require.NoError(t, err)
err = repeatRunE(
ctx,
t,
c,
node,
"add nodesource repository",
`sudo apt install ca-certificates && curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -`,
)
require.NoError(t, err)
err = repeatRunE(
ctx, t, c, node, "install nodejs and npm", `sudo apt-get -qq install nodejs`,
)
require.NoError(t, err)
err = repeatRunE(
ctx, t, c, node, "update npm", `sudo npm i -g npm`,
)
require.NoError(t, err)
err = repeatRunE(
ctx, t, c, node, "install yarn", `sudo npm i -g yarn`,
)
require.NoError(t, err)
err = repeatRunE(
ctx, t, c, node, "install lerna", `sudo npm i --g lerna`,
)
require.NoError(t, err)
err = repeatRunE(
ctx, t, c, node, "remove old node-postgres", `sudo rm -rf /mnt/data1/node-postgres`,
)
require.NoError(t, err)
err = repeatGitCloneE(
ctx,
t,
c,
fmt.Sprintf("https://github.com/%s/node-postgres.git", repoOwner),
"/mnt/data1/node-postgres",
supportedBranch,
node,
)
require.NoError(t, err)
// The upstream repo hasn't updated its dependencies in light of
// https://github.blog/2021-09-01-improving-git-protocol-security-github/
// so we need this configuration.
err = repeatRunE(
ctx, t, c, node, "configure git to avoid unauthenticated protocol",
`cd /mnt/data1/node-postgres && sudo git config --global url."https://github".insteadOf "git://github"`,
)
require.NoError(t, err)
err = repeatRunE(
ctx,
t,
c,
node,
"building node-postgres",
`cd /mnt/data1/node-postgres/ && sudo yarn && sudo yarn lerna bootstrap`,
)
require.NoError(t, err)
t.Status("running node-postgres tests")
result, err := c.RunWithDetailsSingleNode(ctx, t.L(), node,
fmt.Sprintf(
`cd /mnt/data1/node-postgres/ && sudo \
PGPORT=26257 PGUSER=%s PGSSLMODE=require PGDATABASE=postgres_node_test \
PGSSLCERT=$HOME/certs/client.%s.crt PGSSLKEY=$HOME/certs/client.%s.key PGSSLROOTCERT=$HOME/certs/ca.crt yarn test`,
user, user, user,
),
)
// Fatal for a roachprod or SSH error. A roachprod error is when result.Err==nil.
// Proceed for any other (command) errors
if err != nil && (result.Err == nil || errors.Is(err, rperrors.ErrSSH255)) {
t.Fatal(err)
}
rawResultsStr := result.Stdout + result.Stderr
t.L().Printf("Test Results: %s", rawResultsStr)
if err != nil {
// The one failing test is `pool size of 1` which
// fails because it does SELECT count(*) FROM pg_stat_activity which is
// not implemented in CRDB.
if strings.Contains(rawResultsStr, "1 failing") &&
// Failing tests are listed numerically, we only expect one.
// The one failing test should be "pool size of 1".
strings.Contains(rawResultsStr, "1) pool size of 1") {
err = nil
}
if err != nil {
t.Fatal(err)
}
}
}
r.Add(registry.TestSpec{
Name: "node-postgres",
Owner: registry.OwnerSQLFoundations,
Cluster: r.MakeClusterSpec(1),
Leases: registry.MetamorphicLeases,
Tags: registry.Tags(`default`, `driver`),
Run: func(ctx context.Context, t test.Test, c cluster.Cluster) {
runNodeJSPostgres(ctx, t, c)
},
})
}
| pkg/cmd/roachtest/tests/nodejs_postgres.go | 1 | https://github.com/cockroachdb/cockroach/commit/6e68bdafa7aa5b0f1e507af16bb7b272c881adce | [
0.30179885029792786,
0.018557168543338776,
0.00016608976875431836,
0.001574141439050436,
0.06873950362205505
] |
{
"id": 3,
"code_window": [
"\t\t\tctx,\n",
"\t\t\tt,\n",
"\t\t\tc,\n",
"\t\t\tnode,\n",
"\t\t\t\"add nodesource repository\",\n",
"\t\t\t`sudo apt install ca-certificates && curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -`,\n",
"\t\t); err != nil {\n",
"\t\t\tt.Fatal(err)\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t`sudo apt install ca-certificates && curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -`,\n"
],
"file_path": "pkg/cmd/roachtest/tests/typeorm.go",
"type": "replace",
"edit_start_line_idx": 92
} | 4000,W
4001,X
4002,Y
4003,Z
4004,A
4005,B
4006,C
4007,D
4008,E
4009,F
4010,G
4011,H
4012,I
4013,J
4014,K
4015,L
4016,M
4017,N
4018,O
4019,P
4020,Q
4021,R
4022,S
4023,T
4024,U
4025,V
4026,W
4027,X
4028,Y
4029,Z
4030,A
4031,B
4032,C
4033,D
4034,E
4035,F
4036,G
4037,H
4038,I
4039,J
4040,K
4041,L
4042,M
4043,N
4044,O
4045,P
4046,Q
4047,R
4048,S
4049,T
4050,U
4051,V
4052,W
4053,X
4054,Y
4055,Z
4056,A
4057,B
4058,C
4059,D
4060,E
4061,F
4062,G
4063,H
4064,I
4065,J
4066,K
4067,L
4068,M
4069,N
4070,O
4071,P
4072,Q
4073,R
4074,S
4075,T
4076,U
4077,V
4078,W
4079,X
4080,Y
4081,Z
4082,A
4083,B
4084,C
4085,D
4086,E
4087,F
4088,G
4089,H
4090,I
4091,J
4092,K
4093,L
4094,M
4095,N
4096,O
4097,P
4098,Q
4099,R
4100,S
4101,T
4102,U
4103,V
4104,W
4105,X
4106,Y
4107,Z
4108,A
4109,B
4110,C
4111,D
4112,E
4113,F
4114,G
4115,H
4116,I
4117,J
4118,K
4119,L
4120,M
4121,N
4122,O
4123,P
4124,Q
4125,R
4126,S
4127,T
4128,U
4129,V
4130,W
4131,X
4132,Y
4133,Z
4134,A
4135,B
4136,C
4137,D
4138,E
4139,F
4140,G
4141,H
4142,I
4143,J
4144,K
4145,L
4146,M
4147,N
4148,O
4149,P
4150,Q
4151,R
4152,S
4153,T
4154,U
4155,V
4156,W
4157,X
4158,Y
4159,Z
4160,A
4161,B
4162,C
4163,D
4164,E
4165,F
4166,G
4167,H
4168,I
4169,J
4170,K
4171,L
4172,M
4173,N
4174,O
4175,P
4176,Q
4177,R
4178,S
4179,T
4180,U
4181,V
4182,W
4183,X
4184,Y
4185,Z
4186,A
4187,B
4188,C
4189,D
4190,E
4191,F
4192,G
4193,H
4194,I
4195,J
4196,K
4197,L
4198,M
4199,N
4200,O
4201,P
4202,Q
4203,R
4204,S
4205,T
4206,U
4207,V
4208,W
4209,X
4210,Y
4211,Z
4212,A
4213,B
4214,C
4215,D
4216,E
4217,F
4218,G
4219,H
4220,I
4221,J
4222,K
4223,L
4224,M
4225,N
4226,O
4227,P
4228,Q
4229,R
4230,S
4231,T
4232,U
4233,V
4234,W
4235,X
4236,Y
4237,Z
4238,A
4239,B
4240,C
4241,D
4242,E
4243,F
4244,G
4245,H
4246,I
4247,J
4248,K
4249,L
4250,M
4251,N
4252,O
4253,P
4254,Q
4255,R
4256,S
4257,T
4258,U
4259,V
4260,W
4261,X
4262,Y
4263,Z
4264,A
4265,B
4266,C
4267,D
4268,E
4269,F
4270,G
4271,H
4272,I
4273,J
4274,K
4275,L
4276,M
4277,N
4278,O
4279,P
4280,Q
4281,R
4282,S
4283,T
4284,U
4285,V
4286,W
4287,X
4288,Y
4289,Z
4290,A
4291,B
4292,C
4293,D
4294,E
4295,F
4296,G
4297,H
4298,I
4299,J
4300,K
4301,L
4302,M
4303,N
4304,O
4305,P
4306,Q
4307,R
4308,S
4309,T
4310,U
4311,V
4312,W
4313,X
4314,Y
4315,Z
4316,A
4317,B
4318,C
4319,D
4320,E
4321,F
4322,G
4323,H
4324,I
4325,J
4326,K
4327,L
4328,M
4329,N
4330,O
4331,P
4332,Q
4333,R
4334,S
4335,T
4336,U
4337,V
4338,W
4339,X
4340,Y
4341,Z
4342,A
4343,B
4344,C
4345,D
4346,E
4347,F
4348,G
4349,H
4350,I
4351,J
4352,K
4353,L
4354,M
4355,N
4356,O
4357,P
4358,Q
4359,R
4360,S
4361,T
4362,U
4363,V
4364,W
4365,X
4366,Y
4367,Z
4368,A
4369,B
4370,C
4371,D
4372,E
4373,F
4374,G
4375,H
4376,I
4377,J
4378,K
4379,L
4380,M
4381,N
4382,O
4383,P
4384,Q
4385,R
4386,S
4387,T
4388,U
4389,V
4390,W
4391,X
4392,Y
4393,Z
4394,A
4395,B
4396,C
4397,D
4398,E
4399,F
4400,G
4401,H
4402,I
4403,J
4404,K
4405,L
4406,M
4407,N
4408,O
4409,P
4410,Q
4411,R
4412,S
4413,T
4414,U
4415,V
4416,W
4417,X
4418,Y
4419,Z
4420,A
4421,B
4422,C
4423,D
4424,E
4425,F
4426,G
4427,H
4428,I
4429,J
4430,K
4431,L
4432,M
4433,N
4434,O
4435,P
4436,Q
4437,R
4438,S
4439,T
4440,U
4441,V
4442,W
4443,X
4444,Y
4445,Z
4446,A
4447,B
4448,C
4449,D
4450,E
4451,F
4452,G
4453,H
4454,I
4455,J
4456,K
4457,L
4458,M
4459,N
4460,O
4461,P
4462,Q
4463,R
4464,S
4465,T
4466,U
4467,V
4468,W
4469,X
4470,Y
4471,Z
4472,A
4473,B
4474,C
4475,D
4476,E
4477,F
4478,G
4479,H
4480,I
4481,J
4482,K
4483,L
4484,M
4485,N
4486,O
4487,P
4488,Q
4489,R
4490,S
4491,T
4492,U
4493,V
4494,W
4495,X
4496,Y
4497,Z
4498,A
4499,B
4500,C
4501,D
4502,E
4503,F
4504,G
4505,H
4506,I
4507,J
4508,K
4509,L
4510,M
4511,N
4512,O
4513,P
4514,Q
4515,R
4516,S
4517,T
4518,U
4519,V
4520,W
4521,X
4522,Y
4523,Z
4524,A
4525,B
4526,C
4527,D
4528,E
4529,F
4530,G
4531,H
4532,I
4533,J
4534,K
4535,L
4536,M
4537,N
4538,O
4539,P
4540,Q
4541,R
4542,S
4543,T
4544,U
4545,V
4546,W
4547,X
4548,Y
4549,Z
4550,A
4551,B
4552,C
4553,D
4554,E
4555,F
4556,G
4557,H
4558,I
4559,J
4560,K
4561,L
4562,M
4563,N
4564,O
4565,P
4566,Q
4567,R
4568,S
4569,T
4570,U
4571,V
4572,W
4573,X
4574,Y
4575,Z
4576,A
4577,B
4578,C
4579,D
4580,E
4581,F
4582,G
4583,H
4584,I
4585,J
4586,K
4587,L
4588,M
4589,N
4590,O
4591,P
4592,Q
4593,R
4594,S
4595,T
4596,U
4597,V
4598,W
4599,X
4600,Y
4601,Z
4602,A
4603,B
4604,C
4605,D
4606,E
4607,F
4608,G
4609,H
4610,I
4611,J
4612,K
4613,L
4614,M
4615,N
4616,O
4617,P
4618,Q
4619,R
4620,S
4621,T
4622,U
4623,V
4624,W
4625,X
4626,Y
4627,Z
4628,A
4629,B
4630,C
4631,D
4632,E
4633,F
4634,G
4635,H
4636,I
4637,J
4638,K
4639,L
4640,M
4641,N
4642,O
4643,P
4644,Q
4645,R
4646,S
4647,T
4648,U
4649,V
4650,W
4651,X
4652,Y
4653,Z
4654,A
4655,B
4656,C
4657,D
4658,E
4659,F
4660,G
4661,H
4662,I
4663,J
4664,K
4665,L
4666,M
4667,N
4668,O
4669,P
4670,Q
4671,R
4672,S
4673,T
4674,U
4675,V
4676,W
4677,X
4678,Y
4679,Z
4680,A
4681,B
4682,C
4683,D
4684,E
4685,F
4686,G
4687,H
4688,I
4689,J
4690,K
4691,L
4692,M
4693,N
4694,O
4695,P
4696,Q
4697,R
4698,S
4699,T
4700,U
4701,V
4702,W
4703,X
4704,Y
4705,Z
4706,A
4707,B
4708,C
4709,D
4710,E
4711,F
4712,G
4713,H
4714,I
4715,J
4716,K
4717,L
4718,M
4719,N
4720,O
4721,P
4722,Q
4723,R
4724,S
4725,T
4726,U
4727,V
4728,W
4729,X
4730,Y
4731,Z
4732,A
4733,B
4734,C
4735,D
4736,E
4737,F
4738,G
4739,H
4740,I
4741,J
4742,K
4743,L
4744,M
4745,N
4746,O
4747,P
4748,Q
4749,R
4750,S
4751,T
4752,U
4753,V
4754,W
4755,X
4756,Y
4757,Z
4758,A
4759,B
4760,C
4761,D
4762,E
4763,F
4764,G
4765,H
4766,I
4767,J
4768,K
4769,L
4770,M
4771,N
4772,O
4773,P
4774,Q
4775,R
4776,S
4777,T
4778,U
4779,V
4780,W
4781,X
4782,Y
4783,Z
4784,A
4785,B
4786,C
4787,D
4788,E
4789,F
4790,G
4791,H
4792,I
4793,J
4794,K
4795,L
4796,M
4797,N
4798,O
4799,P
4800,Q
4801,R
4802,S
4803,T
4804,U
4805,V
4806,W
4807,X
4808,Y
4809,Z
4810,A
4811,B
4812,C
4813,D
4814,E
4815,F
4816,G
4817,H
4818,I
4819,J
4820,K
4821,L
4822,M
4823,N
4824,O
4825,P
4826,Q
4827,R
4828,S
4829,T
4830,U
4831,V
4832,W
4833,X
4834,Y
4835,Z
4836,A
4837,B
4838,C
4839,D
4840,E
4841,F
4842,G
4843,H
4844,I
4845,J
4846,K
4847,L
4848,M
4849,N
4850,O
4851,P
4852,Q
4853,R
4854,S
4855,T
4856,U
4857,V
4858,W
4859,X
4860,Y
4861,Z
4862,A
4863,B
4864,C
4865,D
4866,E
4867,F
4868,G
4869,H
4870,I
4871,J
4872,K
4873,L
4874,M
4875,N
4876,O
4877,P
4878,Q
4879,R
4880,S
4881,T
4882,U
4883,V
4884,W
4885,X
4886,Y
4887,Z
4888,A
4889,B
4890,C
4891,D
4892,E
4893,F
4894,G
4895,H
4896,I
4897,J
4898,K
4899,L
4900,M
4901,N
4902,O
4903,P
4904,Q
4905,R
4906,S
4907,T
4908,U
4909,V
4910,W
4911,X
4912,Y
4913,Z
4914,A
4915,B
4916,C
4917,D
4918,E
4919,F
4920,G
4921,H
4922,I
4923,J
4924,K
4925,L
4926,M
4927,N
4928,O
4929,P
4930,Q
4931,R
4932,S
4933,T
4934,U
4935,V
4936,W
4937,X
4938,Y
4939,Z
4940,A
4941,B
4942,C
4943,D
4944,E
4945,F
4946,G
4947,H
4948,I
4949,J
4950,K
4951,L
4952,M
4953,N
4954,O
4955,P
4956,Q
4957,R
4958,S
4959,T
4960,U
4961,V
4962,W
4963,X
4964,Y
4965,Z
4966,A
4967,B
4968,C
4969,D
4970,E
4971,F
4972,G
4973,H
4974,I
4975,J
4976,K
4977,L
4978,M
4979,N
4980,O
4981,P
4982,Q
4983,R
4984,S
4985,T
4986,U
4987,V
4988,W
4989,X
4990,Y
4991,Z
4992,A
4993,B
4994,C
4995,D
4996,E
4997,F
4998,G
4999,H
| pkg/sql/importer/testdata/csv/data-4 | 0 | https://github.com/cockroachdb/cockroach/commit/6e68bdafa7aa5b0f1e507af16bb7b272c881adce | [
0.00018655206076800823,
0.00016595044871792197,
0.0001615202345419675,
0.00016520779172424227,
0.000003849769200314768
] |
{
"id": 3,
"code_window": [
"\t\t\tctx,\n",
"\t\t\tt,\n",
"\t\t\tc,\n",
"\t\t\tnode,\n",
"\t\t\t\"add nodesource repository\",\n",
"\t\t\t`sudo apt install ca-certificates && curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -`,\n",
"\t\t); err != nil {\n",
"\t\t\tt.Fatal(err)\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t`sudo apt install ca-certificates && curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -`,\n"
],
"file_path": "pkg/cmd/roachtest/tests/typeorm.go",
"type": "replace",
"edit_start_line_idx": 92
} | // Copyright 2021 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package server
import (
"context"
"encoding/json"
"net/http"
"strings"
"testing"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/server/apiconstants"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/stretchr/testify/require"
)
func TestUsersV2(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testCluster := serverutils.StartCluster(t, 3, base.TestClusterArgs{})
ctx := context.Background()
defer testCluster.Stopper().Stop(ctx)
ts1 := testCluster.Server(0)
conn := testCluster.ServerConn(0)
_, err := conn.Exec("CREATE USER test;")
require.NoError(t, err)
require.NoError(t, conn.Close())
client, err := ts1.GetAdminHTTPClient()
require.NoError(t, err)
req, err := http.NewRequest("GET", ts1.AdminURL().WithPath(apiconstants.APIV2Path+"users/").String(), nil)
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
require.NotNil(t, resp)
require.Equal(t, 200, resp.StatusCode)
var ur usersResponse
require.NoError(t, json.NewDecoder(resp.Body).Decode(&ur))
require.NoError(t, resp.Body.Close())
require.Equal(t, 3, len(ur.Users))
require.Contains(t, ur.Users, serverpb.UsersResponse_User{Username: "root"})
require.Contains(t, ur.Users, serverpb.UsersResponse_User{Username: "test"})
}
func TestDatabasesTablesV2(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testCluster := serverutils.StartCluster(t, 3, base.TestClusterArgs{})
ctx := context.Background()
defer testCluster.Stopper().Stop(ctx)
ts1 := testCluster.Server(0)
conn := testCluster.ServerConn(0)
_, err := conn.Exec("CREATE DATABASE testdb;")
require.NoError(t, err)
_, err = conn.Exec("CREATE TABLE testdb.testtable (id INTEGER PRIMARY KEY, value STRING);")
require.NoError(t, err)
_, err = conn.Exec("CREATE USER testuser WITH PASSWORD 'testpassword';")
require.NoError(t, err)
_, err = conn.Exec("GRANT ALL ON DATABASE testdb TO testuser;")
require.NoError(t, err)
require.NoError(t, conn.Close())
client, err := ts1.GetAdminHTTPClient()
require.NoError(t, err)
defer client.CloseIdleConnections()
req, err := http.NewRequest("GET", ts1.AdminURL().WithPath(apiconstants.APIV2Path+"databases/").String(), nil)
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
require.NotNil(t, resp)
require.Equal(t, 200, resp.StatusCode)
var dr databasesResponse
require.NoError(t, json.NewDecoder(resp.Body).Decode(&dr))
require.NoError(t, resp.Body.Close())
require.Contains(t, dr.Databases, "testdb")
req, err = http.NewRequest("GET", ts1.AdminURL().WithPath(apiconstants.APIV2Path+"databases/testdb/").String(), nil)
require.NoError(t, err)
resp, err = client.Do(req)
require.NoError(t, err)
require.NotNil(t, resp)
require.Equal(t, 200, resp.StatusCode)
var ddr databaseDetailsResponse
require.NoError(t, json.NewDecoder(resp.Body).Decode(&ddr))
require.NoError(t, resp.Body.Close())
req, err = http.NewRequest("GET", ts1.AdminURL().WithPath(apiconstants.APIV2Path+"databases/testdb/grants/").String(), nil)
require.NoError(t, err)
resp, err = client.Do(req)
require.NoError(t, err)
require.NotNil(t, resp)
require.Equal(t, 200, resp.StatusCode)
var dgr databaseGrantsResponse
require.NoError(t, json.NewDecoder(resp.Body).Decode(&dgr))
require.NoError(t, resp.Body.Close())
require.NotEmpty(t, dgr.Grants)
req, err = http.NewRequest("GET", ts1.AdminURL().WithPath(apiconstants.APIV2Path+"databases/testdb/tables/").String(), nil)
require.NoError(t, err)
resp, err = client.Do(req)
require.NoError(t, err)
require.NotNil(t, resp)
require.Equal(t, 200, resp.StatusCode)
var dtr databaseTablesResponse
require.NoError(t, json.NewDecoder(resp.Body).Decode(&dtr))
require.NoError(t, resp.Body.Close())
require.Contains(t, dtr.TableNames, "public.testtable")
// Test that querying the wrong db name returns 404.
req, err = http.NewRequest("GET", ts1.AdminURL().WithPath(apiconstants.APIV2Path+"databases/testdb2/tables/").String(), nil)
require.NoError(t, err)
resp, err = client.Do(req)
require.NoError(t, err)
require.NotNil(t, resp)
require.Equal(t, 404, resp.StatusCode)
require.NoError(t, resp.Body.Close())
req, err = http.NewRequest("GET", ts1.AdminURL().WithPath(apiconstants.APIV2Path+"databases/testdb/tables/public.testtable/").String(), nil)
require.NoError(t, err)
resp, err = client.Do(req)
require.NoError(t, err)
require.NotNil(t, resp)
require.Equal(t, 200, resp.StatusCode)
var tdr tableDetailsResponse
require.NoError(t, json.NewDecoder(resp.Body).Decode(&tdr))
require.NoError(t, resp.Body.Close())
require.Contains(t, tdr.CreateTableStatement, "value")
var columns []string
for _, c := range tdr.Columns {
columns = append(columns, c.Name)
}
require.Contains(t, columns, "id")
require.Contains(t, columns, "value")
}
func TestEventsV2(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testCluster := serverutils.StartCluster(t, 3, base.TestClusterArgs{})
ctx := context.Background()
defer testCluster.Stopper().Stop(ctx)
ts1 := testCluster.Server(0)
conn := testCluster.ServerConn(0)
_, err := conn.Exec("CREATE DATABASE testdb;")
require.NoError(t, err)
require.NoError(t, conn.Close())
client, err := ts1.GetAdminHTTPClient()
require.NoError(t, err)
req, err := http.NewRequest("GET", ts1.AdminURL().WithPath(apiconstants.APIV2Path+"events/").String(), nil)
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
require.NotNil(t, resp)
require.Equal(t, 200, resp.StatusCode)
var er eventsResponse
require.NoError(t, json.NewDecoder(resp.Body).Decode(&er))
require.NoError(t, resp.Body.Close())
found := false
for _, e := range er.Events {
if e.EventType == "create_database" && strings.Contains(e.Info, "testdb") {
found = true
}
}
require.True(t, found, "create_database event not found")
}
| pkg/server/api_v2_sql_schema_test.go | 0 | https://github.com/cockroachdb/cockroach/commit/6e68bdafa7aa5b0f1e507af16bb7b272c881adce | [
0.0017717446899041533,
0.0005166305927559733,
0.0001576029899297282,
0.00017290326650254428,
0.0006287680007517338
] |
{
"id": 3,
"code_window": [
"\t\t\tctx,\n",
"\t\t\tt,\n",
"\t\t\tc,\n",
"\t\t\tnode,\n",
"\t\t\t\"add nodesource repository\",\n",
"\t\t\t`sudo apt install ca-certificates && curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -`,\n",
"\t\t); err != nil {\n",
"\t\t\tt.Fatal(err)\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t`sudo apt install ca-certificates && curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -`,\n"
],
"file_path": "pkg/cmd/roachtest/tests/typeorm.go",
"type": "replace",
"edit_start_line_idx": 92
} | // Copyright 2022 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package server
import (
"context"
"net"
"net/http"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/server/serverctl"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgwirecancel"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catconstants"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/redact"
)
// onDemandServer represents a server that can be started on demand.
type onDemandServer interface {
orchestratedServer
// getHTTPHandlerFn retrieves the function that can serve HTTP
// requests for this server.
getHTTPHandlerFn() http.HandlerFunc
// handleCancel processes a SQL async cancel query.
handleCancel(ctx context.Context, cancelKey pgwirecancel.BackendKeyData)
// serveConn handles an incoming SQL connection.
serveConn(ctx context.Context, conn net.Conn, status pgwire.PreServeStatus) error
// getSQLAddr returns the SQL address for this server.
getSQLAddr() string
// getRPCAddr() returns the RPC address for this server.
getRPCAddr() string
}
// serverController manages a fleet of multiple servers side-by-side.
// They are instantiated on demand the first time they are accessed.
// Instantiation can fail, e.g. if the target tenant doesn't exist or
// is not active.
type serverController struct {
log.AmbientContext
// nodeID is the node ID of the server where the controller
// is running. This is used for logging only.
nodeID *base.NodeIDContainer
// logger is used to report server start/stop events.
logger nodeEventLogger
// tenantServerCreator instantiates tenant servers.
tenantServerCreator tenantServerCreator
// stopper is the parent stopper.
stopper *stop.Stopper
// st refers to the applicable cluster settings.
st *cluster.Settings
// sendSQLRoutingError is a callback to use to report
// a tenant routing error to the incoming client.
sendSQLRoutingError func(ctx context.Context, conn net.Conn, tenantName roachpb.TenantName)
// draining is set when the surrounding server starts draining, and
// prevents further creation of new tenant servers.
draining syncutil.AtomicBool
// orchestrator is the orchestration method to use.
orchestrator serverOrchestrator
mu struct {
syncutil.Mutex
// servers maps tenant names to the server for that tenant.
//
// TODO(knz): Detect when the mapping of name to tenant ID has
// changed, and invalidate the entry.
servers map[roachpb.TenantName]serverState
// testArgs is used when creating new tenant servers.
testArgs map[roachpb.TenantName]base.TestSharedProcessTenantArgs
// nextServerIdx is the index to provide to the next call to
// newServerFn.
nextServerIdx int
}
}
func newServerController(
ctx context.Context,
ambientCtx log.AmbientContext,
logger nodeEventLogger,
parentNodeID *base.NodeIDContainer,
parentStopper *stop.Stopper,
st *cluster.Settings,
tenantServerCreator tenantServerCreator,
systemServer onDemandServer,
systemTenantNameContainer *roachpb.TenantNameContainer,
sendSQLRoutingError func(ctx context.Context, conn net.Conn, tenantName roachpb.TenantName),
) *serverController {
c := &serverController{
AmbientContext: ambientCtx,
nodeID: parentNodeID,
logger: logger,
st: st,
stopper: parentStopper,
tenantServerCreator: tenantServerCreator,
sendSQLRoutingError: sendSQLRoutingError,
}
c.orchestrator = newServerOrchestrator(parentStopper, c)
c.mu.servers = map[roachpb.TenantName]serverState{
catconstants.SystemTenantName: c.orchestrator.makeServerStateForSystemTenant(systemTenantNameContainer, systemServer),
}
c.mu.testArgs = make(map[roachpb.TenantName]base.TestSharedProcessTenantArgs)
parentStopper.AddCloser(c)
return c
}
// tenantServerWrapper implements the onDemandServer interface for SQLServerWrapper.
type tenantServerWrapper struct {
stopper *stop.Stopper
server *SQLServerWrapper
}
var _ onDemandServer = (*tenantServerWrapper)(nil)
func (t *tenantServerWrapper) annotateCtx(ctx context.Context) context.Context {
return t.server.AnnotateCtx(ctx)
}
func (t *tenantServerWrapper) preStart(ctx context.Context) error {
return t.server.PreStart(ctx)
}
func (t *tenantServerWrapper) acceptClients(ctx context.Context) error {
if err := t.server.AcceptClients(ctx); err != nil {
return err
}
// Show the tenant details in logs.
// TODO(knz): Remove this once we can use a single listener.
return t.server.reportTenantInfo(ctx)
}
func (t *tenantServerWrapper) getHTTPHandlerFn() http.HandlerFunc {
return t.server.http.baseHandler
}
func (t *tenantServerWrapper) getSQLAddr() string {
return t.server.sqlServer.cfg.SQLAdvertiseAddr
}
func (t *tenantServerWrapper) getRPCAddr() string {
return t.server.sqlServer.cfg.AdvertiseAddr
}
func (t *tenantServerWrapper) getTenantID() roachpb.TenantID {
return t.server.sqlCfg.TenantID
}
func (s *tenantServerWrapper) getInstanceID() base.SQLInstanceID {
return s.server.sqlServer.sqlIDContainer.SQLInstanceID()
}
func (s *tenantServerWrapper) shutdownRequested() <-chan serverctl.ShutdownRequest {
return s.server.sqlServer.ShutdownRequested()
}
func (s *tenantServerWrapper) gracefulDrain(
ctx context.Context, verbose bool,
) (uint64, redact.RedactableString, error) {
ctx = s.server.AnnotateCtx(ctx)
return s.server.Drain(ctx, verbose)
}
// systemServerWrapper implements the onDemandServer interface for Server.
//
// (We can imagine a future where the SQL service for the system
// tenant is served using the same code path as any other secondary
// tenant, in which case systemServerWrapper can disappear and we use
// tenantServerWrapper everywhere, but we're not there yet.)
//
// We do not implement the onDemandServer interface methods on *Server
// directly so as to not add noise to its go documentation.
type systemServerWrapper struct {
server *topLevelServer
}
var _ onDemandServer = (*systemServerWrapper)(nil)
func (s *systemServerWrapper) annotateCtx(ctx context.Context) context.Context {
return s.server.AnnotateCtx(ctx)
}
func (s *systemServerWrapper) preStart(ctx context.Context) error {
// No-op: the SQL service for the system tenant is started elsewhere.
return nil
}
func (s *systemServerWrapper) acceptClients(ctx context.Context) error {
// No-op: the SQL service for the system tenant is started elsewhere.
return nil
}
func (t *systemServerWrapper) getHTTPHandlerFn() http.HandlerFunc {
return t.server.http.baseHandler
}
func (s *systemServerWrapper) getSQLAddr() string {
return s.server.sqlServer.cfg.SQLAdvertiseAddr
}
func (s *systemServerWrapper) getRPCAddr() string {
return s.server.sqlServer.cfg.AdvertiseAddr
}
func (s *systemServerWrapper) getTenantID() roachpb.TenantID {
return s.server.cfg.TenantID
}
func (s *systemServerWrapper) getInstanceID() base.SQLInstanceID {
// In system tenant, node ID == instance ID.
return base.SQLInstanceID(s.server.nodeIDContainer.Get())
}
func (s *systemServerWrapper) shutdownRequested() <-chan serverctl.ShutdownRequest {
return nil
}
func (s *systemServerWrapper) gracefulDrain(
ctx context.Context, verbose bool,
) (uint64, redact.RedactableString, error) {
// The controller is not responsible for draining the system tenant.
return 0, "", nil
}
| pkg/server/server_controller.go | 0 | https://github.com/cockroachdb/cockroach/commit/6e68bdafa7aa5b0f1e507af16bb7b272c881adce | [
0.0019975965842604637,
0.0004090537840966135,
0.0001616166700841859,
0.0002055864897556603,
0.0005090160411782563
] |
{
"id": 0,
"code_window": [
"\tcache map[string]*dbStore\n",
"}\n",
"\n",
"var (\n",
"\tglobalID int64\n",
"\tglobalVersionProvider kv.VersionProvider\n",
"\tmc storeCache\n",
"\n",
"\t// ErrDBClosed is the error meaning db is closed and we can use it anymore.\n",
"\tErrDBClosed = errors.New(\"db is closed\")\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tglobalID int64\n",
"\n",
"\tproviderMu sync.Mutex\n"
],
"file_path": "store/localstore/kv.go",
"type": "replace",
"edit_start_line_idx": 52
} | // Copyright 2015 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package localstore
import (
"sync"
"github.com/juju/errors"
"github.com/ngaut/log"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/store/localstore/engine"
"github.com/pingcap/tidb/terror"
"github.com/pingcap/tidb/util/codec"
"github.com/twinj/uuid"
)
var (
_ kv.Storage = (*dbStore)(nil)
)
type dbStore struct {
mu sync.Mutex
snapLock sync.RWMutex
db engine.DB
txns map[uint64]*dbTxn
keysLocked map[string]uint64
uuid string
path string
compactor *localstoreCompactor
closed bool
}
type storeCache struct {
mu sync.Mutex
cache map[string]*dbStore
}
var (
globalID int64
globalVersionProvider kv.VersionProvider
mc storeCache
// ErrDBClosed is the error meaning db is closed and we can use it anymore.
ErrDBClosed = errors.New("db is closed")
)
func init() {
mc.cache = make(map[string]*dbStore)
globalVersionProvider = &LocalVersionProvider{}
}
// Driver implements kv.Driver interface.
type Driver struct {
// engine.Driver is the engine driver for different local db engine.
engine.Driver
}
// IsLocalStore checks whether a storage is local or not.
func IsLocalStore(s kv.Storage) bool {
_, ok := s.(*dbStore)
return ok
}
// Open opens or creates a storage with specific format for a local engine Driver.
func (d Driver) Open(schema string) (kv.Storage, error) {
mc.mu.Lock()
defer mc.mu.Unlock()
if store, ok := mc.cache[schema]; ok {
// TODO: check the cache store has the same engine with this Driver.
log.Info("cache store", schema)
return store, nil
}
db, err := d.Driver.Open(schema)
if err != nil {
return nil, errors.Trace(err)
}
log.Info("New store", schema)
s := &dbStore{
txns: make(map[uint64]*dbTxn),
keysLocked: make(map[string]uint64),
uuid: uuid.NewV4().String(),
path: schema,
db: db,
compactor: newLocalCompactor(localCompactDefaultPolicy, db),
closed: false,
}
mc.cache[schema] = s
s.compactor.Start()
return s, nil
}
func (s *dbStore) UUID() string {
return s.uuid
}
func (s *dbStore) GetSnapshot(ver kv.Version) (kv.MvccSnapshot, error) {
s.snapLock.RLock()
defer s.snapLock.RUnlock()
if s.closed {
return nil, errors.Trace(ErrDBClosed)
}
currentVer, err := globalVersionProvider.CurrentVersion()
if err != nil {
return nil, errors.Trace(err)
}
if ver.Cmp(currentVer) > 0 {
ver = currentVer
}
return &dbSnapshot{
store: s,
db: s.db,
version: ver,
}, nil
}
func (s *dbStore) CurrentVersion() (kv.Version, error) {
return globalVersionProvider.CurrentVersion()
}
// Begin transaction
func (s *dbStore) Begin() (kv.Transaction, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return nil, errors.Trace(ErrDBClosed)
}
beginVer, err := globalVersionProvider.CurrentVersion()
if err != nil {
return nil, errors.Trace(err)
}
txn := &dbTxn{
tid: beginVer.Ver,
valid: true,
store: s,
version: kv.MinVersion,
snapshotVals: make(map[string]struct{}),
opts: make(map[kv.Option]interface{}),
}
log.Debugf("Begin txn:%d", txn.tid)
txn.UnionStore = kv.NewUnionStore(&dbSnapshot{
store: s,
db: s.db,
version: beginVer,
}, options(txn.opts))
return txn, nil
}
func (s *dbStore) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
s.snapLock.Lock()
defer s.snapLock.Unlock()
if s.closed {
return nil
}
s.closed = true
mc.mu.Lock()
defer mc.mu.Unlock()
s.compactor.Stop()
delete(mc.cache, s.path)
return s.db.Close()
}
func (s *dbStore) writeBatch(b engine.Batch) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return errors.Trace(ErrDBClosed)
}
err := s.db.Commit(b)
if err != nil {
log.Error(err)
return errors.Trace(err)
}
return nil
}
func (s *dbStore) newBatch() engine.Batch {
return s.db.NewBatch()
}
// Both lock and unlock are used for simulating scenario of percolator papers.
func (s *dbStore) tryConditionLockKey(tid uint64, key string) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return errors.Trace(ErrDBClosed)
}
if _, ok := s.keysLocked[key]; ok {
return errors.Trace(kv.ErrLockConflict)
}
metaKey := codec.EncodeBytes(nil, []byte(key))
currValue, err := s.db.Get(metaKey)
if terror.ErrorEqual(err, kv.ErrNotExist) {
s.keysLocked[key] = tid
return nil
}
if err != nil {
return errors.Trace(err)
}
// key not exist.
if currValue == nil {
s.keysLocked[key] = tid
return nil
}
_, ver, err := codec.DecodeUint(currValue)
if err != nil {
return errors.Trace(err)
}
// If there's newer version of this key, returns error.
if ver > tid {
log.Warnf("txn:%d, tryLockKey condition not match for key %s, currValue:%q", tid, key, currValue)
return errors.Trace(kv.ErrConditionNotMatch)
}
s.keysLocked[key] = tid
return nil
}
func (s *dbStore) unLockKeys(keys ...string) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return errors.Trace(ErrDBClosed)
}
for _, key := range keys {
if _, ok := s.keysLocked[key]; !ok {
return errors.Trace(kv.ErrNotExist)
}
delete(s.keysLocked, key)
}
return nil
}
| store/localstore/kv.go | 1 | https://github.com/pingcap/tidb/commit/58ad162d3418a8a4d1b08884f23e0cef109b67ff | [
0.9985669255256653,
0.34324076771736145,
0.00016817341384012252,
0.042911097407341,
0.43902572989463806
] |
{
"id": 0,
"code_window": [
"\tcache map[string]*dbStore\n",
"}\n",
"\n",
"var (\n",
"\tglobalID int64\n",
"\tglobalVersionProvider kv.VersionProvider\n",
"\tmc storeCache\n",
"\n",
"\t// ErrDBClosed is the error meaning db is closed and we can use it anymore.\n",
"\tErrDBClosed = errors.New(\"db is closed\")\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tglobalID int64\n",
"\n",
"\tproviderMu sync.Mutex\n"
],
"file_path": "store/localstore/kv.go",
"type": "replace",
"edit_start_line_idx": 52
} | // Copyright 2014 The ql Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSES/QL-LICENSE file.
// Copyright 2015 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package rsets
import (
"strings"
"github.com/juju/errors"
"github.com/pingcap/tidb/context"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/field"
"github.com/pingcap/tidb/plan"
"github.com/pingcap/tidb/plan/plans"
)
var (
_ plan.Planner = (*GroupByRset)(nil)
)
// GroupByRset is record set for group by fields.
type GroupByRset struct {
By []expression.Expression
Src plan.Plan
SelectList *plans.SelectList
}
type groupByVisitor struct {
expression.BaseVisitor
selectList *plans.SelectList
rootIdent *expression.Ident
}
func (v *groupByVisitor) VisitIdent(i *expression.Ident) (expression.Expression, error) {
// Group by ambiguous rule:
// select c1 as a, c2 as a from t group by a is ambiguous
// select c1 as a, c2 as a from t group by a + 1 is ambiguous
// select c1 as c2, c2 from t group by c2 is ambiguous
// select c1 as c2, c2 from t group by c2 + 1 is not ambiguous
var (
index int
err error
)
if v.rootIdent == i {
// The group by is an identifier, we must check it first.
index, err = checkIdentAmbiguous(i, v.selectList, GroupByClause)
if err != nil {
return nil, errors.Trace(err)
}
}
// first find this identifier in FROM.
idx := field.GetResultFieldIndex(i.L, v.selectList.FromFields)
if len(idx) > 0 {
i.ReferScope = expression.IdentReferFromTable
i.ReferIndex = idx[0]
return i, nil
}
if v.rootIdent != i {
// This identifier is the part of the group by, check ambiguous here.
index, err = checkIdentAmbiguous(i, v.selectList, GroupByClause)
if err != nil {
return nil, errors.Trace(err)
}
}
// try to find in select list, we have got index using checkIdent before.
if index >= 0 {
// group by can not reference aggregate fields
if _, ok := v.selectList.AggFields[index]; ok {
return nil, errors.Errorf("Reference '%s' not supported (reference to group function)", i)
}
// find in select list
i.ReferScope = expression.IdentReferSelectList
i.ReferIndex = index
return i, nil
}
// TODO: check in out query
return i, errors.Errorf("Unknown column '%s' in 'group statement'", i)
}
func (v *groupByVisitor) VisitCall(c *expression.Call) (expression.Expression, error) {
ok := expression.IsAggregateFunc(c.F)
if ok {
return nil, errors.Errorf("group by cannot contain aggregate function %s", c)
}
var err error
for i, e := range c.Args {
c.Args[i], err = e.Accept(v)
if err != nil {
return nil, errors.Trace(err)
}
}
return c, nil
}
// Plan gets GroupByDefaultPlan.
func (r *GroupByRset) Plan(ctx context.Context) (plan.Plan, error) {
if err := updateSelectFieldsRefer(r.SelectList); err != nil {
return nil, errors.Trace(err)
}
visitor := &groupByVisitor{}
visitor.BaseVisitor.V = visitor
visitor.selectList = r.SelectList
for i, e := range r.By {
pos, err := castPosition(e, r.SelectList, GroupByClause)
if err != nil {
return nil, errors.Trace(err)
}
if pos != nil {
// use Position expression for the associated field.
r.By[i] = pos
continue
}
visitor.rootIdent = castIdent(e)
by, err := e.Accept(visitor)
if err != nil {
return nil, errors.Trace(err)
}
r.By[i] = by
}
return &plans.GroupByDefaultPlan{By: r.By, Src: r.Src,
SelectList: r.SelectList}, nil
}
func (r *GroupByRset) String() string {
a := make([]string, len(r.By))
for i, v := range r.By {
a[i] = v.String()
}
return strings.Join(a, ", ")
}
| rset/rsets/groupby.go | 0 | https://github.com/pingcap/tidb/commit/58ad162d3418a8a4d1b08884f23e0cef109b67ff | [
0.017449840903282166,
0.002358525525778532,
0.00016748720372561365,
0.00017337239114567637,
0.005073360167443752
] |
{
"id": 0,
"code_window": [
"\tcache map[string]*dbStore\n",
"}\n",
"\n",
"var (\n",
"\tglobalID int64\n",
"\tglobalVersionProvider kv.VersionProvider\n",
"\tmc storeCache\n",
"\n",
"\t// ErrDBClosed is the error meaning db is closed and we can use it anymore.\n",
"\tErrDBClosed = errors.New(\"db is closed\")\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tglobalID int64\n",
"\n",
"\tproviderMu sync.Mutex\n"
],
"file_path": "store/localstore/kv.go",
"type": "replace",
"edit_start_line_idx": 52
} | // Copyright 2015 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"database/sql"
"testing"
_ "github.com/go-sql-driver/mysql"
. "github.com/pingcap/check"
)
func TestT(t *testing.T) {
TestingT(t)
}
var regression = true
var dsn = "root@tcp(localhost:4001)/test?strict=true"
func runTests(c *C, dsn string, tests ...func(dbt *DBTest)) {
db, err := sql.Open("mysql", dsn)
c.Assert(err, IsNil, Commentf("Error connecting"))
defer db.Close()
db.Exec("DROP TABLE IF EXISTS test")
dbt := &DBTest{c, db}
for _, test := range tests {
test(dbt)
dbt.db.Exec("DROP TABLE IF EXISTS test")
}
}
type DBTest struct {
*C
db *sql.DB
}
func (dbt *DBTest) fail(method, query string, err error) {
if len(query) > 300 {
query = "[query too large to print]"
}
dbt.Fatalf("Error on %s %s: %s", method, query, err.Error())
}
func (dbt *DBTest) mustExec(query string, args ...interface{}) (res sql.Result) {
res, err := dbt.db.Exec(query, args...)
dbt.Assert(err, IsNil, Commentf("Exec %s", query))
return res
}
func (dbt *DBTest) mustQuery(query string, args ...interface{}) (rows *sql.Rows) {
rows, err := dbt.db.Query(query, args...)
dbt.Assert(err, IsNil, Commentf("Query %s", query))
return rows
}
func (dbt *DBTest) mustQueryRows(query string, args ...interface{}) {
rows := dbt.mustQuery(query, args...)
dbt.Assert(rows.Next(), IsTrue)
rows.Close()
}
func runTestRegression(c *C) {
runTests(c, dsn, func(dbt *DBTest) {
// Create Table
dbt.mustExec("CREATE TABLE test (val TINYINT)")
// Test for unexpected data
var out bool
rows := dbt.mustQuery("SELECT * FROM test")
dbt.Assert(rows.Next(), IsFalse, Commentf("unexpected data in empty table"))
// Create Data
res := dbt.mustExec("INSERT INTO test VALUES (1)")
// res := dbt.mustExec("INSERT INTO test VALUES (?)", 1)
count, err := res.RowsAffected()
dbt.Assert(err, IsNil)
dbt.Check(count, Equals, int64(1))
id, err := res.LastInsertId()
dbt.Assert(err, IsNil)
dbt.Check(id, Equals, int64(0))
// Read
rows = dbt.mustQuery("SELECT val FROM test")
if rows.Next() {
rows.Scan(&out)
dbt.Check(out, IsTrue)
dbt.Check(rows.Next(), IsFalse, Commentf("unexpected data"))
} else {
dbt.Error("no data")
}
rows.Close()
// Update
res = dbt.mustExec("UPDATE test SET val = 0 WHERE val = ?", 1)
count, err = res.RowsAffected()
dbt.Assert(err, IsNil)
dbt.Check(count, Equals, int64(1))
// Check Update
rows = dbt.mustQuery("SELECT val FROM test")
if rows.Next() {
rows.Scan(&out)
dbt.Check(out, IsFalse)
dbt.Check(rows.Next(), IsFalse, Commentf("unexpected data"))
} else {
dbt.Error("no data")
}
rows.Close()
// Delete
res = dbt.mustExec("DELETE FROM test WHERE val = 0")
// res = dbt.mustExec("DELETE FROM test WHERE val = ?", 0)
count, err = res.RowsAffected()
dbt.Assert(err, IsNil)
dbt.Check(count, Equals, int64(1))
// Check for unexpected rows
res = dbt.mustExec("DELETE FROM test")
count, err = res.RowsAffected()
dbt.Assert(err, IsNil)
dbt.Check(count, Equals, int64(0))
dbt.mustQueryRows("SELECT 1")
b := []byte{}
if err := dbt.db.QueryRow("SELECT ?", b).Scan(&b); err != nil {
dbt.Fatal(err)
}
if b == nil {
dbt.Error("nil echo from non-nil input")
}
})
}
func runTestPrepareResultFieldType(t *C) {
var param int64 = 83
runTests(t, dsn, func(dbt *DBTest) {
stmt, err := dbt.db.Prepare(`SELECT ?`)
if err != nil {
dbt.Fatal(err)
}
defer stmt.Close()
row := stmt.QueryRow(param)
var result int64
err = row.Scan(&result)
if err != nil {
dbt.Fatal(err)
}
switch {
case result != param:
dbt.Fatal("Unexpected result value")
}
})
}
func runTestSpecialType(t *C) {
runTests(t, dsn, func(dbt *DBTest) {
dbt.mustExec("create table test (a decimal(10, 5), b datetime, c time)")
dbt.mustExec("insert test values (1.4, '2012-12-21 12:12:12', '4:23:34')")
rows := dbt.mustQuery("select * from test where a > ?", 0)
t.Assert(rows.Next(), IsTrue)
var outA float64
var outB, outC string
err := rows.Scan(&outA, &outB, &outC)
t.Assert(err, IsNil)
t.Assert(outA, Equals, 1.4)
t.Assert(outB, Equals, "2012-12-21 12:12:12")
t.Assert(outC, Equals, "04:23:34")
})
}
func runTestPreparedString(t *C) {
runTests(t, dsn, func(dbt *DBTest) {
dbt.mustExec("create table test (a char(10), b char(10))")
dbt.mustExec("insert test values (?, ?)", "abcdeabcde", "abcde")
rows := dbt.mustQuery("select * from test where 1 = ?", 1)
t.Assert(rows.Next(), IsTrue)
var outA, outB string
err := rows.Scan(&outA, &outB)
t.Assert(err, IsNil)
t.Assert(outA, Equals, "abcdeabcde")
t.Assert(outB, Equals, "abcde")
})
}
func runTestConcurrentUpdate(c *C) {
runTests(c, dsn, func(dbt *DBTest) {
dbt.mustExec("create table test (a int, b int)")
dbt.mustExec("insert test values (1, 1)")
txn1, err := dbt.db.Begin()
c.Assert(err, IsNil)
txn2, err := dbt.db.Begin()
c.Assert(err, IsNil)
_, err = txn2.Exec("update test set a = a + 1 where b = 1")
c.Assert(err, IsNil)
err = txn2.Commit()
c.Assert(err, IsNil)
_, err = txn1.Exec("update test set a = a + 1 where b = 1")
c.Assert(err, IsNil)
err = txn1.Commit()
c.Assert(err, IsNil)
})
}
func runTestAuth(c *C) {
runTests(c, dsn, func(dbt *DBTest) {
dbt.mustExec(`CREATE USER 'test'@'127.0.0.1' IDENTIFIED BY '123';`)
dbt.mustExec(`CREATE USER 'test'@'localhost' IDENTIFIED BY '123';`)
dbt.mustExec(`CREATE USER 'test'@'::1' IDENTIFIED BY '123';`)
})
newDsn := "test:123@tcp(localhost:4001)/test?strict=true"
runTests(c, newDsn, func(dbt *DBTest) {
dbt.mustExec(`USE mysql;`)
})
db, err := sql.Open("mysql", "test:456@tcp(localhost:4001)/test?strict=true")
_, err = db.Query("USE mysql;")
c.Assert(err, NotNil, Commentf("Wrong password should be failed"))
db.Close()
}
func runTestIssues(c *C) {
// For issue #263
unExistsSchemaDsn := "root@tcp(localhost:4001)/unexists_schema?strict=true"
db, err := sql.Open("mysql", unExistsSchemaDsn)
c.Assert(db, NotNil)
c.Assert(err, IsNil)
// Open may just validate its arguments without creating a connection to the database. To verify that the data source name is valid, call Ping.
err = db.Ping()
c.Assert(err, NotNil, Commentf("Connecting to an unexists schema should be error"))
db.Close()
}
| tidb-server/server/server_test.go | 0 | https://github.com/pingcap/tidb/commit/58ad162d3418a8a4d1b08884f23e0cef109b67ff | [
0.03514131158590317,
0.0020117564126849174,
0.00016819506708998233,
0.00019219589012209326,
0.006716920994222164
] |
{
"id": 0,
"code_window": [
"\tcache map[string]*dbStore\n",
"}\n",
"\n",
"var (\n",
"\tglobalID int64\n",
"\tglobalVersionProvider kv.VersionProvider\n",
"\tmc storeCache\n",
"\n",
"\t// ErrDBClosed is the error meaning db is closed and we can use it anymore.\n",
"\tErrDBClosed = errors.New(\"db is closed\")\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tglobalID int64\n",
"\n",
"\tproviderMu sync.Mutex\n"
],
"file_path": "store/localstore/kv.go",
"type": "replace",
"edit_start_line_idx": 52
} | package check
import (
"fmt"
"strings"
"time"
)
// TestName returns the current test name in the form "SuiteName.TestName"
func (c *C) TestName() string {
return c.testName
}
// -----------------------------------------------------------------------
// Basic succeeding/failing logic.
// Failed returns whether the currently running test has already failed.
func (c *C) Failed() bool {
return c.status() == failedSt
}
// Fail marks the currently running test as failed.
//
// Something ought to have been previously logged so the developer can tell
// what went wrong. The higher level helper functions will fail the test
// and do the logging properly.
func (c *C) Fail() {
c.setStatus(failedSt)
}
// FailNow marks the currently running test as failed and stops running it.
// Something ought to have been previously logged so the developer can tell
// what went wrong. The higher level helper functions will fail the test
// and do the logging properly.
func (c *C) FailNow() {
c.Fail()
c.stopNow()
}
// Succeed marks the currently running test as succeeded, undoing any
// previous failures.
func (c *C) Succeed() {
c.setStatus(succeededSt)
}
// SucceedNow marks the currently running test as succeeded, undoing any
// previous failures, and stops running the test.
func (c *C) SucceedNow() {
c.Succeed()
c.stopNow()
}
// ExpectFailure informs that the running test is knowingly broken for
// the provided reason. If the test does not fail, an error will be reported
// to raise attention to this fact. This method is useful to temporarily
// disable tests which cover well known problems until a better time to
// fix the problem is found, without forgetting about the fact that a
// failure still exists.
func (c *C) ExpectFailure(reason string) {
if reason == "" {
panic("Missing reason why the test is expected to fail")
}
c.mustFail = true
c.reason = reason
}
// Skip skips the running test for the provided reason. If run from within
// SetUpTest, the individual test being set up will be skipped, and if run
// from within SetUpSuite, the whole suite is skipped.
func (c *C) Skip(reason string) {
if reason == "" {
panic("Missing reason why the test is being skipped")
}
c.reason = reason
c.setStatus(skippedSt)
c.stopNow()
}
// -----------------------------------------------------------------------
// Basic logging.
// GetTestLog returns the current test error output.
func (c *C) GetTestLog() string {
return c.logb.String()
}
// Log logs some information into the test error output.
// The provided arguments are assembled together into a string with fmt.Sprint.
func (c *C) Log(args ...interface{}) {
c.log(args...)
}
// Log logs some information into the test error output.
// The provided arguments are assembled together into a string with fmt.Sprintf.
func (c *C) Logf(format string, args ...interface{}) {
c.logf(format, args...)
}
// Output enables *C to be used as a logger in functions that require only
// the minimum interface of *log.Logger.
func (c *C) Output(calldepth int, s string) error {
d := time.Now().Sub(c.startTime)
msec := d / time.Millisecond
sec := d / time.Second
min := d / time.Minute
c.Logf("[LOG] %d:%02d.%03d %s", min, sec%60, msec%1000, s)
return nil
}
// Error logs an error into the test error output and marks the test as failed.
// The provided arguments are assembled together into a string with fmt.Sprint.
func (c *C) Error(args ...interface{}) {
c.logCaller(1)
c.logString(fmt.Sprint("Error: ", fmt.Sprint(args...)))
c.logNewLine()
c.Fail()
}
// Errorf logs an error into the test error output and marks the test as failed.
// The provided arguments are assembled together into a string with fmt.Sprintf.
func (c *C) Errorf(format string, args ...interface{}) {
c.logCaller(1)
c.logString(fmt.Sprintf("Error: "+format, args...))
c.logNewLine()
c.Fail()
}
// Fatal logs an error into the test error output, marks the test as failed, and
// stops the test execution. The provided arguments are assembled together into
// a string with fmt.Sprint.
func (c *C) Fatal(args ...interface{}) {
c.logCaller(1)
c.logString(fmt.Sprint("Error: ", fmt.Sprint(args...)))
c.logNewLine()
c.FailNow()
}
// Fatlaf logs an error into the test error output, marks the test as failed, and
// stops the test execution. The provided arguments are assembled together into
// a string with fmt.Sprintf.
func (c *C) Fatalf(format string, args ...interface{}) {
c.logCaller(1)
c.logString(fmt.Sprint("Error: ", fmt.Sprintf(format, args...)))
c.logNewLine()
c.FailNow()
}
// -----------------------------------------------------------------------
// Generic checks and assertions based on checkers.
// Check verifies if the first value matches the expected value according
// to the provided checker. If they do not match, an error is logged, the
// test is marked as failed, and the test execution continues.
//
// Some checkers may not need the expected argument (e.g. IsNil).
//
// Extra arguments provided to the function are logged next to the reported
// problem when the matching fails.
func (c *C) Check(obtained interface{}, checker Checker, args ...interface{}) bool {
return c.internalCheck("Check", obtained, checker, args...)
}
// Assert ensures that the first value matches the expected value according
// to the provided checker. If they do not match, an error is logged, the
// test is marked as failed, and the test execution stops.
//
// Some checkers may not need the expected argument (e.g. IsNil).
//
// Extra arguments provided to the function are logged next to the reported
// problem when the matching fails.
func (c *C) Assert(obtained interface{}, checker Checker, args ...interface{}) {
if !c.internalCheck("Assert", obtained, checker, args...) {
c.stopNow()
}
}
func (c *C) internalCheck(funcName string, obtained interface{}, checker Checker, args ...interface{}) bool {
if checker == nil {
c.logCaller(2)
c.logString(fmt.Sprintf("%s(obtained, nil!?, ...):", funcName))
c.logString("Oops.. you've provided a nil checker!")
c.logNewLine()
c.Fail()
return false
}
// If the last argument is a bug info, extract it out.
var comment CommentInterface
if len(args) > 0 {
if c, ok := args[len(args)-1].(CommentInterface); ok {
comment = c
args = args[:len(args)-1]
}
}
params := append([]interface{}{obtained}, args...)
info := checker.Info()
if len(params) != len(info.Params) {
names := append([]string{info.Params[0], info.Name}, info.Params[1:]...)
c.logCaller(2)
c.logString(fmt.Sprintf("%s(%s):", funcName, strings.Join(names, ", ")))
c.logString(fmt.Sprintf("Wrong number of parameters for %s: want %d, got %d", info.Name, len(names), len(params)+1))
c.logNewLine()
c.Fail()
return false
}
// Copy since it may be mutated by Check.
names := append([]string{}, info.Params...)
// Do the actual check.
result, error := checker.Check(params, names)
if !result || error != "" {
c.logCaller(2)
for i := 0; i != len(params); i++ {
c.logValue(names[i], params[i])
}
if comment != nil {
c.logString(comment.CheckCommentString())
}
if error != "" {
c.logString(error)
}
c.logNewLine()
c.Fail()
return false
}
return true
}
| Godeps/_workspace/src/github.com/pingcap/check/helpers.go | 0 | https://github.com/pingcap/tidb/commit/58ad162d3418a8a4d1b08884f23e0cef109b67ff | [
0.0013456335291266441,
0.0002445333229843527,
0.00016593020700383931,
0.0001722917950246483,
0.00024105426564347
] |
{
"id": 1,
"code_window": [
"\t_, ok := s.(*dbStore)\n",
"\treturn ok\n",
"}\n",
"\n",
"// Open opens or creates a storage with specific format for a local engine Driver.\n",
"func (d Driver) Open(schema string) (kv.Storage, error) {\n",
"\tmc.mu.Lock()\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"func lockVersionProvider() {\n",
"\tproviderMu.Lock()\n",
"}\n",
"\n",
"func unlockVersionProvider() {\n",
"\tproviderMu.Unlock()\n",
"}\n",
"\n"
],
"file_path": "store/localstore/kv.go",
"type": "add",
"edit_start_line_idx": 77
} | // Copyright 2015 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package localstore
import (
"sync"
"github.com/juju/errors"
"github.com/ngaut/log"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/store/localstore/engine"
"github.com/pingcap/tidb/terror"
"github.com/pingcap/tidb/util/codec"
"github.com/twinj/uuid"
)
var (
_ kv.Storage = (*dbStore)(nil)
)
type dbStore struct {
mu sync.Mutex
snapLock sync.RWMutex
db engine.DB
txns map[uint64]*dbTxn
keysLocked map[string]uint64
uuid string
path string
compactor *localstoreCompactor
closed bool
}
type storeCache struct {
mu sync.Mutex
cache map[string]*dbStore
}
var (
globalID int64
globalVersionProvider kv.VersionProvider
mc storeCache
// ErrDBClosed is the error meaning db is closed and we can use it anymore.
ErrDBClosed = errors.New("db is closed")
)
func init() {
mc.cache = make(map[string]*dbStore)
globalVersionProvider = &LocalVersionProvider{}
}
// Driver implements kv.Driver interface.
type Driver struct {
// engine.Driver is the engine driver for different local db engine.
engine.Driver
}
// IsLocalStore checks whether a storage is local or not.
func IsLocalStore(s kv.Storage) bool {
_, ok := s.(*dbStore)
return ok
}
// Open opens or creates a storage with specific format for a local engine Driver.
func (d Driver) Open(schema string) (kv.Storage, error) {
mc.mu.Lock()
defer mc.mu.Unlock()
if store, ok := mc.cache[schema]; ok {
// TODO: check the cache store has the same engine with this Driver.
log.Info("cache store", schema)
return store, nil
}
db, err := d.Driver.Open(schema)
if err != nil {
return nil, errors.Trace(err)
}
log.Info("New store", schema)
s := &dbStore{
txns: make(map[uint64]*dbTxn),
keysLocked: make(map[string]uint64),
uuid: uuid.NewV4().String(),
path: schema,
db: db,
compactor: newLocalCompactor(localCompactDefaultPolicy, db),
closed: false,
}
mc.cache[schema] = s
s.compactor.Start()
return s, nil
}
func (s *dbStore) UUID() string {
return s.uuid
}
func (s *dbStore) GetSnapshot(ver kv.Version) (kv.MvccSnapshot, error) {
s.snapLock.RLock()
defer s.snapLock.RUnlock()
if s.closed {
return nil, errors.Trace(ErrDBClosed)
}
currentVer, err := globalVersionProvider.CurrentVersion()
if err != nil {
return nil, errors.Trace(err)
}
if ver.Cmp(currentVer) > 0 {
ver = currentVer
}
return &dbSnapshot{
store: s,
db: s.db,
version: ver,
}, nil
}
func (s *dbStore) CurrentVersion() (kv.Version, error) {
return globalVersionProvider.CurrentVersion()
}
// Begin transaction
func (s *dbStore) Begin() (kv.Transaction, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return nil, errors.Trace(ErrDBClosed)
}
beginVer, err := globalVersionProvider.CurrentVersion()
if err != nil {
return nil, errors.Trace(err)
}
txn := &dbTxn{
tid: beginVer.Ver,
valid: true,
store: s,
version: kv.MinVersion,
snapshotVals: make(map[string]struct{}),
opts: make(map[kv.Option]interface{}),
}
log.Debugf("Begin txn:%d", txn.tid)
txn.UnionStore = kv.NewUnionStore(&dbSnapshot{
store: s,
db: s.db,
version: beginVer,
}, options(txn.opts))
return txn, nil
}
func (s *dbStore) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
s.snapLock.Lock()
defer s.snapLock.Unlock()
if s.closed {
return nil
}
s.closed = true
mc.mu.Lock()
defer mc.mu.Unlock()
s.compactor.Stop()
delete(mc.cache, s.path)
return s.db.Close()
}
func (s *dbStore) writeBatch(b engine.Batch) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return errors.Trace(ErrDBClosed)
}
err := s.db.Commit(b)
if err != nil {
log.Error(err)
return errors.Trace(err)
}
return nil
}
func (s *dbStore) newBatch() engine.Batch {
return s.db.NewBatch()
}
// Both lock and unlock are used for simulating scenario of percolator papers.
func (s *dbStore) tryConditionLockKey(tid uint64, key string) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return errors.Trace(ErrDBClosed)
}
if _, ok := s.keysLocked[key]; ok {
return errors.Trace(kv.ErrLockConflict)
}
metaKey := codec.EncodeBytes(nil, []byte(key))
currValue, err := s.db.Get(metaKey)
if terror.ErrorEqual(err, kv.ErrNotExist) {
s.keysLocked[key] = tid
return nil
}
if err != nil {
return errors.Trace(err)
}
// key not exist.
if currValue == nil {
s.keysLocked[key] = tid
return nil
}
_, ver, err := codec.DecodeUint(currValue)
if err != nil {
return errors.Trace(err)
}
// If there's newer version of this key, returns error.
if ver > tid {
log.Warnf("txn:%d, tryLockKey condition not match for key %s, currValue:%q", tid, key, currValue)
return errors.Trace(kv.ErrConditionNotMatch)
}
s.keysLocked[key] = tid
return nil
}
func (s *dbStore) unLockKeys(keys ...string) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return errors.Trace(ErrDBClosed)
}
for _, key := range keys {
if _, ok := s.keysLocked[key]; !ok {
return errors.Trace(kv.ErrNotExist)
}
delete(s.keysLocked, key)
}
return nil
}
| store/localstore/kv.go | 1 | https://github.com/pingcap/tidb/commit/58ad162d3418a8a4d1b08884f23e0cef109b67ff | [
0.9979099631309509,
0.14722216129302979,
0.00016884051728993654,
0.006179294548928738,
0.3282134532928467
] |
{
"id": 1,
"code_window": [
"\t_, ok := s.(*dbStore)\n",
"\treturn ok\n",
"}\n",
"\n",
"// Open opens or creates a storage with specific format for a local engine Driver.\n",
"func (d Driver) Open(schema string) (kv.Storage, error) {\n",
"\tmc.mu.Lock()\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"func lockVersionProvider() {\n",
"\tproviderMu.Lock()\n",
"}\n",
"\n",
"func unlockVersionProvider() {\n",
"\tproviderMu.Unlock()\n",
"}\n",
"\n"
],
"file_path": "store/localstore/kv.go",
"type": "add",
"edit_start_line_idx": 77
} | // Copyright (c) 2012, Suryandaru Triandana <[email protected]>
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package leveldb
import (
"errors"
"math/rand"
"runtime"
"sync"
"sync/atomic"
"github.com/syndtr/goleveldb/leveldb/iterator"
"github.com/syndtr/goleveldb/leveldb/opt"
"github.com/syndtr/goleveldb/leveldb/util"
)
var (
errInvalidIkey = errors.New("leveldb: Iterator: invalid internal key")
)
type memdbReleaser struct {
once sync.Once
m *memDB
}
func (mr *memdbReleaser) Release() {
mr.once.Do(func() {
mr.m.decref()
})
}
func (db *DB) newRawIterator(slice *util.Range, ro *opt.ReadOptions) iterator.Iterator {
em, fm := db.getMems()
v := db.s.version()
ti := v.getIterators(slice, ro)
n := len(ti) + 2
i := make([]iterator.Iterator, 0, n)
emi := em.NewIterator(slice)
emi.SetReleaser(&memdbReleaser{m: em})
i = append(i, emi)
if fm != nil {
fmi := fm.NewIterator(slice)
fmi.SetReleaser(&memdbReleaser{m: fm})
i = append(i, fmi)
}
i = append(i, ti...)
strict := opt.GetStrict(db.s.o.Options, ro, opt.StrictReader)
mi := iterator.NewMergedIterator(i, db.s.icmp, strict)
mi.SetReleaser(&versionReleaser{v: v})
return mi
}
func (db *DB) newIterator(seq uint64, slice *util.Range, ro *opt.ReadOptions) *dbIter {
var islice *util.Range
if slice != nil {
islice = &util.Range{}
if slice.Start != nil {
islice.Start = newIkey(slice.Start, kMaxSeq, ktSeek)
}
if slice.Limit != nil {
islice.Limit = newIkey(slice.Limit, kMaxSeq, ktSeek)
}
}
rawIter := db.newRawIterator(islice, ro)
iter := &dbIter{
db: db,
icmp: db.s.icmp,
iter: rawIter,
seq: seq,
strict: opt.GetStrict(db.s.o.Options, ro, opt.StrictReader),
key: make([]byte, 0),
value: make([]byte, 0),
}
atomic.AddInt32(&db.aliveIters, 1)
runtime.SetFinalizer(iter, (*dbIter).Release)
return iter
}
func (db *DB) iterSamplingRate() int {
return rand.Intn(2 * db.s.o.GetIteratorSamplingRate())
}
type dir int
const (
dirReleased dir = iota - 1
dirSOI
dirEOI
dirBackward
dirForward
)
// dbIter represent an interator states over a database session.
type dbIter struct {
db *DB
icmp *iComparer
iter iterator.Iterator
seq uint64
strict bool
smaplingGap int
dir dir
key []byte
value []byte
err error
releaser util.Releaser
}
func (i *dbIter) sampleSeek() {
ikey := i.iter.Key()
i.smaplingGap -= len(ikey) + len(i.iter.Value())
for i.smaplingGap < 0 {
i.smaplingGap += i.db.iterSamplingRate()
i.db.sampleSeek(ikey)
}
}
func (i *dbIter) setErr(err error) {
i.err = err
i.key = nil
i.value = nil
}
func (i *dbIter) iterErr() {
if err := i.iter.Error(); err != nil {
i.setErr(err)
}
}
func (i *dbIter) Valid() bool {
return i.err == nil && i.dir > dirEOI
}
func (i *dbIter) First() bool {
if i.err != nil {
return false
} else if i.dir == dirReleased {
i.err = ErrIterReleased
return false
}
if i.iter.First() {
i.dir = dirSOI
return i.next()
}
i.dir = dirEOI
i.iterErr()
return false
}
func (i *dbIter) Last() bool {
if i.err != nil {
return false
} else if i.dir == dirReleased {
i.err = ErrIterReleased
return false
}
if i.iter.Last() {
return i.prev()
}
i.dir = dirSOI
i.iterErr()
return false
}
func (i *dbIter) Seek(key []byte) bool {
if i.err != nil {
return false
} else if i.dir == dirReleased {
i.err = ErrIterReleased
return false
}
ikey := newIkey(key, i.seq, ktSeek)
if i.iter.Seek(ikey) {
i.dir = dirSOI
return i.next()
}
i.dir = dirEOI
i.iterErr()
return false
}
func (i *dbIter) next() bool {
for {
if ukey, seq, kt, kerr := parseIkey(i.iter.Key()); kerr == nil {
i.sampleSeek()
if seq <= i.seq {
switch kt {
case ktDel:
// Skip deleted key.
i.key = append(i.key[:0], ukey...)
i.dir = dirForward
case ktVal:
if i.dir == dirSOI || i.icmp.uCompare(ukey, i.key) > 0 {
i.key = append(i.key[:0], ukey...)
i.value = append(i.value[:0], i.iter.Value()...)
i.dir = dirForward
return true
}
}
}
} else if i.strict {
i.setErr(kerr)
break
}
if !i.iter.Next() {
i.dir = dirEOI
i.iterErr()
break
}
}
return false
}
func (i *dbIter) Next() bool {
if i.dir == dirEOI || i.err != nil {
return false
} else if i.dir == dirReleased {
i.err = ErrIterReleased
return false
}
if !i.iter.Next() || (i.dir == dirBackward && !i.iter.Next()) {
i.dir = dirEOI
i.iterErr()
return false
}
return i.next()
}
func (i *dbIter) prev() bool {
i.dir = dirBackward
del := true
if i.iter.Valid() {
for {
if ukey, seq, kt, kerr := parseIkey(i.iter.Key()); kerr == nil {
i.sampleSeek()
if seq <= i.seq {
if !del && i.icmp.uCompare(ukey, i.key) < 0 {
return true
}
del = (kt == ktDel)
if !del {
i.key = append(i.key[:0], ukey...)
i.value = append(i.value[:0], i.iter.Value()...)
}
}
} else if i.strict {
i.setErr(kerr)
return false
}
if !i.iter.Prev() {
break
}
}
}
if del {
i.dir = dirSOI
i.iterErr()
return false
}
return true
}
func (i *dbIter) Prev() bool {
if i.dir == dirSOI || i.err != nil {
return false
} else if i.dir == dirReleased {
i.err = ErrIterReleased
return false
}
switch i.dir {
case dirEOI:
return i.Last()
case dirForward:
for i.iter.Prev() {
if ukey, _, _, kerr := parseIkey(i.iter.Key()); kerr == nil {
i.sampleSeek()
if i.icmp.uCompare(ukey, i.key) < 0 {
goto cont
}
} else if i.strict {
i.setErr(kerr)
return false
}
}
i.dir = dirSOI
i.iterErr()
return false
}
cont:
return i.prev()
}
func (i *dbIter) Key() []byte {
if i.err != nil || i.dir <= dirEOI {
return nil
}
return i.key
}
func (i *dbIter) Value() []byte {
if i.err != nil || i.dir <= dirEOI {
return nil
}
return i.value
}
func (i *dbIter) Release() {
if i.dir != dirReleased {
// Clear the finalizer.
runtime.SetFinalizer(i, nil)
if i.releaser != nil {
i.releaser.Release()
i.releaser = nil
}
i.dir = dirReleased
i.key = nil
i.value = nil
i.iter.Release()
i.iter = nil
atomic.AddInt32(&i.db.aliveIters, -1)
i.db = nil
}
}
func (i *dbIter) SetReleaser(releaser util.Releaser) {
if i.dir == dirReleased {
panic(util.ErrReleased)
}
if i.releaser != nil && releaser != nil {
panic(util.ErrHasReleaser)
}
i.releaser = releaser
}
func (i *dbIter) Error() error {
return i.err
}
| Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_iter.go | 0 | https://github.com/pingcap/tidb/commit/58ad162d3418a8a4d1b08884f23e0cef109b67ff | [
0.004561276640743017,
0.0008112901705317199,
0.00016665499424561858,
0.0003627605619840324,
0.0009650926804170012
] |
{
"id": 1,
"code_window": [
"\t_, ok := s.(*dbStore)\n",
"\treturn ok\n",
"}\n",
"\n",
"// Open opens or creates a storage with specific format for a local engine Driver.\n",
"func (d Driver) Open(schema string) (kv.Storage, error) {\n",
"\tmc.mu.Lock()\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"func lockVersionProvider() {\n",
"\tproviderMu.Lock()\n",
"}\n",
"\n",
"func unlockVersionProvider() {\n",
"\tproviderMu.Unlock()\n",
"}\n",
"\n"
],
"file_path": "store/localstore/kv.go",
"type": "add",
"edit_start_line_idx": 77
} | Memory usage
============
(Highly unscientific.)
Command used to gather static memory usage:
```sh
grep ^Vm "/proc/$(ps fax | grep [m]etrics-bench | awk '{print $1}')/status"
```
Program used to gather baseline memory usage:
```go
package main
import "time"
func main() {
time.Sleep(600e9)
}
```
Baseline
--------
```
VmPeak: 42604 kB
VmSize: 42604 kB
VmLck: 0 kB
VmHWM: 1120 kB
VmRSS: 1120 kB
VmData: 35460 kB
VmStk: 136 kB
VmExe: 1020 kB
VmLib: 1848 kB
VmPTE: 36 kB
VmSwap: 0 kB
```
Program used to gather metric memory usage (with other metrics being similar):
```go
package main
import (
"fmt"
"metrics"
"time"
)
func main() {
fmt.Sprintf("foo")
metrics.NewRegistry()
time.Sleep(600e9)
}
```
1000 counters registered
------------------------
```
VmPeak: 44016 kB
VmSize: 44016 kB
VmLck: 0 kB
VmHWM: 1928 kB
VmRSS: 1928 kB
VmData: 36868 kB
VmStk: 136 kB
VmExe: 1024 kB
VmLib: 1848 kB
VmPTE: 40 kB
VmSwap: 0 kB
```
**1.412 kB virtual, TODO 0.808 kB resident per counter.**
100000 counters registered
--------------------------
```
VmPeak: 55024 kB
VmSize: 55024 kB
VmLck: 0 kB
VmHWM: 12440 kB
VmRSS: 12440 kB
VmData: 47876 kB
VmStk: 136 kB
VmExe: 1024 kB
VmLib: 1848 kB
VmPTE: 64 kB
VmSwap: 0 kB
```
**0.1242 kB virtual, 0.1132 kB resident per counter.**
1000 gauges registered
----------------------
```
VmPeak: 44012 kB
VmSize: 44012 kB
VmLck: 0 kB
VmHWM: 1928 kB
VmRSS: 1928 kB
VmData: 36868 kB
VmStk: 136 kB
VmExe: 1020 kB
VmLib: 1848 kB
VmPTE: 40 kB
VmSwap: 0 kB
```
**1.408 kB virtual, 0.808 kB resident per counter.**
100000 gauges registered
------------------------
```
VmPeak: 55020 kB
VmSize: 55020 kB
VmLck: 0 kB
VmHWM: 12432 kB
VmRSS: 12432 kB
VmData: 47876 kB
VmStk: 136 kB
VmExe: 1020 kB
VmLib: 1848 kB
VmPTE: 60 kB
VmSwap: 0 kB
```
**0.12416 kB virtual, 0.11312 resident per gauge.**
1000 histograms with a uniform sample size of 1028
--------------------------------------------------
```
VmPeak: 72272 kB
VmSize: 72272 kB
VmLck: 0 kB
VmHWM: 16204 kB
VmRSS: 16204 kB
VmData: 65100 kB
VmStk: 136 kB
VmExe: 1048 kB
VmLib: 1848 kB
VmPTE: 80 kB
VmSwap: 0 kB
```
**29.668 kB virtual, TODO 15.084 resident per histogram.**
10000 histograms with a uniform sample size of 1028
---------------------------------------------------
```
VmPeak: 256912 kB
VmSize: 256912 kB
VmLck: 0 kB
VmHWM: 146204 kB
VmRSS: 146204 kB
VmData: 249740 kB
VmStk: 136 kB
VmExe: 1048 kB
VmLib: 1848 kB
VmPTE: 448 kB
VmSwap: 0 kB
```
**21.4308 kB virtual, 14.5084 kB resident per histogram.**
50000 histograms with a uniform sample size of 1028
---------------------------------------------------
```
VmPeak: 908112 kB
VmSize: 908112 kB
VmLck: 0 kB
VmHWM: 645832 kB
VmRSS: 645588 kB
VmData: 900940 kB
VmStk: 136 kB
VmExe: 1048 kB
VmLib: 1848 kB
VmPTE: 1716 kB
VmSwap: 1544 kB
```
**17.31016 kB virtual, 12.88936 kB resident per histogram.**
1000 histograms with an exponentially-decaying sample size of 1028 and alpha of 0.015
-------------------------------------------------------------------------------------
```
VmPeak: 62480 kB
VmSize: 62480 kB
VmLck: 0 kB
VmHWM: 11572 kB
VmRSS: 11572 kB
VmData: 55308 kB
VmStk: 136 kB
VmExe: 1048 kB
VmLib: 1848 kB
VmPTE: 64 kB
VmSwap: 0 kB
```
**19.876 kB virtual, 10.452 kB resident per histogram.**
10000 histograms with an exponentially-decaying sample size of 1028 and alpha of 0.015
--------------------------------------------------------------------------------------
```
VmPeak: 153296 kB
VmSize: 153296 kB
VmLck: 0 kB
VmHWM: 101176 kB
VmRSS: 101176 kB
VmData: 146124 kB
VmStk: 136 kB
VmExe: 1048 kB
VmLib: 1848 kB
VmPTE: 240 kB
VmSwap: 0 kB
```
**11.0692 kB virtual, 10.0056 kB resident per histogram.**
50000 histograms with an exponentially-decaying sample size of 1028 and alpha of 0.015
--------------------------------------------------------------------------------------
```
VmPeak: 557264 kB
VmSize: 557264 kB
VmLck: 0 kB
VmHWM: 501056 kB
VmRSS: 501056 kB
VmData: 550092 kB
VmStk: 136 kB
VmExe: 1048 kB
VmLib: 1848 kB
VmPTE: 1032 kB
VmSwap: 0 kB
```
**10.2932 kB virtual, 9.99872 kB resident per histogram.**
1000 meters
-----------
```
VmPeak: 74504 kB
VmSize: 74504 kB
VmLck: 0 kB
VmHWM: 24124 kB
VmRSS: 24124 kB
VmData: 67340 kB
VmStk: 136 kB
VmExe: 1040 kB
VmLib: 1848 kB
VmPTE: 92 kB
VmSwap: 0 kB
```
**31.9 kB virtual, 23.004 kB resident per meter.**
10000 meters
------------
```
VmPeak: 278920 kB
VmSize: 278920 kB
VmLck: 0 kB
VmHWM: 227300 kB
VmRSS: 227300 kB
VmData: 271756 kB
VmStk: 136 kB
VmExe: 1040 kB
VmLib: 1848 kB
VmPTE: 488 kB
VmSwap: 0 kB
```
**23.6316 kB virtual, 22.618 kB resident per meter.**
| Godeps/_workspace/src/github.com/rcrowley/go-metrics/memory.md | 0 | https://github.com/pingcap/tidb/commit/58ad162d3418a8a4d1b08884f23e0cef109b67ff | [
0.00018889234343077987,
0.0001707028568489477,
0.0001648442994337529,
0.00016866432270035148,
0.000006163547368487343
] |
{
"id": 1,
"code_window": [
"\t_, ok := s.(*dbStore)\n",
"\treturn ok\n",
"}\n",
"\n",
"// Open opens or creates a storage with specific format for a local engine Driver.\n",
"func (d Driver) Open(schema string) (kv.Storage, error) {\n",
"\tmc.mu.Lock()\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"func lockVersionProvider() {\n",
"\tproviderMu.Lock()\n",
"}\n",
"\n",
"func unlockVersionProvider() {\n",
"\tproviderMu.Unlock()\n",
"}\n",
"\n"
],
"file_path": "store/localstore/kv.go",
"type": "add",
"edit_start_line_idx": 77
} | Copyright (c) 2011 The Snappy-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.
| Godeps/_workspace/src/github.com/golang/snappy/LICENSE | 0 | https://github.com/pingcap/tidb/commit/58ad162d3418a8a4d1b08884f23e0cef109b67ff | [
0.00017198659770656377,
0.0001684664748609066,
0.000163040982442908,
0.00017037185898516327,
0.0000038926305023778696
] |
{
"id": 2,
"code_window": [
"\n",
"// Begin transaction\n",
"func (s *dbStore) Begin() (kv.Transaction, error) {\n",
"\ts.mu.Lock()\n",
"\tdefer s.mu.Unlock()\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlockVersionProvider()\n",
"\tbeginVer, err := globalVersionProvider.CurrentVersion()\n",
"\tif err != nil {\n",
"\t\tunlockVersionProvider()\n",
"\t\treturn nil, errors.Trace(err)\n",
"\t}\n",
"\tunlockVersionProvider()\n",
"\n"
],
"file_path": "store/localstore/kv.go",
"type": "add",
"edit_start_line_idx": 142
} | // Copyright 2015 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package localstore
import (
"fmt"
"runtime/debug"
"strconv"
"github.com/juju/errors"
"github.com/ngaut/log"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/util/codec"
)
var (
_ kv.Transaction = (*dbTxn)(nil)
// ErrInvalidTxn is the error when commits or rollbacks in an invalid transaction.
ErrInvalidTxn = errors.New("invalid transaction")
// ErrCannotSetNilValue is the error when sets an empty value.
ErrCannotSetNilValue = errors.New("can not set nil value")
)
// dbTxn is not thread safe
type dbTxn struct {
kv.UnionStore
store *dbStore // for commit
tid uint64
valid bool
version kv.Version // commit version
snapshotVals map[string]struct{} // origin version in snapshot
opts map[kv.Option]interface{}
}
func (txn *dbTxn) markOrigin(k []byte) {
keystr := string(k)
// Already exist, do nothing.
if _, ok := txn.snapshotVals[keystr]; ok {
return
}
txn.snapshotVals[keystr] = struct{}{}
}
// Implement transaction interface
func (txn *dbTxn) Inc(k kv.Key, step int64) (int64, error) {
log.Debugf("Inc %q, step %d txn:%d", k, step, txn.tid)
k = kv.EncodeKey(k)
txn.markOrigin(k)
val, err := txn.UnionStore.Get(k)
if kv.IsErrNotFound(err) {
err = txn.UnionStore.Set(k, []byte(strconv.FormatInt(step, 10)))
if err != nil {
return 0, errors.Trace(err)
}
return step, nil
}
if err != nil {
return 0, errors.Trace(err)
}
intVal, err := strconv.ParseInt(string(val), 10, 0)
if err != nil {
return intVal, errors.Trace(err)
}
intVal += step
err = txn.UnionStore.Set(k, []byte(strconv.FormatInt(intVal, 10)))
if err != nil {
return 0, errors.Trace(err)
}
txn.store.compactor.OnSet(k)
return intVal, nil
}
func (txn *dbTxn) GetInt64(k kv.Key) (int64, error) {
k = kv.EncodeKey(k)
val, err := txn.UnionStore.Get(k)
if kv.IsErrNotFound(err) {
return 0, nil
}
if err != nil {
return 0, errors.Trace(err)
}
intVal, err := strconv.ParseInt(string(val), 10, 0)
return intVal, errors.Trace(err)
}
func (txn *dbTxn) String() string {
return fmt.Sprintf("%d", txn.tid)
}
func (txn *dbTxn) Get(k kv.Key) ([]byte, error) {
log.Debugf("get key:%q, txn:%d", k, txn.tid)
k = kv.EncodeKey(k)
val, err := txn.UnionStore.Get(k)
if kv.IsErrNotFound(err) {
return nil, errors.Trace(kv.ErrNotExist)
}
if err != nil {
return nil, errors.Trace(err)
}
if len(val) == 0 {
return nil, errors.Trace(kv.ErrNotExist)
}
txn.store.compactor.OnGet(k)
return val, nil
}
func (txn *dbTxn) BatchPrefetch(keys []kv.Key) error {
encodedKeys := make([]kv.Key, len(keys))
for i, k := range keys {
encodedKeys[i] = kv.EncodeKey(k)
}
_, err := txn.UnionStore.Snapshot.BatchGet(encodedKeys)
return err
}
func (txn *dbTxn) RangePrefetch(start, end kv.Key, limit int) error {
_, err := txn.UnionStore.Snapshot.RangeGet(kv.EncodeKey(start), kv.EncodeKey(end), limit)
return err
}
func (txn *dbTxn) Set(k kv.Key, data []byte) error {
if len(data) == 0 {
// Incase someone use it in the wrong way, we can figure it out immediately.
debug.PrintStack()
return errors.Trace(ErrCannotSetNilValue)
}
log.Debugf("set key:%q, txn:%d", k, txn.tid)
k = kv.EncodeKey(k)
err := txn.UnionStore.Set(k, data)
if err != nil {
return errors.Trace(err)
}
txn.markOrigin(k)
txn.store.compactor.OnSet(k)
return nil
}
func (txn *dbTxn) Seek(k kv.Key) (kv.Iterator, error) {
log.Debugf("seek key:%q, txn:%d", k, txn.tid)
k = kv.EncodeKey(k)
iter, err := txn.UnionStore.Seek(k, txn)
if err != nil {
return nil, errors.Trace(err)
}
if !iter.Valid() {
return &kv.UnionIter{}, nil
}
return kv.NewDecodeKeyIter(iter), nil
}
func (txn *dbTxn) Delete(k kv.Key) error {
log.Debugf("delete key:%q, txn:%d", k, txn.tid)
k = kv.EncodeKey(k)
err := txn.UnionStore.Delete(k)
if err != nil {
return errors.Trace(err)
}
txn.markOrigin(k)
txn.store.compactor.OnDelete(k)
return nil
}
func (txn *dbTxn) each(f func(kv.Iterator) error) error {
iter := txn.UnionStore.WBuffer.NewIterator(nil)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
if err := f(iter); err != nil {
return errors.Trace(err)
}
}
return nil
}
func (txn *dbTxn) doCommit() error {
b := txn.store.newBatch()
keysLocked := make([]string, 0, len(txn.snapshotVals))
defer func() {
for _, key := range keysLocked {
txn.store.unLockKeys(key)
}
}()
// check lazy condition pairs
if err := txn.UnionStore.CheckLazyConditionPairs(); err != nil {
return errors.Trace(err)
}
txn.Snapshot.Release()
// Check locked keys
for k := range txn.snapshotVals {
err := txn.store.tryConditionLockKey(txn.tid, k)
if err != nil {
return errors.Trace(err)
}
keysLocked = append(keysLocked, k)
}
// Check dirty store
curVer, err := globalVersionProvider.CurrentVersion()
if err != nil {
return errors.Trace(err)
}
err = txn.each(func(iter kv.Iterator) error {
metaKey := codec.EncodeBytes(nil, []byte(iter.Key()))
// put dummy meta key, write current version
b.Put(metaKey, codec.EncodeUint(nil, curVer.Ver))
mvccKey := MvccEncodeVersionKey(kv.Key(iter.Key()), curVer)
if len(iter.Value()) == 0 { // Deleted marker
b.Put(mvccKey, nil)
} else {
b.Put(mvccKey, iter.Value())
}
return nil
})
if err != nil {
return errors.Trace(err)
}
// Update commit version.
txn.version = curVer
return txn.store.writeBatch(b)
}
func (txn *dbTxn) Commit() error {
if !txn.valid {
return errors.Trace(ErrInvalidTxn)
}
log.Infof("commit txn %d", txn.tid)
defer func() {
txn.close()
}()
return errors.Trace(txn.doCommit())
}
func (txn *dbTxn) CommittedVersion() (kv.Version, error) {
// Check if this transaction is not committed.
if txn.version.Cmp(kv.MinVersion) == 0 {
return kv.MinVersion, kv.ErrNotCommitted
}
return txn.version, nil
}
func (txn *dbTxn) close() error {
txn.UnionStore.Close()
txn.snapshotVals = nil
txn.valid = false
return nil
}
func (txn *dbTxn) Rollback() error {
if !txn.valid {
return errors.Trace(ErrInvalidTxn)
}
log.Warnf("Rollback txn %d", txn.tid)
return txn.close()
}
func (txn *dbTxn) LockKeys(keys ...kv.Key) error {
for _, key := range keys {
key = kv.EncodeKey(key)
txn.markOrigin(key)
}
return nil
}
func (txn *dbTxn) SetOption(opt kv.Option, val interface{}) {
txn.opts[opt] = val
}
func (txn *dbTxn) DelOption(opt kv.Option) {
delete(txn.opts, opt)
}
type options map[kv.Option]interface{}
func (opts options) Get(opt kv.Option) (interface{}, bool) {
v, ok := opts[opt]
return v, ok
}
| store/localstore/txn.go | 1 | https://github.com/pingcap/tidb/commit/58ad162d3418a8a4d1b08884f23e0cef109b67ff | [
0.9567558765411377,
0.35128113627433777,
0.00016992601740639657,
0.2663697302341461,
0.36336642503738403
] |
{
"id": 2,
"code_window": [
"\n",
"// Begin transaction\n",
"func (s *dbStore) Begin() (kv.Transaction, error) {\n",
"\ts.mu.Lock()\n",
"\tdefer s.mu.Unlock()\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlockVersionProvider()\n",
"\tbeginVer, err := globalVersionProvider.CurrentVersion()\n",
"\tif err != nil {\n",
"\t\tunlockVersionProvider()\n",
"\t\treturn nil, errors.Trace(err)\n",
"\t}\n",
"\tunlockVersionProvider()\n",
"\n"
],
"file_path": "store/localstore/kv.go",
"type": "add",
"edit_start_line_idx": 142
} | // Copyright 2015 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package plans
import (
"github.com/juju/errors"
"github.com/pingcap/tidb/context"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/field"
"github.com/pingcap/tidb/plan"
"github.com/pingcap/tidb/util/format"
)
var (
_ plan.Plan = (*HavingPlan)(nil)
)
// HavingPlan executes the HAVING statement, HavingPlan's behavior is almost the
// same as FilterDefaultPlan.
type HavingPlan struct {
Src plan.Plan
Expr expression.Expression
evalArgs map[interface{}]interface{}
*SelectList
}
// Explain implements plan.Plan Explain interface.
func (r *HavingPlan) Explain(w format.Formatter) {
r.Src.Explain(w)
w.Format("┌Having %s\n└Output field names %v\n", r.Expr.String(), r.Src.GetFields())
}
// Filter implements plan.Plan Filter interface.
func (r *HavingPlan) Filter(ctx context.Context, expr expression.Expression) (plan.Plan, bool, error) {
return r, false, nil
}
// GetFields implements plan.Plan GetFields interface.
func (r *HavingPlan) GetFields() []*field.ResultField {
return r.Src.GetFields()
}
// Next implements plan.Plan Next interface.
func (r *HavingPlan) Next(ctx context.Context) (row *plan.Row, err error) {
if r.evalArgs == nil {
r.evalArgs = map[interface{}]interface{}{}
}
for {
var srcRow *plan.Row
srcRow, err = r.Src.Next(ctx)
if srcRow == nil || err != nil {
return nil, errors.Trace(err)
}
r.evalArgs[expression.ExprEvalIdentReferFunc] = func(name string, scope int, index int) (interface{}, error) {
if scope == expression.IdentReferFromTable {
return srcRow.FromData[index], nil
} else if scope == expression.IdentReferSelectList {
return srcRow.Data[index], nil
}
// try to find in outer query
return getIdentValueFromOuterQuery(ctx, name)
}
r.evalArgs[expression.ExprEvalPositionFunc] = func(position int) (interface{}, error) {
// position is in [1, len(fields)], so we must decrease 1 to get correct index
// TODO: check position invalidation
return srcRow.Data[position-1], nil
}
var v bool
v, err = expression.EvalBoolExpr(ctx, r.Expr, r.evalArgs)
if err != nil {
return nil, errors.Trace(err)
}
if v {
row = srcRow
return
}
}
}
// Close implements plan.Plan Close interface.
func (r *HavingPlan) Close() error {
return r.Src.Close()
}
| plan/plans/having.go | 0 | https://github.com/pingcap/tidb/commit/58ad162d3418a8a4d1b08884f23e0cef109b67ff | [
0.8771788477897644,
0.0925062820315361,
0.0001700603897916153,
0.0018346032593399286,
0.261687308549881
] |
{
"id": 2,
"code_window": [
"\n",
"// Begin transaction\n",
"func (s *dbStore) Begin() (kv.Transaction, error) {\n",
"\ts.mu.Lock()\n",
"\tdefer s.mu.Unlock()\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlockVersionProvider()\n",
"\tbeginVer, err := globalVersionProvider.CurrentVersion()\n",
"\tif err != nil {\n",
"\t\tunlockVersionProvider()\n",
"\t\treturn nil, errors.Trace(err)\n",
"\t}\n",
"\tunlockVersionProvider()\n",
"\n"
],
"file_path": "store/localstore/kv.go",
"type": "add",
"edit_start_line_idx": 142
} | package metrics
import (
"runtime/debug"
"time"
)
var (
debugMetrics struct {
GCStats struct {
LastGC Gauge
NumGC Gauge
Pause Histogram
//PauseQuantiles Histogram
PauseTotal Gauge
}
ReadGCStats Timer
}
gcStats debug.GCStats
)
// Capture new values for the Go garbage collector statistics exported in
// debug.GCStats. This is designed to be called as a goroutine.
func CaptureDebugGCStats(r Registry, d time.Duration) {
for _ = range time.Tick(d) {
CaptureDebugGCStatsOnce(r)
}
}
// Capture new values for the Go garbage collector statistics exported in
// debug.GCStats. This is designed to be called in a background goroutine.
// Giving a registry which has not been given to RegisterDebugGCStats will
// panic.
//
// Be careful (but much less so) with this because debug.ReadGCStats calls
// the C function runtime·lock(runtime·mheap) which, while not a stop-the-world
// operation, isn't something you want to be doing all the time.
func CaptureDebugGCStatsOnce(r Registry) {
lastGC := gcStats.LastGC
t := time.Now()
debug.ReadGCStats(&gcStats)
debugMetrics.ReadGCStats.UpdateSince(t)
debugMetrics.GCStats.LastGC.Update(int64(gcStats.LastGC.UnixNano()))
debugMetrics.GCStats.NumGC.Update(int64(gcStats.NumGC))
if lastGC != gcStats.LastGC && 0 < len(gcStats.Pause) {
debugMetrics.GCStats.Pause.Update(int64(gcStats.Pause[0]))
}
//debugMetrics.GCStats.PauseQuantiles.Update(gcStats.PauseQuantiles)
debugMetrics.GCStats.PauseTotal.Update(int64(gcStats.PauseTotal))
}
// Register metrics for the Go garbage collector statistics exported in
// debug.GCStats. The metrics are named by their fully-qualified Go symbols,
// i.e. debug.GCStats.PauseTotal.
func RegisterDebugGCStats(r Registry) {
debugMetrics.GCStats.LastGC = NewGauge()
debugMetrics.GCStats.NumGC = NewGauge()
debugMetrics.GCStats.Pause = NewHistogram(NewExpDecaySample(1028, 0.015))
//debugMetrics.GCStats.PauseQuantiles = NewHistogram(NewExpDecaySample(1028, 0.015))
debugMetrics.GCStats.PauseTotal = NewGauge()
debugMetrics.ReadGCStats = NewTimer()
r.Register("debug.GCStats.LastGC", debugMetrics.GCStats.LastGC)
r.Register("debug.GCStats.NumGC", debugMetrics.GCStats.NumGC)
r.Register("debug.GCStats.Pause", debugMetrics.GCStats.Pause)
//r.Register("debug.GCStats.PauseQuantiles", debugMetrics.GCStats.PauseQuantiles)
r.Register("debug.GCStats.PauseTotal", debugMetrics.GCStats.PauseTotal)
r.Register("debug.ReadGCStats", debugMetrics.ReadGCStats)
}
// Allocate an initial slice for gcStats.Pause to avoid allocations during
// normal operation.
func init() {
gcStats.Pause = make([]time.Duration, 11)
}
| Godeps/_workspace/src/github.com/rcrowley/go-metrics/debug.go | 0 | https://github.com/pingcap/tidb/commit/58ad162d3418a8a4d1b08884f23e0cef109b67ff | [
0.0016311878571286798,
0.0005404182011261582,
0.0001674536761129275,
0.00023225251061376184,
0.0005000881501473486
] |
{
"id": 2,
"code_window": [
"\n",
"// Begin transaction\n",
"func (s *dbStore) Begin() (kv.Transaction, error) {\n",
"\ts.mu.Lock()\n",
"\tdefer s.mu.Unlock()\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlockVersionProvider()\n",
"\tbeginVer, err := globalVersionProvider.CurrentVersion()\n",
"\tif err != nil {\n",
"\t\tunlockVersionProvider()\n",
"\t\treturn nil, errors.Trace(err)\n",
"\t}\n",
"\tunlockVersionProvider()\n",
"\n"
],
"file_path": "store/localstore/kv.go",
"type": "add",
"edit_start_line_idx": 142
} | // Copyright (c) 2013, Suryandaru Triandana <[email protected]>
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package util provides utilities used throughout leveldb.
package util
import (
"errors"
)
var (
ErrReleased = errors.New("leveldb: resource already relesed")
ErrHasReleaser = errors.New("leveldb: releaser already defined")
)
// Releaser is the interface that wraps the basic Release method.
type Releaser interface {
// Release releases associated resources. Release should always success
// and can be called multipe times without causing error.
Release()
}
// ReleaseSetter is the interface that wraps the basic SetReleaser method.
type ReleaseSetter interface {
// SetReleaser associates the given releaser to the resources. The
// releaser will be called once coresponding resources released.
// Calling SetReleaser with nil will clear the releaser.
//
// This will panic if a releaser already present or coresponding
// resource is already released. Releaser should be cleared first
// before assigned a new one.
SetReleaser(releaser Releaser)
}
// BasicReleaser provides basic implementation of Releaser and ReleaseSetter.
type BasicReleaser struct {
releaser Releaser
released bool
}
// Released returns whether Release method already called.
func (r *BasicReleaser) Released() bool {
return r.released
}
// Release implements Releaser.Release.
func (r *BasicReleaser) Release() {
if !r.released {
if r.releaser != nil {
r.releaser.Release()
r.releaser = nil
}
r.released = true
}
}
// SetReleaser implements ReleaseSetter.SetReleaser.
func (r *BasicReleaser) SetReleaser(releaser Releaser) {
if r.released {
panic(ErrReleased)
}
if r.releaser != nil && releaser != nil {
panic(ErrHasReleaser)
}
r.releaser = releaser
}
type NoopReleaser struct{}
func (NoopReleaser) Release() {}
| Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util/util.go | 0 | https://github.com/pingcap/tidb/commit/58ad162d3418a8a4d1b08884f23e0cef109b67ff | [
0.1894291788339615,
0.025182699784636497,
0.00017124302394222468,
0.0007259437697939575,
0.062126275151968
] |
{
"id": 3,
"code_window": [
"\tdefer s.mu.Unlock()\n",
"\n",
"\tif s.closed {\n",
"\t\treturn nil, errors.Trace(ErrDBClosed)\n",
"\t}\n",
"\n",
"\tbeginVer, err := globalVersionProvider.CurrentVersion()\n",
"\tif err != nil {\n",
"\t\treturn nil, errors.Trace(err)\n",
"\t}\n",
"\ttxn := &dbTxn{\n",
"\t\ttid: beginVer.Ver,\n",
"\t\tvalid: true,\n",
"\t\tstore: s,\n",
"\t\tversion: kv.MinVersion,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "store/localstore/kv.go",
"type": "replace",
"edit_start_line_idx": 148
} | // Copyright 2015 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package localstore
import (
"sync"
"github.com/juju/errors"
"github.com/ngaut/log"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/store/localstore/engine"
"github.com/pingcap/tidb/terror"
"github.com/pingcap/tidb/util/codec"
"github.com/twinj/uuid"
)
var (
_ kv.Storage = (*dbStore)(nil)
)
type dbStore struct {
mu sync.Mutex
snapLock sync.RWMutex
db engine.DB
txns map[uint64]*dbTxn
keysLocked map[string]uint64
uuid string
path string
compactor *localstoreCompactor
closed bool
}
type storeCache struct {
mu sync.Mutex
cache map[string]*dbStore
}
var (
globalID int64
globalVersionProvider kv.VersionProvider
mc storeCache
// ErrDBClosed is the error meaning db is closed and we can use it anymore.
ErrDBClosed = errors.New("db is closed")
)
func init() {
mc.cache = make(map[string]*dbStore)
globalVersionProvider = &LocalVersionProvider{}
}
// Driver implements kv.Driver interface.
type Driver struct {
// engine.Driver is the engine driver for different local db engine.
engine.Driver
}
// IsLocalStore checks whether a storage is local or not.
func IsLocalStore(s kv.Storage) bool {
_, ok := s.(*dbStore)
return ok
}
// Open opens or creates a storage with specific format for a local engine Driver.
func (d Driver) Open(schema string) (kv.Storage, error) {
mc.mu.Lock()
defer mc.mu.Unlock()
if store, ok := mc.cache[schema]; ok {
// TODO: check the cache store has the same engine with this Driver.
log.Info("cache store", schema)
return store, nil
}
db, err := d.Driver.Open(schema)
if err != nil {
return nil, errors.Trace(err)
}
log.Info("New store", schema)
s := &dbStore{
txns: make(map[uint64]*dbTxn),
keysLocked: make(map[string]uint64),
uuid: uuid.NewV4().String(),
path: schema,
db: db,
compactor: newLocalCompactor(localCompactDefaultPolicy, db),
closed: false,
}
mc.cache[schema] = s
s.compactor.Start()
return s, nil
}
func (s *dbStore) UUID() string {
return s.uuid
}
func (s *dbStore) GetSnapshot(ver kv.Version) (kv.MvccSnapshot, error) {
s.snapLock.RLock()
defer s.snapLock.RUnlock()
if s.closed {
return nil, errors.Trace(ErrDBClosed)
}
currentVer, err := globalVersionProvider.CurrentVersion()
if err != nil {
return nil, errors.Trace(err)
}
if ver.Cmp(currentVer) > 0 {
ver = currentVer
}
return &dbSnapshot{
store: s,
db: s.db,
version: ver,
}, nil
}
func (s *dbStore) CurrentVersion() (kv.Version, error) {
return globalVersionProvider.CurrentVersion()
}
// Begin transaction
func (s *dbStore) Begin() (kv.Transaction, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return nil, errors.Trace(ErrDBClosed)
}
beginVer, err := globalVersionProvider.CurrentVersion()
if err != nil {
return nil, errors.Trace(err)
}
txn := &dbTxn{
tid: beginVer.Ver,
valid: true,
store: s,
version: kv.MinVersion,
snapshotVals: make(map[string]struct{}),
opts: make(map[kv.Option]interface{}),
}
log.Debugf("Begin txn:%d", txn.tid)
txn.UnionStore = kv.NewUnionStore(&dbSnapshot{
store: s,
db: s.db,
version: beginVer,
}, options(txn.opts))
return txn, nil
}
func (s *dbStore) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
s.snapLock.Lock()
defer s.snapLock.Unlock()
if s.closed {
return nil
}
s.closed = true
mc.mu.Lock()
defer mc.mu.Unlock()
s.compactor.Stop()
delete(mc.cache, s.path)
return s.db.Close()
}
func (s *dbStore) writeBatch(b engine.Batch) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return errors.Trace(ErrDBClosed)
}
err := s.db.Commit(b)
if err != nil {
log.Error(err)
return errors.Trace(err)
}
return nil
}
func (s *dbStore) newBatch() engine.Batch {
return s.db.NewBatch()
}
// Both lock and unlock are used for simulating scenario of percolator papers.
func (s *dbStore) tryConditionLockKey(tid uint64, key string) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return errors.Trace(ErrDBClosed)
}
if _, ok := s.keysLocked[key]; ok {
return errors.Trace(kv.ErrLockConflict)
}
metaKey := codec.EncodeBytes(nil, []byte(key))
currValue, err := s.db.Get(metaKey)
if terror.ErrorEqual(err, kv.ErrNotExist) {
s.keysLocked[key] = tid
return nil
}
if err != nil {
return errors.Trace(err)
}
// key not exist.
if currValue == nil {
s.keysLocked[key] = tid
return nil
}
_, ver, err := codec.DecodeUint(currValue)
if err != nil {
return errors.Trace(err)
}
// If there's newer version of this key, returns error.
if ver > tid {
log.Warnf("txn:%d, tryLockKey condition not match for key %s, currValue:%q", tid, key, currValue)
return errors.Trace(kv.ErrConditionNotMatch)
}
s.keysLocked[key] = tid
return nil
}
func (s *dbStore) unLockKeys(keys ...string) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return errors.Trace(ErrDBClosed)
}
for _, key := range keys {
if _, ok := s.keysLocked[key]; !ok {
return errors.Trace(kv.ErrNotExist)
}
delete(s.keysLocked, key)
}
return nil
}
| store/localstore/kv.go | 1 | https://github.com/pingcap/tidb/commit/58ad162d3418a8a4d1b08884f23e0cef109b67ff | [
0.9989239573478699,
0.10984214395284653,
0.00016394531121477485,
0.0019099456258118153,
0.30772513151168823
] |
{
"id": 3,
"code_window": [
"\tdefer s.mu.Unlock()\n",
"\n",
"\tif s.closed {\n",
"\t\treturn nil, errors.Trace(ErrDBClosed)\n",
"\t}\n",
"\n",
"\tbeginVer, err := globalVersionProvider.CurrentVersion()\n",
"\tif err != nil {\n",
"\t\treturn nil, errors.Trace(err)\n",
"\t}\n",
"\ttxn := &dbTxn{\n",
"\t\ttid: beginVer.Ver,\n",
"\t\tvalid: true,\n",
"\t\tstore: s,\n",
"\t\tversion: kv.MinVersion,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "store/localstore/kv.go",
"type": "replace",
"edit_start_line_idx": 148
} | package metrics
import (
"math"
"sync"
"sync/atomic"
)
// EWMAs continuously calculate an exponentially-weighted moving average
// based on an outside source of clock ticks.
type EWMA interface {
Rate() float64
Snapshot() EWMA
Tick()
Update(int64)
}
// NewEWMA constructs a new EWMA with the given alpha.
func NewEWMA(alpha float64) EWMA {
if UseNilMetrics {
return NilEWMA{}
}
return &StandardEWMA{alpha: alpha}
}
// NewEWMA1 constructs a new EWMA for a one-minute moving average.
func NewEWMA1() EWMA {
return NewEWMA(1 - math.Exp(-5.0/60.0/1))
}
// NewEWMA5 constructs a new EWMA for a five-minute moving average.
func NewEWMA5() EWMA {
return NewEWMA(1 - math.Exp(-5.0/60.0/5))
}
// NewEWMA15 constructs a new EWMA for a fifteen-minute moving average.
func NewEWMA15() EWMA {
return NewEWMA(1 - math.Exp(-5.0/60.0/15))
}
// EWMASnapshot is a read-only copy of another EWMA.
type EWMASnapshot float64
// Rate returns the rate of events per second at the time the snapshot was
// taken.
func (a EWMASnapshot) Rate() float64 { return float64(a) }
// Snapshot returns the snapshot.
func (a EWMASnapshot) Snapshot() EWMA { return a }
// Tick panics.
func (EWMASnapshot) Tick() {
panic("Tick called on an EWMASnapshot")
}
// Update panics.
func (EWMASnapshot) Update(int64) {
panic("Update called on an EWMASnapshot")
}
// NilEWMA is a no-op EWMA.
type NilEWMA struct{}
// Rate is a no-op.
func (NilEWMA) Rate() float64 { return 0.0 }
// Snapshot is a no-op.
func (NilEWMA) Snapshot() EWMA { return NilEWMA{} }
// Tick is a no-op.
func (NilEWMA) Tick() {}
// Update is a no-op.
func (NilEWMA) Update(n int64) {}
// StandardEWMA is the standard implementation of an EWMA and tracks the number
// of uncounted events and processes them on each tick. It uses the
// sync/atomic package to manage uncounted events.
type StandardEWMA struct {
uncounted int64 // /!\ this should be the first member to ensure 64-bit alignment
alpha float64
rate float64
init bool
mutex sync.Mutex
}
// Rate returns the moving average rate of events per second.
func (a *StandardEWMA) Rate() float64 {
a.mutex.Lock()
defer a.mutex.Unlock()
return a.rate * float64(1e9)
}
// Snapshot returns a read-only copy of the EWMA.
func (a *StandardEWMA) Snapshot() EWMA {
return EWMASnapshot(a.Rate())
}
// Tick ticks the clock to update the moving average. It assumes it is called
// every five seconds.
func (a *StandardEWMA) Tick() {
count := atomic.LoadInt64(&a.uncounted)
atomic.AddInt64(&a.uncounted, -count)
instantRate := float64(count) / float64(5e9)
a.mutex.Lock()
defer a.mutex.Unlock()
if a.init {
a.rate += a.alpha * (instantRate - a.rate)
} else {
a.init = true
a.rate = instantRate
}
}
// Update adds n uncounted events.
func (a *StandardEWMA) Update(n int64) {
atomic.AddInt64(&a.uncounted, n)
}
| Godeps/_workspace/src/github.com/rcrowley/go-metrics/ewma.go | 0 | https://github.com/pingcap/tidb/commit/58ad162d3418a8a4d1b08884f23e0cef109b67ff | [
0.00017544769798405468,
0.00017150967323686928,
0.0001656069653108716,
0.00017122649296652526,
0.0000032105187983688666
] |
{
"id": 3,
"code_window": [
"\tdefer s.mu.Unlock()\n",
"\n",
"\tif s.closed {\n",
"\t\treturn nil, errors.Trace(ErrDBClosed)\n",
"\t}\n",
"\n",
"\tbeginVer, err := globalVersionProvider.CurrentVersion()\n",
"\tif err != nil {\n",
"\t\treturn nil, errors.Trace(err)\n",
"\t}\n",
"\ttxn := &dbTxn{\n",
"\t\ttid: beginVer.Ver,\n",
"\t\tvalid: true,\n",
"\t\tstore: s,\n",
"\t\tversion: kv.MinVersion,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "store/localstore/kv.go",
"type": "replace",
"edit_start_line_idx": 148
} | // Copyright 2015 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package structure
import "github.com/pingcap/tidb/kv"
// NewStructure creates a TxStructure in transaction txn and with key prefix.
func NewStructure(txn kv.Transaction, prefix []byte) *TxStructure {
return &TxStructure{
txn: txn,
prefix: prefix,
}
}
// TxStructure supports some simple data structures like string, hash, list, etc... and
// you can use these in a transaction.
type TxStructure struct {
txn kv.Transaction
prefix []byte
}
| structure/structure.go | 0 | https://github.com/pingcap/tidb/commit/58ad162d3418a8a4d1b08884f23e0cef109b67ff | [
0.9920016527175903,
0.24818730354309082,
0.0001737371931085363,
0.0002868968585971743,
0.4294414222240448
] |
{
"id": 3,
"code_window": [
"\tdefer s.mu.Unlock()\n",
"\n",
"\tif s.closed {\n",
"\t\treturn nil, errors.Trace(ErrDBClosed)\n",
"\t}\n",
"\n",
"\tbeginVer, err := globalVersionProvider.CurrentVersion()\n",
"\tif err != nil {\n",
"\t\treturn nil, errors.Trace(err)\n",
"\t}\n",
"\ttxn := &dbTxn{\n",
"\t\ttid: beginVer.Ver,\n",
"\t\tvalid: true,\n",
"\t\tstore: s,\n",
"\t\tversion: kv.MinVersion,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "store/localstore/kv.go",
"type": "replace",
"edit_start_line_idx": 148
} | // Copyright 2015 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package plans_test
import (
. "github.com/pingcap/check"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/model"
"github.com/pingcap/tidb/parser/opcode"
"github.com/pingcap/tidb/plan/plans"
"github.com/pingcap/tidb/rset/rsets"
"github.com/pingcap/tidb/util/mock"
)
type testWhereSuit struct {
data []*testRowData
}
var _ = Suite(&testWhereSuit{
data: []*testRowData{
{1, []interface{}{10, "10"}},
{2, []interface{}{10, "20"}},
{3, []interface{}{10, "30"}},
{4, []interface{}{40, "40"}},
{6, []interface{}{60, "60"}},
},
})
func (t *testWhereSuit) TestWhere(c *C) {
tblPlan := &testTablePlan{t.data, []string{"id", "name"}, 0}
pln := &plans.FilterDefaultPlan{
Plan: tblPlan,
Expr: &expression.BinaryOperation{
Op: opcode.GE,
L: &expression.Ident{
CIStr: model.NewCIStr("id"),
ReferScope: expression.IdentReferFromTable,
ReferIndex: 0,
},
R: expression.Value{
Val: 30,
},
},
}
cnt := 0
rset := rsets.Recordset{Plan: pln,
Ctx: mock.NewContext()}
rset.Do(func(data []interface{}) (bool, error) {
cnt++
return true, nil
})
c.Assert(cnt, Equals, 2)
}
| plan/plans/where_test.go | 0 | https://github.com/pingcap/tidb/commit/58ad162d3418a8a4d1b08884f23e0cef109b67ff | [
0.00017848493007477373,
0.00017536268569529057,
0.00017315619334112853,
0.00017458228103350848,
0.000002012824097619159
] |
{
"id": 4,
"code_window": [
"\t\t\treturn errors.Trace(err)\n",
"\t\t}\n",
"\t\tkeysLocked = append(keysLocked, k)\n",
"\t}\n",
"\n",
"\t// Check dirty store\n",
"\tcurVer, err := globalVersionProvider.CurrentVersion()\n",
"\tif err != nil {\n",
"\t\treturn errors.Trace(err)\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// disable version provider temporarily\n",
"\tlockVersionProvider()\n",
"\tdefer unlockVersionProvider()\n",
"\n"
],
"file_path": "store/localstore/txn.go",
"type": "replace",
"edit_start_line_idx": 219
} | // Copyright 2015 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package localstore
import (
"sync"
"github.com/juju/errors"
"github.com/ngaut/log"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/store/localstore/engine"
"github.com/pingcap/tidb/terror"
"github.com/pingcap/tidb/util/codec"
"github.com/twinj/uuid"
)
var (
_ kv.Storage = (*dbStore)(nil)
)
type dbStore struct {
mu sync.Mutex
snapLock sync.RWMutex
db engine.DB
txns map[uint64]*dbTxn
keysLocked map[string]uint64
uuid string
path string
compactor *localstoreCompactor
closed bool
}
type storeCache struct {
mu sync.Mutex
cache map[string]*dbStore
}
var (
globalID int64
globalVersionProvider kv.VersionProvider
mc storeCache
// ErrDBClosed is the error meaning db is closed and we can use it anymore.
ErrDBClosed = errors.New("db is closed")
)
func init() {
mc.cache = make(map[string]*dbStore)
globalVersionProvider = &LocalVersionProvider{}
}
// Driver implements kv.Driver interface.
type Driver struct {
// engine.Driver is the engine driver for different local db engine.
engine.Driver
}
// IsLocalStore checks whether a storage is local or not.
func IsLocalStore(s kv.Storage) bool {
_, ok := s.(*dbStore)
return ok
}
// Open opens or creates a storage with specific format for a local engine Driver.
func (d Driver) Open(schema string) (kv.Storage, error) {
mc.mu.Lock()
defer mc.mu.Unlock()
if store, ok := mc.cache[schema]; ok {
// TODO: check the cache store has the same engine with this Driver.
log.Info("cache store", schema)
return store, nil
}
db, err := d.Driver.Open(schema)
if err != nil {
return nil, errors.Trace(err)
}
log.Info("New store", schema)
s := &dbStore{
txns: make(map[uint64]*dbTxn),
keysLocked: make(map[string]uint64),
uuid: uuid.NewV4().String(),
path: schema,
db: db,
compactor: newLocalCompactor(localCompactDefaultPolicy, db),
closed: false,
}
mc.cache[schema] = s
s.compactor.Start()
return s, nil
}
func (s *dbStore) UUID() string {
return s.uuid
}
func (s *dbStore) GetSnapshot(ver kv.Version) (kv.MvccSnapshot, error) {
s.snapLock.RLock()
defer s.snapLock.RUnlock()
if s.closed {
return nil, errors.Trace(ErrDBClosed)
}
currentVer, err := globalVersionProvider.CurrentVersion()
if err != nil {
return nil, errors.Trace(err)
}
if ver.Cmp(currentVer) > 0 {
ver = currentVer
}
return &dbSnapshot{
store: s,
db: s.db,
version: ver,
}, nil
}
func (s *dbStore) CurrentVersion() (kv.Version, error) {
return globalVersionProvider.CurrentVersion()
}
// Begin transaction
func (s *dbStore) Begin() (kv.Transaction, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return nil, errors.Trace(ErrDBClosed)
}
beginVer, err := globalVersionProvider.CurrentVersion()
if err != nil {
return nil, errors.Trace(err)
}
txn := &dbTxn{
tid: beginVer.Ver,
valid: true,
store: s,
version: kv.MinVersion,
snapshotVals: make(map[string]struct{}),
opts: make(map[kv.Option]interface{}),
}
log.Debugf("Begin txn:%d", txn.tid)
txn.UnionStore = kv.NewUnionStore(&dbSnapshot{
store: s,
db: s.db,
version: beginVer,
}, options(txn.opts))
return txn, nil
}
func (s *dbStore) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
s.snapLock.Lock()
defer s.snapLock.Unlock()
if s.closed {
return nil
}
s.closed = true
mc.mu.Lock()
defer mc.mu.Unlock()
s.compactor.Stop()
delete(mc.cache, s.path)
return s.db.Close()
}
func (s *dbStore) writeBatch(b engine.Batch) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return errors.Trace(ErrDBClosed)
}
err := s.db.Commit(b)
if err != nil {
log.Error(err)
return errors.Trace(err)
}
return nil
}
func (s *dbStore) newBatch() engine.Batch {
return s.db.NewBatch()
}
// Both lock and unlock are used for simulating scenario of percolator papers.
func (s *dbStore) tryConditionLockKey(tid uint64, key string) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return errors.Trace(ErrDBClosed)
}
if _, ok := s.keysLocked[key]; ok {
return errors.Trace(kv.ErrLockConflict)
}
metaKey := codec.EncodeBytes(nil, []byte(key))
currValue, err := s.db.Get(metaKey)
if terror.ErrorEqual(err, kv.ErrNotExist) {
s.keysLocked[key] = tid
return nil
}
if err != nil {
return errors.Trace(err)
}
// key not exist.
if currValue == nil {
s.keysLocked[key] = tid
return nil
}
_, ver, err := codec.DecodeUint(currValue)
if err != nil {
return errors.Trace(err)
}
// If there's newer version of this key, returns error.
if ver > tid {
log.Warnf("txn:%d, tryLockKey condition not match for key %s, currValue:%q", tid, key, currValue)
return errors.Trace(kv.ErrConditionNotMatch)
}
s.keysLocked[key] = tid
return nil
}
func (s *dbStore) unLockKeys(keys ...string) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return errors.Trace(ErrDBClosed)
}
for _, key := range keys {
if _, ok := s.keysLocked[key]; !ok {
return errors.Trace(kv.ErrNotExist)
}
delete(s.keysLocked, key)
}
return nil
}
| store/localstore/kv.go | 1 | https://github.com/pingcap/tidb/commit/58ad162d3418a8a4d1b08884f23e0cef109b67ff | [
0.9693298935890198,
0.09033596515655518,
0.0001619980757823214,
0.0006563503993675113,
0.2574915587902069
] |
{
"id": 4,
"code_window": [
"\t\t\treturn errors.Trace(err)\n",
"\t\t}\n",
"\t\tkeysLocked = append(keysLocked, k)\n",
"\t}\n",
"\n",
"\t// Check dirty store\n",
"\tcurVer, err := globalVersionProvider.CurrentVersion()\n",
"\tif err != nil {\n",
"\t\treturn errors.Trace(err)\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// disable version provider temporarily\n",
"\tlockVersionProvider()\n",
"\tdefer unlockVersionProvider()\n",
"\n"
],
"file_path": "store/localstore/txn.go",
"type": "replace",
"edit_start_line_idx": 219
} | // Copyright 2013 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 ignore
package main
// This program generates tables.go:
// go run maketables.go | gofmt > tables.go
// TODO: Emoji extensions?
// http://www.unicode.org/faq/emoji_dingbats.html
// http://www.unicode.org/Public/UNIDATA/EmojiSources.txt
import (
"bufio"
"fmt"
"log"
"net/http"
"sort"
"strings"
)
type entry struct {
jisCode, table int
}
func main() {
fmt.Printf("// generated by go run maketables.go; DO NOT EDIT\n\n")
fmt.Printf("// Package japanese provides Japanese encodings such as EUC-JP and Shift JIS.\n")
fmt.Printf(`package japanese // import "golang.org/x/text/encoding/japanese"` + "\n\n")
reverse := [65536]entry{}
for i := range reverse {
reverse[i].table = -1
}
tables := []struct {
url string
name string
}{
{"http://encoding.spec.whatwg.org/index-jis0208.txt", "0208"},
{"http://encoding.spec.whatwg.org/index-jis0212.txt", "0212"},
}
for i, table := range tables {
res, err := http.Get(table.url)
if err != nil {
log.Fatalf("%q: Get: %v", table.url, err)
}
defer res.Body.Close()
mapping := [65536]uint16{}
scanner := bufio.NewScanner(res.Body)
for scanner.Scan() {
s := strings.TrimSpace(scanner.Text())
if s == "" || s[0] == '#' {
continue
}
x, y := 0, uint16(0)
if _, err := fmt.Sscanf(s, "%d 0x%x", &x, &y); err != nil {
log.Fatalf("%q: could not parse %q", table.url, s)
}
if x < 0 || 120*94 <= x {
log.Fatalf("%q: JIS code %d is out of range", table.url, x)
}
mapping[x] = y
if reverse[y].table == -1 {
reverse[y] = entry{jisCode: x, table: i}
}
}
if err := scanner.Err(); err != nil {
log.Fatalf("%q: scanner error: %v", table.url, err)
}
fmt.Printf("// jis%sDecode is the decoding table from JIS %s code to Unicode.\n// It is defined at %s\n",
table.name, table.name, table.url)
fmt.Printf("var jis%sDecode = [...]uint16{\n", table.name)
for i, m := range mapping {
if m != 0 {
fmt.Printf("\t%d: 0x%04X,\n", i, m)
}
}
fmt.Printf("}\n\n")
}
// Any run of at least separation continuous zero entries in the reverse map will
// be a separate encode table.
const separation = 1024
intervals := []interval(nil)
low, high := -1, -1
for i, v := range reverse {
if v.table == -1 {
continue
}
if low < 0 {
low = i
} else if i-high >= separation {
if high >= 0 {
intervals = append(intervals, interval{low, high})
}
low = i
}
high = i + 1
}
if high >= 0 {
intervals = append(intervals, interval{low, high})
}
sort.Sort(byDecreasingLength(intervals))
fmt.Printf("const (\n")
fmt.Printf("\tjis0208 = 1\n")
fmt.Printf("\tjis0212 = 2\n")
fmt.Printf("\tcodeMask = 0x7f\n")
fmt.Printf("\tcodeShift = 7\n")
fmt.Printf("\ttableShift = 14\n")
fmt.Printf(")\n\n")
fmt.Printf("const numEncodeTables = %d\n\n", len(intervals))
fmt.Printf("// encodeX are the encoding tables from Unicode to JIS code,\n")
fmt.Printf("// sorted by decreasing length.\n")
for i, v := range intervals {
fmt.Printf("// encode%d: %5d entries for runes in [%5d, %5d).\n", i, v.len(), v.low, v.high)
}
fmt.Printf("//\n")
fmt.Printf("// The high two bits of the value record whether the JIS code comes from the\n")
fmt.Printf("// JIS0208 table (high bits == 1) or the JIS0212 table (high bits == 2).\n")
fmt.Printf("// The low 14 bits are two 7-bit unsigned integers j1 and j2 that form the\n")
fmt.Printf("// JIS code (94*j1 + j2) within that table.\n")
fmt.Printf("\n")
for i, v := range intervals {
fmt.Printf("const encode%dLow, encode%dHigh = %d, %d\n\n", i, i, v.low, v.high)
fmt.Printf("var encode%d = [...]uint16{\n", i)
for j := v.low; j < v.high; j++ {
x := reverse[j]
if x.table == -1 {
continue
}
fmt.Printf("\t%d - %d: jis%s<<14 | 0x%02X<<7 | 0x%02X,\n",
j, v.low, tables[x.table].name, x.jisCode/94, x.jisCode%94)
}
fmt.Printf("}\n\n")
}
}
// interval is a half-open interval [low, high).
type interval struct {
low, high int
}
func (i interval) len() int { return i.high - i.low }
// byDecreasingLength sorts intervals by decreasing length.
type byDecreasingLength []interval
func (b byDecreasingLength) Len() int { return len(b) }
func (b byDecreasingLength) Less(i, j int) bool { return b[i].len() > b[j].len() }
func (b byDecreasingLength) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
| Godeps/_workspace/src/golang.org/x/text/encoding/japanese/maketables.go | 0 | https://github.com/pingcap/tidb/commit/58ad162d3418a8a4d1b08884f23e0cef109b67ff | [
0.00017895610653795302,
0.00017004093388095498,
0.00016166413843166083,
0.00016950559802353382,
0.000004381216967885848
] |
{
"id": 4,
"code_window": [
"\t\t\treturn errors.Trace(err)\n",
"\t\t}\n",
"\t\tkeysLocked = append(keysLocked, k)\n",
"\t}\n",
"\n",
"\t// Check dirty store\n",
"\tcurVer, err := globalVersionProvider.CurrentVersion()\n",
"\tif err != nil {\n",
"\t\treturn errors.Trace(err)\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// disable version provider temporarily\n",
"\tlockVersionProvider()\n",
"\tdefer unlockVersionProvider()\n",
"\n"
],
"file_path": "store/localstore/txn.go",
"type": "replace",
"edit_start_line_idx": 219
} | package metrics
import (
"math"
"math/rand"
"sort"
"sync"
"time"
)
const rescaleThreshold = time.Hour
// Samples maintain a statistically-significant selection of values from
// a stream.
type Sample interface {
Clear()
Count() int64
Max() int64
Mean() float64
Min() int64
Percentile(float64) float64
Percentiles([]float64) []float64
Size() int
Snapshot() Sample
StdDev() float64
Sum() int64
Update(int64)
Values() []int64
Variance() float64
}
// ExpDecaySample is an exponentially-decaying sample using a forward-decaying
// priority reservoir. See Cormode et al's "Forward Decay: A Practical Time
// Decay Model for Streaming Systems".
//
// <http://www.research.att.com/people/Cormode_Graham/library/publications/CormodeShkapenyukSrivastavaXu09.pdf>
type ExpDecaySample struct {
alpha float64
count int64
mutex sync.Mutex
reservoirSize int
t0, t1 time.Time
values *expDecaySampleHeap
}
// NewExpDecaySample constructs a new exponentially-decaying sample with the
// given reservoir size and alpha.
func NewExpDecaySample(reservoirSize int, alpha float64) Sample {
if UseNilMetrics {
return NilSample{}
}
s := &ExpDecaySample{
alpha: alpha,
reservoirSize: reservoirSize,
t0: time.Now(),
values: newExpDecaySampleHeap(reservoirSize),
}
s.t1 = s.t0.Add(rescaleThreshold)
return s
}
// Clear clears all samples.
func (s *ExpDecaySample) Clear() {
s.mutex.Lock()
defer s.mutex.Unlock()
s.count = 0
s.t0 = time.Now()
s.t1 = s.t0.Add(rescaleThreshold)
s.values.Clear()
}
// Count returns the number of samples recorded, which may exceed the
// reservoir size.
func (s *ExpDecaySample) Count() int64 {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.count
}
// Max returns the maximum value in the sample, which may not be the maximum
// value ever to be part of the sample.
func (s *ExpDecaySample) Max() int64 {
return SampleMax(s.Values())
}
// Mean returns the mean of the values in the sample.
func (s *ExpDecaySample) Mean() float64 {
return SampleMean(s.Values())
}
// Min returns the minimum value in the sample, which may not be the minimum
// value ever to be part of the sample.
func (s *ExpDecaySample) Min() int64 {
return SampleMin(s.Values())
}
// Percentile returns an arbitrary percentile of values in the sample.
func (s *ExpDecaySample) Percentile(p float64) float64 {
return SamplePercentile(s.Values(), p)
}
// Percentiles returns a slice of arbitrary percentiles of values in the
// sample.
func (s *ExpDecaySample) Percentiles(ps []float64) []float64 {
return SamplePercentiles(s.Values(), ps)
}
// Size returns the size of the sample, which is at most the reservoir size.
func (s *ExpDecaySample) Size() int {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.values.Size()
}
// Snapshot returns a read-only copy of the sample.
func (s *ExpDecaySample) Snapshot() Sample {
s.mutex.Lock()
defer s.mutex.Unlock()
vals := s.values.Values()
values := make([]int64, len(vals))
for i, v := range vals {
values[i] = v.v
}
return &SampleSnapshot{
count: s.count,
values: values,
}
}
// StdDev returns the standard deviation of the values in the sample.
func (s *ExpDecaySample) StdDev() float64 {
return SampleStdDev(s.Values())
}
// Sum returns the sum of the values in the sample.
func (s *ExpDecaySample) Sum() int64 {
return SampleSum(s.Values())
}
// Update samples a new value.
func (s *ExpDecaySample) Update(v int64) {
s.update(time.Now(), v)
}
// Values returns a copy of the values in the sample.
func (s *ExpDecaySample) Values() []int64 {
s.mutex.Lock()
defer s.mutex.Unlock()
vals := s.values.Values()
values := make([]int64, len(vals))
for i, v := range vals {
values[i] = v.v
}
return values
}
// Variance returns the variance of the values in the sample.
func (s *ExpDecaySample) Variance() float64 {
return SampleVariance(s.Values())
}
// update samples a new value at a particular timestamp. This is a method all
// its own to facilitate testing.
func (s *ExpDecaySample) update(t time.Time, v int64) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.count++
if s.values.Size() == s.reservoirSize {
s.values.Pop()
}
s.values.Push(expDecaySample{
k: math.Exp(t.Sub(s.t0).Seconds()*s.alpha) / rand.Float64(),
v: v,
})
if t.After(s.t1) {
values := s.values.Values()
t0 := s.t0
s.values.Clear()
s.t0 = t
s.t1 = s.t0.Add(rescaleThreshold)
for _, v := range values {
v.k = v.k * math.Exp(-s.alpha*s.t0.Sub(t0).Seconds())
s.values.Push(v)
}
}
}
// NilSample is a no-op Sample.
type NilSample struct{}
// Clear is a no-op.
func (NilSample) Clear() {}
// Count is a no-op.
func (NilSample) Count() int64 { return 0 }
// Max is a no-op.
func (NilSample) Max() int64 { return 0 }
// Mean is a no-op.
func (NilSample) Mean() float64 { return 0.0 }
// Min is a no-op.
func (NilSample) Min() int64 { return 0 }
// Percentile is a no-op.
func (NilSample) Percentile(p float64) float64 { return 0.0 }
// Percentiles is a no-op.
func (NilSample) Percentiles(ps []float64) []float64 {
return make([]float64, len(ps))
}
// Size is a no-op.
func (NilSample) Size() int { return 0 }
// Sample is a no-op.
func (NilSample) Snapshot() Sample { return NilSample{} }
// StdDev is a no-op.
func (NilSample) StdDev() float64 { return 0.0 }
// Sum is a no-op.
func (NilSample) Sum() int64 { return 0 }
// Update is a no-op.
func (NilSample) Update(v int64) {}
// Values is a no-op.
func (NilSample) Values() []int64 { return []int64{} }
// Variance is a no-op.
func (NilSample) Variance() float64 { return 0.0 }
// SampleMax returns the maximum value of the slice of int64.
func SampleMax(values []int64) int64 {
if 0 == len(values) {
return 0
}
var max int64 = math.MinInt64
for _, v := range values {
if max < v {
max = v
}
}
return max
}
// SampleMean returns the mean value of the slice of int64.
func SampleMean(values []int64) float64 {
if 0 == len(values) {
return 0.0
}
return float64(SampleSum(values)) / float64(len(values))
}
// SampleMin returns the minimum value of the slice of int64.
func SampleMin(values []int64) int64 {
if 0 == len(values) {
return 0
}
var min int64 = math.MaxInt64
for _, v := range values {
if min > v {
min = v
}
}
return min
}
// SamplePercentiles returns an arbitrary percentile of the slice of int64.
func SamplePercentile(values int64Slice, p float64) float64 {
return SamplePercentiles(values, []float64{p})[0]
}
// SamplePercentiles returns a slice of arbitrary percentiles of the slice of
// int64.
func SamplePercentiles(values int64Slice, ps []float64) []float64 {
scores := make([]float64, len(ps))
size := len(values)
if size > 0 {
sort.Sort(values)
for i, p := range ps {
pos := p * float64(size+1)
if pos < 1.0 {
scores[i] = float64(values[0])
} else if pos >= float64(size) {
scores[i] = float64(values[size-1])
} else {
lower := float64(values[int(pos)-1])
upper := float64(values[int(pos)])
scores[i] = lower + (pos-math.Floor(pos))*(upper-lower)
}
}
}
return scores
}
// SampleSnapshot is a read-only copy of another Sample.
type SampleSnapshot struct {
count int64
values []int64
}
// Clear panics.
func (*SampleSnapshot) Clear() {
panic("Clear called on a SampleSnapshot")
}
// Count returns the count of inputs at the time the snapshot was taken.
func (s *SampleSnapshot) Count() int64 { return s.count }
// Max returns the maximal value at the time the snapshot was taken.
func (s *SampleSnapshot) Max() int64 { return SampleMax(s.values) }
// Mean returns the mean value at the time the snapshot was taken.
func (s *SampleSnapshot) Mean() float64 { return SampleMean(s.values) }
// Min returns the minimal value at the time the snapshot was taken.
func (s *SampleSnapshot) Min() int64 { return SampleMin(s.values) }
// Percentile returns an arbitrary percentile of values at the time the
// snapshot was taken.
func (s *SampleSnapshot) Percentile(p float64) float64 {
return SamplePercentile(s.values, p)
}
// Percentiles returns a slice of arbitrary percentiles of values at the time
// the snapshot was taken.
func (s *SampleSnapshot) Percentiles(ps []float64) []float64 {
return SamplePercentiles(s.values, ps)
}
// Size returns the size of the sample at the time the snapshot was taken.
func (s *SampleSnapshot) Size() int { return len(s.values) }
// Snapshot returns the snapshot.
func (s *SampleSnapshot) Snapshot() Sample { return s }
// StdDev returns the standard deviation of values at the time the snapshot was
// taken.
func (s *SampleSnapshot) StdDev() float64 { return SampleStdDev(s.values) }
// Sum returns the sum of values at the time the snapshot was taken.
func (s *SampleSnapshot) Sum() int64 { return SampleSum(s.values) }
// Update panics.
func (*SampleSnapshot) Update(int64) {
panic("Update called on a SampleSnapshot")
}
// Values returns a copy of the values in the sample.
func (s *SampleSnapshot) Values() []int64 {
values := make([]int64, len(s.values))
copy(values, s.values)
return values
}
// Variance returns the variance of values at the time the snapshot was taken.
func (s *SampleSnapshot) Variance() float64 { return SampleVariance(s.values) }
// SampleStdDev returns the standard deviation of the slice of int64.
func SampleStdDev(values []int64) float64 {
return math.Sqrt(SampleVariance(values))
}
// SampleSum returns the sum of the slice of int64.
func SampleSum(values []int64) int64 {
var sum int64
for _, v := range values {
sum += v
}
return sum
}
// SampleVariance returns the variance of the slice of int64.
func SampleVariance(values []int64) float64 {
if 0 == len(values) {
return 0.0
}
m := SampleMean(values)
var sum float64
for _, v := range values {
d := float64(v) - m
sum += d * d
}
return sum / float64(len(values))
}
// A uniform sample using Vitter's Algorithm R.
//
// <http://www.cs.umd.edu/~samir/498/vitter.pdf>
type UniformSample struct {
count int64
mutex sync.Mutex
reservoirSize int
values []int64
}
// NewUniformSample constructs a new uniform sample with the given reservoir
// size.
func NewUniformSample(reservoirSize int) Sample {
if UseNilMetrics {
return NilSample{}
}
return &UniformSample{
reservoirSize: reservoirSize,
values: make([]int64, 0, reservoirSize),
}
}
// Clear clears all samples.
func (s *UniformSample) Clear() {
s.mutex.Lock()
defer s.mutex.Unlock()
s.count = 0
s.values = make([]int64, 0, s.reservoirSize)
}
// Count returns the number of samples recorded, which may exceed the
// reservoir size.
func (s *UniformSample) Count() int64 {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.count
}
// Max returns the maximum value in the sample, which may not be the maximum
// value ever to be part of the sample.
func (s *UniformSample) Max() int64 {
s.mutex.Lock()
defer s.mutex.Unlock()
return SampleMax(s.values)
}
// Mean returns the mean of the values in the sample.
func (s *UniformSample) Mean() float64 {
s.mutex.Lock()
defer s.mutex.Unlock()
return SampleMean(s.values)
}
// Min returns the minimum value in the sample, which may not be the minimum
// value ever to be part of the sample.
func (s *UniformSample) Min() int64 {
s.mutex.Lock()
defer s.mutex.Unlock()
return SampleMin(s.values)
}
// Percentile returns an arbitrary percentile of values in the sample.
func (s *UniformSample) Percentile(p float64) float64 {
s.mutex.Lock()
defer s.mutex.Unlock()
return SamplePercentile(s.values, p)
}
// Percentiles returns a slice of arbitrary percentiles of values in the
// sample.
func (s *UniformSample) Percentiles(ps []float64) []float64 {
s.mutex.Lock()
defer s.mutex.Unlock()
return SamplePercentiles(s.values, ps)
}
// Size returns the size of the sample, which is at most the reservoir size.
func (s *UniformSample) Size() int {
s.mutex.Lock()
defer s.mutex.Unlock()
return len(s.values)
}
// Snapshot returns a read-only copy of the sample.
func (s *UniformSample) Snapshot() Sample {
s.mutex.Lock()
defer s.mutex.Unlock()
values := make([]int64, len(s.values))
copy(values, s.values)
return &SampleSnapshot{
count: s.count,
values: values,
}
}
// StdDev returns the standard deviation of the values in the sample.
func (s *UniformSample) StdDev() float64 {
s.mutex.Lock()
defer s.mutex.Unlock()
return SampleStdDev(s.values)
}
// Sum returns the sum of the values in the sample.
func (s *UniformSample) Sum() int64 {
s.mutex.Lock()
defer s.mutex.Unlock()
return SampleSum(s.values)
}
// Update samples a new value.
func (s *UniformSample) Update(v int64) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.count++
if len(s.values) < s.reservoirSize {
s.values = append(s.values, v)
} else {
r := rand.Int63n(s.count)
if r < int64(len(s.values)) {
s.values[int(r)] = v
}
}
}
// Values returns a copy of the values in the sample.
func (s *UniformSample) Values() []int64 {
s.mutex.Lock()
defer s.mutex.Unlock()
values := make([]int64, len(s.values))
copy(values, s.values)
return values
}
// Variance returns the variance of the values in the sample.
func (s *UniformSample) Variance() float64 {
s.mutex.Lock()
defer s.mutex.Unlock()
return SampleVariance(s.values)
}
// expDecaySample represents an individual sample in a heap.
type expDecaySample struct {
k float64
v int64
}
func newExpDecaySampleHeap(reservoirSize int) *expDecaySampleHeap {
return &expDecaySampleHeap{make([]expDecaySample, 0, reservoirSize)}
}
// expDecaySampleHeap is a min-heap of expDecaySamples.
// The internal implementation is copied from the standard library's container/heap
type expDecaySampleHeap struct {
s []expDecaySample
}
func (h *expDecaySampleHeap) Clear() {
h.s = h.s[:0]
}
func (h *expDecaySampleHeap) Push(s expDecaySample) {
n := len(h.s)
h.s = h.s[0 : n+1]
h.s[n] = s
h.up(n)
}
func (h *expDecaySampleHeap) Pop() expDecaySample {
n := len(h.s) - 1
h.s[0], h.s[n] = h.s[n], h.s[0]
h.down(0, n)
n = len(h.s)
s := h.s[n-1]
h.s = h.s[0 : n-1]
return s
}
func (h *expDecaySampleHeap) Size() int {
return len(h.s)
}
func (h *expDecaySampleHeap) Values() []expDecaySample {
return h.s
}
func (h *expDecaySampleHeap) up(j int) {
for {
i := (j - 1) / 2 // parent
if i == j || !(h.s[j].k < h.s[i].k) {
break
}
h.s[i], h.s[j] = h.s[j], h.s[i]
j = i
}
}
func (h *expDecaySampleHeap) down(i, n int) {
for {
j1 := 2*i + 1
if j1 >= n || j1 < 0 { // j1 < 0 after int overflow
break
}
j := j1 // left child
if j2 := j1 + 1; j2 < n && !(h.s[j1].k < h.s[j2].k) {
j = j2 // = 2*i + 2 // right child
}
if !(h.s[j].k < h.s[i].k) {
break
}
h.s[i], h.s[j] = h.s[j], h.s[i]
i = j
}
}
type int64Slice []int64
func (p int64Slice) Len() int { return len(p) }
func (p int64Slice) Less(i, j int) bool { return p[i] < p[j] }
func (p int64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
| Godeps/_workspace/src/github.com/rcrowley/go-metrics/sample.go | 0 | https://github.com/pingcap/tidb/commit/58ad162d3418a8a4d1b08884f23e0cef109b67ff | [
0.0008407783461734653,
0.00018187113164458424,
0.00016436261648777872,
0.0001705317699816078,
0.00008513829379808158
] |
{
"id": 4,
"code_window": [
"\t\t\treturn errors.Trace(err)\n",
"\t\t}\n",
"\t\tkeysLocked = append(keysLocked, k)\n",
"\t}\n",
"\n",
"\t// Check dirty store\n",
"\tcurVer, err := globalVersionProvider.CurrentVersion()\n",
"\tif err != nil {\n",
"\t\treturn errors.Trace(err)\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// disable version provider temporarily\n",
"\tlockVersionProvider()\n",
"\tdefer unlockVersionProvider()\n",
"\n"
],
"file_path": "store/localstore/txn.go",
"type": "replace",
"edit_start_line_idx": 219
} | // Copyright 2015 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
// Package mock is just for test only.
package mock
import (
"fmt"
"github.com/pingcap/tidb/context"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/terror"
)
var _ context.Context = (*Context)(nil)
// Context represents mocked context.Context.
type Context struct {
values map[fmt.Stringer]interface{}
// mock global variable
}
// SetValue implements context.Context SetValue interface.
func (c *Context) SetValue(key fmt.Stringer, value interface{}) {
c.values[key] = value
}
// Value implements context.Context Value interface.
func (c *Context) Value(key fmt.Stringer) interface{} {
value := c.values[key]
return value
}
// ClearValue implements context.Context ClearValue interface.
func (c *Context) ClearValue(key fmt.Stringer) {
delete(c.values, key)
}
// GetTxn implements context.Context GetTxn interface.
func (c *Context) GetTxn(forceNew bool) (kv.Transaction, error) {
return nil, nil
}
// FinishTxn implements context.Context FinishTxn interface.
func (c *Context) FinishTxn(rollback bool) error {
return nil
}
// GetGlobalStatusVar implements GlobalVarAccessor GetGlobalStatusVar interface.
func (c *Context) GetGlobalStatusVar(ctx context.Context, name string) (string, error) {
v := variable.GetStatusVar(name)
if v == nil {
return "", terror.UnknownStatusVar.Gen("unknown status variable: %s", name)
}
return v.Value, nil
}
// SetGlobalStatusVar implements GlobalVarAccessor SetGlobalStatusVar interface.
func (c *Context) SetGlobalStatusVar(ctx context.Context, name string, value string) error {
v := variable.GetStatusVar(name)
if v == nil {
return terror.UnknownStatusVar.Gen("unknown status variable: %s", name)
}
v.Value = value
return nil
}
// GetGlobalSysVar implements GlobalVarAccessor GetGlobalSysVar interface.
func (c *Context) GetGlobalSysVar(ctx context.Context, name string) (string, error) {
v := variable.GetSysVar(name)
if v == nil {
return "", terror.UnknownSystemVar.Gen("unknown sys variable: %s", name)
}
return v.Value, nil
}
// SetGlobalSysVar implements GlobalVarAccessor SetGlobalSysVar interface.
func (c *Context) SetGlobalSysVar(ctx context.Context, name string, value string) error {
v := variable.GetSysVar(name)
if v == nil {
return terror.UnknownSystemVar.Gen("unknown sys variable: %s", name)
}
v.Value = value
return nil
}
// NewContext creates a new mocked context.Context.
func NewContext() *Context {
return &Context{
values: make(map[fmt.Stringer]interface{}),
}
}
| util/mock/context.go | 0 | https://github.com/pingcap/tidb/commit/58ad162d3418a8a4d1b08884f23e0cef109b67ff | [
0.000177511406945996,
0.00016986286209430546,
0.00016542420780751854,
0.00016925993259064853,
0.000003985036983067403
] |
{
"id": 0,
"code_window": [
"\tsecretResyncPeriod = time.Minute\n",
"\n",
"\tserviceAccountNameAnnotationKey = \"istio.io/service-account.name\"\n",
"\n",
"\trecommendedMinGracePeriodRatio = 0.3\n",
"\trecommendedMaxGracePeriodRatio = 0.8\n",
"\n",
"\t// The size of a private key for a leaf certificate.\n",
"\tkeySize = 2048\n",
")\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\trecommendedMinGracePeriodRatio = 0.2\n"
],
"file_path": "security/pkg/pki/ca/controller/secret.go",
"type": "replace",
"edit_start_line_idx": 53
} | // Copyright 2017 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 controller
import (
"bytes"
"fmt"
"reflect"
"time"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/cache"
"istio.io/istio/pkg/log"
"istio.io/istio/security/pkg/pki/ca"
"istio.io/istio/security/pkg/pki/util"
)
/* #nosec: disable gas linter */
const (
// The Istio secret annotation type
IstioSecretType = "istio.io/key-and-cert"
// The ID/name for the certificate chain file.
CertChainID = "cert-chain.pem"
// The ID/name for the private key file.
PrivateKeyID = "key.pem"
// The ID/name for the CA root certificate file.
RootCertID = "root-cert.pem"
secretNamePrefix = "istio."
secretResyncPeriod = time.Minute
serviceAccountNameAnnotationKey = "istio.io/service-account.name"
recommendedMinGracePeriodRatio = 0.3
recommendedMaxGracePeriodRatio = 0.8
// The size of a private key for a leaf certificate.
keySize = 2048
)
// SecretController manages the service accounts' secrets that contains Istio keys and certificates.
type SecretController struct {
ca ca.CertificateAuthority
certTTL time.Duration
core corev1.CoreV1Interface
// Length of the grace period for the certificate rotation.
gracePeriodRatio float32
minGracePeriod time.Duration
// Controller and store for service account objects.
saController cache.Controller
saStore cache.Store
// Controller and store for secret objects.
scrtController cache.Controller
scrtStore cache.Store
}
// NewSecretController returns a pointer to a newly constructed SecretController instance.
func NewSecretController(ca ca.CertificateAuthority, certTTL time.Duration, gracePeriodRatio float32, minGracePeriod time.Duration,
core corev1.CoreV1Interface, namespace string) (*SecretController, error) {
if gracePeriodRatio < 0 || gracePeriodRatio > 1 {
return nil, fmt.Errorf("grace period ratio %f should be within [0, 1]", gracePeriodRatio)
}
if gracePeriodRatio < recommendedMinGracePeriodRatio || gracePeriodRatio > recommendedMaxGracePeriodRatio {
log.Warnf("grace period ratio %f is out of the recommended window [%.2f, %.2f]",
gracePeriodRatio, recommendedMinGracePeriodRatio, recommendedMaxGracePeriodRatio)
}
c := &SecretController{
ca: ca,
certTTL: certTTL,
gracePeriodRatio: gracePeriodRatio,
minGracePeriod: minGracePeriod,
core: core,
}
saLW := &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
return core.ServiceAccounts(namespace).List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
return core.ServiceAccounts(namespace).Watch(options)
},
}
rehf := cache.ResourceEventHandlerFuncs{
AddFunc: c.saAdded,
DeleteFunc: c.saDeleted,
UpdateFunc: c.saUpdated,
}
c.saStore, c.saController = cache.NewInformer(saLW, &v1.ServiceAccount{}, time.Minute, rehf)
istioSecretSelector := fields.SelectorFromSet(map[string]string{"type": IstioSecretType}).String()
scrtLW := &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
options.FieldSelector = istioSecretSelector
return core.Secrets(namespace).List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.FieldSelector = istioSecretSelector
return core.Secrets(namespace).Watch(options)
},
}
c.scrtStore, c.scrtController =
cache.NewInformer(scrtLW, &v1.Secret{}, secretResyncPeriod, cache.ResourceEventHandlerFuncs{
DeleteFunc: c.scrtDeleted,
UpdateFunc: c.scrtUpdated,
})
return c, nil
}
// Run starts the SecretController until a value is sent to stopCh.
func (sc *SecretController) Run(stopCh chan struct{}) {
go sc.scrtController.Run(stopCh)
go sc.saController.Run(stopCh)
}
// Handles the event where a service account is added.
func (sc *SecretController) saAdded(obj interface{}) {
acct := obj.(*v1.ServiceAccount)
sc.upsertSecret(acct.GetName(), acct.GetNamespace())
}
// Handles the event where a service account is deleted.
func (sc *SecretController) saDeleted(obj interface{}) {
acct := obj.(*v1.ServiceAccount)
sc.deleteSecret(acct.GetName(), acct.GetNamespace())
}
// Handles the event where a service account is updated.
func (sc *SecretController) saUpdated(oldObj, curObj interface{}) {
if reflect.DeepEqual(oldObj, curObj) {
// Nothing is changed. The method is invoked by periodical re-sync with the apiserver.
return
}
oldSa := oldObj.(*v1.ServiceAccount)
curSa := curObj.(*v1.ServiceAccount)
curName := curSa.GetName()
curNamespace := curSa.GetNamespace()
oldName := oldSa.GetName()
oldNamespace := oldSa.GetNamespace()
// We only care the name and namespace of a service account.
if curName != oldName || curNamespace != oldNamespace {
sc.deleteSecret(oldName, oldNamespace)
sc.upsertSecret(curName, curNamespace)
log.Infof("Service account \"%s\" in namespace \"%s\" has been updated to \"%s\" in namespace \"%s\"",
oldName, oldNamespace, curName, curNamespace)
}
}
func (sc *SecretController) upsertSecret(saName, saNamespace string) {
secret := &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{serviceAccountNameAnnotationKey: saName},
Name: getSecretName(saName),
Namespace: saNamespace,
},
Type: IstioSecretType,
}
_, exists, err := sc.scrtStore.Get(secret)
if err != nil {
log.Errorf("Failed to get secret from the store (error %v)", err)
}
if exists {
// Do nothing for existing secrets. Rotating expiring certs are handled by the `scrtUpdated` method.
return
}
// Now we know the secret does not exist yet. So we create a new one.
chain, key, err := sc.generateKeyAndCert(saName, saNamespace)
if err != nil {
log.Errorf("Failed to generate key and certificate for service account %q in namespace %q (error %v)",
saName, saNamespace, err)
return
}
rootCert := sc.ca.GetRootCertificate()
secret.Data = map[string][]byte{
CertChainID: chain,
PrivateKeyID: key,
RootCertID: rootCert,
}
_, err = sc.core.Secrets(saNamespace).Create(secret)
if err != nil {
log.Errorf("Failed to create secret (error: %s)", err)
return
}
log.Infof("Istio secret for service account \"%s\" in namespace \"%s\" has been created", saName, saNamespace)
}
func (sc *SecretController) deleteSecret(saName, saNamespace string) {
err := sc.core.Secrets(saNamespace).Delete(getSecretName(saName), nil)
// kube-apiserver returns NotFound error when the secret is successfully deleted.
if err == nil || errors.IsNotFound(err) {
log.Infof("Istio secret for service account \"%s\" in namespace \"%s\" has been deleted", saName, saNamespace)
return
}
log.Errorf("Failed to delete Istio secret for service account \"%s\" in namespace \"%s\" (error: %s)",
saName, saNamespace, err)
}
func (sc *SecretController) scrtDeleted(obj interface{}) {
scrt, ok := obj.(*v1.Secret)
if !ok {
log.Warnf("Failed to convert to secret object: %v", obj)
return
}
log.Infof("Re-create deleted Istio secret")
saName := scrt.Annotations[serviceAccountNameAnnotationKey]
sc.upsertSecret(saName, scrt.GetNamespace())
}
func (sc *SecretController) generateKeyAndCert(saName string, saNamespace string) ([]byte, []byte, error) {
id := fmt.Sprintf("%s://cluster.local/ns/%s/sa/%s", util.URIScheme, saNamespace, saName)
options := util.CertOptions{
Host: id,
RSAKeySize: keySize,
}
csrPEM, keyPEM, err := util.GenCSR(options)
if err != nil {
return nil, nil, err
}
certPEM, err := sc.ca.Sign(csrPEM, sc.certTTL, false)
if err != nil {
return nil, nil, err
}
return certPEM, keyPEM, nil
}
func (sc *SecretController) scrtUpdated(oldObj, newObj interface{}) {
scrt, ok := newObj.(*v1.Secret)
if !ok {
log.Warnf("Failed to convert to secret object: %v", newObj)
return
}
certBytes := scrt.Data[CertChainID]
cert, err := util.ParsePemEncodedCertificate(certBytes)
if err != nil {
// TODO: we should refresh secret in this case since the secret contains an
// invalid cert.
log.Errora(err)
return
}
certLifeTimeLeft := time.Until(cert.NotAfter)
certLifeTime := cert.NotAfter.Sub(cert.NotBefore)
// TODO(myidpt): we may introduce a minimum gracePeriod, without making the config too complex.
gracePeriod := time.Duration(sc.gracePeriodRatio) * certLifeTime
if gracePeriod < sc.minGracePeriod {
log.Warnf("gracePeriod (%v * %f) = %v is less than minGracePeriod %v. Apply minGracePeriod.",
certLifeTime, sc.gracePeriodRatio, sc.minGracePeriod)
gracePeriod = sc.minGracePeriod
}
rootCertificate := sc.ca.GetRootCertificate()
// Refresh the secret if 1) the certificate contained in the secret is about
// to expire, or 2) the root certificate in the secret is different than the
// one held by the ca (this may happen when the CA is restarted and
// a new self-signed CA cert is generated).
if certLifeTimeLeft < gracePeriod || !bytes.Equal(rootCertificate, scrt.Data[RootCertID]) {
namespace := scrt.GetNamespace()
name := scrt.GetName()
log.Infof("Refreshing secret %s/%s, either the leaf certificate is about to expire "+
"or the root certificate is outdated", namespace, name)
saName := scrt.Annotations[serviceAccountNameAnnotationKey]
chain, key, err := sc.generateKeyAndCert(saName, namespace)
if err != nil {
log.Errorf("Failed to generate key and certificate for service account %q in namespace %q (error %v)",
saName, namespace, err)
return
}
scrt.Data[CertChainID] = chain
scrt.Data[PrivateKeyID] = key
scrt.Data[RootCertID] = rootCertificate
if _, err = sc.core.Secrets(namespace).Update(scrt); err != nil {
log.Errorf("Failed to update secret %s/%s (error: %s)", namespace, name, err)
}
}
}
func getSecretName(saName string) string {
return secretNamePrefix + saName
}
| security/pkg/pki/ca/controller/secret.go | 1 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.9957559704780579,
0.09653829783201218,
0.00016931093705352396,
0.0010484781814739108,
0.2839774191379547
] |
{
"id": 0,
"code_window": [
"\tsecretResyncPeriod = time.Minute\n",
"\n",
"\tserviceAccountNameAnnotationKey = \"istio.io/service-account.name\"\n",
"\n",
"\trecommendedMinGracePeriodRatio = 0.3\n",
"\trecommendedMaxGracePeriodRatio = 0.8\n",
"\n",
"\t// The size of a private key for a leaf certificate.\n",
"\tkeySize = 2048\n",
")\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\trecommendedMinGracePeriodRatio = 0.2\n"
],
"file_path": "security/pkg/pki/ca/controller/secret.go",
"type": "replace",
"edit_start_line_idx": 53
} | /*******************************************************************************
* Copyright (c) 2017 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 application.rest;
import java.io.StringReader;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonReader;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.CookieParam;
import javax.ws.rs.PathParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.ResponseProcessingException;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/")
public class LibertyRestEndpoint extends Application {
private final static Boolean ratings_enabled = Boolean.valueOf(System.getenv("ENABLE_RATINGS"));
private final static String star_color = System.getenv("STAR_COLOR") == null ? "black" : System.getenv("STAR_COLOR");
private final static String ratings_service = "http://ratings:9080/ratings";
private String getJsonResponse (String productId, int starsReviewer1, int starsReviewer2) {
String result = "{";
result += "\"id\": \"" + productId + "\",";
result += "\"reviews\": [";
// reviewer 1:
result += "{";
result += " \"reviewer\": \"Reviewer1\",";
result += " \"text\": \"An extremely entertaining play by Shakespeare. The slapstick humour is refreshing!\"";
if (ratings_enabled) {
if (starsReviewer1 != -1) {
result += ", \"rating\": {\"stars\": " + starsReviewer1 + ", \"color\": \"" + star_color + "\"}";
}
else {
result += ", \"rating\": {\"error\": \"Ratings service is currently unavailable\"}";
}
}
result += "},";
// reviewer 2:
result += "{";
result += " \"reviewer\": \"Reviewer2\",";
result += " \"text\": \"Absolutely fun and entertaining. The play lacks thematic depth when compared to other plays by Shakespeare.\"";
if (ratings_enabled) {
if (starsReviewer2 != -1) {
result += ", \"rating\": {\"stars\": " + starsReviewer2 + ", \"color\": \"" + star_color + "\"}";
}
else {
result += ", \"rating\": {\"error\": \"Ratings service is currently unavailable\"}";
}
}
result += "}";
result += "]";
result += "}";
return result;
}
private JsonObject getRatings(String productId, Cookie user, String xreq, String xtraceid, String xspanid,
String xparentspanid, String xsampled, String xflags, String xotspan){
ClientBuilder cb = ClientBuilder.newBuilder();
String timeout = star_color.equals("black") ? "10000" : "2500";
cb.property("com.ibm.ws.jaxrs.client.connection.timeout", timeout);
cb.property("com.ibm.ws.jaxrs.client.receive.timeout", timeout);
Client client = cb.build();
WebTarget ratingsTarget = client.target(ratings_service + "/" + productId);
Invocation.Builder builder = ratingsTarget.request(MediaType.APPLICATION_JSON);
if(xreq!=null) {
builder.header("x-request-id",xreq);
}
if(xtraceid!=null) {
builder.header("x-b3-traceid",xtraceid);
}
if(xspanid!=null) {
builder.header("x-b3-spanid",xspanid);
}
if(xparentspanid!=null) {
builder.header("x-b3-parentspanid",xparentspanid);
}
if(xsampled!=null) {
builder.header("x-b3-sampled",xsampled);
}
if(xflags!=null) {
builder.header("x-b3-flags",xflags);
}
if(xotspan!=null) {
builder.header("x-ot-span-context",xotspan);
}
if(user!=null) {
builder.cookie(user);
}
Response r = builder.get();
int statusCode = r.getStatusInfo().getStatusCode();
if (statusCode == Response.Status.OK.getStatusCode() ) {
StringReader stringReader = new StringReader(r.readEntity(String.class));
try (JsonReader jsonReader = Json.createReader(stringReader)) {
JsonObject j = jsonReader.readObject();
return j;
}
}else{
System.out.println("Error: unable to contact "+ratings_service+" got status of "+statusCode);
return null;
}
}
@GET
@Path("/health")
public Response health() {
return Response.ok().type(MediaType.APPLICATION_JSON).entity("{\"status\": \"Reviews is healthy\"}").build();
}
@GET
@Path("/reviews/{productId}")
public Response bookReviewsById(@PathParam("productId") int productId,
@CookieParam("user") Cookie user,
@HeaderParam("x-request-id") String xreq,
@HeaderParam("x-b3-traceid") String xtraceid,
@HeaderParam("x-b3-spanid") String xspanid,
@HeaderParam("x-b3-parentspanid") String xparentspanid,
@HeaderParam("x-b3-sampled") String xsampled,
@HeaderParam("x-b3-flags") String xflags,
@HeaderParam("x-ot-span-context") String xotspan) {
int starsReviewer1 = -1;
int starsReviewer2 = -1;
if (ratings_enabled) {
JsonObject ratingsResponse = getRatings(Integer.toString(productId), user, xreq, xtraceid, xspanid, xparentspanid, xsampled, xflags, xotspan);
if (ratingsResponse != null) {
if (ratingsResponse.containsKey("ratings")) {
JsonObject ratings = ratingsResponse.getJsonObject("ratings");
if (ratings.containsKey("Reviewer1")){
starsReviewer1 = ratings.getInt("Reviewer1");
}
if (ratings.containsKey("Reviewer2")){
starsReviewer2 = ratings.getInt("Reviewer2");
}
}
}
}
String jsonResStr = getJsonResponse(Integer.toString(productId), starsReviewer1, starsReviewer2);
return Response.ok().type(MediaType.APPLICATION_JSON).entity(jsonResStr).build();
}
}
| samples/bookinfo/src/reviews/reviews-application/src/main/java/application/rest/LibertyRestEndpoint.java | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.00017939379904419184,
0.0001757898717187345,
0.00016924798546824604,
0.00017629709327593446,
0.0000029119355531292967
] |
{
"id": 0,
"code_window": [
"\tsecretResyncPeriod = time.Minute\n",
"\n",
"\tserviceAccountNameAnnotationKey = \"istio.io/service-account.name\"\n",
"\n",
"\trecommendedMinGracePeriodRatio = 0.3\n",
"\trecommendedMaxGracePeriodRatio = 0.8\n",
"\n",
"\t// The size of a private key for a leaf certificate.\n",
"\tkeySize = 2048\n",
")\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\trecommendedMinGracePeriodRatio = 0.2\n"
],
"file_path": "security/pkg/pki/ca/controller/secret.go",
"type": "replace",
"edit_start_line_idx": 53
} | // Copyright 2017 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 adapter
import "context"
// Service defines the service specific details.
type Service struct {
// Fully qualified name of the service.
FullName string
}
// RequestData defines information about a request, for example details about the destination service.
//
// This data is delivered to the adapters through the passed in context object.
// Adapter can retrieve this data from the context by invoking `RequestDataFromContext`.
type RequestData struct {
// Details about the destination service.
DestinationService Service
}
// The key type is unexported to prevent collisions with context keys defined in
// other packages.
type reqDataKey int
// requestDataKey is the context key for the RequestData object. If this package defined other context keys,
// they would have different integer values.
const requestDataKey reqDataKey = 0
// RequestDataFromContext retrieves the RequestData object contained inside the given context.
// Returns false if the given context does not contains a valid RequestData object.
func RequestDataFromContext(ctx context.Context) (*RequestData, bool) {
reqData, ok := ctx.Value(requestDataKey).(*RequestData)
return reqData, ok
}
// NewContextWithRequestData returns a new Context that carries the provided RequestData value.
func NewContextWithRequestData(ctx context.Context, reqData *RequestData) context.Context {
return context.WithValue(ctx, requestDataKey, reqData)
}
| mixer/pkg/adapter/requestData.go | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.00018107020878233016,
0.00017376919277012348,
0.00016758881974965334,
0.00017300460604019463,
0.000004801334398507606
] |
{
"id": 0,
"code_window": [
"\tsecretResyncPeriod = time.Minute\n",
"\n",
"\tserviceAccountNameAnnotationKey = \"istio.io/service-account.name\"\n",
"\n",
"\trecommendedMinGracePeriodRatio = 0.3\n",
"\trecommendedMaxGracePeriodRatio = 0.8\n",
"\n",
"\t// The size of a private key for a leaf certificate.\n",
"\tkeySize = 2048\n",
")\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\trecommendedMinGracePeriodRatio = 0.2\n"
],
"file_path": "security/pkg/pki/ca/controller/secret.go",
"type": "replace",
"edit_start_line_idx": 53
} | // Copyright 2017 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 (
"flag"
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/cobra/doc"
"istio.io/istio/broker/cmd/shared"
"istio.io/istio/pkg/collateral"
"istio.io/istio/pkg/version"
)
// GetRootCmd generates the root command for broker server.
func GetRootCmd(args []string) *cobra.Command {
rootCmd := &cobra.Command{
Use: "brks",
Short: "The Istio broker exposes the Open Service Broker functionality form a mesh",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if len(args) > 0 {
return fmt.Errorf("'%s' is an invalid argument", args[0])
}
return nil
},
}
rootCmd.SetArgs(args)
rootCmd.PersistentFlags().AddGoFlagSet(flag.CommandLine)
// hack to make flag.Parsed return true such that glog is happy
// about the flags having been parsed
fs := flag.NewFlagSet("", flag.ContinueOnError)
/* #nosec */
_ = fs.Parse([]string{})
flag.CommandLine = fs
rootCmd.AddCommand(serverCmd(shared.Printf, shared.Fatalf))
rootCmd.AddCommand(version.CobraCommand())
rootCmd.AddCommand(collateral.CobraCommand(rootCmd, &doc.GenManHeader{
Title: "Istio Service Broker",
Section: "brks CLI",
Manual: "Istio Service Broker",
}))
return rootCmd
}
| broker/cmd/brks/cmd/root.go | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.00017882921383716166,
0.000175601351656951,
0.0001680486893747002,
0.00017766532255336642,
0.0000037649538171535823
] |
{
"id": 1,
"code_window": [
"\t}\n",
"\n",
"\tcertLifeTimeLeft := time.Until(cert.NotAfter)\n",
"\tcertLifeTime := cert.NotAfter.Sub(cert.NotBefore)\n",
"\t// TODO(myidpt): we may introduce a minimum gracePeriod, without making the config too complex.\n",
"\tgracePeriod := time.Duration(sc.gracePeriodRatio) * certLifeTime\n",
"\tif gracePeriod < sc.minGracePeriod {\n",
"\t\tlog.Warnf(\"gracePeriod (%v * %f) = %v is less than minGracePeriod %v. Apply minGracePeriod.\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t// Because time.Duration only takes int type, multiply gracePeriodRatio by 1000 and then divide it.\n",
"\tgracePeriod := time.Duration(sc.gracePeriodRatio*1000) * certLifeTime / 1000\n"
],
"file_path": "security/pkg/pki/ca/controller/secret.go",
"type": "replace",
"edit_start_line_idx": 282
} | // Copyright 2017 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 controller
import (
"fmt"
"testing"
"time"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/kubernetes/fake"
ktesting "k8s.io/client-go/testing"
"istio.io/istio/security/pkg/pki/util"
)
const (
defaultTTL = time.Hour
defaultGracePeriodRatio = 0.5
defaultMinGracePeriod = 10 * time.Minute
)
type fakeCa struct{}
func (ca *fakeCa) Sign([]byte, time.Duration, bool) ([]byte, error) {
return []byte("fake cert chain"), nil
}
func (ca *fakeCa) GetRootCertificate() []byte {
return []byte("fake root cert")
}
func (ca *fakeCa) GetCertChain() []byte {
return []byte("fake cert chain")
}
func createSecret(saName, scrtName, namespace string) *v1.Secret {
return &v1.Secret{
Data: map[string][]byte{
CertChainID: []byte("fake cert chain"),
PrivateKeyID: []byte("fake key"),
RootCertID: []byte("fake root cert"),
},
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{"istio.io/service-account.name": saName},
Name: scrtName,
Namespace: namespace,
},
Type: IstioSecretType,
}
}
func createServiceAccount(name, namespace string) *v1.ServiceAccount {
return &v1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
}
}
type updatedSas struct {
curSa *v1.ServiceAccount
oldSa *v1.ServiceAccount
}
func TestSecretController(t *testing.T) {
gvr := schema.GroupVersionResource{
Resource: "secrets",
Version: "v1",
}
testCases := map[string]struct {
existingSecret *v1.Secret
saToAdd *v1.ServiceAccount
saToDelete *v1.ServiceAccount
sasToUpdate *updatedSas
expectedActions []ktesting.Action
}{
"adding service account creates new secret": {
saToAdd: createServiceAccount("test", "test-ns"),
expectedActions: []ktesting.Action{
ktesting.NewCreateAction(gvr, "test-ns", createSecret("test", "istio.test", "test-ns")),
},
},
"removing service account deletes existing secret": {
saToDelete: createServiceAccount("deleted", "deleted-ns"),
expectedActions: []ktesting.Action{
ktesting.NewDeleteAction(gvr, "deleted-ns", "istio.deleted"),
},
},
"updating service accounts does nothing if name and namespace are not changed": {
sasToUpdate: &updatedSas{
curSa: createServiceAccount("name", "ns"),
oldSa: createServiceAccount("name", "ns"),
},
expectedActions: []ktesting.Action{},
},
"updating service accounts deletes old secret and creates a new one": {
sasToUpdate: &updatedSas{
curSa: createServiceAccount("new-name", "new-ns"),
oldSa: createServiceAccount("old-name", "old-ns"),
},
expectedActions: []ktesting.Action{
ktesting.NewDeleteAction(gvr, "old-ns", "istio.old-name"),
ktesting.NewCreateAction(gvr, "new-ns", createSecret("new-name", "istio.new-name", "new-ns")),
},
},
"adding new service account does not overwrite existing secret": {
existingSecret: createSecret("test", "istio.test", "test-ns"),
saToAdd: createServiceAccount("test", "test-ns"),
expectedActions: []ktesting.Action{},
},
}
for k, tc := range testCases {
client := fake.NewSimpleClientset()
controller, err := NewSecretController(&fakeCa{}, defaultTTL, defaultGracePeriodRatio, defaultMinGracePeriod,
client.CoreV1(), metav1.NamespaceAll)
if err != nil {
t.Errorf("failed to create secret controller: %v", err)
}
if tc.existingSecret != nil {
err := controller.scrtStore.Add(tc.existingSecret)
if err != nil {
t.Errorf("Failed to add a secret (error %v)", err)
}
}
if tc.saToAdd != nil {
controller.saAdded(tc.saToAdd)
}
if tc.saToDelete != nil {
controller.saDeleted(tc.saToDelete)
}
if tc.sasToUpdate != nil {
controller.saUpdated(tc.sasToUpdate.oldSa, tc.sasToUpdate.curSa)
}
if err := checkActions(client.Actions(), tc.expectedActions); err != nil {
t.Errorf("Case %q: %s", k, err.Error())
}
}
}
func TestRecoverFromDeletedIstioSecret(t *testing.T) {
client := fake.NewSimpleClientset()
controller, err := NewSecretController(&fakeCa{}, defaultTTL, defaultGracePeriodRatio, defaultMinGracePeriod,
client.CoreV1(), metav1.NamespaceAll)
if err != nil {
t.Errorf("failed to create secret controller: %v", err)
}
scrt := createSecret("test", "istio.test", "test-ns")
controller.scrtDeleted(scrt)
gvr := schema.GroupVersionResource{
Resource: "secrets",
Version: "v1",
}
expectedActions := []ktesting.Action{ktesting.NewCreateAction(gvr, "test-ns", scrt)}
if err := checkActions(client.Actions(), expectedActions); err != nil {
t.Error(err)
}
}
func TestUpdateSecret(t *testing.T) {
gvr := schema.GroupVersionResource{
Resource: "secrets",
Version: "v1",
}
testCases := map[string]struct {
expectedActions []ktesting.Action
ttl time.Duration
gracePeriodRatio float32
minGracePeriod time.Duration
rootCert []byte
}{
"Does not update non-expiring secret": {
expectedActions: []ktesting.Action{},
ttl: time.Hour,
gracePeriodRatio: defaultGracePeriodRatio,
minGracePeriod: defaultMinGracePeriod,
},
"Update secret in grace period": {
expectedActions: []ktesting.Action{
ktesting.NewUpdateAction(gvr, "test-ns", createSecret("test", "istio.test", "test-ns")),
},
ttl: defaultTTL,
gracePeriodRatio: 1, // Always in grace period
minGracePeriod: defaultMinGracePeriod,
},
"Update secret in min grace period": {
expectedActions: []ktesting.Action{
ktesting.NewUpdateAction(gvr, "test-ns", createSecret("test", "istio.test", "test-ns")),
},
ttl: 10 * time.Minute,
gracePeriodRatio: defaultGracePeriodRatio,
minGracePeriod: time.Hour, // ttl is always in minGracePeriod
},
"Update expired secret": {
expectedActions: []ktesting.Action{
ktesting.NewUpdateAction(gvr, "test-ns", createSecret("test", "istio.test", "test-ns")),
},
ttl: -time.Second,
gracePeriodRatio: defaultGracePeriodRatio,
minGracePeriod: defaultMinGracePeriod,
},
"Update secret with different root cert": {
expectedActions: []ktesting.Action{
ktesting.NewUpdateAction(gvr, "test-ns", createSecret("test", "istio.test", "test-ns")),
},
ttl: defaultTTL,
gracePeriodRatio: defaultGracePeriodRatio,
minGracePeriod: defaultMinGracePeriod,
rootCert: []byte("Outdated root cert"),
},
}
for k, tc := range testCases {
client := fake.NewSimpleClientset()
controller, err := NewSecretController(&fakeCa{}, time.Hour, tc.gracePeriodRatio, tc.minGracePeriod,
client.CoreV1(), metav1.NamespaceAll)
if err != nil {
t.Errorf("failed to create secret controller: %v", err)
}
scrt := createSecret("test", "istio.test", "test-ns")
if rc := tc.rootCert; rc != nil {
scrt.Data[RootCertID] = rc
}
opts := util.CertOptions{
IsSelfSigned: true,
TTL: tc.ttl,
RSAKeySize: 512,
}
bs, _, err := util.GenCertKeyFromOptions(opts)
if err != nil {
t.Error(err)
}
scrt.Data[CertChainID] = bs
controller.scrtUpdated(nil, scrt)
if err := checkActions(client.Actions(), tc.expectedActions); err != nil {
t.Errorf("Case %q: %s", k, err.Error())
}
}
}
func checkActions(actual, expected []ktesting.Action) error {
if len(actual) != len(expected) {
return fmt.Errorf("unexpected number of actions, want %d but got %d", len(expected), len(actual))
}
for i, action := range actual {
expectedAction := expected[i]
verb := expectedAction.GetVerb()
resource := expectedAction.GetResource().Resource
if !action.Matches(verb, resource) {
return fmt.Errorf("unexpected %dth action, want %q but got %q", i, expectedAction, action)
}
}
return nil
}
| security/pkg/pki/ca/controller/secret_test.go | 1 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.9983931183815002,
0.3070342242717743,
0.00016336746921297163,
0.0001750194642227143,
0.45748981833457947
] |
{
"id": 1,
"code_window": [
"\t}\n",
"\n",
"\tcertLifeTimeLeft := time.Until(cert.NotAfter)\n",
"\tcertLifeTime := cert.NotAfter.Sub(cert.NotBefore)\n",
"\t// TODO(myidpt): we may introduce a minimum gracePeriod, without making the config too complex.\n",
"\tgracePeriod := time.Duration(sc.gracePeriodRatio) * certLifeTime\n",
"\tif gracePeriod < sc.minGracePeriod {\n",
"\t\tlog.Warnf(\"gracePeriod (%v * %f) = %v is less than minGracePeriod %v. Apply minGracePeriod.\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t// Because time.Duration only takes int type, multiply gracePeriodRatio by 1000 and then divide it.\n",
"\tgracePeriod := time.Duration(sc.gracePeriodRatio*1000) * certLifeTime / 1000\n"
],
"file_path": "security/pkg/pki/ca/controller/secret.go",
"type": "replace",
"edit_start_line_idx": 282
} | syntax = "proto3";
package foo.bar;
import "mixer/adapter/model/v1beta1/extensions.proto";
option (istio.mixer.adapter.model.v1beta1.template_variety) = TEMPLATE_VARIETY_CHECK;
message Template {
// Name field is a reserved field that will be inject in the Instance object. The user defined
// Template should not have a Name field, else there will be a name clash.
// 'Name' within the Instance object would represent the name of the Instance:name
// specified in the operator Yaml file.
string Name = 1;
}
| mixer/tools/codegen/pkg/modelgen/testdata/ReservedFieldInTemplate.proto | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.0001739165309118107,
0.00017306167865172029,
0.00017220681183971465,
0.00017306167865172029,
8.548595360480249e-7
] |
{
"id": 1,
"code_window": [
"\t}\n",
"\n",
"\tcertLifeTimeLeft := time.Until(cert.NotAfter)\n",
"\tcertLifeTime := cert.NotAfter.Sub(cert.NotBefore)\n",
"\t// TODO(myidpt): we may introduce a minimum gracePeriod, without making the config too complex.\n",
"\tgracePeriod := time.Duration(sc.gracePeriodRatio) * certLifeTime\n",
"\tif gracePeriod < sc.minGracePeriod {\n",
"\t\tlog.Warnf(\"gracePeriod (%v * %f) = %v is less than minGracePeriod %v. Apply minGracePeriod.\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t// Because time.Duration only takes int type, multiply gracePeriodRatio by 1000 and then divide it.\n",
"\tgracePeriod := time.Duration(sc.gracePeriodRatio*1000) * certLifeTime / 1000\n"
],
"file_path": "security/pkg/pki/ca/controller/secret.go",
"type": "replace",
"edit_start_line_idx": 282
} | FROM scratch
# obtained from debian ca-certs deb using fetch_cacerts.sh
ADD ca-certificates.tgz /
ADD mixs /usr/local/bin/
ENTRYPOINT ["/usr/local/bin/mixs", "server"]
CMD ["--configStoreURL=fs:///etc/opt/mixer/configroot","--configStoreURL=k8s://","--logtostderr","--v=2"]
| mixer/docker/Dockerfile.mixer | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.0001667726319283247,
0.0001667726319283247,
0.0001667726319283247,
0.0001667726319283247,
0
] |
{
"id": 1,
"code_window": [
"\t}\n",
"\n",
"\tcertLifeTimeLeft := time.Until(cert.NotAfter)\n",
"\tcertLifeTime := cert.NotAfter.Sub(cert.NotBefore)\n",
"\t// TODO(myidpt): we may introduce a minimum gracePeriod, without making the config too complex.\n",
"\tgracePeriod := time.Duration(sc.gracePeriodRatio) * certLifeTime\n",
"\tif gracePeriod < sc.minGracePeriod {\n",
"\t\tlog.Warnf(\"gracePeriod (%v * %f) = %v is less than minGracePeriod %v. Apply minGracePeriod.\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t// Because time.Duration only takes int type, multiply gracePeriodRatio by 1000 and then divide it.\n",
"\tgracePeriod := time.Duration(sc.gracePeriodRatio*1000) * certLifeTime / 1000\n"
],
"file_path": "security/pkg/pki/ca/controller/secret.go",
"type": "replace",
"edit_start_line_idx": 282
} | apiVersion: extensions/v1beta1
kind: Deployment
metadata:
creationTimestamp: null
name: hello
spec:
replicas: 7
strategy: {}
template:
metadata:
annotations:
sidecar.istio.io/status: '{"version":"0fd4ba601a8387ce4a6317d83dd1d8af037d3a5f59512824113a5a0fce04e9b8","initContainers":["istio-init"],"containers":["istio-proxy"],"volumes":["istio-envoy","istio-certs"]}'
creationTimestamp: null
labels:
app: hello
tier: backend
track: stable
spec:
containers:
- image: fake.docker.io/google-samples/hello-go-gke:1.0
name: hello
ports:
- containerPort: 80
name: http
resources: {}
- args:
- proxy
- sidecar
- --configPath
- /etc/istio/proxy
- --binaryPath
- /usr/local/bin/envoy
- --serviceCluster
- hello
- --drainDuration
- 2s
- --parentShutdownDuration
- 3s
- --discoveryAddress
- istio-pilot:15007
- --discoveryRefreshDelay
- 1s
- --zipkinAddress
- ""
- --connectTimeout
- 1s
- --statsdUdpAddress
- ""
- --proxyAdminPort
- "15000"
- --controlPlaneAuthPolicy
- NONE
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: INSTANCE_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
image: docker.io/istio/proxy:unittest
imagePullPolicy: IfNotPresent
name: istio-proxy
resources: {}
securityContext:
privileged: false
readOnlyRootFilesystem: true
runAsUser: 1337
volumeMounts:
- mountPath: /etc/istio/proxy
name: istio-envoy
- mountPath: /etc/certs/
name: istio-certs
readOnly: true
initContainers:
- args:
- -p
- "15001"
- -u
- "1337"
image: docker.io/istio/proxy_init:unittest
imagePullPolicy: IfNotPresent
name: istio-init
resources: {}
securityContext:
capabilities:
add:
- NET_ADMIN
volumes:
- emptyDir:
medium: Memory
name: istio-envoy
- name: istio-certs
secret:
optional: true
secretName: istio.default
status: {}
---
| pilot/pkg/kube/inject/testdata/auth.yaml.injected | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.000176710425876081,
0.00017443187243770808,
0.00017110462067648768,
0.00017470702005084604,
0.000001746701173033216
] |
{
"id": 2,
"code_window": [
"\tif gracePeriod < sc.minGracePeriod {\n",
"\t\tlog.Warnf(\"gracePeriod (%v * %f) = %v is less than minGracePeriod %v. Apply minGracePeriod.\",\n",
"\t\t\tcertLifeTime, sc.gracePeriodRatio, sc.minGracePeriod)\n",
"\t\tgracePeriod = sc.minGracePeriod\n",
"\t}\n",
"\trootCertificate := sc.ca.GetRootCertificate()\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tcertLifeTime, sc.gracePeriodRatio, gracePeriod, sc.minGracePeriod)\n"
],
"file_path": "security/pkg/pki/ca/controller/secret.go",
"type": "replace",
"edit_start_line_idx": 285
} | // Copyright 2017 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 controller
import (
"bytes"
"fmt"
"reflect"
"time"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/cache"
"istio.io/istio/pkg/log"
"istio.io/istio/security/pkg/pki/ca"
"istio.io/istio/security/pkg/pki/util"
)
/* #nosec: disable gas linter */
const (
// The Istio secret annotation type
IstioSecretType = "istio.io/key-and-cert"
// The ID/name for the certificate chain file.
CertChainID = "cert-chain.pem"
// The ID/name for the private key file.
PrivateKeyID = "key.pem"
// The ID/name for the CA root certificate file.
RootCertID = "root-cert.pem"
secretNamePrefix = "istio."
secretResyncPeriod = time.Minute
serviceAccountNameAnnotationKey = "istio.io/service-account.name"
recommendedMinGracePeriodRatio = 0.3
recommendedMaxGracePeriodRatio = 0.8
// The size of a private key for a leaf certificate.
keySize = 2048
)
// SecretController manages the service accounts' secrets that contains Istio keys and certificates.
type SecretController struct {
ca ca.CertificateAuthority
certTTL time.Duration
core corev1.CoreV1Interface
// Length of the grace period for the certificate rotation.
gracePeriodRatio float32
minGracePeriod time.Duration
// Controller and store for service account objects.
saController cache.Controller
saStore cache.Store
// Controller and store for secret objects.
scrtController cache.Controller
scrtStore cache.Store
}
// NewSecretController returns a pointer to a newly constructed SecretController instance.
func NewSecretController(ca ca.CertificateAuthority, certTTL time.Duration, gracePeriodRatio float32, minGracePeriod time.Duration,
core corev1.CoreV1Interface, namespace string) (*SecretController, error) {
if gracePeriodRatio < 0 || gracePeriodRatio > 1 {
return nil, fmt.Errorf("grace period ratio %f should be within [0, 1]", gracePeriodRatio)
}
if gracePeriodRatio < recommendedMinGracePeriodRatio || gracePeriodRatio > recommendedMaxGracePeriodRatio {
log.Warnf("grace period ratio %f is out of the recommended window [%.2f, %.2f]",
gracePeriodRatio, recommendedMinGracePeriodRatio, recommendedMaxGracePeriodRatio)
}
c := &SecretController{
ca: ca,
certTTL: certTTL,
gracePeriodRatio: gracePeriodRatio,
minGracePeriod: minGracePeriod,
core: core,
}
saLW := &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
return core.ServiceAccounts(namespace).List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
return core.ServiceAccounts(namespace).Watch(options)
},
}
rehf := cache.ResourceEventHandlerFuncs{
AddFunc: c.saAdded,
DeleteFunc: c.saDeleted,
UpdateFunc: c.saUpdated,
}
c.saStore, c.saController = cache.NewInformer(saLW, &v1.ServiceAccount{}, time.Minute, rehf)
istioSecretSelector := fields.SelectorFromSet(map[string]string{"type": IstioSecretType}).String()
scrtLW := &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
options.FieldSelector = istioSecretSelector
return core.Secrets(namespace).List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.FieldSelector = istioSecretSelector
return core.Secrets(namespace).Watch(options)
},
}
c.scrtStore, c.scrtController =
cache.NewInformer(scrtLW, &v1.Secret{}, secretResyncPeriod, cache.ResourceEventHandlerFuncs{
DeleteFunc: c.scrtDeleted,
UpdateFunc: c.scrtUpdated,
})
return c, nil
}
// Run starts the SecretController until a value is sent to stopCh.
func (sc *SecretController) Run(stopCh chan struct{}) {
go sc.scrtController.Run(stopCh)
go sc.saController.Run(stopCh)
}
// Handles the event where a service account is added.
func (sc *SecretController) saAdded(obj interface{}) {
acct := obj.(*v1.ServiceAccount)
sc.upsertSecret(acct.GetName(), acct.GetNamespace())
}
// Handles the event where a service account is deleted.
func (sc *SecretController) saDeleted(obj interface{}) {
acct := obj.(*v1.ServiceAccount)
sc.deleteSecret(acct.GetName(), acct.GetNamespace())
}
// Handles the event where a service account is updated.
func (sc *SecretController) saUpdated(oldObj, curObj interface{}) {
if reflect.DeepEqual(oldObj, curObj) {
// Nothing is changed. The method is invoked by periodical re-sync with the apiserver.
return
}
oldSa := oldObj.(*v1.ServiceAccount)
curSa := curObj.(*v1.ServiceAccount)
curName := curSa.GetName()
curNamespace := curSa.GetNamespace()
oldName := oldSa.GetName()
oldNamespace := oldSa.GetNamespace()
// We only care the name and namespace of a service account.
if curName != oldName || curNamespace != oldNamespace {
sc.deleteSecret(oldName, oldNamespace)
sc.upsertSecret(curName, curNamespace)
log.Infof("Service account \"%s\" in namespace \"%s\" has been updated to \"%s\" in namespace \"%s\"",
oldName, oldNamespace, curName, curNamespace)
}
}
func (sc *SecretController) upsertSecret(saName, saNamespace string) {
secret := &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{serviceAccountNameAnnotationKey: saName},
Name: getSecretName(saName),
Namespace: saNamespace,
},
Type: IstioSecretType,
}
_, exists, err := sc.scrtStore.Get(secret)
if err != nil {
log.Errorf("Failed to get secret from the store (error %v)", err)
}
if exists {
// Do nothing for existing secrets. Rotating expiring certs are handled by the `scrtUpdated` method.
return
}
// Now we know the secret does not exist yet. So we create a new one.
chain, key, err := sc.generateKeyAndCert(saName, saNamespace)
if err != nil {
log.Errorf("Failed to generate key and certificate for service account %q in namespace %q (error %v)",
saName, saNamespace, err)
return
}
rootCert := sc.ca.GetRootCertificate()
secret.Data = map[string][]byte{
CertChainID: chain,
PrivateKeyID: key,
RootCertID: rootCert,
}
_, err = sc.core.Secrets(saNamespace).Create(secret)
if err != nil {
log.Errorf("Failed to create secret (error: %s)", err)
return
}
log.Infof("Istio secret for service account \"%s\" in namespace \"%s\" has been created", saName, saNamespace)
}
func (sc *SecretController) deleteSecret(saName, saNamespace string) {
err := sc.core.Secrets(saNamespace).Delete(getSecretName(saName), nil)
// kube-apiserver returns NotFound error when the secret is successfully deleted.
if err == nil || errors.IsNotFound(err) {
log.Infof("Istio secret for service account \"%s\" in namespace \"%s\" has been deleted", saName, saNamespace)
return
}
log.Errorf("Failed to delete Istio secret for service account \"%s\" in namespace \"%s\" (error: %s)",
saName, saNamespace, err)
}
func (sc *SecretController) scrtDeleted(obj interface{}) {
scrt, ok := obj.(*v1.Secret)
if !ok {
log.Warnf("Failed to convert to secret object: %v", obj)
return
}
log.Infof("Re-create deleted Istio secret")
saName := scrt.Annotations[serviceAccountNameAnnotationKey]
sc.upsertSecret(saName, scrt.GetNamespace())
}
func (sc *SecretController) generateKeyAndCert(saName string, saNamespace string) ([]byte, []byte, error) {
id := fmt.Sprintf("%s://cluster.local/ns/%s/sa/%s", util.URIScheme, saNamespace, saName)
options := util.CertOptions{
Host: id,
RSAKeySize: keySize,
}
csrPEM, keyPEM, err := util.GenCSR(options)
if err != nil {
return nil, nil, err
}
certPEM, err := sc.ca.Sign(csrPEM, sc.certTTL, false)
if err != nil {
return nil, nil, err
}
return certPEM, keyPEM, nil
}
func (sc *SecretController) scrtUpdated(oldObj, newObj interface{}) {
scrt, ok := newObj.(*v1.Secret)
if !ok {
log.Warnf("Failed to convert to secret object: %v", newObj)
return
}
certBytes := scrt.Data[CertChainID]
cert, err := util.ParsePemEncodedCertificate(certBytes)
if err != nil {
// TODO: we should refresh secret in this case since the secret contains an
// invalid cert.
log.Errora(err)
return
}
certLifeTimeLeft := time.Until(cert.NotAfter)
certLifeTime := cert.NotAfter.Sub(cert.NotBefore)
// TODO(myidpt): we may introduce a minimum gracePeriod, without making the config too complex.
gracePeriod := time.Duration(sc.gracePeriodRatio) * certLifeTime
if gracePeriod < sc.minGracePeriod {
log.Warnf("gracePeriod (%v * %f) = %v is less than minGracePeriod %v. Apply minGracePeriod.",
certLifeTime, sc.gracePeriodRatio, sc.minGracePeriod)
gracePeriod = sc.minGracePeriod
}
rootCertificate := sc.ca.GetRootCertificate()
// Refresh the secret if 1) the certificate contained in the secret is about
// to expire, or 2) the root certificate in the secret is different than the
// one held by the ca (this may happen when the CA is restarted and
// a new self-signed CA cert is generated).
if certLifeTimeLeft < gracePeriod || !bytes.Equal(rootCertificate, scrt.Data[RootCertID]) {
namespace := scrt.GetNamespace()
name := scrt.GetName()
log.Infof("Refreshing secret %s/%s, either the leaf certificate is about to expire "+
"or the root certificate is outdated", namespace, name)
saName := scrt.Annotations[serviceAccountNameAnnotationKey]
chain, key, err := sc.generateKeyAndCert(saName, namespace)
if err != nil {
log.Errorf("Failed to generate key and certificate for service account %q in namespace %q (error %v)",
saName, namespace, err)
return
}
scrt.Data[CertChainID] = chain
scrt.Data[PrivateKeyID] = key
scrt.Data[RootCertID] = rootCertificate
if _, err = sc.core.Secrets(namespace).Update(scrt); err != nil {
log.Errorf("Failed to update secret %s/%s (error: %s)", namespace, name, err)
}
}
}
func getSecretName(saName string) string {
return secretNamePrefix + saName
}
| security/pkg/pki/ca/controller/secret.go | 1 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.998715877532959,
0.17938648164272308,
0.0001627208839636296,
0.000299065257422626,
0.3749426305294037
] |
{
"id": 2,
"code_window": [
"\tif gracePeriod < sc.minGracePeriod {\n",
"\t\tlog.Warnf(\"gracePeriod (%v * %f) = %v is less than minGracePeriod %v. Apply minGracePeriod.\",\n",
"\t\t\tcertLifeTime, sc.gracePeriodRatio, sc.minGracePeriod)\n",
"\t\tgracePeriod = sc.minGracePeriod\n",
"\t}\n",
"\trootCertificate := sc.ca.GetRootCertificate()\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tcertLifeTime, sc.gracePeriodRatio, gracePeriod, sc.minGracePeriod)\n"
],
"file_path": "security/pkg/pki/ca/controller/secret.go",
"type": "replace",
"edit_start_line_idx": 285
} | approvers:
- sebastienvas
- yutongz
| tests/OWNERS | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.00017166268662549555,
0.00017166268662549555,
0.00017166268662549555,
0.00017166268662549555,
0
] |
{
"id": 2,
"code_window": [
"\tif gracePeriod < sc.minGracePeriod {\n",
"\t\tlog.Warnf(\"gracePeriod (%v * %f) = %v is less than minGracePeriod %v. Apply minGracePeriod.\",\n",
"\t\t\tcertLifeTime, sc.gracePeriodRatio, sc.minGracePeriod)\n",
"\t\tgracePeriod = sc.minGracePeriod\n",
"\t}\n",
"\trootCertificate := sc.ca.GetRootCertificate()\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tcertLifeTime, sc.gracePeriodRatio, gracePeriod, sc.minGracePeriod)\n"
],
"file_path": "security/pkg/pki/ca/controller/secret.go",
"type": "replace",
"edit_start_line_idx": 285
} | // 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.
package routing
import (
"time"
"github.com/prometheus/client_golang/prometheus"
)
const (
meshFunction = "meshFunction"
handlerName = "handler"
adapterName = "adapter"
errorStr = "error"
)
var (
durationBuckets = []float64{.0001, .00025, .0005, .001, .0025, .005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10}
dispatchLabelNames = []string{meshFunction, handlerName, adapterName, errorStr}
dispatchCount = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: "mixer",
Subsystem: "runtime",
Name: "dispatch_count",
Help: "Total number of adapter dispatches handled by Mixer.",
}, dispatchLabelNames)
dispatchDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: "mixer",
Subsystem: "runtime",
Name: "dispatch_duration",
Help: "Histogram of durations for adapter dispatches handled by Mixer.",
Buckets: durationBuckets,
}, dispatchLabelNames)
)
func init() {
prometheus.MustRegister(dispatchCount)
prometheus.MustRegister(dispatchDuration)
}
// DestinationCounters are used to track the total/failed dispatch counts and dispatch duration for a target destination,
// based on the template/handler/adapter label set.
type DestinationCounters struct {
totalCount prometheus.Counter
failedTotalCount prometheus.Counter
duration prometheus.Observer
failedDuration prometheus.Observer
}
// newDestinationCounters returns a new set of DestinationCounters instance.
func newDestinationCounters(template string, handler string, adapter string) DestinationCounters {
successLabels := prometheus.Labels{
meshFunction: template,
handlerName: handler,
adapterName: adapter,
errorStr: "false",
}
failedLabels := prometheus.Labels{
meshFunction: template,
handlerName: handler,
adapterName: adapter,
errorStr: "true",
}
return DestinationCounters{
totalCount: dispatchCount.With(successLabels),
duration: dispatchDuration.With(successLabels),
failedTotalCount: dispatchCount.With(failedLabels),
failedDuration: dispatchDuration.With(failedLabels),
}
}
// Update the counters. Duration is the total dispatch duration. Failed indicates whether the dispatch returned an error or not.
func (d DestinationCounters) Update(duration time.Duration, failed bool) {
if failed {
d.failedTotalCount.Inc()
d.failedDuration.Observe(duration.Seconds())
} else {
d.totalCount.Inc()
d.duration.Observe(duration.Seconds())
}
}
| mixer/pkg/runtime2/routing/monitoring.go | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.00017845071852207184,
0.00017177316476590931,
0.00016447783855255693,
0.00017175637185573578,
0.0000036069288853468606
] |
{
"id": 2,
"code_window": [
"\tif gracePeriod < sc.minGracePeriod {\n",
"\t\tlog.Warnf(\"gracePeriod (%v * %f) = %v is less than minGracePeriod %v. Apply minGracePeriod.\",\n",
"\t\t\tcertLifeTime, sc.gracePeriodRatio, sc.minGracePeriod)\n",
"\t\tgracePeriod = sc.minGracePeriod\n",
"\t}\n",
"\trootCertificate := sc.ca.GetRootCertificate()\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tcertLifeTime, sc.gracePeriodRatio, gracePeriod, sc.minGracePeriod)\n"
],
"file_path": "security/pkg/pki/ca/controller/secret.go",
"type": "replace",
"edit_start_line_idx": 285
} | apiVersion: config.istio.io/v1alpha2
kind: EgressRule
metadata:
name: google
spec:
destination:
service: "*google.com"
ports:
- port: 443
protocol: https
use_egress_proxy: false
| tests/e2e/tests/pilot/testdata/v1alpha1/egress-rule-google.yaml.tmpl | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.00017319864127784967,
0.00017188407946377993,
0.00017056951764971018,
0.00017188407946377993,
0.000001314561814069748
] |
{
"id": 3,
"code_window": [
"\t}{\n",
"\t\t\"Does not update non-expiring secret\": {\n",
"\t\t\texpectedActions: []ktesting.Action{},\n",
"\t\t\tttl: time.Hour,\n",
"\t\t\tgracePeriodRatio: defaultGracePeriodRatio,\n",
"\t\t\tminGracePeriod: defaultMinGracePeriod,\n",
"\t\t},\n",
"\t\t\"Update secret in grace period\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tgracePeriodRatio: 0.5,\n",
"\t\t\tminGracePeriod: 10 * time.Minute,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 194
} | // Copyright 2017 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 controller
import (
"bytes"
"fmt"
"reflect"
"time"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/cache"
"istio.io/istio/pkg/log"
"istio.io/istio/security/pkg/pki/ca"
"istio.io/istio/security/pkg/pki/util"
)
/* #nosec: disable gas linter */
const (
// The Istio secret annotation type
IstioSecretType = "istio.io/key-and-cert"
// The ID/name for the certificate chain file.
CertChainID = "cert-chain.pem"
// The ID/name for the private key file.
PrivateKeyID = "key.pem"
// The ID/name for the CA root certificate file.
RootCertID = "root-cert.pem"
secretNamePrefix = "istio."
secretResyncPeriod = time.Minute
serviceAccountNameAnnotationKey = "istio.io/service-account.name"
recommendedMinGracePeriodRatio = 0.3
recommendedMaxGracePeriodRatio = 0.8
// The size of a private key for a leaf certificate.
keySize = 2048
)
// SecretController manages the service accounts' secrets that contains Istio keys and certificates.
type SecretController struct {
ca ca.CertificateAuthority
certTTL time.Duration
core corev1.CoreV1Interface
// Length of the grace period for the certificate rotation.
gracePeriodRatio float32
minGracePeriod time.Duration
// Controller and store for service account objects.
saController cache.Controller
saStore cache.Store
// Controller and store for secret objects.
scrtController cache.Controller
scrtStore cache.Store
}
// NewSecretController returns a pointer to a newly constructed SecretController instance.
func NewSecretController(ca ca.CertificateAuthority, certTTL time.Duration, gracePeriodRatio float32, minGracePeriod time.Duration,
core corev1.CoreV1Interface, namespace string) (*SecretController, error) {
if gracePeriodRatio < 0 || gracePeriodRatio > 1 {
return nil, fmt.Errorf("grace period ratio %f should be within [0, 1]", gracePeriodRatio)
}
if gracePeriodRatio < recommendedMinGracePeriodRatio || gracePeriodRatio > recommendedMaxGracePeriodRatio {
log.Warnf("grace period ratio %f is out of the recommended window [%.2f, %.2f]",
gracePeriodRatio, recommendedMinGracePeriodRatio, recommendedMaxGracePeriodRatio)
}
c := &SecretController{
ca: ca,
certTTL: certTTL,
gracePeriodRatio: gracePeriodRatio,
minGracePeriod: minGracePeriod,
core: core,
}
saLW := &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
return core.ServiceAccounts(namespace).List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
return core.ServiceAccounts(namespace).Watch(options)
},
}
rehf := cache.ResourceEventHandlerFuncs{
AddFunc: c.saAdded,
DeleteFunc: c.saDeleted,
UpdateFunc: c.saUpdated,
}
c.saStore, c.saController = cache.NewInformer(saLW, &v1.ServiceAccount{}, time.Minute, rehf)
istioSecretSelector := fields.SelectorFromSet(map[string]string{"type": IstioSecretType}).String()
scrtLW := &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
options.FieldSelector = istioSecretSelector
return core.Secrets(namespace).List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.FieldSelector = istioSecretSelector
return core.Secrets(namespace).Watch(options)
},
}
c.scrtStore, c.scrtController =
cache.NewInformer(scrtLW, &v1.Secret{}, secretResyncPeriod, cache.ResourceEventHandlerFuncs{
DeleteFunc: c.scrtDeleted,
UpdateFunc: c.scrtUpdated,
})
return c, nil
}
// Run starts the SecretController until a value is sent to stopCh.
func (sc *SecretController) Run(stopCh chan struct{}) {
go sc.scrtController.Run(stopCh)
go sc.saController.Run(stopCh)
}
// Handles the event where a service account is added.
func (sc *SecretController) saAdded(obj interface{}) {
acct := obj.(*v1.ServiceAccount)
sc.upsertSecret(acct.GetName(), acct.GetNamespace())
}
// Handles the event where a service account is deleted.
func (sc *SecretController) saDeleted(obj interface{}) {
acct := obj.(*v1.ServiceAccount)
sc.deleteSecret(acct.GetName(), acct.GetNamespace())
}
// Handles the event where a service account is updated.
func (sc *SecretController) saUpdated(oldObj, curObj interface{}) {
if reflect.DeepEqual(oldObj, curObj) {
// Nothing is changed. The method is invoked by periodical re-sync with the apiserver.
return
}
oldSa := oldObj.(*v1.ServiceAccount)
curSa := curObj.(*v1.ServiceAccount)
curName := curSa.GetName()
curNamespace := curSa.GetNamespace()
oldName := oldSa.GetName()
oldNamespace := oldSa.GetNamespace()
// We only care the name and namespace of a service account.
if curName != oldName || curNamespace != oldNamespace {
sc.deleteSecret(oldName, oldNamespace)
sc.upsertSecret(curName, curNamespace)
log.Infof("Service account \"%s\" in namespace \"%s\" has been updated to \"%s\" in namespace \"%s\"",
oldName, oldNamespace, curName, curNamespace)
}
}
func (sc *SecretController) upsertSecret(saName, saNamespace string) {
secret := &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{serviceAccountNameAnnotationKey: saName},
Name: getSecretName(saName),
Namespace: saNamespace,
},
Type: IstioSecretType,
}
_, exists, err := sc.scrtStore.Get(secret)
if err != nil {
log.Errorf("Failed to get secret from the store (error %v)", err)
}
if exists {
// Do nothing for existing secrets. Rotating expiring certs are handled by the `scrtUpdated` method.
return
}
// Now we know the secret does not exist yet. So we create a new one.
chain, key, err := sc.generateKeyAndCert(saName, saNamespace)
if err != nil {
log.Errorf("Failed to generate key and certificate for service account %q in namespace %q (error %v)",
saName, saNamespace, err)
return
}
rootCert := sc.ca.GetRootCertificate()
secret.Data = map[string][]byte{
CertChainID: chain,
PrivateKeyID: key,
RootCertID: rootCert,
}
_, err = sc.core.Secrets(saNamespace).Create(secret)
if err != nil {
log.Errorf("Failed to create secret (error: %s)", err)
return
}
log.Infof("Istio secret for service account \"%s\" in namespace \"%s\" has been created", saName, saNamespace)
}
func (sc *SecretController) deleteSecret(saName, saNamespace string) {
err := sc.core.Secrets(saNamespace).Delete(getSecretName(saName), nil)
// kube-apiserver returns NotFound error when the secret is successfully deleted.
if err == nil || errors.IsNotFound(err) {
log.Infof("Istio secret for service account \"%s\" in namespace \"%s\" has been deleted", saName, saNamespace)
return
}
log.Errorf("Failed to delete Istio secret for service account \"%s\" in namespace \"%s\" (error: %s)",
saName, saNamespace, err)
}
func (sc *SecretController) scrtDeleted(obj interface{}) {
scrt, ok := obj.(*v1.Secret)
if !ok {
log.Warnf("Failed to convert to secret object: %v", obj)
return
}
log.Infof("Re-create deleted Istio secret")
saName := scrt.Annotations[serviceAccountNameAnnotationKey]
sc.upsertSecret(saName, scrt.GetNamespace())
}
func (sc *SecretController) generateKeyAndCert(saName string, saNamespace string) ([]byte, []byte, error) {
id := fmt.Sprintf("%s://cluster.local/ns/%s/sa/%s", util.URIScheme, saNamespace, saName)
options := util.CertOptions{
Host: id,
RSAKeySize: keySize,
}
csrPEM, keyPEM, err := util.GenCSR(options)
if err != nil {
return nil, nil, err
}
certPEM, err := sc.ca.Sign(csrPEM, sc.certTTL, false)
if err != nil {
return nil, nil, err
}
return certPEM, keyPEM, nil
}
func (sc *SecretController) scrtUpdated(oldObj, newObj interface{}) {
scrt, ok := newObj.(*v1.Secret)
if !ok {
log.Warnf("Failed to convert to secret object: %v", newObj)
return
}
certBytes := scrt.Data[CertChainID]
cert, err := util.ParsePemEncodedCertificate(certBytes)
if err != nil {
// TODO: we should refresh secret in this case since the secret contains an
// invalid cert.
log.Errora(err)
return
}
certLifeTimeLeft := time.Until(cert.NotAfter)
certLifeTime := cert.NotAfter.Sub(cert.NotBefore)
// TODO(myidpt): we may introduce a minimum gracePeriod, without making the config too complex.
gracePeriod := time.Duration(sc.gracePeriodRatio) * certLifeTime
if gracePeriod < sc.minGracePeriod {
log.Warnf("gracePeriod (%v * %f) = %v is less than minGracePeriod %v. Apply minGracePeriod.",
certLifeTime, sc.gracePeriodRatio, sc.minGracePeriod)
gracePeriod = sc.minGracePeriod
}
rootCertificate := sc.ca.GetRootCertificate()
// Refresh the secret if 1) the certificate contained in the secret is about
// to expire, or 2) the root certificate in the secret is different than the
// one held by the ca (this may happen when the CA is restarted and
// a new self-signed CA cert is generated).
if certLifeTimeLeft < gracePeriod || !bytes.Equal(rootCertificate, scrt.Data[RootCertID]) {
namespace := scrt.GetNamespace()
name := scrt.GetName()
log.Infof("Refreshing secret %s/%s, either the leaf certificate is about to expire "+
"or the root certificate is outdated", namespace, name)
saName := scrt.Annotations[serviceAccountNameAnnotationKey]
chain, key, err := sc.generateKeyAndCert(saName, namespace)
if err != nil {
log.Errorf("Failed to generate key and certificate for service account %q in namespace %q (error %v)",
saName, namespace, err)
return
}
scrt.Data[CertChainID] = chain
scrt.Data[PrivateKeyID] = key
scrt.Data[RootCertID] = rootCertificate
if _, err = sc.core.Secrets(namespace).Update(scrt); err != nil {
log.Errorf("Failed to update secret %s/%s (error: %s)", namespace, name, err)
}
}
}
func getSecretName(saName string) string {
return secretNamePrefix + saName
}
| security/pkg/pki/ca/controller/secret.go | 1 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.01304661389440298,
0.001521614147350192,
0.00016221308032982051,
0.0001736720878398046,
0.0032430810388177633
] |
{
"id": 3,
"code_window": [
"\t}{\n",
"\t\t\"Does not update non-expiring secret\": {\n",
"\t\t\texpectedActions: []ktesting.Action{},\n",
"\t\t\tttl: time.Hour,\n",
"\t\t\tgracePeriodRatio: defaultGracePeriodRatio,\n",
"\t\t\tminGracePeriod: defaultMinGracePeriod,\n",
"\t\t},\n",
"\t\t\"Update secret in grace period\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tgracePeriodRatio: 0.5,\n",
"\t\t\tminGracePeriod: 10 * time.Minute,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 194
} | package runtime
// Copyright 2016 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.
import (
"github.com/prometheus/client_golang/prometheus"
)
const (
meshFunction = "meshFunction"
handlerName = "handler"
adapterName = "adapter"
responseCode = "response_code"
responseMsg = "response_message"
errorStr = "error"
targetStr = "target"
)
var (
promLabelNames = []string{meshFunction, handlerName, adapterName, responseCode, errorStr}
buckets = []float64{.0001, .00025, .0005, .001, .0025, .005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10}
dispatchCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: "mixer",
Subsystem: "adapter",
Name: "dispatch_count",
Help: "Total number of adapter dispatches handled by Mixer.",
}, promLabelNames)
dispatchDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: "mixer",
Subsystem: "adapter",
Name: "dispatch_duration",
Help: "Histogram of times for adapter dispatches handled by Mixer.",
Buckets: buckets,
}, promLabelNames)
resolveLabelNames = []string{targetStr, errorStr}
resolveCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: "mixer",
Subsystem: "config",
Name: "resolve_count",
Help: "Total number of config resolves handled by Mixer.",
}, resolveLabelNames)
resolveDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: "mixer",
Subsystem: "config",
Name: "resolve_duration",
Help: "Histogram of times for config resolves handled by Mixer.",
Buckets: buckets,
}, resolveLabelNames)
countBuckets = []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 15, 20}
resolveRules = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: "mixer",
Subsystem: "config",
Name: "resolve_rules",
Help: "Histogram of rules resolved by Mixer.",
Buckets: countBuckets,
}, resolveLabelNames)
resolveActions = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: "mixer",
Subsystem: "config",
Name: "resolve_actions",
Help: "Histogram of actions resolved by Mixer.",
Buckets: countBuckets,
}, resolveLabelNames)
)
func init() {
prometheus.MustRegister(dispatchCounter)
prometheus.MustRegister(dispatchDuration)
prometheus.MustRegister(resolveCounter)
prometheus.MustRegister(resolveDuration)
prometheus.MustRegister(resolveRules)
prometheus.MustRegister(resolveActions)
}
| mixer/pkg/runtime/monitor.go | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.00017753391875885427,
0.00017355548334307969,
0.00016783204046078026,
0.0001737371931085363,
0.0000029106338388373842
] |
{
"id": 3,
"code_window": [
"\t}{\n",
"\t\t\"Does not update non-expiring secret\": {\n",
"\t\t\texpectedActions: []ktesting.Action{},\n",
"\t\t\tttl: time.Hour,\n",
"\t\t\tgracePeriodRatio: defaultGracePeriodRatio,\n",
"\t\t\tminGracePeriod: defaultMinGracePeriod,\n",
"\t\t},\n",
"\t\t\"Update secret in grace period\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tgracePeriodRatio: 0.5,\n",
"\t\t\tminGracePeriod: 10 * time.Minute,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 194
} | // 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.
package util
import (
"os"
"istio.io/istio/pilot/pkg/serviceregistry"
)
const (
defaultHub = "gcr.io/istio-testing"
defaultRegistry = string(serviceregistry.KubernetesRegistry)
defaultAdmissionServiceName = "istio-pilot"
defaultVerbosity = 2
)
// Config defines the configuration for the test environment.
type Config struct {
KubeConfig string
Hub string
Tag string
Namespace string
IstioNamespace string
Registry string
ErrorLogsDir string
CoreFilesDir string
SelectedTest string
SidecarTemplate string
AdmissionServiceName string
Verbosity int
DebugPort int
TestCount int
Auth bool
Mixer bool
Ingress bool
Zipkin bool
SkipCleanup bool
SkipCleanupOnFailure bool
CheckLogs bool
DebugImagesAndMode bool
UseAutomaticInjection bool
V1alpha1 bool
V1alpha2 bool
UseAdmissionWebhook bool
APIVersions []string
}
// NewConfig creates a new test environment configuration with default values.
func NewConfig() *Config {
return &Config{
KubeConfig: os.Getenv("KUBECONFIG"),
Hub: defaultHub,
Tag: "",
Namespace: "",
IstioNamespace: "",
Registry: defaultRegistry,
Verbosity: defaultVerbosity,
Auth: false,
Mixer: true,
Ingress: true,
Zipkin: true,
DebugPort: 0,
SkipCleanup: false,
SkipCleanupOnFailure: false,
CheckLogs: false,
ErrorLogsDir: "",
CoreFilesDir: "",
TestCount: 1,
SelectedTest: "",
DebugImagesAndMode: true,
UseAutomaticInjection: false,
UseAdmissionWebhook: false,
AdmissionServiceName: defaultAdmissionServiceName,
V1alpha1: false,
V1alpha2: true,
}
}
| tests/e2e/tests/pilot/util/config.go | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.00017843148089013994,
0.0001699026470305398,
0.00016250675253104419,
0.00016912518185563385,
0.000005089481874165358
] |
{
"id": 3,
"code_window": [
"\t}{\n",
"\t\t\"Does not update non-expiring secret\": {\n",
"\t\t\texpectedActions: []ktesting.Action{},\n",
"\t\t\tttl: time.Hour,\n",
"\t\t\tgracePeriodRatio: defaultGracePeriodRatio,\n",
"\t\t\tminGracePeriod: defaultMinGracePeriod,\n",
"\t\t},\n",
"\t\t\"Update secret in grace period\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tgracePeriodRatio: 0.5,\n",
"\t\t\tminGracePeriod: 10 * time.Minute,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 194
} | <!--
Copyright (c) 2016 IBM Corp.
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.
-->
<html>
<body>
<h1>Welcome to your Liberty Application</h1>
<p>Thanks for generating this project using the app accelerator. Please see below for some extra information on each of the technologies you chose</p>
<!--
Copyright (c) 2016 IBM Corp.
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.
-->
<div>
<h2>REST</h2>
<p>
Inside the application project there is a application.rest package
containing the
<code>LibertyRestEndpoint</code>
class. This adds a REST endpoint which you can access at <a
href="rest">/rest</a>
<p>
Inside the wlpcfg project there is the
<code>it.rest.LibertyRestEndpointTest</code>
that will test the REST endpoint to ensure it is working.
</p>
<p>
For the complete feature documentation, see the <a
href="http://www.ibm.com/support/knowledgecenter/SSAW57_8.5.5/com.ibm.websphere.wlp.nd.multiplatform.doc/ae/rwlp_feat.html%23rwlp_feat__jaxrs-2.0">jaxrs-2.0</a>
feature description in IBM Knowledge Center.
</p>
</div>
<div id="technologies">
</div>
</body>
</html>
| samples/bookinfo/src/reviews/reviews-application/src/main/webapp/index.html | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.889832079410553,
0.14845162630081177,
0.00016936536121647805,
0.00017797424516174942,
0.33155539631843567
] |
{
"id": 4,
"code_window": [
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n",
"\t\t\tttl: defaultTTL,\n",
"\t\t\tgracePeriodRatio: 1, // Always in grace period\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t\tttl: time.Hour,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 201
} | // Copyright 2017 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 controller
import (
"bytes"
"fmt"
"reflect"
"time"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/cache"
"istio.io/istio/pkg/log"
"istio.io/istio/security/pkg/pki/ca"
"istio.io/istio/security/pkg/pki/util"
)
/* #nosec: disable gas linter */
const (
// The Istio secret annotation type
IstioSecretType = "istio.io/key-and-cert"
// The ID/name for the certificate chain file.
CertChainID = "cert-chain.pem"
// The ID/name for the private key file.
PrivateKeyID = "key.pem"
// The ID/name for the CA root certificate file.
RootCertID = "root-cert.pem"
secretNamePrefix = "istio."
secretResyncPeriod = time.Minute
serviceAccountNameAnnotationKey = "istio.io/service-account.name"
recommendedMinGracePeriodRatio = 0.3
recommendedMaxGracePeriodRatio = 0.8
// The size of a private key for a leaf certificate.
keySize = 2048
)
// SecretController manages the service accounts' secrets that contains Istio keys and certificates.
type SecretController struct {
ca ca.CertificateAuthority
certTTL time.Duration
core corev1.CoreV1Interface
// Length of the grace period for the certificate rotation.
gracePeriodRatio float32
minGracePeriod time.Duration
// Controller and store for service account objects.
saController cache.Controller
saStore cache.Store
// Controller and store for secret objects.
scrtController cache.Controller
scrtStore cache.Store
}
// NewSecretController returns a pointer to a newly constructed SecretController instance.
func NewSecretController(ca ca.CertificateAuthority, certTTL time.Duration, gracePeriodRatio float32, minGracePeriod time.Duration,
core corev1.CoreV1Interface, namespace string) (*SecretController, error) {
if gracePeriodRatio < 0 || gracePeriodRatio > 1 {
return nil, fmt.Errorf("grace period ratio %f should be within [0, 1]", gracePeriodRatio)
}
if gracePeriodRatio < recommendedMinGracePeriodRatio || gracePeriodRatio > recommendedMaxGracePeriodRatio {
log.Warnf("grace period ratio %f is out of the recommended window [%.2f, %.2f]",
gracePeriodRatio, recommendedMinGracePeriodRatio, recommendedMaxGracePeriodRatio)
}
c := &SecretController{
ca: ca,
certTTL: certTTL,
gracePeriodRatio: gracePeriodRatio,
minGracePeriod: minGracePeriod,
core: core,
}
saLW := &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
return core.ServiceAccounts(namespace).List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
return core.ServiceAccounts(namespace).Watch(options)
},
}
rehf := cache.ResourceEventHandlerFuncs{
AddFunc: c.saAdded,
DeleteFunc: c.saDeleted,
UpdateFunc: c.saUpdated,
}
c.saStore, c.saController = cache.NewInformer(saLW, &v1.ServiceAccount{}, time.Minute, rehf)
istioSecretSelector := fields.SelectorFromSet(map[string]string{"type": IstioSecretType}).String()
scrtLW := &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
options.FieldSelector = istioSecretSelector
return core.Secrets(namespace).List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.FieldSelector = istioSecretSelector
return core.Secrets(namespace).Watch(options)
},
}
c.scrtStore, c.scrtController =
cache.NewInformer(scrtLW, &v1.Secret{}, secretResyncPeriod, cache.ResourceEventHandlerFuncs{
DeleteFunc: c.scrtDeleted,
UpdateFunc: c.scrtUpdated,
})
return c, nil
}
// Run starts the SecretController until a value is sent to stopCh.
func (sc *SecretController) Run(stopCh chan struct{}) {
go sc.scrtController.Run(stopCh)
go sc.saController.Run(stopCh)
}
// Handles the event where a service account is added.
func (sc *SecretController) saAdded(obj interface{}) {
acct := obj.(*v1.ServiceAccount)
sc.upsertSecret(acct.GetName(), acct.GetNamespace())
}
// Handles the event where a service account is deleted.
func (sc *SecretController) saDeleted(obj interface{}) {
acct := obj.(*v1.ServiceAccount)
sc.deleteSecret(acct.GetName(), acct.GetNamespace())
}
// Handles the event where a service account is updated.
func (sc *SecretController) saUpdated(oldObj, curObj interface{}) {
if reflect.DeepEqual(oldObj, curObj) {
// Nothing is changed. The method is invoked by periodical re-sync with the apiserver.
return
}
oldSa := oldObj.(*v1.ServiceAccount)
curSa := curObj.(*v1.ServiceAccount)
curName := curSa.GetName()
curNamespace := curSa.GetNamespace()
oldName := oldSa.GetName()
oldNamespace := oldSa.GetNamespace()
// We only care the name and namespace of a service account.
if curName != oldName || curNamespace != oldNamespace {
sc.deleteSecret(oldName, oldNamespace)
sc.upsertSecret(curName, curNamespace)
log.Infof("Service account \"%s\" in namespace \"%s\" has been updated to \"%s\" in namespace \"%s\"",
oldName, oldNamespace, curName, curNamespace)
}
}
func (sc *SecretController) upsertSecret(saName, saNamespace string) {
secret := &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{serviceAccountNameAnnotationKey: saName},
Name: getSecretName(saName),
Namespace: saNamespace,
},
Type: IstioSecretType,
}
_, exists, err := sc.scrtStore.Get(secret)
if err != nil {
log.Errorf("Failed to get secret from the store (error %v)", err)
}
if exists {
// Do nothing for existing secrets. Rotating expiring certs are handled by the `scrtUpdated` method.
return
}
// Now we know the secret does not exist yet. So we create a new one.
chain, key, err := sc.generateKeyAndCert(saName, saNamespace)
if err != nil {
log.Errorf("Failed to generate key and certificate for service account %q in namespace %q (error %v)",
saName, saNamespace, err)
return
}
rootCert := sc.ca.GetRootCertificate()
secret.Data = map[string][]byte{
CertChainID: chain,
PrivateKeyID: key,
RootCertID: rootCert,
}
_, err = sc.core.Secrets(saNamespace).Create(secret)
if err != nil {
log.Errorf("Failed to create secret (error: %s)", err)
return
}
log.Infof("Istio secret for service account \"%s\" in namespace \"%s\" has been created", saName, saNamespace)
}
func (sc *SecretController) deleteSecret(saName, saNamespace string) {
err := sc.core.Secrets(saNamespace).Delete(getSecretName(saName), nil)
// kube-apiserver returns NotFound error when the secret is successfully deleted.
if err == nil || errors.IsNotFound(err) {
log.Infof("Istio secret for service account \"%s\" in namespace \"%s\" has been deleted", saName, saNamespace)
return
}
log.Errorf("Failed to delete Istio secret for service account \"%s\" in namespace \"%s\" (error: %s)",
saName, saNamespace, err)
}
func (sc *SecretController) scrtDeleted(obj interface{}) {
scrt, ok := obj.(*v1.Secret)
if !ok {
log.Warnf("Failed to convert to secret object: %v", obj)
return
}
log.Infof("Re-create deleted Istio secret")
saName := scrt.Annotations[serviceAccountNameAnnotationKey]
sc.upsertSecret(saName, scrt.GetNamespace())
}
func (sc *SecretController) generateKeyAndCert(saName string, saNamespace string) ([]byte, []byte, error) {
id := fmt.Sprintf("%s://cluster.local/ns/%s/sa/%s", util.URIScheme, saNamespace, saName)
options := util.CertOptions{
Host: id,
RSAKeySize: keySize,
}
csrPEM, keyPEM, err := util.GenCSR(options)
if err != nil {
return nil, nil, err
}
certPEM, err := sc.ca.Sign(csrPEM, sc.certTTL, false)
if err != nil {
return nil, nil, err
}
return certPEM, keyPEM, nil
}
func (sc *SecretController) scrtUpdated(oldObj, newObj interface{}) {
scrt, ok := newObj.(*v1.Secret)
if !ok {
log.Warnf("Failed to convert to secret object: %v", newObj)
return
}
certBytes := scrt.Data[CertChainID]
cert, err := util.ParsePemEncodedCertificate(certBytes)
if err != nil {
// TODO: we should refresh secret in this case since the secret contains an
// invalid cert.
log.Errora(err)
return
}
certLifeTimeLeft := time.Until(cert.NotAfter)
certLifeTime := cert.NotAfter.Sub(cert.NotBefore)
// TODO(myidpt): we may introduce a minimum gracePeriod, without making the config too complex.
gracePeriod := time.Duration(sc.gracePeriodRatio) * certLifeTime
if gracePeriod < sc.minGracePeriod {
log.Warnf("gracePeriod (%v * %f) = %v is less than minGracePeriod %v. Apply minGracePeriod.",
certLifeTime, sc.gracePeriodRatio, sc.minGracePeriod)
gracePeriod = sc.minGracePeriod
}
rootCertificate := sc.ca.GetRootCertificate()
// Refresh the secret if 1) the certificate contained in the secret is about
// to expire, or 2) the root certificate in the secret is different than the
// one held by the ca (this may happen when the CA is restarted and
// a new self-signed CA cert is generated).
if certLifeTimeLeft < gracePeriod || !bytes.Equal(rootCertificate, scrt.Data[RootCertID]) {
namespace := scrt.GetNamespace()
name := scrt.GetName()
log.Infof("Refreshing secret %s/%s, either the leaf certificate is about to expire "+
"or the root certificate is outdated", namespace, name)
saName := scrt.Annotations[serviceAccountNameAnnotationKey]
chain, key, err := sc.generateKeyAndCert(saName, namespace)
if err != nil {
log.Errorf("Failed to generate key and certificate for service account %q in namespace %q (error %v)",
saName, namespace, err)
return
}
scrt.Data[CertChainID] = chain
scrt.Data[PrivateKeyID] = key
scrt.Data[RootCertID] = rootCertificate
if _, err = sc.core.Secrets(namespace).Update(scrt); err != nil {
log.Errorf("Failed to update secret %s/%s (error: %s)", namespace, name, err)
}
}
}
func getSecretName(saName string) string {
return secretNamePrefix + saName
}
| security/pkg/pki/ca/controller/secret.go | 1 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.08442062139511108,
0.004771310370415449,
0.0001632578350836411,
0.00017317122546955943,
0.015524497255682945
] |
{
"id": 4,
"code_window": [
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n",
"\t\t\tttl: defaultTTL,\n",
"\t\t\tgracePeriodRatio: 1, // Always in grace period\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t\tttl: time.Hour,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 201
} | // Copyright 2017 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 (
"flag"
"fmt"
env "istio.io/istio/tests/integration/example/environment/appOnlyEnv"
"istio.io/istio/tests/integration/framework"
)
func main() {
flag.Parse()
testEM := framework.NewTestEnvManager(env.NewAppOnlyEnv(""), "")
if err := testEM.StartUp(); err != nil {
fmt.Printf("Failed to start the environment: %s\n", err)
} else {
fmt.Println("Environment is running")
for {
var input string
fmt.Println("Entry 'exit' to stop the environment, don't use 'ctrl+C'")
fmt.Scanln(&input)
if input == "exit" {
break
}
}
}
testEM.TearDown()
}
| tests/integration/example/environment/appOnlyEnv/cmd/main.go | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.00017548837058711797,
0.00017260006279684603,
0.00016594554472249,
0.00017480298993177712,
0.0000035706204926100327
] |
{
"id": 4,
"code_window": [
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n",
"\t\t\tttl: defaultTTL,\n",
"\t\t\tgracePeriodRatio: 1, // Always in grace period\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t\tttl: time.Hour,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 201
} | apiVersion: extensions/v1beta1
kind: Deployment
metadata:
creationTimestamp: null
name: hello
spec:
replicas: 7
strategy: {}
template:
metadata:
annotations:
sidecar.istio.io/status: '{"version":"0fd4ba601a8387ce4a6317d83dd1d8af037d3a5f59512824113a5a0fce04e9b8","initContainers":["istio-init"],"containers":["istio-proxy"],"volumes":["istio-envoy","istio-certs"]}'
creationTimestamp: null
labels:
app: hello
tier: backend
track: stable
spec:
containers:
- image: fake.docker.io/google-samples/hello-go-gke:1.0
name: hello
ports:
- containerPort: 80
name: http
resources: {}
- args:
- proxy
- sidecar
- --configPath
- /etc/istio/proxy
- --binaryPath
- /usr/local/bin/envoy
- --serviceCluster
- hello
- --drainDuration
- 42s
- --parentShutdownDuration
- 42s
- --discoveryAddress
- istio-pilot:15007
- --discoveryRefreshDelay
- 42s
- --zipkinAddress
- ""
- --connectTimeout
- 42s
- --statsdUdpAddress
- ""
- --proxyAdminPort
- "15000"
- --controlPlaneAuthPolicy
- NONE
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: INSTANCE_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
image: docker.io/istio/proxy:unittest
imagePullPolicy: IfNotPresent
name: istio-proxy
resources: {}
securityContext:
privileged: false
readOnlyRootFilesystem: true
runAsUser: 1337
volumeMounts:
- mountPath: /etc/istio/proxy
name: istio-envoy
- mountPath: /etc/certs/
name: istio-certs
readOnly: true
initContainers:
- args:
- -p
- "15001"
- -u
- "1337"
image: docker.io/istio/proxy_init:unittest
imagePullPolicy: IfNotPresent
name: istio-init
resources: {}
securityContext:
capabilities:
add:
- NET_ADMIN
volumes:
- emptyDir:
medium: Memory
name: istio-envoy
- name: istio-certs
secret:
optional: true
secretName: istio.default
status: {}
---
| pilot/pkg/kube/inject/testdata/format-duration.yaml.injected | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.00019810184312518686,
0.00017520810069981962,
0.0001656248205108568,
0.00017293263226747513,
0.000007796963473083451
] |
{
"id": 4,
"code_window": [
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n",
"\t\t\tttl: defaultTTL,\n",
"\t\t\tgracePeriodRatio: 1, // Always in grace period\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t\tttl: time.Hour,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 201
} | FROM circleci/golang:1.10
# The base circleci image runs as user 'circleci'(3434), with sudo capabilities.
# Based on Debian9. Go installed in /usr/local/go
# Env:
# GOLANG_VERSION
# GPATH=/go
# Workdir: /go
# Also installed docker, docker-compose, dockerize, jq
ARG K8S_VER=v1.9.2
ARG ETCD_VER=v3.2.15
ARG MINIKUBE_VER=v0.25.0
ARG HELM_VER=v2.7.2
# The local test cluster config
ARG MASTER_IP=127.0.0.1
ARG MASTER_CLUSTER_IP=10.99.0.1
# Environment variables used in the build.
ENV GOPATH=/go
ENV KUBECONFIG=/go/out/kube.config
ENV ETCD_DATADIR=/go/out/etcd-data
ENV PATH=/go/bin:/go/out/linux_amd64:$PATH
# Initialization
RUN sudo mkdir -p /go/src/istio.io/istio && \
sudo chown -R circleci /go && \
mkdir -p /go/out && \
mkdir /home/circleci/logs
# Get etcd, apiserver for the local environment
RUN cd /tmp && \
curl -L -o etcd.tgz https://github.com/coreos/etcd/releases/download/${ETCD_VER}/etcd-${ETCD_VER}-linux-amd64.tar.gz && \
tar xzf etcd.tgz && \
sudo mv etcd-${ETCD_VER}-linux-amd64/etcd /usr/local/bin/etcd && \
rm -rf etcd*
RUN curl -L -o /tmp/kube-apiserver https://storage.googleapis.com/kubernetes-release/release/${K8S_VER}/bin/linux/amd64/kube-apiserver && \
chmod +x /tmp/kube-apiserver && \
sudo mv /tmp/kube-apiserver /usr/local/bin
RUN go get -u github.com/golang/dep/cmd/dep
# Tool used to convert 'go test' to junit, for integration with CI dashboard
RUN go get github.com/jstemmer/go-junit-report
# Install fpm tool
RUN sudo apt-get -qqy install ruby ruby-dev rubygems build-essential autoconf libtool autotools-dev && \
sudo gem install --no-ri --no-rdoc fpm
# Include minikube and kubectl in the image
RUN curl -Lo /tmp/kubectl https://storage.googleapis.com/kubernetes-release/release/${K8S_VER}/bin/linux/amd64/kubectl && \
chmod +x /tmp/kubectl && sudo mv /tmp/kubectl /usr/local/bin/
RUN curl -Lo /tmp/minikube https://storage.googleapis.com/minikube/releases/${MINIKUBE_VER}/minikube-linux-amd64 &&\
chmod +x /tmp/minikube && sudo mv /tmp/minikube /usr/local/bin/
# Install helm
RUN cd /tmp && \
curl -Lo /tmp/helm.tgz https://storage.googleapis.com/kubernetes-helm/helm-${HELM_VER}-linux-amd64.tar.gz && \
tar xfz helm.tgz && \
sudo mv linux-amd64/helm /usr/local/bin && \
rm -rf helm.tgz linux-amd64
| .circleci/Dockerfile | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.0003135443839710206,
0.00018860690761357546,
0.00016371630772482604,
0.00016865113866515458,
0.000051063754654023796
] |
{
"id": 5,
"code_window": [
"\t\t\tgracePeriodRatio: 1, // Always in grace period\n",
"\t\t\tminGracePeriod: defaultMinGracePeriod,\n",
"\t\t},\n",
"\t\t\"Update secret in min grace period\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tminGracePeriod: 10 * time.Minute,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 203
} | // Copyright 2017 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 controller
import (
"bytes"
"fmt"
"reflect"
"time"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/cache"
"istio.io/istio/pkg/log"
"istio.io/istio/security/pkg/pki/ca"
"istio.io/istio/security/pkg/pki/util"
)
/* #nosec: disable gas linter */
const (
// The Istio secret annotation type
IstioSecretType = "istio.io/key-and-cert"
// The ID/name for the certificate chain file.
CertChainID = "cert-chain.pem"
// The ID/name for the private key file.
PrivateKeyID = "key.pem"
// The ID/name for the CA root certificate file.
RootCertID = "root-cert.pem"
secretNamePrefix = "istio."
secretResyncPeriod = time.Minute
serviceAccountNameAnnotationKey = "istio.io/service-account.name"
recommendedMinGracePeriodRatio = 0.3
recommendedMaxGracePeriodRatio = 0.8
// The size of a private key for a leaf certificate.
keySize = 2048
)
// SecretController manages the service accounts' secrets that contains Istio keys and certificates.
type SecretController struct {
ca ca.CertificateAuthority
certTTL time.Duration
core corev1.CoreV1Interface
// Length of the grace period for the certificate rotation.
gracePeriodRatio float32
minGracePeriod time.Duration
// Controller and store for service account objects.
saController cache.Controller
saStore cache.Store
// Controller and store for secret objects.
scrtController cache.Controller
scrtStore cache.Store
}
// NewSecretController returns a pointer to a newly constructed SecretController instance.
func NewSecretController(ca ca.CertificateAuthority, certTTL time.Duration, gracePeriodRatio float32, minGracePeriod time.Duration,
core corev1.CoreV1Interface, namespace string) (*SecretController, error) {
if gracePeriodRatio < 0 || gracePeriodRatio > 1 {
return nil, fmt.Errorf("grace period ratio %f should be within [0, 1]", gracePeriodRatio)
}
if gracePeriodRatio < recommendedMinGracePeriodRatio || gracePeriodRatio > recommendedMaxGracePeriodRatio {
log.Warnf("grace period ratio %f is out of the recommended window [%.2f, %.2f]",
gracePeriodRatio, recommendedMinGracePeriodRatio, recommendedMaxGracePeriodRatio)
}
c := &SecretController{
ca: ca,
certTTL: certTTL,
gracePeriodRatio: gracePeriodRatio,
minGracePeriod: minGracePeriod,
core: core,
}
saLW := &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
return core.ServiceAccounts(namespace).List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
return core.ServiceAccounts(namespace).Watch(options)
},
}
rehf := cache.ResourceEventHandlerFuncs{
AddFunc: c.saAdded,
DeleteFunc: c.saDeleted,
UpdateFunc: c.saUpdated,
}
c.saStore, c.saController = cache.NewInformer(saLW, &v1.ServiceAccount{}, time.Minute, rehf)
istioSecretSelector := fields.SelectorFromSet(map[string]string{"type": IstioSecretType}).String()
scrtLW := &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
options.FieldSelector = istioSecretSelector
return core.Secrets(namespace).List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.FieldSelector = istioSecretSelector
return core.Secrets(namespace).Watch(options)
},
}
c.scrtStore, c.scrtController =
cache.NewInformer(scrtLW, &v1.Secret{}, secretResyncPeriod, cache.ResourceEventHandlerFuncs{
DeleteFunc: c.scrtDeleted,
UpdateFunc: c.scrtUpdated,
})
return c, nil
}
// Run starts the SecretController until a value is sent to stopCh.
func (sc *SecretController) Run(stopCh chan struct{}) {
go sc.scrtController.Run(stopCh)
go sc.saController.Run(stopCh)
}
// Handles the event where a service account is added.
func (sc *SecretController) saAdded(obj interface{}) {
acct := obj.(*v1.ServiceAccount)
sc.upsertSecret(acct.GetName(), acct.GetNamespace())
}
// Handles the event where a service account is deleted.
func (sc *SecretController) saDeleted(obj interface{}) {
acct := obj.(*v1.ServiceAccount)
sc.deleteSecret(acct.GetName(), acct.GetNamespace())
}
// Handles the event where a service account is updated.
func (sc *SecretController) saUpdated(oldObj, curObj interface{}) {
if reflect.DeepEqual(oldObj, curObj) {
// Nothing is changed. The method is invoked by periodical re-sync with the apiserver.
return
}
oldSa := oldObj.(*v1.ServiceAccount)
curSa := curObj.(*v1.ServiceAccount)
curName := curSa.GetName()
curNamespace := curSa.GetNamespace()
oldName := oldSa.GetName()
oldNamespace := oldSa.GetNamespace()
// We only care the name and namespace of a service account.
if curName != oldName || curNamespace != oldNamespace {
sc.deleteSecret(oldName, oldNamespace)
sc.upsertSecret(curName, curNamespace)
log.Infof("Service account \"%s\" in namespace \"%s\" has been updated to \"%s\" in namespace \"%s\"",
oldName, oldNamespace, curName, curNamespace)
}
}
func (sc *SecretController) upsertSecret(saName, saNamespace string) {
secret := &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{serviceAccountNameAnnotationKey: saName},
Name: getSecretName(saName),
Namespace: saNamespace,
},
Type: IstioSecretType,
}
_, exists, err := sc.scrtStore.Get(secret)
if err != nil {
log.Errorf("Failed to get secret from the store (error %v)", err)
}
if exists {
// Do nothing for existing secrets. Rotating expiring certs are handled by the `scrtUpdated` method.
return
}
// Now we know the secret does not exist yet. So we create a new one.
chain, key, err := sc.generateKeyAndCert(saName, saNamespace)
if err != nil {
log.Errorf("Failed to generate key and certificate for service account %q in namespace %q (error %v)",
saName, saNamespace, err)
return
}
rootCert := sc.ca.GetRootCertificate()
secret.Data = map[string][]byte{
CertChainID: chain,
PrivateKeyID: key,
RootCertID: rootCert,
}
_, err = sc.core.Secrets(saNamespace).Create(secret)
if err != nil {
log.Errorf("Failed to create secret (error: %s)", err)
return
}
log.Infof("Istio secret for service account \"%s\" in namespace \"%s\" has been created", saName, saNamespace)
}
func (sc *SecretController) deleteSecret(saName, saNamespace string) {
err := sc.core.Secrets(saNamespace).Delete(getSecretName(saName), nil)
// kube-apiserver returns NotFound error when the secret is successfully deleted.
if err == nil || errors.IsNotFound(err) {
log.Infof("Istio secret for service account \"%s\" in namespace \"%s\" has been deleted", saName, saNamespace)
return
}
log.Errorf("Failed to delete Istio secret for service account \"%s\" in namespace \"%s\" (error: %s)",
saName, saNamespace, err)
}
func (sc *SecretController) scrtDeleted(obj interface{}) {
scrt, ok := obj.(*v1.Secret)
if !ok {
log.Warnf("Failed to convert to secret object: %v", obj)
return
}
log.Infof("Re-create deleted Istio secret")
saName := scrt.Annotations[serviceAccountNameAnnotationKey]
sc.upsertSecret(saName, scrt.GetNamespace())
}
func (sc *SecretController) generateKeyAndCert(saName string, saNamespace string) ([]byte, []byte, error) {
id := fmt.Sprintf("%s://cluster.local/ns/%s/sa/%s", util.URIScheme, saNamespace, saName)
options := util.CertOptions{
Host: id,
RSAKeySize: keySize,
}
csrPEM, keyPEM, err := util.GenCSR(options)
if err != nil {
return nil, nil, err
}
certPEM, err := sc.ca.Sign(csrPEM, sc.certTTL, false)
if err != nil {
return nil, nil, err
}
return certPEM, keyPEM, nil
}
func (sc *SecretController) scrtUpdated(oldObj, newObj interface{}) {
scrt, ok := newObj.(*v1.Secret)
if !ok {
log.Warnf("Failed to convert to secret object: %v", newObj)
return
}
certBytes := scrt.Data[CertChainID]
cert, err := util.ParsePemEncodedCertificate(certBytes)
if err != nil {
// TODO: we should refresh secret in this case since the secret contains an
// invalid cert.
log.Errora(err)
return
}
certLifeTimeLeft := time.Until(cert.NotAfter)
certLifeTime := cert.NotAfter.Sub(cert.NotBefore)
// TODO(myidpt): we may introduce a minimum gracePeriod, without making the config too complex.
gracePeriod := time.Duration(sc.gracePeriodRatio) * certLifeTime
if gracePeriod < sc.minGracePeriod {
log.Warnf("gracePeriod (%v * %f) = %v is less than minGracePeriod %v. Apply minGracePeriod.",
certLifeTime, sc.gracePeriodRatio, sc.minGracePeriod)
gracePeriod = sc.minGracePeriod
}
rootCertificate := sc.ca.GetRootCertificate()
// Refresh the secret if 1) the certificate contained in the secret is about
// to expire, or 2) the root certificate in the secret is different than the
// one held by the ca (this may happen when the CA is restarted and
// a new self-signed CA cert is generated).
if certLifeTimeLeft < gracePeriod || !bytes.Equal(rootCertificate, scrt.Data[RootCertID]) {
namespace := scrt.GetNamespace()
name := scrt.GetName()
log.Infof("Refreshing secret %s/%s, either the leaf certificate is about to expire "+
"or the root certificate is outdated", namespace, name)
saName := scrt.Annotations[serviceAccountNameAnnotationKey]
chain, key, err := sc.generateKeyAndCert(saName, namespace)
if err != nil {
log.Errorf("Failed to generate key and certificate for service account %q in namespace %q (error %v)",
saName, namespace, err)
return
}
scrt.Data[CertChainID] = chain
scrt.Data[PrivateKeyID] = key
scrt.Data[RootCertID] = rootCertificate
if _, err = sc.core.Secrets(namespace).Update(scrt); err != nil {
log.Errorf("Failed to update secret %s/%s (error: %s)", namespace, name, err)
}
}
}
func getSecretName(saName string) string {
return secretNamePrefix + saName
}
| security/pkg/pki/ca/controller/secret.go | 1 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.028689686208963394,
0.002777582500129938,
0.00016116209735628217,
0.00023710861569270492,
0.006002419628202915
] |
{
"id": 5,
"code_window": [
"\t\t\tgracePeriodRatio: 1, // Always in grace period\n",
"\t\t\tminGracePeriod: defaultMinGracePeriod,\n",
"\t\t},\n",
"\t\t\"Update secret in min grace period\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tminGracePeriod: 10 * time.Minute,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 203
} | // Copyright 2017 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 memory
import (
"errors"
"istio.io/istio/pilot/pkg/model"
)
type controller struct {
monitor Monitor
configStore model.ConfigStore
}
// NewController return an implementation of model.ConfigStoreCache
// This is a client-side monitor that dispatches events as the changes are being
// made on the client.
func NewController(cs model.ConfigStore) model.ConfigStoreCache {
out := &controller{
configStore: cs,
monitor: NewMonitor(cs),
}
return out
}
// NewBufferedController return an implementation of model.ConfigStoreCache. This differs from NewController in that it
// allows for specifying the size of the internal event buffer.
func NewBufferedController(cs model.ConfigStore, bufferSize int) model.ConfigStoreCache {
out := &controller{
configStore: cs,
monitor: NewBufferedMonitor(cs, bufferSize),
}
return out
}
func (c *controller) RegisterEventHandler(typ string, f func(model.Config, model.Event)) {
c.monitor.AppendEventHandler(typ, f)
}
// Memory implementation is always synchronized with cache
func (c *controller) HasSynced() bool {
return true
}
func (c *controller) Run(stop <-chan struct{}) {
c.monitor.Run(stop)
}
func (c *controller) ConfigDescriptor() model.ConfigDescriptor {
return c.configStore.ConfigDescriptor()
}
func (c *controller) Get(typ, key, namespace string) (*model.Config, bool) {
return c.configStore.Get(typ, key, namespace)
}
func (c *controller) Create(config model.Config) (revision string, err error) {
if revision, err = c.configStore.Create(config); err == nil {
c.monitor.ScheduleProcessEvent(ConfigEvent{
config: config,
event: model.EventAdd,
})
}
return
}
func (c *controller) Update(config model.Config) (newRevision string, err error) {
if newRevision, err = c.configStore.Update(config); err == nil {
c.monitor.ScheduleProcessEvent(ConfigEvent{
config: config,
event: model.EventUpdate,
})
}
return
}
func (c *controller) Delete(typ, key, namespace string) (err error) {
if config, exists := c.Get(typ, key, namespace); exists {
if err = c.configStore.Delete(typ, key, namespace); err == nil {
c.monitor.ScheduleProcessEvent(ConfigEvent{
config: *config,
event: model.EventDelete,
})
return
}
}
return errors.New("Delete failure: config" + key + "does not exist")
}
func (c *controller) List(typ, namespace string) ([]model.Config, error) {
return c.configStore.List(typ, namespace)
}
| pilot/pkg/config/memory/controller.go | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.00017770699923858047,
0.00017137259419541806,
0.00016359458095394075,
0.00017216904961969703,
0.000004269005330570508
] |
{
"id": 5,
"code_window": [
"\t\t\tgracePeriodRatio: 1, // Always in grace period\n",
"\t\t\tminGracePeriod: defaultMinGracePeriod,\n",
"\t\t},\n",
"\t\t\"Update secret in min grace period\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tminGracePeriod: 10 * time.Minute,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 203
} | // Copyright 2017 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 (
"bytes"
"fmt"
"regexp"
"strings"
"testing"
"istio.io/istio/mixer/adapter"
adptr "istio.io/istio/mixer/pkg/adapter"
"istio.io/istio/mixer/pkg/template"
generatedTemplate "istio.io/istio/mixer/template"
)
var empty = ``
var exampleAdapters = []adptr.InfoFn{
func() adptr.Info { return adptr.Info{Name: "foo-bar"} },
func() adptr.Info { return adptr.Info{Name: "abcd"} },
}
var exampleAdaptersCrd = `
kind: CustomResourceDefinition
apiVersion: apiextensions.k8s.io/v1beta1
metadata:
name: foo-bars.config.istio.io
labels:
package: foo-bar
istio: mixer-adapter
spec:
group: config.istio.io
names:
kind: foo-bar
plural: foo-bars
singular: foo-bar
scope: Namespaced
version: v1alpha2
---
kind: CustomResourceDefinition
apiVersion: apiextensions.k8s.io/v1beta1
metadata:
name: abcds.config.istio.io
labels:
package: abcd
istio: mixer-adapter
spec:
group: config.istio.io
names:
kind: abcd
plural: abcds
singular: abcd
scope: Namespaced
version: v1alpha2
---`
var exampleTmplInfos = map[string]template.Info{
"abcd-foo": {Name: "abcd-foo", Impl: "implPathShouldBeDNSCompat"},
"abcdBar": {Name: "abcdBar", Impl: "implPathShouldBeDNSCompat2"},
"entry": {Name: "entry", Impl: "implPathShouldBeDNSCompat2"}, // unusual plural
"prometheus": {Name: "prometheus", Impl: "implPathShouldBeDNSCompat2"}, // unusual plural
"box": {Name: "box", Impl: "implPathShouldBeDNSCompat2"}, // unusual plural
}
var exampleInstanceCrd = `kind: CustomResourceDefinition
apiVersion: apiextensions.k8s.io/v1beta1
metadata:
name: abcd-foos.config.istio.io
labels:
package: implPathShouldBeDNSCompat
istio: mixer-instance
spec:
group: config.istio.io
names:
kind: abcd-foo
plural: abcd-foos
singular: abcd-foo
scope: Namespaced
version: v1alpha2
---
kind: CustomResourceDefinition
apiVersion: apiextensions.k8s.io/v1beta1
metadata:
name: abcdBars.config.istio.io
labels:
package: implPathShouldBeDNSCompat2
istio: mixer-instance
spec:
group: config.istio.io
names:
kind: abcdBar
plural: abcdBars
singular: abcdBar
scope: Namespaced
version: v1alpha2
---
kind: CustomResourceDefinition
apiVersion: apiextensions.k8s.io/v1beta1
metadata:
name: boxes.config.istio.io
labels:
package: implPathShouldBeDNSCompat2
istio: mixer-instance
spec:
group: config.istio.io
names:
kind: box
plural: boxes
singular: box
scope: Namespaced
version: v1alpha2
---
kind: CustomResourceDefinition
apiVersion: apiextensions.k8s.io/v1beta1
metadata:
name: entries.config.istio.io
labels:
package: implPathShouldBeDNSCompat2
istio: mixer-instance
spec:
group: config.istio.io
names:
kind: entry
plural: entries
singular: entry
scope: Namespaced
version: v1alpha2
---
kind: CustomResourceDefinition
apiVersion: apiextensions.k8s.io/v1beta1
metadata:
name: prometheuses.config.istio.io
labels:
package: implPathShouldBeDNSCompat2
istio: mixer-instance
spec:
group: config.istio.io
names:
kind: prometheus
plural: prometheuses
singular: prometheus
scope: Namespaced
version: v1alpha2
---
`
func TestListCrdsAdapters(t *testing.T) {
tests := []struct {
name string
args []adptr.InfoFn
wantOut string
}{
{"empty", []adptr.InfoFn{}, empty},
{"example", exampleAdapters, exampleAdaptersCrd},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var buffer bytes.Buffer
var printf = func(format string, args ...interface{}) {
buffer.WriteString(fmt.Sprintf(format, args...))
}
listCrdsAdapters(printf, printf, tt.args)
gotOut := buffer.String()
if strings.TrimSpace(gotOut) != strings.TrimSpace(tt.wantOut) {
t.Errorf("listCrdsAdapters() = %s, want %s", gotOut, tt.wantOut)
}
})
}
}
func TestListCrdsInstances(t *testing.T) {
tests := []struct {
name string
args map[string]template.Info
wantOut string
}{
{"empty", map[string]template.Info{}, empty},
{"example", exampleTmplInfos, exampleInstanceCrd},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var buffer bytes.Buffer
var printf = func(format string, args ...interface{}) {
buffer.WriteString(fmt.Sprintf(format, args...))
}
listCrdsInstances(printf, printf, tt.args)
gotOut := buffer.String()
if strings.TrimSpace(gotOut) != strings.TrimSpace(tt.wantOut) {
t.Errorf("listCrdsInstances() = %v, want %v", gotOut, tt.wantOut)
}
})
}
}
func TestNameFormat(t *testing.T) {
validNamePattern := regexp.MustCompile(`^([a-z0-9]+-)*[a-z0-9]+$`)
for _, infoFn := range adapter.Inventory() {
info := infoFn()
if !validNamePattern.MatchString(info.Name) {
t.Errorf("Name %s doesn't match the pattern %v", info.Name, validNamePattern)
}
}
for _, info := range generatedTemplate.SupportedTmplInfo {
if !validNamePattern.MatchString(info.Name) {
t.Errorf("Name %s doesn't match the pattern %v", info.Name, validNamePattern)
}
}
}
| mixer/cmd/mixs/cmd/crd_test.go | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.00017892505275085568,
0.00017410241707693785,
0.00016611588944215328,
0.00017544202273711562,
0.000003935089353035437
] |
{
"id": 5,
"code_window": [
"\t\t\tgracePeriodRatio: 1, // Always in grace period\n",
"\t\t\tminGracePeriod: defaultMinGracePeriod,\n",
"\t\t},\n",
"\t\t\"Update secret in min grace period\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tminGracePeriod: 10 * time.Minute,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 203
} | // Copyright 2017 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 store
import (
"errors"
"fmt"
"net/url"
"sync"
"github.com/gogo/protobuf/proto"
"istio.io/istio/pkg/log"
"istio.io/istio/pkg/probe"
)
// ChangeType denotes the type of a change
type ChangeType int
const (
// Update - change was an update or a create to a key.
Update ChangeType = iota
// Delete - key was removed.
Delete
)
// ErrNotFound is the error to be returned when the given key does not exist in the storage.
var ErrNotFound = errors.New("not found")
// ErrWatchAlreadyExists is the error to report that the watching channel already exists.
var ErrWatchAlreadyExists = errors.New("watch already exists")
// Key represents the key to identify a resource in the store.
type Key struct {
Kind string
Namespace string
Name string
}
// BackendEvent is an event used between Backend and Store.
type BackendEvent struct {
Key
Type ChangeType
Value *BackEndResource
}
// ResourceMeta is the standard metadata associated with a resource.
type ResourceMeta struct {
Name string
Namespace string
Labels map[string]string
Annotations map[string]string
Revision string
}
// BackEndResource represents a resources with a raw spec
type BackEndResource struct {
Kind string
Metadata ResourceMeta
Spec map[string]interface{}
}
// Key returns the key of the resource in the store.
func (ber *BackEndResource) Key() Key {
return Key{Kind: ber.Kind, Name: ber.Metadata.Name, Namespace: ber.Metadata.Namespace}
}
// Resource represents a resources with converted spec.
type Resource struct {
Metadata ResourceMeta
Spec proto.Message
}
// String is the Istio compatible string representation of the resource.
// Name.Kind.Namespace
// At the point of use Namespace can be omitted, and it is assumed to be the namespace
// of the document.
func (k Key) String() string {
return k.Name + "." + k.Kind + "." + k.Namespace
}
// Event represents an event. Used by Store.Watch.
type Event struct {
Key
Type ChangeType
// Value refers the new value in the updated event. nil if the event type is delete.
Value *Resource
}
// BackendValidator defines the interface to validte unstructured event.
type BackendValidator interface {
Validate(ev *BackendEvent) error
}
// Validator defines the interface to validate a new change.
type Validator interface {
Validate(ev *Event) error
}
// Backend defines the typeless storage backend for mixer.
type Backend interface {
Init(kinds []string) error
Stop()
// Watch creates a channel to receive the events.
Watch() (<-chan BackendEvent, error)
// Get returns a resource's spec to the key.
Get(key Key) (*BackEndResource, error)
// List returns the whole mapping from key to resource specs in the store.
List() map[Key]*BackEndResource
}
// Store defines the access to the storage for mixer.
type Store interface {
Init(kinds map[string]proto.Message) error
Stop()
// Watch creates a channel to receive the events. A store can conduct a single
// watch channel at the same time. Multiple calls lead to an error.
Watch() (<-chan Event, error)
// Get returns a resource's spec to the key.
Get(key Key, spec proto.Message) error
// List returns the whole mapping from key to resource specs in the store.
List() map[Key]*Resource
probe.SupportsProbe
}
// store is the implementation of Store interface.
type store struct {
kinds map[string]proto.Message
backend Backend
mu sync.Mutex
queue *eventQueue
}
func (s *store) RegisterProbe(c probe.Controller, name string) {
if e, ok := s.backend.(probe.SupportsProbe); ok {
e.RegisterProbe(c, name)
}
}
func (s *store) Stop() {
s.mu.Lock()
if s.queue != nil {
close(s.queue.closec)
}
s.queue = nil
s.mu.Unlock()
s.backend.Stop()
}
// Init initializes the connection with the storage backend. This uses "kinds"
// for the mapping from the kind's name and its structure in protobuf.
func (s *store) Init(kinds map[string]proto.Message) error {
kindNames := make([]string, 0, len(kinds))
for k := range kinds {
kindNames = append(kindNames, k)
}
if err := s.backend.Init(kindNames); err != nil {
return err
}
s.kinds = kinds
return nil
}
// Watch creates a channel to receive the events.
func (s *store) Watch() (<-chan Event, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.queue != nil {
return nil, ErrWatchAlreadyExists
}
ch, err := s.backend.Watch()
if err != nil {
return nil, err
}
q := newQueue(ch, s.kinds)
s.queue = q
return q.chout, nil
}
// Get returns a resource's spec to the key.
func (s *store) Get(key Key, spec proto.Message) error {
obj, err := s.backend.Get(key)
if err != nil {
return err
}
return convert(key, obj.Spec, spec)
}
// List returns the whole mapping from key to resource specs in the store.
func (s *store) List() map[Key]*Resource {
data := s.backend.List()
result := make(map[Key]*Resource, len(data))
for k, d := range data {
pbSpec, err := cloneMessage(k.Kind, s.kinds)
if err != nil {
log.Errorf("Failed to clone %s spec: %v", k, err)
continue
}
if err = convert(k, d.Spec, pbSpec); err != nil {
log.Errorf("Failed to convert %s spec: %v", k, err)
continue
}
result[k] = &Resource{
Metadata: d.Metadata,
Spec: pbSpec,
}
}
return result
}
// WithBackend creates a new Store with a certain backend. This should be used
// only by tests.
func WithBackend(b Backend) Store {
return &store{backend: b}
}
// Builder is the type of function to build a Backend.
type Builder func(u *url.URL) (Backend, error)
// RegisterFunc is the type to register a builder for URL scheme.
type RegisterFunc func(map[string]Builder)
// Registry keeps the relationship between the URL scheme and
// the Backend implementation.
type Registry struct {
builders map[string]Builder
}
// NewRegistry creates a new Registry instance for the inventory.
func NewRegistry(inventory ...RegisterFunc) *Registry {
b := map[string]Builder{}
for _, rf := range inventory {
rf(b)
}
return &Registry{builders: b}
}
// URL types supported by the config store
const (
// example fs:///tmp/testdata/configroot
FSUrl = "fs"
)
// NewStore creates a new Store instance with the specified backend.
func (r *Registry) NewStore(configURL string) (Store, error) {
u, err := url.Parse(configURL)
if err != nil {
return nil, fmt.Errorf("invalid config URL %s %v", configURL, err)
}
var b Backend
switch u.Scheme {
case FSUrl:
b = newFsStore(u.Path)
default:
if builder, ok := r.builders[u.Scheme]; ok {
b, err = builder(u)
if err != nil {
return nil, err
}
}
}
if b != nil {
return &store{backend: b}, nil
}
return nil, fmt.Errorf("unknown config URL %s %v", configURL, u)
}
| mixer/pkg/config/store/store.go | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.0012524883495643735,
0.00023335448349826038,
0.00016112244338728487,
0.0001697996340226382,
0.00022973133309278637
] |
{
"id": 6,
"code_window": [
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n",
"\t\t\tttl: 10 * time.Minute,\n",
"\t\t\tgracePeriodRatio: defaultGracePeriodRatio,\n",
"\t\t\tminGracePeriod: time.Hour, // ttl is always in minGracePeriod\n",
"\t\t},\n",
"\t\t\"Update expired secret\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tgracePeriodRatio: 0.5,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 210
} | // Copyright 2017 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 controller
import (
"bytes"
"fmt"
"reflect"
"time"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/cache"
"istio.io/istio/pkg/log"
"istio.io/istio/security/pkg/pki/ca"
"istio.io/istio/security/pkg/pki/util"
)
/* #nosec: disable gas linter */
const (
// The Istio secret annotation type
IstioSecretType = "istio.io/key-and-cert"
// The ID/name for the certificate chain file.
CertChainID = "cert-chain.pem"
// The ID/name for the private key file.
PrivateKeyID = "key.pem"
// The ID/name for the CA root certificate file.
RootCertID = "root-cert.pem"
secretNamePrefix = "istio."
secretResyncPeriod = time.Minute
serviceAccountNameAnnotationKey = "istio.io/service-account.name"
recommendedMinGracePeriodRatio = 0.3
recommendedMaxGracePeriodRatio = 0.8
// The size of a private key for a leaf certificate.
keySize = 2048
)
// SecretController manages the service accounts' secrets that contains Istio keys and certificates.
type SecretController struct {
ca ca.CertificateAuthority
certTTL time.Duration
core corev1.CoreV1Interface
// Length of the grace period for the certificate rotation.
gracePeriodRatio float32
minGracePeriod time.Duration
// Controller and store for service account objects.
saController cache.Controller
saStore cache.Store
// Controller and store for secret objects.
scrtController cache.Controller
scrtStore cache.Store
}
// NewSecretController returns a pointer to a newly constructed SecretController instance.
func NewSecretController(ca ca.CertificateAuthority, certTTL time.Duration, gracePeriodRatio float32, minGracePeriod time.Duration,
core corev1.CoreV1Interface, namespace string) (*SecretController, error) {
if gracePeriodRatio < 0 || gracePeriodRatio > 1 {
return nil, fmt.Errorf("grace period ratio %f should be within [0, 1]", gracePeriodRatio)
}
if gracePeriodRatio < recommendedMinGracePeriodRatio || gracePeriodRatio > recommendedMaxGracePeriodRatio {
log.Warnf("grace period ratio %f is out of the recommended window [%.2f, %.2f]",
gracePeriodRatio, recommendedMinGracePeriodRatio, recommendedMaxGracePeriodRatio)
}
c := &SecretController{
ca: ca,
certTTL: certTTL,
gracePeriodRatio: gracePeriodRatio,
minGracePeriod: minGracePeriod,
core: core,
}
saLW := &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
return core.ServiceAccounts(namespace).List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
return core.ServiceAccounts(namespace).Watch(options)
},
}
rehf := cache.ResourceEventHandlerFuncs{
AddFunc: c.saAdded,
DeleteFunc: c.saDeleted,
UpdateFunc: c.saUpdated,
}
c.saStore, c.saController = cache.NewInformer(saLW, &v1.ServiceAccount{}, time.Minute, rehf)
istioSecretSelector := fields.SelectorFromSet(map[string]string{"type": IstioSecretType}).String()
scrtLW := &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
options.FieldSelector = istioSecretSelector
return core.Secrets(namespace).List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.FieldSelector = istioSecretSelector
return core.Secrets(namespace).Watch(options)
},
}
c.scrtStore, c.scrtController =
cache.NewInformer(scrtLW, &v1.Secret{}, secretResyncPeriod, cache.ResourceEventHandlerFuncs{
DeleteFunc: c.scrtDeleted,
UpdateFunc: c.scrtUpdated,
})
return c, nil
}
// Run starts the SecretController until a value is sent to stopCh.
func (sc *SecretController) Run(stopCh chan struct{}) {
go sc.scrtController.Run(stopCh)
go sc.saController.Run(stopCh)
}
// Handles the event where a service account is added.
func (sc *SecretController) saAdded(obj interface{}) {
acct := obj.(*v1.ServiceAccount)
sc.upsertSecret(acct.GetName(), acct.GetNamespace())
}
// Handles the event where a service account is deleted.
func (sc *SecretController) saDeleted(obj interface{}) {
acct := obj.(*v1.ServiceAccount)
sc.deleteSecret(acct.GetName(), acct.GetNamespace())
}
// Handles the event where a service account is updated.
func (sc *SecretController) saUpdated(oldObj, curObj interface{}) {
if reflect.DeepEqual(oldObj, curObj) {
// Nothing is changed. The method is invoked by periodical re-sync with the apiserver.
return
}
oldSa := oldObj.(*v1.ServiceAccount)
curSa := curObj.(*v1.ServiceAccount)
curName := curSa.GetName()
curNamespace := curSa.GetNamespace()
oldName := oldSa.GetName()
oldNamespace := oldSa.GetNamespace()
// We only care the name and namespace of a service account.
if curName != oldName || curNamespace != oldNamespace {
sc.deleteSecret(oldName, oldNamespace)
sc.upsertSecret(curName, curNamespace)
log.Infof("Service account \"%s\" in namespace \"%s\" has been updated to \"%s\" in namespace \"%s\"",
oldName, oldNamespace, curName, curNamespace)
}
}
func (sc *SecretController) upsertSecret(saName, saNamespace string) {
secret := &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{serviceAccountNameAnnotationKey: saName},
Name: getSecretName(saName),
Namespace: saNamespace,
},
Type: IstioSecretType,
}
_, exists, err := sc.scrtStore.Get(secret)
if err != nil {
log.Errorf("Failed to get secret from the store (error %v)", err)
}
if exists {
// Do nothing for existing secrets. Rotating expiring certs are handled by the `scrtUpdated` method.
return
}
// Now we know the secret does not exist yet. So we create a new one.
chain, key, err := sc.generateKeyAndCert(saName, saNamespace)
if err != nil {
log.Errorf("Failed to generate key and certificate for service account %q in namespace %q (error %v)",
saName, saNamespace, err)
return
}
rootCert := sc.ca.GetRootCertificate()
secret.Data = map[string][]byte{
CertChainID: chain,
PrivateKeyID: key,
RootCertID: rootCert,
}
_, err = sc.core.Secrets(saNamespace).Create(secret)
if err != nil {
log.Errorf("Failed to create secret (error: %s)", err)
return
}
log.Infof("Istio secret for service account \"%s\" in namespace \"%s\" has been created", saName, saNamespace)
}
func (sc *SecretController) deleteSecret(saName, saNamespace string) {
err := sc.core.Secrets(saNamespace).Delete(getSecretName(saName), nil)
// kube-apiserver returns NotFound error when the secret is successfully deleted.
if err == nil || errors.IsNotFound(err) {
log.Infof("Istio secret for service account \"%s\" in namespace \"%s\" has been deleted", saName, saNamespace)
return
}
log.Errorf("Failed to delete Istio secret for service account \"%s\" in namespace \"%s\" (error: %s)",
saName, saNamespace, err)
}
func (sc *SecretController) scrtDeleted(obj interface{}) {
scrt, ok := obj.(*v1.Secret)
if !ok {
log.Warnf("Failed to convert to secret object: %v", obj)
return
}
log.Infof("Re-create deleted Istio secret")
saName := scrt.Annotations[serviceAccountNameAnnotationKey]
sc.upsertSecret(saName, scrt.GetNamespace())
}
func (sc *SecretController) generateKeyAndCert(saName string, saNamespace string) ([]byte, []byte, error) {
id := fmt.Sprintf("%s://cluster.local/ns/%s/sa/%s", util.URIScheme, saNamespace, saName)
options := util.CertOptions{
Host: id,
RSAKeySize: keySize,
}
csrPEM, keyPEM, err := util.GenCSR(options)
if err != nil {
return nil, nil, err
}
certPEM, err := sc.ca.Sign(csrPEM, sc.certTTL, false)
if err != nil {
return nil, nil, err
}
return certPEM, keyPEM, nil
}
func (sc *SecretController) scrtUpdated(oldObj, newObj interface{}) {
scrt, ok := newObj.(*v1.Secret)
if !ok {
log.Warnf("Failed to convert to secret object: %v", newObj)
return
}
certBytes := scrt.Data[CertChainID]
cert, err := util.ParsePemEncodedCertificate(certBytes)
if err != nil {
// TODO: we should refresh secret in this case since the secret contains an
// invalid cert.
log.Errora(err)
return
}
certLifeTimeLeft := time.Until(cert.NotAfter)
certLifeTime := cert.NotAfter.Sub(cert.NotBefore)
// TODO(myidpt): we may introduce a minimum gracePeriod, without making the config too complex.
gracePeriod := time.Duration(sc.gracePeriodRatio) * certLifeTime
if gracePeriod < sc.minGracePeriod {
log.Warnf("gracePeriod (%v * %f) = %v is less than minGracePeriod %v. Apply minGracePeriod.",
certLifeTime, sc.gracePeriodRatio, sc.minGracePeriod)
gracePeriod = sc.minGracePeriod
}
rootCertificate := sc.ca.GetRootCertificate()
// Refresh the secret if 1) the certificate contained in the secret is about
// to expire, or 2) the root certificate in the secret is different than the
// one held by the ca (this may happen when the CA is restarted and
// a new self-signed CA cert is generated).
if certLifeTimeLeft < gracePeriod || !bytes.Equal(rootCertificate, scrt.Data[RootCertID]) {
namespace := scrt.GetNamespace()
name := scrt.GetName()
log.Infof("Refreshing secret %s/%s, either the leaf certificate is about to expire "+
"or the root certificate is outdated", namespace, name)
saName := scrt.Annotations[serviceAccountNameAnnotationKey]
chain, key, err := sc.generateKeyAndCert(saName, namespace)
if err != nil {
log.Errorf("Failed to generate key and certificate for service account %q in namespace %q (error %v)",
saName, namespace, err)
return
}
scrt.Data[CertChainID] = chain
scrt.Data[PrivateKeyID] = key
scrt.Data[RootCertID] = rootCertificate
if _, err = sc.core.Secrets(namespace).Update(scrt); err != nil {
log.Errorf("Failed to update secret %s/%s (error: %s)", namespace, name, err)
}
}
}
func getSecretName(saName string) string {
return secretNamePrefix + saName
}
| security/pkg/pki/ca/controller/secret.go | 1 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.013470017351210117,
0.0009007601765915751,
0.00016253186913672835,
0.00017005178960971534,
0.00236268131993711
] |
{
"id": 6,
"code_window": [
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n",
"\t\t\tttl: 10 * time.Minute,\n",
"\t\t\tgracePeriodRatio: defaultGracePeriodRatio,\n",
"\t\t\tminGracePeriod: time.Hour, // ttl is always in minGracePeriod\n",
"\t\t},\n",
"\t\t\"Update expired secret\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tgracePeriodRatio: 0.5,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 210
} | // Copyright 2017 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 cloudfoundry
import "istio.io/istio/pilot/pkg/model"
type serviceAccounts struct {
}
// NewServiceAccounts instantiates the Cloud Foundry service account interface
func NewServiceAccounts() model.ServiceAccounts {
return &serviceAccounts{}
}
func (sa *serviceAccounts) GetIstioServiceAccounts(hostname string, ports []string) []string {
return nil
}
| pilot/pkg/serviceregistry/cloudfoundry/serviceaccounts.go | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.00017835290054790676,
0.00017177057452499866,
0.00016322343435604125,
0.00017373537411913276,
0.0000063309043980552815
] |
{
"id": 6,
"code_window": [
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n",
"\t\t\tttl: 10 * time.Minute,\n",
"\t\t\tgracePeriodRatio: defaultGracePeriodRatio,\n",
"\t\t\tminGracePeriod: time.Hour, // ttl is always in minGracePeriod\n",
"\t\t},\n",
"\t\t\"Update expired secret\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tgracePeriodRatio: 0.5,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 210
} | {
"clusters": [
{
"name": "in.1081",
"connect_timeout_ms": 1000,
"type": "static",
"lb_type": "round_robin",
"hosts": [
{
"url": "tcp://127.0.0.1:1081"
}
]
},
{
"name": "in.1090",
"connect_timeout_ms": 1000,
"type": "static",
"lb_type": "round_robin",
"hosts": [
{
"url": "tcp://127.0.0.1:1090"
}
]
},
{
"name": "in.1100",
"connect_timeout_ms": 1000,
"type": "static",
"lb_type": "round_robin",
"hosts": [
{
"url": "tcp://127.0.0.1:1100"
}
]
},
{
"name": "in.1110",
"connect_timeout_ms": 1000,
"type": "static",
"lb_type": "round_robin",
"hosts": [
{
"url": "tcp://127.0.0.1:1110"
}
]
},
{
"name": "in.3333",
"connect_timeout_ms": 1000,
"type": "static",
"lb_type": "round_robin",
"hosts": [
{
"url": "tcp://127.0.0.1:3333"
}
]
},
{
"name": "in.80",
"connect_timeout_ms": 1000,
"type": "static",
"lb_type": "round_robin",
"hosts": [
{
"url": "tcp://127.0.0.1:80"
}
]
},
{
"name": "in.9999",
"connect_timeout_ms": 1000,
"type": "static",
"lb_type": "round_robin",
"hosts": [
{
"url": "tcp://127.0.0.1:9999"
}
]
},
{
"name": "out.*.google.com|external-HTTP-80",
"service_name": "*.google.com|external-HTTP-80",
"connect_timeout_ms": 1000,
"type": "strict_dns",
"lb_type": "round_robin",
"hosts": [
{
"url": "tcp://us.google.com:7080"
},
{
"url": "tcp://uk.google.com:1080"
},
{
"url": "tcp://de.google.com:80"
}
]
},
{
"name": "out.*.google.com|external-HTTP-8080",
"service_name": "*.google.com|external-HTTP-8080",
"connect_timeout_ms": 1000,
"type": "strict_dns",
"lb_type": "round_robin",
"hosts": [
{
"url": "tcp://us.google.com:18080"
},
{
"url": "tcp://uk.google.com:8080"
},
{
"url": "tcp://de.google.com:8080"
}
]
},
{
"name": "out.hello.default.svc.cluster.local|custom",
"service_name": "hello.default.svc.cluster.local|custom",
"connect_timeout_ms": 1000,
"type": "sds",
"lb_type": "round_robin"
},
{
"name": "out.hello.default.svc.cluster.local|http",
"service_name": "hello.default.svc.cluster.local|http",
"connect_timeout_ms": 1000,
"type": "sds",
"lb_type": "round_robin"
},
{
"name": "out.hello.default.svc.cluster.local|http-status",
"service_name": "hello.default.svc.cluster.local|http-status",
"connect_timeout_ms": 1000,
"type": "sds",
"lb_type": "round_robin"
},
{
"name": "out.hello.default.svc.cluster.local|mongo",
"service_name": "hello.default.svc.cluster.local|mongo",
"connect_timeout_ms": 1000,
"type": "sds",
"lb_type": "round_robin"
},
{
"name": "out.hello.default.svc.cluster.local|redis",
"service_name": "hello.default.svc.cluster.local|redis",
"connect_timeout_ms": 1000,
"type": "sds",
"lb_type": "round_robin"
},
{
"name": "out.httpbin.default.svc.cluster.local|http",
"service_name": "httpbin.default.svc.cluster.local|http",
"connect_timeout_ms": 1000,
"type": "strict_dns",
"lb_type": "round_robin",
"hosts": [
{
"url": "tcp://httpbin.default.svc.cluster.local:80"
}
]
},
{
"name": "out.httpsbin.default.svc.cluster.local|https",
"service_name": "httpsbin.default.svc.cluster.local|https",
"connect_timeout_ms": 1000,
"type": "strict_dns",
"lb_type": "round_robin",
"hosts": [
{
"url": "tcp://httpsbin.default.svc.cluster.local:443"
}
]
},
{
"name": "out.world.default.svc.cluster.local|custom",
"service_name": "world.default.svc.cluster.local|custom",
"connect_timeout_ms": 1000,
"type": "sds",
"lb_type": "round_robin"
},
{
"name": "out.world.default.svc.cluster.local|http",
"service_name": "world.default.svc.cluster.local|http",
"connect_timeout_ms": 1000,
"type": "sds",
"lb_type": "round_robin"
},
{
"name": "out.world.default.svc.cluster.local|http-status",
"service_name": "world.default.svc.cluster.local|http-status",
"connect_timeout_ms": 1000,
"type": "sds",
"lb_type": "round_robin"
},
{
"name": "out.world.default.svc.cluster.local|mongo",
"service_name": "world.default.svc.cluster.local|mongo",
"connect_timeout_ms": 1000,
"type": "sds",
"lb_type": "round_robin"
},
{
"name": "out.world.default.svc.cluster.local|redis",
"service_name": "world.default.svc.cluster.local|redis",
"connect_timeout_ms": 1000,
"type": "sds",
"lb_type": "round_robin"
},
{
"name": "mixer_check_server",
"connect_timeout_ms": 1000,
"type": "strict_dns",
"lb_type": "round_robin",
"hosts": [
{
"url": "tcp://istio-mixer.istio-system:9091"
}
],
"features": "http2",
"circuit_breakers": {
"default": {
"max_pending_requests": 10000,
"max_requests": 10000
}
}
},
{
"name": "mixer_report_server",
"connect_timeout_ms": 1000,
"type": "strict_dns",
"lb_type": "round_robin",
"hosts": [
{
"url": "tcp://istio-mixer.istio-system:9091"
}
],
"features": "http2",
"circuit_breakers": {
"default": {
"max_pending_requests": 10000,
"max_requests": 10000
}
}
}
]
} | pilot/pkg/proxy/envoy/v1/testdata/cds-v0-http-dns.json.golden | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.00017573736840859056,
0.00017128072795458138,
0.0001661585265537724,
0.00017081461555790156,
0.000002738847115324461
] |
{
"id": 6,
"code_window": [
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n",
"\t\t\tttl: 10 * time.Minute,\n",
"\t\t\tgracePeriodRatio: defaultGracePeriodRatio,\n",
"\t\t\tminGracePeriod: time.Hour, // ttl is always in minGracePeriod\n",
"\t\t},\n",
"\t\t\"Update expired secret\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tgracePeriodRatio: 0.5,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 210
} | // Copyright 2017 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 consul
import (
"sync"
"testing"
"time"
"github.com/hashicorp/consul/api"
"istio.io/istio/pilot/pkg/model"
)
const (
resync = 5 * time.Millisecond
notifyThreshold = resync * 10
)
func TestController(t *testing.T) {
// https://github.com/istio/istio/issues/2318
t.SkipNow()
ts := newServer()
defer ts.Server.Close()
conf := api.DefaultConfig()
conf.Address = ts.Server.URL
cl, err := api.NewClient(conf)
if err != nil {
t.Errorf("could not create Consul Controller: %v", err)
}
countMutex := sync.Mutex{}
count := 0
incrementCount := func() {
countMutex.Lock()
defer countMutex.Unlock()
count++
}
getCountAndReset := func() int {
countMutex.Lock()
defer countMutex.Unlock()
i := count
count = 0
return i
}
ctl := NewConsulMonitor(cl, resync)
ctl.AppendInstanceHandler(func(instance *api.CatalogService, event model.Event) error {
incrementCount()
return nil
})
ctl.AppendServiceHandler(func(instances []*api.CatalogService, event model.Event) error {
incrementCount()
return nil
})
stop := make(chan struct{})
go ctl.Start(stop)
defer close(stop)
time.Sleep(notifyThreshold)
getCountAndReset()
time.Sleep(notifyThreshold)
if i := getCountAndReset(); i != 0 {
t.Errorf("got %d notifications from controller, want %d", i, 0)
}
// re-ordering of service instances -> does not trigger update
ts.Lock.Lock()
tmpReview := reviews[0]
reviews[0] = reviews[len(reviews)-1]
reviews[len(reviews)-1] = tmpReview
ts.Lock.Unlock()
time.Sleep(notifyThreshold)
if i := getCountAndReset(); i != 0 {
t.Errorf("got %d notifications from controller, want %d", i, 0)
}
// same service, new tag -> triggers instance update
ts.Lock.Lock()
ts.Productpage[0].ServiceTags = append(ts.Productpage[0].ServiceTags, "new|tag")
ts.Lock.Unlock()
time.Sleep(notifyThreshold)
if i := getCountAndReset(); i != 1 {
t.Errorf("got %d notifications from controller, want %d", i, 2)
}
// delete a service instance -> trigger instance update
ts.Lock.Lock()
ts.Reviews = reviews[0:1]
ts.Lock.Unlock()
time.Sleep(notifyThreshold)
if i := getCountAndReset(); i != 1 {
t.Errorf("got %d notifications from controller, want %d", i, 1)
}
// delete a service -> trigger service and instance update
ts.Lock.Lock()
delete(ts.Services, "productpage")
ts.Lock.Unlock()
time.Sleep(notifyThreshold)
if i := getCountAndReset(); i != 2 {
t.Errorf("got %d notifications from controller, want %d", i, 2)
}
}
| pilot/pkg/serviceregistry/consul/monitor_test.go | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.00018098580767400563,
0.00017290377581957728,
0.00016725948080420494,
0.000172944986843504,
0.0000036848325635219226
] |
{
"id": 7,
"code_window": [
"\t\t\"Update expired secret\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n",
"\t\t\tttl: -time.Second,\n",
"\t\t\tgracePeriodRatio: defaultGracePeriodRatio,\n",
"\t\t\tminGracePeriod: defaultMinGracePeriod,\n",
"\t\t},\n",
"\t\t\"Update secret with different root cert\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tgracePeriodRatio: 0.5,\n",
"\t\t\tminGracePeriod: 10 * time.Minute,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 218
} | // Copyright 2017 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 controller
import (
"fmt"
"testing"
"time"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/kubernetes/fake"
ktesting "k8s.io/client-go/testing"
"istio.io/istio/security/pkg/pki/util"
)
const (
defaultTTL = time.Hour
defaultGracePeriodRatio = 0.5
defaultMinGracePeriod = 10 * time.Minute
)
type fakeCa struct{}
func (ca *fakeCa) Sign([]byte, time.Duration, bool) ([]byte, error) {
return []byte("fake cert chain"), nil
}
func (ca *fakeCa) GetRootCertificate() []byte {
return []byte("fake root cert")
}
func (ca *fakeCa) GetCertChain() []byte {
return []byte("fake cert chain")
}
func createSecret(saName, scrtName, namespace string) *v1.Secret {
return &v1.Secret{
Data: map[string][]byte{
CertChainID: []byte("fake cert chain"),
PrivateKeyID: []byte("fake key"),
RootCertID: []byte("fake root cert"),
},
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{"istio.io/service-account.name": saName},
Name: scrtName,
Namespace: namespace,
},
Type: IstioSecretType,
}
}
func createServiceAccount(name, namespace string) *v1.ServiceAccount {
return &v1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
}
}
type updatedSas struct {
curSa *v1.ServiceAccount
oldSa *v1.ServiceAccount
}
func TestSecretController(t *testing.T) {
gvr := schema.GroupVersionResource{
Resource: "secrets",
Version: "v1",
}
testCases := map[string]struct {
existingSecret *v1.Secret
saToAdd *v1.ServiceAccount
saToDelete *v1.ServiceAccount
sasToUpdate *updatedSas
expectedActions []ktesting.Action
}{
"adding service account creates new secret": {
saToAdd: createServiceAccount("test", "test-ns"),
expectedActions: []ktesting.Action{
ktesting.NewCreateAction(gvr, "test-ns", createSecret("test", "istio.test", "test-ns")),
},
},
"removing service account deletes existing secret": {
saToDelete: createServiceAccount("deleted", "deleted-ns"),
expectedActions: []ktesting.Action{
ktesting.NewDeleteAction(gvr, "deleted-ns", "istio.deleted"),
},
},
"updating service accounts does nothing if name and namespace are not changed": {
sasToUpdate: &updatedSas{
curSa: createServiceAccount("name", "ns"),
oldSa: createServiceAccount("name", "ns"),
},
expectedActions: []ktesting.Action{},
},
"updating service accounts deletes old secret and creates a new one": {
sasToUpdate: &updatedSas{
curSa: createServiceAccount("new-name", "new-ns"),
oldSa: createServiceAccount("old-name", "old-ns"),
},
expectedActions: []ktesting.Action{
ktesting.NewDeleteAction(gvr, "old-ns", "istio.old-name"),
ktesting.NewCreateAction(gvr, "new-ns", createSecret("new-name", "istio.new-name", "new-ns")),
},
},
"adding new service account does not overwrite existing secret": {
existingSecret: createSecret("test", "istio.test", "test-ns"),
saToAdd: createServiceAccount("test", "test-ns"),
expectedActions: []ktesting.Action{},
},
}
for k, tc := range testCases {
client := fake.NewSimpleClientset()
controller, err := NewSecretController(&fakeCa{}, defaultTTL, defaultGracePeriodRatio, defaultMinGracePeriod,
client.CoreV1(), metav1.NamespaceAll)
if err != nil {
t.Errorf("failed to create secret controller: %v", err)
}
if tc.existingSecret != nil {
err := controller.scrtStore.Add(tc.existingSecret)
if err != nil {
t.Errorf("Failed to add a secret (error %v)", err)
}
}
if tc.saToAdd != nil {
controller.saAdded(tc.saToAdd)
}
if tc.saToDelete != nil {
controller.saDeleted(tc.saToDelete)
}
if tc.sasToUpdate != nil {
controller.saUpdated(tc.sasToUpdate.oldSa, tc.sasToUpdate.curSa)
}
if err := checkActions(client.Actions(), tc.expectedActions); err != nil {
t.Errorf("Case %q: %s", k, err.Error())
}
}
}
func TestRecoverFromDeletedIstioSecret(t *testing.T) {
client := fake.NewSimpleClientset()
controller, err := NewSecretController(&fakeCa{}, defaultTTL, defaultGracePeriodRatio, defaultMinGracePeriod,
client.CoreV1(), metav1.NamespaceAll)
if err != nil {
t.Errorf("failed to create secret controller: %v", err)
}
scrt := createSecret("test", "istio.test", "test-ns")
controller.scrtDeleted(scrt)
gvr := schema.GroupVersionResource{
Resource: "secrets",
Version: "v1",
}
expectedActions := []ktesting.Action{ktesting.NewCreateAction(gvr, "test-ns", scrt)}
if err := checkActions(client.Actions(), expectedActions); err != nil {
t.Error(err)
}
}
func TestUpdateSecret(t *testing.T) {
gvr := schema.GroupVersionResource{
Resource: "secrets",
Version: "v1",
}
testCases := map[string]struct {
expectedActions []ktesting.Action
ttl time.Duration
gracePeriodRatio float32
minGracePeriod time.Duration
rootCert []byte
}{
"Does not update non-expiring secret": {
expectedActions: []ktesting.Action{},
ttl: time.Hour,
gracePeriodRatio: defaultGracePeriodRatio,
minGracePeriod: defaultMinGracePeriod,
},
"Update secret in grace period": {
expectedActions: []ktesting.Action{
ktesting.NewUpdateAction(gvr, "test-ns", createSecret("test", "istio.test", "test-ns")),
},
ttl: defaultTTL,
gracePeriodRatio: 1, // Always in grace period
minGracePeriod: defaultMinGracePeriod,
},
"Update secret in min grace period": {
expectedActions: []ktesting.Action{
ktesting.NewUpdateAction(gvr, "test-ns", createSecret("test", "istio.test", "test-ns")),
},
ttl: 10 * time.Minute,
gracePeriodRatio: defaultGracePeriodRatio,
minGracePeriod: time.Hour, // ttl is always in minGracePeriod
},
"Update expired secret": {
expectedActions: []ktesting.Action{
ktesting.NewUpdateAction(gvr, "test-ns", createSecret("test", "istio.test", "test-ns")),
},
ttl: -time.Second,
gracePeriodRatio: defaultGracePeriodRatio,
minGracePeriod: defaultMinGracePeriod,
},
"Update secret with different root cert": {
expectedActions: []ktesting.Action{
ktesting.NewUpdateAction(gvr, "test-ns", createSecret("test", "istio.test", "test-ns")),
},
ttl: defaultTTL,
gracePeriodRatio: defaultGracePeriodRatio,
minGracePeriod: defaultMinGracePeriod,
rootCert: []byte("Outdated root cert"),
},
}
for k, tc := range testCases {
client := fake.NewSimpleClientset()
controller, err := NewSecretController(&fakeCa{}, time.Hour, tc.gracePeriodRatio, tc.minGracePeriod,
client.CoreV1(), metav1.NamespaceAll)
if err != nil {
t.Errorf("failed to create secret controller: %v", err)
}
scrt := createSecret("test", "istio.test", "test-ns")
if rc := tc.rootCert; rc != nil {
scrt.Data[RootCertID] = rc
}
opts := util.CertOptions{
IsSelfSigned: true,
TTL: tc.ttl,
RSAKeySize: 512,
}
bs, _, err := util.GenCertKeyFromOptions(opts)
if err != nil {
t.Error(err)
}
scrt.Data[CertChainID] = bs
controller.scrtUpdated(nil, scrt)
if err := checkActions(client.Actions(), tc.expectedActions); err != nil {
t.Errorf("Case %q: %s", k, err.Error())
}
}
}
func checkActions(actual, expected []ktesting.Action) error {
if len(actual) != len(expected) {
return fmt.Errorf("unexpected number of actions, want %d but got %d", len(expected), len(actual))
}
for i, action := range actual {
expectedAction := expected[i]
verb := expectedAction.GetVerb()
resource := expectedAction.GetResource().Resource
if !action.Matches(verb, resource) {
return fmt.Errorf("unexpected %dth action, want %q but got %q", i, expectedAction, action)
}
}
return nil
}
| security/pkg/pki/ca/controller/secret_test.go | 1 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.8293846845626831,
0.033554788678884506,
0.00016507833788637072,
0.0009119640453718603,
0.15119457244873047
] |
{
"id": 7,
"code_window": [
"\t\t\"Update expired secret\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n",
"\t\t\tttl: -time.Second,\n",
"\t\t\tgracePeriodRatio: defaultGracePeriodRatio,\n",
"\t\t\tminGracePeriod: defaultMinGracePeriod,\n",
"\t\t},\n",
"\t\t\"Update secret with different root cert\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tgracePeriodRatio: 0.5,\n",
"\t\t\tminGracePeriod: 10 * time.Minute,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 218
} | // Copyright 2017 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 metric
import (
"fmt"
"testing"
"google.golang.org/genproto/googleapis/api/distribution"
)
func TestIndex(t *testing.T) {
tests := []struct {
name string
in float64
opts *distribution.Distribution_BucketOptions
out int
}{
{"linear-underflow", 0, linear(10, 1, 3), 0}, // 5 buckets: under, 10-11, 11-12, 12-13, over
{"linear-first", 10, linear(10, 1, 3), 1}, // 5 buckets: under, 10-11, 11-12, 12-13, over
{"linear-second", 11, linear(10, 1, 3), 2}, // 5 buckets: under, 10-11, 11-12, 12-13, over
{"linear-third", 12, linear(10, 1, 3), 3}, // 5 buckets: under, 10-11, 11-12, 12-13, over
{"linear-overflow val == max", 13, linear(10, 1, 3), 4}, // 5 buckets: under, 10-11, 11-12, 12-13, over
{"linear-overflow", 17, linear(10, 1, 1), 2}, // 3 buckets total: under, 10-11, over
{"exp-underflow", 0, exp(10, 2, 1), 0}, // 3 buckets: under, 10-20, over
{"exp-first", 10, exp(10, 10, 3), 1}, // 5 buckets: under, 10-100, 100-1000, 1000-10000, over
{"exp-second", 100, exp(10, 10, 3), 2}, // 5 buckets: under, 10-100, 100-1000, 1000-10000, over
{"exp-third", 1000, exp(10, 10, 3), 3}, // 5 buckets: under, 10-100, 100-1000, 1000-10000, over
{"exp-overflow val == max", 20, exp(10, 2, 1), 2}, // 3 buckets: under, 10-20, over
{"exp-overflow", 200, exp(10, 2, 1), 2}, // 3 buckets: under, 10-20, over
{"explicit-underflow", 0, explicit([]float64{1, 2}), 0}, // 3 buckets: under, 1-2, 2-over
{"explicit", 1, explicit([]float64{1, 2}), 1}, // 3 buckets: under, 1-2, 2-over
{"explicit-overflow val == max", 2, explicit([]float64{1, 2}), 2}, // 3 buckets: under, 1-2, 2-over
{"explicit-overflow", 3, explicit([]float64{1, 2}), 2}, // 3 buckets: under, 1-2, 2-over
{"explicit 1 bucket-under", 9, explicit([]float64{10}), 0},
{"explicit 1 bucket-exact", 10, explicit([]float64{10}), 1},
{"explicit 1 bucket-over", 11, explicit([]float64{10}), 1},
}
for idx, tt := range tests {
t.Run(fmt.Sprintf("[%d] %s", idx, tt.name), func(t *testing.T) {
if actual := index(tt.in, tt.opts); actual != tt.out {
t.Fatalf("index(%f, %v) = %d, wanted %d", tt.in, tt.opts, actual, tt.out)
}
})
}
}
func linear(offset, width float64, buckets int32) *distribution.Distribution_BucketOptions {
return &distribution.Distribution_BucketOptions{Options: &distribution.Distribution_BucketOptions_LinearBuckets{
LinearBuckets: &distribution.Distribution_BucketOptions_Linear{
Offset: offset,
Width: width,
NumFiniteBuckets: buckets,
}}}
}
func exp(scale, gf float64, buckets int32) *distribution.Distribution_BucketOptions {
return &distribution.Distribution_BucketOptions{Options: &distribution.Distribution_BucketOptions_ExponentialBuckets{
ExponentialBuckets: &distribution.Distribution_BucketOptions_Exponential{
Scale: scale,
GrowthFactor: gf,
NumFiniteBuckets: buckets,
}}}
}
func explicit(bounds []float64) *distribution.Distribution_BucketOptions {
return &distribution.Distribution_BucketOptions{Options: &distribution.Distribution_BucketOptions_ExplicitBuckets{
ExplicitBuckets: &distribution.Distribution_BucketOptions_Explicit{
Bounds: bounds,
}}}
}
| mixer/adapter/stackdriver/metric/distribution_test.go | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.00017756370652932674,
0.0001726630434859544,
0.0001632293569855392,
0.00017454200133215636,
0.0000043221648411417846
] |
{
"id": 7,
"code_window": [
"\t\t\"Update expired secret\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n",
"\t\t\tttl: -time.Second,\n",
"\t\t\tgracePeriodRatio: defaultGracePeriodRatio,\n",
"\t\t\tminGracePeriod: defaultMinGracePeriod,\n",
"\t\t},\n",
"\t\t\"Update secret with different root cert\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tgracePeriodRatio: 0.5,\n",
"\t\t\tminGracePeriod: 10 * time.Minute,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 218
} | name: hello
subsets:
- name: v0
labels:
version: v0
- name: v1
labels:
version: v1 | pilot/pkg/proxy/envoy/v1/testdata/destination-hello-v1alpha2.yaml.golden | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.00017520412802696228,
0.00017520412802696228,
0.00017520412802696228,
0.00017520412802696228,
0
] |
{
"id": 7,
"code_window": [
"\t\t\"Update expired secret\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n",
"\t\t\tttl: -time.Second,\n",
"\t\t\tgracePeriodRatio: defaultGracePeriodRatio,\n",
"\t\t\tminGracePeriod: defaultMinGracePeriod,\n",
"\t\t},\n",
"\t\t\"Update secret with different root cert\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tgracePeriodRatio: 0.5,\n",
"\t\t\tminGracePeriod: 10 * time.Minute,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 218
} | {
"listeners": [
{
"address": "tcp://0.0.0.0:10080",
"name": "http_0.0.0.0_10080",
"filters": [
{
"type": "read",
"name": "http_connection_manager",
"config": {
"codec_type": "auto",
"stat_prefix": "http",
"generate_request_id": true,
"use_remote_address": true,
"tracing": {
"operation_name": "ingress"
},
"rds": {
"cluster": "rds",
"route_config_name": "10080",
"refresh_delay_ms": 10
},
"filters": [
{
"type": "decoder",
"name": "mixer",
"config": {
"v2": {
"forwardAttributes": {
"attributes": {
"source.ip": {
"bytesValue": "AAAAAAAAAAAAAP//CgMDBQ=="
},
"source.uid": {
"stringValue": "kubernetes://router.default"
}
}
},
"mixerAttributes": {
"attributes": {
"destination.ip": {
"bytesValue": "AAAAAAAAAAAAAP//CgMDBQ=="
},
"destination.uid": {
"stringValue": "kubernetes://router.default"
}
}
},
"serviceConfigs": {},
"transport": {
"checkCluster": "mixer_check_server",
"reportCluster": "mixer_report_server"
}
}
}
},
{
"type": "",
"name": "cors",
"config": {}
},
{
"type": "decoder",
"name": "router",
"config": {}
}
],
"access_log": [
{
"path": "/dev/stdout"
}
]
}
}
],
"bind_to_port": true
},
{
"address": "tcp://0.0.0.0:10088",
"name": "http_0.0.0.0_10088",
"filters": [
{
"type": "read",
"name": "http_connection_manager",
"config": {
"codec_type": "auto",
"stat_prefix": "http",
"generate_request_id": true,
"use_remote_address": true,
"tracing": {
"operation_name": "ingress"
},
"rds": {
"cluster": "rds",
"route_config_name": "10088",
"refresh_delay_ms": 10
},
"filters": [
{
"type": "decoder",
"name": "mixer",
"config": {
"v2": {
"forwardAttributes": {
"attributes": {
"source.ip": {
"bytesValue": "AAAAAAAAAAAAAP//CgMDBQ=="
},
"source.uid": {
"stringValue": "kubernetes://router.default"
}
}
},
"mixerAttributes": {
"attributes": {
"destination.ip": {
"bytesValue": "AAAAAAAAAAAAAP//CgMDBQ=="
},
"destination.uid": {
"stringValue": "kubernetes://router.default"
}
}
},
"serviceConfigs": {},
"transport": {
"checkCluster": "mixer_check_server",
"reportCluster": "mixer_report_server"
}
}
}
},
{
"type": "",
"name": "cors",
"config": {}
},
{
"type": "decoder",
"name": "router",
"config": {}
}
],
"access_log": [
{
"path": "/dev/stdout"
}
]
}
}
],
"bind_to_port": true
}
]
} | pilot/pkg/proxy/envoy/v1/testdata/lds-router-with-gateway.json.golden | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.0001761327584972605,
0.00017333007417619228,
0.00017075387586373836,
0.00017253027181141078,
0.0000016659304264976527
] |
{
"id": 8,
"code_window": [
"\t\t\"Update secret with different root cert\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n",
"\t\t\tttl: defaultTTL,\n",
"\t\t\tgracePeriodRatio: defaultGracePeriodRatio,\n",
"\t\t\tminGracePeriod: defaultMinGracePeriod,\n",
"\t\t\trootCert: []byte(\"Outdated root cert\"),\n",
"\t\t},\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tttl: time.Hour,\n",
"\t\t\tgracePeriodRatio: 0.5,\n",
"\t\t\tminGracePeriod: 10 * time.Minute,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 225
} | // Copyright 2017 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 controller
import (
"bytes"
"fmt"
"reflect"
"time"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/cache"
"istio.io/istio/pkg/log"
"istio.io/istio/security/pkg/pki/ca"
"istio.io/istio/security/pkg/pki/util"
)
/* #nosec: disable gas linter */
const (
// The Istio secret annotation type
IstioSecretType = "istio.io/key-and-cert"
// The ID/name for the certificate chain file.
CertChainID = "cert-chain.pem"
// The ID/name for the private key file.
PrivateKeyID = "key.pem"
// The ID/name for the CA root certificate file.
RootCertID = "root-cert.pem"
secretNamePrefix = "istio."
secretResyncPeriod = time.Minute
serviceAccountNameAnnotationKey = "istio.io/service-account.name"
recommendedMinGracePeriodRatio = 0.3
recommendedMaxGracePeriodRatio = 0.8
// The size of a private key for a leaf certificate.
keySize = 2048
)
// SecretController manages the service accounts' secrets that contains Istio keys and certificates.
type SecretController struct {
ca ca.CertificateAuthority
certTTL time.Duration
core corev1.CoreV1Interface
// Length of the grace period for the certificate rotation.
gracePeriodRatio float32
minGracePeriod time.Duration
// Controller and store for service account objects.
saController cache.Controller
saStore cache.Store
// Controller and store for secret objects.
scrtController cache.Controller
scrtStore cache.Store
}
// NewSecretController returns a pointer to a newly constructed SecretController instance.
func NewSecretController(ca ca.CertificateAuthority, certTTL time.Duration, gracePeriodRatio float32, minGracePeriod time.Duration,
core corev1.CoreV1Interface, namespace string) (*SecretController, error) {
if gracePeriodRatio < 0 || gracePeriodRatio > 1 {
return nil, fmt.Errorf("grace period ratio %f should be within [0, 1]", gracePeriodRatio)
}
if gracePeriodRatio < recommendedMinGracePeriodRatio || gracePeriodRatio > recommendedMaxGracePeriodRatio {
log.Warnf("grace period ratio %f is out of the recommended window [%.2f, %.2f]",
gracePeriodRatio, recommendedMinGracePeriodRatio, recommendedMaxGracePeriodRatio)
}
c := &SecretController{
ca: ca,
certTTL: certTTL,
gracePeriodRatio: gracePeriodRatio,
minGracePeriod: minGracePeriod,
core: core,
}
saLW := &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
return core.ServiceAccounts(namespace).List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
return core.ServiceAccounts(namespace).Watch(options)
},
}
rehf := cache.ResourceEventHandlerFuncs{
AddFunc: c.saAdded,
DeleteFunc: c.saDeleted,
UpdateFunc: c.saUpdated,
}
c.saStore, c.saController = cache.NewInformer(saLW, &v1.ServiceAccount{}, time.Minute, rehf)
istioSecretSelector := fields.SelectorFromSet(map[string]string{"type": IstioSecretType}).String()
scrtLW := &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
options.FieldSelector = istioSecretSelector
return core.Secrets(namespace).List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.FieldSelector = istioSecretSelector
return core.Secrets(namespace).Watch(options)
},
}
c.scrtStore, c.scrtController =
cache.NewInformer(scrtLW, &v1.Secret{}, secretResyncPeriod, cache.ResourceEventHandlerFuncs{
DeleteFunc: c.scrtDeleted,
UpdateFunc: c.scrtUpdated,
})
return c, nil
}
// Run starts the SecretController until a value is sent to stopCh.
func (sc *SecretController) Run(stopCh chan struct{}) {
go sc.scrtController.Run(stopCh)
go sc.saController.Run(stopCh)
}
// Handles the event where a service account is added.
func (sc *SecretController) saAdded(obj interface{}) {
acct := obj.(*v1.ServiceAccount)
sc.upsertSecret(acct.GetName(), acct.GetNamespace())
}
// Handles the event where a service account is deleted.
func (sc *SecretController) saDeleted(obj interface{}) {
acct := obj.(*v1.ServiceAccount)
sc.deleteSecret(acct.GetName(), acct.GetNamespace())
}
// Handles the event where a service account is updated.
func (sc *SecretController) saUpdated(oldObj, curObj interface{}) {
if reflect.DeepEqual(oldObj, curObj) {
// Nothing is changed. The method is invoked by periodical re-sync with the apiserver.
return
}
oldSa := oldObj.(*v1.ServiceAccount)
curSa := curObj.(*v1.ServiceAccount)
curName := curSa.GetName()
curNamespace := curSa.GetNamespace()
oldName := oldSa.GetName()
oldNamespace := oldSa.GetNamespace()
// We only care the name and namespace of a service account.
if curName != oldName || curNamespace != oldNamespace {
sc.deleteSecret(oldName, oldNamespace)
sc.upsertSecret(curName, curNamespace)
log.Infof("Service account \"%s\" in namespace \"%s\" has been updated to \"%s\" in namespace \"%s\"",
oldName, oldNamespace, curName, curNamespace)
}
}
func (sc *SecretController) upsertSecret(saName, saNamespace string) {
secret := &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{serviceAccountNameAnnotationKey: saName},
Name: getSecretName(saName),
Namespace: saNamespace,
},
Type: IstioSecretType,
}
_, exists, err := sc.scrtStore.Get(secret)
if err != nil {
log.Errorf("Failed to get secret from the store (error %v)", err)
}
if exists {
// Do nothing for existing secrets. Rotating expiring certs are handled by the `scrtUpdated` method.
return
}
// Now we know the secret does not exist yet. So we create a new one.
chain, key, err := sc.generateKeyAndCert(saName, saNamespace)
if err != nil {
log.Errorf("Failed to generate key and certificate for service account %q in namespace %q (error %v)",
saName, saNamespace, err)
return
}
rootCert := sc.ca.GetRootCertificate()
secret.Data = map[string][]byte{
CertChainID: chain,
PrivateKeyID: key,
RootCertID: rootCert,
}
_, err = sc.core.Secrets(saNamespace).Create(secret)
if err != nil {
log.Errorf("Failed to create secret (error: %s)", err)
return
}
log.Infof("Istio secret for service account \"%s\" in namespace \"%s\" has been created", saName, saNamespace)
}
func (sc *SecretController) deleteSecret(saName, saNamespace string) {
err := sc.core.Secrets(saNamespace).Delete(getSecretName(saName), nil)
// kube-apiserver returns NotFound error when the secret is successfully deleted.
if err == nil || errors.IsNotFound(err) {
log.Infof("Istio secret for service account \"%s\" in namespace \"%s\" has been deleted", saName, saNamespace)
return
}
log.Errorf("Failed to delete Istio secret for service account \"%s\" in namespace \"%s\" (error: %s)",
saName, saNamespace, err)
}
func (sc *SecretController) scrtDeleted(obj interface{}) {
scrt, ok := obj.(*v1.Secret)
if !ok {
log.Warnf("Failed to convert to secret object: %v", obj)
return
}
log.Infof("Re-create deleted Istio secret")
saName := scrt.Annotations[serviceAccountNameAnnotationKey]
sc.upsertSecret(saName, scrt.GetNamespace())
}
func (sc *SecretController) generateKeyAndCert(saName string, saNamespace string) ([]byte, []byte, error) {
id := fmt.Sprintf("%s://cluster.local/ns/%s/sa/%s", util.URIScheme, saNamespace, saName)
options := util.CertOptions{
Host: id,
RSAKeySize: keySize,
}
csrPEM, keyPEM, err := util.GenCSR(options)
if err != nil {
return nil, nil, err
}
certPEM, err := sc.ca.Sign(csrPEM, sc.certTTL, false)
if err != nil {
return nil, nil, err
}
return certPEM, keyPEM, nil
}
func (sc *SecretController) scrtUpdated(oldObj, newObj interface{}) {
scrt, ok := newObj.(*v1.Secret)
if !ok {
log.Warnf("Failed to convert to secret object: %v", newObj)
return
}
certBytes := scrt.Data[CertChainID]
cert, err := util.ParsePemEncodedCertificate(certBytes)
if err != nil {
// TODO: we should refresh secret in this case since the secret contains an
// invalid cert.
log.Errora(err)
return
}
certLifeTimeLeft := time.Until(cert.NotAfter)
certLifeTime := cert.NotAfter.Sub(cert.NotBefore)
// TODO(myidpt): we may introduce a minimum gracePeriod, without making the config too complex.
gracePeriod := time.Duration(sc.gracePeriodRatio) * certLifeTime
if gracePeriod < sc.minGracePeriod {
log.Warnf("gracePeriod (%v * %f) = %v is less than minGracePeriod %v. Apply minGracePeriod.",
certLifeTime, sc.gracePeriodRatio, sc.minGracePeriod)
gracePeriod = sc.minGracePeriod
}
rootCertificate := sc.ca.GetRootCertificate()
// Refresh the secret if 1) the certificate contained in the secret is about
// to expire, or 2) the root certificate in the secret is different than the
// one held by the ca (this may happen when the CA is restarted and
// a new self-signed CA cert is generated).
if certLifeTimeLeft < gracePeriod || !bytes.Equal(rootCertificate, scrt.Data[RootCertID]) {
namespace := scrt.GetNamespace()
name := scrt.GetName()
log.Infof("Refreshing secret %s/%s, either the leaf certificate is about to expire "+
"or the root certificate is outdated", namespace, name)
saName := scrt.Annotations[serviceAccountNameAnnotationKey]
chain, key, err := sc.generateKeyAndCert(saName, namespace)
if err != nil {
log.Errorf("Failed to generate key and certificate for service account %q in namespace %q (error %v)",
saName, namespace, err)
return
}
scrt.Data[CertChainID] = chain
scrt.Data[PrivateKeyID] = key
scrt.Data[RootCertID] = rootCertificate
if _, err = sc.core.Secrets(namespace).Update(scrt); err != nil {
log.Errorf("Failed to update secret %s/%s (error: %s)", namespace, name, err)
}
}
}
func getSecretName(saName string) string {
return secretNamePrefix + saName
}
| security/pkg/pki/ca/controller/secret.go | 1 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.01471173856407404,
0.0015658853808417916,
0.0001611786865396425,
0.0001729580108076334,
0.0029958488885313272
] |
{
"id": 8,
"code_window": [
"\t\t\"Update secret with different root cert\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n",
"\t\t\tttl: defaultTTL,\n",
"\t\t\tgracePeriodRatio: defaultGracePeriodRatio,\n",
"\t\t\tminGracePeriod: defaultMinGracePeriod,\n",
"\t\t\trootCert: []byte(\"Outdated root cert\"),\n",
"\t\t},\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tttl: time.Hour,\n",
"\t\t\tgracePeriodRatio: 0.5,\n",
"\t\t\tminGracePeriod: 10 * time.Minute,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 225
} | apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: zipkin-to-stackdriver
namespace: {ISTIO_NAMESPACE}
spec:
replicas: 1
selector:
matchLabels:
app: zipkin-to-stackdriver
template:
metadata:
name: zipkin-to-stackdriver
labels:
app: zipkin-to-stackdriver
annotations:
sidecar.istio.io/inject: "false"
spec:
containers:
- name: zipkin-to-stackdriver
image: gcr.io/stackdriver-trace-docker/zipkin-collector
imagePullPolicy: IfNotPresent
# env:
# - name: GOOGLE_APPLICATION_CREDENTIALS
# value: "/path/to/credentials.json"
# - name: PROJECT_ID
# value: "my_project_id"
ports:
- name: zipkin
containerPort: 9411
---
apiVersion: v1
kind: Service
metadata:
name: zipkin-to-stackdriver
spec:
ports:
- name: zipkin
port: 9411
selector:
app: zipkin-to-stackdriver
---
| install/kubernetes/templates/addons/zipkin-to-stackdriver.yaml.tmpl | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.00017520964320283383,
0.00017351839051116258,
0.00017226576164830476,
0.0001735113764880225,
9.770783435669728e-7
] |
{
"id": 8,
"code_window": [
"\t\t\"Update secret with different root cert\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n",
"\t\t\tttl: defaultTTL,\n",
"\t\t\tgracePeriodRatio: defaultGracePeriodRatio,\n",
"\t\t\tminGracePeriod: defaultMinGracePeriod,\n",
"\t\t\trootCert: []byte(\"Outdated root cert\"),\n",
"\t\t},\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tttl: time.Hour,\n",
"\t\t\tgracePeriodRatio: 0.5,\n",
"\t\t\tminGracePeriod: 10 * time.Minute,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 225
} | // Copyright 2017 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 store
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"testing"
"time"
"github.com/ghodss/yaml"
)
const testingCheckDuration = time.Millisecond * 5
func getTempFSStore2() (*fsStore, string) {
fsroot, _ := ioutil.TempDir("/tmp/", "fsStore-")
s := newFsStore(fsroot).(*fsStore)
s.checkDuration = testingCheckDuration
return s, fsroot
}
func cleanupRootIfOK(t *testing.T, fsroot string) {
if t.Failed() {
t.Errorf("Test failed. The data remains at %s", fsroot)
return
}
if err := os.RemoveAll(fsroot); err != nil {
t.Errorf("Failed on cleanup %s: %v", fsroot, err)
}
}
func waitFor(wch <-chan BackendEvent, ct ChangeType, key Key) {
for ev := range wch {
if ev.Key == key && ev.Type == ct {
return
}
}
}
func write(fsroot string, k Key, data map[string]interface{}) error {
path := filepath.Join(fsroot, k.Kind, k.Namespace, k.Name+".yaml")
bytes, err := yaml.Marshal(&BackEndResource{Kind: k.Kind, Metadata: ResourceMeta{Namespace: k.Namespace, Name: k.Name}, Spec: data})
if err != nil {
return err
}
if err = os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return err
}
return ioutil.WriteFile(path, bytes, 0644)
}
func TestFSStore2(t *testing.T) {
s, fsroot := getTempFSStore2()
defer cleanupRootIfOK(t, fsroot)
const ns = "istio-mixer-testing"
if err := s.Init([]string{"Handler", "Action"}); err != nil {
t.Fatal(err.Error())
}
defer s.Stop()
wch, err := s.Watch()
if err != nil {
t.Fatal(err.Error())
}
k := Key{Kind: "Handler", Namespace: ns, Name: "default"}
if _, err = s.Get(k); err != ErrNotFound {
t.Errorf("Got %v, Want ErrNotFound", err)
}
h := map[string]interface{}{"name": "default", "adapter": "noop"}
if err = write(fsroot, k, h); err != nil {
t.Fatalf("Got %v, Want nil", err)
}
waitFor(wch, Update, k)
h2, err := s.Get(k)
if err != nil {
t.Errorf("Got %v, Want nil", err)
}
if !reflect.DeepEqual(h, h2.Spec) {
t.Errorf("Got %+v, Want %+v", h2.Spec, h)
}
want := map[Key]*BackEndResource{k: h2}
if lst := s.List(); !reflect.DeepEqual(lst, want) {
t.Errorf("Got %+v, Want %+v", lst, want)
}
h["adapter"] = "noop2"
if err = write(fsroot, k, h); err != nil {
t.Fatalf("Got %v, Want nil", err)
}
waitFor(wch, Update, k)
if h2, err = s.Get(k); err != nil {
t.Errorf("Got %v, Want nil", err)
}
if !reflect.DeepEqual(h, h2.Spec) {
t.Errorf("Got %+v, Want %+v", h2.Spec, h)
}
if err = os.Remove(filepath.Join(fsroot, k.Kind, k.Namespace, k.Name+".yaml")); err != nil {
t.Errorf("Got %v, Want nil", err)
}
waitFor(wch, Delete, k)
if _, err := s.Get(k); err != ErrNotFound {
t.Errorf("Got %v, Want ErrNotFound", err)
}
}
func TestFSStore2WrongKind(t *testing.T) {
s, fsroot := getTempFSStore2()
defer cleanupRootIfOK(t, fsroot)
const ns = "istio-mixer-testing"
if err := s.Init([]string{"Action"}); err != nil {
t.Fatal(err.Error())
}
defer s.Stop()
k := Key{Kind: "Handler", Namespace: ns, Name: "default"}
h := map[string]interface{}{"name": "default", "adapter": "noop"}
if err := write(fsroot, k, h); err != nil {
t.Error("Got nil, Want error")
}
time.Sleep(testingCheckDuration)
if _, err := s.Get(k); err == nil {
t.Errorf("Got nil, Want error")
}
}
func TestFSStore2FileExtensions(t *testing.T) {
for _, ext := range []string{"yaml", "yml"} {
t.Run(ext, func(tt *testing.T) {
s, fsroot := getTempFSStore2()
defer cleanupRootIfOK(tt, fsroot)
err := ioutil.WriteFile(filepath.Join(fsroot, "foo."+ext), []byte(`
kind: Kind
apiVersion: testing
metadata:
namespace: ns
name: foo
spec:
`), 0644)
if err != nil {
tt.Fatal(err)
}
if err := s.Init([]string{"Kind"}); err != nil {
tt.Fatal(err.Error())
}
defer s.Stop()
if lst := s.List(); len(lst) != 1 {
tt.Errorf("Got %d elements, Want 1", len(lst))
}
})
}
}
func TestFSStore2FileFormat(t *testing.T) {
const good = `
kind: Foo
apiVersion: testing
metadata:
namespace: ns
name: foo
spec:
`
const bad = "abc"
for _, c := range []struct {
title string
resourceCount int
data string
}{
{
"base",
1,
good,
},
{
"illformed",
0,
bad,
},
{
"key missing",
0,
`
kind: Foo
apiVersion: testing
metadata:
name: foo
spec:
`,
},
{
"hyphened",
1,
"---\n" + good + "\n---",
},
{
"empty",
0,
"",
},
{
"hyphen",
0,
"---",
},
{
"multiple",
2,
good + "\n---\n" + good + "\n---\n",
},
{
"fail later",
1,
good + "\n---\n" + bad,
},
{
"fail former",
1,
bad + "\n---\n" + good,
},
{
"fail mulitiple",
0,
bad + "\n---\n" + bad,
},
{
"trailing white space",
1,
good + "\n---\n\n \n",
},
} {
t.Run(c.title, func(tt *testing.T) {
resources := parseFile(c.title, []byte(c.data))
if len(resources) != c.resourceCount {
tt.Errorf("Got %d, Want %d", len(resources), c.resourceCount)
}
})
}
}
func TestFsStore2_ParseChunk(t *testing.T) {
for _, c := range []struct {
title string
isNil bool
data string
}{
{
"whitespace only",
true,
" \n",
},
{
"whitespace with comments",
true,
" \n#This is a comments\n",
},
} {
t.Run(c.title, func(t *testing.T) {
r, err := ParseChunk([]byte(c.data))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if (r == nil) != c.isNil {
t.Fatalf("want Got %v, Want %t", r, c.isNil)
}
})
}
}
func TestFSStore2MissingRoot(t *testing.T) {
s, fsroot := getTempFSStore2()
if err := os.RemoveAll(fsroot); err != nil {
t.Fatal(err)
}
if err := s.Init([]string{"Kind"}); err != nil {
t.Errorf("Got %v, Want nil", err)
}
defer s.Stop()
if lst := s.List(); len(lst) != 0 {
t.Errorf("Got %+v, Want empty", lst)
}
}
func TestFSStore2Robust(t *testing.T) {
const ns = "testing"
const tmpl = `
kind: %s
apiVersion: config.istio.io/v1alpha2
metadata:
namespace: testing
name: %s
spec:
%s
`
for _, c := range []struct {
title string
prepare func(fsroot string) error
}{
{
"wrong permission",
func(fsroot string) error {
path := filepath.Join(fsroot, "aa.yaml")
return ioutil.WriteFile(path, []byte(fmt.Sprintf(tmpl, "Handler", "aa", "foo: bar\n")), 0300)
},
},
{
"illformed yaml",
func(fsroot string) error {
path := filepath.Join(fsroot, "Handler", ns, "bb.yaml")
return ioutil.WriteFile(path, []byte("abc"), 0644)
},
},
{
"directory",
func(fsroot string) error {
return os.MkdirAll(filepath.Join(fsroot, "Handler", ns, "cc.yaml"), 0755)
},
},
{
"unknown kind",
func(fsroot string) error {
k := Key{Kind: "Unknown", Namespace: ns, Name: "default"}
return write(fsroot, k, map[string]interface{}{"foo": "bar"})
},
},
} {
t.Run(c.title, func(tt *testing.T) {
s, fsroot := getTempFSStore2()
defer cleanupRootIfOK(tt, fsroot)
// Normal data
k := Key{Kind: "Handler", Namespace: ns, Name: "default"}
data := map[string]interface{}{"foo": "bar"}
if err := write(fsroot, k, data); err != nil {
tt.Fatalf("Failed to write: %v", err)
}
if err := c.prepare(fsroot); err != nil {
tt.Fatalf("Failed to prepare precondition: %v", err)
}
if err := s.Init([]string{"Handler"}); err != nil {
tt.Fatalf("Init failed: %v", err)
}
defer s.Stop()
want := map[Key]*BackEndResource{k: {Spec: data}}
got := s.List()
if len(got) != len(want) {
tt.Fatalf("data length does not match, want %d, got %d", len(got), len(want))
}
for k, v := range got {
vwant := want[k]
if vwant == nil {
tt.Fatalf("Did not get key for %s", k)
}
if !reflect.DeepEqual(v.Spec, vwant.Spec) {
tt.Fatalf("Got %+v, Want %+v", v, vwant)
}
}
})
}
}
| mixer/pkg/config/store/fsstore_test.go | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.003929014317691326,
0.00032425764948129654,
0.0001627073943382129,
0.00017191600636579096,
0.0006570033146999776
] |
{
"id": 8,
"code_window": [
"\t\t\"Update secret with different root cert\": {\n",
"\t\t\texpectedActions: []ktesting.Action{\n",
"\t\t\t\tktesting.NewUpdateAction(gvr, \"test-ns\", createSecret(\"test\", \"istio.test\", \"test-ns\")),\n",
"\t\t\t},\n",
"\t\t\tttl: defaultTTL,\n",
"\t\t\tgracePeriodRatio: defaultGracePeriodRatio,\n",
"\t\t\tminGracePeriod: defaultMinGracePeriod,\n",
"\t\t\trootCert: []byte(\"Outdated root cert\"),\n",
"\t\t},\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tttl: time.Hour,\n",
"\t\t\tgracePeriodRatio: 0.5,\n",
"\t\t\tminGracePeriod: 10 * time.Minute,\n"
],
"file_path": "security/pkg/pki/ca/controller/secret_test.go",
"type": "replace",
"edit_start_line_idx": 225
} | [
{
"op": "add",
"path": "/spec/initContainers",
"value": [
{
"name": "istio-init",
"image": "example.com/init:latest",
"resources": {},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"imagePullPolicy": "Always"
}
]
},
{
"op": "add",
"path": "/spec/containers/-",
"value": {
"name": "istio-proxy",
"image": "example.com/proxy:latest",
"resources": {},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"imagePullPolicy": "Always"
}
},
{
"op": "add",
"path": "/spec/volumes/-",
"value": {
"name": "istio-envoy",
"emptyDir": {
"medium": "Memory"
}
}
},
{
"op": "add",
"path": "/spec/volumes/-",
"value": {
"name": "istio-certs",
"secret": {
"secretName": "istio.default",
"defaultMode": 420
}
}
},
{
"op": "add",
"path": "/metadata/annotations",
"value": {
"sidecar.istio.io/status": "{\"version\":\"unit-test-fake-version\",\"initContainers\":[\"istio-init\"],\"containers\":[\"istio-proxy\"],\"volumes\":[\"istio-envoy\",\"istio-certs\"]}"
}
}
] | pilot/pkg/kube/inject/testdata/TestWebhookInject_no_initContainers.patch | 0 | https://github.com/istio/istio/commit/ea84b3940f971b8ef607274189c4902e18f2e719 | [
0.00017329510592389852,
0.00016838288865983486,
0.00016441418847534806,
0.0001677309483056888,
0.0000027605910872807726
] |
{
"id": 2,
"code_window": [
"\tif err = mkdirAll(parentFilePath, 0o777); err != nil {\n",
"\t\treturn osErrToFileErr(err)\n",
"\t}\n",
"\n",
"\todirectEnabled := s.oDirect\n",
"\tvar w *os.File\n",
"\tif odirectEnabled {\n",
"\t\tw, err = OpenFileDirectIO(filePath, flags, 0o666)\n",
"\t} else {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\todirectEnabled := !globalAPIConfig.isDisableODirect() && s.oDirect\n",
"\n"
],
"file_path": "cmd/xl-storage.go",
"type": "replace",
"edit_start_line_idx": 1898
} | // Copyright (c) 2015-2023 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package api
import "github.com/minio/minio/internal/config"
// Help template for storageclass feature.
var (
defaultHelpPostfix = func(key string) string {
return config.DefaultHelpPostfix(DefaultKVS, key)
}
Help = config.HelpKVS{
config.HelpKV{
Key: apiRequestsMax,
Description: `set the maximum number of concurrent requests` + defaultHelpPostfix(apiRequestsMax),
Optional: true,
Type: "number",
},
config.HelpKV{
Key: apiRequestsDeadline,
Description: `set the deadline for API requests waiting to be processed` + defaultHelpPostfix(apiRequestsDeadline),
Optional: true,
Type: "duration",
},
config.HelpKV{
Key: apiClusterDeadline,
Description: `set the deadline for cluster readiness check` + defaultHelpPostfix(apiClusterDeadline),
Optional: true,
Type: "duration",
},
config.HelpKV{
Key: apiCorsAllowOrigin,
Description: `set comma separated list of origins allowed for CORS requests` + defaultHelpPostfix(apiCorsAllowOrigin),
Optional: true,
Type: "csv",
},
config.HelpKV{
Key: apiRemoteTransportDeadline,
Description: `set the deadline for API requests on remote transports while proxying between federated instances e.g. "2h"` + defaultHelpPostfix(apiRemoteTransportDeadline),
Optional: true,
Type: "duration",
},
config.HelpKV{
Key: apiListQuorum,
Description: `set the acceptable quorum expected for list operations e.g. "optimal", "reduced", "disk", "strict"` + defaultHelpPostfix(apiListQuorum),
Optional: true,
Type: "string",
},
config.HelpKV{
Key: apiReplicationPriority,
Description: `set replication priority` + defaultHelpPostfix(apiReplicationPriority),
Optional: true,
Type: "string",
},
config.HelpKV{
Key: apiTransitionWorkers,
Description: `set the number of transition workers` + defaultHelpPostfix(apiTransitionWorkers),
Optional: true,
Type: "number",
},
config.HelpKV{
Key: apiStaleUploadsExpiry,
Description: `set to expire stale multipart uploads older than this values` + defaultHelpPostfix(apiStaleUploadsExpiry),
Optional: true,
Type: "duration",
},
config.HelpKV{
Key: apiStaleUploadsCleanupInterval,
Description: `set to change intervals when stale multipart uploads are expired` + defaultHelpPostfix(apiStaleUploadsCleanupInterval),
Optional: true,
Type: "duration",
},
config.HelpKV{
Key: apiDeleteCleanupInterval,
Description: `set to change intervals when deleted objects are permanently deleted from ".trash" folder` + defaultHelpPostfix(apiDeleteCleanupInterval),
Optional: true,
Type: "duration",
},
config.HelpKV{
Key: apiDisableODirect,
Description: "set to disable O_DIRECT for reads under special conditions. NOTE: it is not recommended to disable O_DIRECT without prior testing" + defaultHelpPostfix(apiDisableODirect),
Optional: true,
Type: "boolean",
},
config.HelpKV{
Key: apiRootAccess,
Description: "turn 'off' root credential access for all API calls including s3, admin operations" + defaultHelpPostfix(apiRootAccess),
Optional: true,
Type: "boolean",
},
config.HelpKV{
Key: apiSyncEvents,
Description: "set to enable synchronous bucket notifications" + defaultHelpPostfix(apiSyncEvents),
Optional: true,
Type: "boolean",
},
}
)
| internal/config/api/help.go | 1 | https://github.com/minio/minio/commit/f13cfcb83e931ed6cabdabee588bbaf308e7952b | [
0.00020234502153471112,
0.00017669778026174754,
0.00016963575035333633,
0.00017499364912509918,
0.000008077591701294295
] |
{
"id": 2,
"code_window": [
"\tif err = mkdirAll(parentFilePath, 0o777); err != nil {\n",
"\t\treturn osErrToFileErr(err)\n",
"\t}\n",
"\n",
"\todirectEnabled := s.oDirect\n",
"\tvar w *os.File\n",
"\tif odirectEnabled {\n",
"\t\tw, err = OpenFileDirectIO(filePath, flags, 0o666)\n",
"\t} else {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\todirectEnabled := !globalAPIConfig.isDisableODirect() && s.oDirect\n",
"\n"
],
"file_path": "cmd/xl-storage.go",
"type": "replace",
"edit_start_line_idx": 1898
} | package replication
// Code generated by github.com/tinylib/msgp DO NOT EDIT.
| internal/bucket/replication/datatypes_gen_test.go | 0 | https://github.com/minio/minio/commit/f13cfcb83e931ed6cabdabee588bbaf308e7952b | [
0.000174131739186123,
0.000174131739186123,
0.000174131739186123,
0.000174131739186123,
0
] |
{
"id": 2,
"code_window": [
"\tif err = mkdirAll(parentFilePath, 0o777); err != nil {\n",
"\t\treturn osErrToFileErr(err)\n",
"\t}\n",
"\n",
"\todirectEnabled := s.oDirect\n",
"\tvar w *os.File\n",
"\tif odirectEnabled {\n",
"\t\tw, err = OpenFileDirectIO(filePath, flags, 0o666)\n",
"\t} else {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\todirectEnabled := !globalAPIConfig.isDisableODirect() && s.oDirect\n",
"\n"
],
"file_path": "cmd/xl-storage.go",
"type": "replace",
"edit_start_line_idx": 1898
} | // Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"bytes"
"context"
"crypto/rand"
"encoding/binary"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"path"
"time"
"github.com/minio/madmin-go/v3"
"github.com/minio/minio-go/v7/pkg/tags"
bucketsse "github.com/minio/minio/internal/bucket/encryption"
"github.com/minio/minio/internal/bucket/lifecycle"
objectlock "github.com/minio/minio/internal/bucket/object/lock"
"github.com/minio/minio/internal/bucket/replication"
"github.com/minio/minio/internal/bucket/versioning"
"github.com/minio/minio/internal/crypto"
"github.com/minio/minio/internal/event"
"github.com/minio/minio/internal/fips"
"github.com/minio/minio/internal/kms"
"github.com/minio/minio/internal/logger"
"github.com/minio/pkg/bucket/policy"
"github.com/minio/sio"
)
const (
legacyBucketObjectLockEnabledConfigFile = "object-lock-enabled.json"
legacyBucketObjectLockEnabledConfig = `{"x-amz-bucket-object-lock-enabled":true}`
bucketMetadataFile = ".metadata.bin"
bucketMetadataFormat = 1
bucketMetadataVersion = 1
)
var (
enabledBucketObjectLockConfig = []byte(`<ObjectLockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><ObjectLockEnabled>Enabled</ObjectLockEnabled></ObjectLockConfiguration>`)
enabledBucketVersioningConfig = []byte(`<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Status>Enabled</Status></VersioningConfiguration>`)
)
//go:generate msgp -file $GOFILE
// BucketMetadata contains bucket metadata.
// When adding/removing fields, regenerate the marshal code using the go generate above.
// Only changing meaning of fields requires a version bump.
// bucketMetadataFormat refers to the format.
// bucketMetadataVersion can be used to track a rolling upgrade of a field.
type BucketMetadata struct {
Name string
Created time.Time
LockEnabled bool // legacy not used anymore.
PolicyConfigJSON []byte
NotificationConfigXML []byte
LifecycleConfigXML []byte
ObjectLockConfigXML []byte
VersioningConfigXML []byte
EncryptionConfigXML []byte
TaggingConfigXML []byte
QuotaConfigJSON []byte
ReplicationConfigXML []byte
BucketTargetsConfigJSON []byte
BucketTargetsConfigMetaJSON []byte
PolicyConfigUpdatedAt time.Time
ObjectLockConfigUpdatedAt time.Time
EncryptionConfigUpdatedAt time.Time
TaggingConfigUpdatedAt time.Time
QuotaConfigUpdatedAt time.Time
ReplicationConfigUpdatedAt time.Time
VersioningConfigUpdatedAt time.Time
LifecycleConfigUpdatedAt time.Time
// Unexported fields. Must be updated atomically.
policyConfig *policy.Policy
notificationConfig *event.Config
lifecycleConfig *lifecycle.Lifecycle
objectLockConfig *objectlock.Config
versioningConfig *versioning.Versioning
sseConfig *bucketsse.BucketSSEConfig
taggingConfig *tags.Tags
quotaConfig *madmin.BucketQuota
replicationConfig *replication.Config
bucketTargetConfig *madmin.BucketTargets
bucketTargetConfigMeta map[string]string
}
// newBucketMetadata creates BucketMetadata with the supplied name and Created to Now.
func newBucketMetadata(name string) BucketMetadata {
return BucketMetadata{
Name: name,
notificationConfig: &event.Config{
XMLNS: "http://s3.amazonaws.com/doc/2006-03-01/",
},
quotaConfig: &madmin.BucketQuota{},
versioningConfig: &versioning.Versioning{
XMLNS: "http://s3.amazonaws.com/doc/2006-03-01/",
},
bucketTargetConfig: &madmin.BucketTargets{},
bucketTargetConfigMeta: make(map[string]string),
}
}
// Versioning returns true if versioning is enabled
func (b BucketMetadata) Versioning() bool {
return b.LockEnabled || (b.versioningConfig != nil && b.versioningConfig.Enabled()) || (b.objectLockConfig != nil && b.objectLockConfig.Enabled())
}
// ObjectLocking returns true if object locking is enabled
func (b BucketMetadata) ObjectLocking() bool {
return b.LockEnabled || (b.objectLockConfig != nil && b.objectLockConfig.Enabled())
}
// SetCreatedAt preserves the CreatedAt time for bucket across sites in site replication. It defaults to
// creation time of bucket on this cluster in all other cases.
func (b *BucketMetadata) SetCreatedAt(createdAt time.Time) {
if b.Created.IsZero() {
b.Created = UTCNow()
}
if !createdAt.IsZero() {
b.Created = createdAt.UTC()
}
}
// Load - loads the metadata of bucket by name from ObjectLayer api.
// If an error is returned the returned metadata will be default initialized.
func (b *BucketMetadata) Load(ctx context.Context, api ObjectLayer, name string) error {
if name == "" {
logger.LogIf(ctx, errors.New("bucket name cannot be empty"))
return errInvalidArgument
}
configFile := path.Join(bucketMetaPrefix, name, bucketMetadataFile)
data, err := readConfig(ctx, api, configFile)
if err != nil {
return err
}
if len(data) <= 4 {
return fmt.Errorf("loadBucketMetadata: no data")
}
// Read header
switch binary.LittleEndian.Uint16(data[0:2]) {
case bucketMetadataFormat:
default:
return fmt.Errorf("loadBucketMetadata: unknown format: %d", binary.LittleEndian.Uint16(data[0:2]))
}
switch binary.LittleEndian.Uint16(data[2:4]) {
case bucketMetadataVersion:
default:
return fmt.Errorf("loadBucketMetadata: unknown version: %d", binary.LittleEndian.Uint16(data[2:4]))
}
// OK, parse data.
_, err = b.UnmarshalMsg(data[4:])
b.Name = name // in-case parsing failed for some reason, make sure bucket name is not empty.
return err
}
func loadBucketMetadataParse(ctx context.Context, objectAPI ObjectLayer, bucket string, parse bool) (BucketMetadata, error) {
b := newBucketMetadata(bucket)
err := b.Load(ctx, objectAPI, b.Name)
if err != nil && !errors.Is(err, errConfigNotFound) {
return b, err
}
if err == nil {
b.defaultTimestamps()
}
configs, err := b.getAllLegacyConfigs(ctx, objectAPI)
if err != nil {
return b, err
}
if len(configs) == 0 {
if parse {
// nothing to update, parse and proceed.
err = b.parseAllConfigs(ctx, objectAPI)
}
} else {
// Old bucket without bucket metadata. Hence we migrate existing settings.
err = b.convertLegacyConfigs(ctx, objectAPI, configs)
}
if err != nil {
return b, err
}
// migrate unencrypted remote targets
if err := b.migrateTargetConfig(ctx, objectAPI); err != nil {
return b, err
}
return b, nil
}
// loadBucketMetadata loads and migrates to bucket metadata.
func loadBucketMetadata(ctx context.Context, objectAPI ObjectLayer, bucket string) (BucketMetadata, error) {
return loadBucketMetadataParse(ctx, objectAPI, bucket, true)
}
// parseAllConfigs will parse all configs and populate the private fields.
// The first error encountered is returned.
func (b *BucketMetadata) parseAllConfigs(ctx context.Context, objectAPI ObjectLayer) (err error) {
if len(b.PolicyConfigJSON) != 0 {
b.policyConfig, err = policy.ParseConfig(bytes.NewReader(b.PolicyConfigJSON), b.Name)
if err != nil {
return err
}
} else {
b.policyConfig = nil
}
if len(b.NotificationConfigXML) != 0 {
if err = xml.Unmarshal(b.NotificationConfigXML, b.notificationConfig); err != nil {
return err
}
}
if len(b.LifecycleConfigXML) != 0 {
b.lifecycleConfig, err = lifecycle.ParseLifecycleConfig(bytes.NewReader(b.LifecycleConfigXML))
if err != nil {
return err
}
} else {
b.lifecycleConfig = nil
}
if len(b.EncryptionConfigXML) != 0 {
b.sseConfig, err = bucketsse.ParseBucketSSEConfig(bytes.NewReader(b.EncryptionConfigXML))
if err != nil {
return err
}
} else {
b.sseConfig = nil
}
if len(b.TaggingConfigXML) != 0 {
b.taggingConfig, err = tags.ParseBucketXML(bytes.NewReader(b.TaggingConfigXML))
if err != nil {
return err
}
} else {
b.taggingConfig = nil
}
if bytes.Equal(b.ObjectLockConfigXML, enabledBucketObjectLockConfig) {
b.VersioningConfigXML = enabledBucketVersioningConfig
}
if len(b.ObjectLockConfigXML) != 0 {
b.objectLockConfig, err = objectlock.ParseObjectLockConfig(bytes.NewReader(b.ObjectLockConfigXML))
if err != nil {
return err
}
} else {
b.objectLockConfig = nil
}
if len(b.VersioningConfigXML) != 0 {
b.versioningConfig, err = versioning.ParseConfig(bytes.NewReader(b.VersioningConfigXML))
if err != nil {
return err
}
}
if len(b.QuotaConfigJSON) != 0 {
b.quotaConfig, err = parseBucketQuota(b.Name, b.QuotaConfigJSON)
if err != nil {
return err
}
}
if len(b.ReplicationConfigXML) != 0 {
b.replicationConfig, err = replication.ParseConfig(bytes.NewReader(b.ReplicationConfigXML))
if err != nil {
return err
}
} else {
b.replicationConfig = nil
}
if len(b.BucketTargetsConfigJSON) != 0 {
b.bucketTargetConfig, err = parseBucketTargetConfig(b.Name, b.BucketTargetsConfigJSON, b.BucketTargetsConfigMetaJSON)
if err != nil {
return err
}
} else {
b.bucketTargetConfig = &madmin.BucketTargets{}
}
return nil
}
func (b *BucketMetadata) getAllLegacyConfigs(ctx context.Context, objectAPI ObjectLayer) (map[string][]byte, error) {
legacyConfigs := []string{
legacyBucketObjectLockEnabledConfigFile,
bucketPolicyConfig,
bucketNotificationConfig,
bucketLifecycleConfig,
bucketQuotaConfigFile,
bucketSSEConfig,
bucketTaggingConfig,
bucketReplicationConfig,
bucketTargetsFile,
objectLockConfig,
}
configs := make(map[string][]byte, len(legacyConfigs))
// Handle migration from lockEnabled to newer format.
if b.LockEnabled {
configs[objectLockConfig] = enabledBucketObjectLockConfig
b.LockEnabled = false // legacy value unset it
// we are only interested in b.ObjectLockConfigXML or objectLockConfig value
}
for _, legacyFile := range legacyConfigs {
configFile := path.Join(bucketMetaPrefix, b.Name, legacyFile)
configData, err := readConfig(ctx, objectAPI, configFile)
if err != nil {
if _, ok := err.(ObjectExistsAsDirectory); ok {
// in FS mode it possible that we have actual
// files in this folder with `.minio.sys/buckets/bucket/configFile`
continue
}
if errors.Is(err, errConfigNotFound) {
// legacy file config not found, proceed to look for new metadata.
continue
}
return nil, err
}
configs[legacyFile] = configData
}
return configs, nil
}
func (b *BucketMetadata) convertLegacyConfigs(ctx context.Context, objectAPI ObjectLayer, configs map[string][]byte) error {
for legacyFile, configData := range configs {
switch legacyFile {
case legacyBucketObjectLockEnabledConfigFile:
if string(configData) == legacyBucketObjectLockEnabledConfig {
b.ObjectLockConfigXML = enabledBucketObjectLockConfig
b.VersioningConfigXML = enabledBucketVersioningConfig
b.LockEnabled = false // legacy value unset it
// we are only interested in b.ObjectLockConfigXML
}
case bucketPolicyConfig:
b.PolicyConfigJSON = configData
case bucketNotificationConfig:
b.NotificationConfigXML = configData
case bucketLifecycleConfig:
b.LifecycleConfigXML = configData
case bucketSSEConfig:
b.EncryptionConfigXML = configData
case bucketTaggingConfig:
b.TaggingConfigXML = configData
case objectLockConfig:
b.ObjectLockConfigXML = configData
b.VersioningConfigXML = enabledBucketVersioningConfig
case bucketQuotaConfigFile:
b.QuotaConfigJSON = configData
case bucketReplicationConfig:
b.ReplicationConfigXML = configData
case bucketTargetsFile:
b.BucketTargetsConfigJSON = configData
}
}
b.defaultTimestamps()
if err := b.Save(ctx, objectAPI); err != nil {
return err
}
for legacyFile := range configs {
configFile := path.Join(bucketMetaPrefix, b.Name, legacyFile)
if err := deleteConfig(ctx, objectAPI, configFile); err != nil && !errors.Is(err, errConfigNotFound) {
logger.LogIf(ctx, err)
}
}
return nil
}
// default timestamps to metadata Created timestamp if unset.
func (b *BucketMetadata) defaultTimestamps() {
if b.PolicyConfigUpdatedAt.IsZero() {
b.PolicyConfigUpdatedAt = b.Created
}
if b.EncryptionConfigUpdatedAt.IsZero() {
b.EncryptionConfigUpdatedAt = b.Created
}
if b.TaggingConfigUpdatedAt.IsZero() {
b.TaggingConfigUpdatedAt = b.Created
}
if b.ObjectLockConfigUpdatedAt.IsZero() {
b.ObjectLockConfigUpdatedAt = b.Created
}
if b.QuotaConfigUpdatedAt.IsZero() {
b.QuotaConfigUpdatedAt = b.Created
}
if b.ReplicationConfigUpdatedAt.IsZero() {
b.ReplicationConfigUpdatedAt = b.Created
}
if b.VersioningConfigUpdatedAt.IsZero() {
b.VersioningConfigUpdatedAt = b.Created
}
if b.LifecycleConfigUpdatedAt.IsZero() {
b.LifecycleConfigUpdatedAt = b.Created
}
}
// Save config to supplied ObjectLayer api.
func (b *BucketMetadata) Save(ctx context.Context, api ObjectLayer) error {
if err := b.parseAllConfigs(ctx, api); err != nil {
return err
}
data := make([]byte, 4, b.Msgsize()+4)
// Initialize the header.
binary.LittleEndian.PutUint16(data[0:2], bucketMetadataFormat)
binary.LittleEndian.PutUint16(data[2:4], bucketMetadataVersion)
// Marshal the bucket metadata
data, err := b.MarshalMsg(data)
if err != nil {
return err
}
configFile := path.Join(bucketMetaPrefix, b.Name, bucketMetadataFile)
return saveConfig(ctx, api, configFile, data)
}
// migrate config for remote targets by encrypting data if currently unencrypted and kms is configured.
func (b *BucketMetadata) migrateTargetConfig(ctx context.Context, objectAPI ObjectLayer) error {
var err error
// early return if no targets or already encrypted
if len(b.BucketTargetsConfigJSON) == 0 || GlobalKMS == nil || len(b.BucketTargetsConfigMetaJSON) != 0 {
return nil
}
encBytes, metaBytes, err := encryptBucketMetadata(ctx, b.Name, b.BucketTargetsConfigJSON, kms.Context{b.Name: b.Name, bucketTargetsFile: bucketTargetsFile})
if err != nil {
return err
}
b.BucketTargetsConfigJSON = encBytes
b.BucketTargetsConfigMetaJSON = metaBytes
return b.Save(ctx, objectAPI)
}
// encrypt bucket metadata if kms is configured.
func encryptBucketMetadata(ctx context.Context, bucket string, input []byte, kmsContext kms.Context) (output, metabytes []byte, err error) {
if GlobalKMS == nil {
output = input
return
}
metadata := make(map[string]string)
key, err := GlobalKMS.GenerateKey(ctx, "", kmsContext)
if err != nil {
return
}
outbuf := bytes.NewBuffer(nil)
objectKey := crypto.GenerateKey(key.Plaintext, rand.Reader)
sealedKey := objectKey.Seal(key.Plaintext, crypto.GenerateIV(rand.Reader), crypto.S3.String(), bucket, "")
crypto.S3.CreateMetadata(metadata, key.KeyID, key.Ciphertext, sealedKey)
_, err = sio.Encrypt(outbuf, bytes.NewBuffer(input), sio.Config{Key: objectKey[:], MinVersion: sio.Version20, CipherSuites: fips.DARECiphers()})
if err != nil {
return output, metabytes, err
}
metabytes, err = json.Marshal(metadata)
if err != nil {
return
}
return outbuf.Bytes(), metabytes, nil
}
// decrypt bucket metadata if kms is configured.
func decryptBucketMetadata(input []byte, bucket string, meta map[string]string, kmsContext kms.Context) ([]byte, error) {
if GlobalKMS == nil {
return nil, errKMSNotConfigured
}
keyID, kmsKey, sealedKey, err := crypto.S3.ParseMetadata(meta)
if err != nil {
return nil, err
}
extKey, err := GlobalKMS.DecryptKey(keyID, kmsKey, kmsContext)
if err != nil {
return nil, err
}
var objectKey crypto.ObjectKey
if err = objectKey.Unseal(extKey, sealedKey, crypto.S3.String(), bucket, ""); err != nil {
return nil, err
}
outbuf := bytes.NewBuffer(nil)
_, err = sio.Decrypt(outbuf, bytes.NewBuffer(input), sio.Config{Key: objectKey[:], MinVersion: sio.Version20, CipherSuites: fips.DARECiphers()})
return outbuf.Bytes(), err
}
| cmd/bucket-metadata.go | 0 | https://github.com/minio/minio/commit/f13cfcb83e931ed6cabdabee588bbaf308e7952b | [
0.0019887108355760574,
0.0002501234703231603,
0.0001620371622266248,
0.00017213243700098246,
0.0003176843165419996
] |
{
"id": 2,
"code_window": [
"\tif err = mkdirAll(parentFilePath, 0o777); err != nil {\n",
"\t\treturn osErrToFileErr(err)\n",
"\t}\n",
"\n",
"\todirectEnabled := s.oDirect\n",
"\tvar w *os.File\n",
"\tif odirectEnabled {\n",
"\t\tw, err = OpenFileDirectIO(filePath, flags, 0o666)\n",
"\t} else {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\todirectEnabled := !globalAPIConfig.isDisableODirect() && s.oDirect\n",
"\n"
],
"file_path": "cmd/xl-storage.go",
"type": "replace",
"edit_start_line_idx": 1898
} | // Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"sort"
"strings"
"github.com/minio/minio/internal/auth"
"github.com/minio/minio/internal/crypto"
xhttp "github.com/minio/minio/internal/http"
xioutil "github.com/minio/minio/internal/ioutil"
"github.com/minio/minio/internal/logger"
"github.com/minio/pkg/bucket/policy"
xnet "github.com/minio/pkg/net"
"github.com/minio/zipindex"
)
const (
archiveType = "zip"
archiveTypeEnc = "zip-enc"
archiveExt = "." + archiveType // ".zip"
archiveSeparator = "/"
archivePattern = archiveExt + archiveSeparator // ".zip/"
archiveTypeMetadataKey = ReservedMetadataPrefixLower + "archive-type" // "x-minio-internal-archive-type"
archiveInfoMetadataKey = ReservedMetadataPrefixLower + "archive-info" // "x-minio-internal-archive-info"
// Peek into a zip archive
xMinIOExtract = "x-minio-extract"
)
// splitZipExtensionPath splits the S3 path to the zip file and the path inside the zip:
//
// e.g /path/to/archive.zip/backup-2021/myimage.png => /path/to/archive.zip, backup/myimage.png
func splitZipExtensionPath(input string) (zipPath, object string, err error) {
idx := strings.Index(input, archivePattern)
if idx < 0 {
// Should never happen
return "", "", errors.New("unable to parse zip path")
}
return input[:idx+len(archivePattern)-1], input[idx+len(archivePattern):], nil
}
// getObjectInArchiveFileHandler - GET Object in the archive file
func (api objectAPIHandlers) getObjectInArchiveFileHandler(ctx context.Context, objectAPI ObjectLayer, bucket, object string, w http.ResponseWriter, r *http.Request) {
if crypto.S3.IsRequested(r.Header) || crypto.S3KMS.IsRequested(r.Header) { // If SSE-S3 or SSE-KMS present -> AWS fails with undefined error
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrBadRequest), r.URL)
return
}
zipPath, object, err := splitZipExtensionPath(object)
if err != nil {
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
return
}
opts, err := getOpts(ctx, r, bucket, zipPath)
if err != nil {
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
return
}
getObjectInfo := objectAPI.GetObjectInfo
if api.CacheAPI() != nil {
getObjectInfo = api.CacheAPI().GetObjectInfo
}
// Check for auth type to return S3 compatible error.
// type to return the correct error (NoSuchKey vs AccessDenied)
if s3Error := checkRequestAuthType(ctx, r, policy.GetObjectAction, bucket, zipPath); s3Error != ErrNone {
if getRequestAuthType(r) == authTypeAnonymous {
// As per "Permission" section in
// https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html
// If the object you request does not exist,
// the error Amazon S3 returns depends on
// whether you also have the s3:ListBucket
// permission.
// * If you have the s3:ListBucket permission
// on the bucket, Amazon S3 will return an
// HTTP status code 404 ("no such key")
// error.
// * if you don’t have the s3:ListBucket
// permission, Amazon S3 will return an HTTP
// status code 403 ("access denied") error.`
if globalPolicySys.IsAllowed(policy.Args{
Action: policy.ListBucketAction,
BucketName: bucket,
ConditionValues: getConditionValues(r, "", auth.AnonymousCredentials),
IsOwner: false,
}) {
_, err = getObjectInfo(ctx, bucket, zipPath, opts)
if toAPIError(ctx, err).Code == "NoSuchKey" {
s3Error = ErrNoSuchKey
}
}
}
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Error), r.URL)
return
}
// We do not allow offsetting into extracted files.
if opts.PartNumber != 0 {
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrInvalidPartNumber), r.URL)
return
}
if r.Header.Get(xhttp.Range) != "" {
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrInvalidRange), r.URL)
return
}
// Validate pre-conditions if any.
opts.CheckPrecondFn = func(oi ObjectInfo) bool {
if _, err := DecryptObjectInfo(&oi, r); err != nil {
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
return true
}
return checkPreconditions(ctx, w, r, oi, opts)
}
zipObjInfo, err := getObjectInfo(ctx, bucket, zipPath, opts)
if err != nil {
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
return
}
zipInfo := zipObjInfo.ArchiveInfo()
if len(zipInfo) == 0 {
opts.EncryptFn, err = zipObjInfo.metadataEncryptFn(r.Header)
if err != nil {
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
return
}
zipInfo, err = updateObjectMetadataWithZipInfo(ctx, objectAPI, bucket, zipPath, opts)
}
if err != nil {
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
return
}
file, err := zipindex.FindSerialized(zipInfo, object)
if err != nil {
if err == io.EOF {
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrNoSuchKey), r.URL)
} else {
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
}
return
}
// New object info
fileObjInfo := ObjectInfo{
Bucket: bucket,
Name: object,
Size: int64(file.UncompressedSize64),
ModTime: zipObjInfo.ModTime,
}
var rc io.ReadCloser
if file.UncompressedSize64 > 0 {
// There may be number of header bytes before the content.
// Reading 64K extra. This should more than cover name and any "extra" details.
end := file.Offset + int64(file.CompressedSize64) + 64<<10
if end > zipObjInfo.Size {
end = zipObjInfo.Size
}
rs := &HTTPRangeSpec{Start: file.Offset, End: end}
gr, err := objectAPI.GetObjectNInfo(ctx, bucket, zipPath, rs, nil, opts)
if err != nil {
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
return
}
defer gr.Close()
rc, err = file.Open(gr)
if err != nil {
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
return
}
} else {
rc = io.NopCloser(bytes.NewReader([]byte{}))
}
defer rc.Close()
if err = setObjectHeaders(w, fileObjInfo, nil, opts); err != nil {
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
return
}
// s3zip does not allow ranges
w.Header().Del(xhttp.AcceptRanges)
setHeadGetRespHeaders(w, r.Form)
httpWriter := xioutil.WriteOnClose(w)
// Write object content to response body
if _, err = xioutil.Copy(httpWriter, rc); err != nil {
if !httpWriter.HasWritten() {
// write error response only if no data or headers has been written to client yet
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
return
}
if !xnet.IsNetworkOrHostDown(err, true) { // do not need to log disconnected clients
logger.LogIf(ctx, fmt.Errorf("Unable to write all the data to client: %w", err))
}
return
}
if err = httpWriter.Close(); err != nil {
if !httpWriter.HasWritten() { // write error response only if no data or headers has been written to client yet
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
return
}
if !xnet.IsNetworkOrHostDown(err, true) { // do not need to log disconnected clients
logger.LogIf(ctx, fmt.Errorf("Unable to write all the data to client: %w", err))
}
return
}
}
// listObjectsV2InArchive generates S3 listing result ListObjectsV2Info from zip file, all parameters are already validated by the caller.
func listObjectsV2InArchive(ctx context.Context, objectAPI ObjectLayer, bucket, prefix, token, delimiter string, maxKeys int, fetchOwner bool, startAfter string) (ListObjectsV2Info, error) {
zipPath, _, err := splitZipExtensionPath(prefix)
if err != nil {
// Return empty listing
return ListObjectsV2Info{}, nil
}
zipObjInfo, err := objectAPI.GetObjectInfo(ctx, bucket, zipPath, ObjectOptions{})
if err != nil {
// Return empty listing
return ListObjectsV2Info{}, nil
}
zipInfo := zipObjInfo.ArchiveInfo()
if len(zipInfo) == 0 {
// Always update the latest version
zipInfo, err = updateObjectMetadataWithZipInfo(ctx, objectAPI, bucket, zipPath, ObjectOptions{})
}
if err != nil {
return ListObjectsV2Info{}, err
}
files, err := zipindex.DeserializeFiles(zipInfo)
if err != nil {
return ListObjectsV2Info{}, err
}
sort.Slice(files, func(i, j int) bool {
return files[i].Name < files[j].Name
})
var (
count int
isTruncated bool
nextToken string
listObjectsInfo ListObjectsV2Info
)
// Always set this
listObjectsInfo.ContinuationToken = token
// Open and iterate through the files in the archive.
for _, file := range files {
objName := zipObjInfo.Name + archiveSeparator + file.Name
if objName <= startAfter || objName <= token {
continue
}
if strings.HasPrefix(objName, prefix) {
if count == maxKeys {
isTruncated = true
break
}
if delimiter != "" {
i := strings.Index(objName[len(prefix):], delimiter)
if i >= 0 {
commonPrefix := objName[:len(prefix)+i+1]
if len(listObjectsInfo.Prefixes) == 0 || commonPrefix != listObjectsInfo.Prefixes[len(listObjectsInfo.Prefixes)-1] {
listObjectsInfo.Prefixes = append(listObjectsInfo.Prefixes, commonPrefix)
count++
}
goto next
}
}
listObjectsInfo.Objects = append(listObjectsInfo.Objects, ObjectInfo{
Bucket: bucket,
Name: objName,
Size: int64(file.UncompressedSize64),
ModTime: zipObjInfo.ModTime,
})
count++
}
next:
nextToken = objName
}
if isTruncated {
listObjectsInfo.IsTruncated = true
listObjectsInfo.NextContinuationToken = nextToken
}
return listObjectsInfo, nil
}
// getFilesFromZIPObject reads a partial stream of a zip file to build the zipindex.Files index
func getFilesListFromZIPObject(ctx context.Context, objectAPI ObjectLayer, bucket, object string, opts ObjectOptions) (zipindex.Files, ObjectInfo, error) {
size := 1 << 20
var objSize int64
for {
rs := &HTTPRangeSpec{IsSuffixLength: true, Start: int64(-size)}
gr, err := objectAPI.GetObjectNInfo(ctx, bucket, object, rs, nil, opts)
if err != nil {
return nil, ObjectInfo{}, err
}
b, err := io.ReadAll(gr)
gr.Close()
if err != nil {
return nil, ObjectInfo{}, err
}
if size > len(b) {
size = len(b)
}
// Calculate the object real size if encrypted
if _, ok := crypto.IsEncrypted(gr.ObjInfo.UserDefined); ok {
objSize, err = gr.ObjInfo.DecryptedSize()
if err != nil {
return nil, ObjectInfo{}, err
}
} else {
objSize = gr.ObjInfo.Size
}
files, err := zipindex.ReadDir(b[len(b)-size:], objSize, nil)
if err == nil {
return files, gr.ObjInfo, nil
}
var terr zipindex.ErrNeedMoreData
if errors.As(err, &terr) {
size = int(terr.FromEnd)
if size <= 0 || size > 100<<20 {
return nil, ObjectInfo{}, errors.New("zip directory too large")
}
} else {
return nil, ObjectInfo{}, err
}
}
}
// headObjectInArchiveFileHandler - HEAD Object in an archive file
func (api objectAPIHandlers) headObjectInArchiveFileHandler(ctx context.Context, objectAPI ObjectLayer, bucket, object string, w http.ResponseWriter, r *http.Request) {
if crypto.S3.IsRequested(r.Header) || crypto.S3KMS.IsRequested(r.Header) { // If SSE-S3 or SSE-KMS present -> AWS fails with undefined error
writeErrorResponseHeadersOnly(w, errorCodes.ToAPIErr(ErrBadRequest))
return
}
zipPath, object, err := splitZipExtensionPath(object)
if err != nil {
writeErrorResponseHeadersOnly(w, toAPIError(ctx, err))
return
}
getObjectInfo := objectAPI.GetObjectInfo
if api.CacheAPI() != nil {
getObjectInfo = api.CacheAPI().GetObjectInfo
}
opts, err := getOpts(ctx, r, bucket, zipPath)
if err != nil {
writeErrorResponseHeadersOnly(w, toAPIError(ctx, err))
return
}
if s3Error := checkRequestAuthType(ctx, r, policy.GetObjectAction, bucket, zipPath); s3Error != ErrNone {
if getRequestAuthType(r) == authTypeAnonymous {
// As per "Permission" section in
// https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectHEAD.html
// If the object you request does not exist,
// the error Amazon S3 returns depends on
// whether you also have the s3:ListBucket
// permission.
// * If you have the s3:ListBucket permission
// on the bucket, Amazon S3 will return an
// HTTP status code 404 ("no such key")
// error.
// * if you don’t have the s3:ListBucket
// permission, Amazon S3 will return an HTTP
// status code 403 ("access denied") error.`
if globalPolicySys.IsAllowed(policy.Args{
Action: policy.ListBucketAction,
BucketName: bucket,
ConditionValues: getConditionValues(r, "", auth.AnonymousCredentials),
IsOwner: false,
}) {
_, err = getObjectInfo(ctx, bucket, zipPath, opts)
if toAPIError(ctx, err).Code == "NoSuchKey" {
s3Error = ErrNoSuchKey
}
}
}
errCode := errorCodes.ToAPIErr(s3Error)
w.Header().Set(xMinIOErrCodeHeader, errCode.Code)
w.Header().Set(xMinIOErrDescHeader, "\""+errCode.Description+"\"")
writeErrorResponseHeadersOnly(w, errCode)
return
}
// Validate pre-conditions if any.
opts.CheckPrecondFn = func(oi ObjectInfo) bool {
return checkPreconditions(ctx, w, r, oi, opts)
}
// We do not allow offsetting into extracted files.
if opts.PartNumber != 0 {
writeErrorResponseHeadersOnly(w, errorCodes.ToAPIErr(ErrInvalidPartNumber))
return
}
if r.Header.Get(xhttp.Range) != "" {
writeErrorResponseHeadersOnly(w, errorCodes.ToAPIErr(ErrInvalidRange))
return
}
zipObjInfo, err := getObjectInfo(ctx, bucket, zipPath, opts)
if err != nil {
writeErrorResponseHeadersOnly(w, toAPIError(ctx, err))
return
}
zipInfo := zipObjInfo.ArchiveInfo()
if len(zipInfo) == 0 {
opts.EncryptFn, err = zipObjInfo.metadataEncryptFn(r.Header)
if err != nil {
writeErrorResponseHeadersOnly(w, toAPIError(ctx, err))
return
}
zipInfo, err = updateObjectMetadataWithZipInfo(ctx, objectAPI, bucket, zipPath, opts)
}
if err != nil {
writeErrorResponseHeadersOnly(w, toAPIError(ctx, err))
return
}
file, err := zipindex.FindSerialized(zipInfo, object)
if err != nil {
if err == io.EOF {
writeErrorResponseHeadersOnly(w, errorCodes.ToAPIErr(ErrNoSuchKey))
} else {
writeErrorResponseHeadersOnly(w, toAPIError(ctx, err))
}
return
}
objInfo := ObjectInfo{
Bucket: bucket,
Name: file.Name,
Size: int64(file.UncompressedSize64),
ModTime: zipObjInfo.ModTime,
}
// Set standard object headers.
if err = setObjectHeaders(w, objInfo, nil, opts); err != nil {
writeErrorResponseHeadersOnly(w, toAPIError(ctx, err))
return
}
// s3zip does not allow ranges.
w.Header().Del(xhttp.AcceptRanges)
// Set any additional requested response headers.
setHeadGetRespHeaders(w, r.Form)
// Successful response.
w.WriteHeader(http.StatusOK)
}
// Update the passed zip object metadata with the zip contents info, file name, modtime, size, etc.
// The returned zip index will de decrypted.
func updateObjectMetadataWithZipInfo(ctx context.Context, objectAPI ObjectLayer, bucket, object string, opts ObjectOptions) ([]byte, error) {
files, srcInfo, err := getFilesListFromZIPObject(ctx, objectAPI, bucket, object, opts)
if err != nil {
return nil, err
}
files.OptimizeSize()
zipInfo, err := files.Serialize()
if err != nil {
return nil, err
}
at := archiveType
zipInfoStr := string(zipInfo)
if opts.EncryptFn != nil {
at = archiveTypeEnc
zipInfoStr = string(opts.EncryptFn(archiveTypeEnc, zipInfo))
}
srcInfo.UserDefined[archiveTypeMetadataKey] = at
popts := ObjectOptions{
MTime: srcInfo.ModTime,
VersionID: srcInfo.VersionID,
EvalMetadataFn: func(oi *ObjectInfo, gerr error) (dsc ReplicateDecision, err error) {
oi.UserDefined[archiveTypeMetadataKey] = at
oi.UserDefined[archiveInfoMetadataKey] = zipInfoStr
return dsc, nil
},
}
// For all other modes use in-place update to update metadata on a specific version.
if _, err = objectAPI.PutObjectMetadata(ctx, bucket, object, popts); err != nil {
return nil, err
}
return zipInfo, nil
}
| cmd/s3-zip-handlers.go | 0 | https://github.com/minio/minio/commit/f13cfcb83e931ed6cabdabee588bbaf308e7952b | [
0.9919697642326355,
0.3670474588871002,
0.00016487919492647052,
0.00017738222959451377,
0.46372348070144653
] |
{
"id": 0,
"code_window": [
" compute-largem: ${{ steps.setup-outputs.outputs.compute-largem }}\n",
" compute-xlarge: ${{ steps.setup-outputs.outputs.compute-xlarge }}\n",
" enterprise: ${{ steps.setup-outputs.outputs.enterprise }}\n",
" go-tags: ${{ steps.setup-outputs.outputs.go-tags }}\n",
" steps:\n",
" - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3\n",
" - id: setup-outputs\n",
" name: Setup outputs\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkout-ref: ${{ steps.checkout-ref-output.outputs.checkout-ref }}\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 30
} | on:
workflow_call:
inputs:
go-arch:
description: The execution architecture (arm, amd64, etc.)
required: true
type: string
enterprise:
description: A flag indicating if this workflow is executing for the enterprise repository.
required: true
type: string
total-runners:
description: Number of runners to use for executing non-binary tests.
required: true
type: string
binary-tests:
description: Whether to run the binary tests.
required: false
default: false
type: boolean
env-vars:
description: A map of environment variables as JSON.
required: false
type: string
default: '{}'
extra-flags:
description: A space-separated list of additional build flags.
required: false
type: string
default: ''
runs-on:
description: An expression indicating which kind of runners to use.
required: false
type: string
default: ubuntu-latest
go-tags:
description: A comma-separated list of additional build tags to consider satisfied during the build.
required: false
type: string
name:
description: A suffix to append to archived test results
required: false
default: ''
type: string
go-test-parallelism:
description: The parallelism parameter for Go tests
required: false
default: 20
type: number
timeout-minutes:
description: The maximum number of minutes that this workflow should run
required: false
default: 60
type: number
testonly:
description: Whether to run the tests tagged with testonly.
required: false
default: false
type: boolean
test-timing-cache-enabled:
description: Cache the gotestsum test timing data.
required: false
default: true
type: boolean
test-timing-cache-key:
description: The cache key to use for gotestsum test timing data.
required: false
default: go-test-reports
type: string
env: ${{ fromJSON(inputs.env-vars) }}
jobs:
test-matrix:
permissions:
id-token: write # Note: this permission is explicitly required for Vault auth
contents: read
runs-on: ${{ fromJSON(inputs.runs-on) }}
steps:
- uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
- uses: ./.github/actions/set-up-go
with:
github-token: ${{ secrets.ELEVATED_GITHUB_TOKEN }}
- name: Authenticate to Vault
id: vault-auth
if: github.repository == 'hashicorp/vault-enterprise'
run: vault-auth
- name: Fetch Secrets
id: secrets
if: github.repository == 'hashicorp/vault-enterprise'
uses: hashicorp/vault-action@130d1f5f4fe645bb6c83e4225c04d64cfb62de6e
with:
url: ${{ steps.vault-auth.outputs.addr }}
caCertificate: ${{ steps.vault-auth.outputs.ca_certificate }}
token: ${{ steps.vault-auth.outputs.token }}
secrets: |
kv/data/github/${{ github.repository }}/datadog-ci DATADOG_API_KEY;
kv/data/github/${{ github.repository }}/github-token username-and-token | github-token;
kv/data/github/${{ github.repository }}/license license_1 | VAULT_LICENSE_CI;
kv/data/github/${{ github.repository }}/license license_2 | VAULT_LICENSE_2;
kv/data/github/${{ github.repository }}/hcp-link HCP_API_ADDRESS;
kv/data/github/${{ github.repository }}/hcp-link HCP_AUTH_URL;
kv/data/github/${{ github.repository }}/hcp-link HCP_CLIENT_ID;
kv/data/github/${{ github.repository }}/hcp-link HCP_CLIENT_SECRET;
kv/data/github/${{ github.repository }}/hcp-link HCP_RESOURCE_ID;
- id: setup-git-private
name: Setup Git configuration (private)
if: github.repository == 'hashicorp/vault-enterprise'
run: |
git config --global url."https://${{ steps.secrets.outputs.github-token }}@github.com".insteadOf https://github.com
- id: setup-git-public
name: Setup Git configuration (public)
if: github.repository != 'hashicorp/vault-enterprise'
run: |
git config --global url."https://${{ secrets.ELEVATED_GITHUB_TOKEN}}@github.com".insteadOf https://github.com
- uses: ./.github/actions/set-up-gotestsum
- run: mkdir -p test-results/go-test
- uses: actions/cache/restore@88522ab9f39a2ea568f7027eddc7d8d8bc9d59c8 # v3.3.1
if: inputs.test-timing-cache-enabled
with:
path: test-results/go-test
key: ${{ inputs.test-timing-cache-key }}-${{ github.run_number }}
restore-keys: |
${{ inputs.test-timing-cache-key }}-
go-test-reports-
- name: Sanitize timing files
id: sanitize-timing-files
run: |
# Prune invalid timing files
find test-results/go-test -mindepth 1 -type f -name "*.json" -exec sh -c '
file="$1";
jq . "$file" || rm "$file"
' shell {} \; > /dev/null 2>&1
- name: Build matrix excluding binary, integration, and testonly tests
id: build-non-binary
if: ${{ !inputs.testonly }}
env:
GOPRIVATE: github.com/hashicorp/*
run: |
# testonly tests need additional build tag though let's exclude them anyway for clarity
(
go list ./... | grep -v "_binary" | grep -v "vault/integ" | grep -v "testonly" | gotestsum tool ci-matrix --debug \
--partitions "${{ inputs.total-runners }}" \
--timing-files 'test-results/go-test/*.json' > matrix.json
)
- name: Build matrix for tests tagged with testonly
if: ${{ inputs.testonly }}
env:
GOPRIVATE: github.com/hashicorp/*
run: |
set -exo pipefail
# enable glob expansion
shopt -s nullglob
# testonly tagged tests need an additional tag to be included
# also running some extra tests for sanity checking with the testonly build tag
(
go list -tags=testonly ./vault/external_tests/{kv,token,*replication-perf*,*testonly*} ./vault/ | gotestsum tool ci-matrix --debug \
--partitions "${{ inputs.total-runners }}" \
--timing-files 'test-results/go-test/*.json' > matrix.json
)
# disable glob expansion
shopt -u nullglob
- name: Capture list of binary tests
if: inputs.binary-tests
id: list-binary-tests
run: |
LIST="$(go list ./... | grep "_binary" | xargs)"
echo "list=$LIST" >> "$GITHUB_OUTPUT"
- name: Build complete matrix
id: build
run: |
set -exo pipefail
matrix_file="matrix.json"
if [ "${{ inputs.binary-tests}}" == "true" ] && [ -n "${{ steps.list-binary-tests.outputs.list }}" ]; then
export BINARY_TESTS="${{ steps.list-binary-tests.outputs.list }}"
jq --arg BINARY "${BINARY_TESTS}" --arg BINARY_INDEX "${{ inputs.total-runners }}" \
'.include += [{
"id": $BINARY_INDEX,
"estimatedRuntime": "N/A",
"packages": $BINARY,
"description": "partition $BINARY_INDEX - binary test packages"
}]' matrix.json > new-matrix.json
matrix_file="new-matrix.json"
fi
# convert the json to a map keyed by id
(
echo -n "matrix="
jq -c \
'.include | map( { (.id|tostring): . } ) | add' "$matrix_file"
) >> "$GITHUB_OUTPUT"
# extract an array of ids from the json
(
echo -n "matrix_ids="
jq -c \
'[ .include[].id | tostring ]' "$matrix_file"
) >> "$GITHUB_OUTPUT"
outputs:
matrix: ${{ steps.build.outputs.matrix }}
matrix_ids: ${{ steps.build.outputs.matrix_ids }}
test-go:
needs: test-matrix
permissions:
actions: read
contents: read
id-token: write # Note: this permission is explicitly required for Vault auth
runs-on: ${{ fromJSON(inputs.runs-on) }}
strategy:
fail-fast: false
matrix:
id: ${{ fromJSON(needs.test-matrix.outputs.matrix_ids) }}
env:
GOPRIVATE: github.com/hashicorp/*
TIMEOUT_IN_MINUTES: ${{ inputs.timeout-minutes }}
steps:
- uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
- uses: ./.github/actions/set-up-go
with:
github-token: ${{ secrets.ELEVATED_GITHUB_TOKEN }}
- name: Authenticate to Vault
id: vault-auth
if: github.repository == 'hashicorp/vault-enterprise'
run: vault-auth
- name: Fetch Secrets
id: secrets
if: github.repository == 'hashicorp/vault-enterprise'
uses: hashicorp/vault-action@130d1f5f4fe645bb6c83e4225c04d64cfb62de6e
with:
url: ${{ steps.vault-auth.outputs.addr }}
caCertificate: ${{ steps.vault-auth.outputs.ca_certificate }}
token: ${{ steps.vault-auth.outputs.token }}
secrets: |
kv/data/github/${{ github.repository }}/datadog-ci DATADOG_API_KEY;
kv/data/github/${{ github.repository }}/github-token username-and-token | github-token;
kv/data/github/${{ github.repository }}/license license_1 | VAULT_LICENSE_CI;
kv/data/github/${{ github.repository }}/license license_2 | VAULT_LICENSE_2;
kv/data/github/${{ github.repository }}/hcp-link HCP_API_ADDRESS;
kv/data/github/${{ github.repository }}/hcp-link HCP_AUTH_URL;
kv/data/github/${{ github.repository }}/hcp-link HCP_CLIENT_ID;
kv/data/github/${{ github.repository }}/hcp-link HCP_CLIENT_SECRET;
kv/data/github/${{ github.repository }}/hcp-link HCP_RESOURCE_ID;
- id: setup-git-private
name: Setup Git configuration (private)
if: github.repository == 'hashicorp/vault-enterprise'
run: |
git config --global url."https://${{ steps.secrets.outputs.github-token }}@github.com".insteadOf https://github.com
- id: setup-git-public
name: Setup Git configuration (public)
if: github.repository != 'hashicorp/vault-enterprise'
run: |
git config --global url."https://${{ secrets.ELEVATED_GITHUB_TOKEN}}@github.com".insteadOf https://github.com
- id: build
if: inputs.binary-tests && matrix.id == inputs.total-runners
env:
GOPRIVATE: github.com/hashicorp/*
run: time make ci-bootstrap dev
- uses: ./.github/actions/set-up-gotestsum
- name: Install gVisor
# Enterprise repo runners do not allow sudo, so can't install gVisor there yet.
if: ${{ !inputs.enterprise }}
run: |
(
set -e
ARCH="$(uname -m)"
URL="https://storage.googleapis.com/gvisor/releases/release/latest/${ARCH}"
wget --quiet "${URL}/runsc" "${URL}/runsc.sha512" \
"${URL}/containerd-shim-runsc-v1" "${URL}/containerd-shim-runsc-v1.sha512"
sha512sum -c runsc.sha512 \
-c containerd-shim-runsc-v1.sha512
rm -f -- *.sha512
chmod a+rx runsc containerd-shim-runsc-v1
sudo mv runsc containerd-shim-runsc-v1 /usr/local/bin
)
sudo tee /etc/docker/daemon.json <<EOF
{
"runtimes": {
"runsc": {
"path": "/usr/local/bin/runsc",
"runtimeArgs": [
"--host-uds=all",
"--host-fifo=open"
]
}
}
}
EOF
sudo systemctl reload docker
- id: run-go-tests
name: Run Go tests
timeout-minutes: ${{ fromJSON(env.TIMEOUT_IN_MINUTES) }}
env:
COMMIT_SHA: ${{ github.sha }}
run: |
set -exo pipefail
# Build the dynamically generated source files.
make prep
packages=$(echo "${{ toJSON(needs.test-matrix.outputs.matrix) }}" | jq -c -r --arg id "${{ matrix.id }}" '.[$id] | .packages')
if [ -z "$packages" ]; then
echo "no test packages to run"
exit 1
fi
# We don't want VAULT_LICENSE set when running Go tests, because that's
# not what developers have in their environments and it could break some
# tests; it would be like setting VAULT_TOKEN. However some non-Go
# CI commands, like the UI tests, shouldn't have to worry about licensing.
# So we provide the tests which want an externally supplied license with licenses
# via the VAULT_LICENSE_CI and VAULT_LICENSE_2 environment variables, and here we unset it.
# shellcheck disable=SC2034
VAULT_LICENSE=
# Assign test licenses to relevant variables if they aren't already
if [[ ${{ github.repository }} == 'hashicorp/vault' ]]; then
export VAULT_LICENSE_CI=${{ secrets.ci_license }}
export VAULT_LICENSE_2=${{ secrets.ci_license_2 }}
export HCP_API_ADDRESS=${{ secrets.HCP_API_ADDRESS }}
export HCP_AUTH_URL=${{ secrets.HCP_AUTH_URL }}
export HCP_CLIENT_ID=${{ secrets.HCP_CLIENT_ID }}
export HCP_CLIENT_SECRET=${{ secrets.HCP_CLIENT_SECRET }}
export HCP_RESOURCE_ID=${{ secrets.HCP_RESOURCE_ID }}
# Temporarily removing this variable to cause HCP Link tests
# to be skipped.
#export HCP_SCADA_ADDRESS=${{ secrets.HCP_SCADA_ADDRESS }}
fi
if [ -f bin/vault ]; then
VAULT_BINARY="$(pwd)/bin/vault"
export VAULT_BINARY
fi
# On a release branch, add a flag to rerun failed tests
# shellcheck disable=SC2193 # can get false positive for this comparision
if [[ "${{ github.base_ref }}" == release/* ]] || [[ -z "${{ github.base_ref }}" && "${{ github.ref_name }}" == release/* ]]
then
# TODO remove this extra condition once 1.15 is about to released GA
if [[ "${{ github.base_ref }}" != release/1.15* ]] || [[ -z "${{ github.base_ref }}" && "${{ github.ref_name }}" != release/1.15* ]]
then
RERUN_FAILS="--rerun-fails"
fi
fi
# shellcheck disable=SC2086 # can't quote RERUN_FAILS
GOARCH=${{ inputs.go-arch }} \
gotestsum --format=short-verbose \
--junitfile test-results/go-test/results-${{ matrix.id }}.xml \
--jsonfile test-results/go-test/results-${{ matrix.id }}.json \
--jsonfile-timing-events failure-summary-${{ matrix.id }}${{ inputs.name != '' && '-' || '' }}${{ inputs.name }}.json \
$RERUN_FAILS \
--packages "$packages" \
-- \
-tags "${{ inputs.go-tags }}" \
-timeout=${{ env.TIMEOUT_IN_MINUTES }}m \
-parallel=${{ inputs.go-test-parallelism }} \
${{ inputs.extra-flags }} \
- name: Prepare datadog-ci
if: github.repository == 'hashicorp/vault' && (success() || failure())
continue-on-error: true
run: |
curl -L --fail "https://github.com/DataDog/datadog-ci/releases/latest/download/datadog-ci_linux-x64" --output "/usr/local/bin/datadog-ci"
chmod +x /usr/local/bin/datadog-ci
- name: Upload test results to DataDog
continue-on-error: true
env:
DD_ENV: ci
run: |
if [[ ${{ github.repository }} == 'hashicorp/vault' ]]; then
export DATADOG_API_KEY=${{ secrets.DATADOG_API_KEY }}
fi
datadog-ci junit upload --service "$GITHUB_REPOSITORY" test-results/go-test/results-${{ matrix.id }}.xml
if: success() || failure()
- name: Archive test results
uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # v3.1.2
with:
name: test-results${{ inputs.name != '' && '-' || '' }}${{ inputs.name }}
path: test-results/go-test
if: success() || failure()
# GitHub Actions doesn't expose the job ID or the URL to the job execution,
# so we have to fetch it from the API
- name: Fetch job logs URL
uses: actions/github-script@d7906e4ad0b1822421a7e6a35d5ca353c962f410 # v6.4.1
if: success() || failure()
continue-on-error: true
with:
retries: 3
script: |
// We surround the whole script with a try-catch block, to avoid each of the matrix jobs
// displaying an error in the GHA workflow run annotations, which gets very noisy.
// If an error occurs, it will be logged so that we don't lose any information about the reason for failure.
try {
const fs = require("fs");
const result = await github.rest.actions.listJobsForWorkflowRun({
owner: context.repo.owner,
per_page: 100,
repo: context.repo.repo,
run_id: context.runId,
});
// Determine what job name to use for the query. These values are hardcoded, because GHA doesn't
// expose them in any of the contexts available within a workflow run.
let prefixToSearchFor;
switch ("${{ inputs.name }}") {
case "race":
prefixToSearchFor = 'Run Go tests with data race detection / test-go (${{ matrix.id }})'
break
case "fips":
prefixToSearchFor = 'Run Go tests with FIPS configuration / test-go (${{ matrix.id }})'
break
default:
prefixToSearchFor = 'Run Go tests / test-go (${{ matrix.id }})'
}
const jobData = result.data.jobs.filter(
(job) => job.name.startsWith(prefixToSearchFor)
);
const url = jobData[0].html_url;
const envVarName = "GH_JOB_URL";
const envVar = envVarName + "=" + url;
const envFile = process.env.GITHUB_ENV;
fs.appendFile(envFile, envVar, (err) => {
if (err) throw err;
console.log("Successfully set " + envVarName + " to: " + url);
});
} catch (error) {
console.log("Error: " + error);
return
}
- name: Prepare failure summary
if: success() || failure()
continue-on-error: true
run: |
# This jq query filters out successful tests, leaving only the failures.
# Then, it formats the results into rows of a Markdown table.
# An example row will resemble this:
# | github.com/hashicorp/vault/package | TestName | fips | 0 | 2 | [view results](github.com/link-to-logs) |
jq -r -n 'inputs
| select(.Action == "fail")
| "| ${{inputs.name}} | \(.Package) | \(.Test // "-") | \(.Elapsed) | ${{ matrix.id }} | [view test results :scroll:](${{ env.GH_JOB_URL }}) |"' \
failure-summary-${{ matrix.id }}${{ inputs.name != '' && '-' || '' }}${{inputs.name}}.json \
>> failure-summary-${{ matrix.id }}${{ inputs.name != '' && '-' || '' }}${{inputs.name}}.md
- name: Upload failure summary
uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # v3.1.2
if: success() || failure()
with:
name: failure-summary
path: failure-summary-${{ matrix.id }}${{ inputs.name != '' && '-' || '' }}${{inputs.name}}.md
test-collect-reports:
if: ${{ ! cancelled() && needs.test-go.result == 'success' && inputs.test-timing-cache-enabled }}
needs: test-go
runs-on: ${{ fromJSON(inputs.runs-on) }}
steps:
- uses: actions/cache@88522ab9f39a2ea568f7027eddc7d8d8bc9d59c8 # v3.3.1
with:
path: test-results/go-test
key: ${{ inputs.test-timing-cache-key }}-${{ github.run_number }}
restore-keys: |
${{ inputs.test-timing-cache-key }}-
go-test-reports-
- uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # v3.0.2
with:
name: test-results
path: test-results/go-test
- run: |
ls -lhR test-results/go-test
find test-results/go-test -mindepth 1 -mtime +3 -delete
# Prune invalid timing files
find test-results/go-test -mindepth 1 -type f -name "*.json" -exec sh -c '
file="$1";
jq . "$file" || rm "$file"
' shell {} \; > /dev/null 2>&1
ls -lhR test-results/go-test
| .github/workflows/test-go.yml | 1 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.014769371598958969,
0.0007498307968489826,
0.00016432953998446465,
0.00016977427003439516,
0.00232476694509387
] |
{
"id": 0,
"code_window": [
" compute-largem: ${{ steps.setup-outputs.outputs.compute-largem }}\n",
" compute-xlarge: ${{ steps.setup-outputs.outputs.compute-xlarge }}\n",
" enterprise: ${{ steps.setup-outputs.outputs.enterprise }}\n",
" go-tags: ${{ steps.setup-outputs.outputs.go-tags }}\n",
" steps:\n",
" - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3\n",
" - id: setup-outputs\n",
" name: Setup outputs\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkout-ref: ${{ steps.checkout-ref-output.outputs.checkout-ref }}\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 30
} | ---
layout: api
page_title: Secrets Engines - HTTP API
description: |-
Each secrets engine publishes its own set of API paths and methods. These
endpoints are documented in this section.
---
# Secrets engines
Each secrets engine publishes its own set of API paths and methods. These
endpoints are documented in this section. secrets engines are enabled at a path,
but the documentation will assume the default paths for simplicity. If you are
enabled at a different path, you should adjust your API calls accordingly.
For the API documentation for a specific secrets engine, please choose a secrets
engine from the navigation.
| website/content/api-docs/secret/index.mdx | 0 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.0001646630116738379,
0.00016401251195929945,
0.000163362012244761,
0.00016401251195929945,
6.50499714538455e-7
] |
{
"id": 0,
"code_window": [
" compute-largem: ${{ steps.setup-outputs.outputs.compute-largem }}\n",
" compute-xlarge: ${{ steps.setup-outputs.outputs.compute-xlarge }}\n",
" enterprise: ${{ steps.setup-outputs.outputs.enterprise }}\n",
" go-tags: ${{ steps.setup-outputs.outputs.go-tags }}\n",
" steps:\n",
" - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3\n",
" - id: setup-outputs\n",
" name: Setup outputs\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkout-ref: ${{ steps.checkout-ref-output.outputs.checkout-ref }}\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 30
} | /**
* Copyright (c) HashiCorp, Inc.
* SPDX-License-Identifier: BUSL-1.1
*/
export { default } from 'core/components/vault-logo-spinner';
| ui/lib/core/app/components/vault-logo-spinner.js | 0 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.00016803380276542157,
0.00016803380276542157,
0.00016803380276542157,
0.00016803380276542157,
0
] |
{
"id": 0,
"code_window": [
" compute-largem: ${{ steps.setup-outputs.outputs.compute-largem }}\n",
" compute-xlarge: ${{ steps.setup-outputs.outputs.compute-xlarge }}\n",
" enterprise: ${{ steps.setup-outputs.outputs.enterprise }}\n",
" go-tags: ${{ steps.setup-outputs.outputs.go-tags }}\n",
" steps:\n",
" - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3\n",
" - id: setup-outputs\n",
" name: Setup outputs\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkout-ref: ${{ steps.checkout-ref-output.outputs.checkout-ref }}\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 30
} | {{!
Copyright (c) HashiCorp, Inc.
SPDX-License-Identifier: BUSL-1.1
~}}
<PageHeader as |p|>
<p.top>
<Page::Breadcrumbs @breadcrumbs={{@breadcrumbs}} />
</p.top>
<p.levelLeft>
<h1 class="title is-3">
Configure Kubernetes
</h1>
</p.levelLeft>
</PageHeader>
<hr class="is-marginless has-background-gray-200" />
<p class="has-top-margin-m">
To customize your configuration, specify the type of Kubernetes cluster that credentials will be generated for.
</p>
<div class="is-flex-row has-top-margin-s">
<RadioCard
class="has-fixed-width"
@title="Local cluster"
@description="Generate credentials for the local Kubernetes cluster that Vault is running on, using Vault’s service account."
@icon="kubernetes-color"
@value={{false}}
@groupValue={{@model.disableLocalCaJwt}}
@onChange={{this.onRadioSelect}}
data-test-radio-card="local"
/>
<RadioCard
class="has-fixed-width"
@title="Manual configuration"
@description="Generate credentials for an external Kubernetes cluster, using a service account that you specify."
@icon="vault"
@iconClass="has-text-black"
@value={{true}}
@groupValue={{@model.disableLocalCaJwt}}
@onChange={{this.onRadioSelect}}
data-test-radio-card="manual"
/>
</div>
<div class="has-top-margin-m" data-test-config>
{{#if @model.disableLocalCaJwt}}
<MessageError @errorMessage={{this.error}} />
{{#each @model.formFields as |attr|}}
<FormField @attr={{attr}} @model={{@model}} @modelValidations={{this.modelValidations}} />
{{/each}}
{{else if (eq this.inferredState "success")}}
<Icon @name="check-circle-fill" class="has-text-success" />
<span>Configuration values were inferred successfully.</span>
{{else if (eq this.inferredState "error")}}
<Icon @name="x-square-fill" class="has-text-danger" />
<span class="has-text-danger">
Vault could not infer a configuration from your environment variables. Check your configuration file to edit or delete
them, or configure manually.
</span>
{{else}}
<p>
Configuration values can be inferred from the pod and your local environment variables.
</p>
<div>
<button
class="button has-top-margin-s {{if this.fetchInferred.isRunning 'is-loading'}}"
type="button"
disabled={{this.fetchInferred.isRunning}}
{{on "click" (perform this.fetchInferred)}}
>
Get config values
</button>
</div>
{{/if}}
</div>
<hr class="has-background-gray-200 has-top-margin-l" />
<div class="has-top-margin-s has-bottom-margin-s is-flex">
<button
data-test-config-save
class="button is-primary"
type="button"
disabled={{this.isDisabled}}
{{on "click" (perform this.save)}}
>
Save
</button>
<button
data-test-config-cancel
class="button has-left-margin-xs"
type="button"
disabled={{or this.save.isRunning this.fetchInferred.isRunning}}
{{on "click" this.cancel}}
>
Back
</button>
{{#if this.alert}}
<AlertInline @type="danger" @paddingTop={{true}} @message={{this.alert}} @mimicRefresh={{true}} data-test-alert />
{{/if}}
</div>
{{#if this.showConfirm}}
<Modal
@title="Edit configuration"
@type="warning"
@isActive={{this.showConfirm}}
@showCloseButton={{true}}
@onClose={{fn (mut this.showConfirm) false}}
>
<section class="modal-card-body">
<p>
Making changes to your configuration may affect how Vault will reach the Kubernetes API and authenticate with it. Are
you sure?
</p>
</section>
<footer class="modal-card-foot modal-card-foot-outlined">
<button data-test-config-confirm type="button" class="button is-primary" {{on "click" (perform this.save)}}>
Confirm
</button>
<button type="button" class="button" onclick={{fn (mut this.showConfirm) false}}>
Cancel
</button>
</footer>
</Modal>
{{/if}} | ui/lib/kubernetes/addon/components/page/configure.hbs | 0 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.00017490620666649193,
0.0001698775595286861,
0.0001623902644496411,
0.0001697402767604217,
0.000003439600959609379
] |
{
"id": 1,
"code_window": [
" with:\n",
" github-token: ${{ secrets.ELEVATED_GITHUB_TOKEN }}\n",
" no-restore: true # don't download them on a cache hit\n",
"\n",
" verify-changes:\n",
" name: Verify doc-ui only PRs\n",
" uses: ./.github/workflows/verify_changes.yml\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" # control checking out head instead of base ref by a GH label\n",
" # if checkout-head label is added to a PR, checkout HEAD otherwise checkout base_ref\n",
" - if: ${{ !contains(github.event.pull_request.labels.*.name, 'checkout-head') }}\n",
" run: echo \"CHECKOUT_REF=${{ github.base_ref }}\" >> \"$GITHUB_ENV\"\n",
" - if: ${{ contains(github.event.pull_request.labels.*.name, 'checkout-head') }}\n",
" run: echo \"CHECKOUT_REF=${{ github.event.pull_request.head.sha }}\" >> \"$GITHUB_ENV\"\n",
" - id: checkout-ref-output\n",
" run: echo \"checkout-ref=${{ env.CHECKOUT_REF }}\" >> \"$GITHUB_OUTPUT\"\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 61
} | name: CI
on:
pull_request:
# The default types for pull_request are [ opened, synchronize, reopened ].
# This is insufficient for our needs, since we're skipping stuff on PRs in
# draft mode. By adding the ready_for_review type, when a draft pr is marked
# ready, we run everything, including the stuff we'd have skipped up until now.
types: [opened, synchronize, reopened, ready_for_review]
push:
branches:
- main
- release/**
workflow_dispatch:
concurrency:
group: ${{ github.head_ref || github.run_id }}-ci
cancel-in-progress: true
jobs:
setup:
name: Setup
runs-on: ubuntu-latest
outputs:
compute-small: ${{ steps.setup-outputs.outputs.compute-small }}
compute-medium: ${{ steps.setup-outputs.outputs.compute-medium }}
compute-large: ${{ steps.setup-outputs.outputs.compute-large }}
compute-largem: ${{ steps.setup-outputs.outputs.compute-largem }}
compute-xlarge: ${{ steps.setup-outputs.outputs.compute-xlarge }}
enterprise: ${{ steps.setup-outputs.outputs.enterprise }}
go-tags: ${{ steps.setup-outputs.outputs.go-tags }}
steps:
- uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
- id: setup-outputs
name: Setup outputs
run: |
github_repository="${{ github.repository }}"
if [ "${github_repository##*/}" == "vault-enterprise" ] ; then
# shellcheck disable=SC2129
echo 'compute-small=["self-hosted","ondemand","linux","type=c6a.large"]' >> "$GITHUB_OUTPUT" # 2x vCPUs, 4 GiB RAM,
echo 'compute-medium=["self-hosted","ondemand","linux","type=c6a.xlarge"]' >> "$GITHUB_OUTPUT" # 4x vCPUs, 8 GiB RAM,
echo 'compute-large=["self-hosted","ondemand","linux","type=c6a.2xlarge","disk_gb=64"]' >> "$GITHUB_OUTPUT" # 8x vCPUs, 16 GiB RAM,
echo 'compute-largem=["self-hosted","ondemand","linux","type=m6a.2xlarge"]' >> "$GITHUB_OUTPUT" # 8x vCPUs, 32 GiB RAM,
echo 'compute-xlarge=["self-hosted","ondemand","linux","type=c6a.4xlarge"]' >> "$GITHUB_OUTPUT" # 16x vCPUs, 32 GiB RAM,
echo 'enterprise=1' >> "$GITHUB_OUTPUT"
echo 'go-tags=ent,enterprise' >> "$GITHUB_OUTPUT"
else
# shellcheck disable=SC2129
echo 'compute-small="ubuntu-latest"' >> "$GITHUB_OUTPUT" # 2x vCPUs, 7 GiB RAM, 14 GB SSD
echo 'compute-medium="custom-linux-small-vault-latest"' >> "$GITHUB_OUTPUT" # 8x vCPUs, 32 GiB RAM, 300 GB SSD
echo 'compute-large="custom-linux-medium-vault-latest"' >> "$GITHUB_OUTPUT" # 16x vCPUs, 64 GiB RAM, 600 GB SSD
echo 'compute-largem="custom-linux-medium-vault-latest"' >> "$GITHUB_OUTPUT" # 16x vCPUs, 64 GiB RAM, 600 GB SSD
echo 'compute-xlarge="custom-linux-xl-vault-latest"' >> "$GITHUB_OUTPUT" # 32x vCPUs, 128 GiB RAM, 1200 GB SSD
echo 'enterprise=' >> "$GITHUB_OUTPUT"
echo 'go-tags=' >> "$GITHUB_OUTPUT"
fi
- name: Ensure Go modules are cached
uses: ./.github/actions/set-up-go
with:
github-token: ${{ secrets.ELEVATED_GITHUB_TOKEN }}
no-restore: true # don't download them on a cache hit
verify-changes:
name: Verify doc-ui only PRs
uses: ./.github/workflows/verify_changes.yml
test-go:
name: Run Go tests
needs:
- setup
- verify-changes
# Don't run this job for docs/ui only PRs
if: |
needs.verify-changes.outputs.is_docs_change == 'false' &&
needs.verify-changes.outputs.is_ui_change == 'false'
uses: ./.github/workflows/test-go.yml
with:
# The regular Go tests use an extra runner to execute the
# binary-dependent tests. We isolate them there so that the
# other tests aren't slowed down waiting for a binary build.
binary-tests: true
total-runners: 16
go-arch: amd64
go-tags: '${{ needs.setup.outputs.go-tags }},deadlock'
runs-on: ${{ needs.setup.outputs.compute-large }}
enterprise: ${{ needs.setup.outputs.enterprise }}
test-timing-cache-key: go-test-timing-standard
secrets: inherit
test-go-testonly:
name: Run Go tests tagged with testonly
needs:
- setup
- verify-changes
# Don't run this job for docs/ui only PRs
if: |
needs.verify-changes.outputs.is_docs_change == 'false' &&
needs.verify-changes.outputs.is_ui_change == 'false'
uses: ./.github/workflows/test-go.yml
with:
testonly: true
total-runners: 2 # test runners cannot be less than 2
go-arch: amd64
go-tags: '${{ needs.setup.outputs.go-tags }},deadlock,testonly'
runs-on: ${{ needs.setup.outputs.compute-large }}
enterprise: ${{ needs.setup.outputs.enterprise }}
test-timing-cache-enabled: false
secrets: inherit
test-go-race:
name: Run Go tests with data race detection
needs:
- setup
- verify-changes
# Don't run this job for docs/ui only PRs
if: |
github.event.pull_request.draft == false &&
needs.verify-changes.outputs.is_docs_change == 'false' &&
needs.verify-changes.outputs.is_ui_change == 'false'
uses: ./.github/workflows/test-go.yml
with:
total-runners: 16
env-vars: |
{
"VAULT_CI_GO_TEST_RACE": 1
}
extra-flags: '-race'
go-arch: amd64
go-tags: ${{ needs.setup.outputs.go-tags }}
runs-on: ${{ needs.setup.outputs.compute-large }}
enterprise: ${{ needs.setup.outputs.enterprise }}
name: "race"
test-timing-cache-key: go-test-timing-race
secrets: inherit
test-go-fips:
name: Run Go tests with FIPS configuration
# Only run this job for the enterprise repo if the PR is not docs/ui only
if: |
github.event.pull_request.draft == false &&
needs.setup.outputs.enterprise == 1 &&
needs.verify-changes.outputs.is_docs_change == 'false' &&
needs.verify-changes.outputs.is_ui_change == 'false'
needs:
- setup
- verify-changes
uses: ./.github/workflows/test-go.yml
with:
total-runners: 16
env-vars: |
{
"GOEXPERIMENT": "boringcrypto"
}
go-arch: amd64
go-tags: '${{ needs.setup.outputs.go-tags }},deadlock,cgo,fips,fips_140_2'
runs-on: ${{ needs.setup.outputs.compute-large }}
enterprise: ${{ needs.setup.outputs.enterprise }}
name: "fips"
test-timing-cache-key: go-test-timing-fips
secrets: inherit
test-ui:
name: Test UI
# The test-ui job is only run on:
# - pushes to main and branches starting with "release/"
# - PRs where the branch starts with "ui/", "backport/ui/", "merge", or when base branch starts with "release/"
# - PRs with the "ui" label on GitHub
if: |
github.ref_name == 'main' ||
startsWith(github.ref_name, 'release/') ||
startsWith(github.head_ref, 'ui/') ||
startsWith(github.head_ref, 'backport/ui/') ||
startsWith(github.head_ref, 'merge') ||
contains(github.event.pull_request.labels.*.name, 'ui')
needs:
- setup
permissions:
id-token: write
contents: read
runs-on: ${{ fromJSON(needs.setup.outputs.compute-largem) }}
steps:
- uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
- uses: ./.github/actions/set-up-go
with:
github-token: ${{ secrets.ELEVATED_GITHUB_TOKEN }}
# Setup node.js without caching to allow running npm install -g yarn (next step)
- uses: actions/setup-node@e33196f7422957bea03ed53f6fbb155025ffc7b8 # v3.7.0
with:
node-version-file: './ui/package.json'
- id: install-yarn
run: |
npm install -g yarn
# Setup node.js with caching using the yarn.lock file
- uses: actions/setup-node@e33196f7422957bea03ed53f6fbb155025ffc7b8 # v3.7.0
with:
node-version-file: './ui/package.json'
cache: yarn
cache-dependency-path: ui/yarn.lock
- id: install-browser
uses: browser-actions/setup-chrome@c485fa3bab6be59dce18dbc18ef6ab7cbc8ff5f1 # v1.2.0
- id: ui-dependencies
name: ui-dependencies
working-directory: ./ui
run: |
yarn install --frozen-lockfile
npm rebuild node-sass
- id: vault-auth
name: Authenticate to Vault
if: github.repository == 'hashicorp/vault-enterprise'
run: vault-auth
- id: secrets
name: Fetch secrets
if: github.repository == 'hashicorp/vault-enterprise'
uses: hashicorp/vault-action@130d1f5f4fe645bb6c83e4225c04d64cfb62de6e
with:
url: ${{ steps.vault-auth.outputs.addr }}
caCertificate: ${{ steps.vault-auth.outputs.ca_certificate }}
token: ${{ steps.vault-auth.outputs.token }}
secrets: |
kv/data/github/hashicorp/vault-enterprise/github-token username-and-token | PRIVATE_REPO_GITHUB_TOKEN;
kv/data/github/hashicorp/vault-enterprise/license license_1 | VAULT_LICENSE;
- id: setup-git
name: Setup Git
if: github.repository == 'hashicorp/vault-enterprise'
run: |
git config --global url."https://${{ steps.secrets.outputs.PRIVATE_REPO_GITHUB_TOKEN }}@github.com".insteadOf https://github.com
- id: build-go-dev
name: build-go-dev
run: |
rm -rf ./pkg
mkdir ./pkg
make ci-bootstrap dev
- id: test-ui
name: test-ui
env:
VAULT_LICENSE: ${{ steps.secrets.outputs.VAULT_LICENSE }}
run: |
export PATH="${PWD}/bin:${PATH}"
if [ "${{ github.repository }}" == 'hashicorp/vault' ] ; then
export VAULT_LICENSE="${{ secrets.VAULT_LICENSE }}"
fi
# Run Ember tests
cd ui
mkdir -p test-results/qunit
yarn test:oss
- uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # v3.1.2
with:
name: test-results-ui
path: ui/test-results
if: success() || failure()
- uses: test-summary/action@62bc5c68de2a6a0d02039763b8c754569df99e3f # v2.1
with:
paths: "ui/test-results/qunit/results.xml"
show: "fail"
if: always()
tests-completed:
needs:
- setup
- test-go
- test-ui
if: always()
runs-on: ${{ fromJSON(needs.setup.outputs.compute-small) }}
steps:
- run: |
tr -d '\n' <<< '${{ toJSON(needs.*.result) }}' | grep -q -v -E '(failure|cancelled)'
notify-tests-completed-failures-ce:
if: |
always() &&
github.repository == 'hashicorp/vault' &&
(needs.test-go.result == 'failure' ||
needs.test-go-testonly.result == 'failure' ||
needs.test-go-race.result == 'failure' ||
needs.test-ui.result == 'failure'
) && (github.ref_name == 'main' || startsWith(github.ref_name, 'release/'))
runs-on: ubuntu-latest
permissions:
id-token: write
contents: read
strategy:
fail-fast: false
needs:
- test-go
- test-go-testonly
- test-go-race
- test-ui
steps:
- name: send-notification
uses: slackapi/slack-github-action@e28cf165c92ffef168d23c5c9000cffc8a25e117 # v1.24.0
# We intentionally aren't using the following here since it's from an internal repo
# uses: hashicorp/cloud-gha-slack-notifier@730a033037b8e603adf99ebd3085f0fdfe75e2f4 #v1
env:
SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}
with:
channel-id: "C05AABYEA9Y" # sent to #feed-vault-ci-official, use "C05Q4D5V89W"/test-vault-ci-slack-integration for testing
payload: |
{
"text": "CE test failures on ${{ github.ref_name }}",
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": ":rotating_light: CE test failures on ${{ github.ref_name }} :rotating_light:",
"emoji": true
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "${{ needs.test-go.result != 'failure' && ':white_check_mark:' || ':x:' }} Go tests\n${{ needs.test-go-race.result != 'failure' && ':white_check_mark:' || ':x:' }} Go race tests\n${{ needs.test-go-testonly.result != 'failure' && ':white_check_mark:' || ':x:' }} Go testonly tests\n${{ needs.test-ui.result != 'failure' && ':white_check_mark:' || ':x:' }} UI tests"
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "View Failing Workflow",
"emoji": true
},
"url": "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
}
}
]
}
notify-tests-completed-failures-ent:
if: |
always() &&
github.repository == 'hashicorp/vault-enterprise' &&
(needs.test-go.result == 'failure' ||
needs.test-go-testonly.result == 'failure' ||
needs.test-go-fips.result == 'failure' ||
needs.test-go-race.result == 'failure' ||
needs.test-ui.result == 'failure'
) && (github.ref_name == 'main' || startsWith(github.ref_name, 'release/'))
runs-on: ['self-hosted', 'linux', 'small']
permissions:
id-token: write
contents: read
strategy:
fail-fast: false
needs:
- test-go
- test-go-testonly
- test-go-race
- test-go-fips
- test-ui
steps:
- id: vault-auth
name: Vault Authenticate
run: vault-auth
- id: secrets
name: Fetch Vault Secrets
uses: hashicorp/vault-action@130d1f5f4fe645bb6c83e4225c04d64cfb62de6e
with:
url: ${{ steps.vault-auth.outputs.addr }}
caCertificate: ${{ steps.vault-auth.outputs.ca_certificate }}
token: ${{ steps.vault-auth.outputs.token }}
secrets: |
kv/data/github/${{ github.repository }}/github_actions_notifications_bot token | SLACK_BOT_TOKEN;
- name: send-notification
uses: hashicorp/cloud-gha-slack-notifier@730a033037b8e603adf99ebd3085f0fdfe75e2f4 #v1
with:
channel-id: "C05AABYEA9Y" # sent to #feed-vault-ci-official, use "C05Q4D5V89W"/test-vault-ci-slack-integration for testing
slack-bot-token: ${{ steps.secrets.outputs.SLACK_BOT_TOKEN }}
payload: |
{
"text": "Enterprise test failures on ${{ github.ref_name }}",
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": ":rotating_light: Enterprise test failures on ${{ github.ref_name }} :rotating_light:",
"emoji": true
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "${{ needs.test-go.result != 'failure' && ':white_check_mark:' || ':x:' }} Go tests\n${{ needs.test-go-fips.result != 'failure' && ':white_check_mark:' || ':x:' }} Go FIPS tests\n${{ needs.test-go-race.result != 'failure' && ':white_check_mark:' || ':x:' }} Go race tests\n${{ needs.test-go-testonly.result != 'failure' && ':white_check_mark:' || ':x:' }} Go testonly tests\n${{ needs.test-ui.result != 'failure' && ':white_check_mark:' || ':x:' }} UI tests"
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "View Failing Workflow",
"emoji": true
},
"url": "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
}
}
]
}
test-summary:
name: Go test failures
runs-on: ubuntu-latest
if: |
always() &&
(needs.test-go.result == 'success' ||
needs.test-go.result == 'failure' ||
needs.test-go-fips.result == 'success' ||
needs.test-go-fips.result == 'failure' ||
needs.test-go-race.result == 'success' ||
needs.test-go-race.result == 'failure') &&
(github.repository != 'hashicorp/vault' ||
(github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name))
# The last check ensures this doesn't run on community-contributed PRs, who
# won't have the permissions to run this job.
needs:
- test-go
- test-go-fips
- test-go-race
steps:
- name: Download failure summary
uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # v3.0.2
with:
name: failure-summary
- name: Prepare failure summary
run: |
# Sort all of the summary table rows and push them to a temp file.
temp_file_name=temp-$(date +%s)
cat failure-summary-*.md | sort >> "$temp_file_name"
# If there are test failures, present them in a format of a GitHub Markdown table.
if [ -s "$temp_file_name" ]; then
# shellcheck disable=SC2129
# Here we create the headings for the summary table
echo "| Test Type | Package | Test | Elapsed | Runner Index | Logs |" >> "$GITHUB_STEP_SUMMARY"
echo "| --------- | ------- | ---- | ------- | ------------ | ---- |" >> "$GITHUB_STEP_SUMMARY"
# shellcheck disable=SC2002
cat "$temp_file_name" >> "$GITHUB_STEP_SUMMARY"
else
echo "### All Go tests passed! :white_check_mark:" >> "$GITHUB_STEP_SUMMARY"
fi
# the random EOF is needed for a multiline environment variable
EOF=$(dd if=/dev/urandom bs=15 count=1 status=none | base64)
# shellcheck disable=SC2129
echo "TABLE_TEST_RESULTS<<$EOF" >> "$GITHUB_ENV"
cat "$temp_file_name" >> "$GITHUB_ENV"
echo "$EOF" >> "$GITHUB_ENV"
- uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
- name: Create comment
if: github.head_ref != ''
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ github.event.pull_request.number }}
RUN_ID: ${{ github.run_id }}
REPO: ${{ github.event.repository.name }}
TABLE_DATA: ${{ env.TABLE_TEST_RESULTS }}
run: ./.github/scripts/report_failed_tests.sh
| .github/workflows/ci.yml | 1 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.25746893882751465,
0.00731529900804162,
0.0001615411601960659,
0.000262540765106678,
0.03737185522913933
] |
{
"id": 1,
"code_window": [
" with:\n",
" github-token: ${{ secrets.ELEVATED_GITHUB_TOKEN }}\n",
" no-restore: true # don't download them on a cache hit\n",
"\n",
" verify-changes:\n",
" name: Verify doc-ui only PRs\n",
" uses: ./.github/workflows/verify_changes.yml\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" # control checking out head instead of base ref by a GH label\n",
" # if checkout-head label is added to a PR, checkout HEAD otherwise checkout base_ref\n",
" - if: ${{ !contains(github.event.pull_request.labels.*.name, 'checkout-head') }}\n",
" run: echo \"CHECKOUT_REF=${{ github.base_ref }}\" >> \"$GITHUB_ENV\"\n",
" - if: ${{ contains(github.event.pull_request.labels.*.name, 'checkout-head') }}\n",
" run: echo \"CHECKOUT_REF=${{ github.event.pull_request.head.sha }}\" >> \"$GITHUB_ENV\"\n",
" - id: checkout-ref-output\n",
" run: echo \"checkout-ref=${{ env.CHECKOUT_REF }}\" >> \"$GITHUB_OUTPUT\"\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 61
} | ```release-note:security
Limited Unauthenticated Remove Peer: As of Vault 1.6, the remove-peer command
on DR secondaries did not require authentication. This issue impacts the
stability of HA architecture, as a bad actor could remove all standby
nodes from a DR
secondary. This issue affects Vault Enterprise 1.6.0 and 1.6.1, and is fixed in
1.6.2 (CVE-2021-3282).
```
| changelog/_2021Jan26.txt | 0 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.00016551194130443037,
0.00016551194130443037,
0.00016551194130443037,
0.00016551194130443037,
0
] |
{
"id": 1,
"code_window": [
" with:\n",
" github-token: ${{ secrets.ELEVATED_GITHUB_TOKEN }}\n",
" no-restore: true # don't download them on a cache hit\n",
"\n",
" verify-changes:\n",
" name: Verify doc-ui only PRs\n",
" uses: ./.github/workflows/verify_changes.yml\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" # control checking out head instead of base ref by a GH label\n",
" # if checkout-head label is added to a PR, checkout HEAD otherwise checkout base_ref\n",
" - if: ${{ !contains(github.event.pull_request.labels.*.name, 'checkout-head') }}\n",
" run: echo \"CHECKOUT_REF=${{ github.base_ref }}\" >> \"$GITHUB_ENV\"\n",
" - if: ${{ contains(github.event.pull_request.labels.*.name, 'checkout-head') }}\n",
" run: echo \"CHECKOUT_REF=${{ github.event.pull_request.head.sha }}\" >> \"$GITHUB_ENV\"\n",
" - id: checkout-ref-output\n",
" run: echo \"checkout-ref=${{ env.CHECKOUT_REF }}\" >> \"$GITHUB_OUTPUT\"\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 61
} | /**
* Copyright (c) HashiCorp, Inc.
* SPDX-License-Identifier: BUSL-1.1
*/
export { default } from 'core/components/doc-link';
| ui/lib/core/app/components/doc-link.js | 0 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.00017125395243056118,
0.00017125395243056118,
0.00017125395243056118,
0.00017125395243056118,
0
] |
{
"id": 1,
"code_window": [
" with:\n",
" github-token: ${{ secrets.ELEVATED_GITHUB_TOKEN }}\n",
" no-restore: true # don't download them on a cache hit\n",
"\n",
" verify-changes:\n",
" name: Verify doc-ui only PRs\n",
" uses: ./.github/workflows/verify_changes.yml\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" # control checking out head instead of base ref by a GH label\n",
" # if checkout-head label is added to a PR, checkout HEAD otherwise checkout base_ref\n",
" - if: ${{ !contains(github.event.pull_request.labels.*.name, 'checkout-head') }}\n",
" run: echo \"CHECKOUT_REF=${{ github.base_ref }}\" >> \"$GITHUB_ENV\"\n",
" - if: ${{ contains(github.event.pull_request.labels.*.name, 'checkout-head') }}\n",
" run: echo \"CHECKOUT_REF=${{ github.event.pull_request.head.sha }}\" >> \"$GITHUB_ENV\"\n",
" - id: checkout-ref-output\n",
" run: echo \"checkout-ref=${{ env.CHECKOUT_REF }}\" >> \"$GITHUB_OUTPUT\"\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 61
} | <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none" viewBox="0 0 20 20">
<path fill-rule="evenodd" stroke="var(--gray-5, #dbdbdc)" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M8.575 4.04838L1.51667 15.8317C1.22054 16.3445 1.21877 16.976 1.51202 17.4905C1.80528 18.005 2.34951 18.3252 2.94167 18.3317H17.0583C17.6505 18.3252 18.1947 18.005 18.488 17.4905C18.7812 16.976 18.7795 16.3445 18.4833 15.8317L11.425 4.04838C11.1229 3.55028 10.5826 3.24609 10 3.24609C9.41743 3.24609 8.87714 3.55028 8.575 4.04838Z" clip-rule="evenodd"/>
<path stroke="#E80134" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M10 8.33203V11.6654"/>
<ellipse cx="10" cy="15.0013" fill="#E80134" rx="0.833333" ry="0.833334"/>
</svg>
| website/public/img/icons/alert-triangle.svg | 0 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.00017014228797052056,
0.00017014228797052056,
0.00017014228797052056,
0.00017014228797052056,
0
] |
{
"id": 2,
"code_window": [
" go-arch: amd64\n",
" go-tags: '${{ needs.setup.outputs.go-tags }},deadlock'\n",
" runs-on: ${{ needs.setup.outputs.compute-large }}\n",
" enterprise: ${{ needs.setup.outputs.enterprise }}\n",
" test-timing-cache-key: go-test-timing-standard\n",
" secrets: inherit\n",
"\n",
" test-go-testonly:\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkout-ref: ${{ needs.setup.outputs.checkout-ref }}\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 87
} | name: CI
on:
pull_request:
# The default types for pull_request are [ opened, synchronize, reopened ].
# This is insufficient for our needs, since we're skipping stuff on PRs in
# draft mode. By adding the ready_for_review type, when a draft pr is marked
# ready, we run everything, including the stuff we'd have skipped up until now.
types: [opened, synchronize, reopened, ready_for_review]
push:
branches:
- main
- release/**
workflow_dispatch:
concurrency:
group: ${{ github.head_ref || github.run_id }}-ci
cancel-in-progress: true
jobs:
setup:
name: Setup
runs-on: ubuntu-latest
outputs:
compute-small: ${{ steps.setup-outputs.outputs.compute-small }}
compute-medium: ${{ steps.setup-outputs.outputs.compute-medium }}
compute-large: ${{ steps.setup-outputs.outputs.compute-large }}
compute-largem: ${{ steps.setup-outputs.outputs.compute-largem }}
compute-xlarge: ${{ steps.setup-outputs.outputs.compute-xlarge }}
enterprise: ${{ steps.setup-outputs.outputs.enterprise }}
go-tags: ${{ steps.setup-outputs.outputs.go-tags }}
steps:
- uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
- id: setup-outputs
name: Setup outputs
run: |
github_repository="${{ github.repository }}"
if [ "${github_repository##*/}" == "vault-enterprise" ] ; then
# shellcheck disable=SC2129
echo 'compute-small=["self-hosted","ondemand","linux","type=c6a.large"]' >> "$GITHUB_OUTPUT" # 2x vCPUs, 4 GiB RAM,
echo 'compute-medium=["self-hosted","ondemand","linux","type=c6a.xlarge"]' >> "$GITHUB_OUTPUT" # 4x vCPUs, 8 GiB RAM,
echo 'compute-large=["self-hosted","ondemand","linux","type=c6a.2xlarge","disk_gb=64"]' >> "$GITHUB_OUTPUT" # 8x vCPUs, 16 GiB RAM,
echo 'compute-largem=["self-hosted","ondemand","linux","type=m6a.2xlarge"]' >> "$GITHUB_OUTPUT" # 8x vCPUs, 32 GiB RAM,
echo 'compute-xlarge=["self-hosted","ondemand","linux","type=c6a.4xlarge"]' >> "$GITHUB_OUTPUT" # 16x vCPUs, 32 GiB RAM,
echo 'enterprise=1' >> "$GITHUB_OUTPUT"
echo 'go-tags=ent,enterprise' >> "$GITHUB_OUTPUT"
else
# shellcheck disable=SC2129
echo 'compute-small="ubuntu-latest"' >> "$GITHUB_OUTPUT" # 2x vCPUs, 7 GiB RAM, 14 GB SSD
echo 'compute-medium="custom-linux-small-vault-latest"' >> "$GITHUB_OUTPUT" # 8x vCPUs, 32 GiB RAM, 300 GB SSD
echo 'compute-large="custom-linux-medium-vault-latest"' >> "$GITHUB_OUTPUT" # 16x vCPUs, 64 GiB RAM, 600 GB SSD
echo 'compute-largem="custom-linux-medium-vault-latest"' >> "$GITHUB_OUTPUT" # 16x vCPUs, 64 GiB RAM, 600 GB SSD
echo 'compute-xlarge="custom-linux-xl-vault-latest"' >> "$GITHUB_OUTPUT" # 32x vCPUs, 128 GiB RAM, 1200 GB SSD
echo 'enterprise=' >> "$GITHUB_OUTPUT"
echo 'go-tags=' >> "$GITHUB_OUTPUT"
fi
- name: Ensure Go modules are cached
uses: ./.github/actions/set-up-go
with:
github-token: ${{ secrets.ELEVATED_GITHUB_TOKEN }}
no-restore: true # don't download them on a cache hit
verify-changes:
name: Verify doc-ui only PRs
uses: ./.github/workflows/verify_changes.yml
test-go:
name: Run Go tests
needs:
- setup
- verify-changes
# Don't run this job for docs/ui only PRs
if: |
needs.verify-changes.outputs.is_docs_change == 'false' &&
needs.verify-changes.outputs.is_ui_change == 'false'
uses: ./.github/workflows/test-go.yml
with:
# The regular Go tests use an extra runner to execute the
# binary-dependent tests. We isolate them there so that the
# other tests aren't slowed down waiting for a binary build.
binary-tests: true
total-runners: 16
go-arch: amd64
go-tags: '${{ needs.setup.outputs.go-tags }},deadlock'
runs-on: ${{ needs.setup.outputs.compute-large }}
enterprise: ${{ needs.setup.outputs.enterprise }}
test-timing-cache-key: go-test-timing-standard
secrets: inherit
test-go-testonly:
name: Run Go tests tagged with testonly
needs:
- setup
- verify-changes
# Don't run this job for docs/ui only PRs
if: |
needs.verify-changes.outputs.is_docs_change == 'false' &&
needs.verify-changes.outputs.is_ui_change == 'false'
uses: ./.github/workflows/test-go.yml
with:
testonly: true
total-runners: 2 # test runners cannot be less than 2
go-arch: amd64
go-tags: '${{ needs.setup.outputs.go-tags }},deadlock,testonly'
runs-on: ${{ needs.setup.outputs.compute-large }}
enterprise: ${{ needs.setup.outputs.enterprise }}
test-timing-cache-enabled: false
secrets: inherit
test-go-race:
name: Run Go tests with data race detection
needs:
- setup
- verify-changes
# Don't run this job for docs/ui only PRs
if: |
github.event.pull_request.draft == false &&
needs.verify-changes.outputs.is_docs_change == 'false' &&
needs.verify-changes.outputs.is_ui_change == 'false'
uses: ./.github/workflows/test-go.yml
with:
total-runners: 16
env-vars: |
{
"VAULT_CI_GO_TEST_RACE": 1
}
extra-flags: '-race'
go-arch: amd64
go-tags: ${{ needs.setup.outputs.go-tags }}
runs-on: ${{ needs.setup.outputs.compute-large }}
enterprise: ${{ needs.setup.outputs.enterprise }}
name: "race"
test-timing-cache-key: go-test-timing-race
secrets: inherit
test-go-fips:
name: Run Go tests with FIPS configuration
# Only run this job for the enterprise repo if the PR is not docs/ui only
if: |
github.event.pull_request.draft == false &&
needs.setup.outputs.enterprise == 1 &&
needs.verify-changes.outputs.is_docs_change == 'false' &&
needs.verify-changes.outputs.is_ui_change == 'false'
needs:
- setup
- verify-changes
uses: ./.github/workflows/test-go.yml
with:
total-runners: 16
env-vars: |
{
"GOEXPERIMENT": "boringcrypto"
}
go-arch: amd64
go-tags: '${{ needs.setup.outputs.go-tags }},deadlock,cgo,fips,fips_140_2'
runs-on: ${{ needs.setup.outputs.compute-large }}
enterprise: ${{ needs.setup.outputs.enterprise }}
name: "fips"
test-timing-cache-key: go-test-timing-fips
secrets: inherit
test-ui:
name: Test UI
# The test-ui job is only run on:
# - pushes to main and branches starting with "release/"
# - PRs where the branch starts with "ui/", "backport/ui/", "merge", or when base branch starts with "release/"
# - PRs with the "ui" label on GitHub
if: |
github.ref_name == 'main' ||
startsWith(github.ref_name, 'release/') ||
startsWith(github.head_ref, 'ui/') ||
startsWith(github.head_ref, 'backport/ui/') ||
startsWith(github.head_ref, 'merge') ||
contains(github.event.pull_request.labels.*.name, 'ui')
needs:
- setup
permissions:
id-token: write
contents: read
runs-on: ${{ fromJSON(needs.setup.outputs.compute-largem) }}
steps:
- uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
- uses: ./.github/actions/set-up-go
with:
github-token: ${{ secrets.ELEVATED_GITHUB_TOKEN }}
# Setup node.js without caching to allow running npm install -g yarn (next step)
- uses: actions/setup-node@e33196f7422957bea03ed53f6fbb155025ffc7b8 # v3.7.0
with:
node-version-file: './ui/package.json'
- id: install-yarn
run: |
npm install -g yarn
# Setup node.js with caching using the yarn.lock file
- uses: actions/setup-node@e33196f7422957bea03ed53f6fbb155025ffc7b8 # v3.7.0
with:
node-version-file: './ui/package.json'
cache: yarn
cache-dependency-path: ui/yarn.lock
- id: install-browser
uses: browser-actions/setup-chrome@c485fa3bab6be59dce18dbc18ef6ab7cbc8ff5f1 # v1.2.0
- id: ui-dependencies
name: ui-dependencies
working-directory: ./ui
run: |
yarn install --frozen-lockfile
npm rebuild node-sass
- id: vault-auth
name: Authenticate to Vault
if: github.repository == 'hashicorp/vault-enterprise'
run: vault-auth
- id: secrets
name: Fetch secrets
if: github.repository == 'hashicorp/vault-enterprise'
uses: hashicorp/vault-action@130d1f5f4fe645bb6c83e4225c04d64cfb62de6e
with:
url: ${{ steps.vault-auth.outputs.addr }}
caCertificate: ${{ steps.vault-auth.outputs.ca_certificate }}
token: ${{ steps.vault-auth.outputs.token }}
secrets: |
kv/data/github/hashicorp/vault-enterprise/github-token username-and-token | PRIVATE_REPO_GITHUB_TOKEN;
kv/data/github/hashicorp/vault-enterprise/license license_1 | VAULT_LICENSE;
- id: setup-git
name: Setup Git
if: github.repository == 'hashicorp/vault-enterprise'
run: |
git config --global url."https://${{ steps.secrets.outputs.PRIVATE_REPO_GITHUB_TOKEN }}@github.com".insteadOf https://github.com
- id: build-go-dev
name: build-go-dev
run: |
rm -rf ./pkg
mkdir ./pkg
make ci-bootstrap dev
- id: test-ui
name: test-ui
env:
VAULT_LICENSE: ${{ steps.secrets.outputs.VAULT_LICENSE }}
run: |
export PATH="${PWD}/bin:${PATH}"
if [ "${{ github.repository }}" == 'hashicorp/vault' ] ; then
export VAULT_LICENSE="${{ secrets.VAULT_LICENSE }}"
fi
# Run Ember tests
cd ui
mkdir -p test-results/qunit
yarn test:oss
- uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # v3.1.2
with:
name: test-results-ui
path: ui/test-results
if: success() || failure()
- uses: test-summary/action@62bc5c68de2a6a0d02039763b8c754569df99e3f # v2.1
with:
paths: "ui/test-results/qunit/results.xml"
show: "fail"
if: always()
tests-completed:
needs:
- setup
- test-go
- test-ui
if: always()
runs-on: ${{ fromJSON(needs.setup.outputs.compute-small) }}
steps:
- run: |
tr -d '\n' <<< '${{ toJSON(needs.*.result) }}' | grep -q -v -E '(failure|cancelled)'
notify-tests-completed-failures-ce:
if: |
always() &&
github.repository == 'hashicorp/vault' &&
(needs.test-go.result == 'failure' ||
needs.test-go-testonly.result == 'failure' ||
needs.test-go-race.result == 'failure' ||
needs.test-ui.result == 'failure'
) && (github.ref_name == 'main' || startsWith(github.ref_name, 'release/'))
runs-on: ubuntu-latest
permissions:
id-token: write
contents: read
strategy:
fail-fast: false
needs:
- test-go
- test-go-testonly
- test-go-race
- test-ui
steps:
- name: send-notification
uses: slackapi/slack-github-action@e28cf165c92ffef168d23c5c9000cffc8a25e117 # v1.24.0
# We intentionally aren't using the following here since it's from an internal repo
# uses: hashicorp/cloud-gha-slack-notifier@730a033037b8e603adf99ebd3085f0fdfe75e2f4 #v1
env:
SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}
with:
channel-id: "C05AABYEA9Y" # sent to #feed-vault-ci-official, use "C05Q4D5V89W"/test-vault-ci-slack-integration for testing
payload: |
{
"text": "CE test failures on ${{ github.ref_name }}",
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": ":rotating_light: CE test failures on ${{ github.ref_name }} :rotating_light:",
"emoji": true
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "${{ needs.test-go.result != 'failure' && ':white_check_mark:' || ':x:' }} Go tests\n${{ needs.test-go-race.result != 'failure' && ':white_check_mark:' || ':x:' }} Go race tests\n${{ needs.test-go-testonly.result != 'failure' && ':white_check_mark:' || ':x:' }} Go testonly tests\n${{ needs.test-ui.result != 'failure' && ':white_check_mark:' || ':x:' }} UI tests"
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "View Failing Workflow",
"emoji": true
},
"url": "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
}
}
]
}
notify-tests-completed-failures-ent:
if: |
always() &&
github.repository == 'hashicorp/vault-enterprise' &&
(needs.test-go.result == 'failure' ||
needs.test-go-testonly.result == 'failure' ||
needs.test-go-fips.result == 'failure' ||
needs.test-go-race.result == 'failure' ||
needs.test-ui.result == 'failure'
) && (github.ref_name == 'main' || startsWith(github.ref_name, 'release/'))
runs-on: ['self-hosted', 'linux', 'small']
permissions:
id-token: write
contents: read
strategy:
fail-fast: false
needs:
- test-go
- test-go-testonly
- test-go-race
- test-go-fips
- test-ui
steps:
- id: vault-auth
name: Vault Authenticate
run: vault-auth
- id: secrets
name: Fetch Vault Secrets
uses: hashicorp/vault-action@130d1f5f4fe645bb6c83e4225c04d64cfb62de6e
with:
url: ${{ steps.vault-auth.outputs.addr }}
caCertificate: ${{ steps.vault-auth.outputs.ca_certificate }}
token: ${{ steps.vault-auth.outputs.token }}
secrets: |
kv/data/github/${{ github.repository }}/github_actions_notifications_bot token | SLACK_BOT_TOKEN;
- name: send-notification
uses: hashicorp/cloud-gha-slack-notifier@730a033037b8e603adf99ebd3085f0fdfe75e2f4 #v1
with:
channel-id: "C05AABYEA9Y" # sent to #feed-vault-ci-official, use "C05Q4D5V89W"/test-vault-ci-slack-integration for testing
slack-bot-token: ${{ steps.secrets.outputs.SLACK_BOT_TOKEN }}
payload: |
{
"text": "Enterprise test failures on ${{ github.ref_name }}",
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": ":rotating_light: Enterprise test failures on ${{ github.ref_name }} :rotating_light:",
"emoji": true
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "${{ needs.test-go.result != 'failure' && ':white_check_mark:' || ':x:' }} Go tests\n${{ needs.test-go-fips.result != 'failure' && ':white_check_mark:' || ':x:' }} Go FIPS tests\n${{ needs.test-go-race.result != 'failure' && ':white_check_mark:' || ':x:' }} Go race tests\n${{ needs.test-go-testonly.result != 'failure' && ':white_check_mark:' || ':x:' }} Go testonly tests\n${{ needs.test-ui.result != 'failure' && ':white_check_mark:' || ':x:' }} UI tests"
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "View Failing Workflow",
"emoji": true
},
"url": "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
}
}
]
}
test-summary:
name: Go test failures
runs-on: ubuntu-latest
if: |
always() &&
(needs.test-go.result == 'success' ||
needs.test-go.result == 'failure' ||
needs.test-go-fips.result == 'success' ||
needs.test-go-fips.result == 'failure' ||
needs.test-go-race.result == 'success' ||
needs.test-go-race.result == 'failure') &&
(github.repository != 'hashicorp/vault' ||
(github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name))
# The last check ensures this doesn't run on community-contributed PRs, who
# won't have the permissions to run this job.
needs:
- test-go
- test-go-fips
- test-go-race
steps:
- name: Download failure summary
uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # v3.0.2
with:
name: failure-summary
- name: Prepare failure summary
run: |
# Sort all of the summary table rows and push them to a temp file.
temp_file_name=temp-$(date +%s)
cat failure-summary-*.md | sort >> "$temp_file_name"
# If there are test failures, present them in a format of a GitHub Markdown table.
if [ -s "$temp_file_name" ]; then
# shellcheck disable=SC2129
# Here we create the headings for the summary table
echo "| Test Type | Package | Test | Elapsed | Runner Index | Logs |" >> "$GITHUB_STEP_SUMMARY"
echo "| --------- | ------- | ---- | ------- | ------------ | ---- |" >> "$GITHUB_STEP_SUMMARY"
# shellcheck disable=SC2002
cat "$temp_file_name" >> "$GITHUB_STEP_SUMMARY"
else
echo "### All Go tests passed! :white_check_mark:" >> "$GITHUB_STEP_SUMMARY"
fi
# the random EOF is needed for a multiline environment variable
EOF=$(dd if=/dev/urandom bs=15 count=1 status=none | base64)
# shellcheck disable=SC2129
echo "TABLE_TEST_RESULTS<<$EOF" >> "$GITHUB_ENV"
cat "$temp_file_name" >> "$GITHUB_ENV"
echo "$EOF" >> "$GITHUB_ENV"
- uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
- name: Create comment
if: github.head_ref != ''
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ github.event.pull_request.number }}
RUN_ID: ${{ github.run_id }}
REPO: ${{ github.event.repository.name }}
TABLE_DATA: ${{ env.TABLE_TEST_RESULTS }}
run: ./.github/scripts/report_failed_tests.sh
| .github/workflows/ci.yml | 1 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.6083433032035828,
0.0173825453966856,
0.00016382045578211546,
0.0005019571399316192,
0.08868836611509323
] |
{
"id": 2,
"code_window": [
" go-arch: amd64\n",
" go-tags: '${{ needs.setup.outputs.go-tags }},deadlock'\n",
" runs-on: ${{ needs.setup.outputs.compute-large }}\n",
" enterprise: ${{ needs.setup.outputs.enterprise }}\n",
" test-timing-cache-key: go-test-timing-standard\n",
" secrets: inherit\n",
"\n",
" test-go-testonly:\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkout-ref: ${{ needs.setup.outputs.checkout-ref }}\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 87
} | ---
layout: docs
page_title: Vault HA upgrades without Autopilot Upgrade Automation (Pre 1.11)
description: |-
Upgrade instructions for Vault HA Pre 1.11 or Vault without autopilot upgrade automation being enabled. Be sure to read the Upgrading-Vault Guides as well.
---
# Vault HA upgrades without autopilot upgrade automation (Pre 1.11)
This is our recommended upgrade procedure if **one** of the following applies:
- Running Vault version earlier than 1.11
- Opt-out the [Autopilot automated upgrade](/vault/docs/concepts/integrated-storage/autopilot#automated-upgrade) features with Vault 1.11 or later
- Running Vault with external storage backend such as Consul
You should consider how to apply the steps described in this document to your
particular setup since HA setups can differ on whether a load balancer is in
use, what addresses clients are being given to connect to Vault (standby +
leader, leader-only, or discovered via service discovery), etc.
If you are running on Vault 1.11+ with Integrated Storage and wish to enable the
Autopilot upgrade automation features, read to the [automated
upgrades](/vault/docs/concepts/integrated-storage/autopilot#automated-upgrades)
documentation for details and the [Automate Upgrades with Vault
Enterprise](/vault/tutorials/raft/raft-upgrade-automation) tutorial for
additional guidance.
## HA installations
Regardless of the method you use, do not fail over from a newer version of Vault
to an older version. Our suggested procedure is designed to prevent this.
Please note that Vault does not support true zero-downtime upgrades, but with
proper upgrade procedure the downtime should be very short (a few hundred
milliseconds to a second depending on how the speed of access to the storage
backend).
<Warning title="Important">
If you are currently running on Vault 1.11+ with Integrated Storage and have
chosen to opt-out the Autopilot automated upgrade features, please disable the
default automated upgrade migrations feature of the Vault. To disable this
feature, follow the [Automate Upgrades with Vault Enterprise Autopilot
configuration](/vault/tutorials/raft/raft-upgrade-automation#autopilot-configuration)
tutorial for more details. Without disabling this feature, you may run into Lost
Quorum issue as described in the [Quorum lost while upgrading the vault from
1.11.0 to later version of
it](https://support.hashicorp.com/hc/en-us/articles/7122445204755-Quorum-lost-while-upgrading-the-vault-from-1-11-0-to-later-version-of-it)
article.
</Warning>
Perform these steps on each standby:
1. Properly shut down Vault on the standby node via `SIGINT` or `SIGTERM`
2. Replace the Vault binary with the new version; ensure that `mlock()`
capability is added to the new binary with
[setcap](/vault/docs/configuration#disable_mlock)
3. Start the standby node
4. Unseal the standby node
5. Verify `vault status` shows correct Version and HA Mode is `standby`
6. Review the node's logs to ensure successful startup and unseal
At this point all standby nodes are upgraded and ready to take over. The
upgrade will not complete until one of the upgraded standby nodes takes over
active duty.
To complete the cluster upgrade:
1. Properly shut down the remaining (active) node
<Note>
It is important that you shut the node down properly.
This will perform a step-down and release the HA lock, allowing a standby
node to take over with a very short delay.
If you kill Vault without letting it release the lock, a standby node will
not be able to take over until the lock's timeout period has expired. This
is backend-specific but could be ten seconds or more.
</Note>
2. Replace the Vault binary with the new version; ensure that `mlock()`
capability is added to the new binary with
[setcap](/vault/docs/configuration#disable_mlock)
3. Start the node
4. Unseal the node
5. Verify `vault status` shows correct Version and HA Mode is `standby`
6. Review the node's logs to ensure successful startup and unseal
Internal upgrade tasks will happen after one of the upgraded standby nodes
takes over active duty.
Be sure to also read and follow any instructions in the version-specific
upgrade notes.
## Enterprise replication installations
See the main [upgrading](/vault/docs/upgrading#enterprise-replication-installations) page.
| website/content/docs/upgrading/vault-ha-upgrade.mdx | 0 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.00017384755483362824,
0.00016735584358684719,
0.00016093466547317803,
0.00016793528629932553,
0.000003702926505866344
] |
{
"id": 2,
"code_window": [
" go-arch: amd64\n",
" go-tags: '${{ needs.setup.outputs.go-tags }},deadlock'\n",
" runs-on: ${{ needs.setup.outputs.compute-large }}\n",
" enterprise: ${{ needs.setup.outputs.enterprise }}\n",
" test-timing-cache-key: go-test-timing-standard\n",
" secrets: inherit\n",
"\n",
" test-go-testonly:\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkout-ref: ${{ needs.setup.outputs.checkout-ref }}\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 87
} | ---
layout: api
page_title: /sys/config/cors - HTTP API
description: >-
The '/sys/config/cors' endpoint configures how the Vault server responds to
cross-origin requests.
---
# `/sys/config/cors`
@include 'alerts/restricted-root.mdx'
The `/sys/config/cors` endpoint is used to configure CORS settings.
- **`sudo` required** – All CORS endpoints require `sudo` capability in
addition to any path-specific capabilities.
## Read CORS settings
This endpoint returns the current CORS configuration.
| Method | Path |
| :----- | :----------------- |
| `GET` | `/sys/config/cors` |
### Sample request
```shell-session
$ curl \
--header "X-Vault-Token: ..." \
http://127.0.0.1:8200/v1/sys/config/cors
```
### Sample response
```json
{
"enabled": true,
"allowed_origins": ["http://www.example.com"],
"allowed_headers": [
"Content-Type",
"X-Requested-With",
"X-Vault-AWS-IAM-Server-ID",
"X-Vault-No-Request-Forwarding",
"X-Vault-Token",
"Authorization",
"X-Vault-Wrap-Format",
"X-Vault-Wrap-TTL"
]
}
```
## Configure CORS settings
This endpoint allows configuring the origins that are permitted to make
cross-origin requests, as well as headers that are allowed on cross-origin requests.
| Method | Path |
| :----- | :----------------- |
| `POST` | `/sys/config/cors` |
### Parameters
- `allowed_origins` `(string or string array: <required>)` – A wildcard (`*`), comma-delimited string, or array of strings specifying the origins that are permitted to make cross-origin requests.
- `allowed_headers` `(string or string array: "" or [])` – A comma-delimited string or array of strings specifying headers that are permitted to be on cross-origin requests. Headers set via this parameter will be appended to the list of headers that Vault allows by default.
### Sample payload
```json
{
"allowed_origins": "*",
"allowed_headers": "X-Custom-Header"
}
```
### Sample request
```shell-session
$ curl \
--header "X-Vault-Token: ..." \
--request POST \
--data @payload.json \
http://127.0.0.1:8200/v1/sys/config/cors
```
## Delete CORS settings
This endpoint removes any CORS configuration.
| Method | Path |
| :------- | :----------------- |
| `DELETE` | `/sys/config/cors` |
### Sample request
```shell-session
$ curl \
--header "X-Vault-Token: ..." \
--request DELETE \
http://127.0.0.1:8200/v1/sys/config/cors
```
| website/content/api-docs/system/config-cors.mdx | 0 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.00031311361817643046,
0.00018367386655882,
0.0001638140674913302,
0.00017250195378437638,
0.000041027440602192655
] |
{
"id": 2,
"code_window": [
" go-arch: amd64\n",
" go-tags: '${{ needs.setup.outputs.go-tags }},deadlock'\n",
" runs-on: ${{ needs.setup.outputs.compute-large }}\n",
" enterprise: ${{ needs.setup.outputs.enterprise }}\n",
" test-timing-cache-key: go-test-timing-standard\n",
" secrets: inherit\n",
"\n",
" test-go-testonly:\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkout-ref: ${{ needs.setup.outputs.checkout-ref }}\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 87
} | // Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package event
import (
"testing"
"github.com/stretchr/testify/require"
)
// TestEventType_Validate exercises the Validate method for EventType.
func TestEventType_Validate(t *testing.T) {
tests := map[string]struct {
Value string
IsValid bool
ExpectedError string
}{
"audit": {
Value: "audit",
IsValid: true,
},
"empty": {
Value: "",
IsValid: false,
ExpectedError: "event.(EventType).Validate: '' is not a valid event type: invalid parameter",
},
"random": {
Value: "random",
IsValid: false,
ExpectedError: "event.(EventType).Validate: 'random' is not a valid event type: invalid parameter",
},
}
for name, tc := range tests {
name := name
tc := tc
t.Run(name, func(t *testing.T) {
t.Parallel()
eventType := EventType(tc.Value)
err := eventType.Validate()
switch {
case tc.IsValid:
require.NoError(t, err)
case !tc.IsValid:
require.Error(t, err)
require.EqualError(t, err, tc.ExpectedError)
}
})
}
}
| internal/observability/event/event_type_test.go | 0 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.00017783092334866524,
0.00017322303028777242,
0.00016414601122960448,
0.00017483861302025616,
0.00000438907682109857
] |
{
"id": 3,
"code_window": [
" go-tags: '${{ needs.setup.outputs.go-tags }},deadlock,testonly'\n",
" runs-on: ${{ needs.setup.outputs.compute-large }}\n",
" enterprise: ${{ needs.setup.outputs.enterprise }}\n",
" test-timing-cache-enabled: false\n",
" secrets: inherit\n",
"\n",
" test-go-race:\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkout-ref: ${{ needs.setup.outputs.checkout-ref }}\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 107
} | name: CI
on:
pull_request:
# The default types for pull_request are [ opened, synchronize, reopened ].
# This is insufficient for our needs, since we're skipping stuff on PRs in
# draft mode. By adding the ready_for_review type, when a draft pr is marked
# ready, we run everything, including the stuff we'd have skipped up until now.
types: [opened, synchronize, reopened, ready_for_review]
push:
branches:
- main
- release/**
workflow_dispatch:
concurrency:
group: ${{ github.head_ref || github.run_id }}-ci
cancel-in-progress: true
jobs:
setup:
name: Setup
runs-on: ubuntu-latest
outputs:
compute-small: ${{ steps.setup-outputs.outputs.compute-small }}
compute-medium: ${{ steps.setup-outputs.outputs.compute-medium }}
compute-large: ${{ steps.setup-outputs.outputs.compute-large }}
compute-largem: ${{ steps.setup-outputs.outputs.compute-largem }}
compute-xlarge: ${{ steps.setup-outputs.outputs.compute-xlarge }}
enterprise: ${{ steps.setup-outputs.outputs.enterprise }}
go-tags: ${{ steps.setup-outputs.outputs.go-tags }}
steps:
- uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
- id: setup-outputs
name: Setup outputs
run: |
github_repository="${{ github.repository }}"
if [ "${github_repository##*/}" == "vault-enterprise" ] ; then
# shellcheck disable=SC2129
echo 'compute-small=["self-hosted","ondemand","linux","type=c6a.large"]' >> "$GITHUB_OUTPUT" # 2x vCPUs, 4 GiB RAM,
echo 'compute-medium=["self-hosted","ondemand","linux","type=c6a.xlarge"]' >> "$GITHUB_OUTPUT" # 4x vCPUs, 8 GiB RAM,
echo 'compute-large=["self-hosted","ondemand","linux","type=c6a.2xlarge","disk_gb=64"]' >> "$GITHUB_OUTPUT" # 8x vCPUs, 16 GiB RAM,
echo 'compute-largem=["self-hosted","ondemand","linux","type=m6a.2xlarge"]' >> "$GITHUB_OUTPUT" # 8x vCPUs, 32 GiB RAM,
echo 'compute-xlarge=["self-hosted","ondemand","linux","type=c6a.4xlarge"]' >> "$GITHUB_OUTPUT" # 16x vCPUs, 32 GiB RAM,
echo 'enterprise=1' >> "$GITHUB_OUTPUT"
echo 'go-tags=ent,enterprise' >> "$GITHUB_OUTPUT"
else
# shellcheck disable=SC2129
echo 'compute-small="ubuntu-latest"' >> "$GITHUB_OUTPUT" # 2x vCPUs, 7 GiB RAM, 14 GB SSD
echo 'compute-medium="custom-linux-small-vault-latest"' >> "$GITHUB_OUTPUT" # 8x vCPUs, 32 GiB RAM, 300 GB SSD
echo 'compute-large="custom-linux-medium-vault-latest"' >> "$GITHUB_OUTPUT" # 16x vCPUs, 64 GiB RAM, 600 GB SSD
echo 'compute-largem="custom-linux-medium-vault-latest"' >> "$GITHUB_OUTPUT" # 16x vCPUs, 64 GiB RAM, 600 GB SSD
echo 'compute-xlarge="custom-linux-xl-vault-latest"' >> "$GITHUB_OUTPUT" # 32x vCPUs, 128 GiB RAM, 1200 GB SSD
echo 'enterprise=' >> "$GITHUB_OUTPUT"
echo 'go-tags=' >> "$GITHUB_OUTPUT"
fi
- name: Ensure Go modules are cached
uses: ./.github/actions/set-up-go
with:
github-token: ${{ secrets.ELEVATED_GITHUB_TOKEN }}
no-restore: true # don't download them on a cache hit
verify-changes:
name: Verify doc-ui only PRs
uses: ./.github/workflows/verify_changes.yml
test-go:
name: Run Go tests
needs:
- setup
- verify-changes
# Don't run this job for docs/ui only PRs
if: |
needs.verify-changes.outputs.is_docs_change == 'false' &&
needs.verify-changes.outputs.is_ui_change == 'false'
uses: ./.github/workflows/test-go.yml
with:
# The regular Go tests use an extra runner to execute the
# binary-dependent tests. We isolate them there so that the
# other tests aren't slowed down waiting for a binary build.
binary-tests: true
total-runners: 16
go-arch: amd64
go-tags: '${{ needs.setup.outputs.go-tags }},deadlock'
runs-on: ${{ needs.setup.outputs.compute-large }}
enterprise: ${{ needs.setup.outputs.enterprise }}
test-timing-cache-key: go-test-timing-standard
secrets: inherit
test-go-testonly:
name: Run Go tests tagged with testonly
needs:
- setup
- verify-changes
# Don't run this job for docs/ui only PRs
if: |
needs.verify-changes.outputs.is_docs_change == 'false' &&
needs.verify-changes.outputs.is_ui_change == 'false'
uses: ./.github/workflows/test-go.yml
with:
testonly: true
total-runners: 2 # test runners cannot be less than 2
go-arch: amd64
go-tags: '${{ needs.setup.outputs.go-tags }},deadlock,testonly'
runs-on: ${{ needs.setup.outputs.compute-large }}
enterprise: ${{ needs.setup.outputs.enterprise }}
test-timing-cache-enabled: false
secrets: inherit
test-go-race:
name: Run Go tests with data race detection
needs:
- setup
- verify-changes
# Don't run this job for docs/ui only PRs
if: |
github.event.pull_request.draft == false &&
needs.verify-changes.outputs.is_docs_change == 'false' &&
needs.verify-changes.outputs.is_ui_change == 'false'
uses: ./.github/workflows/test-go.yml
with:
total-runners: 16
env-vars: |
{
"VAULT_CI_GO_TEST_RACE": 1
}
extra-flags: '-race'
go-arch: amd64
go-tags: ${{ needs.setup.outputs.go-tags }}
runs-on: ${{ needs.setup.outputs.compute-large }}
enterprise: ${{ needs.setup.outputs.enterprise }}
name: "race"
test-timing-cache-key: go-test-timing-race
secrets: inherit
test-go-fips:
name: Run Go tests with FIPS configuration
# Only run this job for the enterprise repo if the PR is not docs/ui only
if: |
github.event.pull_request.draft == false &&
needs.setup.outputs.enterprise == 1 &&
needs.verify-changes.outputs.is_docs_change == 'false' &&
needs.verify-changes.outputs.is_ui_change == 'false'
needs:
- setup
- verify-changes
uses: ./.github/workflows/test-go.yml
with:
total-runners: 16
env-vars: |
{
"GOEXPERIMENT": "boringcrypto"
}
go-arch: amd64
go-tags: '${{ needs.setup.outputs.go-tags }},deadlock,cgo,fips,fips_140_2'
runs-on: ${{ needs.setup.outputs.compute-large }}
enterprise: ${{ needs.setup.outputs.enterprise }}
name: "fips"
test-timing-cache-key: go-test-timing-fips
secrets: inherit
test-ui:
name: Test UI
# The test-ui job is only run on:
# - pushes to main and branches starting with "release/"
# - PRs where the branch starts with "ui/", "backport/ui/", "merge", or when base branch starts with "release/"
# - PRs with the "ui" label on GitHub
if: |
github.ref_name == 'main' ||
startsWith(github.ref_name, 'release/') ||
startsWith(github.head_ref, 'ui/') ||
startsWith(github.head_ref, 'backport/ui/') ||
startsWith(github.head_ref, 'merge') ||
contains(github.event.pull_request.labels.*.name, 'ui')
needs:
- setup
permissions:
id-token: write
contents: read
runs-on: ${{ fromJSON(needs.setup.outputs.compute-largem) }}
steps:
- uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
- uses: ./.github/actions/set-up-go
with:
github-token: ${{ secrets.ELEVATED_GITHUB_TOKEN }}
# Setup node.js without caching to allow running npm install -g yarn (next step)
- uses: actions/setup-node@e33196f7422957bea03ed53f6fbb155025ffc7b8 # v3.7.0
with:
node-version-file: './ui/package.json'
- id: install-yarn
run: |
npm install -g yarn
# Setup node.js with caching using the yarn.lock file
- uses: actions/setup-node@e33196f7422957bea03ed53f6fbb155025ffc7b8 # v3.7.0
with:
node-version-file: './ui/package.json'
cache: yarn
cache-dependency-path: ui/yarn.lock
- id: install-browser
uses: browser-actions/setup-chrome@c485fa3bab6be59dce18dbc18ef6ab7cbc8ff5f1 # v1.2.0
- id: ui-dependencies
name: ui-dependencies
working-directory: ./ui
run: |
yarn install --frozen-lockfile
npm rebuild node-sass
- id: vault-auth
name: Authenticate to Vault
if: github.repository == 'hashicorp/vault-enterprise'
run: vault-auth
- id: secrets
name: Fetch secrets
if: github.repository == 'hashicorp/vault-enterprise'
uses: hashicorp/vault-action@130d1f5f4fe645bb6c83e4225c04d64cfb62de6e
with:
url: ${{ steps.vault-auth.outputs.addr }}
caCertificate: ${{ steps.vault-auth.outputs.ca_certificate }}
token: ${{ steps.vault-auth.outputs.token }}
secrets: |
kv/data/github/hashicorp/vault-enterprise/github-token username-and-token | PRIVATE_REPO_GITHUB_TOKEN;
kv/data/github/hashicorp/vault-enterprise/license license_1 | VAULT_LICENSE;
- id: setup-git
name: Setup Git
if: github.repository == 'hashicorp/vault-enterprise'
run: |
git config --global url."https://${{ steps.secrets.outputs.PRIVATE_REPO_GITHUB_TOKEN }}@github.com".insteadOf https://github.com
- id: build-go-dev
name: build-go-dev
run: |
rm -rf ./pkg
mkdir ./pkg
make ci-bootstrap dev
- id: test-ui
name: test-ui
env:
VAULT_LICENSE: ${{ steps.secrets.outputs.VAULT_LICENSE }}
run: |
export PATH="${PWD}/bin:${PATH}"
if [ "${{ github.repository }}" == 'hashicorp/vault' ] ; then
export VAULT_LICENSE="${{ secrets.VAULT_LICENSE }}"
fi
# Run Ember tests
cd ui
mkdir -p test-results/qunit
yarn test:oss
- uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # v3.1.2
with:
name: test-results-ui
path: ui/test-results
if: success() || failure()
- uses: test-summary/action@62bc5c68de2a6a0d02039763b8c754569df99e3f # v2.1
with:
paths: "ui/test-results/qunit/results.xml"
show: "fail"
if: always()
tests-completed:
needs:
- setup
- test-go
- test-ui
if: always()
runs-on: ${{ fromJSON(needs.setup.outputs.compute-small) }}
steps:
- run: |
tr -d '\n' <<< '${{ toJSON(needs.*.result) }}' | grep -q -v -E '(failure|cancelled)'
notify-tests-completed-failures-ce:
if: |
always() &&
github.repository == 'hashicorp/vault' &&
(needs.test-go.result == 'failure' ||
needs.test-go-testonly.result == 'failure' ||
needs.test-go-race.result == 'failure' ||
needs.test-ui.result == 'failure'
) && (github.ref_name == 'main' || startsWith(github.ref_name, 'release/'))
runs-on: ubuntu-latest
permissions:
id-token: write
contents: read
strategy:
fail-fast: false
needs:
- test-go
- test-go-testonly
- test-go-race
- test-ui
steps:
- name: send-notification
uses: slackapi/slack-github-action@e28cf165c92ffef168d23c5c9000cffc8a25e117 # v1.24.0
# We intentionally aren't using the following here since it's from an internal repo
# uses: hashicorp/cloud-gha-slack-notifier@730a033037b8e603adf99ebd3085f0fdfe75e2f4 #v1
env:
SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}
with:
channel-id: "C05AABYEA9Y" # sent to #feed-vault-ci-official, use "C05Q4D5V89W"/test-vault-ci-slack-integration for testing
payload: |
{
"text": "CE test failures on ${{ github.ref_name }}",
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": ":rotating_light: CE test failures on ${{ github.ref_name }} :rotating_light:",
"emoji": true
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "${{ needs.test-go.result != 'failure' && ':white_check_mark:' || ':x:' }} Go tests\n${{ needs.test-go-race.result != 'failure' && ':white_check_mark:' || ':x:' }} Go race tests\n${{ needs.test-go-testonly.result != 'failure' && ':white_check_mark:' || ':x:' }} Go testonly tests\n${{ needs.test-ui.result != 'failure' && ':white_check_mark:' || ':x:' }} UI tests"
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "View Failing Workflow",
"emoji": true
},
"url": "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
}
}
]
}
notify-tests-completed-failures-ent:
if: |
always() &&
github.repository == 'hashicorp/vault-enterprise' &&
(needs.test-go.result == 'failure' ||
needs.test-go-testonly.result == 'failure' ||
needs.test-go-fips.result == 'failure' ||
needs.test-go-race.result == 'failure' ||
needs.test-ui.result == 'failure'
) && (github.ref_name == 'main' || startsWith(github.ref_name, 'release/'))
runs-on: ['self-hosted', 'linux', 'small']
permissions:
id-token: write
contents: read
strategy:
fail-fast: false
needs:
- test-go
- test-go-testonly
- test-go-race
- test-go-fips
- test-ui
steps:
- id: vault-auth
name: Vault Authenticate
run: vault-auth
- id: secrets
name: Fetch Vault Secrets
uses: hashicorp/vault-action@130d1f5f4fe645bb6c83e4225c04d64cfb62de6e
with:
url: ${{ steps.vault-auth.outputs.addr }}
caCertificate: ${{ steps.vault-auth.outputs.ca_certificate }}
token: ${{ steps.vault-auth.outputs.token }}
secrets: |
kv/data/github/${{ github.repository }}/github_actions_notifications_bot token | SLACK_BOT_TOKEN;
- name: send-notification
uses: hashicorp/cloud-gha-slack-notifier@730a033037b8e603adf99ebd3085f0fdfe75e2f4 #v1
with:
channel-id: "C05AABYEA9Y" # sent to #feed-vault-ci-official, use "C05Q4D5V89W"/test-vault-ci-slack-integration for testing
slack-bot-token: ${{ steps.secrets.outputs.SLACK_BOT_TOKEN }}
payload: |
{
"text": "Enterprise test failures on ${{ github.ref_name }}",
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": ":rotating_light: Enterprise test failures on ${{ github.ref_name }} :rotating_light:",
"emoji": true
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "${{ needs.test-go.result != 'failure' && ':white_check_mark:' || ':x:' }} Go tests\n${{ needs.test-go-fips.result != 'failure' && ':white_check_mark:' || ':x:' }} Go FIPS tests\n${{ needs.test-go-race.result != 'failure' && ':white_check_mark:' || ':x:' }} Go race tests\n${{ needs.test-go-testonly.result != 'failure' && ':white_check_mark:' || ':x:' }} Go testonly tests\n${{ needs.test-ui.result != 'failure' && ':white_check_mark:' || ':x:' }} UI tests"
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "View Failing Workflow",
"emoji": true
},
"url": "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
}
}
]
}
test-summary:
name: Go test failures
runs-on: ubuntu-latest
if: |
always() &&
(needs.test-go.result == 'success' ||
needs.test-go.result == 'failure' ||
needs.test-go-fips.result == 'success' ||
needs.test-go-fips.result == 'failure' ||
needs.test-go-race.result == 'success' ||
needs.test-go-race.result == 'failure') &&
(github.repository != 'hashicorp/vault' ||
(github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name))
# The last check ensures this doesn't run on community-contributed PRs, who
# won't have the permissions to run this job.
needs:
- test-go
- test-go-fips
- test-go-race
steps:
- name: Download failure summary
uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # v3.0.2
with:
name: failure-summary
- name: Prepare failure summary
run: |
# Sort all of the summary table rows and push them to a temp file.
temp_file_name=temp-$(date +%s)
cat failure-summary-*.md | sort >> "$temp_file_name"
# If there are test failures, present them in a format of a GitHub Markdown table.
if [ -s "$temp_file_name" ]; then
# shellcheck disable=SC2129
# Here we create the headings for the summary table
echo "| Test Type | Package | Test | Elapsed | Runner Index | Logs |" >> "$GITHUB_STEP_SUMMARY"
echo "| --------- | ------- | ---- | ------- | ------------ | ---- |" >> "$GITHUB_STEP_SUMMARY"
# shellcheck disable=SC2002
cat "$temp_file_name" >> "$GITHUB_STEP_SUMMARY"
else
echo "### All Go tests passed! :white_check_mark:" >> "$GITHUB_STEP_SUMMARY"
fi
# the random EOF is needed for a multiline environment variable
EOF=$(dd if=/dev/urandom bs=15 count=1 status=none | base64)
# shellcheck disable=SC2129
echo "TABLE_TEST_RESULTS<<$EOF" >> "$GITHUB_ENV"
cat "$temp_file_name" >> "$GITHUB_ENV"
echo "$EOF" >> "$GITHUB_ENV"
- uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
- name: Create comment
if: github.head_ref != ''
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ github.event.pull_request.number }}
RUN_ID: ${{ github.run_id }}
REPO: ${{ github.event.repository.name }}
TABLE_DATA: ${{ env.TABLE_TEST_RESULTS }}
run: ./.github/scripts/report_failed_tests.sh
| .github/workflows/ci.yml | 1 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.486345112323761,
0.014562385156750679,
0.00016373395919799805,
0.00032243007444776595,
0.07256176322698593
] |
{
"id": 3,
"code_window": [
" go-tags: '${{ needs.setup.outputs.go-tags }},deadlock,testonly'\n",
" runs-on: ${{ needs.setup.outputs.compute-large }}\n",
" enterprise: ${{ needs.setup.outputs.enterprise }}\n",
" test-timing-cache-enabled: false\n",
" secrets: inherit\n",
"\n",
" test-go-race:\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkout-ref: ${{ needs.setup.outputs.checkout-ref }}\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 107
} | // Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package template
import (
"crypto/sha256"
"encoding/base64"
"fmt"
"strconv"
"strings"
"time"
UUID "github.com/hashicorp/go-uuid"
)
func unixTime() string {
return strconv.FormatInt(time.Now().Unix(), 10)
}
func unixTimeMillis() string {
return strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
}
func timestamp(format string) string {
return time.Now().Format(format)
}
func truncate(maxLen int, str string) (string, error) {
if maxLen <= 0 {
return "", fmt.Errorf("max length must be > 0 but was %d", maxLen)
}
if len(str) > maxLen {
return str[:maxLen], nil
}
return str, nil
}
const (
sha256HashLen = 8
)
func truncateSHA256(maxLen int, str string) (string, error) {
if maxLen <= 8 {
return "", fmt.Errorf("max length must be > 8 but was %d", maxLen)
}
if len(str) <= maxLen {
return str, nil
}
truncIndex := maxLen - sha256HashLen
hash := hashSHA256(str[truncIndex:])
result := fmt.Sprintf("%s%s", str[:truncIndex], hash[:sha256HashLen])
return result, nil
}
func hashSHA256(str string) string {
return fmt.Sprintf("%x", sha256.Sum256([]byte(str)))
}
func encodeBase64(str string) string {
return base64.StdEncoding.EncodeToString([]byte(str))
}
func uppercase(str string) string {
return strings.ToUpper(str)
}
func lowercase(str string) string {
return strings.ToLower(str)
}
func replace(find string, replace string, str string) string {
return strings.ReplaceAll(str, find, replace)
}
func uuid() (string, error) {
return UUID.GenerateUUID()
}
| sdk/helper/template/funcs.go | 0 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.001366359880194068,
0.00031585010583512485,
0.00016638459055684507,
0.0001762122119544074,
0.00037190382136031985
] |
{
"id": 3,
"code_window": [
" go-tags: '${{ needs.setup.outputs.go-tags }},deadlock,testonly'\n",
" runs-on: ${{ needs.setup.outputs.compute-large }}\n",
" enterprise: ${{ needs.setup.outputs.enterprise }}\n",
" test-timing-cache-enabled: false\n",
" secrets: inherit\n",
"\n",
" test-go-race:\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkout-ref: ${{ needs.setup.outputs.checkout-ref }}\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 107
} | /**
* Copyright (c) HashiCorp, Inc.
* SPDX-License-Identifier: BUSL-1.1
*/
import ClusterRoute from './cluster-route-base';
export default ClusterRoute.extend({});
| ui/app/routes/vault/cluster/init.js | 0 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.00017500178364571184,
0.00017500178364571184,
0.00017500178364571184,
0.00017500178364571184,
0
] |
{
"id": 3,
"code_window": [
" go-tags: '${{ needs.setup.outputs.go-tags }},deadlock,testonly'\n",
" runs-on: ${{ needs.setup.outputs.compute-large }}\n",
" enterprise: ${{ needs.setup.outputs.enterprise }}\n",
" test-timing-cache-enabled: false\n",
" secrets: inherit\n",
"\n",
" test-go-race:\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkout-ref: ${{ needs.setup.outputs.checkout-ref }}\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 107
} | /**
* Copyright (c) HashiCorp, Inc.
* SPDX-License-Identifier: BUSL-1.1
*/
import { resolve } from 'rsvp';
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
module('Unit | Adapter | secret', function (hooks) {
setupTest(hooks);
test('secret api urls', function (assert) {
let url, method, options;
const adapter = this.owner.factoryFor('adapter:secret').create({
ajax: (...args) => {
[url, method, options] = args;
return resolve({});
},
});
adapter.query({}, 'secret', { id: '', backend: 'secret' });
assert.strictEqual(url, '/v1/secret/', 'query generic url OK');
assert.strictEqual(method, 'GET', 'query generic method OK');
assert.deepEqual(options, { data: { list: true } }, 'query generic url OK');
adapter.queryRecord({}, 'secret', { id: 'foo', backend: 'secret' });
assert.strictEqual(url, '/v1/secret/foo', 'queryRecord generic url OK');
assert.strictEqual(method, 'GET', 'queryRecord generic method OK');
});
});
| ui/tests/unit/adapters/secret-test.js | 0 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.0002257182786706835,
0.00018532818648964167,
0.00016671523917466402,
0.00017443959950469434,
0.00002356633558520116
] |
{
"id": 4,
"code_window": [
" runs-on: ${{ needs.setup.outputs.compute-large }}\n",
" enterprise: ${{ needs.setup.outputs.enterprise }}\n",
" name: \"race\"\n",
" test-timing-cache-key: go-test-timing-race\n",
" secrets: inherit\n",
"\n",
" test-go-fips:\n",
" name: Run Go tests with FIPS configuration\n",
" # Only run this job for the enterprise repo if the PR is not docs/ui only\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkout-ref: ${{ needs.setup.outputs.checkout-ref }}\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 133
} | name: CI
on:
pull_request:
# The default types for pull_request are [ opened, synchronize, reopened ].
# This is insufficient for our needs, since we're skipping stuff on PRs in
# draft mode. By adding the ready_for_review type, when a draft pr is marked
# ready, we run everything, including the stuff we'd have skipped up until now.
types: [opened, synchronize, reopened, ready_for_review]
push:
branches:
- main
- release/**
workflow_dispatch:
concurrency:
group: ${{ github.head_ref || github.run_id }}-ci
cancel-in-progress: true
jobs:
setup:
name: Setup
runs-on: ubuntu-latest
outputs:
compute-small: ${{ steps.setup-outputs.outputs.compute-small }}
compute-medium: ${{ steps.setup-outputs.outputs.compute-medium }}
compute-large: ${{ steps.setup-outputs.outputs.compute-large }}
compute-largem: ${{ steps.setup-outputs.outputs.compute-largem }}
compute-xlarge: ${{ steps.setup-outputs.outputs.compute-xlarge }}
enterprise: ${{ steps.setup-outputs.outputs.enterprise }}
go-tags: ${{ steps.setup-outputs.outputs.go-tags }}
steps:
- uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
- id: setup-outputs
name: Setup outputs
run: |
github_repository="${{ github.repository }}"
if [ "${github_repository##*/}" == "vault-enterprise" ] ; then
# shellcheck disable=SC2129
echo 'compute-small=["self-hosted","ondemand","linux","type=c6a.large"]' >> "$GITHUB_OUTPUT" # 2x vCPUs, 4 GiB RAM,
echo 'compute-medium=["self-hosted","ondemand","linux","type=c6a.xlarge"]' >> "$GITHUB_OUTPUT" # 4x vCPUs, 8 GiB RAM,
echo 'compute-large=["self-hosted","ondemand","linux","type=c6a.2xlarge","disk_gb=64"]' >> "$GITHUB_OUTPUT" # 8x vCPUs, 16 GiB RAM,
echo 'compute-largem=["self-hosted","ondemand","linux","type=m6a.2xlarge"]' >> "$GITHUB_OUTPUT" # 8x vCPUs, 32 GiB RAM,
echo 'compute-xlarge=["self-hosted","ondemand","linux","type=c6a.4xlarge"]' >> "$GITHUB_OUTPUT" # 16x vCPUs, 32 GiB RAM,
echo 'enterprise=1' >> "$GITHUB_OUTPUT"
echo 'go-tags=ent,enterprise' >> "$GITHUB_OUTPUT"
else
# shellcheck disable=SC2129
echo 'compute-small="ubuntu-latest"' >> "$GITHUB_OUTPUT" # 2x vCPUs, 7 GiB RAM, 14 GB SSD
echo 'compute-medium="custom-linux-small-vault-latest"' >> "$GITHUB_OUTPUT" # 8x vCPUs, 32 GiB RAM, 300 GB SSD
echo 'compute-large="custom-linux-medium-vault-latest"' >> "$GITHUB_OUTPUT" # 16x vCPUs, 64 GiB RAM, 600 GB SSD
echo 'compute-largem="custom-linux-medium-vault-latest"' >> "$GITHUB_OUTPUT" # 16x vCPUs, 64 GiB RAM, 600 GB SSD
echo 'compute-xlarge="custom-linux-xl-vault-latest"' >> "$GITHUB_OUTPUT" # 32x vCPUs, 128 GiB RAM, 1200 GB SSD
echo 'enterprise=' >> "$GITHUB_OUTPUT"
echo 'go-tags=' >> "$GITHUB_OUTPUT"
fi
- name: Ensure Go modules are cached
uses: ./.github/actions/set-up-go
with:
github-token: ${{ secrets.ELEVATED_GITHUB_TOKEN }}
no-restore: true # don't download them on a cache hit
verify-changes:
name: Verify doc-ui only PRs
uses: ./.github/workflows/verify_changes.yml
test-go:
name: Run Go tests
needs:
- setup
- verify-changes
# Don't run this job for docs/ui only PRs
if: |
needs.verify-changes.outputs.is_docs_change == 'false' &&
needs.verify-changes.outputs.is_ui_change == 'false'
uses: ./.github/workflows/test-go.yml
with:
# The regular Go tests use an extra runner to execute the
# binary-dependent tests. We isolate them there so that the
# other tests aren't slowed down waiting for a binary build.
binary-tests: true
total-runners: 16
go-arch: amd64
go-tags: '${{ needs.setup.outputs.go-tags }},deadlock'
runs-on: ${{ needs.setup.outputs.compute-large }}
enterprise: ${{ needs.setup.outputs.enterprise }}
test-timing-cache-key: go-test-timing-standard
secrets: inherit
test-go-testonly:
name: Run Go tests tagged with testonly
needs:
- setup
- verify-changes
# Don't run this job for docs/ui only PRs
if: |
needs.verify-changes.outputs.is_docs_change == 'false' &&
needs.verify-changes.outputs.is_ui_change == 'false'
uses: ./.github/workflows/test-go.yml
with:
testonly: true
total-runners: 2 # test runners cannot be less than 2
go-arch: amd64
go-tags: '${{ needs.setup.outputs.go-tags }},deadlock,testonly'
runs-on: ${{ needs.setup.outputs.compute-large }}
enterprise: ${{ needs.setup.outputs.enterprise }}
test-timing-cache-enabled: false
secrets: inherit
test-go-race:
name: Run Go tests with data race detection
needs:
- setup
- verify-changes
# Don't run this job for docs/ui only PRs
if: |
github.event.pull_request.draft == false &&
needs.verify-changes.outputs.is_docs_change == 'false' &&
needs.verify-changes.outputs.is_ui_change == 'false'
uses: ./.github/workflows/test-go.yml
with:
total-runners: 16
env-vars: |
{
"VAULT_CI_GO_TEST_RACE": 1
}
extra-flags: '-race'
go-arch: amd64
go-tags: ${{ needs.setup.outputs.go-tags }}
runs-on: ${{ needs.setup.outputs.compute-large }}
enterprise: ${{ needs.setup.outputs.enterprise }}
name: "race"
test-timing-cache-key: go-test-timing-race
secrets: inherit
test-go-fips:
name: Run Go tests with FIPS configuration
# Only run this job for the enterprise repo if the PR is not docs/ui only
if: |
github.event.pull_request.draft == false &&
needs.setup.outputs.enterprise == 1 &&
needs.verify-changes.outputs.is_docs_change == 'false' &&
needs.verify-changes.outputs.is_ui_change == 'false'
needs:
- setup
- verify-changes
uses: ./.github/workflows/test-go.yml
with:
total-runners: 16
env-vars: |
{
"GOEXPERIMENT": "boringcrypto"
}
go-arch: amd64
go-tags: '${{ needs.setup.outputs.go-tags }},deadlock,cgo,fips,fips_140_2'
runs-on: ${{ needs.setup.outputs.compute-large }}
enterprise: ${{ needs.setup.outputs.enterprise }}
name: "fips"
test-timing-cache-key: go-test-timing-fips
secrets: inherit
test-ui:
name: Test UI
# The test-ui job is only run on:
# - pushes to main and branches starting with "release/"
# - PRs where the branch starts with "ui/", "backport/ui/", "merge", or when base branch starts with "release/"
# - PRs with the "ui" label on GitHub
if: |
github.ref_name == 'main' ||
startsWith(github.ref_name, 'release/') ||
startsWith(github.head_ref, 'ui/') ||
startsWith(github.head_ref, 'backport/ui/') ||
startsWith(github.head_ref, 'merge') ||
contains(github.event.pull_request.labels.*.name, 'ui')
needs:
- setup
permissions:
id-token: write
contents: read
runs-on: ${{ fromJSON(needs.setup.outputs.compute-largem) }}
steps:
- uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
- uses: ./.github/actions/set-up-go
with:
github-token: ${{ secrets.ELEVATED_GITHUB_TOKEN }}
# Setup node.js without caching to allow running npm install -g yarn (next step)
- uses: actions/setup-node@e33196f7422957bea03ed53f6fbb155025ffc7b8 # v3.7.0
with:
node-version-file: './ui/package.json'
- id: install-yarn
run: |
npm install -g yarn
# Setup node.js with caching using the yarn.lock file
- uses: actions/setup-node@e33196f7422957bea03ed53f6fbb155025ffc7b8 # v3.7.0
with:
node-version-file: './ui/package.json'
cache: yarn
cache-dependency-path: ui/yarn.lock
- id: install-browser
uses: browser-actions/setup-chrome@c485fa3bab6be59dce18dbc18ef6ab7cbc8ff5f1 # v1.2.0
- id: ui-dependencies
name: ui-dependencies
working-directory: ./ui
run: |
yarn install --frozen-lockfile
npm rebuild node-sass
- id: vault-auth
name: Authenticate to Vault
if: github.repository == 'hashicorp/vault-enterprise'
run: vault-auth
- id: secrets
name: Fetch secrets
if: github.repository == 'hashicorp/vault-enterprise'
uses: hashicorp/vault-action@130d1f5f4fe645bb6c83e4225c04d64cfb62de6e
with:
url: ${{ steps.vault-auth.outputs.addr }}
caCertificate: ${{ steps.vault-auth.outputs.ca_certificate }}
token: ${{ steps.vault-auth.outputs.token }}
secrets: |
kv/data/github/hashicorp/vault-enterprise/github-token username-and-token | PRIVATE_REPO_GITHUB_TOKEN;
kv/data/github/hashicorp/vault-enterprise/license license_1 | VAULT_LICENSE;
- id: setup-git
name: Setup Git
if: github.repository == 'hashicorp/vault-enterprise'
run: |
git config --global url."https://${{ steps.secrets.outputs.PRIVATE_REPO_GITHUB_TOKEN }}@github.com".insteadOf https://github.com
- id: build-go-dev
name: build-go-dev
run: |
rm -rf ./pkg
mkdir ./pkg
make ci-bootstrap dev
- id: test-ui
name: test-ui
env:
VAULT_LICENSE: ${{ steps.secrets.outputs.VAULT_LICENSE }}
run: |
export PATH="${PWD}/bin:${PATH}"
if [ "${{ github.repository }}" == 'hashicorp/vault' ] ; then
export VAULT_LICENSE="${{ secrets.VAULT_LICENSE }}"
fi
# Run Ember tests
cd ui
mkdir -p test-results/qunit
yarn test:oss
- uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # v3.1.2
with:
name: test-results-ui
path: ui/test-results
if: success() || failure()
- uses: test-summary/action@62bc5c68de2a6a0d02039763b8c754569df99e3f # v2.1
with:
paths: "ui/test-results/qunit/results.xml"
show: "fail"
if: always()
tests-completed:
needs:
- setup
- test-go
- test-ui
if: always()
runs-on: ${{ fromJSON(needs.setup.outputs.compute-small) }}
steps:
- run: |
tr -d '\n' <<< '${{ toJSON(needs.*.result) }}' | grep -q -v -E '(failure|cancelled)'
notify-tests-completed-failures-ce:
if: |
always() &&
github.repository == 'hashicorp/vault' &&
(needs.test-go.result == 'failure' ||
needs.test-go-testonly.result == 'failure' ||
needs.test-go-race.result == 'failure' ||
needs.test-ui.result == 'failure'
) && (github.ref_name == 'main' || startsWith(github.ref_name, 'release/'))
runs-on: ubuntu-latest
permissions:
id-token: write
contents: read
strategy:
fail-fast: false
needs:
- test-go
- test-go-testonly
- test-go-race
- test-ui
steps:
- name: send-notification
uses: slackapi/slack-github-action@e28cf165c92ffef168d23c5c9000cffc8a25e117 # v1.24.0
# We intentionally aren't using the following here since it's from an internal repo
# uses: hashicorp/cloud-gha-slack-notifier@730a033037b8e603adf99ebd3085f0fdfe75e2f4 #v1
env:
SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}
with:
channel-id: "C05AABYEA9Y" # sent to #feed-vault-ci-official, use "C05Q4D5V89W"/test-vault-ci-slack-integration for testing
payload: |
{
"text": "CE test failures on ${{ github.ref_name }}",
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": ":rotating_light: CE test failures on ${{ github.ref_name }} :rotating_light:",
"emoji": true
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "${{ needs.test-go.result != 'failure' && ':white_check_mark:' || ':x:' }} Go tests\n${{ needs.test-go-race.result != 'failure' && ':white_check_mark:' || ':x:' }} Go race tests\n${{ needs.test-go-testonly.result != 'failure' && ':white_check_mark:' || ':x:' }} Go testonly tests\n${{ needs.test-ui.result != 'failure' && ':white_check_mark:' || ':x:' }} UI tests"
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "View Failing Workflow",
"emoji": true
},
"url": "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
}
}
]
}
notify-tests-completed-failures-ent:
if: |
always() &&
github.repository == 'hashicorp/vault-enterprise' &&
(needs.test-go.result == 'failure' ||
needs.test-go-testonly.result == 'failure' ||
needs.test-go-fips.result == 'failure' ||
needs.test-go-race.result == 'failure' ||
needs.test-ui.result == 'failure'
) && (github.ref_name == 'main' || startsWith(github.ref_name, 'release/'))
runs-on: ['self-hosted', 'linux', 'small']
permissions:
id-token: write
contents: read
strategy:
fail-fast: false
needs:
- test-go
- test-go-testonly
- test-go-race
- test-go-fips
- test-ui
steps:
- id: vault-auth
name: Vault Authenticate
run: vault-auth
- id: secrets
name: Fetch Vault Secrets
uses: hashicorp/vault-action@130d1f5f4fe645bb6c83e4225c04d64cfb62de6e
with:
url: ${{ steps.vault-auth.outputs.addr }}
caCertificate: ${{ steps.vault-auth.outputs.ca_certificate }}
token: ${{ steps.vault-auth.outputs.token }}
secrets: |
kv/data/github/${{ github.repository }}/github_actions_notifications_bot token | SLACK_BOT_TOKEN;
- name: send-notification
uses: hashicorp/cloud-gha-slack-notifier@730a033037b8e603adf99ebd3085f0fdfe75e2f4 #v1
with:
channel-id: "C05AABYEA9Y" # sent to #feed-vault-ci-official, use "C05Q4D5V89W"/test-vault-ci-slack-integration for testing
slack-bot-token: ${{ steps.secrets.outputs.SLACK_BOT_TOKEN }}
payload: |
{
"text": "Enterprise test failures on ${{ github.ref_name }}",
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": ":rotating_light: Enterprise test failures on ${{ github.ref_name }} :rotating_light:",
"emoji": true
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "${{ needs.test-go.result != 'failure' && ':white_check_mark:' || ':x:' }} Go tests\n${{ needs.test-go-fips.result != 'failure' && ':white_check_mark:' || ':x:' }} Go FIPS tests\n${{ needs.test-go-race.result != 'failure' && ':white_check_mark:' || ':x:' }} Go race tests\n${{ needs.test-go-testonly.result != 'failure' && ':white_check_mark:' || ':x:' }} Go testonly tests\n${{ needs.test-ui.result != 'failure' && ':white_check_mark:' || ':x:' }} UI tests"
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "View Failing Workflow",
"emoji": true
},
"url": "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
}
}
]
}
test-summary:
name: Go test failures
runs-on: ubuntu-latest
if: |
always() &&
(needs.test-go.result == 'success' ||
needs.test-go.result == 'failure' ||
needs.test-go-fips.result == 'success' ||
needs.test-go-fips.result == 'failure' ||
needs.test-go-race.result == 'success' ||
needs.test-go-race.result == 'failure') &&
(github.repository != 'hashicorp/vault' ||
(github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name))
# The last check ensures this doesn't run on community-contributed PRs, who
# won't have the permissions to run this job.
needs:
- test-go
- test-go-fips
- test-go-race
steps:
- name: Download failure summary
uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # v3.0.2
with:
name: failure-summary
- name: Prepare failure summary
run: |
# Sort all of the summary table rows and push them to a temp file.
temp_file_name=temp-$(date +%s)
cat failure-summary-*.md | sort >> "$temp_file_name"
# If there are test failures, present them in a format of a GitHub Markdown table.
if [ -s "$temp_file_name" ]; then
# shellcheck disable=SC2129
# Here we create the headings for the summary table
echo "| Test Type | Package | Test | Elapsed | Runner Index | Logs |" >> "$GITHUB_STEP_SUMMARY"
echo "| --------- | ------- | ---- | ------- | ------------ | ---- |" >> "$GITHUB_STEP_SUMMARY"
# shellcheck disable=SC2002
cat "$temp_file_name" >> "$GITHUB_STEP_SUMMARY"
else
echo "### All Go tests passed! :white_check_mark:" >> "$GITHUB_STEP_SUMMARY"
fi
# the random EOF is needed for a multiline environment variable
EOF=$(dd if=/dev/urandom bs=15 count=1 status=none | base64)
# shellcheck disable=SC2129
echo "TABLE_TEST_RESULTS<<$EOF" >> "$GITHUB_ENV"
cat "$temp_file_name" >> "$GITHUB_ENV"
echo "$EOF" >> "$GITHUB_ENV"
- uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
- name: Create comment
if: github.head_ref != ''
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ github.event.pull_request.number }}
RUN_ID: ${{ github.run_id }}
REPO: ${{ github.event.repository.name }}
TABLE_DATA: ${{ env.TABLE_TEST_RESULTS }}
run: ./.github/scripts/report_failed_tests.sh
| .github/workflows/ci.yml | 1 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.9932917356491089,
0.02187817171216011,
0.0001645655429456383,
0.0003297120565548539,
0.14323082566261292
] |
{
"id": 4,
"code_window": [
" runs-on: ${{ needs.setup.outputs.compute-large }}\n",
" enterprise: ${{ needs.setup.outputs.enterprise }}\n",
" name: \"race\"\n",
" test-timing-cache-key: go-test-timing-race\n",
" secrets: inherit\n",
"\n",
" test-go-fips:\n",
" name: Run Go tests with FIPS configuration\n",
" # Only run this job for the enterprise repo if the PR is not docs/ui only\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkout-ref: ${{ needs.setup.outputs.checkout-ref }}\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 133
} | ### vault.core.pre_seal ((#vault-core-pre_seal))
Metric type | Value | Description
----------- | ----- | -----------
summary | ms | Time required to complete pre-seal operations | website/content/partials/telemetry-metrics/vault/core/pre_seal.mdx | 0 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.00017738010501489043,
0.00017738010501489043,
0.00017738010501489043,
0.00017738010501489043,
0
] |
{
"id": 4,
"code_window": [
" runs-on: ${{ needs.setup.outputs.compute-large }}\n",
" enterprise: ${{ needs.setup.outputs.enterprise }}\n",
" name: \"race\"\n",
" test-timing-cache-key: go-test-timing-race\n",
" secrets: inherit\n",
"\n",
" test-go-fips:\n",
" name: Run Go tests with FIPS configuration\n",
" # Only run this job for the enterprise repo if the PR is not docs/ui only\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkout-ref: ${{ needs.setup.outputs.checkout-ref }}\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 133
} | package pkcs7
import (
"bytes"
"crypto/x509"
"testing"
)
func TestEncrypt(t *testing.T) {
modes := []int{
EncryptionAlgorithmDESCBC,
EncryptionAlgorithmAES128CBC,
EncryptionAlgorithmAES256CBC,
EncryptionAlgorithmAES128GCM,
EncryptionAlgorithmAES256GCM,
}
sigalgs := []x509.SignatureAlgorithm{
x509.SHA256WithRSA,
x509.SHA512WithRSA,
}
for _, mode := range modes {
for _, sigalg := range sigalgs {
ContentEncryptionAlgorithm = mode
plaintext := []byte("Hello Secret World!")
cert, err := createTestCertificate(sigalg)
if err != nil {
t.Fatal(err)
}
encrypted, err := Encrypt(plaintext, []*x509.Certificate{cert.Certificate})
if err != nil {
t.Fatal(err)
}
p7, err := Parse(encrypted)
if err != nil {
t.Fatalf("cannot Parse encrypted result: %s", err)
}
result, err := p7.Decrypt(cert.Certificate, *cert.PrivateKey)
if err != nil {
t.Fatalf("cannot Decrypt encrypted result: %s", err)
}
if !bytes.Equal(plaintext, result) {
t.Errorf("encrypted data does not match plaintext:\n\tExpected: %s\n\tActual: %s", plaintext, result)
}
}
}
}
func TestEncryptUsingPSK(t *testing.T) {
modes := []int{
EncryptionAlgorithmDESCBC,
EncryptionAlgorithmAES128GCM,
}
for _, mode := range modes {
ContentEncryptionAlgorithm = mode
plaintext := []byte("Hello Secret World!")
var key []byte
switch mode {
case EncryptionAlgorithmDESCBC:
key = []byte("64BitKey")
case EncryptionAlgorithmAES128GCM:
key = []byte("128BitKey4AESGCM")
}
ciphertext, err := EncryptUsingPSK(plaintext, key)
if err != nil {
t.Fatal(err)
}
p7, _ := Parse(ciphertext)
result, err := p7.DecryptUsingPSK(key)
if err != nil {
t.Fatalf("cannot Decrypt encrypted result: %s", err)
}
if !bytes.Equal(plaintext, result) {
t.Errorf("encrypted data does not match plaintext:\n\tExpected: %s\n\tActual: %s", plaintext, result)
}
}
}
func TestPad(t *testing.T) {
tests := []struct {
Original []byte
Expected []byte
BlockSize int
}{
{[]byte{0x1, 0x2, 0x3, 0x10}, []byte{0x1, 0x2, 0x3, 0x10, 0x4, 0x4, 0x4, 0x4}, 8},
{[]byte{0x1, 0x2, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0}, []byte{0x1, 0x2, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8}, 8},
}
for _, test := range tests {
padded, err := pad(test.Original, test.BlockSize)
if err != nil {
t.Errorf("pad encountered error: %s", err)
continue
}
if !bytes.Equal(test.Expected, padded) {
t.Errorf("pad results mismatch:\n\tExpected: %X\n\tActual: %X", test.Expected, padded)
}
}
}
| builtin/credential/aws/pkcs7/encrypt_test.go | 0 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.00028997278423048556,
0.00018177327001467347,
0.0001636265660636127,
0.0001723112800391391,
0.00003445248512434773
] |
{
"id": 4,
"code_window": [
" runs-on: ${{ needs.setup.outputs.compute-large }}\n",
" enterprise: ${{ needs.setup.outputs.enterprise }}\n",
" name: \"race\"\n",
" test-timing-cache-key: go-test-timing-race\n",
" secrets: inherit\n",
"\n",
" test-go-fips:\n",
" name: Run Go tests with FIPS configuration\n",
" # Only run this job for the enterprise repo if the PR is not docs/ui only\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkout-ref: ${{ needs.setup.outputs.checkout-ref }}\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 133
} | {{!
Copyright (c) HashiCorp, Inc.
SPDX-License-Identifier: BUSL-1.1
~}}
<Sidebar::Nav::Policies />
{{outlet}} | ui/app/templates/vault/cluster/policies.hbs | 0 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.00017820722132455558,
0.00017820722132455558,
0.00017820722132455558,
0.00017820722132455558,
0
] |
{
"id": 5,
"code_window": [
" go-tags: '${{ needs.setup.outputs.go-tags }},deadlock,cgo,fips,fips_140_2'\n",
" runs-on: ${{ needs.setup.outputs.compute-large }}\n",
" enterprise: ${{ needs.setup.outputs.enterprise }}\n",
" name: \"fips\"\n",
" test-timing-cache-key: go-test-timing-fips\n",
" secrets: inherit\n",
"\n",
" test-ui:\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkout-ref: ${{ needs.setup.outputs.checkout-ref }}\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 159
} | name: CI
on:
pull_request:
# The default types for pull_request are [ opened, synchronize, reopened ].
# This is insufficient for our needs, since we're skipping stuff on PRs in
# draft mode. By adding the ready_for_review type, when a draft pr is marked
# ready, we run everything, including the stuff we'd have skipped up until now.
types: [opened, synchronize, reopened, ready_for_review]
push:
branches:
- main
- release/**
workflow_dispatch:
concurrency:
group: ${{ github.head_ref || github.run_id }}-ci
cancel-in-progress: true
jobs:
setup:
name: Setup
runs-on: ubuntu-latest
outputs:
compute-small: ${{ steps.setup-outputs.outputs.compute-small }}
compute-medium: ${{ steps.setup-outputs.outputs.compute-medium }}
compute-large: ${{ steps.setup-outputs.outputs.compute-large }}
compute-largem: ${{ steps.setup-outputs.outputs.compute-largem }}
compute-xlarge: ${{ steps.setup-outputs.outputs.compute-xlarge }}
enterprise: ${{ steps.setup-outputs.outputs.enterprise }}
go-tags: ${{ steps.setup-outputs.outputs.go-tags }}
steps:
- uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
- id: setup-outputs
name: Setup outputs
run: |
github_repository="${{ github.repository }}"
if [ "${github_repository##*/}" == "vault-enterprise" ] ; then
# shellcheck disable=SC2129
echo 'compute-small=["self-hosted","ondemand","linux","type=c6a.large"]' >> "$GITHUB_OUTPUT" # 2x vCPUs, 4 GiB RAM,
echo 'compute-medium=["self-hosted","ondemand","linux","type=c6a.xlarge"]' >> "$GITHUB_OUTPUT" # 4x vCPUs, 8 GiB RAM,
echo 'compute-large=["self-hosted","ondemand","linux","type=c6a.2xlarge","disk_gb=64"]' >> "$GITHUB_OUTPUT" # 8x vCPUs, 16 GiB RAM,
echo 'compute-largem=["self-hosted","ondemand","linux","type=m6a.2xlarge"]' >> "$GITHUB_OUTPUT" # 8x vCPUs, 32 GiB RAM,
echo 'compute-xlarge=["self-hosted","ondemand","linux","type=c6a.4xlarge"]' >> "$GITHUB_OUTPUT" # 16x vCPUs, 32 GiB RAM,
echo 'enterprise=1' >> "$GITHUB_OUTPUT"
echo 'go-tags=ent,enterprise' >> "$GITHUB_OUTPUT"
else
# shellcheck disable=SC2129
echo 'compute-small="ubuntu-latest"' >> "$GITHUB_OUTPUT" # 2x vCPUs, 7 GiB RAM, 14 GB SSD
echo 'compute-medium="custom-linux-small-vault-latest"' >> "$GITHUB_OUTPUT" # 8x vCPUs, 32 GiB RAM, 300 GB SSD
echo 'compute-large="custom-linux-medium-vault-latest"' >> "$GITHUB_OUTPUT" # 16x vCPUs, 64 GiB RAM, 600 GB SSD
echo 'compute-largem="custom-linux-medium-vault-latest"' >> "$GITHUB_OUTPUT" # 16x vCPUs, 64 GiB RAM, 600 GB SSD
echo 'compute-xlarge="custom-linux-xl-vault-latest"' >> "$GITHUB_OUTPUT" # 32x vCPUs, 128 GiB RAM, 1200 GB SSD
echo 'enterprise=' >> "$GITHUB_OUTPUT"
echo 'go-tags=' >> "$GITHUB_OUTPUT"
fi
- name: Ensure Go modules are cached
uses: ./.github/actions/set-up-go
with:
github-token: ${{ secrets.ELEVATED_GITHUB_TOKEN }}
no-restore: true # don't download them on a cache hit
verify-changes:
name: Verify doc-ui only PRs
uses: ./.github/workflows/verify_changes.yml
test-go:
name: Run Go tests
needs:
- setup
- verify-changes
# Don't run this job for docs/ui only PRs
if: |
needs.verify-changes.outputs.is_docs_change == 'false' &&
needs.verify-changes.outputs.is_ui_change == 'false'
uses: ./.github/workflows/test-go.yml
with:
# The regular Go tests use an extra runner to execute the
# binary-dependent tests. We isolate them there so that the
# other tests aren't slowed down waiting for a binary build.
binary-tests: true
total-runners: 16
go-arch: amd64
go-tags: '${{ needs.setup.outputs.go-tags }},deadlock'
runs-on: ${{ needs.setup.outputs.compute-large }}
enterprise: ${{ needs.setup.outputs.enterprise }}
test-timing-cache-key: go-test-timing-standard
secrets: inherit
test-go-testonly:
name: Run Go tests tagged with testonly
needs:
- setup
- verify-changes
# Don't run this job for docs/ui only PRs
if: |
needs.verify-changes.outputs.is_docs_change == 'false' &&
needs.verify-changes.outputs.is_ui_change == 'false'
uses: ./.github/workflows/test-go.yml
with:
testonly: true
total-runners: 2 # test runners cannot be less than 2
go-arch: amd64
go-tags: '${{ needs.setup.outputs.go-tags }},deadlock,testonly'
runs-on: ${{ needs.setup.outputs.compute-large }}
enterprise: ${{ needs.setup.outputs.enterprise }}
test-timing-cache-enabled: false
secrets: inherit
test-go-race:
name: Run Go tests with data race detection
needs:
- setup
- verify-changes
# Don't run this job for docs/ui only PRs
if: |
github.event.pull_request.draft == false &&
needs.verify-changes.outputs.is_docs_change == 'false' &&
needs.verify-changes.outputs.is_ui_change == 'false'
uses: ./.github/workflows/test-go.yml
with:
total-runners: 16
env-vars: |
{
"VAULT_CI_GO_TEST_RACE": 1
}
extra-flags: '-race'
go-arch: amd64
go-tags: ${{ needs.setup.outputs.go-tags }}
runs-on: ${{ needs.setup.outputs.compute-large }}
enterprise: ${{ needs.setup.outputs.enterprise }}
name: "race"
test-timing-cache-key: go-test-timing-race
secrets: inherit
test-go-fips:
name: Run Go tests with FIPS configuration
# Only run this job for the enterprise repo if the PR is not docs/ui only
if: |
github.event.pull_request.draft == false &&
needs.setup.outputs.enterprise == 1 &&
needs.verify-changes.outputs.is_docs_change == 'false' &&
needs.verify-changes.outputs.is_ui_change == 'false'
needs:
- setup
- verify-changes
uses: ./.github/workflows/test-go.yml
with:
total-runners: 16
env-vars: |
{
"GOEXPERIMENT": "boringcrypto"
}
go-arch: amd64
go-tags: '${{ needs.setup.outputs.go-tags }},deadlock,cgo,fips,fips_140_2'
runs-on: ${{ needs.setup.outputs.compute-large }}
enterprise: ${{ needs.setup.outputs.enterprise }}
name: "fips"
test-timing-cache-key: go-test-timing-fips
secrets: inherit
test-ui:
name: Test UI
# The test-ui job is only run on:
# - pushes to main and branches starting with "release/"
# - PRs where the branch starts with "ui/", "backport/ui/", "merge", or when base branch starts with "release/"
# - PRs with the "ui" label on GitHub
if: |
github.ref_name == 'main' ||
startsWith(github.ref_name, 'release/') ||
startsWith(github.head_ref, 'ui/') ||
startsWith(github.head_ref, 'backport/ui/') ||
startsWith(github.head_ref, 'merge') ||
contains(github.event.pull_request.labels.*.name, 'ui')
needs:
- setup
permissions:
id-token: write
contents: read
runs-on: ${{ fromJSON(needs.setup.outputs.compute-largem) }}
steps:
- uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
- uses: ./.github/actions/set-up-go
with:
github-token: ${{ secrets.ELEVATED_GITHUB_TOKEN }}
# Setup node.js without caching to allow running npm install -g yarn (next step)
- uses: actions/setup-node@e33196f7422957bea03ed53f6fbb155025ffc7b8 # v3.7.0
with:
node-version-file: './ui/package.json'
- id: install-yarn
run: |
npm install -g yarn
# Setup node.js with caching using the yarn.lock file
- uses: actions/setup-node@e33196f7422957bea03ed53f6fbb155025ffc7b8 # v3.7.0
with:
node-version-file: './ui/package.json'
cache: yarn
cache-dependency-path: ui/yarn.lock
- id: install-browser
uses: browser-actions/setup-chrome@c485fa3bab6be59dce18dbc18ef6ab7cbc8ff5f1 # v1.2.0
- id: ui-dependencies
name: ui-dependencies
working-directory: ./ui
run: |
yarn install --frozen-lockfile
npm rebuild node-sass
- id: vault-auth
name: Authenticate to Vault
if: github.repository == 'hashicorp/vault-enterprise'
run: vault-auth
- id: secrets
name: Fetch secrets
if: github.repository == 'hashicorp/vault-enterprise'
uses: hashicorp/vault-action@130d1f5f4fe645bb6c83e4225c04d64cfb62de6e
with:
url: ${{ steps.vault-auth.outputs.addr }}
caCertificate: ${{ steps.vault-auth.outputs.ca_certificate }}
token: ${{ steps.vault-auth.outputs.token }}
secrets: |
kv/data/github/hashicorp/vault-enterprise/github-token username-and-token | PRIVATE_REPO_GITHUB_TOKEN;
kv/data/github/hashicorp/vault-enterprise/license license_1 | VAULT_LICENSE;
- id: setup-git
name: Setup Git
if: github.repository == 'hashicorp/vault-enterprise'
run: |
git config --global url."https://${{ steps.secrets.outputs.PRIVATE_REPO_GITHUB_TOKEN }}@github.com".insteadOf https://github.com
- id: build-go-dev
name: build-go-dev
run: |
rm -rf ./pkg
mkdir ./pkg
make ci-bootstrap dev
- id: test-ui
name: test-ui
env:
VAULT_LICENSE: ${{ steps.secrets.outputs.VAULT_LICENSE }}
run: |
export PATH="${PWD}/bin:${PATH}"
if [ "${{ github.repository }}" == 'hashicorp/vault' ] ; then
export VAULT_LICENSE="${{ secrets.VAULT_LICENSE }}"
fi
# Run Ember tests
cd ui
mkdir -p test-results/qunit
yarn test:oss
- uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # v3.1.2
with:
name: test-results-ui
path: ui/test-results
if: success() || failure()
- uses: test-summary/action@62bc5c68de2a6a0d02039763b8c754569df99e3f # v2.1
with:
paths: "ui/test-results/qunit/results.xml"
show: "fail"
if: always()
tests-completed:
needs:
- setup
- test-go
- test-ui
if: always()
runs-on: ${{ fromJSON(needs.setup.outputs.compute-small) }}
steps:
- run: |
tr -d '\n' <<< '${{ toJSON(needs.*.result) }}' | grep -q -v -E '(failure|cancelled)'
notify-tests-completed-failures-ce:
if: |
always() &&
github.repository == 'hashicorp/vault' &&
(needs.test-go.result == 'failure' ||
needs.test-go-testonly.result == 'failure' ||
needs.test-go-race.result == 'failure' ||
needs.test-ui.result == 'failure'
) && (github.ref_name == 'main' || startsWith(github.ref_name, 'release/'))
runs-on: ubuntu-latest
permissions:
id-token: write
contents: read
strategy:
fail-fast: false
needs:
- test-go
- test-go-testonly
- test-go-race
- test-ui
steps:
- name: send-notification
uses: slackapi/slack-github-action@e28cf165c92ffef168d23c5c9000cffc8a25e117 # v1.24.0
# We intentionally aren't using the following here since it's from an internal repo
# uses: hashicorp/cloud-gha-slack-notifier@730a033037b8e603adf99ebd3085f0fdfe75e2f4 #v1
env:
SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}
with:
channel-id: "C05AABYEA9Y" # sent to #feed-vault-ci-official, use "C05Q4D5V89W"/test-vault-ci-slack-integration for testing
payload: |
{
"text": "CE test failures on ${{ github.ref_name }}",
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": ":rotating_light: CE test failures on ${{ github.ref_name }} :rotating_light:",
"emoji": true
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "${{ needs.test-go.result != 'failure' && ':white_check_mark:' || ':x:' }} Go tests\n${{ needs.test-go-race.result != 'failure' && ':white_check_mark:' || ':x:' }} Go race tests\n${{ needs.test-go-testonly.result != 'failure' && ':white_check_mark:' || ':x:' }} Go testonly tests\n${{ needs.test-ui.result != 'failure' && ':white_check_mark:' || ':x:' }} UI tests"
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "View Failing Workflow",
"emoji": true
},
"url": "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
}
}
]
}
notify-tests-completed-failures-ent:
if: |
always() &&
github.repository == 'hashicorp/vault-enterprise' &&
(needs.test-go.result == 'failure' ||
needs.test-go-testonly.result == 'failure' ||
needs.test-go-fips.result == 'failure' ||
needs.test-go-race.result == 'failure' ||
needs.test-ui.result == 'failure'
) && (github.ref_name == 'main' || startsWith(github.ref_name, 'release/'))
runs-on: ['self-hosted', 'linux', 'small']
permissions:
id-token: write
contents: read
strategy:
fail-fast: false
needs:
- test-go
- test-go-testonly
- test-go-race
- test-go-fips
- test-ui
steps:
- id: vault-auth
name: Vault Authenticate
run: vault-auth
- id: secrets
name: Fetch Vault Secrets
uses: hashicorp/vault-action@130d1f5f4fe645bb6c83e4225c04d64cfb62de6e
with:
url: ${{ steps.vault-auth.outputs.addr }}
caCertificate: ${{ steps.vault-auth.outputs.ca_certificate }}
token: ${{ steps.vault-auth.outputs.token }}
secrets: |
kv/data/github/${{ github.repository }}/github_actions_notifications_bot token | SLACK_BOT_TOKEN;
- name: send-notification
uses: hashicorp/cloud-gha-slack-notifier@730a033037b8e603adf99ebd3085f0fdfe75e2f4 #v1
with:
channel-id: "C05AABYEA9Y" # sent to #feed-vault-ci-official, use "C05Q4D5V89W"/test-vault-ci-slack-integration for testing
slack-bot-token: ${{ steps.secrets.outputs.SLACK_BOT_TOKEN }}
payload: |
{
"text": "Enterprise test failures on ${{ github.ref_name }}",
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": ":rotating_light: Enterprise test failures on ${{ github.ref_name }} :rotating_light:",
"emoji": true
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "${{ needs.test-go.result != 'failure' && ':white_check_mark:' || ':x:' }} Go tests\n${{ needs.test-go-fips.result != 'failure' && ':white_check_mark:' || ':x:' }} Go FIPS tests\n${{ needs.test-go-race.result != 'failure' && ':white_check_mark:' || ':x:' }} Go race tests\n${{ needs.test-go-testonly.result != 'failure' && ':white_check_mark:' || ':x:' }} Go testonly tests\n${{ needs.test-ui.result != 'failure' && ':white_check_mark:' || ':x:' }} UI tests"
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "View Failing Workflow",
"emoji": true
},
"url": "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
}
}
]
}
test-summary:
name: Go test failures
runs-on: ubuntu-latest
if: |
always() &&
(needs.test-go.result == 'success' ||
needs.test-go.result == 'failure' ||
needs.test-go-fips.result == 'success' ||
needs.test-go-fips.result == 'failure' ||
needs.test-go-race.result == 'success' ||
needs.test-go-race.result == 'failure') &&
(github.repository != 'hashicorp/vault' ||
(github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name))
# The last check ensures this doesn't run on community-contributed PRs, who
# won't have the permissions to run this job.
needs:
- test-go
- test-go-fips
- test-go-race
steps:
- name: Download failure summary
uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # v3.0.2
with:
name: failure-summary
- name: Prepare failure summary
run: |
# Sort all of the summary table rows and push them to a temp file.
temp_file_name=temp-$(date +%s)
cat failure-summary-*.md | sort >> "$temp_file_name"
# If there are test failures, present them in a format of a GitHub Markdown table.
if [ -s "$temp_file_name" ]; then
# shellcheck disable=SC2129
# Here we create the headings for the summary table
echo "| Test Type | Package | Test | Elapsed | Runner Index | Logs |" >> "$GITHUB_STEP_SUMMARY"
echo "| --------- | ------- | ---- | ------- | ------------ | ---- |" >> "$GITHUB_STEP_SUMMARY"
# shellcheck disable=SC2002
cat "$temp_file_name" >> "$GITHUB_STEP_SUMMARY"
else
echo "### All Go tests passed! :white_check_mark:" >> "$GITHUB_STEP_SUMMARY"
fi
# the random EOF is needed for a multiline environment variable
EOF=$(dd if=/dev/urandom bs=15 count=1 status=none | base64)
# shellcheck disable=SC2129
echo "TABLE_TEST_RESULTS<<$EOF" >> "$GITHUB_ENV"
cat "$temp_file_name" >> "$GITHUB_ENV"
echo "$EOF" >> "$GITHUB_ENV"
- uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
- name: Create comment
if: github.head_ref != ''
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ github.event.pull_request.number }}
RUN_ID: ${{ github.run_id }}
REPO: ${{ github.event.repository.name }}
TABLE_DATA: ${{ env.TABLE_TEST_RESULTS }}
run: ./.github/scripts/report_failed_tests.sh
| .github/workflows/ci.yml | 1 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.9541543126106262,
0.02107691578567028,
0.00016164810222107917,
0.0002717156894505024,
0.13757994771003723
] |
{
"id": 5,
"code_window": [
" go-tags: '${{ needs.setup.outputs.go-tags }},deadlock,cgo,fips,fips_140_2'\n",
" runs-on: ${{ needs.setup.outputs.compute-large }}\n",
" enterprise: ${{ needs.setup.outputs.enterprise }}\n",
" name: \"fips\"\n",
" test-timing-cache-key: go-test-timing-fips\n",
" secrets: inherit\n",
"\n",
" test-ui:\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkout-ref: ${{ needs.setup.outputs.checkout-ref }}\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 159
} | // Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
//go:build !enterprise
package builtinplugins
import "github.com/hashicorp/vault/sdk/helper/consts"
// IsBuiltinEntPlugin checks whether the plugin is an enterprise only builtin plugin
func (r *registry) IsBuiltinEntPlugin(name string, pluginType consts.PluginType) bool {
return false
}
| helper/builtinplugins/registry_util.go | 0 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.00016439033788628876,
0.000164291966939345,
0.00016419359599240124,
0.000164291966939345,
9.837094694375992e-8
] |
{
"id": 5,
"code_window": [
" go-tags: '${{ needs.setup.outputs.go-tags }},deadlock,cgo,fips,fips_140_2'\n",
" runs-on: ${{ needs.setup.outputs.compute-large }}\n",
" enterprise: ${{ needs.setup.outputs.enterprise }}\n",
" name: \"fips\"\n",
" test-timing-cache-key: go-test-timing-fips\n",
" secrets: inherit\n",
"\n",
" test-ui:\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkout-ref: ${{ needs.setup.outputs.checkout-ref }}\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 159
} | /**
* Copyright (c) HashiCorp, Inc.
* SPDX-License-Identifier: BUSL-1.1
*/
import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { click, currentURL } from '@ember/test-helpers';
import { setupMirage } from 'ember-cli-mirage/test-support';
import authPage from 'vault/tests/pages/auth';
import modifyPassthroughResponse from 'vault/mirage/helpers/modify-passthrough-response';
const link = (label) => `[data-test-sidebar-nav-link="${label}"]`;
const panel = (label) => `[data-test-sidebar-nav-panel="${label}"]`;
module('Acceptance | sidebar navigation', function (hooks) {
setupApplicationTest(hooks);
setupMirage(hooks);
hooks.beforeEach(function () {
// set storage_type to raft to test link
this.server.get('/sys/seal-status', (schema, req) => {
return modifyPassthroughResponse(req, { storage_type: 'raft' });
});
this.server.get('/sys/storage/raft/configuration', () => this.server.create('configuration', 'withRaft'));
return authPage.login();
});
test('it should navigate back to the dashboard when logo is clicked', async function (assert) {
await click('[data-test-sidebar-logo]');
assert.strictEqual(currentURL(), '/vault/dashboard', 'dashboard route renders');
});
test('it should link to correct routes at the cluster level', async function (assert) {
assert.expect(11);
assert.dom(panel('Cluster')).exists('Cluster nav panel renders');
const subNavs = [
{ label: 'Access', route: 'access' },
{ label: 'Policies', route: 'policies/acl' },
{ label: 'Tools', route: 'tools/wrap' },
];
for (const subNav of subNavs) {
const { label, route } = subNav;
await click(link(label));
assert.strictEqual(currentURL(), `/vault/${route}`, `${label} route renders`);
assert.dom(panel(label)).exists(`${label} nav panel renders`);
await click(link('Back to main navigation'));
}
const links = [
{ label: 'Raft Storage', route: '/vault/storage/raft' },
{ label: 'Seal Vault', route: '/vault/settings/seal' },
{ label: 'Secrets engines', route: '/vault/secrets' },
{ label: 'Dashboard', route: '/vault/dashboard' },
];
for (const l of links) {
await click(link(l.label));
assert.strictEqual(currentURL(), l.route, `${l.label} route renders`);
}
});
test('it should link to correct routes at the access level', async function (assert) {
assert.expect(7);
await click(link('Access'));
assert.dom(panel('Access')).exists('Access nav panel renders');
const links = [
{ label: 'Multi-Factor Authentication', route: '/vault/access/mfa' },
{ label: 'OIDC Provider', route: '/vault/access/oidc' },
{ label: 'Groups', route: '/vault/access/identity/groups' },
{ label: 'Entities', route: '/vault/access/identity/entities' },
{ label: 'Leases', route: '/vault/access/leases/list' },
{ label: 'Authentication Methods', route: '/vault/access' },
];
for (const l of links) {
await click(link(l.label));
assert.ok(currentURL().includes(l.route), `${l.label} route renders`);
}
});
test('it should link to correct routes at the policies level', async function (assert) {
assert.expect(2);
await click(link('Policies'));
assert.dom(panel('Policies')).exists('Access nav panel renders');
await click(link('ACL Policies'));
assert.strictEqual(currentURL(), '/vault/policies/acl', 'ACL Policies route renders');
});
test('it should link to correct routes at the tools level', async function (assert) {
assert.expect(7);
await click(link('Tools'));
assert.dom(panel('Tools')).exists('Access nav panel renders');
const links = [
{ label: 'Wrap', route: '/vault/tools/wrap' },
{ label: 'Lookup', route: '/vault/tools/lookup' },
{ label: 'Unwrap', route: '/vault/tools/unwrap' },
{ label: 'Rewrap', route: '/vault/tools/rewrap' },
{ label: 'Random', route: '/vault/tools/random' },
{ label: 'Hash', route: '/vault/tools/hash' },
];
for (const l of links) {
await click(link(l.label));
assert.strictEqual(currentURL(), l.route, `${l.label} route renders`);
}
});
test('it should display access nav when mounting and configuring auth methods', async function (assert) {
await click(link('Access'));
await click('[data-test-auth-enable]');
assert.dom('[data-test-sidebar-nav-panel="Access"]').exists('Access nav panel renders');
await click(link('Authentication Methods'));
await click('[data-test-auth-backend-link="token"]');
await click('[data-test-configure-link]');
assert.dom('[data-test-sidebar-nav-panel="Access"]').exists('Access nav panel renders');
});
});
| ui/tests/acceptance/sidebar-nav-test.js | 0 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.000175282169948332,
0.0001735526748234406,
0.0001702278241282329,
0.00017397872579749674,
0.0000016301919458783232
] |
{
"id": 5,
"code_window": [
" go-tags: '${{ needs.setup.outputs.go-tags }},deadlock,cgo,fips,fips_140_2'\n",
" runs-on: ${{ needs.setup.outputs.compute-large }}\n",
" enterprise: ${{ needs.setup.outputs.enterprise }}\n",
" name: \"fips\"\n",
" test-timing-cache-key: go-test-timing-fips\n",
" secrets: inherit\n",
"\n",
" test-ui:\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" checkout-ref: ${{ needs.setup.outputs.checkout-ref }}\n"
],
"file_path": ".github/workflows/ci.yml",
"type": "add",
"edit_start_line_idx": 159
} | ```release-note:feature
agent: Support for persisting the agent cache to disk
```
| changelog/10938.txt | 0 | https://github.com/hashicorp/vault/commit/375c2be624cfd9b19b2f21cbb62a3e453d605f58 | [
0.00016479118494316936,
0.00016479118494316936,
0.00016479118494316936,
0.00016479118494316936,
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.