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": 8, "code_window": [ "\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n", "\t\treturn migrateFile(oldPath, newPath, \"state.yml\")\n", "\t}\n", "\n", "\tpath, err = homedir.Dir()\n", "\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n", "\t\treturn migrateFile(oldPath, newPath, \"state.yml\")\n", "\t}\n", "\n", "\treturn errNotExist\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "internal/config/config_file.go", "type": "replace", "edit_start_line_idx": 121 }
package config import ( "errors" "fmt" "io/ioutil" "os" "path/filepath" "runtime" "syscall" "github.com/mitchellh/go-homedir" "gopkg.in/yaml.v3" ) const ( GH_CONFIG_DIR = "GH_CONFIG_DIR" XDG_CONFIG_HOME = "XDG_CONFIG_HOME" XDG_STATE_HOME = "XDG_STATE_HOME" XDG_DATA_HOME = "XDG_DATA_HOME" APP_DATA = "AppData" LOCAL_APP_DATA = "LocalAppData" ) // Config path precedence // 1. GH_CONFIG_DIR // 2. XDG_CONFIG_HOME // 3. AppData (windows only) // 4. HOME func ConfigDir() string { var path string if a := os.Getenv(GH_CONFIG_DIR); a != "" { path = a } else if b := os.Getenv(XDG_CONFIG_HOME); b != "" { path = filepath.Join(b, "gh") } else if c := os.Getenv(APP_DATA); runtime.GOOS == "windows" && c != "" { path = filepath.Join(c, "GitHub CLI") } else { d, _ := os.UserHomeDir() path = filepath.Join(d, ".config", "gh") } // If the path does not exist and the GH_CONFIG_DIR flag is not set try // migrating config from default paths. if !dirExists(path) && os.Getenv(GH_CONFIG_DIR) == "" { _ = autoMigrateConfigDir(path) } return path } // State path precedence // 1. XDG_CONFIG_HOME // 2. LocalAppData (windows only) // 3. HOME func StateDir() string { var path string if a := os.Getenv(XDG_STATE_HOME); a != "" { path = filepath.Join(a, "gh") } else if b := os.Getenv(LOCAL_APP_DATA); runtime.GOOS == "windows" && b != "" { path = filepath.Join(b, "GitHub CLI") } else { c, _ := os.UserHomeDir() path = filepath.Join(c, ".local", "state", "gh") } // If the path does not exist try migrating state from default paths if !dirExists(path) { _ = autoMigrateStateDir(path) } return path } // Data path precedence // 1. XDG_DATA_HOME // 2. LocalAppData (windows only) // 3. HOME func DataDir() string { var path string if a := os.Getenv(XDG_DATA_HOME); a != "" { path = filepath.Join(a, "gh") } else if b := os.Getenv(LOCAL_APP_DATA); runtime.GOOS == "windows" && b != "" { path = filepath.Join(b, "GitHub CLI") } else { c, _ := os.UserHomeDir() path = filepath.Join(c, ".local", "share", "gh") } return path } var errSamePath = errors.New("same path") var errNotExist = errors.New("not exist") // Check default paths (os.UserHomeDir, and homedir.Dir) for existing configs // If configs exist then move them to newPath // TODO: Remove support for homedir.Dir location in v2 func autoMigrateConfigDir(newPath string) error { path, err := os.UserHomeDir() if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) { return migrateDir(oldPath, newPath) } path, err = homedir.Dir() if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) { return migrateDir(oldPath, newPath) } return errNotExist } // Check default paths (os.UserHomeDir, and homedir.Dir) for existing state file (state.yml) // If state file exist then move it to newPath // TODO: Remove support for homedir.Dir location in v2 func autoMigrateStateDir(newPath string) error { path, err := os.UserHomeDir() if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) { return migrateFile(oldPath, newPath, "state.yml") } path, err = homedir.Dir() if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) { return migrateFile(oldPath, newPath, "state.yml") } return errNotExist } func migrateFile(oldPath, newPath, file string) error { if oldPath == newPath { return errSamePath } oldFile := filepath.Join(oldPath, file) newFile := filepath.Join(newPath, file) if !fileExists(oldFile) { return errNotExist } _ = os.MkdirAll(filepath.Dir(newFile), 0755) return os.Rename(oldFile, newFile) } func migrateDir(oldPath, newPath string) error { if oldPath == newPath { return errSamePath } if !dirExists(oldPath) { return errNotExist } _ = os.MkdirAll(filepath.Dir(newPath), 0755) return os.Rename(oldPath, newPath) } func dirExists(path string) bool { f, err := os.Stat(path) return err == nil && f.IsDir() } func fileExists(path string) bool { f, err := os.Stat(path) return err == nil && !f.IsDir() } func ConfigFile() string { return filepath.Join(ConfigDir(), "config.yml") } func HostsConfigFile() string { return filepath.Join(ConfigDir(), "hosts.yml") } func ParseDefaultConfig() (Config, error) { return parseConfig(ConfigFile()) } func HomeDirPath(subdir string) (string, error) { homeDir, err := os.UserHomeDir() if err != nil { // TODO: remove go-homedir fallback in GitHub CLI v2 if legacyDir, err := homedir.Dir(); err == nil { return filepath.Join(legacyDir, subdir), nil } return "", err } newPath := filepath.Join(homeDir, subdir) if s, err := os.Stat(newPath); err == nil && s.IsDir() { return newPath, nil } // TODO: remove go-homedir fallback in GitHub CLI v2 if legacyDir, err := homedir.Dir(); err == nil { legacyPath := filepath.Join(legacyDir, subdir) if s, err := os.Stat(legacyPath); err == nil && s.IsDir() { return legacyPath, nil } } return newPath, nil } var ReadConfigFile = func(filename string) ([]byte, error) { f, err := os.Open(filename) if err != nil { return nil, pathError(err) } defer f.Close() data, err := ioutil.ReadAll(f) if err != nil { return nil, err } return data, nil } var WriteConfigFile = func(filename string, data []byte) error { err := os.MkdirAll(filepath.Dir(filename), 0771) if err != nil { return pathError(err) } cfgFile, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) // cargo coded from setup if err != nil { return err } defer cfgFile.Close() _, err = cfgFile.Write(data) return err } var BackupConfigFile = func(filename string) error { return os.Rename(filename, filename+".bak") } func parseConfigFile(filename string) ([]byte, *yaml.Node, error) { data, err := ReadConfigFile(filename) if err != nil { return nil, nil, err } root, err := parseConfigData(data) if err != nil { return nil, nil, err } return data, root, err } func parseConfigData(data []byte) (*yaml.Node, error) { var root yaml.Node err := yaml.Unmarshal(data, &root) if err != nil { return nil, err } if len(root.Content) == 0 { return &yaml.Node{ Kind: yaml.DocumentNode, Content: []*yaml.Node{{Kind: yaml.MappingNode}}, }, nil } if root.Content[0].Kind != yaml.MappingNode { return &root, fmt.Errorf("expected a top level map") } return &root, nil } func isLegacy(root *yaml.Node) bool { for _, v := range root.Content[0].Content { if v.Value == "github.com" { return true } } return false } func migrateConfig(filename string) error { b, err := ReadConfigFile(filename) if err != nil { return err } var hosts map[string][]yaml.Node err = yaml.Unmarshal(b, &hosts) if err != nil { return fmt.Errorf("error decoding legacy format: %w", err) } cfg := NewBlankConfig() for hostname, entries := range hosts { if len(entries) < 1 { continue } mapContent := entries[0].Content for i := 0; i < len(mapContent)-1; i += 2 { if err := cfg.Set(hostname, mapContent[i].Value, mapContent[i+1].Value); err != nil { return err } } } err = BackupConfigFile(filename) if err != nil { return fmt.Errorf("failed to back up existing config: %w", err) } return cfg.Write() } func parseConfig(filename string) (Config, error) { _, root, err := parseConfigFile(filename) if err != nil { if os.IsNotExist(err) { root = NewBlankRoot() } else { return nil, err } } if isLegacy(root) { err = migrateConfig(filename) if err != nil { return nil, fmt.Errorf("error migrating legacy config: %w", err) } _, root, err = parseConfigFile(filename) if err != nil { return nil, fmt.Errorf("failed to reparse migrated config: %w", err) } } else { if _, hostsRoot, err := parseConfigFile(HostsConfigFile()); err == nil { if len(hostsRoot.Content[0].Content) > 0 { newContent := []*yaml.Node{ {Value: "hosts"}, hostsRoot.Content[0], } restContent := root.Content[0].Content root.Content[0].Content = append(newContent, restContent...) } } else if !errors.Is(err, os.ErrNotExist) { return nil, err } } return NewConfig(root), nil } func pathError(err error) error { var pathError *os.PathError if errors.As(err, &pathError) && errors.Is(pathError.Err, syscall.ENOTDIR) { if p := findRegularFile(pathError.Path); p != "" { return fmt.Errorf("remove or rename regular file `%s` (must be a directory)", p) } } return err } func findRegularFile(p string) string { for { if s, err := os.Stat(p); err == nil && s.Mode().IsRegular() { return p } newPath := filepath.Dir(p) if newPath == p || newPath == "/" || newPath == "." { break } p = newPath } return "" }
internal/config/config_file.go
1
https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c
[ 0.9982370138168335, 0.15359564125537872, 0.00016230481560342014, 0.0045035770162940025, 0.342548131942749 ]
{ "id": 8, "code_window": [ "\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n", "\t\treturn migrateFile(oldPath, newPath, \"state.yml\")\n", "\t}\n", "\n", "\tpath, err = homedir.Dir()\n", "\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n", "\t\treturn migrateFile(oldPath, newPath, \"state.yml\")\n", "\t}\n", "\n", "\treturn errNotExist\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "internal/config/config_file.go", "type": "replace", "edit_start_line_idx": 121 }
name: goreleaser on: push: tags: - "v*" jobs: goreleaser: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v2 - name: Set up Go 1.15 uses: actions/setup-go@v2 with: go-version: 1.15 - name: Generate changelog run: | echo "GORELEASER_CURRENT_TAG=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV git fetch --unshallow script/changelog | tee CHANGELOG.md - name: Run GoReleaser uses: goreleaser/goreleaser-action@v2 with: version: v0.174.1 args: release --release-notes=CHANGELOG.md env: GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} - name: Checkout documentation site uses: actions/checkout@v2 with: repository: github/cli.github.com path: site fetch-depth: 0 token: ${{secrets.SITE_GITHUB_TOKEN}} - name: Update site man pages env: GIT_COMMITTER_NAME: cli automation GIT_AUTHOR_NAME: cli automation GIT_COMMITTER_EMAIL: [email protected] GIT_AUTHOR_EMAIL: [email protected] run: make site-bump - name: Move project cards continue-on-error: true env: GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} PENDING_COLUMN: 8189733 DONE_COLUMN: 7110130 run: | api() { gh api -H 'accept: application/vnd.github.inertia-preview+json' "$@"; } api-write() { [[ $GITHUB_REF == *-* ]] && echo "skipping: api $*" || api "$@"; } cards=$(api --paginate projects/columns/$PENDING_COLUMN/cards | jq ".[].id") for card in $cards; do api-write --silent projects/columns/cards/$card/moves -f position=top -F column_id=$DONE_COLUMN done echo "moved ${#cards[@]} cards to the Done column" - name: Install packaging dependencies run: sudo apt-get install -y rpm reprepro - name: Set up GPG run: | gpg --import --no-tty --batch --yes < script/pubkey.asc echo "${{secrets.GPG_KEY}}" | base64 -d | gpg --import --no-tty --batch --yes echo "allow-preset-passphrase" > ~/.gnupg/gpg-agent.conf gpg-connect-agent RELOADAGENT /bye echo "${{secrets.GPG_PASSPHRASE}}" | /usr/lib/gnupg2/gpg-preset-passphrase --preset 867DAD5051270B843EF54F6186FA10E3A1D22DC5 - name: Sign RPMs run: | cp script/rpmmacros ~/.rpmmacros rpmsign --addsign dist/*.rpm - name: Run createrepo run: | mkdir -p site/packages/rpm cp dist/*.rpm site/packages/rpm/ ./script/createrepo.sh cp -r dist/repodata site/packages/rpm/ pushd site/packages/rpm gpg --yes --detach-sign --armor repodata/repomd.xml popd - name: Run reprepro env: RELEASES: "cosmic eoan disco groovy focal stable oldstable testing sid unstable buster bullseye stretch jessie bionic trusty precise xenial hirsute impish kali-rolling" run: | mkdir -p upload for release in $RELEASES; do for file in dist/*.deb; do reprepro --confdir="+b/script" includedeb "$release" "$file" done done cp -a dists/ pool/ upload/ mkdir -p site/packages cp -a upload/* site/packages/ - name: Publish site env: GIT_COMMITTER_NAME: cli automation GIT_AUTHOR_NAME: cli automation GIT_COMMITTER_EMAIL: [email protected] GIT_AUTHOR_EMAIL: [email protected] working-directory: ./site run: | git add packages git commit -m "Add rpm and deb packages for ${GITHUB_REF#refs/tags/}" if [[ $GITHUB_REF == *-* ]]; then git log --oneline @{upstream}.. git diff --name-status @{upstream}.. else git push fi msi: needs: goreleaser runs-on: windows-latest steps: - name: Checkout uses: actions/checkout@v2 - name: Download gh.exe id: download_exe shell: bash run: | hub release download "${GITHUB_REF#refs/tags/}" -i '*windows_amd64*.zip' printf "::set-output name=zip::%s\n" *.zip unzip -o *.zip && rm -v *.zip env: GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} - name: Install go-msi run: choco install -y "go-msi" - name: Prepare PATH shell: bash run: | echo "$WIX\\bin" >> $GITHUB_PATH echo "C:\\Program Files\\go-msi" >> $GITHUB_PATH - name: Build MSI id: buildmsi shell: bash env: ZIP_FILE: ${{ steps.download_exe.outputs.zip }} run: | mkdir -p build msi="$(basename "$ZIP_FILE" ".zip").msi" printf "::set-output name=msi::%s\n" "$msi" go-msi make --msi "$PWD/$msi" --out "$PWD/build" --version "${GITHUB_REF#refs/tags/}" - name: Obtain signing cert id: obtain_cert env: DESKTOP_CERT_TOKEN: ${{ secrets.DESKTOP_CERT_TOKEN }} run: .\script\setup-windows-certificate.ps1 - name: Sign MSI env: CERT_FILE: ${{ steps.obtain_cert.outputs.cert-file }} EXE_FILE: ${{ steps.buildmsi.outputs.msi }} GITHUB_CERT_PASSWORD: ${{ secrets.GITHUB_CERT_PASSWORD }} run: .\script\sign.ps1 -Certificate $env:CERT_FILE -Executable $env:EXE_FILE - name: Upload MSI shell: bash run: | tag_name="${GITHUB_REF#refs/tags/}" hub release edit "$tag_name" -m "" -a "$MSI_FILE" release_url="$(gh api repos/:owner/:repo/releases -q ".[]|select(.tag_name==\"${tag_name}\")|.url")" publish_args=( -F draft=false ) if [[ $GITHUB_REF != *-* ]]; then publish_args+=( -f discussion_category_name="$DISCUSSION_CATEGORY" ) fi gh api -X PATCH "$release_url" "${publish_args[@]}" env: MSI_FILE: ${{ steps.buildmsi.outputs.msi }} DISCUSSION_CATEGORY: General GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} - name: Bump homebrew-core formula uses: mislav/bump-homebrew-formula-action@v1 if: "!contains(github.ref, '-')" # skip prereleases with: formula-name: gh env: COMMITTER_TOKEN: ${{ secrets.UPLOAD_GITHUB_TOKEN }} - name: Checkout scoop bucket uses: actions/checkout@v2 with: repository: cli/scoop-gh path: scoop-gh fetch-depth: 0 token: ${{secrets.UPLOAD_GITHUB_TOKEN}} - name: Bump scoop bucket shell: bash run: | hub release download "${GITHUB_REF#refs/tags/}" -i '*_checksums.txt' script/scoop-gen "${GITHUB_REF#refs/tags/}" ./scoop-gh/gh.json < *_checksums.txt git -C ./scoop-gh commit -m "gh ${GITHUB_REF#refs/tags/}" gh.json if [[ $GITHUB_REF == *-* ]]; then git -C ./scoop-gh show -m else git -C ./scoop-gh push fi env: GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} GIT_COMMITTER_NAME: cli automation GIT_AUTHOR_NAME: cli automation GIT_COMMITTER_EMAIL: [email protected] GIT_AUTHOR_EMAIL: [email protected] - name: Bump Winget manifest shell: pwsh env: WINGETCREATE_VERSION: v0.2.0.29-preview GITHUB_TOKEN: ${{ secrets.UPLOAD_GITHUB_TOKEN }} run: | $tagname = $env:GITHUB_REF.Replace("refs/tags/", "") $version = $tagname.Replace("v", "") $url = "https://github.com/cli/cli/releases/download/${tagname}/gh_${version}_windows_amd64.msi" iwr https://github.com/microsoft/winget-create/releases/download/${env:WINGETCREATE_VERSION}/wingetcreate.exe -OutFile wingetcreate.exe .\wingetcreate.exe update GitHub.cli --url $url --version $version if ($version -notmatch "-") { .\wingetcreate.exe submit .\manifests\g\GitHub\cli\${version}\ --token $env:GITHUB_TOKEN }
.github/workflows/releases.yml
0
https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c
[ 0.00017778616165742278, 0.00017269344243686646, 0.00016520952340215445, 0.00017337879398837686, 0.0000032233767797151813 ]
{ "id": 8, "code_window": [ "\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n", "\t\treturn migrateFile(oldPath, newPath, \"state.yml\")\n", "\t}\n", "\n", "\tpath, err = homedir.Dir()\n", "\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n", "\t\treturn migrateFile(oldPath, newPath, \"state.yml\")\n", "\t}\n", "\n", "\treturn errNotExist\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "internal/config/config_file.go", "type": "replace", "edit_start_line_idx": 121 }
package comment import ( "bytes" "fmt" "io/ioutil" "net/http" "path/filepath" "testing" "github.com/cli/cli/internal/ghrepo" "github.com/cli/cli/pkg/cmd/pr/shared" "github.com/cli/cli/pkg/cmdutil" "github.com/cli/cli/pkg/httpmock" "github.com/cli/cli/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNewCmdComment(t *testing.T) { tmpFile := filepath.Join(t.TempDir(), "my-body.md") err := ioutil.WriteFile(tmpFile, []byte("a body from file"), 0600) require.NoError(t, err) tests := []struct { name string input string stdin string output shared.CommentableOptions wantsErr bool }{ { name: "no arguments", input: "", output: shared.CommentableOptions{}, wantsErr: true, }, { name: "issue number", input: "1", output: shared.CommentableOptions{ Interactive: true, InputType: 0, Body: "", }, wantsErr: false, }, { name: "issue url", input: "https://github.com/OWNER/REPO/issues/12", output: shared.CommentableOptions{ Interactive: true, InputType: 0, Body: "", }, wantsErr: false, }, { name: "body flag", input: "1 --body test", output: shared.CommentableOptions{ Interactive: false, InputType: shared.InputTypeInline, Body: "test", }, wantsErr: false, }, { name: "body from stdin", input: "1 --body-file -", stdin: "this is on standard input", output: shared.CommentableOptions{ Interactive: false, InputType: shared.InputTypeInline, Body: "this is on standard input", }, wantsErr: false, }, { name: "body from file", input: fmt.Sprintf("1 --body-file '%s'", tmpFile), output: shared.CommentableOptions{ Interactive: false, InputType: shared.InputTypeInline, Body: "a body from file", }, wantsErr: false, }, { name: "editor flag", input: "1 --editor", output: shared.CommentableOptions{ Interactive: false, InputType: shared.InputTypeEditor, Body: "", }, wantsErr: false, }, { name: "web flag", input: "1 --web", output: shared.CommentableOptions{ Interactive: false, InputType: shared.InputTypeWeb, Body: "", }, wantsErr: false, }, { name: "body and body-file flags", input: "1 --body 'test' --body-file 'test-file.txt'", output: shared.CommentableOptions{}, wantsErr: true, }, { name: "editor and web flags", input: "1 --editor --web", output: shared.CommentableOptions{}, wantsErr: true, }, { name: "editor and body flags", input: "1 --editor --body test", output: shared.CommentableOptions{}, wantsErr: true, }, { name: "web and body flags", input: "1 --web --body test", output: shared.CommentableOptions{}, wantsErr: true, }, { name: "editor, web, and body flags", input: "1 --editor --web --body test", output: shared.CommentableOptions{}, wantsErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { io, stdin, _, _ := iostreams.Test() io.SetStdoutTTY(true) io.SetStdinTTY(true) io.SetStderrTTY(true) if tt.stdin != "" { _, _ = stdin.WriteString(tt.stdin) } f := &cmdutil.Factory{ IOStreams: io, Browser: &cmdutil.TestBrowser{}, } argv, err := shlex.Split(tt.input) assert.NoError(t, err) var gotOpts *shared.CommentableOptions cmd := NewCmdComment(f, func(opts *shared.CommentableOptions) error { gotOpts = opts return nil }) cmd.Flags().BoolP("help", "x", false, "") cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.output.Interactive, gotOpts.Interactive) assert.Equal(t, tt.output.InputType, gotOpts.InputType) assert.Equal(t, tt.output.Body, gotOpts.Body) }) } } func Test_commentRun(t *testing.T) { tests := []struct { name string input *shared.CommentableOptions httpStubs func(*testing.T, *httpmock.Registry) stdout string stderr string }{ { name: "interactive editor", input: &shared.CommentableOptions{ Interactive: true, InputType: 0, Body: "", InteractiveEditSurvey: func() (string, error) { return "comment body", nil }, ConfirmSubmitSurvey: func() (bool, error) { return true, nil }, }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { mockIssueFromNumber(t, reg) mockCommentCreate(t, reg) }, stdout: "https://github.com/OWNER/REPO/issues/123#issuecomment-456\n", }, { name: "non-interactive web", input: &shared.CommentableOptions{ Interactive: false, InputType: shared.InputTypeWeb, Body: "", OpenInBrowser: func(string) error { return nil }, }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { mockIssueFromNumber(t, reg) }, stderr: "Opening github.com/OWNER/REPO/issues/123 in your browser.\n", }, { name: "non-interactive editor", input: &shared.CommentableOptions{ Interactive: false, InputType: shared.InputTypeEditor, Body: "", EditSurvey: func() (string, error) { return "comment body", nil }, }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { mockIssueFromNumber(t, reg) mockCommentCreate(t, reg) }, stdout: "https://github.com/OWNER/REPO/issues/123#issuecomment-456\n", }, { name: "non-interactive inline", input: &shared.CommentableOptions{ Interactive: false, InputType: shared.InputTypeInline, Body: "comment body", }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { mockIssueFromNumber(t, reg) mockCommentCreate(t, reg) }, stdout: "https://github.com/OWNER/REPO/issues/123#issuecomment-456\n", }, } for _, tt := range tests { io, _, stdout, stderr := iostreams.Test() io.SetStdoutTTY(true) io.SetStdinTTY(true) io.SetStderrTTY(true) reg := &httpmock.Registry{} defer reg.Verify(t) tt.httpStubs(t, reg) httpClient := func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } baseRepo := func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil } tt.input.IO = io tt.input.HttpClient = httpClient tt.input.RetrieveCommentable = retrieveIssue(tt.input.HttpClient, baseRepo, "123") t.Run(tt.name, func(t *testing.T) { err := shared.CommentableRun(tt.input) assert.NoError(t, err) assert.Equal(t, tt.stdout, stdout.String()) assert.Equal(t, tt.stderr, stderr.String()) }) } } func mockIssueFromNumber(_ *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "number": 123, "url": "https://github.com/OWNER/REPO/issues/123" } } } }`), ) } func mockCommentCreate(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`mutation CommentCreate\b`), httpmock.GraphQLMutation(` { "data": { "addComment": { "commentEdge": { "node": { "url": "https://github.com/OWNER/REPO/issues/123#issuecomment-456" } } } } }`, func(inputs map[string]interface{}) { assert.Equal(t, "comment body", inputs["body"]) }), ) }
pkg/cmd/issue/comment/comment_test.go
0
https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c
[ 0.00048205809434875846, 0.00018193638243246824, 0.00016523110389243811, 0.00017286831280216575, 0.000054871234169695526 ]
{ "id": 8, "code_window": [ "\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n", "\t\treturn migrateFile(oldPath, newPath, \"state.yml\")\n", "\t}\n", "\n", "\tpath, err = homedir.Dir()\n", "\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n", "\t\treturn migrateFile(oldPath, newPath, \"state.yml\")\n", "\t}\n", "\n", "\treturn errNotExist\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "internal/config/config_file.go", "type": "replace", "edit_start_line_idx": 121 }
package extension import ( "bytes" "errors" "fmt" "io" "io/ioutil" "os" "os/exec" "path" "path/filepath" "runtime" "strings" "github.com/cli/cli/internal/config" "github.com/cli/cli/pkg/extensions" "github.com/cli/cli/pkg/findsh" "github.com/cli/safeexec" ) type Manager struct { dataDir func() string lookPath func(string) (string, error) findSh func() (string, error) newCommand func(string, ...string) *exec.Cmd } func NewManager() *Manager { return &Manager{ dataDir: config.DataDir, lookPath: safeexec.LookPath, findSh: findsh.Find, newCommand: exec.Command, } } func (m *Manager) Dispatch(args []string, stdin io.Reader, stdout, stderr io.Writer) (bool, error) { if len(args) == 0 { return false, errors.New("too few arguments in list") } var exe string extName := args[0] forwardArgs := args[1:] exts, _ := m.list(false) for _, e := range exts { if e.Name() == extName { exe = e.Path() break } } if exe == "" { return false, nil } var externalCmd *exec.Cmd if runtime.GOOS == "windows" { // Dispatch all extension calls through the `sh` interpreter to support executable files with a // shebang line on Windows. shExe, err := m.findSh() if err != nil { if errors.Is(err, exec.ErrNotFound) { return true, errors.New("the `sh.exe` interpreter is required. Please install Git for Windows and try again") } return true, err } forwardArgs = append([]string{"-c", `command "$@"`, "--", exe}, forwardArgs...) externalCmd = m.newCommand(shExe, forwardArgs...) } else { externalCmd = m.newCommand(exe, forwardArgs...) } externalCmd.Stdin = stdin externalCmd.Stdout = stdout externalCmd.Stderr = stderr return true, externalCmd.Run() } func (m *Manager) List(includeMetadata bool) []extensions.Extension { exts, _ := m.list(includeMetadata) return exts } func (m *Manager) list(includeMetadata bool) ([]extensions.Extension, error) { dir := m.installDir() entries, err := ioutil.ReadDir(dir) if err != nil { return nil, err } var results []extensions.Extension for _, f := range entries { if !strings.HasPrefix(f.Name(), "gh-") { continue } var remoteUrl string updateAvailable := false isLocal := false exePath := filepath.Join(dir, f.Name(), f.Name()) if f.IsDir() { if includeMetadata { remoteUrl = m.getRemoteUrl(f.Name()) updateAvailable = m.checkUpdateAvailable(f.Name()) } } else { isLocal = true if !isSymlink(f.Mode()) { // if this is a regular file, its contents is the local directory of the extension p, err := readPathFromFile(filepath.Join(dir, f.Name())) if err != nil { return nil, err } exePath = filepath.Join(p, f.Name()) } } results = append(results, &Extension{ path: exePath, url: remoteUrl, isLocal: isLocal, updateAvailable: updateAvailable, }) } return results, nil } func (m *Manager) getRemoteUrl(extension string) string { gitExe, err := m.lookPath("git") if err != nil { return "" } dir := m.installDir() gitDir := "--git-dir=" + filepath.Join(dir, extension, ".git") cmd := m.newCommand(gitExe, gitDir, "config", "remote.origin.url") url, err := cmd.Output() if err != nil { return "" } return strings.TrimSpace(string(url)) } func (m *Manager) checkUpdateAvailable(extension string) bool { gitExe, err := m.lookPath("git") if err != nil { return false } dir := m.installDir() gitDir := "--git-dir=" + filepath.Join(dir, extension, ".git") cmd := m.newCommand(gitExe, gitDir, "ls-remote", "origin", "HEAD") lsRemote, err := cmd.Output() if err != nil { return false } remoteSha := bytes.SplitN(lsRemote, []byte("\t"), 2)[0] cmd = m.newCommand(gitExe, gitDir, "rev-parse", "HEAD") localSha, err := cmd.Output() if err != nil { return false } localSha = bytes.TrimSpace(localSha) return !bytes.Equal(remoteSha, localSha) } func (m *Manager) InstallLocal(dir string) error { name := filepath.Base(dir) targetLink := filepath.Join(m.installDir(), name) if err := os.MkdirAll(filepath.Dir(targetLink), 0755); err != nil { return err } return makeSymlink(dir, targetLink) } func (m *Manager) Install(cloneURL string, stdout, stderr io.Writer) error { exe, err := m.lookPath("git") if err != nil { return err } name := strings.TrimSuffix(path.Base(cloneURL), ".git") targetDir := filepath.Join(m.installDir(), name) externalCmd := m.newCommand(exe, "clone", cloneURL, targetDir) externalCmd.Stdout = stdout externalCmd.Stderr = stderr return externalCmd.Run() } var localExtensionUpgradeError = errors.New("local extensions can not be upgraded") func (m *Manager) Upgrade(name string, force bool, stdout, stderr io.Writer) error { exe, err := m.lookPath("git") if err != nil { return err } exts := m.List(false) if len(exts) == 0 { return errors.New("no extensions installed") } someUpgraded := false for _, f := range exts { if name == "" { fmt.Fprintf(stdout, "[%s]: ", f.Name()) } else if f.Name() != name { continue } if f.IsLocal() { if name == "" { fmt.Fprintf(stdout, "%s\n", localExtensionUpgradeError) } else { err = localExtensionUpgradeError } continue } var cmds []*exec.Cmd dir := filepath.Dir(f.Path()) if force { fetchCmd := m.newCommand(exe, "-C", dir, "--git-dir="+filepath.Join(dir, ".git"), "fetch", "origin", "HEAD") resetCmd := m.newCommand(exe, "-C", dir, "--git-dir="+filepath.Join(dir, ".git"), "reset", "--hard", "origin/HEAD") cmds = []*exec.Cmd{fetchCmd, resetCmd} } else { pullCmd := m.newCommand(exe, "-C", dir, "--git-dir="+filepath.Join(dir, ".git"), "pull", "--ff-only") cmds = []*exec.Cmd{pullCmd} } if e := runCmds(cmds, stdout, stderr); e != nil { err = e } someUpgraded = true } if err == nil && !someUpgraded { err = fmt.Errorf("no extension matched %q", name) } return err } func (m *Manager) Remove(name string) error { targetDir := filepath.Join(m.installDir(), "gh-"+name) if _, err := os.Lstat(targetDir); os.IsNotExist(err) { return fmt.Errorf("no extension found: %q", targetDir) } return os.RemoveAll(targetDir) } func (m *Manager) installDir() string { return filepath.Join(m.dataDir(), "extensions") } func runCmds(cmds []*exec.Cmd, stdout, stderr io.Writer) error { for _, cmd := range cmds { cmd.Stdout = stdout cmd.Stderr = stderr if err := cmd.Run(); err != nil { return err } } return nil } func isSymlink(m os.FileMode) bool { return m&os.ModeSymlink != 0 } // reads the product of makeSymlink on Windows func readPathFromFile(path string) (string, error) { f, err := os.Open(path) if err != nil { return "", err } defer f.Close() b := make([]byte, 1024) n, err := f.Read(b) return strings.TrimSpace(string(b[:n])), err }
pkg/cmd/extension/manager.go
0
https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c
[ 0.8597782850265503, 0.03166757896542549, 0.00016368180513381958, 0.00017463252879679203, 0.15938299894332886 ]
{ "id": 9, "code_window": [ "}\n", "\n", "func HomeDirPath(subdir string) (string, error) {\n", "\thomeDir, err := os.UserHomeDir()\n", "\tif err != nil {\n", "\t\t// TODO: remove go-homedir fallback in GitHub CLI v2\n", "\t\tif legacyDir, err := homedir.Dir(); err == nil {\n", "\t\t\treturn filepath.Join(legacyDir, subdir), nil\n", "\t\t}\n", "\t\treturn \"\", err\n", "\t}\n", "\n", "\tnewPath := filepath.Join(homeDir, subdir)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "internal/config/config_file.go", "type": "replace", "edit_start_line_idx": 183 }
module github.com/cli/cli go 1.13 require ( github.com/AlecAivazis/survey/v2 v2.2.14 github.com/MakeNowJust/heredoc v1.0.0 github.com/briandowns/spinner v1.11.1 github.com/charmbracelet/glamour v0.3.0 github.com/cli/browser v1.1.0 github.com/cli/oauth v0.8.0 github.com/cli/safeexec v1.0.0 github.com/cpuguy83/go-md2man/v2 v2.0.0 github.com/creack/pty v1.1.13 github.com/gabriel-vasile/mimetype v1.1.2 github.com/google/go-cmp v0.5.5 github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 github.com/hashicorp/go-version v1.2.1 github.com/henvic/httpretty v0.0.6 github.com/itchyny/gojq v0.12.4 github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 github.com/mattn/go-colorable v0.1.8 github.com/mattn/go-isatty v0.0.13 github.com/mattn/go-runewidth v0.0.10 github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d github.com/mitchellh/go-homedir v1.1.0 github.com/muesli/termenv v0.8.1 github.com/rivo/uniseg v0.2.0 github.com/shurcooL/githubv4 v0.0.0-20200928013246-d292edc3691b github.com/shurcooL/graphql v0.0.0-20181231061246-d48a9a75455f github.com/spf13/cobra v1.2.1 github.com/spf13/pflag v1.0.5 github.com/stretchr/objx v0.1.1 // indirect github.com/stretchr/testify v1.7.0 golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c golang.org/x/sys v0.0.0-20210601080250-7ecdf8ef093b golang.org/x/term v0.0.0-20210503060354-a79de5458b56 gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b ) replace github.com/shurcooL/graphql => github.com/cli/shurcooL-graphql v0.0.0-20200707151639-0f7232a2bf7e
go.mod
1
https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c
[ 0.0020078113302588463, 0.0005408516735769808, 0.00016540211800020188, 0.00016706627502571791, 0.0007335874834097922 ]
{ "id": 9, "code_window": [ "}\n", "\n", "func HomeDirPath(subdir string) (string, error) {\n", "\thomeDir, err := os.UserHomeDir()\n", "\tif err != nil {\n", "\t\t// TODO: remove go-homedir fallback in GitHub CLI v2\n", "\t\tif legacyDir, err := homedir.Dir(); err == nil {\n", "\t\t\treturn filepath.Join(legacyDir, subdir), nil\n", "\t\t}\n", "\t\treturn \"\", err\n", "\t}\n", "\n", "\tnewPath := filepath.Join(homeDir, subdir)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "internal/config/config_file.go", "type": "replace", "edit_start_line_idx": 183 }
package clone import ( "fmt" "net/http" "strings" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/api" "github.com/cli/cli/git" "github.com/cli/cli/internal/config" "github.com/cli/cli/internal/ghrepo" "github.com/cli/cli/pkg/cmdutil" "github.com/cli/cli/pkg/iostreams" "github.com/spf13/cobra" "github.com/spf13/pflag" ) type CloneOptions struct { HttpClient func() (*http.Client, error) Config func() (config.Config, error) IO *iostreams.IOStreams GitArgs []string Repository string } func NewCmdClone(f *cmdutil.Factory, runF func(*CloneOptions) error) *cobra.Command { opts := &CloneOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Config: f.Config, } cmd := &cobra.Command{ DisableFlagsInUseLine: true, Use: "clone <repository> [<directory>] [-- <gitflags>...]", Args: cmdutil.MinimumArgs(1, "cannot clone: repository argument required"), Short: "Clone a repository locally", Long: heredoc.Doc(` Clone a GitHub repository locally. If the "OWNER/" portion of the "OWNER/REPO" repository argument is omitted, it defaults to the name of the authenticating user. Pass additional 'git clone' flags by listing them after '--'. `), RunE: func(cmd *cobra.Command, args []string) error { opts.Repository = args[0] opts.GitArgs = args[1:] if runF != nil { return runF(opts) } return cloneRun(opts) }, } cmd.SetFlagErrorFunc(func(cmd *cobra.Command, err error) error { if err == pflag.ErrHelp { return err } return &cmdutil.FlagError{Err: fmt.Errorf("%w\nSeparate git clone flags with '--'.", err)} }) return cmd } func cloneRun(opts *CloneOptions) error { httpClient, err := opts.HttpClient() if err != nil { return err } cfg, err := opts.Config() if err != nil { return err } apiClient := api.NewClientFromHTTP(httpClient) repositoryIsURL := strings.Contains(opts.Repository, ":") repositoryIsFullName := !repositoryIsURL && strings.Contains(opts.Repository, "/") var repo ghrepo.Interface var protocol string if repositoryIsURL { repoURL, err := git.ParseURL(opts.Repository) if err != nil { return err } repo, err = ghrepo.FromURL(repoURL) if err != nil { return err } if repoURL.Scheme == "git+ssh" { repoURL.Scheme = "ssh" } protocol = repoURL.Scheme } else { var fullName string if repositoryIsFullName { fullName = opts.Repository } else { host, err := cfg.DefaultHost() if err != nil { return err } currentUser, err := api.CurrentLoginName(apiClient, host) if err != nil { return err } fullName = currentUser + "/" + opts.Repository } repo, err = ghrepo.FromFullName(fullName) if err != nil { return err } protocol, err = cfg.Get(repo.RepoHost(), "git_protocol") if err != nil { return err } } wantsWiki := strings.HasSuffix(repo.RepoName(), ".wiki") if wantsWiki { repoName := strings.TrimSuffix(repo.RepoName(), ".wiki") repo = ghrepo.NewWithHost(repo.RepoOwner(), repoName, repo.RepoHost()) } // Load the repo from the API to get the username/repo name in its // canonical capitalization canonicalRepo, err := api.GitHubRepo(apiClient, repo) if err != nil { return err } canonicalCloneURL := ghrepo.FormatRemoteURL(canonicalRepo, protocol) // If repo HasWikiEnabled and wantsWiki is true then create a new clone URL if wantsWiki { if !canonicalRepo.HasWikiEnabled { return fmt.Errorf("The '%s' repository does not have a wiki", ghrepo.FullName(canonicalRepo)) } canonicalCloneURL = strings.TrimSuffix(canonicalCloneURL, ".git") + ".wiki.git" } cloneDir, err := git.RunClone(canonicalCloneURL, opts.GitArgs) if err != nil { return err } // If the repo is a fork, add the parent as an upstream if canonicalRepo.Parent != nil { protocol, err := cfg.Get(canonicalRepo.Parent.RepoHost(), "git_protocol") if err != nil { return err } upstreamURL := ghrepo.FormatRemoteURL(canonicalRepo.Parent, protocol) err = git.AddUpstreamRemote(upstreamURL, cloneDir, []string{canonicalRepo.Parent.DefaultBranchRef.Name}) if err != nil { return err } } return nil }
pkg/cmd/repo/clone/clone.go
0
https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c
[ 0.002753589069470763, 0.0005446862778626382, 0.00016656778461765498, 0.00019994887406937778, 0.0007065608515404165 ]
{ "id": 9, "code_window": [ "}\n", "\n", "func HomeDirPath(subdir string) (string, error) {\n", "\thomeDir, err := os.UserHomeDir()\n", "\tif err != nil {\n", "\t\t// TODO: remove go-homedir fallback in GitHub CLI v2\n", "\t\tif legacyDir, err := homedir.Dir(); err == nil {\n", "\t\t\treturn filepath.Join(legacyDir, subdir), nil\n", "\t\t}\n", "\t\treturn \"\", err\n", "\t}\n", "\n", "\tnewPath := filepath.Join(homeDir, subdir)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "internal/config/config_file.go", "type": "replace", "edit_start_line_idx": 183 }
package delete import ( "fmt" "github.com/cli/cli/internal/config" "github.com/cli/cli/pkg/cmdutil" "github.com/cli/cli/pkg/iostreams" "github.com/spf13/cobra" ) type DeleteOptions struct { Config func() (config.Config, error) IO *iostreams.IOStreams Name string } func NewCmdDelete(f *cmdutil.Factory, runF func(*DeleteOptions) error) *cobra.Command { opts := &DeleteOptions{ IO: f.IOStreams, Config: f.Config, } cmd := &cobra.Command{ Use: "delete <alias>", Short: "Delete an alias", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.Name = args[0] if runF != nil { return runF(opts) } return deleteRun(opts) }, } return cmd } func deleteRun(opts *DeleteOptions) error { cfg, err := opts.Config() if err != nil { return err } aliasCfg, err := cfg.Aliases() if err != nil { return fmt.Errorf("couldn't read aliases config: %w", err) } expansion, ok := aliasCfg.Get(opts.Name) if !ok { return fmt.Errorf("no such alias %s", opts.Name) } err = aliasCfg.Delete(opts.Name) if err != nil { return fmt.Errorf("failed to delete alias %s: %w", opts.Name, err) } if opts.IO.IsStdoutTTY() { cs := opts.IO.ColorScheme() fmt.Fprintf(opts.IO.ErrOut, "%s Deleted alias %s; was %s\n", cs.SuccessIconWithColor(cs.Red), opts.Name, expansion) } return nil }
pkg/cmd/alias/delete/delete.go
0
https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c
[ 0.001172196469269693, 0.0003384464362170547, 0.00016693842189852148, 0.00018121050379704684, 0.0003283908008597791 ]
{ "id": 9, "code_window": [ "}\n", "\n", "func HomeDirPath(subdir string) (string, error) {\n", "\thomeDir, err := os.UserHomeDir()\n", "\tif err != nil {\n", "\t\t// TODO: remove go-homedir fallback in GitHub CLI v2\n", "\t\tif legacyDir, err := homedir.Dir(); err == nil {\n", "\t\t\treturn filepath.Join(legacyDir, subdir), nil\n", "\t\t}\n", "\t\treturn \"\", err\n", "\t}\n", "\n", "\tnewPath := filepath.Join(homeDir, subdir)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "internal/config/config_file.go", "type": "replace", "edit_start_line_idx": 183 }
package sync import ( "github.com/stretchr/testify/mock" ) type mockGitClient struct { mock.Mock } func (g *mockGitClient) BranchRemote(a string) (string, error) { args := g.Called(a) return args.String(0), args.Error(1) } func (g *mockGitClient) UpdateBranch(b, r string) error { args := g.Called(b, r) return args.Error(0) } func (g *mockGitClient) CreateBranch(b, r, u string) error { args := g.Called(b, r, u) return args.Error(0) } func (g *mockGitClient) CurrentBranch() (string, error) { args := g.Called() return args.String(0), args.Error(1) } func (g *mockGitClient) Fetch(a, b string) error { args := g.Called(a, b) return args.Error(0) } func (g *mockGitClient) HasLocalBranch(a string) bool { args := g.Called(a) return args.Bool(0) } func (g *mockGitClient) IsAncestor(a, b string) (bool, error) { args := g.Called(a, b) return args.Bool(0), args.Error(1) } func (g *mockGitClient) IsDirty() (bool, error) { args := g.Called() return args.Bool(0), args.Error(1) } func (g *mockGitClient) MergeFastForward(a string) error { args := g.Called(a) return args.Error(0) } func (g *mockGitClient) ResetHard(a string) error { args := g.Called(a) return args.Error(0) }
pkg/cmd/repo/sync/mocks.go
0
https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c
[ 0.00023199697898235172, 0.00019164154946338385, 0.00017147847393061966, 0.0001877668546512723, 0.00001931330371007789 ]
{ "id": 10, "code_window": [ "\t\treturn \"\", err\n", "\t}\n", "\n", "\tnewPath := filepath.Join(homeDir, subdir)\n", "\tif s, err := os.Stat(newPath); err == nil && s.IsDir() {\n", "\t\treturn newPath, nil\n", "\t}\n", "\n", "\t// TODO: remove go-homedir fallback in GitHub CLI v2\n", "\tif legacyDir, err := homedir.Dir(); err == nil {\n", "\t\tlegacyPath := filepath.Join(legacyDir, subdir)\n", "\t\tif s, err := os.Stat(legacyPath); err == nil && s.IsDir() {\n", "\t\t\treturn legacyPath, nil\n", "\t\t}\n", "\t}\n", "\n", "\treturn newPath, nil\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "internal/config/config_file.go", "type": "replace", "edit_start_line_idx": 191 }
package config import ( "errors" "fmt" "io/ioutil" "os" "path/filepath" "runtime" "syscall" "github.com/mitchellh/go-homedir" "gopkg.in/yaml.v3" ) const ( GH_CONFIG_DIR = "GH_CONFIG_DIR" XDG_CONFIG_HOME = "XDG_CONFIG_HOME" XDG_STATE_HOME = "XDG_STATE_HOME" XDG_DATA_HOME = "XDG_DATA_HOME" APP_DATA = "AppData" LOCAL_APP_DATA = "LocalAppData" ) // Config path precedence // 1. GH_CONFIG_DIR // 2. XDG_CONFIG_HOME // 3. AppData (windows only) // 4. HOME func ConfigDir() string { var path string if a := os.Getenv(GH_CONFIG_DIR); a != "" { path = a } else if b := os.Getenv(XDG_CONFIG_HOME); b != "" { path = filepath.Join(b, "gh") } else if c := os.Getenv(APP_DATA); runtime.GOOS == "windows" && c != "" { path = filepath.Join(c, "GitHub CLI") } else { d, _ := os.UserHomeDir() path = filepath.Join(d, ".config", "gh") } // If the path does not exist and the GH_CONFIG_DIR flag is not set try // migrating config from default paths. if !dirExists(path) && os.Getenv(GH_CONFIG_DIR) == "" { _ = autoMigrateConfigDir(path) } return path } // State path precedence // 1. XDG_CONFIG_HOME // 2. LocalAppData (windows only) // 3. HOME func StateDir() string { var path string if a := os.Getenv(XDG_STATE_HOME); a != "" { path = filepath.Join(a, "gh") } else if b := os.Getenv(LOCAL_APP_DATA); runtime.GOOS == "windows" && b != "" { path = filepath.Join(b, "GitHub CLI") } else { c, _ := os.UserHomeDir() path = filepath.Join(c, ".local", "state", "gh") } // If the path does not exist try migrating state from default paths if !dirExists(path) { _ = autoMigrateStateDir(path) } return path } // Data path precedence // 1. XDG_DATA_HOME // 2. LocalAppData (windows only) // 3. HOME func DataDir() string { var path string if a := os.Getenv(XDG_DATA_HOME); a != "" { path = filepath.Join(a, "gh") } else if b := os.Getenv(LOCAL_APP_DATA); runtime.GOOS == "windows" && b != "" { path = filepath.Join(b, "GitHub CLI") } else { c, _ := os.UserHomeDir() path = filepath.Join(c, ".local", "share", "gh") } return path } var errSamePath = errors.New("same path") var errNotExist = errors.New("not exist") // Check default paths (os.UserHomeDir, and homedir.Dir) for existing configs // If configs exist then move them to newPath // TODO: Remove support for homedir.Dir location in v2 func autoMigrateConfigDir(newPath string) error { path, err := os.UserHomeDir() if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) { return migrateDir(oldPath, newPath) } path, err = homedir.Dir() if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) { return migrateDir(oldPath, newPath) } return errNotExist } // Check default paths (os.UserHomeDir, and homedir.Dir) for existing state file (state.yml) // If state file exist then move it to newPath // TODO: Remove support for homedir.Dir location in v2 func autoMigrateStateDir(newPath string) error { path, err := os.UserHomeDir() if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) { return migrateFile(oldPath, newPath, "state.yml") } path, err = homedir.Dir() if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) { return migrateFile(oldPath, newPath, "state.yml") } return errNotExist } func migrateFile(oldPath, newPath, file string) error { if oldPath == newPath { return errSamePath } oldFile := filepath.Join(oldPath, file) newFile := filepath.Join(newPath, file) if !fileExists(oldFile) { return errNotExist } _ = os.MkdirAll(filepath.Dir(newFile), 0755) return os.Rename(oldFile, newFile) } func migrateDir(oldPath, newPath string) error { if oldPath == newPath { return errSamePath } if !dirExists(oldPath) { return errNotExist } _ = os.MkdirAll(filepath.Dir(newPath), 0755) return os.Rename(oldPath, newPath) } func dirExists(path string) bool { f, err := os.Stat(path) return err == nil && f.IsDir() } func fileExists(path string) bool { f, err := os.Stat(path) return err == nil && !f.IsDir() } func ConfigFile() string { return filepath.Join(ConfigDir(), "config.yml") } func HostsConfigFile() string { return filepath.Join(ConfigDir(), "hosts.yml") } func ParseDefaultConfig() (Config, error) { return parseConfig(ConfigFile()) } func HomeDirPath(subdir string) (string, error) { homeDir, err := os.UserHomeDir() if err != nil { // TODO: remove go-homedir fallback in GitHub CLI v2 if legacyDir, err := homedir.Dir(); err == nil { return filepath.Join(legacyDir, subdir), nil } return "", err } newPath := filepath.Join(homeDir, subdir) if s, err := os.Stat(newPath); err == nil && s.IsDir() { return newPath, nil } // TODO: remove go-homedir fallback in GitHub CLI v2 if legacyDir, err := homedir.Dir(); err == nil { legacyPath := filepath.Join(legacyDir, subdir) if s, err := os.Stat(legacyPath); err == nil && s.IsDir() { return legacyPath, nil } } return newPath, nil } var ReadConfigFile = func(filename string) ([]byte, error) { f, err := os.Open(filename) if err != nil { return nil, pathError(err) } defer f.Close() data, err := ioutil.ReadAll(f) if err != nil { return nil, err } return data, nil } var WriteConfigFile = func(filename string, data []byte) error { err := os.MkdirAll(filepath.Dir(filename), 0771) if err != nil { return pathError(err) } cfgFile, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) // cargo coded from setup if err != nil { return err } defer cfgFile.Close() _, err = cfgFile.Write(data) return err } var BackupConfigFile = func(filename string) error { return os.Rename(filename, filename+".bak") } func parseConfigFile(filename string) ([]byte, *yaml.Node, error) { data, err := ReadConfigFile(filename) if err != nil { return nil, nil, err } root, err := parseConfigData(data) if err != nil { return nil, nil, err } return data, root, err } func parseConfigData(data []byte) (*yaml.Node, error) { var root yaml.Node err := yaml.Unmarshal(data, &root) if err != nil { return nil, err } if len(root.Content) == 0 { return &yaml.Node{ Kind: yaml.DocumentNode, Content: []*yaml.Node{{Kind: yaml.MappingNode}}, }, nil } if root.Content[0].Kind != yaml.MappingNode { return &root, fmt.Errorf("expected a top level map") } return &root, nil } func isLegacy(root *yaml.Node) bool { for _, v := range root.Content[0].Content { if v.Value == "github.com" { return true } } return false } func migrateConfig(filename string) error { b, err := ReadConfigFile(filename) if err != nil { return err } var hosts map[string][]yaml.Node err = yaml.Unmarshal(b, &hosts) if err != nil { return fmt.Errorf("error decoding legacy format: %w", err) } cfg := NewBlankConfig() for hostname, entries := range hosts { if len(entries) < 1 { continue } mapContent := entries[0].Content for i := 0; i < len(mapContent)-1; i += 2 { if err := cfg.Set(hostname, mapContent[i].Value, mapContent[i+1].Value); err != nil { return err } } } err = BackupConfigFile(filename) if err != nil { return fmt.Errorf("failed to back up existing config: %w", err) } return cfg.Write() } func parseConfig(filename string) (Config, error) { _, root, err := parseConfigFile(filename) if err != nil { if os.IsNotExist(err) { root = NewBlankRoot() } else { return nil, err } } if isLegacy(root) { err = migrateConfig(filename) if err != nil { return nil, fmt.Errorf("error migrating legacy config: %w", err) } _, root, err = parseConfigFile(filename) if err != nil { return nil, fmt.Errorf("failed to reparse migrated config: %w", err) } } else { if _, hostsRoot, err := parseConfigFile(HostsConfigFile()); err == nil { if len(hostsRoot.Content[0].Content) > 0 { newContent := []*yaml.Node{ {Value: "hosts"}, hostsRoot.Content[0], } restContent := root.Content[0].Content root.Content[0].Content = append(newContent, restContent...) } } else if !errors.Is(err, os.ErrNotExist) { return nil, err } } return NewConfig(root), nil } func pathError(err error) error { var pathError *os.PathError if errors.As(err, &pathError) && errors.Is(pathError.Err, syscall.ENOTDIR) { if p := findRegularFile(pathError.Path); p != "" { return fmt.Errorf("remove or rename regular file `%s` (must be a directory)", p) } } return err } func findRegularFile(p string) string { for { if s, err := os.Stat(p); err == nil && s.Mode().IsRegular() { return p } newPath := filepath.Dir(p) if newPath == p || newPath == "/" || newPath == "." { break } p = newPath } return "" }
internal/config/config_file.go
1
https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c
[ 0.9985137581825256, 0.03836289793252945, 0.00016054061416070908, 0.0005060109542682767, 0.17061063647270203 ]
{ "id": 10, "code_window": [ "\t\treturn \"\", err\n", "\t}\n", "\n", "\tnewPath := filepath.Join(homeDir, subdir)\n", "\tif s, err := os.Stat(newPath); err == nil && s.IsDir() {\n", "\t\treturn newPath, nil\n", "\t}\n", "\n", "\t// TODO: remove go-homedir fallback in GitHub CLI v2\n", "\tif legacyDir, err := homedir.Dir(); err == nil {\n", "\t\tlegacyPath := filepath.Join(legacyDir, subdir)\n", "\t\tif s, err := os.Stat(legacyPath); err == nil && s.IsDir() {\n", "\t\t\treturn legacyPath, nil\n", "\t\t}\n", "\t}\n", "\n", "\treturn newPath, nil\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "internal/config/config_file.go", "type": "replace", "edit_start_line_idx": 191 }
package api import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "sort" "strings" "time" "github.com/cli/cli/internal/ghrepo" "github.com/shurcooL/githubv4" ) // Repository contains information about a GitHub repo type Repository struct { ID string Name string NameWithOwner string Owner RepositoryOwner Parent *Repository TemplateRepository *Repository Description string HomepageURL string OpenGraphImageURL string UsesCustomOpenGraphImage bool URL string SSHURL string MirrorURL string SecurityPolicyURL string CreatedAt time.Time PushedAt *time.Time UpdatedAt time.Time IsBlankIssuesEnabled bool IsSecurityPolicyEnabled bool HasIssuesEnabled bool HasProjectsEnabled bool HasWikiEnabled bool MergeCommitAllowed bool SquashMergeAllowed bool RebaseMergeAllowed bool ForkCount int StargazerCount int Watchers struct { TotalCount int `json:"totalCount"` } Issues struct { TotalCount int `json:"totalCount"` } PullRequests struct { TotalCount int `json:"totalCount"` } CodeOfConduct *CodeOfConduct ContactLinks []ContactLink DefaultBranchRef BranchRef DeleteBranchOnMerge bool DiskUsage int FundingLinks []FundingLink IsArchived bool IsEmpty bool IsFork bool IsInOrganization bool IsMirror bool IsPrivate bool IsTemplate bool IsUserConfigurationRepository bool LicenseInfo *RepositoryLicense ViewerCanAdminister bool ViewerDefaultCommitEmail string ViewerDefaultMergeMethod string ViewerHasStarred bool ViewerPermission string ViewerPossibleCommitEmails []string ViewerSubscription string RepositoryTopics struct { Nodes []struct { Topic RepositoryTopic } } PrimaryLanguage *CodingLanguage Languages struct { Edges []struct { Size int `json:"size"` Node CodingLanguage `json:"node"` } } IssueTemplates []IssueTemplate PullRequestTemplates []PullRequestTemplate Labels struct { Nodes []IssueLabel } Milestones struct { Nodes []Milestone } LatestRelease *RepositoryRelease AssignableUsers struct { Nodes []GitHubUser } MentionableUsers struct { Nodes []GitHubUser } Projects struct { Nodes []RepoProject } // pseudo-field that keeps track of host name of this repo hostname string } // RepositoryOwner is the owner of a GitHub repository type RepositoryOwner struct { ID string `json:"id"` Login string `json:"login"` } type GitHubUser struct { ID string `json:"id"` Login string `json:"login"` Name string `json:"name"` } // BranchRef is the branch name in a GitHub repository type BranchRef struct { Name string `json:"name"` } type CodeOfConduct struct { Key string `json:"key"` Name string `json:"name"` URL string `json:"url"` } type RepositoryLicense struct { Key string `json:"key"` Name string `json:"name"` Nickname string `json:"nickname"` } type ContactLink struct { About string `json:"about"` Name string `json:"name"` URL string `json:"url"` } type FundingLink struct { Platform string `json:"platform"` URL string `json:"url"` } type CodingLanguage struct { Name string `json:"name"` } type IssueTemplate struct { Name string `json:"name"` Title string `json:"title"` Body string `json:"body"` About string `json:"about"` } type PullRequestTemplate struct { Filename string `json:"filename"` Body string `json:"body"` } type RepositoryTopic struct { Name string `json:"name"` } type RepositoryRelease struct { Name string `json:"name"` TagName string `json:"tagName"` URL string `json:"url"` PublishedAt time.Time `json:"publishedAt"` } type IssueLabel struct { ID string `json:"id"` Name string `json:"name"` Description string `json:"description"` Color string `json:"color"` } type License struct { Key string `json:"key"` Name string `json:"name"` } // RepoOwner is the login name of the owner func (r Repository) RepoOwner() string { return r.Owner.Login } // RepoName is the name of the repository func (r Repository) RepoName() string { return r.Name } // RepoHost is the GitHub hostname of the repository func (r Repository) RepoHost() string { return r.hostname } // ViewerCanPush is true when the requesting user has push access func (r Repository) ViewerCanPush() bool { switch r.ViewerPermission { case "ADMIN", "MAINTAIN", "WRITE": return true default: return false } } // ViewerCanTriage is true when the requesting user can triage issues and pull requests func (r Repository) ViewerCanTriage() bool { switch r.ViewerPermission { case "ADMIN", "MAINTAIN", "WRITE", "TRIAGE": return true default: return false } } func GitHubRepo(client *Client, repo ghrepo.Interface) (*Repository, error) { query := ` fragment repo on Repository { id name owner { login } hasIssuesEnabled description hasWikiEnabled viewerPermission defaultBranchRef { name } } query RepositoryInfo($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { ...repo parent { ...repo } mergeCommitAllowed rebaseMergeAllowed squashMergeAllowed } }` variables := map[string]interface{}{ "owner": repo.RepoOwner(), "name": repo.RepoName(), } result := struct { Repository Repository }{} err := client.GraphQL(repo.RepoHost(), query, variables, &result) if err != nil { return nil, err } return InitRepoHostname(&result.Repository, repo.RepoHost()), nil } func RepoDefaultBranch(client *Client, repo ghrepo.Interface) (string, error) { if r, ok := repo.(*Repository); ok && r.DefaultBranchRef.Name != "" { return r.DefaultBranchRef.Name, nil } r, err := GitHubRepo(client, repo) if err != nil { return "", err } return r.DefaultBranchRef.Name, nil } func CanPushToRepo(httpClient *http.Client, repo ghrepo.Interface) (bool, error) { if r, ok := repo.(*Repository); ok && r.ViewerPermission != "" { return r.ViewerCanPush(), nil } apiClient := NewClientFromHTTP(httpClient) r, err := GitHubRepo(apiClient, repo) if err != nil { return false, err } return r.ViewerCanPush(), nil } // RepoParent finds out the parent repository of a fork func RepoParent(client *Client, repo ghrepo.Interface) (ghrepo.Interface, error) { var query struct { Repository struct { Parent *struct { Name string Owner struct { Login string } } } `graphql:"repository(owner: $owner, name: $name)"` } variables := map[string]interface{}{ "owner": githubv4.String(repo.RepoOwner()), "name": githubv4.String(repo.RepoName()), } gql := graphQLClient(client.http, repo.RepoHost()) err := gql.QueryNamed(context.Background(), "RepositoryFindParent", &query, variables) if err != nil { return nil, err } if query.Repository.Parent == nil { return nil, nil } parent := ghrepo.NewWithHost(query.Repository.Parent.Owner.Login, query.Repository.Parent.Name, repo.RepoHost()) return parent, nil } // RepoNetworkResult describes the relationship between related repositories type RepoNetworkResult struct { ViewerLogin string Repositories []*Repository } // RepoNetwork inspects the relationship between multiple GitHub repositories func RepoNetwork(client *Client, repos []ghrepo.Interface) (RepoNetworkResult, error) { var hostname string if len(repos) > 0 { hostname = repos[0].RepoHost() } queries := make([]string, 0, len(repos)) for i, repo := range repos { queries = append(queries, fmt.Sprintf(` repo_%03d: repository(owner: %q, name: %q) { ...repo parent { ...repo } } `, i, repo.RepoOwner(), repo.RepoName())) } // Since the query is constructed dynamically, we can't parse a response // format using a static struct. Instead, hold the raw JSON data until we // decide how to parse it manually. graphqlResult := make(map[string]*json.RawMessage) var result RepoNetworkResult err := client.GraphQL(hostname, fmt.Sprintf(` fragment repo on Repository { id name owner { login } viewerPermission defaultBranchRef { name } isPrivate } query RepositoryNetwork { viewer { login } %s } `, strings.Join(queries, "")), nil, &graphqlResult) graphqlError, isGraphQLError := err.(*GraphQLErrorResponse) if isGraphQLError { // If the only errors are that certain repositories are not found, // continue processing this response instead of returning an error tolerated := true for _, ge := range graphqlError.Errors { if ge.Type != "NOT_FOUND" { tolerated = false } } if tolerated { err = nil } } if err != nil { return result, err } keys := make([]string, 0, len(graphqlResult)) for key := range graphqlResult { keys = append(keys, key) } // sort keys to ensure `repo_{N}` entries are processed in order sort.Strings(keys) // Iterate over keys of GraphQL response data and, based on its name, // dynamically allocate the target struct an individual message gets decoded to. for _, name := range keys { jsonMessage := graphqlResult[name] if name == "viewer" { viewerResult := struct { Login string }{} decoder := json.NewDecoder(bytes.NewReader([]byte(*jsonMessage))) if err := decoder.Decode(&viewerResult); err != nil { return result, err } result.ViewerLogin = viewerResult.Login } else if strings.HasPrefix(name, "repo_") { if jsonMessage == nil { result.Repositories = append(result.Repositories, nil) continue } var repo Repository decoder := json.NewDecoder(bytes.NewReader(*jsonMessage)) if err := decoder.Decode(&repo); err != nil { return result, err } result.Repositories = append(result.Repositories, InitRepoHostname(&repo, hostname)) } else { return result, fmt.Errorf("unknown GraphQL result key %q", name) } } return result, nil } func InitRepoHostname(repo *Repository, hostname string) *Repository { repo.hostname = hostname if repo.Parent != nil { repo.Parent.hostname = hostname } return repo } // RepositoryV3 is the repository result from GitHub API v3 type repositoryV3 struct { NodeID string `json:"node_id"` Name string CreatedAt time.Time `json:"created_at"` Owner struct { Login string } Private bool HTMLUrl string `json:"html_url"` Parent *repositoryV3 } // ForkRepo forks the repository on GitHub and returns the new repository func ForkRepo(client *Client, repo ghrepo.Interface, org string) (*Repository, error) { path := fmt.Sprintf("repos/%s/forks", ghrepo.FullName(repo)) params := map[string]interface{}{} if org != "" { params["organization"] = org } body := &bytes.Buffer{} enc := json.NewEncoder(body) if err := enc.Encode(params); err != nil { return nil, err } result := repositoryV3{} err := client.REST(repo.RepoHost(), "POST", path, body, &result) if err != nil { return nil, err } return &Repository{ ID: result.NodeID, Name: result.Name, CreatedAt: result.CreatedAt, Owner: RepositoryOwner{ Login: result.Owner.Login, }, ViewerPermission: "WRITE", hostname: repo.RepoHost(), }, nil } // RepoFindForks finds forks of the repo that are affiliated with the viewer func RepoFindForks(client *Client, repo ghrepo.Interface, limit int) ([]*Repository, error) { result := struct { Repository struct { Forks struct { Nodes []Repository } } }{} variables := map[string]interface{}{ "owner": repo.RepoOwner(), "repo": repo.RepoName(), "limit": limit, } if err := client.GraphQL(repo.RepoHost(), ` query RepositoryFindFork($owner: String!, $repo: String!, $limit: Int!) { repository(owner: $owner, name: $repo) { forks(first: $limit, affiliations: [OWNER, COLLABORATOR]) { nodes { id name owner { login } url viewerPermission } } } } `, variables, &result); err != nil { return nil, err } var results []*Repository for _, r := range result.Repository.Forks.Nodes { // we check ViewerCanPush, even though we expect it to always be true per // `affiliations` condition, to guard against versions of GitHub with a // faulty `affiliations` implementation if !r.ViewerCanPush() { continue } results = append(results, InitRepoHostname(&r, repo.RepoHost())) } return results, nil } type RepoMetadataResult struct { AssignableUsers []RepoAssignee Labels []RepoLabel Projects []RepoProject Milestones []RepoMilestone Teams []OrgTeam } func (m *RepoMetadataResult) MembersToIDs(names []string) ([]string, error) { var ids []string for _, assigneeLogin := range names { found := false for _, u := range m.AssignableUsers { if strings.EqualFold(assigneeLogin, u.Login) { ids = append(ids, u.ID) found = true break } } if !found { return nil, fmt.Errorf("'%s' not found", assigneeLogin) } } return ids, nil } func (m *RepoMetadataResult) TeamsToIDs(names []string) ([]string, error) { var ids []string for _, teamSlug := range names { found := false slug := teamSlug[strings.IndexRune(teamSlug, '/')+1:] for _, t := range m.Teams { if strings.EqualFold(slug, t.Slug) { ids = append(ids, t.ID) found = true break } } if !found { return nil, fmt.Errorf("'%s' not found", teamSlug) } } return ids, nil } func (m *RepoMetadataResult) LabelsToIDs(names []string) ([]string, error) { var ids []string for _, labelName := range names { found := false for _, l := range m.Labels { if strings.EqualFold(labelName, l.Name) { ids = append(ids, l.ID) found = true break } } if !found { return nil, fmt.Errorf("'%s' not found", labelName) } } return ids, nil } func (m *RepoMetadataResult) ProjectsToIDs(names []string) ([]string, error) { var ids []string for _, projectName := range names { found := false for _, p := range m.Projects { if strings.EqualFold(projectName, p.Name) { ids = append(ids, p.ID) found = true break } } if !found { return nil, fmt.Errorf("'%s' not found", projectName) } } return ids, nil } func ProjectsToPaths(projects []RepoProject, names []string) ([]string, error) { var paths []string for _, projectName := range names { found := false for _, p := range projects { if strings.EqualFold(projectName, p.Name) { // format of ResourcePath: /OWNER/REPO/projects/PROJECT_NUMBER or /orgs/ORG/projects/PROJECT_NUMBER // required format of path: OWNER/REPO/PROJECT_NUMBER or ORG/PROJECT_NUMBER var path string pathParts := strings.Split(p.ResourcePath, "/") if pathParts[1] == "orgs" { path = fmt.Sprintf("%s/%s", pathParts[2], pathParts[4]) } else { path = fmt.Sprintf("%s/%s/%s", pathParts[1], pathParts[2], pathParts[4]) } paths = append(paths, path) found = true break } } if !found { return nil, fmt.Errorf("'%s' not found", projectName) } } return paths, nil } func (m *RepoMetadataResult) MilestoneToID(title string) (string, error) { for _, m := range m.Milestones { if strings.EqualFold(title, m.Title) { return m.ID, nil } } return "", fmt.Errorf("'%s' not found", title) } func (m *RepoMetadataResult) Merge(m2 *RepoMetadataResult) { if len(m2.AssignableUsers) > 0 || len(m.AssignableUsers) == 0 { m.AssignableUsers = m2.AssignableUsers } if len(m2.Teams) > 0 || len(m.Teams) == 0 { m.Teams = m2.Teams } if len(m2.Labels) > 0 || len(m.Labels) == 0 { m.Labels = m2.Labels } if len(m2.Projects) > 0 || len(m.Projects) == 0 { m.Projects = m2.Projects } if len(m2.Milestones) > 0 || len(m.Milestones) == 0 { m.Milestones = m2.Milestones } } type RepoMetadataInput struct { Assignees bool Reviewers bool Labels bool Projects bool Milestones bool } // RepoMetadata pre-fetches the metadata for attaching to issues and pull requests func RepoMetadata(client *Client, repo ghrepo.Interface, input RepoMetadataInput) (*RepoMetadataResult, error) { result := RepoMetadataResult{} errc := make(chan error) count := 0 if input.Assignees || input.Reviewers { count++ go func() { users, err := RepoAssignableUsers(client, repo) if err != nil { err = fmt.Errorf("error fetching assignees: %w", err) } result.AssignableUsers = users errc <- err }() } if input.Reviewers { count++ go func() { teams, err := OrganizationTeams(client, repo) // TODO: better detection of non-org repos if err != nil && !strings.HasPrefix(err.Error(), "Could not resolve to an Organization") { errc <- fmt.Errorf("error fetching organization teams: %w", err) return } result.Teams = teams errc <- nil }() } if input.Labels { count++ go func() { labels, err := RepoLabels(client, repo) if err != nil { err = fmt.Errorf("error fetching labels: %w", err) } result.Labels = labels errc <- err }() } if input.Projects { count++ go func() { projects, err := RepoAndOrgProjects(client, repo) if err != nil { errc <- err return } result.Projects = projects errc <- nil }() } if input.Milestones { count++ go func() { milestones, err := RepoMilestones(client, repo, "open") if err != nil { err = fmt.Errorf("error fetching milestones: %w", err) } result.Milestones = milestones errc <- err }() } var err error for i := 0; i < count; i++ { if e := <-errc; e != nil { err = e } } return &result, err } type RepoResolveInput struct { Assignees []string Reviewers []string Labels []string Projects []string Milestones []string } // RepoResolveMetadataIDs looks up GraphQL node IDs in bulk func RepoResolveMetadataIDs(client *Client, repo ghrepo.Interface, input RepoResolveInput) (*RepoMetadataResult, error) { users := input.Assignees hasUser := func(target string) bool { for _, u := range users { if strings.EqualFold(u, target) { return true } } return false } var teams []string for _, r := range input.Reviewers { if i := strings.IndexRune(r, '/'); i > -1 { teams = append(teams, r[i+1:]) } else if !hasUser(r) { users = append(users, r) } } // there is no way to look up projects nor milestones by name, so preload them all mi := RepoMetadataInput{ Projects: len(input.Projects) > 0, Milestones: len(input.Milestones) > 0, } result, err := RepoMetadata(client, repo, mi) if err != nil { return result, err } if len(users) == 0 && len(teams) == 0 && len(input.Labels) == 0 { return result, nil } query := &bytes.Buffer{} fmt.Fprint(query, "query RepositoryResolveMetadataIDs {\n") for i, u := range users { fmt.Fprintf(query, "u%03d: user(login:%q){id,login}\n", i, u) } if len(input.Labels) > 0 { fmt.Fprintf(query, "repository(owner:%q,name:%q){\n", repo.RepoOwner(), repo.RepoName()) for i, l := range input.Labels { fmt.Fprintf(query, "l%03d: label(name:%q){id,name}\n", i, l) } fmt.Fprint(query, "}\n") } if len(teams) > 0 { fmt.Fprintf(query, "organization(login:%q){\n", repo.RepoOwner()) for i, t := range teams { fmt.Fprintf(query, "t%03d: team(slug:%q){id,slug}\n", i, t) } fmt.Fprint(query, "}\n") } fmt.Fprint(query, "}\n") response := make(map[string]json.RawMessage) err = client.GraphQL(repo.RepoHost(), query.String(), nil, &response) if err != nil { return result, err } for key, v := range response { switch key { case "repository": repoResponse := make(map[string]RepoLabel) err := json.Unmarshal(v, &repoResponse) if err != nil { return result, err } for _, l := range repoResponse { result.Labels = append(result.Labels, l) } case "organization": orgResponse := make(map[string]OrgTeam) err := json.Unmarshal(v, &orgResponse) if err != nil { return result, err } for _, t := range orgResponse { result.Teams = append(result.Teams, t) } default: user := RepoAssignee{} err := json.Unmarshal(v, &user) if err != nil { return result, err } result.AssignableUsers = append(result.AssignableUsers, user) } } return result, nil } type RepoProject struct { ID string `json:"id"` Name string `json:"name"` Number int `json:"number"` ResourcePath string `json:"resourcePath"` } // RepoProjects fetches all open projects for a repository func RepoProjects(client *Client, repo ghrepo.Interface) ([]RepoProject, error) { type responseData struct { Repository struct { Projects struct { Nodes []RepoProject PageInfo struct { HasNextPage bool EndCursor string } } `graphql:"projects(states: [OPEN], first: 100, orderBy: {field: NAME, direction: ASC}, after: $endCursor)"` } `graphql:"repository(owner: $owner, name: $name)"` } variables := map[string]interface{}{ "owner": githubv4.String(repo.RepoOwner()), "name": githubv4.String(repo.RepoName()), "endCursor": (*githubv4.String)(nil), } gql := graphQLClient(client.http, repo.RepoHost()) var projects []RepoProject for { var query responseData err := gql.QueryNamed(context.Background(), "RepositoryProjectList", &query, variables) if err != nil { return nil, err } projects = append(projects, query.Repository.Projects.Nodes...) if !query.Repository.Projects.PageInfo.HasNextPage { break } variables["endCursor"] = githubv4.String(query.Repository.Projects.PageInfo.EndCursor) } return projects, nil } // RepoAndOrgProjects fetches all open projects for a repository and its org func RepoAndOrgProjects(client *Client, repo ghrepo.Interface) ([]RepoProject, error) { projects, err := RepoProjects(client, repo) if err != nil { return projects, fmt.Errorf("error fetching projects: %w", err) } orgProjects, err := OrganizationProjects(client, repo) // TODO: better detection of non-org repos if err != nil && !strings.HasPrefix(err.Error(), "Could not resolve to an Organization") { return projects, fmt.Errorf("error fetching organization projects: %w", err) } projects = append(projects, orgProjects...) return projects, nil } type RepoAssignee struct { ID string Login string } // RepoAssignableUsers fetches all the assignable users for a repository func RepoAssignableUsers(client *Client, repo ghrepo.Interface) ([]RepoAssignee, error) { type responseData struct { Repository struct { AssignableUsers struct { Nodes []RepoAssignee PageInfo struct { HasNextPage bool EndCursor string } } `graphql:"assignableUsers(first: 100, after: $endCursor)"` } `graphql:"repository(owner: $owner, name: $name)"` } variables := map[string]interface{}{ "owner": githubv4.String(repo.RepoOwner()), "name": githubv4.String(repo.RepoName()), "endCursor": (*githubv4.String)(nil), } gql := graphQLClient(client.http, repo.RepoHost()) var users []RepoAssignee for { var query responseData err := gql.QueryNamed(context.Background(), "RepositoryAssignableUsers", &query, variables) if err != nil { return nil, err } users = append(users, query.Repository.AssignableUsers.Nodes...) if !query.Repository.AssignableUsers.PageInfo.HasNextPage { break } variables["endCursor"] = githubv4.String(query.Repository.AssignableUsers.PageInfo.EndCursor) } return users, nil } type RepoLabel struct { ID string Name string } // RepoLabels fetches all the labels in a repository func RepoLabels(client *Client, repo ghrepo.Interface) ([]RepoLabel, error) { type responseData struct { Repository struct { Labels struct { Nodes []RepoLabel PageInfo struct { HasNextPage bool EndCursor string } } `graphql:"labels(first: 100, orderBy: {field: NAME, direction: ASC}, after: $endCursor)"` } `graphql:"repository(owner: $owner, name: $name)"` } variables := map[string]interface{}{ "owner": githubv4.String(repo.RepoOwner()), "name": githubv4.String(repo.RepoName()), "endCursor": (*githubv4.String)(nil), } gql := graphQLClient(client.http, repo.RepoHost()) var labels []RepoLabel for { var query responseData err := gql.QueryNamed(context.Background(), "RepositoryLabelList", &query, variables) if err != nil { return nil, err } labels = append(labels, query.Repository.Labels.Nodes...) if !query.Repository.Labels.PageInfo.HasNextPage { break } variables["endCursor"] = githubv4.String(query.Repository.Labels.PageInfo.EndCursor) } return labels, nil } type RepoMilestone struct { ID string Title string } // RepoMilestones fetches milestones in a repository func RepoMilestones(client *Client, repo ghrepo.Interface, state string) ([]RepoMilestone, error) { type responseData struct { Repository struct { Milestones struct { Nodes []RepoMilestone PageInfo struct { HasNextPage bool EndCursor string } } `graphql:"milestones(states: $states, first: 100, after: $endCursor)"` } `graphql:"repository(owner: $owner, name: $name)"` } var states []githubv4.MilestoneState switch state { case "open": states = []githubv4.MilestoneState{"OPEN"} case "closed": states = []githubv4.MilestoneState{"CLOSED"} case "all": states = []githubv4.MilestoneState{"OPEN", "CLOSED"} default: return nil, fmt.Errorf("invalid state: %s", state) } variables := map[string]interface{}{ "owner": githubv4.String(repo.RepoOwner()), "name": githubv4.String(repo.RepoName()), "states": states, "endCursor": (*githubv4.String)(nil), } gql := graphQLClient(client.http, repo.RepoHost()) var milestones []RepoMilestone for { var query responseData err := gql.QueryNamed(context.Background(), "RepositoryMilestoneList", &query, variables) if err != nil { return nil, err } milestones = append(milestones, query.Repository.Milestones.Nodes...) if !query.Repository.Milestones.PageInfo.HasNextPage { break } variables["endCursor"] = githubv4.String(query.Repository.Milestones.PageInfo.EndCursor) } return milestones, nil } func MilestoneByTitle(client *Client, repo ghrepo.Interface, state, title string) (*RepoMilestone, error) { milestones, err := RepoMilestones(client, repo, state) if err != nil { return nil, err } for i := range milestones { if strings.EqualFold(milestones[i].Title, title) { return &milestones[i], nil } } return nil, fmt.Errorf("no milestone found with title %q", title) } func MilestoneByNumber(client *Client, repo ghrepo.Interface, number int32) (*RepoMilestone, error) { var query struct { Repository struct { Milestone *RepoMilestone `graphql:"milestone(number: $number)"` } `graphql:"repository(owner: $owner, name: $name)"` } variables := map[string]interface{}{ "owner": githubv4.String(repo.RepoOwner()), "name": githubv4.String(repo.RepoName()), "number": githubv4.Int(number), } gql := graphQLClient(client.http, repo.RepoHost()) err := gql.QueryNamed(context.Background(), "RepositoryMilestoneByNumber", &query, variables) if err != nil { return nil, err } if query.Repository.Milestone == nil { return nil, fmt.Errorf("no milestone found with number '%d'", number) } return query.Repository.Milestone, nil } func ProjectNamesToPaths(client *Client, repo ghrepo.Interface, projectNames []string) ([]string, error) { var paths []string projects, err := RepoAndOrgProjects(client, repo) if err != nil { return paths, err } return ProjectsToPaths(projects, projectNames) } func CreateRepoTransformToV4(apiClient *Client, hostname string, method string, path string, body io.Reader) (*Repository, error) { var responsev3 repositoryV3 err := apiClient.REST(hostname, method, path, body, &responsev3) if err != nil { return nil, err } return &Repository{ Name: responsev3.Name, CreatedAt: responsev3.CreatedAt, Owner: RepositoryOwner{ Login: responsev3.Owner.Login, }, ID: responsev3.NodeID, hostname: hostname, URL: responsev3.HTMLUrl, IsPrivate: responsev3.Private, }, nil }
api/queries_repo.go
0
https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c
[ 0.0010422921041026711, 0.00020799372578039765, 0.00015828009054530412, 0.00017262059554923326, 0.00012656618491746485 ]
{ "id": 10, "code_window": [ "\t\treturn \"\", err\n", "\t}\n", "\n", "\tnewPath := filepath.Join(homeDir, subdir)\n", "\tif s, err := os.Stat(newPath); err == nil && s.IsDir() {\n", "\t\treturn newPath, nil\n", "\t}\n", "\n", "\t// TODO: remove go-homedir fallback in GitHub CLI v2\n", "\tif legacyDir, err := homedir.Dir(); err == nil {\n", "\t\tlegacyPath := filepath.Join(legacyDir, subdir)\n", "\t\tif s, err := os.Stat(legacyPath); err == nil && s.IsDir() {\n", "\t\t\treturn legacyPath, nil\n", "\t\t}\n", "\t}\n", "\n", "\treturn newPath, nil\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "internal/config/config_file.go", "type": "replace", "edit_start_line_idx": 191 }
package git import ( "os" "reflect" "testing" "github.com/cli/cli/internal/run" ) func setGitDir(t *testing.T, dir string) { // TODO: also set XDG_CONFIG_HOME, GIT_CONFIG_NOSYSTEM old_GIT_DIR := os.Getenv("GIT_DIR") os.Setenv("GIT_DIR", dir) t.Cleanup(func() { os.Setenv("GIT_DIR", old_GIT_DIR) }) } func TestLastCommit(t *testing.T) { setGitDir(t, "./fixtures/simple.git") c, err := LastCommit() if err != nil { t.Fatalf("LastCommit error: %v", err) } if c.Sha != "6f1a2405cace1633d89a79c74c65f22fe78f9659" { t.Errorf("expected sha %q, got %q", "6f1a2405cace1633d89a79c74c65f22fe78f9659", c.Sha) } if c.Title != "Second commit" { t.Errorf("expected title %q, got %q", "Second commit", c.Title) } } func TestCommitBody(t *testing.T) { setGitDir(t, "./fixtures/simple.git") body, err := CommitBody("6f1a2405cace1633d89a79c74c65f22fe78f9659") if err != nil { t.Fatalf("CommitBody error: %v", err) } if body != "I'm starting to get the hang of things\n" { t.Errorf("expected %q, got %q", "I'm starting to get the hang of things\n", body) } } /* NOTE: below this are stubbed git tests, i.e. those that do not actually invoke `git`. If possible, utilize `setGitDir()` to allow new tests to interact with `git`. For write operations, you can use `t.TempDir()` to host a temporary git repository that is safe to be changed. */ func Test_UncommittedChangeCount(t *testing.T) { type c struct { Label string Expected int Output string } cases := []c{ {Label: "no changes", Expected: 0, Output: ""}, {Label: "one change", Expected: 1, Output: " M poem.txt"}, {Label: "untracked file", Expected: 2, Output: " M poem.txt\n?? new.txt"}, } for _, v := range cases { t.Run(v.Label, func(t *testing.T) { cs, restore := run.Stub() defer restore(t) cs.Register(`git status --porcelain`, 0, v.Output) ucc, _ := UncommittedChangeCount() if ucc != v.Expected { t.Errorf("UncommittedChangeCount() = %d, expected %d", ucc, v.Expected) } }) } } func Test_CurrentBranch(t *testing.T) { type c struct { Stub string Expected string } cases := []c{ { Stub: "branch-name\n", Expected: "branch-name", }, { Stub: "refs/heads/branch-name\n", Expected: "branch-name", }, { Stub: "refs/heads/branch\u00A0with\u00A0non\u00A0breaking\u00A0space\n", Expected: "branch\u00A0with\u00A0non\u00A0breaking\u00A0space", }, } for _, v := range cases { cs, teardown := run.Stub() cs.Register(`git symbolic-ref --quiet HEAD`, 0, v.Stub) result, err := CurrentBranch() if err != nil { t.Errorf("got unexpected error: %w", err) } if result != v.Expected { t.Errorf("unexpected branch name: %s instead of %s", result, v.Expected) } teardown(t) } } func Test_CurrentBranch_detached_head(t *testing.T) { cs, teardown := run.Stub() defer teardown(t) cs.Register(`git symbolic-ref --quiet HEAD`, 1, "") _, err := CurrentBranch() if err == nil { t.Fatal("expected an error, got nil") } if err != ErrNotOnAnyBranch { t.Errorf("got unexpected error: %s instead of %s", err, ErrNotOnAnyBranch) } } func TestParseExtraCloneArgs(t *testing.T) { type Wanted struct { args []string dir string } tests := []struct { name string args []string want Wanted }{ { name: "args and target", args: []string{"target_directory", "-o", "upstream", "--depth", "1"}, want: Wanted{ args: []string{"-o", "upstream", "--depth", "1"}, dir: "target_directory", }, }, { name: "only args", args: []string{"-o", "upstream", "--depth", "1"}, want: Wanted{ args: []string{"-o", "upstream", "--depth", "1"}, dir: "", }, }, { name: "only target", args: []string{"target_directory"}, want: Wanted{ args: []string{}, dir: "target_directory", }, }, { name: "no args", args: []string{}, want: Wanted{ args: []string{}, dir: "", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { args, dir := parseCloneArgs(tt.args) got := Wanted{ args: args, dir: dir, } if !reflect.DeepEqual(got, tt.want) { t.Errorf("got %#v want %#v", got, tt.want) } }) } } func TestAddUpstreamRemote(t *testing.T) { tests := []struct { name string upstreamURL string cloneDir string branches []string want string }{ { name: "fetch all", upstreamURL: "URL", cloneDir: "DIRECTORY", branches: []string{}, want: "git -C DIRECTORY remote add -f upstream URL", }, { name: "fetch specific branches only", upstreamURL: "URL", cloneDir: "DIRECTORY", branches: []string{"master", "dev"}, want: "git -C DIRECTORY remote add -t master -t dev -f upstream URL", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { cs, cmdTeardown := run.Stub() defer cmdTeardown(t) cs.Register(tt.want, 0, "") err := AddUpstreamRemote(tt.upstreamURL, tt.cloneDir, tt.branches) if err != nil { t.Fatalf("error running command `git remote add -f`: %v", err) } }) } }
git/git_test.go
0
https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c
[ 0.0007683614385314286, 0.00024055813264567405, 0.00016403694462496787, 0.0001725220208754763, 0.00015248804993461818 ]
{ "id": 10, "code_window": [ "\t\treturn \"\", err\n", "\t}\n", "\n", "\tnewPath := filepath.Join(homeDir, subdir)\n", "\tif s, err := os.Stat(newPath); err == nil && s.IsDir() {\n", "\t\treturn newPath, nil\n", "\t}\n", "\n", "\t// TODO: remove go-homedir fallback in GitHub CLI v2\n", "\tif legacyDir, err := homedir.Dir(); err == nil {\n", "\t\tlegacyPath := filepath.Join(legacyDir, subdir)\n", "\t\tif s, err := os.Stat(legacyPath); err == nil && s.IsDir() {\n", "\t\t\treturn legacyPath, nil\n", "\t\t}\n", "\t}\n", "\n", "\treturn newPath, nil\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "internal/config/config_file.go", "type": "replace", "edit_start_line_idx": 191 }
package create import ( "bytes" "io" "regexp" ) func NewRegexpWriter(out io.Writer, re *regexp.Regexp, repl string) *RegexpWriter { return &RegexpWriter{out: out, re: *re, repl: repl} } type RegexpWriter struct { out io.Writer re regexp.Regexp repl string buf []byte } func (s *RegexpWriter) Write(data []byte) (int, error) { if len(data) == 0 { return 0, nil } filtered := []byte{} repl := []byte(s.repl) lines := bytes.SplitAfter(data, []byte("\n")) if len(s.buf) > 0 { lines[0] = append(s.buf, lines[0]...) } for i, line := range lines { if i == len(lines) { s.buf = line } else { f := s.re.ReplaceAll(line, repl) if len(f) > 0 { filtered = append(filtered, f...) } } } if len(filtered) != 0 { _, err := s.out.Write(filtered) if err != nil { return 0, err } } return len(data), nil } func (s *RegexpWriter) Flush() (int, error) { if len(s.buf) > 0 { repl := []byte(s.repl) filtered := s.re.ReplaceAll(s.buf, repl) if len(filtered) > 0 { return s.out.Write(filtered) } } return 0, nil }
pkg/cmd/pr/create/regexp_writer.go
0
https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c
[ 0.0003099951718468219, 0.00018835533410310745, 0.00016214379866141826, 0.00016746278561186045, 0.000049819547712104395 ]
{ "id": 0, "code_window": [ "\t\"k8s.io/kubernetes/cmd/kube-controller-manager/app\"\n", "\tkubecontrollerconfig \"k8s.io/kubernetes/cmd/kube-controller-manager/app/config\"\n", "\t\"k8s.io/kubernetes/cmd/kube-controller-manager/app/options\"\n", ")\n", "\n", "// TearDownFunc is to be called to tear down a test server.\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\"k8s.io/klog/v2\"\n" ], "file_path": "cmd/kube-controller-manager/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 33 }
/* Copyright 2018 The Kubernetes 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 testing import ( "context" "fmt" "io/ioutil" "net" "os" "strings" "time" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes" restclient "k8s.io/client-go/rest" cloudprovider "k8s.io/cloud-provider" "k8s.io/cloud-provider/app" "k8s.io/cloud-provider/app/config" "k8s.io/cloud-provider/options" cliflag "k8s.io/component-base/cli/flag" ) // TearDownFunc is to be called to tear down a test server. type TearDownFunc func() // TestServer return values supplied by kube-test-ApiServer type TestServer struct { LoopbackClientConfig *restclient.Config // Rest client config using the magic token Options *options.CloudControllerManagerOptions Config *config.CompletedConfig TearDownFn TearDownFunc // TearDown function TmpDir string // Temp Dir used, by the apiserver } // Logger allows t.Testing and b.Testing to be passed to StartTestServer and StartTestServerOrDie type Logger interface { Errorf(format string, args ...interface{}) Fatalf(format string, args ...interface{}) Logf(format string, args ...interface{}) } // StartTestServer starts a cloud-controller-manager. A rest client config and a tear-down func, // and location of the tmpdir are returned. // // Note: we return a tear-down func instead of a stop channel because the later will leak temporary // files that because Golang testing's call to os.Exit will not give a stop channel go routine // enough time to remove temporary files. func StartTestServer(t Logger, customFlags []string) (result TestServer, err error) { stopCh := make(chan struct{}) configDoneCh := make(chan struct{}) var capturedConfig config.CompletedConfig tearDown := func() { close(stopCh) if len(result.TmpDir) != 0 { os.RemoveAll(result.TmpDir) } } defer func() { if result.TearDownFn == nil { tearDown() } }() result.TmpDir, err = ioutil.TempDir("", "cloud-controller-manager") if err != nil { return result, fmt.Errorf("failed to create temp dir: %v", err) } s, err := options.NewCloudControllerManagerOptions() if err != nil { return TestServer{}, err } cloudInitializer := func(config *config.CompletedConfig) cloudprovider.Interface { capturedConfig = *config // send signal to indicate the capturedConfig has been properly set close(configDoneCh) cloudConfig := config.ComponentConfig.KubeCloudShared.CloudProvider cloud, err := cloudprovider.InitCloudProvider(cloudConfig.Name, cloudConfig.CloudConfigFile) if err != nil { t.Fatalf("Cloud provider could not be initialized: %v", err) } s.SecureServing.ServerCert.CertDirectory = result.TmpDir if cloud == nil { t.Fatalf("Cloud provider is nil") } return cloud } fss := cliflag.NamedFlagSets{} command := app.NewCloudControllerManagerCommand(s, cloudInitializer, app.DefaultInitFuncConstructors, fss, stopCh) commandArgs := []string{} listeners := []net.Listener{} disableSecure := false for _, arg := range customFlags { if strings.HasPrefix(arg, "--secure-port=") { if arg == "--secure-port=0" { commandArgs = append(commandArgs, arg) disableSecure = true } } else if strings.HasPrefix(arg, "--cert-dir=") { // skip it } else { commandArgs = append(commandArgs, arg) } } if !disableSecure { listener, bindPort, err := createListenerOnFreePort() if err != nil { return result, fmt.Errorf("failed to create listener: %v", err) } listeners = append(listeners, listener) commandArgs = append(commandArgs, fmt.Sprintf("--secure-port=%d", bindPort)) commandArgs = append(commandArgs, fmt.Sprintf("--cert-dir=%s", result.TmpDir)) t.Logf("cloud-controller-manager will listen securely on port %d...", bindPort) } for _, listener := range listeners { listener.Close() } errCh := make(chan error) go func() { command.SetArgs(commandArgs) if err := command.Execute(); err != nil { errCh <- err } close(errCh) }() select { case <-configDoneCh: case err := <-errCh: return result, err } t.Logf("Waiting for /healthz to be ok...") client, err := kubernetes.NewForConfig(capturedConfig.LoopbackClientConfig) if err != nil { return result, fmt.Errorf("failed to create a client: %v", err) } err = wait.Poll(100*time.Millisecond, 30*time.Second, func() (bool, error) { select { case err := <-errCh: return false, err default: } result := client.CoreV1().RESTClient().Get().AbsPath("/healthz").Do(context.TODO()) status := 0 result.StatusCode(&status) if status == 200 { return true, nil } return false, nil }) if err != nil { return result, fmt.Errorf("failed to wait for /healthz to return ok: %v", err) } // from here the caller must call tearDown result.LoopbackClientConfig = capturedConfig.LoopbackClientConfig result.Options = s result.Config = &capturedConfig result.TearDownFn = tearDown return result, nil } // StartTestServerOrDie calls StartTestServer t.Fatal if it does not succeed. func StartTestServerOrDie(t Logger, flags []string) *TestServer { result, err := StartTestServer(t, flags) if err == nil { return &result } t.Fatalf("failed to launch server: %v", err) return nil } func createListenerOnFreePort() (net.Listener, int, error) { ln, err := net.Listen("tcp", ":0") if err != nil { return nil, 0, err } // get port tcpAddr, ok := ln.Addr().(*net.TCPAddr) if !ok { ln.Close() return nil, 0, fmt.Errorf("invalid listen address: %q", ln.Addr().String()) } return ln, tcpAddr.Port, nil }
staging/src/k8s.io/cloud-provider/app/testing/testserver.go
1
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.07554889470338821, 0.009422757662832737, 0.0001648251200094819, 0.00018923946481663734, 0.018630610778927803 ]
{ "id": 0, "code_window": [ "\t\"k8s.io/kubernetes/cmd/kube-controller-manager/app\"\n", "\tkubecontrollerconfig \"k8s.io/kubernetes/cmd/kube-controller-manager/app/config\"\n", "\t\"k8s.io/kubernetes/cmd/kube-controller-manager/app/options\"\n", ")\n", "\n", "// TearDownFunc is to be called to tear down a test server.\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\"k8s.io/klog/v2\"\n" ], "file_path": "cmd/kube-controller-manager/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 33 }
The MIT License (MIT) Copyright (c) 2014 Alex Saskevich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
vendor/github.com/asaskevich/govalidator/LICENSE
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.00017674159607850015, 0.0001702330628177151, 0.00016409890668001026, 0.00016985864203888923, 0.000005168141797184944 ]
{ "id": 0, "code_window": [ "\t\"k8s.io/kubernetes/cmd/kube-controller-manager/app\"\n", "\tkubecontrollerconfig \"k8s.io/kubernetes/cmd/kube-controller-manager/app/config\"\n", "\t\"k8s.io/kubernetes/cmd/kube-controller-manager/app/options\"\n", ")\n", "\n", "// TearDownFunc is to be called to tear down a test server.\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\"k8s.io/klog/v2\"\n" ], "file_path": "cmd/kube-controller-manager/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 33 }
{ "kind": "DaemonSet", "apiVersion": "apps/v1", "metadata": { "name": "nameValue", "generateName": "generateNameValue", "namespace": "namespaceValue", "selfLink": "selfLinkValue", "uid": "uidValue", "resourceVersion": "resourceVersionValue", "generation": 7, "creationTimestamp": "2008-01-01T01:01:01Z", "deletionTimestamp": "2009-01-01T01:01:01Z", "deletionGracePeriodSeconds": 10, "labels": { "labelsKey": "labelsValue" }, "annotations": { "annotationsKey": "annotationsValue" }, "ownerReferences": [ { "apiVersion": "apiVersionValue", "kind": "kindValue", "name": "nameValue", "uid": "uidValue", "controller": true, "blockOwnerDeletion": true } ], "finalizers": [ "finalizersValue" ], "managedFields": [ { "manager": "managerValue", "operation": "operationValue", "apiVersion": "apiVersionValue", "time": "2004-01-01T01:01:01Z", "fieldsType": "fieldsTypeValue", "fieldsV1": {}, "subresource": "subresourceValue" } ] }, "spec": { "selector": { "matchLabels": { "matchLabelsKey": "matchLabelsValue" }, "matchExpressions": [ { "key": "keyValue", "operator": "operatorValue", "values": [ "valuesValue" ] } ] }, "template": { "metadata": { "name": "nameValue", "generateName": "generateNameValue", "namespace": "namespaceValue", "selfLink": "selfLinkValue", "uid": "uidValue", "resourceVersion": "resourceVersionValue", "generation": 7, "creationTimestamp": "2008-01-01T01:01:01Z", "deletionTimestamp": "2009-01-01T01:01:01Z", "deletionGracePeriodSeconds": 10, "labels": { "labelsKey": "labelsValue" }, "annotations": { "annotationsKey": "annotationsValue" }, "ownerReferences": [ { "apiVersion": "apiVersionValue", "kind": "kindValue", "name": "nameValue", "uid": "uidValue", "controller": true, "blockOwnerDeletion": true } ], "finalizers": [ "finalizersValue" ], "managedFields": [ { "manager": "managerValue", "operation": "operationValue", "apiVersion": "apiVersionValue", "time": "2004-01-01T01:01:01Z", "fieldsType": "fieldsTypeValue", "fieldsV1": {}, "subresource": "subresourceValue" } ] }, "spec": { "volumes": [ { "name": "nameValue", "hostPath": { "path": "pathValue", "type": "typeValue" }, "emptyDir": { "medium": "mediumValue", "sizeLimit": "0" }, "gcePersistentDisk": { "pdName": "pdNameValue", "fsType": "fsTypeValue", "partition": 3, "readOnly": true }, "awsElasticBlockStore": { "volumeID": "volumeIDValue", "fsType": "fsTypeValue", "partition": 3, "readOnly": true }, "gitRepo": { "repository": "repositoryValue", "revision": "revisionValue", "directory": "directoryValue" }, "secret": { "secretName": "secretNameValue", "items": [ { "key": "keyValue", "path": "pathValue", "mode": 3 } ], "defaultMode": 3, "optional": true }, "nfs": { "server": "serverValue", "path": "pathValue", "readOnly": true }, "iscsi": { "targetPortal": "targetPortalValue", "iqn": "iqnValue", "lun": 3, "iscsiInterface": "iscsiInterfaceValue", "fsType": "fsTypeValue", "readOnly": true, "portals": [ "portalsValue" ], "chapAuthDiscovery": true, "chapAuthSession": true, "secretRef": { "name": "nameValue" }, "initiatorName": "initiatorNameValue" }, "glusterfs": { "endpoints": "endpointsValue", "path": "pathValue", "readOnly": true }, "persistentVolumeClaim": { "claimName": "claimNameValue", "readOnly": true }, "rbd": { "monitors": [ "monitorsValue" ], "image": "imageValue", "fsType": "fsTypeValue", "pool": "poolValue", "user": "userValue", "keyring": "keyringValue", "secretRef": { "name": "nameValue" }, "readOnly": true }, "flexVolume": { "driver": "driverValue", "fsType": "fsTypeValue", "secretRef": { "name": "nameValue" }, "readOnly": true, "options": { "optionsKey": "optionsValue" } }, "cinder": { "volumeID": "volumeIDValue", "fsType": "fsTypeValue", "readOnly": true, "secretRef": { "name": "nameValue" } }, "cephfs": { "monitors": [ "monitorsValue" ], "path": "pathValue", "user": "userValue", "secretFile": "secretFileValue", "secretRef": { "name": "nameValue" }, "readOnly": true }, "flocker": { "datasetName": "datasetNameValue", "datasetUUID": "datasetUUIDValue" }, "downwardAPI": { "items": [ { "path": "pathValue", "fieldRef": { "apiVersion": "apiVersionValue", "fieldPath": "fieldPathValue" }, "resourceFieldRef": { "containerName": "containerNameValue", "resource": "resourceValue", "divisor": "0" }, "mode": 4 } ], "defaultMode": 2 }, "fc": { "targetWWNs": [ "targetWWNsValue" ], "lun": 2, "fsType": "fsTypeValue", "readOnly": true, "wwids": [ "wwidsValue" ] }, "azureFile": { "secretName": "secretNameValue", "shareName": "shareNameValue", "readOnly": true }, "configMap": { "name": "nameValue", "items": [ { "key": "keyValue", "path": "pathValue", "mode": 3 } ], "defaultMode": 3, "optional": true }, "vsphereVolume": { "volumePath": "volumePathValue", "fsType": "fsTypeValue", "storagePolicyName": "storagePolicyNameValue", "storagePolicyID": "storagePolicyIDValue" }, "quobyte": { "registry": "registryValue", "volume": "volumeValue", "readOnly": true, "user": "userValue", "group": "groupValue", "tenant": "tenantValue" }, "azureDisk": { "diskName": "diskNameValue", "diskURI": "diskURIValue", "cachingMode": "cachingModeValue", "fsType": "fsTypeValue", "readOnly": true, "kind": "kindValue" }, "photonPersistentDisk": { "pdID": "pdIDValue", "fsType": "fsTypeValue" }, "projected": { "sources": [ { "secret": { "name": "nameValue", "items": [ { "key": "keyValue", "path": "pathValue", "mode": 3 } ], "optional": true }, "downwardAPI": { "items": [ { "path": "pathValue", "fieldRef": { "apiVersion": "apiVersionValue", "fieldPath": "fieldPathValue" }, "resourceFieldRef": { "containerName": "containerNameValue", "resource": "resourceValue", "divisor": "0" }, "mode": 4 } ] }, "configMap": { "name": "nameValue", "items": [ { "key": "keyValue", "path": "pathValue", "mode": 3 } ], "optional": true }, "serviceAccountToken": { "audience": "audienceValue", "expirationSeconds": 2, "path": "pathValue" } } ], "defaultMode": 2 }, "portworxVolume": { "volumeID": "volumeIDValue", "fsType": "fsTypeValue", "readOnly": true }, "scaleIO": { "gateway": "gatewayValue", "system": "systemValue", "secretRef": { "name": "nameValue" }, "sslEnabled": true, "protectionDomain": "protectionDomainValue", "storagePool": "storagePoolValue", "storageMode": "storageModeValue", "volumeName": "volumeNameValue", "fsType": "fsTypeValue", "readOnly": true }, "storageos": { "volumeName": "volumeNameValue", "volumeNamespace": "volumeNamespaceValue", "fsType": "fsTypeValue", "readOnly": true, "secretRef": { "name": "nameValue" } }, "csi": { "driver": "driverValue", "readOnly": true, "fsType": "fsTypeValue", "volumeAttributes": { "volumeAttributesKey": "volumeAttributesValue" }, "nodePublishSecretRef": { "name": "nameValue" } }, "ephemeral": { "volumeClaimTemplate": { "metadata": { "name": "nameValue", "generateName": "generateNameValue", "namespace": "namespaceValue", "selfLink": "selfLinkValue", "uid": "uidValue", "resourceVersion": "resourceVersionValue", "generation": 7, "creationTimestamp": "2008-01-01T01:01:01Z", "deletionTimestamp": "2009-01-01T01:01:01Z", "deletionGracePeriodSeconds": 10, "labels": { "labelsKey": "labelsValue" }, "annotations": { "annotationsKey": "annotationsValue" }, "ownerReferences": [ { "apiVersion": "apiVersionValue", "kind": "kindValue", "name": "nameValue", "uid": "uidValue", "controller": true, "blockOwnerDeletion": true } ], "finalizers": [ "finalizersValue" ], "managedFields": [ { "manager": "managerValue", "operation": "operationValue", "apiVersion": "apiVersionValue", "time": "2004-01-01T01:01:01Z", "fieldsType": "fieldsTypeValue", "fieldsV1": {}, "subresource": "subresourceValue" } ] }, "spec": { "accessModes": [ "accessModesValue" ], "selector": { "matchLabels": { "matchLabelsKey": "matchLabelsValue" }, "matchExpressions": [ { "key": "keyValue", "operator": "operatorValue", "values": [ "valuesValue" ] } ] }, "resources": { "limits": { "limitsKey": "0" }, "requests": { "requestsKey": "0" } }, "volumeName": "volumeNameValue", "storageClassName": "storageClassNameValue", "volumeMode": "volumeModeValue", "dataSource": { "apiGroup": "apiGroupValue", "kind": "kindValue", "name": "nameValue" }, "dataSourceRef": { "apiGroup": "apiGroupValue", "kind": "kindValue", "name": "nameValue" } } } } } ], "initContainers": [ { "name": "nameValue", "image": "imageValue", "command": [ "commandValue" ], "args": [ "argsValue" ], "workingDir": "workingDirValue", "ports": [ { "name": "nameValue", "hostPort": 2, "containerPort": 3, "protocol": "protocolValue", "hostIP": "hostIPValue" } ], "envFrom": [ { "prefix": "prefixValue", "configMapRef": { "name": "nameValue", "optional": true }, "secretRef": { "name": "nameValue", "optional": true } } ], "env": [ { "name": "nameValue", "value": "valueValue", "valueFrom": { "fieldRef": { "apiVersion": "apiVersionValue", "fieldPath": "fieldPathValue" }, "resourceFieldRef": { "containerName": "containerNameValue", "resource": "resourceValue", "divisor": "0" }, "configMapKeyRef": { "name": "nameValue", "key": "keyValue", "optional": true }, "secretKeyRef": { "name": "nameValue", "key": "keyValue", "optional": true } } } ], "resources": { "limits": { "limitsKey": "0" }, "requests": { "requestsKey": "0" } }, "volumeMounts": [ { "name": "nameValue", "readOnly": true, "mountPath": "mountPathValue", "subPath": "subPathValue", "mountPropagation": "mountPropagationValue", "subPathExpr": "subPathExprValue" } ], "volumeDevices": [ { "name": "nameValue", "devicePath": "devicePathValue" } ], "livenessProbe": { "exec": { "command": [ "commandValue" ] }, "httpGet": { "path": "pathValue", "port": "portValue", "host": "hostValue", "scheme": "schemeValue", "httpHeaders": [ { "name": "nameValue", "value": "valueValue" } ] }, "tcpSocket": { "port": "portValue", "host": "hostValue" }, "grpc": { "port": 1, "service": "serviceValue" }, "initialDelaySeconds": 2, "timeoutSeconds": 3, "periodSeconds": 4, "successThreshold": 5, "failureThreshold": 6, "terminationGracePeriodSeconds": 7 }, "readinessProbe": { "exec": { "command": [ "commandValue" ] }, "httpGet": { "path": "pathValue", "port": "portValue", "host": "hostValue", "scheme": "schemeValue", "httpHeaders": [ { "name": "nameValue", "value": "valueValue" } ] }, "tcpSocket": { "port": "portValue", "host": "hostValue" }, "grpc": { "port": 1, "service": "serviceValue" }, "initialDelaySeconds": 2, "timeoutSeconds": 3, "periodSeconds": 4, "successThreshold": 5, "failureThreshold": 6, "terminationGracePeriodSeconds": 7 }, "startupProbe": { "exec": { "command": [ "commandValue" ] }, "httpGet": { "path": "pathValue", "port": "portValue", "host": "hostValue", "scheme": "schemeValue", "httpHeaders": [ { "name": "nameValue", "value": "valueValue" } ] }, "tcpSocket": { "port": "portValue", "host": "hostValue" }, "grpc": { "port": 1, "service": "serviceValue" }, "initialDelaySeconds": 2, "timeoutSeconds": 3, "periodSeconds": 4, "successThreshold": 5, "failureThreshold": 6, "terminationGracePeriodSeconds": 7 }, "lifecycle": { "postStart": { "exec": { "command": [ "commandValue" ] }, "httpGet": { "path": "pathValue", "port": "portValue", "host": "hostValue", "scheme": "schemeValue", "httpHeaders": [ { "name": "nameValue", "value": "valueValue" } ] }, "tcpSocket": { "port": "portValue", "host": "hostValue" } }, "preStop": { "exec": { "command": [ "commandValue" ] }, "httpGet": { "path": "pathValue", "port": "portValue", "host": "hostValue", "scheme": "schemeValue", "httpHeaders": [ { "name": "nameValue", "value": "valueValue" } ] }, "tcpSocket": { "port": "portValue", "host": "hostValue" } } }, "terminationMessagePath": "terminationMessagePathValue", "terminationMessagePolicy": "terminationMessagePolicyValue", "imagePullPolicy": "imagePullPolicyValue", "securityContext": { "capabilities": { "add": [ "addValue" ], "drop": [ "dropValue" ] }, "privileged": true, "seLinuxOptions": { "user": "userValue", "role": "roleValue", "type": "typeValue", "level": "levelValue" }, "windowsOptions": { "gmsaCredentialSpecName": "gmsaCredentialSpecNameValue", "gmsaCredentialSpec": "gmsaCredentialSpecValue", "runAsUserName": "runAsUserNameValue", "hostProcess": true }, "runAsUser": 4, "runAsGroup": 8, "runAsNonRoot": true, "readOnlyRootFilesystem": true, "allowPrivilegeEscalation": true, "procMount": "procMountValue", "seccompProfile": { "type": "typeValue", "localhostProfile": "localhostProfileValue" } }, "stdin": true, "stdinOnce": true, "tty": true } ], "containers": [ { "name": "nameValue", "image": "imageValue", "command": [ "commandValue" ], "args": [ "argsValue" ], "workingDir": "workingDirValue", "ports": [ { "name": "nameValue", "hostPort": 2, "containerPort": 3, "protocol": "protocolValue", "hostIP": "hostIPValue" } ], "envFrom": [ { "prefix": "prefixValue", "configMapRef": { "name": "nameValue", "optional": true }, "secretRef": { "name": "nameValue", "optional": true } } ], "env": [ { "name": "nameValue", "value": "valueValue", "valueFrom": { "fieldRef": { "apiVersion": "apiVersionValue", "fieldPath": "fieldPathValue" }, "resourceFieldRef": { "containerName": "containerNameValue", "resource": "resourceValue", "divisor": "0" }, "configMapKeyRef": { "name": "nameValue", "key": "keyValue", "optional": true }, "secretKeyRef": { "name": "nameValue", "key": "keyValue", "optional": true } } } ], "resources": { "limits": { "limitsKey": "0" }, "requests": { "requestsKey": "0" } }, "volumeMounts": [ { "name": "nameValue", "readOnly": true, "mountPath": "mountPathValue", "subPath": "subPathValue", "mountPropagation": "mountPropagationValue", "subPathExpr": "subPathExprValue" } ], "volumeDevices": [ { "name": "nameValue", "devicePath": "devicePathValue" } ], "livenessProbe": { "exec": { "command": [ "commandValue" ] }, "httpGet": { "path": "pathValue", "port": "portValue", "host": "hostValue", "scheme": "schemeValue", "httpHeaders": [ { "name": "nameValue", "value": "valueValue" } ] }, "tcpSocket": { "port": "portValue", "host": "hostValue" }, "grpc": { "port": 1, "service": "serviceValue" }, "initialDelaySeconds": 2, "timeoutSeconds": 3, "periodSeconds": 4, "successThreshold": 5, "failureThreshold": 6, "terminationGracePeriodSeconds": 7 }, "readinessProbe": { "exec": { "command": [ "commandValue" ] }, "httpGet": { "path": "pathValue", "port": "portValue", "host": "hostValue", "scheme": "schemeValue", "httpHeaders": [ { "name": "nameValue", "value": "valueValue" } ] }, "tcpSocket": { "port": "portValue", "host": "hostValue" }, "grpc": { "port": 1, "service": "serviceValue" }, "initialDelaySeconds": 2, "timeoutSeconds": 3, "periodSeconds": 4, "successThreshold": 5, "failureThreshold": 6, "terminationGracePeriodSeconds": 7 }, "startupProbe": { "exec": { "command": [ "commandValue" ] }, "httpGet": { "path": "pathValue", "port": "portValue", "host": "hostValue", "scheme": "schemeValue", "httpHeaders": [ { "name": "nameValue", "value": "valueValue" } ] }, "tcpSocket": { "port": "portValue", "host": "hostValue" }, "grpc": { "port": 1, "service": "serviceValue" }, "initialDelaySeconds": 2, "timeoutSeconds": 3, "periodSeconds": 4, "successThreshold": 5, "failureThreshold": 6, "terminationGracePeriodSeconds": 7 }, "lifecycle": { "postStart": { "exec": { "command": [ "commandValue" ] }, "httpGet": { "path": "pathValue", "port": "portValue", "host": "hostValue", "scheme": "schemeValue", "httpHeaders": [ { "name": "nameValue", "value": "valueValue" } ] }, "tcpSocket": { "port": "portValue", "host": "hostValue" } }, "preStop": { "exec": { "command": [ "commandValue" ] }, "httpGet": { "path": "pathValue", "port": "portValue", "host": "hostValue", "scheme": "schemeValue", "httpHeaders": [ { "name": "nameValue", "value": "valueValue" } ] }, "tcpSocket": { "port": "portValue", "host": "hostValue" } } }, "terminationMessagePath": "terminationMessagePathValue", "terminationMessagePolicy": "terminationMessagePolicyValue", "imagePullPolicy": "imagePullPolicyValue", "securityContext": { "capabilities": { "add": [ "addValue" ], "drop": [ "dropValue" ] }, "privileged": true, "seLinuxOptions": { "user": "userValue", "role": "roleValue", "type": "typeValue", "level": "levelValue" }, "windowsOptions": { "gmsaCredentialSpecName": "gmsaCredentialSpecNameValue", "gmsaCredentialSpec": "gmsaCredentialSpecValue", "runAsUserName": "runAsUserNameValue", "hostProcess": true }, "runAsUser": 4, "runAsGroup": 8, "runAsNonRoot": true, "readOnlyRootFilesystem": true, "allowPrivilegeEscalation": true, "procMount": "procMountValue", "seccompProfile": { "type": "typeValue", "localhostProfile": "localhostProfileValue" } }, "stdin": true, "stdinOnce": true, "tty": true } ], "ephemeralContainers": [ { "name": "nameValue", "image": "imageValue", "command": [ "commandValue" ], "args": [ "argsValue" ], "workingDir": "workingDirValue", "ports": [ { "name": "nameValue", "hostPort": 2, "containerPort": 3, "protocol": "protocolValue", "hostIP": "hostIPValue" } ], "envFrom": [ { "prefix": "prefixValue", "configMapRef": { "name": "nameValue", "optional": true }, "secretRef": { "name": "nameValue", "optional": true } } ], "env": [ { "name": "nameValue", "value": "valueValue", "valueFrom": { "fieldRef": { "apiVersion": "apiVersionValue", "fieldPath": "fieldPathValue" }, "resourceFieldRef": { "containerName": "containerNameValue", "resource": "resourceValue", "divisor": "0" }, "configMapKeyRef": { "name": "nameValue", "key": "keyValue", "optional": true }, "secretKeyRef": { "name": "nameValue", "key": "keyValue", "optional": true } } } ], "resources": { "limits": { "limitsKey": "0" }, "requests": { "requestsKey": "0" } }, "volumeMounts": [ { "name": "nameValue", "readOnly": true, "mountPath": "mountPathValue", "subPath": "subPathValue", "mountPropagation": "mountPropagationValue", "subPathExpr": "subPathExprValue" } ], "volumeDevices": [ { "name": "nameValue", "devicePath": "devicePathValue" } ], "livenessProbe": { "exec": { "command": [ "commandValue" ] }, "httpGet": { "path": "pathValue", "port": "portValue", "host": "hostValue", "scheme": "schemeValue", "httpHeaders": [ { "name": "nameValue", "value": "valueValue" } ] }, "tcpSocket": { "port": "portValue", "host": "hostValue" }, "grpc": { "port": 1, "service": "serviceValue" }, "initialDelaySeconds": 2, "timeoutSeconds": 3, "periodSeconds": 4, "successThreshold": 5, "failureThreshold": 6, "terminationGracePeriodSeconds": 7 }, "readinessProbe": { "exec": { "command": [ "commandValue" ] }, "httpGet": { "path": "pathValue", "port": "portValue", "host": "hostValue", "scheme": "schemeValue", "httpHeaders": [ { "name": "nameValue", "value": "valueValue" } ] }, "tcpSocket": { "port": "portValue", "host": "hostValue" }, "grpc": { "port": 1, "service": "serviceValue" }, "initialDelaySeconds": 2, "timeoutSeconds": 3, "periodSeconds": 4, "successThreshold": 5, "failureThreshold": 6, "terminationGracePeriodSeconds": 7 }, "startupProbe": { "exec": { "command": [ "commandValue" ] }, "httpGet": { "path": "pathValue", "port": "portValue", "host": "hostValue", "scheme": "schemeValue", "httpHeaders": [ { "name": "nameValue", "value": "valueValue" } ] }, "tcpSocket": { "port": "portValue", "host": "hostValue" }, "grpc": { "port": 1, "service": "serviceValue" }, "initialDelaySeconds": 2, "timeoutSeconds": 3, "periodSeconds": 4, "successThreshold": 5, "failureThreshold": 6, "terminationGracePeriodSeconds": 7 }, "lifecycle": { "postStart": { "exec": { "command": [ "commandValue" ] }, "httpGet": { "path": "pathValue", "port": "portValue", "host": "hostValue", "scheme": "schemeValue", "httpHeaders": [ { "name": "nameValue", "value": "valueValue" } ] }, "tcpSocket": { "port": "portValue", "host": "hostValue" } }, "preStop": { "exec": { "command": [ "commandValue" ] }, "httpGet": { "path": "pathValue", "port": "portValue", "host": "hostValue", "scheme": "schemeValue", "httpHeaders": [ { "name": "nameValue", "value": "valueValue" } ] }, "tcpSocket": { "port": "portValue", "host": "hostValue" } } }, "terminationMessagePath": "terminationMessagePathValue", "terminationMessagePolicy": "terminationMessagePolicyValue", "imagePullPolicy": "imagePullPolicyValue", "securityContext": { "capabilities": { "add": [ "addValue" ], "drop": [ "dropValue" ] }, "privileged": true, "seLinuxOptions": { "user": "userValue", "role": "roleValue", "type": "typeValue", "level": "levelValue" }, "windowsOptions": { "gmsaCredentialSpecName": "gmsaCredentialSpecNameValue", "gmsaCredentialSpec": "gmsaCredentialSpecValue", "runAsUserName": "runAsUserNameValue", "hostProcess": true }, "runAsUser": 4, "runAsGroup": 8, "runAsNonRoot": true, "readOnlyRootFilesystem": true, "allowPrivilegeEscalation": true, "procMount": "procMountValue", "seccompProfile": { "type": "typeValue", "localhostProfile": "localhostProfileValue" } }, "stdin": true, "stdinOnce": true, "tty": true, "targetContainerName": "targetContainerNameValue" } ], "restartPolicy": "restartPolicyValue", "terminationGracePeriodSeconds": 4, "activeDeadlineSeconds": 5, "dnsPolicy": "dnsPolicyValue", "nodeSelector": { "nodeSelectorKey": "nodeSelectorValue" }, "serviceAccountName": "serviceAccountNameValue", "serviceAccount": "serviceAccountValue", "automountServiceAccountToken": true, "nodeName": "nodeNameValue", "hostNetwork": true, "hostPID": true, "hostIPC": true, "shareProcessNamespace": true, "securityContext": { "seLinuxOptions": { "user": "userValue", "role": "roleValue", "type": "typeValue", "level": "levelValue" }, "windowsOptions": { "gmsaCredentialSpecName": "gmsaCredentialSpecNameValue", "gmsaCredentialSpec": "gmsaCredentialSpecValue", "runAsUserName": "runAsUserNameValue", "hostProcess": true }, "runAsUser": 2, "runAsGroup": 6, "runAsNonRoot": true, "supplementalGroups": [ 4 ], "fsGroup": 5, "sysctls": [ { "name": "nameValue", "value": "valueValue" } ], "fsGroupChangePolicy": "fsGroupChangePolicyValue", "seccompProfile": { "type": "typeValue", "localhostProfile": "localhostProfileValue" } }, "imagePullSecrets": [ { "name": "nameValue" } ], "hostname": "hostnameValue", "subdomain": "subdomainValue", "affinity": { "nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [ { "matchExpressions": [ { "key": "keyValue", "operator": "operatorValue", "values": [ "valuesValue" ] } ], "matchFields": [ { "key": "keyValue", "operator": "operatorValue", "values": [ "valuesValue" ] } ] } ] }, "preferredDuringSchedulingIgnoredDuringExecution": [ { "weight": 1, "preference": { "matchExpressions": [ { "key": "keyValue", "operator": "operatorValue", "values": [ "valuesValue" ] } ], "matchFields": [ { "key": "keyValue", "operator": "operatorValue", "values": [ "valuesValue" ] } ] } } ] }, "podAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [ { "labelSelector": { "matchLabels": { "matchLabelsKey": "matchLabelsValue" }, "matchExpressions": [ { "key": "keyValue", "operator": "operatorValue", "values": [ "valuesValue" ] } ] }, "namespaces": [ "namespacesValue" ], "topologyKey": "topologyKeyValue", "namespaceSelector": { "matchLabels": { "matchLabelsKey": "matchLabelsValue" }, "matchExpressions": [ { "key": "keyValue", "operator": "operatorValue", "values": [ "valuesValue" ] } ] } } ], "preferredDuringSchedulingIgnoredDuringExecution": [ { "weight": 1, "podAffinityTerm": { "labelSelector": { "matchLabels": { "matchLabelsKey": "matchLabelsValue" }, "matchExpressions": [ { "key": "keyValue", "operator": "operatorValue", "values": [ "valuesValue" ] } ] }, "namespaces": [ "namespacesValue" ], "topologyKey": "topologyKeyValue", "namespaceSelector": { "matchLabels": { "matchLabelsKey": "matchLabelsValue" }, "matchExpressions": [ { "key": "keyValue", "operator": "operatorValue", "values": [ "valuesValue" ] } ] } } } ] }, "podAntiAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [ { "labelSelector": { "matchLabels": { "matchLabelsKey": "matchLabelsValue" }, "matchExpressions": [ { "key": "keyValue", "operator": "operatorValue", "values": [ "valuesValue" ] } ] }, "namespaces": [ "namespacesValue" ], "topologyKey": "topologyKeyValue", "namespaceSelector": { "matchLabels": { "matchLabelsKey": "matchLabelsValue" }, "matchExpressions": [ { "key": "keyValue", "operator": "operatorValue", "values": [ "valuesValue" ] } ] } } ], "preferredDuringSchedulingIgnoredDuringExecution": [ { "weight": 1, "podAffinityTerm": { "labelSelector": { "matchLabels": { "matchLabelsKey": "matchLabelsValue" }, "matchExpressions": [ { "key": "keyValue", "operator": "operatorValue", "values": [ "valuesValue" ] } ] }, "namespaces": [ "namespacesValue" ], "topologyKey": "topologyKeyValue", "namespaceSelector": { "matchLabels": { "matchLabelsKey": "matchLabelsValue" }, "matchExpressions": [ { "key": "keyValue", "operator": "operatorValue", "values": [ "valuesValue" ] } ] } } } ] } }, "schedulerName": "schedulerNameValue", "tolerations": [ { "key": "keyValue", "operator": "operatorValue", "value": "valueValue", "effect": "effectValue", "tolerationSeconds": 5 } ], "hostAliases": [ { "ip": "ipValue", "hostnames": [ "hostnamesValue" ] } ], "priorityClassName": "priorityClassNameValue", "priority": 25, "dnsConfig": { "nameservers": [ "nameserversValue" ], "searches": [ "searchesValue" ], "options": [ { "name": "nameValue", "value": "valueValue" } ] }, "readinessGates": [ { "conditionType": "conditionTypeValue" } ], "runtimeClassName": "runtimeClassNameValue", "enableServiceLinks": true, "preemptionPolicy": "preemptionPolicyValue", "overhead": { "overheadKey": "0" }, "topologySpreadConstraints": [ { "maxSkew": 1, "topologyKey": "topologyKeyValue", "whenUnsatisfiable": "whenUnsatisfiableValue", "labelSelector": { "matchLabels": { "matchLabelsKey": "matchLabelsValue" }, "matchExpressions": [ { "key": "keyValue", "operator": "operatorValue", "values": [ "valuesValue" ] } ] }, "minDomains": 5 } ], "setHostnameAsFQDN": true, "os": { "name": "nameValue" } } }, "updateStrategy": { "type": "typeValue", "rollingUpdate": { "maxUnavailable": "maxUnavailableValue", "maxSurge": "maxSurgeValue" } }, "minReadySeconds": 4, "revisionHistoryLimit": 6 }, "status": { "currentNumberScheduled": 1, "numberMisscheduled": 2, "desiredNumberScheduled": 3, "numberReady": 4, "observedGeneration": 5, "updatedNumberScheduled": 6, "numberAvailable": 7, "numberUnavailable": 8, "collisionCount": 9, "conditions": [ { "type": "typeValue", "status": "statusValue", "lastTransitionTime": "2003-01-01T01:01:01Z", "reason": "reasonValue", "message": "messageValue" } ] } }
staging/src/k8s.io/api/testdata/v1.24.0/apps.v1.DaemonSet.json
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.0001762797764968127, 0.00017078424571081996, 0.0001664682204136625, 0.0001707960618659854, 0.0000018965454273711657 ]
{ "id": 0, "code_window": [ "\t\"k8s.io/kubernetes/cmd/kube-controller-manager/app\"\n", "\tkubecontrollerconfig \"k8s.io/kubernetes/cmd/kube-controller-manager/app/config\"\n", "\t\"k8s.io/kubernetes/cmd/kube-controller-manager/app/options\"\n", ")\n", "\n", "// TearDownFunc is to be called to tear down a test server.\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\"k8s.io/klog/v2\"\n" ], "file_path": "cmd/kube-controller-manager/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 33 }
// Copyright ©2015 The Gonum Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // TODO(kortschak): Generate this file from shadow.go when all complex type are available. package mat import "gonum.org/v1/gonum/blas/cblas128" // checkOverlapComplex returns false if the receiver does not overlap data elements // referenced by the parameter and panics otherwise. // // checkOverlapComplex methods return a boolean to allow the check call to be added to a // boolean expression, making use of short-circuit operators. func checkOverlapComplex(a, b cblas128.General) bool { if cap(a.Data) == 0 || cap(b.Data) == 0 { return false } off := offsetComplex(a.Data[:1], b.Data[:1]) if off == 0 { // At least one element overlaps. if a.Cols == b.Cols && a.Rows == b.Rows && a.Stride == b.Stride { panic(regionIdentity) } panic(regionOverlap) } if off > 0 && len(a.Data) <= off { // We know a is completely before b. return false } if off < 0 && len(b.Data) <= -off { // We know a is completely after b. return false } if a.Stride != b.Stride && a.Stride != 1 && b.Stride != 1 { // Too hard, so assume the worst; if either stride // is one it will be caught in rectanglesOverlap. panic(mismatchedStrides) } if off < 0 { off = -off a.Cols, b.Cols = b.Cols, a.Cols } if rectanglesOverlap(off, a.Cols, b.Cols, min(a.Stride, b.Stride)) { panic(regionOverlap) } return false } func (m *CDense) checkOverlapComplex(a cblas128.General) bool { return checkOverlapComplex(m.RawCMatrix(), a) } func (m *CDense) checkOverlapMatrix(a CMatrix) bool { if m == a { return false } var amat cblas128.General switch ar := a.(type) { default: return false case RawCMatrixer: amat = ar.RawCMatrix() } return m.checkOverlapComplex(amat) }
vendor/gonum.org/v1/gonum/mat/shadow_complex.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.00017994665540754795, 0.00017389809363521636, 0.0001685046881902963, 0.00017473303887527436, 0.0000036086714771954576 ]
{ "id": 1, "code_window": [ "// \t\t enough time to remove temporary files.\n", "func StartTestServer(t Logger, customFlags []string) (result TestServer, err error) {\n", "\tstopCh := make(chan struct{})\n", "\ttearDown := func() {\n", "\t\tclose(stopCh)\n" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\tvar errCh chan error\n" ], "file_path": "cmd/kube-controller-manager/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 62 }
/* Copyright 2018 The Kubernetes 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 testing import ( "context" "fmt" "net" "os" "time" "github.com/spf13/pflag" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes" restclient "k8s.io/client-go/rest" "k8s.io/kubernetes/cmd/kube-controller-manager/app" kubecontrollerconfig "k8s.io/kubernetes/cmd/kube-controller-manager/app/config" "k8s.io/kubernetes/cmd/kube-controller-manager/app/options" ) // TearDownFunc is to be called to tear down a test server. type TearDownFunc func() // TestServer return values supplied by kube-test-ApiServer type TestServer struct { LoopbackClientConfig *restclient.Config // Rest client config using the magic token Options *options.KubeControllerManagerOptions Config *kubecontrollerconfig.Config TearDownFn TearDownFunc // TearDown function TmpDir string // Temp Dir used, by the apiserver } // Logger allows t.Testing and b.Testing to be passed to StartTestServer and StartTestServerOrDie type Logger interface { Errorf(format string, args ...interface{}) Fatalf(format string, args ...interface{}) Logf(format string, args ...interface{}) } // StartTestServer starts a kube-controller-manager. A rest client config and a tear-down func, // and location of the tmpdir are returned. // // Note: we return a tear-down func instead of a stop channel because the later will leak temporary // files that because Golang testing's call to os.Exit will not give a stop channel go routine // enough time to remove temporary files. func StartTestServer(t Logger, customFlags []string) (result TestServer, err error) { stopCh := make(chan struct{}) tearDown := func() { close(stopCh) if len(result.TmpDir) != 0 { os.RemoveAll(result.TmpDir) } } defer func() { if result.TearDownFn == nil { tearDown() } }() result.TmpDir, err = os.MkdirTemp("", "kube-controller-manager") if err != nil { return result, fmt.Errorf("failed to create temp dir: %v", err) } fs := pflag.NewFlagSet("test", pflag.PanicOnError) s, err := options.NewKubeControllerManagerOptions() if err != nil { return TestServer{}, err } all, disabled := app.KnownControllers(), app.ControllersDisabledByDefault.List() namedFlagSets := s.Flags(all, disabled) for _, f := range namedFlagSets.FlagSets { fs.AddFlagSet(f) } fs.Parse(customFlags) if s.SecureServing.BindPort != 0 { s.SecureServing.Listener, s.SecureServing.BindPort, err = createListenerOnFreePort() if err != nil { return result, fmt.Errorf("failed to create listener: %v", err) } s.SecureServing.ServerCert.CertDirectory = result.TmpDir t.Logf("kube-controller-manager will listen securely on port %d...", s.SecureServing.BindPort) } config, err := s.Config(all, disabled) if err != nil { return result, fmt.Errorf("failed to create config from options: %v", err) } errCh := make(chan error) go func(stopCh <-chan struct{}) { if err := app.Run(config.Complete(), stopCh); err != nil { errCh <- err } }(stopCh) t.Logf("Waiting for /healthz to be ok...") client, err := kubernetes.NewForConfig(config.LoopbackClientConfig) if err != nil { return result, fmt.Errorf("failed to create a client: %v", err) } err = wait.Poll(100*time.Millisecond, 30*time.Second, func() (bool, error) { select { case err := <-errCh: return false, err default: } result := client.CoreV1().RESTClient().Get().AbsPath("/healthz").Do(context.TODO()) status := 0 result.StatusCode(&status) if status == 200 { return true, nil } return false, nil }) if err != nil { return result, fmt.Errorf("failed to wait for /healthz to return ok: %v", err) } // from here the caller must call tearDown result.LoopbackClientConfig = config.LoopbackClientConfig result.Options = s result.Config = config result.TearDownFn = tearDown return result, nil } // StartTestServerOrDie calls StartTestServer t.Fatal if it does not succeed. func StartTestServerOrDie(t Logger, flags []string) *TestServer { result, err := StartTestServer(t, flags) if err == nil { return &result } t.Fatalf("failed to launch server: %v", err) return nil } func createListenerOnFreePort() (net.Listener, int, error) { ln, err := net.Listen("tcp", ":0") if err != nil { return nil, 0, err } // get port tcpAddr, ok := ln.Addr().(*net.TCPAddr) if !ok { ln.Close() return nil, 0, fmt.Errorf("invalid listen address: %q", ln.Addr().String()) } return ln, tcpAddr.Port, nil }
cmd/kube-controller-manager/app/testing/testserver.go
1
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.9990696310997009, 0.49734681844711304, 0.00016858844901435077, 0.4970686435699463, 0.49271857738494873 ]
{ "id": 1, "code_window": [ "// \t\t enough time to remove temporary files.\n", "func StartTestServer(t Logger, customFlags []string) (result TestServer, err error) {\n", "\tstopCh := make(chan struct{})\n", "\ttearDown := func() {\n", "\t\tclose(stopCh)\n" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\tvar errCh chan error\n" ], "file_path": "cmd/kube-controller-manager/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 62 }
/* Copyright 2018 The Kubernetes 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 cloudresource import ( "errors" "reflect" "testing" "time" "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/util/diff" "k8s.io/cloud-provider/fake" ) func createNodeInternalIPAddress(address string) []v1.NodeAddress { return []v1.NodeAddress{ { Type: v1.NodeInternalIP, Address: address, }, } } func TestNodeAddressesDelay(t *testing.T) { syncPeriod := 100 * time.Millisecond cloud := &fake.Cloud{ Addresses: createNodeInternalIPAddress("10.0.1.12"), // Set the request delay so the manager timeouts and collects the node addresses later RequestDelay: 200 * time.Millisecond, } stopCh := make(chan struct{}) defer close(stopCh) manager := NewSyncManager(cloud, "defaultNode", syncPeriod).(*cloudResourceSyncManager) go manager.Run(stopCh) nodeAddresses, err := manager.NodeAddresses() if err != nil { t.Errorf("Unexpected err: %q\n", err) } if !reflect.DeepEqual(nodeAddresses, cloud.Addresses) { t.Errorf("Unexpected diff of node addresses: %v", diff.ObjectReflectDiff(nodeAddresses, cloud.Addresses)) } // Change the IP address cloud.SetNodeAddresses(createNodeInternalIPAddress("10.0.1.13")) // Wait until the IP address changes maxRetry := 5 for i := 0; i < maxRetry; i++ { nodeAddresses, err := manager.NodeAddresses() t.Logf("nodeAddresses: %#v, err: %v", nodeAddresses, err) if err != nil { t.Errorf("Unexpected err: %q\n", err) } // It is safe to read cloud.Addresses since no routine is changing the value at the same time if err == nil && nodeAddresses[0].Address != cloud.Addresses[0].Address { time.Sleep(syncPeriod) continue } if err != nil { t.Errorf("Unexpected err: %q\n", err) } return } t.Errorf("Timeout waiting for %q address to appear", cloud.Addresses[0].Address) } func TestNodeAddressesUsesLastSuccess(t *testing.T) { cloud := &fake.Cloud{} manager := NewSyncManager(cloud, "defaultNode", 0).(*cloudResourceSyncManager) // These tests are stateful and order dependent. tests := []struct { name string addrs []v1.NodeAddress err error wantAddrs []v1.NodeAddress wantErr bool }{ { name: "first sync loop encounters an error", err: errors.New("bad"), wantErr: true, }, { name: "subsequent sync loop succeeds", addrs: createNodeInternalIPAddress("10.0.1.12"), wantAddrs: createNodeInternalIPAddress("10.0.1.12"), }, { name: "subsequent sync loop encounters an error, last addresses returned", err: errors.New("bad"), wantAddrs: createNodeInternalIPAddress("10.0.1.12"), }, { name: "subsequent sync loop succeeds changing addresses", addrs: createNodeInternalIPAddress("10.0.1.13"), wantAddrs: createNodeInternalIPAddress("10.0.1.13"), }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { cloud.Addresses = test.addrs cloud.Err = test.err manager.syncNodeAddresses() nodeAddresses, err := manager.NodeAddresses() if (err != nil) != test.wantErr { t.Errorf("unexpected err: %v", err) } if got, want := nodeAddresses, test.wantAddrs; !reflect.DeepEqual(got, want) { t.Errorf("Unexpected diff of node addresses: %v", diff.ObjectReflectDiff(got, want)) } }) } }
pkg/kubelet/cloudresource/cloud_request_manager_test.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.9822385311126709, 0.07032289355993271, 0.00016846695507410914, 0.00017271759861614555, 0.25291988253593445 ]
{ "id": 1, "code_window": [ "// \t\t enough time to remove temporary files.\n", "func StartTestServer(t Logger, customFlags []string) (result TestServer, err error) {\n", "\tstopCh := make(chan struct{})\n", "\ttearDown := func() {\n", "\t\tclose(stopCh)\n" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\tvar errCh chan error\n" ], "file_path": "cmd/kube-controller-manager/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 62 }
/* Copyright 2014 The Kubernetes 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 versioned import ( "fmt" "strconv" "strings" "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/kubectl/pkg/generate" ) // The only difference between ServiceGeneratorV1 and V2 is that the service port is named "default" in V1, while it is left unnamed in V2. type ServiceGeneratorV1 struct{} func (ServiceGeneratorV1) ParamNames() []generate.GeneratorParam { return paramNames() } func (ServiceGeneratorV1) Generate(params map[string]interface{}) (runtime.Object, error) { params["port-name"] = "default" return generateService(params) } type ServiceGeneratorV2 struct{} func (ServiceGeneratorV2) ParamNames() []generate.GeneratorParam { return paramNames() } func (ServiceGeneratorV2) Generate(params map[string]interface{}) (runtime.Object, error) { return generateService(params) } func paramNames() []generate.GeneratorParam { return []generate.GeneratorParam{ {Name: "default-name", Required: true}, {Name: "name", Required: false}, {Name: "selector", Required: true}, // port will be used if a user specifies --port OR the exposed object // has one port {Name: "port", Required: false}, // ports will be used iff a user doesn't specify --port AND the // exposed object has multiple ports {Name: "ports", Required: false}, {Name: "labels", Required: false}, {Name: "external-ip", Required: false}, {Name: "load-balancer-ip", Required: false}, {Name: "type", Required: false}, {Name: "protocol", Required: false}, // protocols will be used to keep port-protocol mapping derived from // exposed object {Name: "protocols", Required: false}, {Name: "container-port", Required: false}, // alias of target-port {Name: "target-port", Required: false}, {Name: "port-name", Required: false}, {Name: "session-affinity", Required: false}, {Name: "cluster-ip", Required: false}, } } func generateService(genericParams map[string]interface{}) (runtime.Object, error) { params := map[string]string{} for key, value := range genericParams { strVal, isString := value.(string) if !isString { return nil, fmt.Errorf("expected string, saw %v for '%s'", value, key) } params[key] = strVal } selectorString, found := params["selector"] if !found || len(selectorString) == 0 { return nil, fmt.Errorf("'selector' is a required parameter") } selector, err := generate.ParseLabels(selectorString) if err != nil { return nil, err } labelsString, found := params["labels"] var labels map[string]string if found && len(labelsString) > 0 { labels, err = generate.ParseLabels(labelsString) if err != nil { return nil, err } } name, found := params["name"] if !found || len(name) == 0 { name, found = params["default-name"] if !found || len(name) == 0 { return nil, fmt.Errorf("'name' is a required parameter") } } isHeadlessService := params["cluster-ip"] == "None" ports := []v1.ServicePort{} servicePortName, found := params["port-name"] if !found { // Leave the port unnamed. servicePortName = "" } protocolsString, found := params["protocols"] var portProtocolMap map[string]string if found && len(protocolsString) > 0 { portProtocolMap, err = generate.ParseProtocols(protocolsString) if err != nil { return nil, err } } // ports takes precedence over port since it will be // specified only when the user hasn't specified a port // via --port and the exposed object has multiple ports. var portString string if portString, found = params["ports"]; !found { portString, found = params["port"] if !found && !isHeadlessService { return nil, fmt.Errorf("'ports' or 'port' is a required parameter") } } if portString != "" { portStringSlice := strings.Split(portString, ",") for i, stillPortString := range portStringSlice { port, err := strconv.Atoi(stillPortString) if err != nil { return nil, err } name := servicePortName // If we are going to assign multiple ports to a service, we need to // generate a different name for each one. if len(portStringSlice) > 1 { name = fmt.Sprintf("port-%d", i+1) } protocol := params["protocol"] switch { case len(protocol) == 0 && len(portProtocolMap) == 0: // Default to TCP, what the flag was doing previously. protocol = "TCP" case len(protocol) > 0 && len(portProtocolMap) > 0: // User has specified the --protocol while exposing a multiprotocol resource // We should stomp multiple protocols with the one specified ie. do nothing case len(protocol) == 0 && len(portProtocolMap) > 0: // no --protocol and we expose a multiprotocol resource protocol = "TCP" // have the default so we can stay sane if exposeProtocol, found := portProtocolMap[stillPortString]; found { protocol = exposeProtocol } } ports = append(ports, v1.ServicePort{ Name: name, Port: int32(port), Protocol: v1.Protocol(protocol), }) } } service := v1.Service{ ObjectMeta: metav1.ObjectMeta{ Name: name, Labels: labels, }, Spec: v1.ServiceSpec{ Selector: selector, Ports: ports, }, } targetPortString := params["target-port"] if len(targetPortString) == 0 { targetPortString = params["container-port"] } if len(targetPortString) > 0 { var targetPort intstr.IntOrString if portNum, err := strconv.Atoi(targetPortString); err != nil { targetPort = intstr.FromString(targetPortString) } else { targetPort = intstr.FromInt(portNum) } // Use the same target-port for every port for i := range service.Spec.Ports { service.Spec.Ports[i].TargetPort = targetPort } } else { // If --target-port or --container-port haven't been specified, this // should be the same as Port for i := range service.Spec.Ports { port := service.Spec.Ports[i].Port service.Spec.Ports[i].TargetPort = intstr.FromInt(int(port)) } } if len(params["external-ip"]) > 0 { service.Spec.ExternalIPs = []string{params["external-ip"]} } if len(params["type"]) != 0 { service.Spec.Type = v1.ServiceType(params["type"]) } if service.Spec.Type == v1.ServiceTypeLoadBalancer { service.Spec.LoadBalancerIP = params["load-balancer-ip"] } if len(params["session-affinity"]) != 0 { switch v1.ServiceAffinity(params["session-affinity"]) { case v1.ServiceAffinityNone: service.Spec.SessionAffinity = v1.ServiceAffinityNone case v1.ServiceAffinityClientIP: service.Spec.SessionAffinity = v1.ServiceAffinityClientIP default: return nil, fmt.Errorf("unknown session affinity: %s", params["session-affinity"]) } } if len(params["cluster-ip"]) != 0 { if params["cluster-ip"] == "None" { service.Spec.ClusterIP = v1.ClusterIPNone } else { service.Spec.ClusterIP = params["cluster-ip"] } } return &service, nil }
staging/src/k8s.io/kubectl/pkg/generate/versioned/service.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.00017876509809866548, 0.00017194703104905784, 0.00016509424312971532, 0.00017187265621032566, 0.0000034893400879809633 ]
{ "id": 1, "code_window": [ "// \t\t enough time to remove temporary files.\n", "func StartTestServer(t Logger, customFlags []string) (result TestServer, err error) {\n", "\tstopCh := make(chan struct{})\n", "\ttearDown := func() {\n", "\t\tclose(stopCh)\n" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\tvar errCh chan error\n" ], "file_path": "cmd/kube-controller-manager/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 62 }
/* Copyright 2019 The Kubernetes 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 dynamiccertificates import ( "bytes" ) // dynamicCertificateContent holds the content that overrides the baseTLSConfig type dynamicCertificateContent struct { // clientCA holds the content for the clientCA bundle clientCA caBundleContent servingCert certKeyContent sniCerts []sniCertKeyContent } // caBundleContent holds the content for the clientCA bundle. Wrapping the bytes makes the Equals work nicely with the // method receiver. type caBundleContent struct { caBundle []byte } func (c *dynamicCertificateContent) Equal(rhs *dynamicCertificateContent) bool { if c == nil || rhs == nil { return c == rhs } if !c.clientCA.Equal(&rhs.clientCA) { return false } if !c.servingCert.Equal(&rhs.servingCert) { return false } if len(c.sniCerts) != len(rhs.sniCerts) { return false } for i := range c.sniCerts { if !c.sniCerts[i].Equal(&rhs.sniCerts[i]) { return false } } return true } func (c *caBundleContent) Equal(rhs *caBundleContent) bool { if c == nil || rhs == nil { return c == rhs } return bytes.Equal(c.caBundle, rhs.caBundle) }
staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/client_ca.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.00017797663167584687, 0.00017294772260356694, 0.00016591533494647592, 0.0001758978032739833, 0.000004802620424015913 ]
{ "id": 2, "code_window": [ "\ttearDown := func() {\n", "\t\tclose(stopCh)\n", "\t\tif len(result.TmpDir) != 0 {\n", "\t\t\tos.RemoveAll(result.TmpDir)\n", "\t\t}\n", "\t}\n", "\tdefer func() {\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\t// If the kube-controller-manager was started, let's wait for\n", "\t\t// it to shutdown clearly.\n", "\t\tif errCh != nil {\n", "\t\t\terr, ok := <-errCh\n", "\t\t\tif ok && err != nil {\n", "\t\t\t\tklog.Errorf(\"Failed to shutdown test server clearly: %v\", err)\n", "\t\t\t}\n", "\t\t}\n" ], "file_path": "cmd/kube-controller-manager/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 64 }
/* Copyright 2018 The Kubernetes 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 testing import ( "context" "fmt" "net" "os" "time" "github.com/spf13/pflag" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes" restclient "k8s.io/client-go/rest" "k8s.io/kubernetes/cmd/kube-controller-manager/app" kubecontrollerconfig "k8s.io/kubernetes/cmd/kube-controller-manager/app/config" "k8s.io/kubernetes/cmd/kube-controller-manager/app/options" ) // TearDownFunc is to be called to tear down a test server. type TearDownFunc func() // TestServer return values supplied by kube-test-ApiServer type TestServer struct { LoopbackClientConfig *restclient.Config // Rest client config using the magic token Options *options.KubeControllerManagerOptions Config *kubecontrollerconfig.Config TearDownFn TearDownFunc // TearDown function TmpDir string // Temp Dir used, by the apiserver } // Logger allows t.Testing and b.Testing to be passed to StartTestServer and StartTestServerOrDie type Logger interface { Errorf(format string, args ...interface{}) Fatalf(format string, args ...interface{}) Logf(format string, args ...interface{}) } // StartTestServer starts a kube-controller-manager. A rest client config and a tear-down func, // and location of the tmpdir are returned. // // Note: we return a tear-down func instead of a stop channel because the later will leak temporary // files that because Golang testing's call to os.Exit will not give a stop channel go routine // enough time to remove temporary files. func StartTestServer(t Logger, customFlags []string) (result TestServer, err error) { stopCh := make(chan struct{}) tearDown := func() { close(stopCh) if len(result.TmpDir) != 0 { os.RemoveAll(result.TmpDir) } } defer func() { if result.TearDownFn == nil { tearDown() } }() result.TmpDir, err = os.MkdirTemp("", "kube-controller-manager") if err != nil { return result, fmt.Errorf("failed to create temp dir: %v", err) } fs := pflag.NewFlagSet("test", pflag.PanicOnError) s, err := options.NewKubeControllerManagerOptions() if err != nil { return TestServer{}, err } all, disabled := app.KnownControllers(), app.ControllersDisabledByDefault.List() namedFlagSets := s.Flags(all, disabled) for _, f := range namedFlagSets.FlagSets { fs.AddFlagSet(f) } fs.Parse(customFlags) if s.SecureServing.BindPort != 0 { s.SecureServing.Listener, s.SecureServing.BindPort, err = createListenerOnFreePort() if err != nil { return result, fmt.Errorf("failed to create listener: %v", err) } s.SecureServing.ServerCert.CertDirectory = result.TmpDir t.Logf("kube-controller-manager will listen securely on port %d...", s.SecureServing.BindPort) } config, err := s.Config(all, disabled) if err != nil { return result, fmt.Errorf("failed to create config from options: %v", err) } errCh := make(chan error) go func(stopCh <-chan struct{}) { if err := app.Run(config.Complete(), stopCh); err != nil { errCh <- err } }(stopCh) t.Logf("Waiting for /healthz to be ok...") client, err := kubernetes.NewForConfig(config.LoopbackClientConfig) if err != nil { return result, fmt.Errorf("failed to create a client: %v", err) } err = wait.Poll(100*time.Millisecond, 30*time.Second, func() (bool, error) { select { case err := <-errCh: return false, err default: } result := client.CoreV1().RESTClient().Get().AbsPath("/healthz").Do(context.TODO()) status := 0 result.StatusCode(&status) if status == 200 { return true, nil } return false, nil }) if err != nil { return result, fmt.Errorf("failed to wait for /healthz to return ok: %v", err) } // from here the caller must call tearDown result.LoopbackClientConfig = config.LoopbackClientConfig result.Options = s result.Config = config result.TearDownFn = tearDown return result, nil } // StartTestServerOrDie calls StartTestServer t.Fatal if it does not succeed. func StartTestServerOrDie(t Logger, flags []string) *TestServer { result, err := StartTestServer(t, flags) if err == nil { return &result } t.Fatalf("failed to launch server: %v", err) return nil } func createListenerOnFreePort() (net.Listener, int, error) { ln, err := net.Listen("tcp", ":0") if err != nil { return nil, 0, err } // get port tcpAddr, ok := ln.Addr().(*net.TCPAddr) if !ok { ln.Close() return nil, 0, fmt.Errorf("invalid listen address: %q", ln.Addr().String()) } return ln, tcpAddr.Port, nil }
cmd/kube-controller-manager/app/testing/testserver.go
1
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.9969801306724548, 0.11903324723243713, 0.0001665133167989552, 0.002240185858681798, 0.31085655093193054 ]
{ "id": 2, "code_window": [ "\ttearDown := func() {\n", "\t\tclose(stopCh)\n", "\t\tif len(result.TmpDir) != 0 {\n", "\t\t\tos.RemoveAll(result.TmpDir)\n", "\t\t}\n", "\t}\n", "\tdefer func() {\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\t// If the kube-controller-manager was started, let's wait for\n", "\t\t// it to shutdown clearly.\n", "\t\tif errCh != nil {\n", "\t\t\terr, ok := <-errCh\n", "\t\t\tif ok && err != nil {\n", "\t\t\t\tklog.Errorf(\"Failed to shutdown test server clearly: %v\", err)\n", "\t\t\t}\n", "\t\t}\n" ], "file_path": "cmd/kube-controller-manager/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 64 }
/* Copyright The Kubernetes 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. */ // Code generated by client-gen. DO NOT EDIT. // This package has the automatically generated typed clients. package v1beta1
staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/doc.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.00017904298147186637, 0.00017662103346083313, 0.0001723752066027373, 0.00017844492685981095, 0.000003012167780980235 ]
{ "id": 2, "code_window": [ "\ttearDown := func() {\n", "\t\tclose(stopCh)\n", "\t\tif len(result.TmpDir) != 0 {\n", "\t\t\tos.RemoveAll(result.TmpDir)\n", "\t\t}\n", "\t}\n", "\tdefer func() {\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\t// If the kube-controller-manager was started, let's wait for\n", "\t\t// it to shutdown clearly.\n", "\t\tif errCh != nil {\n", "\t\t\terr, ok := <-errCh\n", "\t\t\tif ok && err != nil {\n", "\t\t\t\tklog.Errorf(\"Failed to shutdown test server clearly: %v\", err)\n", "\t\t\t}\n", "\t\t}\n" ], "file_path": "cmd/kube-controller-manager/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 64 }
/* Copyright The Kubernetes 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. */ // Code generated by client-gen. DO NOT EDIT. package v1 import ( "context" json "encoding/json" "fmt" "time" v1 "k8s.io/api/apps/v1" autoscalingv1 "k8s.io/api/autoscaling/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" appsv1 "k8s.io/client-go/applyconfigurations/apps/v1" applyconfigurationsautoscalingv1 "k8s.io/client-go/applyconfigurations/autoscaling/v1" scheme "k8s.io/client-go/kubernetes/scheme" rest "k8s.io/client-go/rest" ) // ReplicaSetsGetter has a method to return a ReplicaSetInterface. // A group's client should implement this interface. type ReplicaSetsGetter interface { ReplicaSets(namespace string) ReplicaSetInterface } // ReplicaSetInterface has methods to work with ReplicaSet resources. type ReplicaSetInterface interface { Create(ctx context.Context, replicaSet *v1.ReplicaSet, opts metav1.CreateOptions) (*v1.ReplicaSet, error) Update(ctx context.Context, replicaSet *v1.ReplicaSet, opts metav1.UpdateOptions) (*v1.ReplicaSet, error) UpdateStatus(ctx context.Context, replicaSet *v1.ReplicaSet, opts metav1.UpdateOptions) (*v1.ReplicaSet, error) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.ReplicaSet, error) List(ctx context.Context, opts metav1.ListOptions) (*v1.ReplicaSetList, error) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ReplicaSet, err error) Apply(ctx context.Context, replicaSet *appsv1.ReplicaSetApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ReplicaSet, err error) ApplyStatus(ctx context.Context, replicaSet *appsv1.ReplicaSetApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ReplicaSet, err error) GetScale(ctx context.Context, replicaSetName string, options metav1.GetOptions) (*autoscalingv1.Scale, error) UpdateScale(ctx context.Context, replicaSetName string, scale *autoscalingv1.Scale, opts metav1.UpdateOptions) (*autoscalingv1.Scale, error) ApplyScale(ctx context.Context, replicaSetName string, scale *applyconfigurationsautoscalingv1.ScaleApplyConfiguration, opts metav1.ApplyOptions) (*autoscalingv1.Scale, error) ReplicaSetExpansion } // replicaSets implements ReplicaSetInterface type replicaSets struct { client rest.Interface ns string } // newReplicaSets returns a ReplicaSets func newReplicaSets(c *AppsV1Client, namespace string) *replicaSets { return &replicaSets{ client: c.RESTClient(), ns: namespace, } } // Get takes name of the replicaSet, and returns the corresponding replicaSet object, and an error if there is any. func (c *replicaSets) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ReplicaSet, err error) { result = &v1.ReplicaSet{} err = c.client.Get(). Namespace(c.ns). Resource("replicasets"). Name(name). VersionedParams(&options, scheme.ParameterCodec). Do(ctx). Into(result) return } // List takes label and field selectors, and returns the list of ReplicaSets that match those selectors. func (c *replicaSets) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ReplicaSetList, err error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } result = &v1.ReplicaSetList{} err = c.client.Get(). Namespace(c.ns). Resource("replicasets"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Do(ctx). Into(result) return } // Watch returns a watch.Interface that watches the requested replicaSets. func (c *replicaSets) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } opts.Watch = true return c.client.Get(). Namespace(c.ns). Resource("replicasets"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Watch(ctx) } // Create takes the representation of a replicaSet and creates it. Returns the server's representation of the replicaSet, and an error, if there is any. func (c *replicaSets) Create(ctx context.Context, replicaSet *v1.ReplicaSet, opts metav1.CreateOptions) (result *v1.ReplicaSet, err error) { result = &v1.ReplicaSet{} err = c.client.Post(). Namespace(c.ns). Resource("replicasets"). VersionedParams(&opts, scheme.ParameterCodec). Body(replicaSet). Do(ctx). Into(result) return } // Update takes the representation of a replicaSet and updates it. Returns the server's representation of the replicaSet, and an error, if there is any. func (c *replicaSets) Update(ctx context.Context, replicaSet *v1.ReplicaSet, opts metav1.UpdateOptions) (result *v1.ReplicaSet, err error) { result = &v1.ReplicaSet{} err = c.client.Put(). Namespace(c.ns). Resource("replicasets"). Name(replicaSet.Name). VersionedParams(&opts, scheme.ParameterCodec). Body(replicaSet). Do(ctx). Into(result) return } // UpdateStatus was generated because the type contains a Status member. // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). func (c *replicaSets) UpdateStatus(ctx context.Context, replicaSet *v1.ReplicaSet, opts metav1.UpdateOptions) (result *v1.ReplicaSet, err error) { result = &v1.ReplicaSet{} err = c.client.Put(). Namespace(c.ns). Resource("replicasets"). Name(replicaSet.Name). SubResource("status"). VersionedParams(&opts, scheme.ParameterCodec). Body(replicaSet). Do(ctx). Into(result) return } // Delete takes name of the replicaSet and deletes it. Returns an error if one occurs. func (c *replicaSets) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { return c.client.Delete(). Namespace(c.ns). Resource("replicasets"). Name(name). Body(&opts). Do(ctx). Error() } // DeleteCollection deletes a collection of objects. func (c *replicaSets) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { var timeout time.Duration if listOpts.TimeoutSeconds != nil { timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second } return c.client.Delete(). Namespace(c.ns). Resource("replicasets"). VersionedParams(&listOpts, scheme.ParameterCodec). Timeout(timeout). Body(&opts). Do(ctx). Error() } // Patch applies the patch and returns the patched replicaSet. func (c *replicaSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ReplicaSet, err error) { result = &v1.ReplicaSet{} err = c.client.Patch(pt). Namespace(c.ns). Resource("replicasets"). Name(name). SubResource(subresources...). VersionedParams(&opts, scheme.ParameterCodec). Body(data). Do(ctx). Into(result) return } // Apply takes the given apply declarative configuration, applies it and returns the applied replicaSet. func (c *replicaSets) Apply(ctx context.Context, replicaSet *appsv1.ReplicaSetApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ReplicaSet, err error) { if replicaSet == nil { return nil, fmt.Errorf("replicaSet provided to Apply must not be nil") } patchOpts := opts.ToPatchOptions() data, err := json.Marshal(replicaSet) if err != nil { return nil, err } name := replicaSet.Name if name == nil { return nil, fmt.Errorf("replicaSet.Name must be provided to Apply") } result = &v1.ReplicaSet{} err = c.client.Patch(types.ApplyPatchType). Namespace(c.ns). Resource("replicasets"). Name(*name). VersionedParams(&patchOpts, scheme.ParameterCodec). Body(data). Do(ctx). Into(result) return } // ApplyStatus was generated because the type contains a Status member. // Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus(). func (c *replicaSets) ApplyStatus(ctx context.Context, replicaSet *appsv1.ReplicaSetApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ReplicaSet, err error) { if replicaSet == nil { return nil, fmt.Errorf("replicaSet provided to Apply must not be nil") } patchOpts := opts.ToPatchOptions() data, err := json.Marshal(replicaSet) if err != nil { return nil, err } name := replicaSet.Name if name == nil { return nil, fmt.Errorf("replicaSet.Name must be provided to Apply") } result = &v1.ReplicaSet{} err = c.client.Patch(types.ApplyPatchType). Namespace(c.ns). Resource("replicasets"). Name(*name). SubResource("status"). VersionedParams(&patchOpts, scheme.ParameterCodec). Body(data). Do(ctx). Into(result) return } // GetScale takes name of the replicaSet, and returns the corresponding autoscalingv1.Scale object, and an error if there is any. func (c *replicaSets) GetScale(ctx context.Context, replicaSetName string, options metav1.GetOptions) (result *autoscalingv1.Scale, err error) { result = &autoscalingv1.Scale{} err = c.client.Get(). Namespace(c.ns). Resource("replicasets"). Name(replicaSetName). SubResource("scale"). VersionedParams(&options, scheme.ParameterCodec). Do(ctx). Into(result) return } // UpdateScale takes the top resource name and the representation of a scale and updates it. Returns the server's representation of the scale, and an error, if there is any. func (c *replicaSets) UpdateScale(ctx context.Context, replicaSetName string, scale *autoscalingv1.Scale, opts metav1.UpdateOptions) (result *autoscalingv1.Scale, err error) { result = &autoscalingv1.Scale{} err = c.client.Put(). Namespace(c.ns). Resource("replicasets"). Name(replicaSetName). SubResource("scale"). VersionedParams(&opts, scheme.ParameterCodec). Body(scale). Do(ctx). Into(result) return } // ApplyScale takes top resource name and the apply declarative configuration for scale, // applies it and returns the applied scale, and an error, if there is any. func (c *replicaSets) ApplyScale(ctx context.Context, replicaSetName string, scale *applyconfigurationsautoscalingv1.ScaleApplyConfiguration, opts metav1.ApplyOptions) (result *autoscalingv1.Scale, err error) { if scale == nil { return nil, fmt.Errorf("scale provided to ApplyScale must not be nil") } patchOpts := opts.ToPatchOptions() data, err := json.Marshal(scale) if err != nil { return nil, err } result = &autoscalingv1.Scale{} err = c.client.Patch(types.ApplyPatchType). Namespace(c.ns). Resource("replicasets"). Name(replicaSetName). SubResource("scale"). VersionedParams(&patchOpts, scheme.ParameterCodec). Body(data). Do(ctx). Into(result) return }
staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/replicaset.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.0033794231712818146, 0.0008379860082641244, 0.00016212076297961175, 0.00028957013273611665, 0.0008099544211290777 ]
{ "id": 2, "code_window": [ "\ttearDown := func() {\n", "\t\tclose(stopCh)\n", "\t\tif len(result.TmpDir) != 0 {\n", "\t\t\tos.RemoveAll(result.TmpDir)\n", "\t\t}\n", "\t}\n", "\tdefer func() {\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\t// If the kube-controller-manager was started, let's wait for\n", "\t\t// it to shutdown clearly.\n", "\t\tif errCh != nil {\n", "\t\t\terr, ok := <-errCh\n", "\t\t\tif ok && err != nil {\n", "\t\t\t\tklog.Errorf(\"Failed to shutdown test server clearly: %v\", err)\n", "\t\t\t}\n", "\t\t}\n" ], "file_path": "cmd/kube-controller-manager/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 64 }
/* Copyright 2016 The Kubernetes 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 term import ( "time" "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/client-go/tools/remotecommand" ) // monitorResizeEvents spawns a goroutine that periodically gets the terminal size and tries to send // it to the resizeEvents channel if the size has changed. The goroutine stops when the stop channel // is closed. func monitorResizeEvents(fd uintptr, resizeEvents chan<- remotecommand.TerminalSize, stop chan struct{}) { go func() { defer runtime.HandleCrash() size := GetSize(fd) if size == nil { return } lastSize := *size for { // see if we need to stop running select { case <-stop: return default: } size := GetSize(fd) if size == nil { return } if size.Height != lastSize.Height || size.Width != lastSize.Width { lastSize.Height = size.Height lastSize.Width = size.Width resizeEvents <- *size } // sleep to avoid hot looping time.Sleep(250 * time.Millisecond) } }() }
staging/src/k8s.io/kubectl/pkg/util/term/resizeevents_windows.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.0013911864953115582, 0.00035016777110286057, 0.0001715676044113934, 0.000178862625034526, 0.0004250062338542193 ]
{ "id": 3, "code_window": [ "\t\treturn result, fmt.Errorf(\"failed to create config from options: %v\", err)\n", "\t}\n", "\n", "\terrCh := make(chan error)\n", "\tgo func(stopCh <-chan struct{}) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\terrCh = make(chan error)\n" ], "file_path": "cmd/kube-controller-manager/app/testing/testserver.go", "type": "replace", "edit_start_line_idx": 107 }
/* Copyright 2018 The Kubernetes 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 testing import ( "context" "fmt" "net" "os" "time" "github.com/spf13/pflag" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes" restclient "k8s.io/client-go/rest" "k8s.io/kubernetes/cmd/kube-controller-manager/app" kubecontrollerconfig "k8s.io/kubernetes/cmd/kube-controller-manager/app/config" "k8s.io/kubernetes/cmd/kube-controller-manager/app/options" ) // TearDownFunc is to be called to tear down a test server. type TearDownFunc func() // TestServer return values supplied by kube-test-ApiServer type TestServer struct { LoopbackClientConfig *restclient.Config // Rest client config using the magic token Options *options.KubeControllerManagerOptions Config *kubecontrollerconfig.Config TearDownFn TearDownFunc // TearDown function TmpDir string // Temp Dir used, by the apiserver } // Logger allows t.Testing and b.Testing to be passed to StartTestServer and StartTestServerOrDie type Logger interface { Errorf(format string, args ...interface{}) Fatalf(format string, args ...interface{}) Logf(format string, args ...interface{}) } // StartTestServer starts a kube-controller-manager. A rest client config and a tear-down func, // and location of the tmpdir are returned. // // Note: we return a tear-down func instead of a stop channel because the later will leak temporary // files that because Golang testing's call to os.Exit will not give a stop channel go routine // enough time to remove temporary files. func StartTestServer(t Logger, customFlags []string) (result TestServer, err error) { stopCh := make(chan struct{}) tearDown := func() { close(stopCh) if len(result.TmpDir) != 0 { os.RemoveAll(result.TmpDir) } } defer func() { if result.TearDownFn == nil { tearDown() } }() result.TmpDir, err = os.MkdirTemp("", "kube-controller-manager") if err != nil { return result, fmt.Errorf("failed to create temp dir: %v", err) } fs := pflag.NewFlagSet("test", pflag.PanicOnError) s, err := options.NewKubeControllerManagerOptions() if err != nil { return TestServer{}, err } all, disabled := app.KnownControllers(), app.ControllersDisabledByDefault.List() namedFlagSets := s.Flags(all, disabled) for _, f := range namedFlagSets.FlagSets { fs.AddFlagSet(f) } fs.Parse(customFlags) if s.SecureServing.BindPort != 0 { s.SecureServing.Listener, s.SecureServing.BindPort, err = createListenerOnFreePort() if err != nil { return result, fmt.Errorf("failed to create listener: %v", err) } s.SecureServing.ServerCert.CertDirectory = result.TmpDir t.Logf("kube-controller-manager will listen securely on port %d...", s.SecureServing.BindPort) } config, err := s.Config(all, disabled) if err != nil { return result, fmt.Errorf("failed to create config from options: %v", err) } errCh := make(chan error) go func(stopCh <-chan struct{}) { if err := app.Run(config.Complete(), stopCh); err != nil { errCh <- err } }(stopCh) t.Logf("Waiting for /healthz to be ok...") client, err := kubernetes.NewForConfig(config.LoopbackClientConfig) if err != nil { return result, fmt.Errorf("failed to create a client: %v", err) } err = wait.Poll(100*time.Millisecond, 30*time.Second, func() (bool, error) { select { case err := <-errCh: return false, err default: } result := client.CoreV1().RESTClient().Get().AbsPath("/healthz").Do(context.TODO()) status := 0 result.StatusCode(&status) if status == 200 { return true, nil } return false, nil }) if err != nil { return result, fmt.Errorf("failed to wait for /healthz to return ok: %v", err) } // from here the caller must call tearDown result.LoopbackClientConfig = config.LoopbackClientConfig result.Options = s result.Config = config result.TearDownFn = tearDown return result, nil } // StartTestServerOrDie calls StartTestServer t.Fatal if it does not succeed. func StartTestServerOrDie(t Logger, flags []string) *TestServer { result, err := StartTestServer(t, flags) if err == nil { return &result } t.Fatalf("failed to launch server: %v", err) return nil } func createListenerOnFreePort() (net.Listener, int, error) { ln, err := net.Listen("tcp", ":0") if err != nil { return nil, 0, err } // get port tcpAddr, ok := ln.Addr().(*net.TCPAddr) if !ok { ln.Close() return nil, 0, fmt.Errorf("invalid listen address: %q", ln.Addr().String()) } return ln, tcpAddr.Port, nil }
cmd/kube-controller-manager/app/testing/testserver.go
1
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.9986039996147156, 0.16726666688919067, 0.00016981814405880868, 0.0005197729915380478, 0.37053269147872925 ]
{ "id": 3, "code_window": [ "\t\treturn result, fmt.Errorf(\"failed to create config from options: %v\", err)\n", "\t}\n", "\n", "\terrCh := make(chan error)\n", "\tgo func(stopCh <-chan struct{}) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\terrCh = make(chan error)\n" ], "file_path": "cmd/kube-controller-manager/app/testing/testserver.go", "type": "replace", "edit_start_line_idx": 107 }
/* Copyright 2015 The Kubernetes 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 helper import ( "reflect" "testing" "k8s.io/apimachinery/pkg/api/resource" "k8s.io/apimachinery/pkg/labels" "k8s.io/kubernetes/pkg/apis/core" ) func TestSemantic(t *testing.T) { table := []struct { a, b interface{} shouldEqual bool }{ {resource.MustParse("0"), resource.Quantity{}, true}, {resource.Quantity{}, resource.MustParse("0"), true}, {resource.Quantity{}, resource.MustParse("1m"), false}, { resource.NewQuantity(5, resource.BinarySI), resource.NewQuantity(5, resource.DecimalSI), true, }, {resource.MustParse("2m"), resource.MustParse("1m"), false}, } for index, item := range table { if e, a := item.shouldEqual, Semantic.DeepEqual(item.a, item.b); e != a { t.Errorf("case[%d], expected %v, got %v.", index, e, a) } } } func TestIsStandardResource(t *testing.T) { testCases := []struct { input string output bool }{ {"cpu", true}, {"memory", true}, {"disk", false}, {"blah", false}, {"x.y.z", false}, {"hugepages-2Mi", true}, {"requests.hugepages-2Mi", true}, } for i, tc := range testCases { if IsStandardResourceName(tc.input) != tc.output { t.Errorf("case[%d], input: %s, expected: %t, got: %t", i, tc.input, tc.output, !tc.output) } } } func TestIsStandardContainerResource(t *testing.T) { testCases := []struct { input string output bool }{ {"cpu", true}, {"memory", true}, {"disk", false}, {"hugepages-2Mi", true}, } for i, tc := range testCases { if IsStandardContainerResourceName(tc.input) != tc.output { t.Errorf("case[%d], input: %s, expected: %t, got: %t", i, tc.input, tc.output, !tc.output) } } } func TestGetAccessModesFromString(t *testing.T) { modes := GetAccessModesFromString("ROX") if !ContainsAccessMode(modes, core.ReadOnlyMany) { t.Errorf("Expected mode %s, but got %+v", core.ReadOnlyMany, modes) } modes = GetAccessModesFromString("ROX,RWX") if !ContainsAccessMode(modes, core.ReadOnlyMany) { t.Errorf("Expected mode %s, but got %+v", core.ReadOnlyMany, modes) } if !ContainsAccessMode(modes, core.ReadWriteMany) { t.Errorf("Expected mode %s, but got %+v", core.ReadWriteMany, modes) } modes = GetAccessModesFromString("RWO,ROX,RWX") if !ContainsAccessMode(modes, core.ReadWriteOnce) { t.Errorf("Expected mode %s, but got %+v", core.ReadWriteOnce, modes) } if !ContainsAccessMode(modes, core.ReadOnlyMany) { t.Errorf("Expected mode %s, but got %+v", core.ReadOnlyMany, modes) } if !ContainsAccessMode(modes, core.ReadWriteMany) { t.Errorf("Expected mode %s, but got %+v", core.ReadWriteMany, modes) } modes = GetAccessModesFromString("RWO,ROX,RWX,RWOP") if !ContainsAccessMode(modes, core.ReadWriteOnce) { t.Errorf("Expected mode %s, but got %+v", core.ReadWriteOnce, modes) } if !ContainsAccessMode(modes, core.ReadOnlyMany) { t.Errorf("Expected mode %s, but got %+v", core.ReadOnlyMany, modes) } if !ContainsAccessMode(modes, core.ReadWriteMany) { t.Errorf("Expected mode %s, but got %+v", core.ReadWriteMany, modes) } if !ContainsAccessMode(modes, core.ReadWriteOncePod) { t.Errorf("Expected mode %s, but got %+v", core.ReadWriteOncePod, modes) } } func TestRemoveDuplicateAccessModes(t *testing.T) { modes := []core.PersistentVolumeAccessMode{ core.ReadWriteOnce, core.ReadOnlyMany, core.ReadOnlyMany, core.ReadOnlyMany, } modes = removeDuplicateAccessModes(modes) if len(modes) != 2 { t.Errorf("Expected 2 distinct modes in set but found %v", len(modes)) } } func TestNodeSelectorRequirementsAsSelector(t *testing.T) { matchExpressions := []core.NodeSelectorRequirement{{ Key: "foo", Operator: core.NodeSelectorOpIn, Values: []string{"bar", "baz"}, }} mustParse := func(s string) labels.Selector { out, e := labels.Parse(s) if e != nil { panic(e) } return out } tc := []struct { in []core.NodeSelectorRequirement out labels.Selector expectErr bool }{ {in: nil, out: labels.Nothing()}, {in: []core.NodeSelectorRequirement{}, out: labels.Nothing()}, { in: matchExpressions, out: mustParse("foo in (baz,bar)"), }, { in: []core.NodeSelectorRequirement{{ Key: "foo", Operator: core.NodeSelectorOpExists, Values: []string{"bar", "baz"}, }}, expectErr: true, }, { in: []core.NodeSelectorRequirement{{ Key: "foo", Operator: core.NodeSelectorOpGt, Values: []string{"1"}, }}, out: mustParse("foo>1"), }, { in: []core.NodeSelectorRequirement{{ Key: "bar", Operator: core.NodeSelectorOpLt, Values: []string{"7"}, }}, out: mustParse("bar<7"), }, } for i, tc := range tc { out, err := NodeSelectorRequirementsAsSelector(tc.in) if err == nil && tc.expectErr { t.Errorf("[%v]expected error but got none.", i) } if err != nil && !tc.expectErr { t.Errorf("[%v]did not expect error but got: %v", i, err) } if !reflect.DeepEqual(out, tc.out) { t.Errorf("[%v]expected:\n\t%+v\nbut got:\n\t%+v", i, tc.out, out) } } } func TestIsHugePageResourceName(t *testing.T) { testCases := []struct { name core.ResourceName result bool }{ { name: core.ResourceName("hugepages-2Mi"), result: true, }, { name: core.ResourceName("hugepages-1Gi"), result: true, }, { name: core.ResourceName("cpu"), result: false, }, { name: core.ResourceName("memory"), result: false, }, } for _, testCase := range testCases { if testCase.result != IsHugePageResourceName(testCase.name) { t.Errorf("resource: %v expected result: %v", testCase.name, testCase.result) } } } func TestIsHugePageResourceValueDivisible(t *testing.T) { testCases := []struct { name core.ResourceName quantity resource.Quantity result bool }{ { name: core.ResourceName("hugepages-2Mi"), quantity: resource.MustParse("4Mi"), result: true, }, { name: core.ResourceName("hugepages-2Mi"), quantity: resource.MustParse("5Mi"), result: false, }, { name: core.ResourceName("hugepages-1Gi"), quantity: resource.MustParse("2Gi"), result: true, }, { name: core.ResourceName("hugepages-1Gi"), quantity: resource.MustParse("2.1Gi"), result: false, }, { name: core.ResourceName("hugepages-1Mi"), quantity: resource.MustParse("2.1Mi"), result: false, }, { name: core.ResourceName("hugepages-64Ki"), quantity: resource.MustParse("128Ki"), result: true, }, { name: core.ResourceName("hugepages-"), quantity: resource.MustParse("128Ki"), result: false, }, { name: core.ResourceName("hugepages"), quantity: resource.MustParse("128Ki"), result: false, }, } for _, testCase := range testCases { if testCase.result != IsHugePageResourceValueDivisible(testCase.name, testCase.quantity) { t.Errorf("resource: %v storage:%v expected result: %v", testCase.name, testCase.quantity, testCase.result) } } } func TestHugePageResourceName(t *testing.T) { testCases := []struct { pageSize resource.Quantity name core.ResourceName }{ { pageSize: resource.MustParse("2Mi"), name: core.ResourceName("hugepages-2Mi"), }, { pageSize: resource.MustParse("1Gi"), name: core.ResourceName("hugepages-1Gi"), }, { // verify we do not regress our canonical representation pageSize: *resource.NewQuantity(int64(2097152), resource.BinarySI), name: core.ResourceName("hugepages-2Mi"), }, } for _, testCase := range testCases { if result := HugePageResourceName(testCase.pageSize); result != testCase.name { t.Errorf("pageSize: %v, expected: %v, but got: %v", testCase.pageSize.String(), testCase.name, result.String()) } } } func TestHugePageSizeFromResourceName(t *testing.T) { testCases := []struct { name core.ResourceName expectErr bool pageSize resource.Quantity }{ { name: core.ResourceName("hugepages-2Mi"), pageSize: resource.MustParse("2Mi"), expectErr: false, }, { name: core.ResourceName("hugepages-1Gi"), pageSize: resource.MustParse("1Gi"), expectErr: false, }, { name: core.ResourceName("hugepages-bad"), expectErr: true, }, } for _, testCase := range testCases { value, err := HugePageSizeFromResourceName(testCase.name) if testCase.expectErr && err == nil { t.Errorf("Expected an error for %v", testCase.name) } else if !testCase.expectErr && err != nil { t.Errorf("Unexpected error for %v, got %v", testCase.name, err) } else if testCase.pageSize.Value() != value.Value() { t.Errorf("Unexpected pageSize for resource %v got %v", testCase.name, value.String()) } } } func TestIsOvercommitAllowed(t *testing.T) { testCases := []struct { name core.ResourceName allowed bool }{ { name: core.ResourceCPU, allowed: true, }, { name: core.ResourceMemory, allowed: true, }, { name: HugePageResourceName(resource.MustParse("2Mi")), allowed: false, }, } for _, testCase := range testCases { if testCase.allowed != IsOvercommitAllowed(testCase.name) { t.Errorf("Unexpected result for %v", testCase.name) } } } func TestIsServiceIPSet(t *testing.T) { testCases := []struct { input core.ServiceSpec output bool name string }{ { name: "nil cluster ip", input: core.ServiceSpec{ ClusterIPs: nil, }, output: false, }, { name: "headless service", input: core.ServiceSpec{ ClusterIP: "None", ClusterIPs: []string{"None"}, }, output: false, }, // true cases { name: "one ipv4", input: core.ServiceSpec{ ClusterIP: "1.2.3.4", ClusterIPs: []string{"1.2.3.4"}, }, output: true, }, { name: "one ipv6", input: core.ServiceSpec{ ClusterIP: "2001::1", ClusterIPs: []string{"2001::1"}, }, output: true, }, { name: "v4, v6", input: core.ServiceSpec{ ClusterIP: "1.2.3.4", ClusterIPs: []string{"1.2.3.4", "2001::1"}, }, output: true, }, { name: "v6, v4", input: core.ServiceSpec{ ClusterIP: "2001::1", ClusterIPs: []string{"2001::1", "1.2.3.4"}, }, output: true, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { s := core.Service{ Spec: tc.input, } if IsServiceIPSet(&s) != tc.output { t.Errorf("case, input: %v, expected: %v, got: %v", tc.input, tc.output, !tc.output) } }) } }
pkg/apis/core/helper/helpers_test.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.001208991277962923, 0.00019989591964986175, 0.00016341856098733842, 0.0001712079392746091, 0.00015604296640958637 ]
{ "id": 3, "code_window": [ "\t\treturn result, fmt.Errorf(\"failed to create config from options: %v\", err)\n", "\t}\n", "\n", "\terrCh := make(chan error)\n", "\tgo func(stopCh <-chan struct{}) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\terrCh = make(chan error)\n" ], "file_path": "cmd/kube-controller-manager/app/testing/testserver.go", "type": "replace", "edit_start_line_idx": 107 }
// Copyright 2015 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. package websocket import ( "crypto/tls" "net" ) func dialWithDialer(dialer *net.Dialer, config *Config) (conn net.Conn, err error) { switch config.Location.Scheme { case "ws": conn, err = dialer.Dial("tcp", parseAuthority(config.Location)) case "wss": conn, err = tls.DialWithDialer(dialer, "tcp", parseAuthority(config.Location), config.TlsConfig) default: err = ErrBadScheme } return }
vendor/golang.org/x/net/websocket/dial.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.004614806268364191, 0.0020950764883309603, 0.00017958121316041797, 0.0014908419689163566, 0.0018603996140882373 ]
{ "id": 3, "code_window": [ "\t\treturn result, fmt.Errorf(\"failed to create config from options: %v\", err)\n", "\t}\n", "\n", "\terrCh := make(chan error)\n", "\tgo func(stopCh <-chan struct{}) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\terrCh = make(chan error)\n" ], "file_path": "cmd/kube-controller-manager/app/testing/testserver.go", "type": "replace", "edit_start_line_idx": 107 }
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* * This test checks that various VolumeSources are working. * * There are two ways, how to test the volumes: * 1) With containerized server (NFS, Ceph, Gluster, iSCSI, ...) * The test creates a server pod, exporting simple 'index.html' file. * Then it uses appropriate VolumeSource to import this file into a client pod * and checks that the pod can see the file. It does so by importing the file * into web server root and loading the index.html from it. * * These tests work only when privileged containers are allowed, exporting * various filesystems (NFS, GlusterFS, ...) usually needs some mounting or * other privileged magic in the server pod. * * Note that the server containers are for testing purposes only and should not * be used in production. * * 2) With server outside of Kubernetes (Cinder, ...) * Appropriate server (e.g. OpenStack Cinder) must exist somewhere outside * the tested Kubernetes cluster. The test itself creates a new volume, * and checks, that Kubernetes can use it as a volume. */ // GlusterFS test is duplicated from test/e2e/volumes.go. Any changes made there // should be duplicated here package storage import ( "context" v1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" clientset "k8s.io/client-go/kubernetes" "k8s.io/kubernetes/test/e2e/framework" e2eskipper "k8s.io/kubernetes/test/e2e/framework/skipper" e2evolume "k8s.io/kubernetes/test/e2e/framework/volume" admissionapi "k8s.io/pod-security-admission/api" "github.com/onsi/ginkgo/v2" ) // TODO(#99468): Check if these tests are still needed. var _ = SIGDescribe("Volumes", func() { f := framework.NewDefaultFramework("volume") f.NamespacePodSecurityEnforceLevel = admissionapi.LevelPrivileged // note that namespace deletion is handled by delete-namespace flag // filled in BeforeEach var namespace *v1.Namespace var c clientset.Interface ginkgo.BeforeEach(func() { e2eskipper.SkipUnlessNodeOSDistroIs("gci", "ubuntu", "custom") namespace = f.Namespace c = f.ClientSet }) //////////////////////////////////////////////////////////////////////// // NFS //////////////////////////////////////////////////////////////////////// ginkgo.Describe("NFSv4", func() { ginkgo.It("should be mountable for NFSv4", func() { config, _, serverHost := e2evolume.NewNFSServer(c, namespace.Name, []string{}) defer e2evolume.TestServerCleanup(f, config) tests := []e2evolume.Test{ { Volume: v1.VolumeSource{ NFS: &v1.NFSVolumeSource{ Server: serverHost, Path: "/", ReadOnly: true, }, }, File: "index.html", ExpectedContent: "Hello from NFS!", }, } // Must match content of test/images/volumes-tester/nfs/index.html e2evolume.TestVolumeClient(f, config, nil, "" /* fsType */, tests) }) }) ginkgo.Describe("NFSv3", func() { ginkgo.It("should be mountable for NFSv3", func() { config, _, serverHost := e2evolume.NewNFSServer(c, namespace.Name, []string{}) defer e2evolume.TestServerCleanup(f, config) tests := []e2evolume.Test{ { Volume: v1.VolumeSource{ NFS: &v1.NFSVolumeSource{ Server: serverHost, Path: "/exports", ReadOnly: true, }, }, File: "index.html", ExpectedContent: "Hello from NFS!", }, } // Must match content of test/images/volume-tester/nfs/index.html e2evolume.TestVolumeClient(f, config, nil, "" /* fsType */, tests) }) }) //////////////////////////////////////////////////////////////////////// // Gluster //////////////////////////////////////////////////////////////////////// ginkgo.Describe("GlusterFS", func() { ginkgo.It("should be mountable", func() { // create gluster server and endpoints config, _, _ := e2evolume.NewGlusterfsServer(c, namespace.Name) name := config.Prefix + "-server" defer func() { e2evolume.TestServerCleanup(f, config) err := c.CoreV1().Endpoints(namespace.Name).Delete(context.TODO(), name, metav1.DeleteOptions{}) if !apierrors.IsNotFound(err) { framework.ExpectNoError(err, "defer: Gluster delete endpoints failed") } }() tests := []e2evolume.Test{ { Volume: v1.VolumeSource{ Glusterfs: &v1.GlusterfsVolumeSource{ EndpointsName: name, // 'test_vol' comes from test/images/volumes-tester/gluster/run_gluster.sh Path: "test_vol", ReadOnly: true, }, }, File: "index.html", // Must match content of test/images/volumes-tester/gluster/index.html ExpectedContent: "Hello from GlusterFS!", }, } e2evolume.TestVolumeClient(f, config, nil, "" /* fsType */, tests) }) }) })
test/e2e/common/storage/volumes.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.0009313018526881933, 0.00023290520766749978, 0.00016336965200025588, 0.00017111864872276783, 0.000185743163456209 ]
{ "id": 4, "code_window": [ "\tgo func(stopCh <-chan struct{}) {\n", "\t\tif err := app.Run(config.Complete(), stopCh); err != nil {\n", "\t\t\terrCh <- err\n", "\t\t}\n", "\t}(stopCh)\n", "\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tdefer close(errCh)\n", "\n" ], "file_path": "cmd/kube-controller-manager/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 109 }
/* Copyright 2018 The Kubernetes 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 testing import ( "context" "fmt" "net" "os" "time" "github.com/spf13/pflag" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes" restclient "k8s.io/client-go/rest" "k8s.io/kubernetes/cmd/kube-controller-manager/app" kubecontrollerconfig "k8s.io/kubernetes/cmd/kube-controller-manager/app/config" "k8s.io/kubernetes/cmd/kube-controller-manager/app/options" ) // TearDownFunc is to be called to tear down a test server. type TearDownFunc func() // TestServer return values supplied by kube-test-ApiServer type TestServer struct { LoopbackClientConfig *restclient.Config // Rest client config using the magic token Options *options.KubeControllerManagerOptions Config *kubecontrollerconfig.Config TearDownFn TearDownFunc // TearDown function TmpDir string // Temp Dir used, by the apiserver } // Logger allows t.Testing and b.Testing to be passed to StartTestServer and StartTestServerOrDie type Logger interface { Errorf(format string, args ...interface{}) Fatalf(format string, args ...interface{}) Logf(format string, args ...interface{}) } // StartTestServer starts a kube-controller-manager. A rest client config and a tear-down func, // and location of the tmpdir are returned. // // Note: we return a tear-down func instead of a stop channel because the later will leak temporary // files that because Golang testing's call to os.Exit will not give a stop channel go routine // enough time to remove temporary files. func StartTestServer(t Logger, customFlags []string) (result TestServer, err error) { stopCh := make(chan struct{}) tearDown := func() { close(stopCh) if len(result.TmpDir) != 0 { os.RemoveAll(result.TmpDir) } } defer func() { if result.TearDownFn == nil { tearDown() } }() result.TmpDir, err = os.MkdirTemp("", "kube-controller-manager") if err != nil { return result, fmt.Errorf("failed to create temp dir: %v", err) } fs := pflag.NewFlagSet("test", pflag.PanicOnError) s, err := options.NewKubeControllerManagerOptions() if err != nil { return TestServer{}, err } all, disabled := app.KnownControllers(), app.ControllersDisabledByDefault.List() namedFlagSets := s.Flags(all, disabled) for _, f := range namedFlagSets.FlagSets { fs.AddFlagSet(f) } fs.Parse(customFlags) if s.SecureServing.BindPort != 0 { s.SecureServing.Listener, s.SecureServing.BindPort, err = createListenerOnFreePort() if err != nil { return result, fmt.Errorf("failed to create listener: %v", err) } s.SecureServing.ServerCert.CertDirectory = result.TmpDir t.Logf("kube-controller-manager will listen securely on port %d...", s.SecureServing.BindPort) } config, err := s.Config(all, disabled) if err != nil { return result, fmt.Errorf("failed to create config from options: %v", err) } errCh := make(chan error) go func(stopCh <-chan struct{}) { if err := app.Run(config.Complete(), stopCh); err != nil { errCh <- err } }(stopCh) t.Logf("Waiting for /healthz to be ok...") client, err := kubernetes.NewForConfig(config.LoopbackClientConfig) if err != nil { return result, fmt.Errorf("failed to create a client: %v", err) } err = wait.Poll(100*time.Millisecond, 30*time.Second, func() (bool, error) { select { case err := <-errCh: return false, err default: } result := client.CoreV1().RESTClient().Get().AbsPath("/healthz").Do(context.TODO()) status := 0 result.StatusCode(&status) if status == 200 { return true, nil } return false, nil }) if err != nil { return result, fmt.Errorf("failed to wait for /healthz to return ok: %v", err) } // from here the caller must call tearDown result.LoopbackClientConfig = config.LoopbackClientConfig result.Options = s result.Config = config result.TearDownFn = tearDown return result, nil } // StartTestServerOrDie calls StartTestServer t.Fatal if it does not succeed. func StartTestServerOrDie(t Logger, flags []string) *TestServer { result, err := StartTestServer(t, flags) if err == nil { return &result } t.Fatalf("failed to launch server: %v", err) return nil } func createListenerOnFreePort() (net.Listener, int, error) { ln, err := net.Listen("tcp", ":0") if err != nil { return nil, 0, err } // get port tcpAddr, ok := ln.Addr().(*net.TCPAddr) if !ok { ln.Close() return nil, 0, fmt.Errorf("invalid listen address: %q", ln.Addr().String()) } return ln, tcpAddr.Port, nil }
cmd/kube-controller-manager/app/testing/testserver.go
1
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.9964162111282349, 0.18404226005077362, 0.00016591975872870535, 0.00022853660630062222, 0.3488977551460266 ]
{ "id": 4, "code_window": [ "\tgo func(stopCh <-chan struct{}) {\n", "\t\tif err := app.Run(config.Complete(), stopCh); err != nil {\n", "\t\t\terrCh <- err\n", "\t\t}\n", "\t}(stopCh)\n", "\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tdefer close(errCh)\n", "\n" ], "file_path": "cmd/kube-controller-manager/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 109 }
/* Copyright 2019 The Kubernetes 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 dns import ( "fmt" "os" "strings" "github.com/spf13/cobra" ) // CmdDNSSuffix is used by agnhost Cobra. var CmdDNSSuffix = &cobra.Command{ Use: "dns-suffix", Short: "Prints the host's DNS suffix list", Long: `Prints the DNS suffixes of this host.`, Args: cobra.MaximumNArgs(0), Run: printDNSSuffixList, } // CmdDNSServerList is used by agnhost Cobra. var CmdDNSServerList = &cobra.Command{ Use: "dns-server-list", Short: "Prints the host's DNS Server list", Long: `Prints the DNS Server list of this host.`, Args: cobra.MaximumNArgs(0), Run: printDNSServerList, } // CmdEtcHosts is used by agnhost Cobra. var CmdEtcHosts = &cobra.Command{ Use: "etc-hosts", Short: "Prints the host's /etc/hosts file", Long: `Prints the "hosts" file of this host."`, Args: cobra.MaximumNArgs(0), Run: printHostsFile, } func printDNSSuffixList(cmd *cobra.Command, args []string) { dnsSuffixList := GetDNSSuffixList() fmt.Println(strings.Join(dnsSuffixList, ",")) } func printDNSServerList(cmd *cobra.Command, args []string) { dnsServerList := getDNSServerList() fmt.Println(strings.Join(dnsServerList, ",")) } func printHostsFile(cmd *cobra.Command, args []string) { fmt.Println(readFile(etcHostsFile)) } func readFile(fileName string) string { fileData, err := os.ReadFile(fileName) if err != nil { panic(err) } return string(fileData) }
test/images/agnhost/dns/common.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.0002852787438314408, 0.00019088288536295295, 0.0001655534579185769, 0.00017750708502717316, 0.000037726800655946136 ]
{ "id": 4, "code_window": [ "\tgo func(stopCh <-chan struct{}) {\n", "\t\tif err := app.Run(config.Complete(), stopCh); err != nil {\n", "\t\t\terrCh <- err\n", "\t\t}\n", "\t}(stopCh)\n", "\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tdefer close(errCh)\n", "\n" ], "file_path": "cmd/kube-controller-manager/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 109 }
/* Copyright The Kubernetes 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. */ // Code generated by client-gen. DO NOT EDIT. package fake import ( "context" json "encoding/json" "fmt" corev1 "k8s.io/api/core/v1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" schema "k8s.io/apimachinery/pkg/runtime/schema" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" applyconfigurationscorev1 "k8s.io/client-go/applyconfigurations/core/v1" testing "k8s.io/client-go/testing" ) // FakePersistentVolumeClaims implements PersistentVolumeClaimInterface type FakePersistentVolumeClaims struct { Fake *FakeCoreV1 ns string } var persistentvolumeclaimsResource = schema.GroupVersionResource{Group: "", Version: "v1", Resource: "persistentvolumeclaims"} var persistentvolumeclaimsKind = schema.GroupVersionKind{Group: "", Version: "v1", Kind: "PersistentVolumeClaim"} // Get takes name of the persistentVolumeClaim, and returns the corresponding persistentVolumeClaim object, and an error if there is any. func (c *FakePersistentVolumeClaims) Get(ctx context.Context, name string, options v1.GetOptions) (result *corev1.PersistentVolumeClaim, err error) { obj, err := c.Fake. Invokes(testing.NewGetAction(persistentvolumeclaimsResource, c.ns, name), &corev1.PersistentVolumeClaim{}) if obj == nil { return nil, err } return obj.(*corev1.PersistentVolumeClaim), err } // List takes label and field selectors, and returns the list of PersistentVolumeClaims that match those selectors. func (c *FakePersistentVolumeClaims) List(ctx context.Context, opts v1.ListOptions) (result *corev1.PersistentVolumeClaimList, err error) { obj, err := c.Fake. Invokes(testing.NewListAction(persistentvolumeclaimsResource, persistentvolumeclaimsKind, c.ns, opts), &corev1.PersistentVolumeClaimList{}) if obj == nil { return nil, err } label, _, _ := testing.ExtractFromListOptions(opts) if label == nil { label = labels.Everything() } list := &corev1.PersistentVolumeClaimList{ListMeta: obj.(*corev1.PersistentVolumeClaimList).ListMeta} for _, item := range obj.(*corev1.PersistentVolumeClaimList).Items { if label.Matches(labels.Set(item.Labels)) { list.Items = append(list.Items, item) } } return list, err } // Watch returns a watch.Interface that watches the requested persistentVolumeClaims. func (c *FakePersistentVolumeClaims) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { return c.Fake. InvokesWatch(testing.NewWatchAction(persistentvolumeclaimsResource, c.ns, opts)) } // Create takes the representation of a persistentVolumeClaim and creates it. Returns the server's representation of the persistentVolumeClaim, and an error, if there is any. func (c *FakePersistentVolumeClaims) Create(ctx context.Context, persistentVolumeClaim *corev1.PersistentVolumeClaim, opts v1.CreateOptions) (result *corev1.PersistentVolumeClaim, err error) { obj, err := c.Fake. Invokes(testing.NewCreateAction(persistentvolumeclaimsResource, c.ns, persistentVolumeClaim), &corev1.PersistentVolumeClaim{}) if obj == nil { return nil, err } return obj.(*corev1.PersistentVolumeClaim), err } // Update takes the representation of a persistentVolumeClaim and updates it. Returns the server's representation of the persistentVolumeClaim, and an error, if there is any. func (c *FakePersistentVolumeClaims) Update(ctx context.Context, persistentVolumeClaim *corev1.PersistentVolumeClaim, opts v1.UpdateOptions) (result *corev1.PersistentVolumeClaim, err error) { obj, err := c.Fake. Invokes(testing.NewUpdateAction(persistentvolumeclaimsResource, c.ns, persistentVolumeClaim), &corev1.PersistentVolumeClaim{}) if obj == nil { return nil, err } return obj.(*corev1.PersistentVolumeClaim), err } // UpdateStatus was generated because the type contains a Status member. // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). func (c *FakePersistentVolumeClaims) UpdateStatus(ctx context.Context, persistentVolumeClaim *corev1.PersistentVolumeClaim, opts v1.UpdateOptions) (*corev1.PersistentVolumeClaim, error) { obj, err := c.Fake. Invokes(testing.NewUpdateSubresourceAction(persistentvolumeclaimsResource, "status", c.ns, persistentVolumeClaim), &corev1.PersistentVolumeClaim{}) if obj == nil { return nil, err } return obj.(*corev1.PersistentVolumeClaim), err } // Delete takes name of the persistentVolumeClaim and deletes it. Returns an error if one occurs. func (c *FakePersistentVolumeClaims) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { _, err := c.Fake. Invokes(testing.NewDeleteActionWithOptions(persistentvolumeclaimsResource, c.ns, name, opts), &corev1.PersistentVolumeClaim{}) return err } // DeleteCollection deletes a collection of objects. func (c *FakePersistentVolumeClaims) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { action := testing.NewDeleteCollectionAction(persistentvolumeclaimsResource, c.ns, listOpts) _, err := c.Fake.Invokes(action, &corev1.PersistentVolumeClaimList{}) return err } // Patch applies the patch and returns the patched persistentVolumeClaim. func (c *FakePersistentVolumeClaims) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *corev1.PersistentVolumeClaim, err error) { obj, err := c.Fake. Invokes(testing.NewPatchSubresourceAction(persistentvolumeclaimsResource, c.ns, name, pt, data, subresources...), &corev1.PersistentVolumeClaim{}) if obj == nil { return nil, err } return obj.(*corev1.PersistentVolumeClaim), err } // Apply takes the given apply declarative configuration, applies it and returns the applied persistentVolumeClaim. func (c *FakePersistentVolumeClaims) Apply(ctx context.Context, persistentVolumeClaim *applyconfigurationscorev1.PersistentVolumeClaimApplyConfiguration, opts v1.ApplyOptions) (result *corev1.PersistentVolumeClaim, err error) { if persistentVolumeClaim == nil { return nil, fmt.Errorf("persistentVolumeClaim provided to Apply must not be nil") } data, err := json.Marshal(persistentVolumeClaim) if err != nil { return nil, err } name := persistentVolumeClaim.Name if name == nil { return nil, fmt.Errorf("persistentVolumeClaim.Name must be provided to Apply") } obj, err := c.Fake. Invokes(testing.NewPatchSubresourceAction(persistentvolumeclaimsResource, c.ns, *name, types.ApplyPatchType, data), &corev1.PersistentVolumeClaim{}) if obj == nil { return nil, err } return obj.(*corev1.PersistentVolumeClaim), err } // ApplyStatus was generated because the type contains a Status member. // Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus(). func (c *FakePersistentVolumeClaims) ApplyStatus(ctx context.Context, persistentVolumeClaim *applyconfigurationscorev1.PersistentVolumeClaimApplyConfiguration, opts v1.ApplyOptions) (result *corev1.PersistentVolumeClaim, err error) { if persistentVolumeClaim == nil { return nil, fmt.Errorf("persistentVolumeClaim provided to Apply must not be nil") } data, err := json.Marshal(persistentVolumeClaim) if err != nil { return nil, err } name := persistentVolumeClaim.Name if name == nil { return nil, fmt.Errorf("persistentVolumeClaim.Name must be provided to Apply") } obj, err := c.Fake. Invokes(testing.NewPatchSubresourceAction(persistentvolumeclaimsResource, c.ns, *name, types.ApplyPatchType, data, "status"), &corev1.PersistentVolumeClaim{}) if obj == nil { return nil, err } return obj.(*corev1.PersistentVolumeClaim), err }
staging/src/k8s.io/client-go/kubernetes/typed/core/v1/fake/fake_persistentvolumeclaim.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.0003243189712520689, 0.0001892224099719897, 0.00016617625078652054, 0.00016970900469459593, 0.00004628362876246683 ]
{ "id": 4, "code_window": [ "\tgo func(stopCh <-chan struct{}) {\n", "\t\tif err := app.Run(config.Complete(), stopCh); err != nil {\n", "\t\t\terrCh <- err\n", "\t\t}\n", "\t}(stopCh)\n", "\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tdefer close(errCh)\n", "\n" ], "file_path": "cmd/kube-controller-manager/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 109 }
apiVersion: v1 kind: Pod metadata: name: selinuxoptions1 spec: containers: - image: k8s.gcr.io/pause name: container1 securityContext: allowPrivilegeEscalation: false seLinuxOptions: type: somevalue initContainers: - image: k8s.gcr.io/pause name: initcontainer1 securityContext: allowPrivilegeEscalation: false seLinuxOptions: {} securityContext: runAsNonRoot: true seLinuxOptions: {} seccompProfile: type: RuntimeDefault
staging/src/k8s.io/pod-security-admission/test/testdata/restricted/v1.19/fail/selinuxoptions1.yaml
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.000174393760971725, 0.00017214508261531591, 0.00016940639761742204, 0.0001726350892568007, 0.0000020653535557357827 ]
{ "id": 5, "code_window": [ "\t\"k8s.io/cloud-provider/app\"\n", "\t\"k8s.io/cloud-provider/app/config\"\n", "\t\"k8s.io/cloud-provider/options\"\n", "\tcliflag \"k8s.io/component-base/cli/flag\"\n", ")\n", "\n", "// TearDownFunc is to be called to tear down a test server.\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\"k8s.io/klog/v2\"\n" ], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 35 }
/* Copyright 2018 The Kubernetes 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 testing import ( "context" "fmt" "io/ioutil" "net" "os" "strings" "time" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes" restclient "k8s.io/client-go/rest" cloudprovider "k8s.io/cloud-provider" "k8s.io/cloud-provider/app" "k8s.io/cloud-provider/app/config" "k8s.io/cloud-provider/options" cliflag "k8s.io/component-base/cli/flag" ) // TearDownFunc is to be called to tear down a test server. type TearDownFunc func() // TestServer return values supplied by kube-test-ApiServer type TestServer struct { LoopbackClientConfig *restclient.Config // Rest client config using the magic token Options *options.CloudControllerManagerOptions Config *config.CompletedConfig TearDownFn TearDownFunc // TearDown function TmpDir string // Temp Dir used, by the apiserver } // Logger allows t.Testing and b.Testing to be passed to StartTestServer and StartTestServerOrDie type Logger interface { Errorf(format string, args ...interface{}) Fatalf(format string, args ...interface{}) Logf(format string, args ...interface{}) } // StartTestServer starts a cloud-controller-manager. A rest client config and a tear-down func, // and location of the tmpdir are returned. // // Note: we return a tear-down func instead of a stop channel because the later will leak temporary // files that because Golang testing's call to os.Exit will not give a stop channel go routine // enough time to remove temporary files. func StartTestServer(t Logger, customFlags []string) (result TestServer, err error) { stopCh := make(chan struct{}) configDoneCh := make(chan struct{}) var capturedConfig config.CompletedConfig tearDown := func() { close(stopCh) if len(result.TmpDir) != 0 { os.RemoveAll(result.TmpDir) } } defer func() { if result.TearDownFn == nil { tearDown() } }() result.TmpDir, err = ioutil.TempDir("", "cloud-controller-manager") if err != nil { return result, fmt.Errorf("failed to create temp dir: %v", err) } s, err := options.NewCloudControllerManagerOptions() if err != nil { return TestServer{}, err } cloudInitializer := func(config *config.CompletedConfig) cloudprovider.Interface { capturedConfig = *config // send signal to indicate the capturedConfig has been properly set close(configDoneCh) cloudConfig := config.ComponentConfig.KubeCloudShared.CloudProvider cloud, err := cloudprovider.InitCloudProvider(cloudConfig.Name, cloudConfig.CloudConfigFile) if err != nil { t.Fatalf("Cloud provider could not be initialized: %v", err) } s.SecureServing.ServerCert.CertDirectory = result.TmpDir if cloud == nil { t.Fatalf("Cloud provider is nil") } return cloud } fss := cliflag.NamedFlagSets{} command := app.NewCloudControllerManagerCommand(s, cloudInitializer, app.DefaultInitFuncConstructors, fss, stopCh) commandArgs := []string{} listeners := []net.Listener{} disableSecure := false for _, arg := range customFlags { if strings.HasPrefix(arg, "--secure-port=") { if arg == "--secure-port=0" { commandArgs = append(commandArgs, arg) disableSecure = true } } else if strings.HasPrefix(arg, "--cert-dir=") { // skip it } else { commandArgs = append(commandArgs, arg) } } if !disableSecure { listener, bindPort, err := createListenerOnFreePort() if err != nil { return result, fmt.Errorf("failed to create listener: %v", err) } listeners = append(listeners, listener) commandArgs = append(commandArgs, fmt.Sprintf("--secure-port=%d", bindPort)) commandArgs = append(commandArgs, fmt.Sprintf("--cert-dir=%s", result.TmpDir)) t.Logf("cloud-controller-manager will listen securely on port %d...", bindPort) } for _, listener := range listeners { listener.Close() } errCh := make(chan error) go func() { command.SetArgs(commandArgs) if err := command.Execute(); err != nil { errCh <- err } close(errCh) }() select { case <-configDoneCh: case err := <-errCh: return result, err } t.Logf("Waiting for /healthz to be ok...") client, err := kubernetes.NewForConfig(capturedConfig.LoopbackClientConfig) if err != nil { return result, fmt.Errorf("failed to create a client: %v", err) } err = wait.Poll(100*time.Millisecond, 30*time.Second, func() (bool, error) { select { case err := <-errCh: return false, err default: } result := client.CoreV1().RESTClient().Get().AbsPath("/healthz").Do(context.TODO()) status := 0 result.StatusCode(&status) if status == 200 { return true, nil } return false, nil }) if err != nil { return result, fmt.Errorf("failed to wait for /healthz to return ok: %v", err) } // from here the caller must call tearDown result.LoopbackClientConfig = capturedConfig.LoopbackClientConfig result.Options = s result.Config = &capturedConfig result.TearDownFn = tearDown return result, nil } // StartTestServerOrDie calls StartTestServer t.Fatal if it does not succeed. func StartTestServerOrDie(t Logger, flags []string) *TestServer { result, err := StartTestServer(t, flags) if err == nil { return &result } t.Fatalf("failed to launch server: %v", err) return nil } func createListenerOnFreePort() (net.Listener, int, error) { ln, err := net.Listen("tcp", ":0") if err != nil { return nil, 0, err } // get port tcpAddr, ok := ln.Addr().(*net.TCPAddr) if !ok { ln.Close() return nil, 0, fmt.Errorf("invalid listen address: %q", ln.Addr().String()) } return ln, tcpAddr.Port, nil }
staging/src/k8s.io/cloud-provider/app/testing/testserver.go
1
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.971919059753418, 0.048257216811180115, 0.000166228404850699, 0.00017684687918517739, 0.2017575353384018 ]
{ "id": 5, "code_window": [ "\t\"k8s.io/cloud-provider/app\"\n", "\t\"k8s.io/cloud-provider/app/config\"\n", "\t\"k8s.io/cloud-provider/options\"\n", "\tcliflag \"k8s.io/component-base/cli/flag\"\n", ")\n", "\n", "// TearDownFunc is to be called to tear down a test server.\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\"k8s.io/klog/v2\"\n" ], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 35 }
/* Copyright The Kubernetes 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. */ // Code generated by client-gen. DO NOT EDIT. package v1 import ( "context" json "encoding/json" "fmt" "time" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" corev1 "k8s.io/client-go/applyconfigurations/core/v1" scheme "k8s.io/client-go/kubernetes/scheme" rest "k8s.io/client-go/rest" ) // ComponentStatusesGetter has a method to return a ComponentStatusInterface. // A group's client should implement this interface. type ComponentStatusesGetter interface { ComponentStatuses() ComponentStatusInterface } // ComponentStatusInterface has methods to work with ComponentStatus resources. type ComponentStatusInterface interface { Create(ctx context.Context, componentStatus *v1.ComponentStatus, opts metav1.CreateOptions) (*v1.ComponentStatus, error) Update(ctx context.Context, componentStatus *v1.ComponentStatus, opts metav1.UpdateOptions) (*v1.ComponentStatus, error) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.ComponentStatus, error) List(ctx context.Context, opts metav1.ListOptions) (*v1.ComponentStatusList, error) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ComponentStatus, err error) Apply(ctx context.Context, componentStatus *corev1.ComponentStatusApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ComponentStatus, err error) ComponentStatusExpansion } // componentStatuses implements ComponentStatusInterface type componentStatuses struct { client rest.Interface } // newComponentStatuses returns a ComponentStatuses func newComponentStatuses(c *CoreV1Client) *componentStatuses { return &componentStatuses{ client: c.RESTClient(), } } // Get takes name of the componentStatus, and returns the corresponding componentStatus object, and an error if there is any. func (c *componentStatuses) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ComponentStatus, err error) { result = &v1.ComponentStatus{} err = c.client.Get(). Resource("componentstatuses"). Name(name). VersionedParams(&options, scheme.ParameterCodec). Do(ctx). Into(result) return } // List takes label and field selectors, and returns the list of ComponentStatuses that match those selectors. func (c *componentStatuses) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ComponentStatusList, err error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } result = &v1.ComponentStatusList{} err = c.client.Get(). Resource("componentstatuses"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Do(ctx). Into(result) return } // Watch returns a watch.Interface that watches the requested componentStatuses. func (c *componentStatuses) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } opts.Watch = true return c.client.Get(). Resource("componentstatuses"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Watch(ctx) } // Create takes the representation of a componentStatus and creates it. Returns the server's representation of the componentStatus, and an error, if there is any. func (c *componentStatuses) Create(ctx context.Context, componentStatus *v1.ComponentStatus, opts metav1.CreateOptions) (result *v1.ComponentStatus, err error) { result = &v1.ComponentStatus{} err = c.client.Post(). Resource("componentstatuses"). VersionedParams(&opts, scheme.ParameterCodec). Body(componentStatus). Do(ctx). Into(result) return } // Update takes the representation of a componentStatus and updates it. Returns the server's representation of the componentStatus, and an error, if there is any. func (c *componentStatuses) Update(ctx context.Context, componentStatus *v1.ComponentStatus, opts metav1.UpdateOptions) (result *v1.ComponentStatus, err error) { result = &v1.ComponentStatus{} err = c.client.Put(). Resource("componentstatuses"). Name(componentStatus.Name). VersionedParams(&opts, scheme.ParameterCodec). Body(componentStatus). Do(ctx). Into(result) return } // Delete takes name of the componentStatus and deletes it. Returns an error if one occurs. func (c *componentStatuses) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { return c.client.Delete(). Resource("componentstatuses"). Name(name). Body(&opts). Do(ctx). Error() } // DeleteCollection deletes a collection of objects. func (c *componentStatuses) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { var timeout time.Duration if listOpts.TimeoutSeconds != nil { timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second } return c.client.Delete(). Resource("componentstatuses"). VersionedParams(&listOpts, scheme.ParameterCodec). Timeout(timeout). Body(&opts). Do(ctx). Error() } // Patch applies the patch and returns the patched componentStatus. func (c *componentStatuses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ComponentStatus, err error) { result = &v1.ComponentStatus{} err = c.client.Patch(pt). Resource("componentstatuses"). Name(name). SubResource(subresources...). VersionedParams(&opts, scheme.ParameterCodec). Body(data). Do(ctx). Into(result) return } // Apply takes the given apply declarative configuration, applies it and returns the applied componentStatus. func (c *componentStatuses) Apply(ctx context.Context, componentStatus *corev1.ComponentStatusApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ComponentStatus, err error) { if componentStatus == nil { return nil, fmt.Errorf("componentStatus provided to Apply must not be nil") } patchOpts := opts.ToPatchOptions() data, err := json.Marshal(componentStatus) if err != nil { return nil, err } name := componentStatus.Name if name == nil { return nil, fmt.Errorf("componentStatus.Name must be provided to Apply") } result = &v1.ComponentStatus{} err = c.client.Patch(types.ApplyPatchType). Resource("componentstatuses"). Name(*name). VersionedParams(&patchOpts, scheme.ParameterCodec). Body(data). Do(ctx). Into(result) return }
staging/src/k8s.io/client-go/kubernetes/typed/core/v1/componentstatus.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.001427375478670001, 0.00030581530882045627, 0.0001672459184192121, 0.00023032586614135653, 0.00026724496274255216 ]
{ "id": 5, "code_window": [ "\t\"k8s.io/cloud-provider/app\"\n", "\t\"k8s.io/cloud-provider/app/config\"\n", "\t\"k8s.io/cloud-provider/options\"\n", "\tcliflag \"k8s.io/component-base/cli/flag\"\n", ")\n", "\n", "// TearDownFunc is to be called to tear down a test server.\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\"k8s.io/klog/v2\"\n" ], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 35 }
## Obsolete Config Files From Docs These config files were originally from docs, but have been separated and put here to be used by various tests.
test/fixtures/doc-yaml/README.md
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.0001616531953914091, 0.0001616531953914091, 0.0001616531953914091, 0.0001616531953914091, 0 ]
{ "id": 5, "code_window": [ "\t\"k8s.io/cloud-provider/app\"\n", "\t\"k8s.io/cloud-provider/app/config\"\n", "\t\"k8s.io/cloud-provider/options\"\n", "\tcliflag \"k8s.io/component-base/cli/flag\"\n", ")\n", "\n", "// TearDownFunc is to be called to tear down a test server.\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\"k8s.io/klog/v2\"\n" ], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 35 }
apiVersion: v1 kind: Pod metadata: name: selinuxoptions0 spec: containers: - image: k8s.gcr.io/pause name: container1 securityContext: {} initContainers: - image: k8s.gcr.io/pause name: initcontainer1 securityContext: seLinuxOptions: {} securityContext: {}
staging/src/k8s.io/pod-security-admission/test/testdata/baseline/v1.23/pass/selinuxoptions0.yaml
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.00016853732813615352, 0.0001658904948271811, 0.0001632436760701239, 0.0001658904948271811, 0.000002646826033014804 ]
{ "id": 6, "code_window": [ "// Note: we return a tear-down func instead of a stop channel because the later will leak temporary\n", "// \t\t files that because Golang testing's call to os.Exit will not give a stop channel go routine\n", "// \t\t enough time to remove temporary files.\n", "func StartTestServer(t Logger, customFlags []string) (result TestServer, err error) {\n", "\tstopCh := make(chan struct{})\n", "\tconfigDoneCh := make(chan struct{})\n", "\tvar capturedConfig config.CompletedConfig\n", "\ttearDown := func() {\n", "\t\tclose(stopCh)\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tvar errCh chan error\n" ], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 64 }
/* Copyright 2018 The Kubernetes 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 testing import ( "context" "fmt" "net" "os" "time" "github.com/spf13/pflag" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes" restclient "k8s.io/client-go/rest" "k8s.io/kubernetes/cmd/kube-controller-manager/app" kubecontrollerconfig "k8s.io/kubernetes/cmd/kube-controller-manager/app/config" "k8s.io/kubernetes/cmd/kube-controller-manager/app/options" ) // TearDownFunc is to be called to tear down a test server. type TearDownFunc func() // TestServer return values supplied by kube-test-ApiServer type TestServer struct { LoopbackClientConfig *restclient.Config // Rest client config using the magic token Options *options.KubeControllerManagerOptions Config *kubecontrollerconfig.Config TearDownFn TearDownFunc // TearDown function TmpDir string // Temp Dir used, by the apiserver } // Logger allows t.Testing and b.Testing to be passed to StartTestServer and StartTestServerOrDie type Logger interface { Errorf(format string, args ...interface{}) Fatalf(format string, args ...interface{}) Logf(format string, args ...interface{}) } // StartTestServer starts a kube-controller-manager. A rest client config and a tear-down func, // and location of the tmpdir are returned. // // Note: we return a tear-down func instead of a stop channel because the later will leak temporary // files that because Golang testing's call to os.Exit will not give a stop channel go routine // enough time to remove temporary files. func StartTestServer(t Logger, customFlags []string) (result TestServer, err error) { stopCh := make(chan struct{}) tearDown := func() { close(stopCh) if len(result.TmpDir) != 0 { os.RemoveAll(result.TmpDir) } } defer func() { if result.TearDownFn == nil { tearDown() } }() result.TmpDir, err = os.MkdirTemp("", "kube-controller-manager") if err != nil { return result, fmt.Errorf("failed to create temp dir: %v", err) } fs := pflag.NewFlagSet("test", pflag.PanicOnError) s, err := options.NewKubeControllerManagerOptions() if err != nil { return TestServer{}, err } all, disabled := app.KnownControllers(), app.ControllersDisabledByDefault.List() namedFlagSets := s.Flags(all, disabled) for _, f := range namedFlagSets.FlagSets { fs.AddFlagSet(f) } fs.Parse(customFlags) if s.SecureServing.BindPort != 0 { s.SecureServing.Listener, s.SecureServing.BindPort, err = createListenerOnFreePort() if err != nil { return result, fmt.Errorf("failed to create listener: %v", err) } s.SecureServing.ServerCert.CertDirectory = result.TmpDir t.Logf("kube-controller-manager will listen securely on port %d...", s.SecureServing.BindPort) } config, err := s.Config(all, disabled) if err != nil { return result, fmt.Errorf("failed to create config from options: %v", err) } errCh := make(chan error) go func(stopCh <-chan struct{}) { if err := app.Run(config.Complete(), stopCh); err != nil { errCh <- err } }(stopCh) t.Logf("Waiting for /healthz to be ok...") client, err := kubernetes.NewForConfig(config.LoopbackClientConfig) if err != nil { return result, fmt.Errorf("failed to create a client: %v", err) } err = wait.Poll(100*time.Millisecond, 30*time.Second, func() (bool, error) { select { case err := <-errCh: return false, err default: } result := client.CoreV1().RESTClient().Get().AbsPath("/healthz").Do(context.TODO()) status := 0 result.StatusCode(&status) if status == 200 { return true, nil } return false, nil }) if err != nil { return result, fmt.Errorf("failed to wait for /healthz to return ok: %v", err) } // from here the caller must call tearDown result.LoopbackClientConfig = config.LoopbackClientConfig result.Options = s result.Config = config result.TearDownFn = tearDown return result, nil } // StartTestServerOrDie calls StartTestServer t.Fatal if it does not succeed. func StartTestServerOrDie(t Logger, flags []string) *TestServer { result, err := StartTestServer(t, flags) if err == nil { return &result } t.Fatalf("failed to launch server: %v", err) return nil } func createListenerOnFreePort() (net.Listener, int, error) { ln, err := net.Listen("tcp", ":0") if err != nil { return nil, 0, err } // get port tcpAddr, ok := ln.Addr().(*net.TCPAddr) if !ok { ln.Close() return nil, 0, fmt.Errorf("invalid listen address: %q", ln.Addr().String()) } return ln, tcpAddr.Port, nil }
cmd/kube-controller-manager/app/testing/testserver.go
1
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.9984949827194214, 0.3336665630340576, 0.0001689436030574143, 0.003219850128516555, 0.4315924346446991 ]
{ "id": 6, "code_window": [ "// Note: we return a tear-down func instead of a stop channel because the later will leak temporary\n", "// \t\t files that because Golang testing's call to os.Exit will not give a stop channel go routine\n", "// \t\t enough time to remove temporary files.\n", "func StartTestServer(t Logger, customFlags []string) (result TestServer, err error) {\n", "\tstopCh := make(chan struct{})\n", "\tconfigDoneCh := make(chan struct{})\n", "\tvar capturedConfig config.CompletedConfig\n", "\ttearDown := func() {\n", "\t\tclose(stopCh)\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tvar errCh chan error\n" ], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 64 }
apiVersion: authorization.k8s.io/v1beta1 kind: LocalSubjectAccessReview metadata: annotations: annotationsKey: annotationsValue creationTimestamp: "2008-01-01T01:01:01Z" deletionGracePeriodSeconds: 10 deletionTimestamp: "2009-01-01T01:01:01Z" finalizers: - finalizersValue generateName: generateNameValue generation: 7 labels: labelsKey: labelsValue managedFields: - apiVersion: apiVersionValue fieldsType: fieldsTypeValue fieldsV1: {} manager: managerValue operation: operationValue subresource: subresourceValue time: "2004-01-01T01:01:01Z" name: nameValue namespace: namespaceValue ownerReferences: - apiVersion: apiVersionValue blockOwnerDeletion: true controller: true kind: kindValue name: nameValue uid: uidValue resourceVersion: resourceVersionValue selfLink: selfLinkValue uid: uidValue spec: extra: extraKey: - extraValue group: - groupValue nonResourceAttributes: path: pathValue verb: verbValue resourceAttributes: group: groupValue name: nameValue namespace: namespaceValue resource: resourceValue subresource: subresourceValue verb: verbValue version: versionValue uid: uidValue user: userValue status: allowed: true denied: true evaluationError: evaluationErrorValue reason: reasonValue
staging/src/k8s.io/api/testdata/HEAD/authorization.k8s.io.v1beta1.LocalSubjectAccessReview.yaml
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.0001781238242983818, 0.0001774245174601674, 0.00017619608843233436, 0.00017741277406457812, 6.413197866095288e-7 ]
{ "id": 6, "code_window": [ "// Note: we return a tear-down func instead of a stop channel because the later will leak temporary\n", "// \t\t files that because Golang testing's call to os.Exit will not give a stop channel go routine\n", "// \t\t enough time to remove temporary files.\n", "func StartTestServer(t Logger, customFlags []string) (result TestServer, err error) {\n", "\tstopCh := make(chan struct{})\n", "\tconfigDoneCh := make(chan struct{})\n", "\tvar capturedConfig config.CompletedConfig\n", "\ttearDown := func() {\n", "\t\tclose(stopCh)\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tvar errCh chan error\n" ], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 64 }
// Copyright 2017, 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. package value import ( "math" "reflect" ) // IsZero reports whether v is the zero value. // This does not rely on Interface and so can be used on unexported fields. func IsZero(v reflect.Value) bool { switch v.Kind() { case reflect.Bool: return v.Bool() == false case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int() == 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return v.Uint() == 0 case reflect.Float32, reflect.Float64: return math.Float64bits(v.Float()) == 0 case reflect.Complex64, reflect.Complex128: return math.Float64bits(real(v.Complex())) == 0 && math.Float64bits(imag(v.Complex())) == 0 case reflect.String: return v.String() == "" case reflect.UnsafePointer: return v.Pointer() == 0 case reflect.Chan, reflect.Func, reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice: return v.IsNil() case reflect.Array: for i := 0; i < v.Len(); i++ { if !IsZero(v.Index(i)) { return false } } return true case reflect.Struct: for i := 0; i < v.NumField(); i++ { if !IsZero(v.Field(i)) { return false } } return true } return false }
vendor/github.com/google/go-cmp/cmp/internal/value/zero.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.00017969272448681295, 0.00017258959996979684, 0.00016353907994925976, 0.00017323927022516727, 0.000005280853201838909 ]
{ "id": 6, "code_window": [ "// Note: we return a tear-down func instead of a stop channel because the later will leak temporary\n", "// \t\t files that because Golang testing's call to os.Exit will not give a stop channel go routine\n", "// \t\t enough time to remove temporary files.\n", "func StartTestServer(t Logger, customFlags []string) (result TestServer, err error) {\n", "\tstopCh := make(chan struct{})\n", "\tconfigDoneCh := make(chan struct{})\n", "\tvar capturedConfig config.CompletedConfig\n", "\ttearDown := func() {\n", "\t\tclose(stopCh)\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tvar errCh chan error\n" ], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 64 }
apiVersion: v1 kind: PodTemplate metadata: annotations: annotationsKey: annotationsValue creationTimestamp: "2008-01-01T01:01:01Z" deletionGracePeriodSeconds: 10 deletionTimestamp: "2009-01-01T01:01:01Z" finalizers: - finalizersValue generateName: generateNameValue generation: 7 labels: labelsKey: labelsValue managedFields: - apiVersion: apiVersionValue fieldsType: fieldsTypeValue fieldsV1: {} manager: managerValue operation: operationValue subresource: subresourceValue time: "2004-01-01T01:01:01Z" name: nameValue namespace: namespaceValue ownerReferences: - apiVersion: apiVersionValue blockOwnerDeletion: true controller: true kind: kindValue name: nameValue uid: uidValue resourceVersion: resourceVersionValue selfLink: selfLinkValue uid: uidValue template: metadata: annotations: annotationsKey: annotationsValue creationTimestamp: "2008-01-01T01:01:01Z" deletionGracePeriodSeconds: 10 deletionTimestamp: "2009-01-01T01:01:01Z" finalizers: - finalizersValue generateName: generateNameValue generation: 7 labels: labelsKey: labelsValue managedFields: - apiVersion: apiVersionValue fieldsType: fieldsTypeValue fieldsV1: {} manager: managerValue operation: operationValue subresource: subresourceValue time: "2004-01-01T01:01:01Z" name: nameValue namespace: namespaceValue ownerReferences: - apiVersion: apiVersionValue blockOwnerDeletion: true controller: true kind: kindValue name: nameValue uid: uidValue resourceVersion: resourceVersionValue selfLink: selfLinkValue uid: uidValue spec: activeDeadlineSeconds: 5 affinity: nodeAffinity: preferredDuringSchedulingIgnoredDuringExecution: - preference: matchExpressions: - key: keyValue operator: operatorValue values: - valuesValue matchFields: - key: keyValue operator: operatorValue values: - valuesValue weight: 1 requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: keyValue operator: operatorValue values: - valuesValue matchFields: - key: keyValue operator: operatorValue values: - valuesValue podAffinity: preferredDuringSchedulingIgnoredDuringExecution: - podAffinityTerm: labelSelector: matchExpressions: - key: keyValue operator: operatorValue values: - valuesValue matchLabels: matchLabelsKey: matchLabelsValue namespaceSelector: matchExpressions: - key: keyValue operator: operatorValue values: - valuesValue matchLabels: matchLabelsKey: matchLabelsValue namespaces: - namespacesValue topologyKey: topologyKeyValue weight: 1 requiredDuringSchedulingIgnoredDuringExecution: - labelSelector: matchExpressions: - key: keyValue operator: operatorValue values: - valuesValue matchLabels: matchLabelsKey: matchLabelsValue namespaceSelector: matchExpressions: - key: keyValue operator: operatorValue values: - valuesValue matchLabels: matchLabelsKey: matchLabelsValue namespaces: - namespacesValue topologyKey: topologyKeyValue podAntiAffinity: preferredDuringSchedulingIgnoredDuringExecution: - podAffinityTerm: labelSelector: matchExpressions: - key: keyValue operator: operatorValue values: - valuesValue matchLabels: matchLabelsKey: matchLabelsValue namespaceSelector: matchExpressions: - key: keyValue operator: operatorValue values: - valuesValue matchLabels: matchLabelsKey: matchLabelsValue namespaces: - namespacesValue topologyKey: topologyKeyValue weight: 1 requiredDuringSchedulingIgnoredDuringExecution: - labelSelector: matchExpressions: - key: keyValue operator: operatorValue values: - valuesValue matchLabels: matchLabelsKey: matchLabelsValue namespaceSelector: matchExpressions: - key: keyValue operator: operatorValue values: - valuesValue matchLabels: matchLabelsKey: matchLabelsValue namespaces: - namespacesValue topologyKey: topologyKeyValue automountServiceAccountToken: true containers: - args: - argsValue command: - commandValue env: - name: nameValue value: valueValue valueFrom: configMapKeyRef: key: keyValue name: nameValue optional: true fieldRef: apiVersion: apiVersionValue fieldPath: fieldPathValue resourceFieldRef: containerName: containerNameValue divisor: "0" resource: resourceValue secretKeyRef: key: keyValue name: nameValue optional: true envFrom: - configMapRef: name: nameValue optional: true prefix: prefixValue secretRef: name: nameValue optional: true image: imageValue imagePullPolicy: imagePullPolicyValue lifecycle: postStart: exec: command: - commandValue httpGet: host: hostValue httpHeaders: - name: nameValue value: valueValue path: pathValue port: portValue scheme: schemeValue tcpSocket: host: hostValue port: portValue preStop: exec: command: - commandValue httpGet: host: hostValue httpHeaders: - name: nameValue value: valueValue path: pathValue port: portValue scheme: schemeValue tcpSocket: host: hostValue port: portValue livenessProbe: exec: command: - commandValue failureThreshold: 6 grpc: port: 1 service: serviceValue httpGet: host: hostValue httpHeaders: - name: nameValue value: valueValue path: pathValue port: portValue scheme: schemeValue initialDelaySeconds: 2 periodSeconds: 4 successThreshold: 5 tcpSocket: host: hostValue port: portValue terminationGracePeriodSeconds: 7 timeoutSeconds: 3 name: nameValue ports: - containerPort: 3 hostIP: hostIPValue hostPort: 2 name: nameValue protocol: protocolValue readinessProbe: exec: command: - commandValue failureThreshold: 6 grpc: port: 1 service: serviceValue httpGet: host: hostValue httpHeaders: - name: nameValue value: valueValue path: pathValue port: portValue scheme: schemeValue initialDelaySeconds: 2 periodSeconds: 4 successThreshold: 5 tcpSocket: host: hostValue port: portValue terminationGracePeriodSeconds: 7 timeoutSeconds: 3 resources: limits: limitsKey: "0" requests: requestsKey: "0" securityContext: allowPrivilegeEscalation: true capabilities: add: - addValue drop: - dropValue privileged: true procMount: procMountValue readOnlyRootFilesystem: true runAsGroup: 8 runAsNonRoot: true runAsUser: 4 seLinuxOptions: level: levelValue role: roleValue type: typeValue user: userValue seccompProfile: localhostProfile: localhostProfileValue type: typeValue windowsOptions: gmsaCredentialSpec: gmsaCredentialSpecValue gmsaCredentialSpecName: gmsaCredentialSpecNameValue hostProcess: true runAsUserName: runAsUserNameValue startupProbe: exec: command: - commandValue failureThreshold: 6 grpc: port: 1 service: serviceValue httpGet: host: hostValue httpHeaders: - name: nameValue value: valueValue path: pathValue port: portValue scheme: schemeValue initialDelaySeconds: 2 periodSeconds: 4 successThreshold: 5 tcpSocket: host: hostValue port: portValue terminationGracePeriodSeconds: 7 timeoutSeconds: 3 stdin: true stdinOnce: true terminationMessagePath: terminationMessagePathValue terminationMessagePolicy: terminationMessagePolicyValue tty: true volumeDevices: - devicePath: devicePathValue name: nameValue volumeMounts: - mountPath: mountPathValue mountPropagation: mountPropagationValue name: nameValue readOnly: true subPath: subPathValue subPathExpr: subPathExprValue workingDir: workingDirValue dnsConfig: nameservers: - nameserversValue options: - name: nameValue value: valueValue searches: - searchesValue dnsPolicy: dnsPolicyValue enableServiceLinks: true ephemeralContainers: - args: - argsValue command: - commandValue env: - name: nameValue value: valueValue valueFrom: configMapKeyRef: key: keyValue name: nameValue optional: true fieldRef: apiVersion: apiVersionValue fieldPath: fieldPathValue resourceFieldRef: containerName: containerNameValue divisor: "0" resource: resourceValue secretKeyRef: key: keyValue name: nameValue optional: true envFrom: - configMapRef: name: nameValue optional: true prefix: prefixValue secretRef: name: nameValue optional: true image: imageValue imagePullPolicy: imagePullPolicyValue lifecycle: postStart: exec: command: - commandValue httpGet: host: hostValue httpHeaders: - name: nameValue value: valueValue path: pathValue port: portValue scheme: schemeValue tcpSocket: host: hostValue port: portValue preStop: exec: command: - commandValue httpGet: host: hostValue httpHeaders: - name: nameValue value: valueValue path: pathValue port: portValue scheme: schemeValue tcpSocket: host: hostValue port: portValue livenessProbe: exec: command: - commandValue failureThreshold: 6 grpc: port: 1 service: serviceValue httpGet: host: hostValue httpHeaders: - name: nameValue value: valueValue path: pathValue port: portValue scheme: schemeValue initialDelaySeconds: 2 periodSeconds: 4 successThreshold: 5 tcpSocket: host: hostValue port: portValue terminationGracePeriodSeconds: 7 timeoutSeconds: 3 name: nameValue ports: - containerPort: 3 hostIP: hostIPValue hostPort: 2 name: nameValue protocol: protocolValue readinessProbe: exec: command: - commandValue failureThreshold: 6 grpc: port: 1 service: serviceValue httpGet: host: hostValue httpHeaders: - name: nameValue value: valueValue path: pathValue port: portValue scheme: schemeValue initialDelaySeconds: 2 periodSeconds: 4 successThreshold: 5 tcpSocket: host: hostValue port: portValue terminationGracePeriodSeconds: 7 timeoutSeconds: 3 resources: limits: limitsKey: "0" requests: requestsKey: "0" securityContext: allowPrivilegeEscalation: true capabilities: add: - addValue drop: - dropValue privileged: true procMount: procMountValue readOnlyRootFilesystem: true runAsGroup: 8 runAsNonRoot: true runAsUser: 4 seLinuxOptions: level: levelValue role: roleValue type: typeValue user: userValue seccompProfile: localhostProfile: localhostProfileValue type: typeValue windowsOptions: gmsaCredentialSpec: gmsaCredentialSpecValue gmsaCredentialSpecName: gmsaCredentialSpecNameValue hostProcess: true runAsUserName: runAsUserNameValue startupProbe: exec: command: - commandValue failureThreshold: 6 grpc: port: 1 service: serviceValue httpGet: host: hostValue httpHeaders: - name: nameValue value: valueValue path: pathValue port: portValue scheme: schemeValue initialDelaySeconds: 2 periodSeconds: 4 successThreshold: 5 tcpSocket: host: hostValue port: portValue terminationGracePeriodSeconds: 7 timeoutSeconds: 3 stdin: true stdinOnce: true targetContainerName: targetContainerNameValue terminationMessagePath: terminationMessagePathValue terminationMessagePolicy: terminationMessagePolicyValue tty: true volumeDevices: - devicePath: devicePathValue name: nameValue volumeMounts: - mountPath: mountPathValue mountPropagation: mountPropagationValue name: nameValue readOnly: true subPath: subPathValue subPathExpr: subPathExprValue workingDir: workingDirValue hostAliases: - hostnames: - hostnamesValue ip: ipValue hostIPC: true hostNetwork: true hostPID: true hostname: hostnameValue imagePullSecrets: - name: nameValue initContainers: - args: - argsValue command: - commandValue env: - name: nameValue value: valueValue valueFrom: configMapKeyRef: key: keyValue name: nameValue optional: true fieldRef: apiVersion: apiVersionValue fieldPath: fieldPathValue resourceFieldRef: containerName: containerNameValue divisor: "0" resource: resourceValue secretKeyRef: key: keyValue name: nameValue optional: true envFrom: - configMapRef: name: nameValue optional: true prefix: prefixValue secretRef: name: nameValue optional: true image: imageValue imagePullPolicy: imagePullPolicyValue lifecycle: postStart: exec: command: - commandValue httpGet: host: hostValue httpHeaders: - name: nameValue value: valueValue path: pathValue port: portValue scheme: schemeValue tcpSocket: host: hostValue port: portValue preStop: exec: command: - commandValue httpGet: host: hostValue httpHeaders: - name: nameValue value: valueValue path: pathValue port: portValue scheme: schemeValue tcpSocket: host: hostValue port: portValue livenessProbe: exec: command: - commandValue failureThreshold: 6 grpc: port: 1 service: serviceValue httpGet: host: hostValue httpHeaders: - name: nameValue value: valueValue path: pathValue port: portValue scheme: schemeValue initialDelaySeconds: 2 periodSeconds: 4 successThreshold: 5 tcpSocket: host: hostValue port: portValue terminationGracePeriodSeconds: 7 timeoutSeconds: 3 name: nameValue ports: - containerPort: 3 hostIP: hostIPValue hostPort: 2 name: nameValue protocol: protocolValue readinessProbe: exec: command: - commandValue failureThreshold: 6 grpc: port: 1 service: serviceValue httpGet: host: hostValue httpHeaders: - name: nameValue value: valueValue path: pathValue port: portValue scheme: schemeValue initialDelaySeconds: 2 periodSeconds: 4 successThreshold: 5 tcpSocket: host: hostValue port: portValue terminationGracePeriodSeconds: 7 timeoutSeconds: 3 resources: limits: limitsKey: "0" requests: requestsKey: "0" securityContext: allowPrivilegeEscalation: true capabilities: add: - addValue drop: - dropValue privileged: true procMount: procMountValue readOnlyRootFilesystem: true runAsGroup: 8 runAsNonRoot: true runAsUser: 4 seLinuxOptions: level: levelValue role: roleValue type: typeValue user: userValue seccompProfile: localhostProfile: localhostProfileValue type: typeValue windowsOptions: gmsaCredentialSpec: gmsaCredentialSpecValue gmsaCredentialSpecName: gmsaCredentialSpecNameValue hostProcess: true runAsUserName: runAsUserNameValue startupProbe: exec: command: - commandValue failureThreshold: 6 grpc: port: 1 service: serviceValue httpGet: host: hostValue httpHeaders: - name: nameValue value: valueValue path: pathValue port: portValue scheme: schemeValue initialDelaySeconds: 2 periodSeconds: 4 successThreshold: 5 tcpSocket: host: hostValue port: portValue terminationGracePeriodSeconds: 7 timeoutSeconds: 3 stdin: true stdinOnce: true terminationMessagePath: terminationMessagePathValue terminationMessagePolicy: terminationMessagePolicyValue tty: true volumeDevices: - devicePath: devicePathValue name: nameValue volumeMounts: - mountPath: mountPathValue mountPropagation: mountPropagationValue name: nameValue readOnly: true subPath: subPathValue subPathExpr: subPathExprValue workingDir: workingDirValue nodeName: nodeNameValue nodeSelector: nodeSelectorKey: nodeSelectorValue os: name: nameValue overhead: overheadKey: "0" preemptionPolicy: preemptionPolicyValue priority: 25 priorityClassName: priorityClassNameValue readinessGates: - conditionType: conditionTypeValue restartPolicy: restartPolicyValue runtimeClassName: runtimeClassNameValue schedulerName: schedulerNameValue securityContext: fsGroup: 5 fsGroupChangePolicy: fsGroupChangePolicyValue runAsGroup: 6 runAsNonRoot: true runAsUser: 2 seLinuxOptions: level: levelValue role: roleValue type: typeValue user: userValue seccompProfile: localhostProfile: localhostProfileValue type: typeValue supplementalGroups: - 4 sysctls: - name: nameValue value: valueValue windowsOptions: gmsaCredentialSpec: gmsaCredentialSpecValue gmsaCredentialSpecName: gmsaCredentialSpecNameValue hostProcess: true runAsUserName: runAsUserNameValue serviceAccount: serviceAccountValue serviceAccountName: serviceAccountNameValue setHostnameAsFQDN: true shareProcessNamespace: true subdomain: subdomainValue terminationGracePeriodSeconds: 4 tolerations: - effect: effectValue key: keyValue operator: operatorValue tolerationSeconds: 5 value: valueValue topologySpreadConstraints: - labelSelector: matchExpressions: - key: keyValue operator: operatorValue values: - valuesValue matchLabels: matchLabelsKey: matchLabelsValue maxSkew: 1 minDomains: 5 nodeAffinityPolicy: nodeAffinityPolicyValue nodeTaintsPolicy: nodeTaintsPolicyValue topologyKey: topologyKeyValue whenUnsatisfiable: whenUnsatisfiableValue volumes: - awsElasticBlockStore: fsType: fsTypeValue partition: 3 readOnly: true volumeID: volumeIDValue azureDisk: cachingMode: cachingModeValue diskName: diskNameValue diskURI: diskURIValue fsType: fsTypeValue kind: kindValue readOnly: true azureFile: readOnly: true secretName: secretNameValue shareName: shareNameValue cephfs: monitors: - monitorsValue path: pathValue readOnly: true secretFile: secretFileValue secretRef: name: nameValue user: userValue cinder: fsType: fsTypeValue readOnly: true secretRef: name: nameValue volumeID: volumeIDValue configMap: defaultMode: 3 items: - key: keyValue mode: 3 path: pathValue name: nameValue optional: true csi: driver: driverValue fsType: fsTypeValue nodePublishSecretRef: name: nameValue readOnly: true volumeAttributes: volumeAttributesKey: volumeAttributesValue downwardAPI: defaultMode: 2 items: - fieldRef: apiVersion: apiVersionValue fieldPath: fieldPathValue mode: 4 path: pathValue resourceFieldRef: containerName: containerNameValue divisor: "0" resource: resourceValue emptyDir: medium: mediumValue sizeLimit: "0" ephemeral: volumeClaimTemplate: metadata: annotations: annotationsKey: annotationsValue creationTimestamp: "2008-01-01T01:01:01Z" deletionGracePeriodSeconds: 10 deletionTimestamp: "2009-01-01T01:01:01Z" finalizers: - finalizersValue generateName: generateNameValue generation: 7 labels: labelsKey: labelsValue managedFields: - apiVersion: apiVersionValue fieldsType: fieldsTypeValue fieldsV1: {} manager: managerValue operation: operationValue subresource: subresourceValue time: "2004-01-01T01:01:01Z" name: nameValue namespace: namespaceValue ownerReferences: - apiVersion: apiVersionValue blockOwnerDeletion: true controller: true kind: kindValue name: nameValue uid: uidValue resourceVersion: resourceVersionValue selfLink: selfLinkValue uid: uidValue spec: accessModes: - accessModesValue dataSource: apiGroup: apiGroupValue kind: kindValue name: nameValue dataSourceRef: apiGroup: apiGroupValue kind: kindValue name: nameValue resources: limits: limitsKey: "0" requests: requestsKey: "0" selector: matchExpressions: - key: keyValue operator: operatorValue values: - valuesValue matchLabels: matchLabelsKey: matchLabelsValue storageClassName: storageClassNameValue volumeMode: volumeModeValue volumeName: volumeNameValue fc: fsType: fsTypeValue lun: 2 readOnly: true targetWWNs: - targetWWNsValue wwids: - wwidsValue flexVolume: driver: driverValue fsType: fsTypeValue options: optionsKey: optionsValue readOnly: true secretRef: name: nameValue flocker: datasetName: datasetNameValue datasetUUID: datasetUUIDValue gcePersistentDisk: fsType: fsTypeValue partition: 3 pdName: pdNameValue readOnly: true gitRepo: directory: directoryValue repository: repositoryValue revision: revisionValue glusterfs: endpoints: endpointsValue path: pathValue readOnly: true hostPath: path: pathValue type: typeValue iscsi: chapAuthDiscovery: true chapAuthSession: true fsType: fsTypeValue initiatorName: initiatorNameValue iqn: iqnValue iscsiInterface: iscsiInterfaceValue lun: 3 portals: - portalsValue readOnly: true secretRef: name: nameValue targetPortal: targetPortalValue name: nameValue nfs: path: pathValue readOnly: true server: serverValue persistentVolumeClaim: claimName: claimNameValue readOnly: true photonPersistentDisk: fsType: fsTypeValue pdID: pdIDValue portworxVolume: fsType: fsTypeValue readOnly: true volumeID: volumeIDValue projected: defaultMode: 2 sources: - configMap: items: - key: keyValue mode: 3 path: pathValue name: nameValue optional: true downwardAPI: items: - fieldRef: apiVersion: apiVersionValue fieldPath: fieldPathValue mode: 4 path: pathValue resourceFieldRef: containerName: containerNameValue divisor: "0" resource: resourceValue secret: items: - key: keyValue mode: 3 path: pathValue name: nameValue optional: true serviceAccountToken: audience: audienceValue expirationSeconds: 2 path: pathValue quobyte: group: groupValue readOnly: true registry: registryValue tenant: tenantValue user: userValue volume: volumeValue rbd: fsType: fsTypeValue image: imageValue keyring: keyringValue monitors: - monitorsValue pool: poolValue readOnly: true secretRef: name: nameValue user: userValue scaleIO: fsType: fsTypeValue gateway: gatewayValue protectionDomain: protectionDomainValue readOnly: true secretRef: name: nameValue sslEnabled: true storageMode: storageModeValue storagePool: storagePoolValue system: systemValue volumeName: volumeNameValue secret: defaultMode: 3 items: - key: keyValue mode: 3 path: pathValue optional: true secretName: secretNameValue storageos: fsType: fsTypeValue readOnly: true secretRef: name: nameValue volumeName: volumeNameValue volumeNamespace: volumeNamespaceValue vsphereVolume: fsType: fsTypeValue storagePolicyID: storagePolicyIDValue storagePolicyName: storagePolicyNameValue volumePath: volumePathValue
staging/src/k8s.io/api/testdata/HEAD/core.v1.PodTemplate.yaml
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.0001789272646419704, 0.00017633786774240434, 0.0001711617223918438, 0.0001765808992786333, 0.0000014584747987100855 ]
{ "id": 7, "code_window": [ "\tvar capturedConfig config.CompletedConfig\n", "\ttearDown := func() {\n", "\t\tclose(stopCh)\n", "\t\tif len(result.TmpDir) != 0 {\n", "\t\t\tos.RemoveAll(result.TmpDir)\n", "\t\t}\n", "\t}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\t// If cloud-controller-manager was started, let's wait for\n", "\t\t// it to shutdown clearly.\n", "\t\tif errCh != nil {\n", "\t\t\terr, ok := <-errCh\n", "\t\t\tif ok && err != nil {\n", "\t\t\t\tklog.Errorf(\"Failed to shutdown test server clearly: %v\", err)\n", "\t\t\t}\n", "\t\t}\n" ], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 68 }
/* Copyright 2018 The Kubernetes 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 testing import ( "context" "fmt" "io/ioutil" "net" "os" "strings" "time" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes" restclient "k8s.io/client-go/rest" cloudprovider "k8s.io/cloud-provider" "k8s.io/cloud-provider/app" "k8s.io/cloud-provider/app/config" "k8s.io/cloud-provider/options" cliflag "k8s.io/component-base/cli/flag" ) // TearDownFunc is to be called to tear down a test server. type TearDownFunc func() // TestServer return values supplied by kube-test-ApiServer type TestServer struct { LoopbackClientConfig *restclient.Config // Rest client config using the magic token Options *options.CloudControllerManagerOptions Config *config.CompletedConfig TearDownFn TearDownFunc // TearDown function TmpDir string // Temp Dir used, by the apiserver } // Logger allows t.Testing and b.Testing to be passed to StartTestServer and StartTestServerOrDie type Logger interface { Errorf(format string, args ...interface{}) Fatalf(format string, args ...interface{}) Logf(format string, args ...interface{}) } // StartTestServer starts a cloud-controller-manager. A rest client config and a tear-down func, // and location of the tmpdir are returned. // // Note: we return a tear-down func instead of a stop channel because the later will leak temporary // files that because Golang testing's call to os.Exit will not give a stop channel go routine // enough time to remove temporary files. func StartTestServer(t Logger, customFlags []string) (result TestServer, err error) { stopCh := make(chan struct{}) configDoneCh := make(chan struct{}) var capturedConfig config.CompletedConfig tearDown := func() { close(stopCh) if len(result.TmpDir) != 0 { os.RemoveAll(result.TmpDir) } } defer func() { if result.TearDownFn == nil { tearDown() } }() result.TmpDir, err = ioutil.TempDir("", "cloud-controller-manager") if err != nil { return result, fmt.Errorf("failed to create temp dir: %v", err) } s, err := options.NewCloudControllerManagerOptions() if err != nil { return TestServer{}, err } cloudInitializer := func(config *config.CompletedConfig) cloudprovider.Interface { capturedConfig = *config // send signal to indicate the capturedConfig has been properly set close(configDoneCh) cloudConfig := config.ComponentConfig.KubeCloudShared.CloudProvider cloud, err := cloudprovider.InitCloudProvider(cloudConfig.Name, cloudConfig.CloudConfigFile) if err != nil { t.Fatalf("Cloud provider could not be initialized: %v", err) } s.SecureServing.ServerCert.CertDirectory = result.TmpDir if cloud == nil { t.Fatalf("Cloud provider is nil") } return cloud } fss := cliflag.NamedFlagSets{} command := app.NewCloudControllerManagerCommand(s, cloudInitializer, app.DefaultInitFuncConstructors, fss, stopCh) commandArgs := []string{} listeners := []net.Listener{} disableSecure := false for _, arg := range customFlags { if strings.HasPrefix(arg, "--secure-port=") { if arg == "--secure-port=0" { commandArgs = append(commandArgs, arg) disableSecure = true } } else if strings.HasPrefix(arg, "--cert-dir=") { // skip it } else { commandArgs = append(commandArgs, arg) } } if !disableSecure { listener, bindPort, err := createListenerOnFreePort() if err != nil { return result, fmt.Errorf("failed to create listener: %v", err) } listeners = append(listeners, listener) commandArgs = append(commandArgs, fmt.Sprintf("--secure-port=%d", bindPort)) commandArgs = append(commandArgs, fmt.Sprintf("--cert-dir=%s", result.TmpDir)) t.Logf("cloud-controller-manager will listen securely on port %d...", bindPort) } for _, listener := range listeners { listener.Close() } errCh := make(chan error) go func() { command.SetArgs(commandArgs) if err := command.Execute(); err != nil { errCh <- err } close(errCh) }() select { case <-configDoneCh: case err := <-errCh: return result, err } t.Logf("Waiting for /healthz to be ok...") client, err := kubernetes.NewForConfig(capturedConfig.LoopbackClientConfig) if err != nil { return result, fmt.Errorf("failed to create a client: %v", err) } err = wait.Poll(100*time.Millisecond, 30*time.Second, func() (bool, error) { select { case err := <-errCh: return false, err default: } result := client.CoreV1().RESTClient().Get().AbsPath("/healthz").Do(context.TODO()) status := 0 result.StatusCode(&status) if status == 200 { return true, nil } return false, nil }) if err != nil { return result, fmt.Errorf("failed to wait for /healthz to return ok: %v", err) } // from here the caller must call tearDown result.LoopbackClientConfig = capturedConfig.LoopbackClientConfig result.Options = s result.Config = &capturedConfig result.TearDownFn = tearDown return result, nil } // StartTestServerOrDie calls StartTestServer t.Fatal if it does not succeed. func StartTestServerOrDie(t Logger, flags []string) *TestServer { result, err := StartTestServer(t, flags) if err == nil { return &result } t.Fatalf("failed to launch server: %v", err) return nil } func createListenerOnFreePort() (net.Listener, int, error) { ln, err := net.Listen("tcp", ":0") if err != nil { return nil, 0, err } // get port tcpAddr, ok := ln.Addr().(*net.TCPAddr) if !ok { ln.Close() return nil, 0, fmt.Errorf("invalid listen address: %q", ln.Addr().String()) } return ln, tcpAddr.Port, nil }
staging/src/k8s.io/cloud-provider/app/testing/testserver.go
1
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.9982045888900757, 0.27527353167533875, 0.00016571073501836509, 0.001183722517453134, 0.4397334158420563 ]
{ "id": 7, "code_window": [ "\tvar capturedConfig config.CompletedConfig\n", "\ttearDown := func() {\n", "\t\tclose(stopCh)\n", "\t\tif len(result.TmpDir) != 0 {\n", "\t\t\tos.RemoveAll(result.TmpDir)\n", "\t\t}\n", "\t}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\t// If cloud-controller-manager was started, let's wait for\n", "\t\t// it to shutdown clearly.\n", "\t\tif errCh != nil {\n", "\t\t\terr, ok := <-errCh\n", "\t\t\tif ok && err != nil {\n", "\t\t\t\tklog.Errorf(\"Failed to shutdown test server clearly: %v\", err)\n", "\t\t\t}\n", "\t\t}\n" ], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 68 }
// +build !go1.7 package sdkio // Copy of Go 1.7 io package's Seeker constants. const ( SeekStart = 0 // seek relative to the origin of the file SeekCurrent = 1 // seek relative to the current offset SeekEnd = 2 // seek relative to the end )
vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.6.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.00017752884014043957, 0.00017414079047739506, 0.00017075274081435055, 0.00017414079047739506, 0.0000033880496630445123 ]
{ "id": 7, "code_window": [ "\tvar capturedConfig config.CompletedConfig\n", "\ttearDown := func() {\n", "\t\tclose(stopCh)\n", "\t\tif len(result.TmpDir) != 0 {\n", "\t\t\tos.RemoveAll(result.TmpDir)\n", "\t\t}\n", "\t}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\t// If cloud-controller-manager was started, let's wait for\n", "\t\t// it to shutdown clearly.\n", "\t\tif errCh != nil {\n", "\t\t\terr, ok := <-errCh\n", "\t\t\tif ok && err != nil {\n", "\t\t\t\tklog.Errorf(\"Failed to shutdown test server clearly: %v\", err)\n", "\t\t\t}\n", "\t\t}\n" ], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 68 }
-----BEGIN CERTIFICATE----- MIIC9zCCAd+gAwIBAgIJAOWJ8tWNUIsZMA0GCSqGSIb3DQEBCwUAMBIxEDAOBgNV BAMMB2t1YmUtY2EwHhcNMTYxMjIyMDAyNTI5WhcNNDQwNTA5MDAyNTI5WjASMRAw DgYDVQQDDAdrdWJlLWNhMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA 1HK1d2p7N7UC6px8lVtABw8jPpVyNYjrJmI+TKTTdCgWGsUTFMCw4t4Q/KQDDlvB P19uPhbfp8aLwOWXBCxOPZzlM2mAEjSUgKjbyGCW/8vaXa2VgQm3tKZdydKiFvIo fEsNA+58w8A0WWEB8wYFcdCt8uPyQ0ws/TxE+WW3u7EPlC0/inIX9JqeZZMpDk3N lHEv/pGEjQmoet/hBwGHq9PKepkN5/V6rrSADJ5I4Uklp2f7G9MCP/zV8xKfs0lK CMoJsIPK3nL9N3C0rqBQPfcyKE2fnEkxC3UVZA8brvLTkBfOgmM2eVg/nauU1ejv zOJL7tDwUioLriw2hiGrFwIDAQABo1AwTjAdBgNVHQ4EFgQUbGJxJeW7BgZ4xSmW d3Aw3gq8YZUwHwYDVR0jBBgwFoAUbGJxJeW7BgZ4xSmWd3Aw3gq8YZUwDAYDVR0T BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAunzpYAxpzguzxG83pK5n3ObsGDwO 78d38qX1VRvMLPvioZxYgquqqFPdLI3xe8b8KdZNzb65549tgjAI17tTKGTRgJu5 yzLU1tO4vNaAFecMCtPvElYfkrAv2vbGCVJ1bYKTnjdu3083jG3sY9TDj0364A57 lNwKEd5uxHGWg4H+NbyHkDqfKmllzLvJ9XjSWBPmNVLSW50hV+h9fUXgz9LN+qVY VEDfAEWqb6PVy9ANw8A8QLnuSRxbd7hAigtlC4MwzYJ6tyFIIH6bCIgfoZuA+brm WGcpIxl4fKEGafSgjsK/6Yhb61mkhHmG16mzEUZNkNsjiYJuF2QxpOlQrw== -----END CERTIFICATE-----
pkg/controller/certificates/signer/testdata/ca.crt
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.00040743660065345466, 0.00028582190861925483, 0.00016420720203313977, 0.00028582190861925483, 0.00012161469931015745 ]
{ "id": 7, "code_window": [ "\tvar capturedConfig config.CompletedConfig\n", "\ttearDown := func() {\n", "\t\tclose(stopCh)\n", "\t\tif len(result.TmpDir) != 0 {\n", "\t\t\tos.RemoveAll(result.TmpDir)\n", "\t\t}\n", "\t}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\t// If cloud-controller-manager was started, let's wait for\n", "\t\t// it to shutdown clearly.\n", "\t\tif errCh != nil {\n", "\t\t\terr, ok := <-errCh\n", "\t\t\tif ok && err != nil {\n", "\t\t\t\tklog.Errorf(\"Failed to shutdown test server clearly: %v\", err)\n", "\t\t\t}\n", "\t\t}\n" ], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 68 }
/*- * Copyright 2014 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package josecipher import ( "bytes" "crypto/cipher" "crypto/hmac" "crypto/sha256" "crypto/sha512" "crypto/subtle" "encoding/binary" "errors" "hash" ) const ( nonceBytes = 16 ) // NewCBCHMAC instantiates a new AEAD based on CBC+HMAC. func NewCBCHMAC(key []byte, newBlockCipher func([]byte) (cipher.Block, error)) (cipher.AEAD, error) { keySize := len(key) / 2 integrityKey := key[:keySize] encryptionKey := key[keySize:] blockCipher, err := newBlockCipher(encryptionKey) if err != nil { return nil, err } var hash func() hash.Hash switch keySize { case 16: hash = sha256.New case 24: hash = sha512.New384 case 32: hash = sha512.New } return &cbcAEAD{ hash: hash, blockCipher: blockCipher, authtagBytes: keySize, integrityKey: integrityKey, }, nil } // An AEAD based on CBC+HMAC type cbcAEAD struct { hash func() hash.Hash authtagBytes int integrityKey []byte blockCipher cipher.Block } func (ctx *cbcAEAD) NonceSize() int { return nonceBytes } func (ctx *cbcAEAD) Overhead() int { // Maximum overhead is block size (for padding) plus auth tag length, where // the length of the auth tag is equivalent to the key size. return ctx.blockCipher.BlockSize() + ctx.authtagBytes } // Seal encrypts and authenticates the plaintext. func (ctx *cbcAEAD) Seal(dst, nonce, plaintext, data []byte) []byte { // Output buffer -- must take care not to mangle plaintext input. ciphertext := make([]byte, uint64(len(plaintext))+uint64(ctx.Overhead()))[:len(plaintext)] copy(ciphertext, plaintext) ciphertext = padBuffer(ciphertext, ctx.blockCipher.BlockSize()) cbc := cipher.NewCBCEncrypter(ctx.blockCipher, nonce) cbc.CryptBlocks(ciphertext, ciphertext) authtag := ctx.computeAuthTag(data, nonce, ciphertext) ret, out := resize(dst, uint64(len(dst))+uint64(len(ciphertext))+uint64(len(authtag))) copy(out, ciphertext) copy(out[len(ciphertext):], authtag) return ret } // Open decrypts and authenticates the ciphertext. func (ctx *cbcAEAD) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) { if len(ciphertext) < ctx.authtagBytes { return nil, errors.New("square/go-jose: invalid ciphertext (too short)") } offset := len(ciphertext) - ctx.authtagBytes expectedTag := ctx.computeAuthTag(data, nonce, ciphertext[:offset]) match := subtle.ConstantTimeCompare(expectedTag, ciphertext[offset:]) if match != 1 { return nil, errors.New("square/go-jose: invalid ciphertext (auth tag mismatch)") } cbc := cipher.NewCBCDecrypter(ctx.blockCipher, nonce) // Make copy of ciphertext buffer, don't want to modify in place buffer := append([]byte{}, []byte(ciphertext[:offset])...) if len(buffer)%ctx.blockCipher.BlockSize() > 0 { return nil, errors.New("square/go-jose: invalid ciphertext (invalid length)") } cbc.CryptBlocks(buffer, buffer) // Remove padding plaintext, err := unpadBuffer(buffer, ctx.blockCipher.BlockSize()) if err != nil { return nil, err } ret, out := resize(dst, uint64(len(dst))+uint64(len(plaintext))) copy(out, plaintext) return ret, nil } // Compute an authentication tag func (ctx *cbcAEAD) computeAuthTag(aad, nonce, ciphertext []byte) []byte { buffer := make([]byte, uint64(len(aad))+uint64(len(nonce))+uint64(len(ciphertext))+8) n := 0 n += copy(buffer, aad) n += copy(buffer[n:], nonce) n += copy(buffer[n:], ciphertext) binary.BigEndian.PutUint64(buffer[n:], uint64(len(aad))*8) // According to documentation, Write() on hash.Hash never fails. hmac := hmac.New(ctx.hash, ctx.integrityKey) _, _ = hmac.Write(buffer) return hmac.Sum(nil)[:ctx.authtagBytes] } // resize ensures the the given slice has a capacity of at least n bytes. // If the capacity of the slice is less than n, a new slice is allocated // and the existing data will be copied. func resize(in []byte, n uint64) (head, tail []byte) { if uint64(cap(in)) >= n { head = in[:n] } else { head = make([]byte, n) copy(head, in) } tail = head[len(in):] return } // Apply padding func padBuffer(buffer []byte, blockSize int) []byte { missing := blockSize - (len(buffer) % blockSize) ret, out := resize(buffer, uint64(len(buffer))+uint64(missing)) padding := bytes.Repeat([]byte{byte(missing)}, missing) copy(out, padding) return ret } // Remove padding func unpadBuffer(buffer []byte, blockSize int) ([]byte, error) { if len(buffer)%blockSize != 0 { return nil, errors.New("square/go-jose: invalid padding") } last := buffer[len(buffer)-1] count := int(last) if count == 0 || count > blockSize || count > len(buffer) { return nil, errors.New("square/go-jose: invalid padding") } padding := bytes.Repeat([]byte{last}, count) if !bytes.HasSuffix(buffer, padding) { return nil, errors.New("square/go-jose: invalid padding") } return buffer[:len(buffer)-count], nil }
vendor/gopkg.in/square/go-jose.v2/cipher/cbc_hmac.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.00029092232580296695, 0.00018556308350525796, 0.00016163222608156502, 0.00017305059009231627, 0.00003751769691007212 ]
{ "id": 8, "code_window": [ "\t}\n", "\tfor _, listener := range listeners {\n", "\t\tlistener.Close()\n", "\t}\n", "\n", "\terrCh := make(chan error)\n", "\tgo func() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\terrCh = make(chan error)\n" ], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "replace", "edit_start_line_idx": 137 }
/* Copyright 2018 The Kubernetes 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 testing import ( "context" "fmt" "net" "os" "time" "github.com/spf13/pflag" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes" restclient "k8s.io/client-go/rest" "k8s.io/kubernetes/cmd/kube-controller-manager/app" kubecontrollerconfig "k8s.io/kubernetes/cmd/kube-controller-manager/app/config" "k8s.io/kubernetes/cmd/kube-controller-manager/app/options" ) // TearDownFunc is to be called to tear down a test server. type TearDownFunc func() // TestServer return values supplied by kube-test-ApiServer type TestServer struct { LoopbackClientConfig *restclient.Config // Rest client config using the magic token Options *options.KubeControllerManagerOptions Config *kubecontrollerconfig.Config TearDownFn TearDownFunc // TearDown function TmpDir string // Temp Dir used, by the apiserver } // Logger allows t.Testing and b.Testing to be passed to StartTestServer and StartTestServerOrDie type Logger interface { Errorf(format string, args ...interface{}) Fatalf(format string, args ...interface{}) Logf(format string, args ...interface{}) } // StartTestServer starts a kube-controller-manager. A rest client config and a tear-down func, // and location of the tmpdir are returned. // // Note: we return a tear-down func instead of a stop channel because the later will leak temporary // files that because Golang testing's call to os.Exit will not give a stop channel go routine // enough time to remove temporary files. func StartTestServer(t Logger, customFlags []string) (result TestServer, err error) { stopCh := make(chan struct{}) tearDown := func() { close(stopCh) if len(result.TmpDir) != 0 { os.RemoveAll(result.TmpDir) } } defer func() { if result.TearDownFn == nil { tearDown() } }() result.TmpDir, err = os.MkdirTemp("", "kube-controller-manager") if err != nil { return result, fmt.Errorf("failed to create temp dir: %v", err) } fs := pflag.NewFlagSet("test", pflag.PanicOnError) s, err := options.NewKubeControllerManagerOptions() if err != nil { return TestServer{}, err } all, disabled := app.KnownControllers(), app.ControllersDisabledByDefault.List() namedFlagSets := s.Flags(all, disabled) for _, f := range namedFlagSets.FlagSets { fs.AddFlagSet(f) } fs.Parse(customFlags) if s.SecureServing.BindPort != 0 { s.SecureServing.Listener, s.SecureServing.BindPort, err = createListenerOnFreePort() if err != nil { return result, fmt.Errorf("failed to create listener: %v", err) } s.SecureServing.ServerCert.CertDirectory = result.TmpDir t.Logf("kube-controller-manager will listen securely on port %d...", s.SecureServing.BindPort) } config, err := s.Config(all, disabled) if err != nil { return result, fmt.Errorf("failed to create config from options: %v", err) } errCh := make(chan error) go func(stopCh <-chan struct{}) { if err := app.Run(config.Complete(), stopCh); err != nil { errCh <- err } }(stopCh) t.Logf("Waiting for /healthz to be ok...") client, err := kubernetes.NewForConfig(config.LoopbackClientConfig) if err != nil { return result, fmt.Errorf("failed to create a client: %v", err) } err = wait.Poll(100*time.Millisecond, 30*time.Second, func() (bool, error) { select { case err := <-errCh: return false, err default: } result := client.CoreV1().RESTClient().Get().AbsPath("/healthz").Do(context.TODO()) status := 0 result.StatusCode(&status) if status == 200 { return true, nil } return false, nil }) if err != nil { return result, fmt.Errorf("failed to wait for /healthz to return ok: %v", err) } // from here the caller must call tearDown result.LoopbackClientConfig = config.LoopbackClientConfig result.Options = s result.Config = config result.TearDownFn = tearDown return result, nil } // StartTestServerOrDie calls StartTestServer t.Fatal if it does not succeed. func StartTestServerOrDie(t Logger, flags []string) *TestServer { result, err := StartTestServer(t, flags) if err == nil { return &result } t.Fatalf("failed to launch server: %v", err) return nil } func createListenerOnFreePort() (net.Listener, int, error) { ln, err := net.Listen("tcp", ":0") if err != nil { return nil, 0, err } // get port tcpAddr, ok := ln.Addr().(*net.TCPAddr) if !ok { ln.Close() return nil, 0, fmt.Errorf("invalid listen address: %q", ln.Addr().String()) } return ln, tcpAddr.Port, nil }
cmd/kube-controller-manager/app/testing/testserver.go
1
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.9973305463790894, 0.17224329710006714, 0.00016621334361843765, 0.00017954061331693083, 0.34468623995780945 ]
{ "id": 8, "code_window": [ "\t}\n", "\tfor _, listener := range listeners {\n", "\t\tlistener.Close()\n", "\t}\n", "\n", "\terrCh := make(chan error)\n", "\tgo func() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\terrCh = make(chan error)\n" ], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "replace", "edit_start_line_idx": 137 }
// Copyright 2015 The etcd 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 rafthttp import ( "context" "sync" "time" "go.etcd.io/etcd/client/pkg/v3/types" "go.etcd.io/etcd/raft/v3" "go.etcd.io/etcd/raft/v3/raftpb" "go.etcd.io/etcd/server/v3/etcdserver/api/snap" stats "go.etcd.io/etcd/server/v3/etcdserver/api/v2stats" "go.uber.org/zap" "golang.org/x/time/rate" ) const ( // ConnReadTimeout and ConnWriteTimeout are the i/o timeout set on each connection rafthttp pkg creates. // A 5 seconds timeout is good enough for recycling bad connections. Or we have to wait for // tcp keepalive failing to detect a bad connection, which is at minutes level. // For long term streaming connections, rafthttp pkg sends application level linkHeartbeatMessage // to keep the connection alive. // For short term pipeline connections, the connection MUST be killed to avoid it being // put back to http pkg connection pool. DefaultConnReadTimeout = 5 * time.Second DefaultConnWriteTimeout = 5 * time.Second recvBufSize = 4096 // maxPendingProposals holds the proposals during one leader election process. // Generally one leader election takes at most 1 sec. It should have // 0-2 election conflicts, and each one takes 0.5 sec. // We assume the number of concurrent proposers is smaller than 4096. // One client blocks on its proposal for at least 1 sec, so 4096 is enough // to hold all proposals. maxPendingProposals = 4096 streamAppV2 = "streamMsgAppV2" streamMsg = "streamMsg" pipelineMsg = "pipeline" sendSnap = "sendMsgSnap" ) var ( ConnReadTimeout = DefaultConnReadTimeout ConnWriteTimeout = DefaultConnWriteTimeout ) type Peer interface { // send sends the message to the remote peer. The function is non-blocking // and has no promise that the message will be received by the remote. // When it fails to send message out, it will report the status to underlying // raft. send(m raftpb.Message) // sendSnap sends the merged snapshot message to the remote peer. Its behavior // is similar to send. sendSnap(m snap.Message) // update updates the urls of remote peer. update(urls types.URLs) // attachOutgoingConn attaches the outgoing connection to the peer for // stream usage. After the call, the ownership of the outgoing // connection hands over to the peer. The peer will close the connection // when it is no longer used. attachOutgoingConn(conn *outgoingConn) // activeSince returns the time that the connection with the // peer becomes active. activeSince() time.Time // stop performs any necessary finalization and terminates the peer // elegantly. stop() } // peer is the representative of a remote raft node. Local raft node sends // messages to the remote through peer. // Each peer has two underlying mechanisms to send out a message: stream and // pipeline. // A stream is a receiver initialized long-polling connection, which // is always open to transfer messages. Besides general stream, peer also has // a optimized stream for sending msgApp since msgApp accounts for large part // of all messages. Only raft leader uses the optimized stream to send msgApp // to the remote follower node. // A pipeline is a series of http clients that send http requests to the remote. // It is only used when the stream has not been established. type peer struct { lg *zap.Logger localID types.ID // id of the remote raft peer node id types.ID r Raft status *peerStatus picker *urlPicker msgAppV2Writer *streamWriter writer *streamWriter pipeline *pipeline snapSender *snapshotSender // snapshot sender to send v3 snapshot messages msgAppV2Reader *streamReader msgAppReader *streamReader recvc chan raftpb.Message propc chan raftpb.Message mu sync.Mutex paused bool cancel context.CancelFunc // cancel pending works in go routine created by peer. stopc chan struct{} } func startPeer(t *Transport, urls types.URLs, peerID types.ID, fs *stats.FollowerStats) *peer { if t.Logger != nil { t.Logger.Info("starting remote peer", zap.String("remote-peer-id", peerID.String())) } defer func() { if t.Logger != nil { t.Logger.Info("started remote peer", zap.String("remote-peer-id", peerID.String())) } }() status := newPeerStatus(t.Logger, t.ID, peerID) picker := newURLPicker(urls) errorc := t.ErrorC r := t.Raft pipeline := &pipeline{ peerID: peerID, tr: t, picker: picker, status: status, followerStats: fs, raft: r, errorc: errorc, } pipeline.start() p := &peer{ lg: t.Logger, localID: t.ID, id: peerID, r: r, status: status, picker: picker, msgAppV2Writer: startStreamWriter(t.Logger, t.ID, peerID, status, fs, r), writer: startStreamWriter(t.Logger, t.ID, peerID, status, fs, r), pipeline: pipeline, snapSender: newSnapshotSender(t, picker, peerID, status), recvc: make(chan raftpb.Message, recvBufSize), propc: make(chan raftpb.Message, maxPendingProposals), stopc: make(chan struct{}), } ctx, cancel := context.WithCancel(context.Background()) p.cancel = cancel go func() { for { select { case mm := <-p.recvc: if err := r.Process(ctx, mm); err != nil { if t.Logger != nil { t.Logger.Warn("failed to process Raft message", zap.Error(err)) } } case <-p.stopc: return } } }() // r.Process might block for processing proposal when there is no leader. // Thus propc must be put into a separate routine with recvc to avoid blocking // processing other raft messages. go func() { for { select { case mm := <-p.propc: if err := r.Process(ctx, mm); err != nil { if t.Logger != nil { t.Logger.Warn("failed to process Raft message", zap.Error(err)) } } case <-p.stopc: return } } }() p.msgAppV2Reader = &streamReader{ lg: t.Logger, peerID: peerID, typ: streamTypeMsgAppV2, tr: t, picker: picker, status: status, recvc: p.recvc, propc: p.propc, rl: rate.NewLimiter(t.DialRetryFrequency, 1), } p.msgAppReader = &streamReader{ lg: t.Logger, peerID: peerID, typ: streamTypeMessage, tr: t, picker: picker, status: status, recvc: p.recvc, propc: p.propc, rl: rate.NewLimiter(t.DialRetryFrequency, 1), } p.msgAppV2Reader.start() p.msgAppReader.start() return p } func (p *peer) send(m raftpb.Message) { p.mu.Lock() paused := p.paused p.mu.Unlock() if paused { return } writec, name := p.pick(m) select { case writec <- m: default: p.r.ReportUnreachable(m.To) if isMsgSnap(m) { p.r.ReportSnapshot(m.To, raft.SnapshotFailure) } if p.status.isActive() { if p.lg != nil { p.lg.Warn( "dropped internal Raft message since sending buffer is full (overloaded network)", zap.String("message-type", m.Type.String()), zap.String("local-member-id", p.localID.String()), zap.String("from", types.ID(m.From).String()), zap.String("remote-peer-id", p.id.String()), zap.String("remote-peer-name", name), zap.Bool("remote-peer-active", p.status.isActive()), ) } } else { if p.lg != nil { p.lg.Warn( "dropped internal Raft message since sending buffer is full (overloaded network)", zap.String("message-type", m.Type.String()), zap.String("local-member-id", p.localID.String()), zap.String("from", types.ID(m.From).String()), zap.String("remote-peer-id", p.id.String()), zap.String("remote-peer-name", name), zap.Bool("remote-peer-active", p.status.isActive()), ) } } sentFailures.WithLabelValues(types.ID(m.To).String()).Inc() } } func (p *peer) sendSnap(m snap.Message) { go p.snapSender.send(m) } func (p *peer) update(urls types.URLs) { p.picker.update(urls) } func (p *peer) attachOutgoingConn(conn *outgoingConn) { var ok bool switch conn.t { case streamTypeMsgAppV2: ok = p.msgAppV2Writer.attach(conn) case streamTypeMessage: ok = p.writer.attach(conn) default: if p.lg != nil { p.lg.Panic("unknown stream type", zap.String("type", conn.t.String())) } } if !ok { conn.Close() } } func (p *peer) activeSince() time.Time { return p.status.activeSince() } // Pause pauses the peer. The peer will simply drops all incoming // messages without returning an error. func (p *peer) Pause() { p.mu.Lock() defer p.mu.Unlock() p.paused = true p.msgAppReader.pause() p.msgAppV2Reader.pause() } // Resume resumes a paused peer. func (p *peer) Resume() { p.mu.Lock() defer p.mu.Unlock() p.paused = false p.msgAppReader.resume() p.msgAppV2Reader.resume() } func (p *peer) stop() { if p.lg != nil { p.lg.Info("stopping remote peer", zap.String("remote-peer-id", p.id.String())) } defer func() { if p.lg != nil { p.lg.Info("stopped remote peer", zap.String("remote-peer-id", p.id.String())) } }() close(p.stopc) p.cancel() p.msgAppV2Writer.stop() p.writer.stop() p.pipeline.stop() p.snapSender.stop() p.msgAppV2Reader.stop() p.msgAppReader.stop() } // pick picks a chan for sending the given message. The picked chan and the picked chan // string name are returned. func (p *peer) pick(m raftpb.Message) (writec chan<- raftpb.Message, picked string) { var ok bool // Considering MsgSnap may have a big size, e.g., 1G, and will block // stream for a long time, only use one of the N pipelines to send MsgSnap. if isMsgSnap(m) { return p.pipeline.msgc, pipelineMsg } else if writec, ok = p.msgAppV2Writer.writec(); ok && isMsgApp(m) { return writec, streamAppV2 } else if writec, ok = p.writer.writec(); ok { return writec, streamMsg } return p.pipeline.msgc, pipelineMsg } func isMsgApp(m raftpb.Message) bool { return m.Type == raftpb.MsgApp } func isMsgSnap(m raftpb.Message) bool { return m.Type == raftpb.MsgSnap }
vendor/go.etcd.io/etcd/server/v3/etcdserver/api/rafthttp/peer.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.00018475373508408666, 0.00016934207815211266, 0.00016342215531039983, 0.0001678245171206072, 0.000004760330284625525 ]
{ "id": 8, "code_window": [ "\t}\n", "\tfor _, listener := range listeners {\n", "\t\tlistener.Close()\n", "\t}\n", "\n", "\terrCh := make(chan error)\n", "\tgo func() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\terrCh = make(chan error)\n" ], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "replace", "edit_start_line_idx": 137 }
/* Copyright 2015 The Kubernetes 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 secret import ( "testing" apitesting "k8s.io/kubernetes/pkg/api/testing" api "k8s.io/kubernetes/pkg/apis/core" // ensure types are installed _ "k8s.io/kubernetes/pkg/apis/core/install" ) func TestSelectableFieldLabelConversions(t *testing.T) { apitesting.TestSelectableFieldLabelConversionsOfKind(t, "v1", "Secret", SelectableFields(&api.Secret{}), nil, ) }
pkg/registry/core/secret/strategy_test.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.0001798085868358612, 0.00017530059267301112, 0.0001666419702814892, 0.00017737591406330466, 0.000005280830919218715 ]
{ "id": 8, "code_window": [ "\t}\n", "\tfor _, listener := range listeners {\n", "\t\tlistener.Close()\n", "\t}\n", "\n", "\terrCh := make(chan error)\n", "\tgo func() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\terrCh = make(chan error)\n" ], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "replace", "edit_start_line_idx": 137 }
// Copyright 2015 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. //go:build gccgo && !aix // +build gccgo,!aix package unix import "syscall" // We can't use the gc-syntax .s files for gccgo. On the plus side // much of the functionality can be written directly in Go. func realSyscallNoError(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r uintptr) func realSyscall(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r, errno uintptr) func SyscallNoError(trap, a1, a2, a3 uintptr) (r1, r2 uintptr) { syscall.Entersyscall() r := realSyscallNoError(trap, a1, a2, a3, 0, 0, 0, 0, 0, 0) syscall.Exitsyscall() return r, 0 } func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) { syscall.Entersyscall() r, errno := realSyscall(trap, a1, a2, a3, 0, 0, 0, 0, 0, 0) syscall.Exitsyscall() return r, 0, syscall.Errno(errno) } func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) { syscall.Entersyscall() r, errno := realSyscall(trap, a1, a2, a3, a4, a5, a6, 0, 0, 0) syscall.Exitsyscall() return r, 0, syscall.Errno(errno) } func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) { syscall.Entersyscall() r, errno := realSyscall(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9) syscall.Exitsyscall() return r, 0, syscall.Errno(errno) } func RawSyscallNoError(trap, a1, a2, a3 uintptr) (r1, r2 uintptr) { r := realSyscallNoError(trap, a1, a2, a3, 0, 0, 0, 0, 0, 0) return r, 0 } func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) { r, errno := realSyscall(trap, a1, a2, a3, 0, 0, 0, 0, 0, 0) return r, 0, syscall.Errno(errno) } func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) { r, errno := realSyscall(trap, a1, a2, a3, a4, a5, a6, 0, 0, 0) return r, 0, syscall.Errno(errno) }
vendor/golang.org/x/sys/unix/gccgo.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.0003311510372441262, 0.00020637451962102205, 0.00016680205590091646, 0.00018913872190751135, 0.00005232168041402474 ]
{ "id": 9, "code_window": [ "\tgo func() {\n", "\t\tcommand.SetArgs(commandArgs)\n", "\t\tif err := command.Execute(); err != nil {\n", "\t\t\terrCh <- err\n", "\t\t}\n" ], "labels": [ "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tdefer close(errCh)\n", "\n" ], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 139 }
/* Copyright 2018 The Kubernetes 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 testing import ( "context" "fmt" "io/ioutil" "net" "os" "strings" "time" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes" restclient "k8s.io/client-go/rest" cloudprovider "k8s.io/cloud-provider" "k8s.io/cloud-provider/app" "k8s.io/cloud-provider/app/config" "k8s.io/cloud-provider/options" cliflag "k8s.io/component-base/cli/flag" ) // TearDownFunc is to be called to tear down a test server. type TearDownFunc func() // TestServer return values supplied by kube-test-ApiServer type TestServer struct { LoopbackClientConfig *restclient.Config // Rest client config using the magic token Options *options.CloudControllerManagerOptions Config *config.CompletedConfig TearDownFn TearDownFunc // TearDown function TmpDir string // Temp Dir used, by the apiserver } // Logger allows t.Testing and b.Testing to be passed to StartTestServer and StartTestServerOrDie type Logger interface { Errorf(format string, args ...interface{}) Fatalf(format string, args ...interface{}) Logf(format string, args ...interface{}) } // StartTestServer starts a cloud-controller-manager. A rest client config and a tear-down func, // and location of the tmpdir are returned. // // Note: we return a tear-down func instead of a stop channel because the later will leak temporary // files that because Golang testing's call to os.Exit will not give a stop channel go routine // enough time to remove temporary files. func StartTestServer(t Logger, customFlags []string) (result TestServer, err error) { stopCh := make(chan struct{}) configDoneCh := make(chan struct{}) var capturedConfig config.CompletedConfig tearDown := func() { close(stopCh) if len(result.TmpDir) != 0 { os.RemoveAll(result.TmpDir) } } defer func() { if result.TearDownFn == nil { tearDown() } }() result.TmpDir, err = ioutil.TempDir("", "cloud-controller-manager") if err != nil { return result, fmt.Errorf("failed to create temp dir: %v", err) } s, err := options.NewCloudControllerManagerOptions() if err != nil { return TestServer{}, err } cloudInitializer := func(config *config.CompletedConfig) cloudprovider.Interface { capturedConfig = *config // send signal to indicate the capturedConfig has been properly set close(configDoneCh) cloudConfig := config.ComponentConfig.KubeCloudShared.CloudProvider cloud, err := cloudprovider.InitCloudProvider(cloudConfig.Name, cloudConfig.CloudConfigFile) if err != nil { t.Fatalf("Cloud provider could not be initialized: %v", err) } s.SecureServing.ServerCert.CertDirectory = result.TmpDir if cloud == nil { t.Fatalf("Cloud provider is nil") } return cloud } fss := cliflag.NamedFlagSets{} command := app.NewCloudControllerManagerCommand(s, cloudInitializer, app.DefaultInitFuncConstructors, fss, stopCh) commandArgs := []string{} listeners := []net.Listener{} disableSecure := false for _, arg := range customFlags { if strings.HasPrefix(arg, "--secure-port=") { if arg == "--secure-port=0" { commandArgs = append(commandArgs, arg) disableSecure = true } } else if strings.HasPrefix(arg, "--cert-dir=") { // skip it } else { commandArgs = append(commandArgs, arg) } } if !disableSecure { listener, bindPort, err := createListenerOnFreePort() if err != nil { return result, fmt.Errorf("failed to create listener: %v", err) } listeners = append(listeners, listener) commandArgs = append(commandArgs, fmt.Sprintf("--secure-port=%d", bindPort)) commandArgs = append(commandArgs, fmt.Sprintf("--cert-dir=%s", result.TmpDir)) t.Logf("cloud-controller-manager will listen securely on port %d...", bindPort) } for _, listener := range listeners { listener.Close() } errCh := make(chan error) go func() { command.SetArgs(commandArgs) if err := command.Execute(); err != nil { errCh <- err } close(errCh) }() select { case <-configDoneCh: case err := <-errCh: return result, err } t.Logf("Waiting for /healthz to be ok...") client, err := kubernetes.NewForConfig(capturedConfig.LoopbackClientConfig) if err != nil { return result, fmt.Errorf("failed to create a client: %v", err) } err = wait.Poll(100*time.Millisecond, 30*time.Second, func() (bool, error) { select { case err := <-errCh: return false, err default: } result := client.CoreV1().RESTClient().Get().AbsPath("/healthz").Do(context.TODO()) status := 0 result.StatusCode(&status) if status == 200 { return true, nil } return false, nil }) if err != nil { return result, fmt.Errorf("failed to wait for /healthz to return ok: %v", err) } // from here the caller must call tearDown result.LoopbackClientConfig = capturedConfig.LoopbackClientConfig result.Options = s result.Config = &capturedConfig result.TearDownFn = tearDown return result, nil } // StartTestServerOrDie calls StartTestServer t.Fatal if it does not succeed. func StartTestServerOrDie(t Logger, flags []string) *TestServer { result, err := StartTestServer(t, flags) if err == nil { return &result } t.Fatalf("failed to launch server: %v", err) return nil } func createListenerOnFreePort() (net.Listener, int, error) { ln, err := net.Listen("tcp", ":0") if err != nil { return nil, 0, err } // get port tcpAddr, ok := ln.Addr().(*net.TCPAddr) if !ok { ln.Close() return nil, 0, fmt.Errorf("invalid listen address: %q", ln.Addr().String()) } return ln, tcpAddr.Port, nil }
staging/src/k8s.io/cloud-provider/app/testing/testserver.go
1
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.9758148789405823, 0.09224269539117813, 0.00016451108967885375, 0.0005767892580479383, 0.27606940269470215 ]
{ "id": 9, "code_window": [ "\tgo func() {\n", "\t\tcommand.SetArgs(commandArgs)\n", "\t\tif err := command.Execute(); err != nil {\n", "\t\t\terrCh <- err\n", "\t\t}\n" ], "labels": [ "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tdefer close(errCh)\n", "\n" ], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 139 }
/* Copyright 2015 The Kubernetes 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 testing import ( "testing" clientv3 "go.etcd.io/etcd/client/v3" "k8s.io/apiserver/pkg/storage/etcd3/testserver" "k8s.io/apiserver/pkg/storage/storagebackend" ) // EtcdTestServer encapsulates the datastructures needed to start local instance for testing type EtcdTestServer struct { V3Client *clientv3.Client } func (e *EtcdTestServer) Terminate(t *testing.T) { // no-op, server termination moved to test cleanup } // NewUnsecuredEtcd3TestClientServer creates a new client and server for testing func NewUnsecuredEtcd3TestClientServer(t *testing.T) (*EtcdTestServer, *storagebackend.Config) { server := &EtcdTestServer{} server.V3Client = testserver.RunEtcd(t, nil) config := &storagebackend.Config{ Type: "etcd3", Prefix: PathPrefix(), Transport: storagebackend.TransportConfig{ ServerList: server.V3Client.Endpoints(), }, Paging: true, } return server, config }
staging/src/k8s.io/apiserver/pkg/storage/etcd3/testing/test_server.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.00017829729767981917, 0.00017377740005031228, 0.00016670521290507168, 0.00017515392391942441, 0.000004368176178104477 ]
{ "id": 9, "code_window": [ "\tgo func() {\n", "\t\tcommand.SetArgs(commandArgs)\n", "\t\tif err := command.Execute(); err != nil {\n", "\t\t\terrCh <- err\n", "\t\t}\n" ], "labels": [ "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tdefer close(errCh)\n", "\n" ], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 139 }
# Please edit the 'last-applied-configuration' annotations below. # Lines beginning with a '#' will be ignored, and an empty file will abort the edit. # # The edited file had a syntax error: unable to get type info from the object "*unstructured.Unstructured": Object 'apiVersion' is missing in 'object has no apiVersion field' # apiVersion: v1 items: - apiVersion: v1 data: baz: qux foo: changed-value new-data: new-value new-data2: new-value new-data3: newivalue kind: ConfigMap metadata: annotations: {} name: cm1 namespace: myproject - kind: Service metadata: annotations: {} labels: app: svc1 new-label: foo new-label2: foo2 name: svc1 namespace: myproject spec: ports: - name: "80" port: 82 protocol: TCP targetPort: 81 sessionAffinity: None type: ClusterIP status: loadBalancer: {} kind: List metadata: {}
staging/src/k8s.io/kubectl/pkg/cmd/edit/testdata/testcase-apply-edit-last-applied-list-fail/3.original
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.00017849939467851073, 0.00017560487322043628, 0.00017231274978257716, 0.00017607331392355263, 0.0000023314953523367876 ]
{ "id": 9, "code_window": [ "\tgo func() {\n", "\t\tcommand.SetArgs(commandArgs)\n", "\t\tif err := command.Execute(); err != nil {\n", "\t\t\terrCh <- err\n", "\t\t}\n" ], "labels": [ "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tdefer close(errCh)\n", "\n" ], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "add", "edit_start_line_idx": 139 }
/* Copyright 2014 The Kubernetes 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 hostutil import ( "fmt" "os" "k8s.io/mount-utils" ) // FileType enumerates the known set of possible file types. type FileType string const ( // FileTypeBlockDev defines a constant for the block device FileType. FileTypeBlockDev FileType = "BlockDevice" // FileTypeCharDev defines a constant for the character device FileType. FileTypeCharDev FileType = "CharDevice" // FileTypeDirectory defines a constant for the directory FileType. FileTypeDirectory FileType = "Directory" // FileTypeFile defines a constant for the file FileType. FileTypeFile FileType = "File" // FileTypeSocket defines a constant for the socket FileType. FileTypeSocket FileType = "Socket" // FileTypeUnknown defines a constant for an unknown FileType. FileTypeUnknown FileType = "" ) // HostUtils defines the set of methods for interacting with paths on a host. type HostUtils interface { // DeviceOpened determines if the device (e.g. /dev/sdc) is in use elsewhere // on the system, i.e. still mounted. DeviceOpened(pathname string) (bool, error) // PathIsDevice determines if a path is a device. PathIsDevice(pathname string) (bool, error) // GetDeviceNameFromMount finds the device name by checking the mount path // to get the global mount path within its plugin directory. GetDeviceNameFromMount(mounter mount.Interface, mountPath, pluginMountDir string) (string, error) // MakeRShared checks that given path is on a mount with 'rshared' mount // propagation. If not, it bind-mounts the path as rshared. MakeRShared(path string) error // GetFileType checks for file/directory/socket/block/character devices. GetFileType(pathname string) (FileType, error) // PathExists tests if the given path already exists // Error is returned on any other error than "file not found". PathExists(pathname string) (bool, error) // EvalHostSymlinks returns the path name after evaluating symlinks. EvalHostSymlinks(pathname string) (string, error) // GetOwner returns the integer ID for the user and group of the given path GetOwner(pathname string) (int64, int64, error) // GetSELinuxSupport returns true if given path is on a mount that supports // SELinux. GetSELinuxSupport(pathname string) (bool, error) // GetMode returns permissions of the path. GetMode(pathname string) (os.FileMode, error) } // Compile-time check to ensure all HostUtil implementations satisfy // the Interface. var _ HostUtils = &HostUtil{} // getFileType checks for file/directory/socket and block/character devices. func getFileType(pathname string) (FileType, error) { var pathType FileType info, err := os.Stat(pathname) if os.IsNotExist(err) { return pathType, fmt.Errorf("path %q does not exist", pathname) } // err in call to os.Stat if err != nil { return pathType, err } // checks whether the mode is the target mode. isSpecificMode := func(mode, targetMode os.FileMode) bool { return mode&targetMode == targetMode } mode := info.Mode() if mode.IsDir() { return FileTypeDirectory, nil } else if mode.IsRegular() { return FileTypeFile, nil } else if isSpecificMode(mode, os.ModeSocket) { return FileTypeSocket, nil } else if isSpecificMode(mode, os.ModeDevice) { if isSpecificMode(mode, os.ModeCharDevice) { return FileTypeCharDev, nil } return FileTypeBlockDev, nil } return pathType, fmt.Errorf("only recognise file, directory, socket, block device and character device") }
pkg/volume/util/hostutil/hostutil.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.9433736801147461, 0.0859193354845047, 0.0001661963906371966, 0.000171188497915864, 0.2711508870124817 ]
{ "id": 10, "code_window": [ "\t\tcommand.SetArgs(commandArgs)\n", "\t\tif err := command.Execute(); err != nil {\n", "\t\t\terrCh <- err\n", "\t\t}\n", "\t\tclose(errCh)\n", "\t}()\n", "\n", "\tselect {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "replace", "edit_start_line_idx": 143 }
/* Copyright 2018 The Kubernetes 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 testing import ( "context" "fmt" "io/ioutil" "net" "os" "strings" "time" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes" restclient "k8s.io/client-go/rest" cloudprovider "k8s.io/cloud-provider" "k8s.io/cloud-provider/app" "k8s.io/cloud-provider/app/config" "k8s.io/cloud-provider/options" cliflag "k8s.io/component-base/cli/flag" ) // TearDownFunc is to be called to tear down a test server. type TearDownFunc func() // TestServer return values supplied by kube-test-ApiServer type TestServer struct { LoopbackClientConfig *restclient.Config // Rest client config using the magic token Options *options.CloudControllerManagerOptions Config *config.CompletedConfig TearDownFn TearDownFunc // TearDown function TmpDir string // Temp Dir used, by the apiserver } // Logger allows t.Testing and b.Testing to be passed to StartTestServer and StartTestServerOrDie type Logger interface { Errorf(format string, args ...interface{}) Fatalf(format string, args ...interface{}) Logf(format string, args ...interface{}) } // StartTestServer starts a cloud-controller-manager. A rest client config and a tear-down func, // and location of the tmpdir are returned. // // Note: we return a tear-down func instead of a stop channel because the later will leak temporary // files that because Golang testing's call to os.Exit will not give a stop channel go routine // enough time to remove temporary files. func StartTestServer(t Logger, customFlags []string) (result TestServer, err error) { stopCh := make(chan struct{}) configDoneCh := make(chan struct{}) var capturedConfig config.CompletedConfig tearDown := func() { close(stopCh) if len(result.TmpDir) != 0 { os.RemoveAll(result.TmpDir) } } defer func() { if result.TearDownFn == nil { tearDown() } }() result.TmpDir, err = ioutil.TempDir("", "cloud-controller-manager") if err != nil { return result, fmt.Errorf("failed to create temp dir: %v", err) } s, err := options.NewCloudControllerManagerOptions() if err != nil { return TestServer{}, err } cloudInitializer := func(config *config.CompletedConfig) cloudprovider.Interface { capturedConfig = *config // send signal to indicate the capturedConfig has been properly set close(configDoneCh) cloudConfig := config.ComponentConfig.KubeCloudShared.CloudProvider cloud, err := cloudprovider.InitCloudProvider(cloudConfig.Name, cloudConfig.CloudConfigFile) if err != nil { t.Fatalf("Cloud provider could not be initialized: %v", err) } s.SecureServing.ServerCert.CertDirectory = result.TmpDir if cloud == nil { t.Fatalf("Cloud provider is nil") } return cloud } fss := cliflag.NamedFlagSets{} command := app.NewCloudControllerManagerCommand(s, cloudInitializer, app.DefaultInitFuncConstructors, fss, stopCh) commandArgs := []string{} listeners := []net.Listener{} disableSecure := false for _, arg := range customFlags { if strings.HasPrefix(arg, "--secure-port=") { if arg == "--secure-port=0" { commandArgs = append(commandArgs, arg) disableSecure = true } } else if strings.HasPrefix(arg, "--cert-dir=") { // skip it } else { commandArgs = append(commandArgs, arg) } } if !disableSecure { listener, bindPort, err := createListenerOnFreePort() if err != nil { return result, fmt.Errorf("failed to create listener: %v", err) } listeners = append(listeners, listener) commandArgs = append(commandArgs, fmt.Sprintf("--secure-port=%d", bindPort)) commandArgs = append(commandArgs, fmt.Sprintf("--cert-dir=%s", result.TmpDir)) t.Logf("cloud-controller-manager will listen securely on port %d...", bindPort) } for _, listener := range listeners { listener.Close() } errCh := make(chan error) go func() { command.SetArgs(commandArgs) if err := command.Execute(); err != nil { errCh <- err } close(errCh) }() select { case <-configDoneCh: case err := <-errCh: return result, err } t.Logf("Waiting for /healthz to be ok...") client, err := kubernetes.NewForConfig(capturedConfig.LoopbackClientConfig) if err != nil { return result, fmt.Errorf("failed to create a client: %v", err) } err = wait.Poll(100*time.Millisecond, 30*time.Second, func() (bool, error) { select { case err := <-errCh: return false, err default: } result := client.CoreV1().RESTClient().Get().AbsPath("/healthz").Do(context.TODO()) status := 0 result.StatusCode(&status) if status == 200 { return true, nil } return false, nil }) if err != nil { return result, fmt.Errorf("failed to wait for /healthz to return ok: %v", err) } // from here the caller must call tearDown result.LoopbackClientConfig = capturedConfig.LoopbackClientConfig result.Options = s result.Config = &capturedConfig result.TearDownFn = tearDown return result, nil } // StartTestServerOrDie calls StartTestServer t.Fatal if it does not succeed. func StartTestServerOrDie(t Logger, flags []string) *TestServer { result, err := StartTestServer(t, flags) if err == nil { return &result } t.Fatalf("failed to launch server: %v", err) return nil } func createListenerOnFreePort() (net.Listener, int, error) { ln, err := net.Listen("tcp", ":0") if err != nil { return nil, 0, err } // get port tcpAddr, ok := ln.Addr().(*net.TCPAddr) if !ok { ln.Close() return nil, 0, fmt.Errorf("invalid listen address: %q", ln.Addr().String()) } return ln, tcpAddr.Port, nil }
staging/src/k8s.io/cloud-provider/app/testing/testserver.go
1
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.9190370440483093, 0.04233512654900551, 0.00016408560622949153, 0.0001747828646330163, 0.1913139373064041 ]
{ "id": 10, "code_window": [ "\t\tcommand.SetArgs(commandArgs)\n", "\t\tif err := command.Execute(); err != nil {\n", "\t\t\terrCh <- err\n", "\t\t}\n", "\t\tclose(errCh)\n", "\t}()\n", "\n", "\tselect {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "replace", "edit_start_line_idx": 143 }
# Container-Optimized OS [Container-Optimized OS](https://cloud.google.com/container-optimized-os/docs), (previously Google Container-VM image a.k.a GCI) is a container-optimized OS image for the Google Cloud Platform (GCP). It is primarily for running Google services on GCP. Container-Optimized OS is an open source OS based on the open source [ChromiumOS project](https://www.chromium.org/chromium-os), allowing us greater control over the build management, security compliance, and customizations for GCP. Container-Optimized OS is [open source](https://cos.googlesource.com), and is released on milestones. Example milestones are 81, 85. Each milestone will experience three release channels -- dev, beta and stable to reach stability. The promotion between those channels are about six weeks. Starting milestone 69, for every 4 milestones, the last milestone will be promoted into LTS image after it becomes stable. For details, please see COS's [Release Channels](https://cloud.google.com/container-optimized-os/docs/concepts/release-channels) and [Support Policy](https://cloud.google.com/container-optimized-os/docs/resources/support-policy). ## COS in End-to-End tests Container-Optimized OS images are used by kubernetes [End-to-End tests](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-testing/e2e-tests.md) and [Node End-to-End tests](https://github.com/kubernetes/community/tree/master/contributors/devel/sig-node). To see current active releases, please refer to COS's [Release Notes](https://cloud.google.com/container-optimized-os/docs/release-notes). ### How to choose an image in configuration file There are three ways to specify an image used by each testing suite: `image`, `image_regex` or `image_family`. * `image` is preferred, but manual updates are needed to use a newly released COS image, so the test suites don't use deprecated images. This will result to frequent yaml configuration file update everytime COS releases new image.One future option is to use an autobumper robot to update COS image automatically. e.g: ``` cos-stable: image: cos-77-12371-274-0 project: cos-cloud metadata: "user-data</go/src/github.com/containerd/cri/test/e2e_node/init.yaml,containerd-configure-sh</go/src/github.com/containerd/cri/cluster/gce/configure.sh,containerd-extra-init-sh</go/src/github.com/containerd/cri/test/e2e_node/gci-init.sh,containerd-env</workspace/test-infra/jobs/e2e_node/containerd/cri-master/env,gci-update-strategy=update_disabled" ``` * `image_family` should be used if you always want to use latest image in the same family. Tests will start to use new images once COS releases new image. This is not predictable and test can potentially be broken because of this. The probability of a breakage due to the OS itself is low for LTS or stable image, but high for dev or beta image. If things went wrong, it will be hard to rollback images using `image_regex` and `image_family`. e.g: ``` cos-stable: image_family: cos-77-lts project: cos-cloud metadata: "user-data</workspace/test-infra/jobs/e2e_node/containerd/init.yaml,cni-template</workspace/test-infra/jobs/e2e_node/containerd/cni.template,containerd-config</workspace/test-infra/jobs/e2e_node/containerd/config.toml" ``` * `image_regex` can also be used if you want image with the same naming pattern. Latest image will be chosen when multiple images match the regular expression. However, this option is rarely seen in the test code. * To update the images, using image in the same channel is preferred. Keep in mind, 69 is the first LTS image. Before that, COS only has dev, beta and stable images. That is why stable images are used quite frequently in current testing. For now, images should slowly migrate from stable to LTS if possible. For testing using dev or beta, we need to consider the original intention and keep using image in existing channel unless we understand the underlying reason. ### What image is needed for your test Consider the importance of tests and the stability of Container-Optimized OS, the following guidelines are proposed for image choice in E2E testing. * To run release blocking tests, the latest LTS images are preferred. 'image' should be used to specify the image. * To run presubmit, postsubmit or periodic tests, the latest LTS images are preferred. If tests need two images, you can use the latest two LTS images. LTS images are stable and usually include latest bug and security fix. 'image' should be used to specify the image. * To integrate continuously with other container related technologies like runc, containerd, docker and kubernertes, the latest LTS or stable images are preferred. 'image_family' should be used to specify the image. * To try out latest COS features, the latest dev or beta or stable images are preferred. 'image' or 'image_family' should be used to specify the image. ### How to find current COS image in each channel To find the current COS image, use the following command: ```shell $ gcloud compute images list --project=cos-cloud | grep cos-cloud cos-69-10895-385-0 cos-cloud cos-69-lts READY cos-73-11647-534-0 cos-cloud cos-73-lts READY cos-77-12371-274-0 cos-cloud cos-77-lts READY cos-81-12871-119-0 cos-cloud cos-81-lts READY cos-beta-81-12871-117-0 cos-cloud cos-beta READY cos-dev-84-13078-0-0 cos-cloud cos-dev READY cos-stable-81-12871-119-0 cos-cloud cos-stable READY ``` COS image will experience dev, beta, stable and LTS stage. Before LTS stage, image is named with its family as a prefix, e.g cos-dev, cos-beta, cos-stable. However, the milestone number in those families may change when channel promotions happen. Only when a milestone becomes LTS, the image will have a new family, and the milestone number in the image name stays the same. The image will be always there even after the milestone is deprecated.
cluster/gce/gci/README.md
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.00017446462879888713, 0.0001701724249869585, 0.00016504214727319777, 0.0001720152940833941, 0.0000030024827992747305 ]
{ "id": 10, "code_window": [ "\t\tcommand.SetArgs(commandArgs)\n", "\t\tif err := command.Execute(); err != nil {\n", "\t\t\terrCh <- err\n", "\t\t}\n", "\t\tclose(errCh)\n", "\t}()\n", "\n", "\tselect {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "replace", "edit_start_line_idx": 143 }
/* Copyright 2016 The Kubernetes 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 validation import ( "context" "errors" "fmt" "strings" "k8s.io/klog/v2" rbacv1 "k8s.io/api/rbac/v1" utilerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apiserver/pkg/authentication/serviceaccount" "k8s.io/apiserver/pkg/authentication/user" genericapirequest "k8s.io/apiserver/pkg/endpoints/request" "k8s.io/component-helpers/auth/rbac/validation" rbacv1helpers "k8s.io/kubernetes/pkg/apis/rbac/v1" ) type AuthorizationRuleResolver interface { // GetRoleReferenceRules attempts to resolve the role reference of a RoleBinding or ClusterRoleBinding. The passed namespace should be the namespace // of the role binding, the empty string if a cluster role binding. GetRoleReferenceRules(roleRef rbacv1.RoleRef, namespace string) ([]rbacv1.PolicyRule, error) // RulesFor returns the list of rules that apply to a given user in a given namespace and error. If an error is returned, the slice of // PolicyRules may not be complete, but it contains all retrievable rules. This is done because policy rules are purely additive and policy determinations // can be made on the basis of those rules that are found. RulesFor(user user.Info, namespace string) ([]rbacv1.PolicyRule, error) // VisitRulesFor invokes visitor() with each rule that applies to a given user in a given namespace, and each error encountered resolving those rules. // If visitor() returns false, visiting is short-circuited. VisitRulesFor(user user.Info, namespace string, visitor func(source fmt.Stringer, rule *rbacv1.PolicyRule, err error) bool) } // ConfirmNoEscalation determines if the roles for a given user in a given namespace encompass the provided role. func ConfirmNoEscalation(ctx context.Context, ruleResolver AuthorizationRuleResolver, rules []rbacv1.PolicyRule) error { ruleResolutionErrors := []error{} user, ok := genericapirequest.UserFrom(ctx) if !ok { return fmt.Errorf("no user on context") } namespace, _ := genericapirequest.NamespaceFrom(ctx) ownerRules, err := ruleResolver.RulesFor(user, namespace) if err != nil { // As per AuthorizationRuleResolver contract, this may return a non fatal error with an incomplete list of policies. Log the error and continue. klog.V(1).Infof("non-fatal error getting local rules for %v: %v", user, err) ruleResolutionErrors = append(ruleResolutionErrors, err) } ownerRightsCover, missingRights := validation.Covers(ownerRules, rules) if !ownerRightsCover { compactMissingRights := missingRights if compact, err := CompactRules(missingRights); err == nil { compactMissingRights = compact } missingDescriptions := sets.NewString() for _, missing := range compactMissingRights { missingDescriptions.Insert(rbacv1helpers.CompactString(missing)) } msg := fmt.Sprintf("user %q (groups=%q) is attempting to grant RBAC permissions not currently held:\n%s", user.GetName(), user.GetGroups(), strings.Join(missingDescriptions.List(), "\n")) if len(ruleResolutionErrors) > 0 { msg = msg + fmt.Sprintf("; resolution errors: %v", ruleResolutionErrors) } return errors.New(msg) } return nil } type DefaultRuleResolver struct { roleGetter RoleGetter roleBindingLister RoleBindingLister clusterRoleGetter ClusterRoleGetter clusterRoleBindingLister ClusterRoleBindingLister } func NewDefaultRuleResolver(roleGetter RoleGetter, roleBindingLister RoleBindingLister, clusterRoleGetter ClusterRoleGetter, clusterRoleBindingLister ClusterRoleBindingLister) *DefaultRuleResolver { return &DefaultRuleResolver{roleGetter, roleBindingLister, clusterRoleGetter, clusterRoleBindingLister} } type RoleGetter interface { GetRole(namespace, name string) (*rbacv1.Role, error) } type RoleBindingLister interface { ListRoleBindings(namespace string) ([]*rbacv1.RoleBinding, error) } type ClusterRoleGetter interface { GetClusterRole(name string) (*rbacv1.ClusterRole, error) } type ClusterRoleBindingLister interface { ListClusterRoleBindings() ([]*rbacv1.ClusterRoleBinding, error) } func (r *DefaultRuleResolver) RulesFor(user user.Info, namespace string) ([]rbacv1.PolicyRule, error) { visitor := &ruleAccumulator{} r.VisitRulesFor(user, namespace, visitor.visit) return visitor.rules, utilerrors.NewAggregate(visitor.errors) } type ruleAccumulator struct { rules []rbacv1.PolicyRule errors []error } func (r *ruleAccumulator) visit(source fmt.Stringer, rule *rbacv1.PolicyRule, err error) bool { if rule != nil { r.rules = append(r.rules, *rule) } if err != nil { r.errors = append(r.errors, err) } return true } func describeSubject(s *rbacv1.Subject, bindingNamespace string) string { switch s.Kind { case rbacv1.ServiceAccountKind: if len(s.Namespace) > 0 { return fmt.Sprintf("%s %q", s.Kind, s.Name+"/"+s.Namespace) } return fmt.Sprintf("%s %q", s.Kind, s.Name+"/"+bindingNamespace) default: return fmt.Sprintf("%s %q", s.Kind, s.Name) } } type clusterRoleBindingDescriber struct { binding *rbacv1.ClusterRoleBinding subject *rbacv1.Subject } func (d *clusterRoleBindingDescriber) String() string { return fmt.Sprintf("ClusterRoleBinding %q of %s %q to %s", d.binding.Name, d.binding.RoleRef.Kind, d.binding.RoleRef.Name, describeSubject(d.subject, ""), ) } type roleBindingDescriber struct { binding *rbacv1.RoleBinding subject *rbacv1.Subject } func (d *roleBindingDescriber) String() string { return fmt.Sprintf("RoleBinding %q of %s %q to %s", d.binding.Name+"/"+d.binding.Namespace, d.binding.RoleRef.Kind, d.binding.RoleRef.Name, describeSubject(d.subject, d.binding.Namespace), ) } func (r *DefaultRuleResolver) VisitRulesFor(user user.Info, namespace string, visitor func(source fmt.Stringer, rule *rbacv1.PolicyRule, err error) bool) { if clusterRoleBindings, err := r.clusterRoleBindingLister.ListClusterRoleBindings(); err != nil { if !visitor(nil, nil, err) { return } } else { sourceDescriber := &clusterRoleBindingDescriber{} for _, clusterRoleBinding := range clusterRoleBindings { subjectIndex, applies := appliesTo(user, clusterRoleBinding.Subjects, "") if !applies { continue } rules, err := r.GetRoleReferenceRules(clusterRoleBinding.RoleRef, "") if err != nil { if !visitor(nil, nil, err) { return } continue } sourceDescriber.binding = clusterRoleBinding sourceDescriber.subject = &clusterRoleBinding.Subjects[subjectIndex] for i := range rules { if !visitor(sourceDescriber, &rules[i], nil) { return } } } } if len(namespace) > 0 { if roleBindings, err := r.roleBindingLister.ListRoleBindings(namespace); err != nil { if !visitor(nil, nil, err) { return } } else { sourceDescriber := &roleBindingDescriber{} for _, roleBinding := range roleBindings { subjectIndex, applies := appliesTo(user, roleBinding.Subjects, namespace) if !applies { continue } rules, err := r.GetRoleReferenceRules(roleBinding.RoleRef, namespace) if err != nil { if !visitor(nil, nil, err) { return } continue } sourceDescriber.binding = roleBinding sourceDescriber.subject = &roleBinding.Subjects[subjectIndex] for i := range rules { if !visitor(sourceDescriber, &rules[i], nil) { return } } } } } } // GetRoleReferenceRules attempts to resolve the RoleBinding or ClusterRoleBinding. func (r *DefaultRuleResolver) GetRoleReferenceRules(roleRef rbacv1.RoleRef, bindingNamespace string) ([]rbacv1.PolicyRule, error) { switch roleRef.Kind { case "Role": role, err := r.roleGetter.GetRole(bindingNamespace, roleRef.Name) if err != nil { return nil, err } return role.Rules, nil case "ClusterRole": clusterRole, err := r.clusterRoleGetter.GetClusterRole(roleRef.Name) if err != nil { return nil, err } return clusterRole.Rules, nil default: return nil, fmt.Errorf("unsupported role reference kind: %q", roleRef.Kind) } } // appliesTo returns whether any of the bindingSubjects applies to the specified subject, // and if true, the index of the first subject that applies func appliesTo(user user.Info, bindingSubjects []rbacv1.Subject, namespace string) (int, bool) { for i, bindingSubject := range bindingSubjects { if appliesToUser(user, bindingSubject, namespace) { return i, true } } return 0, false } func has(set []string, ele string) bool { for _, s := range set { if s == ele { return true } } return false } func appliesToUser(user user.Info, subject rbacv1.Subject, namespace string) bool { switch subject.Kind { case rbacv1.UserKind: return user.GetName() == subject.Name case rbacv1.GroupKind: return has(user.GetGroups(), subject.Name) case rbacv1.ServiceAccountKind: // default the namespace to namespace we're working in if its available. This allows rolebindings that reference // SAs in th local namespace to avoid having to qualify them. saNamespace := namespace if len(subject.Namespace) > 0 { saNamespace = subject.Namespace } if len(saNamespace) == 0 { return false } // use a more efficient comparison for RBAC checking return serviceaccount.MatchesUsername(saNamespace, subject.Name, user.GetName()) default: return false } } // NewTestRuleResolver returns a rule resolver from lists of role objects. func NewTestRuleResolver(roles []*rbacv1.Role, roleBindings []*rbacv1.RoleBinding, clusterRoles []*rbacv1.ClusterRole, clusterRoleBindings []*rbacv1.ClusterRoleBinding) (AuthorizationRuleResolver, *StaticRoles) { r := StaticRoles{ roles: roles, roleBindings: roleBindings, clusterRoles: clusterRoles, clusterRoleBindings: clusterRoleBindings, } return newMockRuleResolver(&r), &r } func newMockRuleResolver(r *StaticRoles) AuthorizationRuleResolver { return NewDefaultRuleResolver(r, r, r, r) } // StaticRoles is a rule resolver that resolves from lists of role objects. type StaticRoles struct { roles []*rbacv1.Role roleBindings []*rbacv1.RoleBinding clusterRoles []*rbacv1.ClusterRole clusterRoleBindings []*rbacv1.ClusterRoleBinding } func (r *StaticRoles) GetRole(namespace, name string) (*rbacv1.Role, error) { if len(namespace) == 0 { return nil, errors.New("must provide namespace when getting role") } for _, role := range r.roles { if role.Namespace == namespace && role.Name == name { return role, nil } } return nil, errors.New("role not found") } func (r *StaticRoles) GetClusterRole(name string) (*rbacv1.ClusterRole, error) { for _, clusterRole := range r.clusterRoles { if clusterRole.Name == name { return clusterRole, nil } } return nil, errors.New("clusterrole not found") } func (r *StaticRoles) ListRoleBindings(namespace string) ([]*rbacv1.RoleBinding, error) { if len(namespace) == 0 { return nil, errors.New("must provide namespace when listing role bindings") } roleBindingList := []*rbacv1.RoleBinding{} for _, roleBinding := range r.roleBindings { if roleBinding.Namespace != namespace { continue } // TODO(ericchiang): need to implement label selectors? roleBindingList = append(roleBindingList, roleBinding) } return roleBindingList, nil } func (r *StaticRoles) ListClusterRoleBindings() ([]*rbacv1.ClusterRoleBinding, error) { return r.clusterRoleBindings, nil }
pkg/registry/rbac/validation/rule.go
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.001509253866970539, 0.00021897077385801822, 0.00016489507106598467, 0.0001743462198646739, 0.00021677493350580335 ]
{ "id": 10, "code_window": [ "\t\tcommand.SetArgs(commandArgs)\n", "\t\tif err := command.Execute(); err != nil {\n", "\t\t\terrCh <- err\n", "\t\t}\n", "\t\tclose(errCh)\n", "\t}()\n", "\n", "\tselect {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "staging/src/k8s.io/cloud-provider/app/testing/testserver.go", "type": "replace", "edit_start_line_idx": 143 }
apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: standard annotations: storageclass.kubernetes.io/is-default-class: "true" labels: addonmanager.kubernetes.io/mode: EnsureExists provisioner: kubernetes.io/cinder
cluster/addons/storage-class/openstack/default.yaml
0
https://github.com/kubernetes/kubernetes/commit/1f4f98e40d9d2a8f30051b780c877cb4fbb04170
[ 0.0001741790765663609, 0.0001741790765663609, 0.0001741790765663609, 0.0001741790765663609, 0 ]
{ "id": 0, "code_window": [ ".SH DESCRIPTION\n", ".PP\n", "Displays merged kubeconfig settings or a specified kubeconfig file.\n", "\n", ".PP\n", "You can use \\-\\-output=template \\-\\-template=TEMPLATE to extract specific values.\n", "\n", "\n", ".SH OPTIONS\n", ".PP\n", "\\fB\\-\\-flatten\\fP=false\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "You can use \\-\\-output jsonpath={...} to extract specific values using a jsonpath expression.\n" ], "file_path": "docs/man/man1/kubectl-config-view.1", "type": "replace", "edit_start_line_idx": 18 }
/* Copyright 2014 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package config import ( "errors" "fmt" "io" "github.com/spf13/cobra" "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/latest" "k8s.io/kubernetes/pkg/kubectl" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "k8s.io/kubernetes/pkg/util" ) type ViewOptions struct { ConfigAccess ConfigAccess Merge util.BoolFlag Flatten bool Minify bool RawByteData bool } const ( view_long = `Displays merged kubeconfig settings or a specified kubeconfig file. You can use --output=template --template=TEMPLATE to extract specific values.` view_example = `# Show Merged kubeconfig settings. $ kubectl config view # Get the password for the e2e user $ kubectl config view -o template --template='{{range .users}}{{ if eq .name "e2e" }}{{ index .user.password }}{{end}}{{end}}'` ) func NewCmdConfigView(out io.Writer, ConfigAccess ConfigAccess) *cobra.Command { options := &ViewOptions{ConfigAccess: ConfigAccess} // Default to yaml defaultOutputFormat := "yaml" cmd := &cobra.Command{ Use: "view", Short: "Displays merged kubeconfig settings or a specified kubeconfig file.", Long: view_long, Example: view_example, Run: func(cmd *cobra.Command, args []string) { options.Complete() outputFormat := cmdutil.GetFlagString(cmd, "output") if outputFormat == "wide" { fmt.Printf("--output wide is not available in kubectl config view; reset to default output format (%s)\n\n", defaultOutputFormat) cmd.Flags().Set("output", defaultOutputFormat) } printer, _, err := cmdutil.PrinterForCommand(cmd) cmdutil.CheckErr(err) version, err := cmdutil.OutputVersion(cmd, &latest.ExternalVersion) cmdutil.CheckErr(err) printer = kubectl.NewVersionedPrinter(printer, clientcmdapi.Scheme, version) cmdutil.CheckErr(options.Run(out, printer)) }, } cmdutil.AddPrinterFlags(cmd) cmd.Flags().Set("output", defaultOutputFormat) options.Merge.Default(true) f := cmd.Flags().VarPF(&options.Merge, "merge", "", "merge together the full hierarchy of kubeconfig files") f.NoOptDefVal = "true" cmd.Flags().BoolVar(&options.RawByteData, "raw", false, "display raw byte data") cmd.Flags().BoolVar(&options.Flatten, "flatten", false, "flatten the resulting kubeconfig file into self contained output (useful for creating portable kubeconfig files)") cmd.Flags().BoolVar(&options.Minify, "minify", false, "remove all information not used by current-context from the output") return cmd } func (o ViewOptions) Run(out io.Writer, printer kubectl.ResourcePrinter) error { config, err := o.loadConfig() if err != nil { return err } if o.Minify { if err := clientcmdapi.MinifyConfig(config); err != nil { return err } } if o.Flatten { if err := clientcmdapi.FlattenConfig(config); err != nil { return err } } else if !o.RawByteData { clientcmdapi.ShortenConfig(config) } err = printer.PrintObj(config, out) if err != nil { return err } return nil } func (o *ViewOptions) Complete() bool { if o.ConfigAccess.IsExplicitFile() { if !o.Merge.Provided() { o.Merge.Set("false") } } return true } func (o ViewOptions) loadConfig() (*clientcmdapi.Config, error) { err := o.Validate() if err != nil { return nil, err } config, err := o.getStartingConfig() return config, err } func (o ViewOptions) Validate() error { if !o.Merge.Value() && !o.ConfigAccess.IsExplicitFile() { return errors.New("if merge==false a precise file must to specified") } return nil } // getStartingConfig returns the Config object built from the sources specified by the options, the filename read (only if it was a single file), and an error if something goes wrong func (o *ViewOptions) getStartingConfig() (*clientcmdapi.Config, error) { switch { case !o.Merge.Value(): return clientcmd.LoadFromFile(o.ConfigAccess.GetExplicitFile()) default: return o.ConfigAccess.GetStartingConfig() } }
pkg/kubectl/cmd/config/view.go
1
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.0716957300901413, 0.009804165922105312, 0.00016996376507449895, 0.000725114019587636, 0.021763678640127182 ]
{ "id": 0, "code_window": [ ".SH DESCRIPTION\n", ".PP\n", "Displays merged kubeconfig settings or a specified kubeconfig file.\n", "\n", ".PP\n", "You can use \\-\\-output=template \\-\\-template=TEMPLATE to extract specific values.\n", "\n", "\n", ".SH OPTIONS\n", ".PP\n", "\\fB\\-\\-flatten\\fP=false\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "You can use \\-\\-output jsonpath={...} to extract specific values using a jsonpath expression.\n" ], "file_path": "docs/man/man1/kubectl-config-view.1", "type": "replace", "edit_start_line_idx": 18 }
// +build !windows package term import ( "errors" "io" "os" "os/signal" "syscall" "unsafe" ) var ( ErrInvalidState = errors.New("Invalid terminal state") ) type State struct { termios Termios } type Winsize struct { Height uint16 Width uint16 x uint16 y uint16 } func StdStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) { return os.Stdin, os.Stdout, os.Stderr } func GetFdInfo(in interface{}) (uintptr, bool) { var inFd uintptr var isTerminalIn bool if file, ok := in.(*os.File); ok { inFd = file.Fd() isTerminalIn = IsTerminal(inFd) } return inFd, isTerminalIn } func GetWinsize(fd uintptr) (*Winsize, error) { ws := &Winsize{} _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(ws))) // Skipp errno = 0 if err == 0 { return ws, nil } return ws, err } func SetWinsize(fd uintptr, ws *Winsize) error { _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(syscall.TIOCSWINSZ), uintptr(unsafe.Pointer(ws))) // Skipp errno = 0 if err == 0 { return nil } return err } // IsTerminal returns true if the given file descriptor is a terminal. func IsTerminal(fd uintptr) bool { var termios Termios return tcget(fd, &termios) == 0 } // Restore restores the terminal connected to the given file descriptor to a // previous state. func RestoreTerminal(fd uintptr, state *State) error { if state == nil { return ErrInvalidState } if err := tcset(fd, &state.termios); err != 0 { return err } return nil } func SaveState(fd uintptr) (*State, error) { var oldState State if err := tcget(fd, &oldState.termios); err != 0 { return nil, err } return &oldState, nil } func DisableEcho(fd uintptr, state *State) error { newState := state.termios newState.Lflag &^= syscall.ECHO if err := tcset(fd, &newState); err != 0 { return err } handleInterrupt(fd, state) return nil } func SetRawTerminal(fd uintptr) (*State, error) { oldState, err := MakeRaw(fd) if err != nil { return nil, err } handleInterrupt(fd, oldState) return oldState, err } func handleInterrupt(fd uintptr, state *State) { sigchan := make(chan os.Signal, 1) signal.Notify(sigchan, os.Interrupt) go func() { _ = <-sigchan RestoreTerminal(fd, state) os.Exit(0) }() }
Godeps/_workspace/src/github.com/docker/docker/pkg/term/term.go
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.002619874430820346, 0.0008537010289728642, 0.00018836824165191501, 0.00046025856863707304, 0.0008359376806765795 ]
{ "id": 0, "code_window": [ ".SH DESCRIPTION\n", ".PP\n", "Displays merged kubeconfig settings or a specified kubeconfig file.\n", "\n", ".PP\n", "You can use \\-\\-output=template \\-\\-template=TEMPLATE to extract specific values.\n", "\n", "\n", ".SH OPTIONS\n", ".PP\n", "\\fB\\-\\-flatten\\fP=false\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "You can use \\-\\-output jsonpath={...} to extract specific values using a jsonpath expression.\n" ], "file_path": "docs/man/man1/kubectl-config-view.1", "type": "replace", "edit_start_line_idx": 18 }
// Copyright 2015 CoreOS, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package capnslog import ( "bufio" "fmt" "io" "strings" "time" ) type Formatter interface { Format(pkg string, level LogLevel, depth int, entries ...interface{}) Flush() } func NewStringFormatter(w io.Writer) *StringFormatter { return &StringFormatter{ w: bufio.NewWriter(w), } } type StringFormatter struct { w *bufio.Writer } func (s *StringFormatter) Format(pkg string, l LogLevel, i int, entries ...interface{}) { now := time.Now() y, m, d := now.Date() h, min, sec := now.Clock() s.w.WriteString(fmt.Sprintf("%d/%02d/%d %02d:%02d:%02d ", y, m, d, h, min, sec)) s.writeEntries(pkg, l, i, entries...) } func (s *StringFormatter) writeEntries(pkg string, _ LogLevel, _ int, entries ...interface{}) { if pkg != "" { s.w.WriteString(pkg + ": ") } str := fmt.Sprint(entries...) endsInNL := strings.HasSuffix(str, "\n") s.w.WriteString(str) if !endsInNL { s.w.WriteString("\n") } s.Flush() } func (s *StringFormatter) Flush() { s.w.Flush() }
Godeps/_workspace/src/github.com/coreos/pkg/capnslog/formatters.go
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.0007900677737779915, 0.0003501888713799417, 0.00017236731946468353, 0.00029780794284306467, 0.00018929979705717415 ]
{ "id": 0, "code_window": [ ".SH DESCRIPTION\n", ".PP\n", "Displays merged kubeconfig settings or a specified kubeconfig file.\n", "\n", ".PP\n", "You can use \\-\\-output=template \\-\\-template=TEMPLATE to extract specific values.\n", "\n", "\n", ".SH OPTIONS\n", ".PP\n", "\\fB\\-\\-flatten\\fP=false\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "You can use \\-\\-output jsonpath={...} to extract specific values using a jsonpath expression.\n" ], "file_path": "docs/man/man1/kubectl-config-view.1", "type": "replace", "edit_start_line_idx": 18 }
/* Copyright 2015 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package http import ( "fmt" "net" "net/http" "net/http/httptest" "net/url" "strconv" "strings" "testing" "time" "k8s.io/kubernetes/pkg/probe" ) const FailureCode int = -1 func containsAny(s string, substrs []string) bool { for _, substr := range substrs { if strings.Contains(s, substr) { return true } } return false } func TestHTTPProbeChecker(t *testing.T) { handleReq := func(s int, body string) func(w http.ResponseWriter) { return func(w http.ResponseWriter) { w.WriteHeader(s) w.Write([]byte(body)) } } prober := New() testCases := []struct { handler func(w http.ResponseWriter) health probe.Result // go1.5: error message changed for timeout, need to support // both old and new accBodies []string }{ // The probe will be filled in below. This is primarily testing that an HTTP GET happens. { handleReq(http.StatusOK, "ok body"), probe.Success, []string{"ok body"}, }, { handleReq(FailureCode, "fail body"), probe.Failure, []string{fmt.Sprintf("HTTP probe failed with statuscode: %d", FailureCode)}, }, { func(w http.ResponseWriter) { time.Sleep(3 * time.Second) }, probe.Failure, []string{ "use of closed network connection", "request canceled (Client.Timeout exceeded while awaiting headers)", }, }, } for _, test := range testCases { // TODO: Close() this when fix #19254 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { test.handler(w) })) u, err := url.Parse(server.URL) if err != nil { t.Errorf("Unexpected error: %v", err) } _, port, err := net.SplitHostPort(u.Host) if err != nil { t.Errorf("Unexpected error: %v", err) } _, err = strconv.Atoi(port) if err != nil { t.Errorf("Unexpected error: %v", err) } health, output, err := prober.Probe(u, 1*time.Second) if test.health == probe.Unknown && err == nil { t.Errorf("Expected error") } if test.health != probe.Unknown && err != nil { t.Errorf("Unexpected error: %v", err) } if health != test.health { t.Errorf("Expected %v, got %v", test.health, health) } if !containsAny(output, test.accBodies) { t.Errorf("Expected one of %#v, got %v", test.accBodies, output) } } }
pkg/probe/http/http_test.go
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.0022204795386642218, 0.00065465341322124, 0.0001691500801825896, 0.00024404612486250699, 0.0007177658844739199 ]
{ "id": 1, "code_window": [ "$ kubectl config view\n", "\n", "# Get the password for the e2e user\n", "$ kubectl config view \\-o template \\-\\-template='{{range .users}}{{ if eq .name \"e2e\" }}{{ index .user.password }}{{end}}{{end}}'\n", "\n", ".fi\n", ".RE\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "$ kubectl config view \\-o jsonpath='{.users[?(@.name == \"e2e\")].user.password}'\n" ], "file_path": "docs/man/man1/kubectl-config-view.1", "type": "replace", "edit_start_line_idx": 169 }
<!-- BEGIN MUNGE: UNVERSIONED_WARNING --> <!-- BEGIN STRIP_FOR_RELEASE --> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <h2>PLEASE NOTE: This document applies to the HEAD of the source tree</h2> If you are using a released version of Kubernetes, you should refer to the docs that go with that version. <!-- TAG RELEASE_LINK, added by the munger automatically --> <strong> The latest release of this document can be found [here](http://releases.k8s.io/release-1.1/docs/user-guide/kubectl/kubectl_config_view.md). Documentation for other releases can be found at [releases.k8s.io](http://releases.k8s.io). </strong> -- <!-- END STRIP_FOR_RELEASE --> <!-- END MUNGE: UNVERSIONED_WARNING --> ## kubectl config view Displays merged kubeconfig settings or a specified kubeconfig file. ### Synopsis Displays merged kubeconfig settings or a specified kubeconfig file. You can use --output=template --template=TEMPLATE to extract specific values. ``` kubectl config view ``` ### Examples ``` # Show Merged kubeconfig settings. $ kubectl config view # Get the password for the e2e user $ kubectl config view -o template --template='{{range .users}}{{ if eq .name "e2e" }}{{ index .user.password }}{{end}}{{end}}' ``` ### Options ``` --flatten[=false]: flatten the resulting kubeconfig file into self contained output (useful for creating portable kubeconfig files) --merge[=true]: merge together the full hierarchy of kubeconfig files --minify[=false]: remove all information not used by current-context from the output --no-headers[=false]: When using the default output, don't print headers. -o, --output="": Output format. One of: json|yaml|wide|name|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=... See golang template [http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template [http://releases.k8s.io/HEAD/docs/user-guide/jsonpath.md]. --output-version="": Output the formatted object with the given version (default api-version). --raw[=false]: display raw byte data -a, --show-all[=false]: When printing, show all resources (default hide terminated pods.) --sort-by="": If non-empty, sort list types using this field specification. The field specification is expressed as a JSONPath expression (e.g. 'ObjectMeta.Name'). The field in the API resource specified by this JSONPath expression must be an integer or a string. --template="": Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview]. ``` ### Options inherited from parent commands ``` --alsologtostderr[=false]: log to standard error as well as files --api-version="": The API version to use when talking to the server --certificate-authority="": Path to a cert. file for the certificate authority. --client-certificate="": Path to a client certificate file for TLS. --client-key="": Path to a client key file for TLS. --cluster="": The name of the kubeconfig cluster to use --context="": The name of the kubeconfig context to use --insecure-skip-tls-verify[=false]: If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure. --kubeconfig="": use a particular kubeconfig file --log-backtrace-at=:0: when logging hits line file:N, emit a stack trace --log-dir="": If non-empty, write log files in this directory --log-flush-frequency=5s: Maximum number of seconds between log flushes --logtostderr[=true]: log to standard error instead of files --match-server-version[=false]: Require server version to match client version --namespace="": If present, the namespace scope for this CLI request. --password="": Password for basic authentication to the API server. -s, --server="": The address and port of the Kubernetes API server --stderrthreshold=2: logs at or above this threshold go to stderr --token="": Bearer token for authentication to the API server. --user="": The name of the kubeconfig user to use --username="": Username for basic authentication to the API server. --v=0: log level for V logs --vmodule=: comma-separated list of pattern=N settings for file-filtered logging ``` ### SEE ALSO * [kubectl config](kubectl_config.md) - config modifies kubeconfig files ###### Auto generated by spf13/cobra on 8-Jan-2016 <!-- BEGIN MUNGE: GENERATED_ANALYTICS --> [![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/kubectl/kubectl_config_view.md?pixel)]() <!-- END MUNGE: GENERATED_ANALYTICS -->
docs/user-guide/kubectl/kubectl_config_view.md
1
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.17955298721790314, 0.015285941772162914, 0.00016431794210802764, 0.00018061784794554114, 0.049529626965522766 ]
{ "id": 1, "code_window": [ "$ kubectl config view\n", "\n", "# Get the password for the e2e user\n", "$ kubectl config view \\-o template \\-\\-template='{{range .users}}{{ if eq .name \"e2e\" }}{{ index .user.password }}{{end}}{{end}}'\n", "\n", ".fi\n", ".RE\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "$ kubectl config view \\-o jsonpath='{.users[?(@.name == \"e2e\")].user.password}'\n" ], "file_path": "docs/man/man1/kubectl-config-view.1", "type": "replace", "edit_start_line_idx": 169 }
kind: PersistentVolume apiVersion: v1 metadata: name: pv0001 labels: type: local spec: capacity: storage: 10Gi accessModes: - ReadWriteOnce hostPath: path: "/tmp/data01"
docs/user-guide/persistent-volumes/volumes/local-01.yaml
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.000171887906617485, 0.00017180836584884673, 0.00017172882508020848, 0.00017180836584884673, 7.954076863825321e-8 ]
{ "id": 1, "code_window": [ "$ kubectl config view\n", "\n", "# Get the password for the e2e user\n", "$ kubectl config view \\-o template \\-\\-template='{{range .users}}{{ if eq .name \"e2e\" }}{{ index .user.password }}{{end}}{{end}}'\n", "\n", ".fi\n", ".RE\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "$ kubectl config view \\-o jsonpath='{.users[?(@.name == \"e2e\")].user.password}'\n" ], "file_path": "docs/man/man1/kubectl-config-view.1", "type": "replace", "edit_start_line_idx": 169 }
// Copyright 2012 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. // This is a package for testing comment placement by go/printer. // package main // Test cases for idempotent comment formatting (was issue 1835). /* c1a */ /* c1b */ /* foo c1c */ /* foo c1d */ /* c1e foo */ /* c1f foo */ func f() { /* c2a */ /* c2b */ /* foo c2c */ /* foo c2d */ /* c2e foo */ /* c2f foo */ } func g() { /* c3a */ /* c3b */ /* foo c3c */ /* foo c3d */ /* c3e foo */ /* c3f foo */ } // Test case taken literally from issue 1835. func main() { /* prints test 5 times */ for i := 0; i < 5; i++ { println("test") } } func issue5623() { L: _ = yyyyyyyyyyyyyyyy // comment - should be aligned _ = xxxxxxxxxxxxxxxxxxxxxxxxxxxx /* comment */ _ = yyyyyyyyyyyyyyyy /* comment - should be aligned */ _ = xxxxxxxxxxxxxxxxxxxxxxxxxxxx // comment LLLLLLL: _ = yyyyyyyyyyyyyyyy // comment - should be aligned _ = xxxxxxxxxxxxxxxxxxxxxxxxxxxx // comment LL: LLLLL: _ = xxxxxxxxxxxxxxxxxxxxxxxxxxxx /* comment */ _ = yyyyyyyyyyyyyyyy /* comment - should be aligned */ _ = xxxxxxxxxxxxxxxxxxxxxxxxxxxx // comment _ = yyyyyyyyyyyyyyyy // comment - should be aligned // test case from issue label: mask := uint64(1)<<c - 1 // Allocation mask used := atomic.LoadUint64(&h.used) // Current allocations }
third_party/golang/go/printer/testdata/comments2.input
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.00017513733473606408, 0.00017014870536513627, 0.00016519786731805652, 0.00016883682110346854, 0.000002903187123592943 ]
{ "id": 1, "code_window": [ "$ kubectl config view\n", "\n", "# Get the password for the e2e user\n", "$ kubectl config view \\-o template \\-\\-template='{{range .users}}{{ if eq .name \"e2e\" }}{{ index .user.password }}{{end}}{{end}}'\n", "\n", ".fi\n", ".RE\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "$ kubectl config view \\-o jsonpath='{.users[?(@.name == \"e2e\")].user.password}'\n" ], "file_path": "docs/man/man1/kubectl-config-view.1", "type": "replace", "edit_start_line_idx": 169 }
// Copyright (c) 2013, Vastech SA (PTY) LTD. All rights reserved. // http://github.com/gogo/protobuf // // 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. // // 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. package description import ( "github.com/gogo/protobuf/gogoproto" "github.com/gogo/protobuf/plugin/testgen" "github.com/gogo/protobuf/protoc-gen-gogo/generator" ) type test struct { *generator.Generator } func NewTest(g *generator.Generator) testgen.TestPlugin { return &test{g} } func (p *test) Generate(imports generator.PluginImports, file *generator.FileDescriptor) bool { used := false testingPkg := imports.NewImport("testing") for _, message := range file.Messages() { if !gogoproto.HasDescription(file.FileDescriptorProto, message.DescriptorProto) || !gogoproto.HasTestGen(file.FileDescriptorProto, message.DescriptorProto) { continue } if message.DescriptorProto.GetOptions().GetMapEntry() { continue } used = true } if used { localName := generator.FileName(file) p.P(`func Test`, localName, `Description(t *`, testingPkg.Use(), `.T) {`) p.In() p.P(localName, `Description()`) p.Out() p.P(`}`) } return used } func init() { testgen.RegisterTestPlugin(NewTest) }
Godeps/_workspace/src/github.com/gogo/protobuf/plugin/description/descriptiontest.go
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.00017362376092933118, 0.00017109740292653441, 0.00016441606567241251, 0.00017233125981874764, 0.0000028118899990658974 ]
{ "id": 2, "code_window": [ "\n", "Displays merged kubeconfig settings or a specified kubeconfig file.\n", "\n", "You can use --output=template --template=TEMPLATE to extract specific values.\n", "\n", "```\n", "kubectl config view\n", "```\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "You can use --output jsonpath={...} to extract specific values using a jsonpath expression.\n" ], "file_path": "docs/user-guide/kubectl/kubectl_config_view.md", "type": "replace", "edit_start_line_idx": 43 }
/* Copyright 2014 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package config import ( "errors" "fmt" "io" "github.com/spf13/cobra" "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/latest" "k8s.io/kubernetes/pkg/kubectl" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "k8s.io/kubernetes/pkg/util" ) type ViewOptions struct { ConfigAccess ConfigAccess Merge util.BoolFlag Flatten bool Minify bool RawByteData bool } const ( view_long = `Displays merged kubeconfig settings or a specified kubeconfig file. You can use --output=template --template=TEMPLATE to extract specific values.` view_example = `# Show Merged kubeconfig settings. $ kubectl config view # Get the password for the e2e user $ kubectl config view -o template --template='{{range .users}}{{ if eq .name "e2e" }}{{ index .user.password }}{{end}}{{end}}'` ) func NewCmdConfigView(out io.Writer, ConfigAccess ConfigAccess) *cobra.Command { options := &ViewOptions{ConfigAccess: ConfigAccess} // Default to yaml defaultOutputFormat := "yaml" cmd := &cobra.Command{ Use: "view", Short: "Displays merged kubeconfig settings or a specified kubeconfig file.", Long: view_long, Example: view_example, Run: func(cmd *cobra.Command, args []string) { options.Complete() outputFormat := cmdutil.GetFlagString(cmd, "output") if outputFormat == "wide" { fmt.Printf("--output wide is not available in kubectl config view; reset to default output format (%s)\n\n", defaultOutputFormat) cmd.Flags().Set("output", defaultOutputFormat) } printer, _, err := cmdutil.PrinterForCommand(cmd) cmdutil.CheckErr(err) version, err := cmdutil.OutputVersion(cmd, &latest.ExternalVersion) cmdutil.CheckErr(err) printer = kubectl.NewVersionedPrinter(printer, clientcmdapi.Scheme, version) cmdutil.CheckErr(options.Run(out, printer)) }, } cmdutil.AddPrinterFlags(cmd) cmd.Flags().Set("output", defaultOutputFormat) options.Merge.Default(true) f := cmd.Flags().VarPF(&options.Merge, "merge", "", "merge together the full hierarchy of kubeconfig files") f.NoOptDefVal = "true" cmd.Flags().BoolVar(&options.RawByteData, "raw", false, "display raw byte data") cmd.Flags().BoolVar(&options.Flatten, "flatten", false, "flatten the resulting kubeconfig file into self contained output (useful for creating portable kubeconfig files)") cmd.Flags().BoolVar(&options.Minify, "minify", false, "remove all information not used by current-context from the output") return cmd } func (o ViewOptions) Run(out io.Writer, printer kubectl.ResourcePrinter) error { config, err := o.loadConfig() if err != nil { return err } if o.Minify { if err := clientcmdapi.MinifyConfig(config); err != nil { return err } } if o.Flatten { if err := clientcmdapi.FlattenConfig(config); err != nil { return err } } else if !o.RawByteData { clientcmdapi.ShortenConfig(config) } err = printer.PrintObj(config, out) if err != nil { return err } return nil } func (o *ViewOptions) Complete() bool { if o.ConfigAccess.IsExplicitFile() { if !o.Merge.Provided() { o.Merge.Set("false") } } return true } func (o ViewOptions) loadConfig() (*clientcmdapi.Config, error) { err := o.Validate() if err != nil { return nil, err } config, err := o.getStartingConfig() return config, err } func (o ViewOptions) Validate() error { if !o.Merge.Value() && !o.ConfigAccess.IsExplicitFile() { return errors.New("if merge==false a precise file must to specified") } return nil } // getStartingConfig returns the Config object built from the sources specified by the options, the filename read (only if it was a single file), and an error if something goes wrong func (o *ViewOptions) getStartingConfig() (*clientcmdapi.Config, error) { switch { case !o.Merge.Value(): return clientcmd.LoadFromFile(o.ConfigAccess.GetExplicitFile()) default: return o.ConfigAccess.GetStartingConfig() } }
pkg/kubectl/cmd/config/view.go
1
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.32437410950660706, 0.026763346046209335, 0.00016597341164015234, 0.0010951749281957746, 0.07824968546628952 ]
{ "id": 2, "code_window": [ "\n", "Displays merged kubeconfig settings or a specified kubeconfig file.\n", "\n", "You can use --output=template --template=TEMPLATE to extract specific values.\n", "\n", "```\n", "kubectl config view\n", "```\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "You can use --output jsonpath={...} to extract specific values using a jsonpath expression.\n" ], "file_path": "docs/user-guide/kubectl/kubectl_config_view.md", "type": "replace", "edit_start_line_idx": 43 }
package subnets import ( "fmt" "github.com/rackspace/gophercloud" "github.com/rackspace/gophercloud/pagination" ) // AdminState gives users a solid type to work with for create and update // operations. It is recommended that users use the `Up` and `Down` enums. type AdminState *bool // Convenience vars for AdminStateUp values. var ( iTrue = true iFalse = false Up AdminState = &iTrue Down AdminState = &iFalse ) // ListOptsBuilder allows extensions to add additional parameters to the // List request. type ListOptsBuilder interface { ToSubnetListQuery() (string, error) } // ListOpts allows the filtering and sorting of paginated collections through // the API. Filtering is achieved by passing in struct field values that map to // the subnet attributes you want to see returned. SortKey allows you to sort // by a particular subnet attribute. SortDir sets the direction, and is either // `asc' or `desc'. Marker and Limit are used for pagination. type ListOpts struct { Name string `q:"name"` EnableDHCP *bool `q:"enable_dhcp"` NetworkID string `q:"network_id"` TenantID string `q:"tenant_id"` IPVersion int `q:"ip_version"` GatewayIP string `q:"gateway_ip"` CIDR string `q:"cidr"` ID string `q:"id"` Limit int `q:"limit"` Marker string `q:"marker"` SortKey string `q:"sort_key"` SortDir string `q:"sort_dir"` } // ToSubnetListQuery formats a ListOpts into a query string. func (opts ListOpts) ToSubnetListQuery() (string, error) { q, err := gophercloud.BuildQueryString(opts) if err != nil { return "", err } return q.String(), nil } // List returns a Pager which allows you to iterate over a collection of // subnets. It accepts a ListOpts struct, which allows you to filter and sort // the returned collection for greater efficiency. // // Default policy settings return only those subnets that are owned by the tenant // who submits the request, unless the request is submitted by a user with // administrative rights. func List(c *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager { url := listURL(c) if opts != nil { query, err := opts.ToSubnetListQuery() if err != nil { return pagination.Pager{Err: err} } url += query } return pagination.NewPager(c, url, func(r pagination.PageResult) pagination.Page { return SubnetPage{pagination.LinkedPageBase{PageResult: r}} }) } // Get retrieves a specific subnet based on its unique ID. func Get(c *gophercloud.ServiceClient, id string) GetResult { var res GetResult _, res.Err = c.Get(getURL(c, id), &res.Body, nil) return res } // Valid IP types const ( IPv4 = 4 IPv6 = 6 ) // CreateOptsBuilder is the interface options structs have to satisfy in order // to be used in the main Create operation in this package. Since many // extensions decorate or modify the common logic, it is useful for them to // satisfy a basic interface in order for them to be used. type CreateOptsBuilder interface { ToSubnetCreateMap() (map[string]interface{}, error) } // CreateOpts represents the attributes used when creating a new subnet. type CreateOpts struct { // Required NetworkID string CIDR string // Optional Name string TenantID string AllocationPools []AllocationPool GatewayIP string IPVersion int EnableDHCP *bool DNSNameservers []string HostRoutes []HostRoute } // ToSubnetCreateMap casts a CreateOpts struct to a map. func (opts CreateOpts) ToSubnetCreateMap() (map[string]interface{}, error) { s := make(map[string]interface{}) if opts.NetworkID == "" { return nil, errNetworkIDRequired } if opts.CIDR == "" { return nil, errCIDRRequired } if opts.IPVersion != 0 && opts.IPVersion != IPv4 && opts.IPVersion != IPv6 { return nil, errInvalidIPType } s["network_id"] = opts.NetworkID s["cidr"] = opts.CIDR if opts.EnableDHCP != nil { s["enable_dhcp"] = &opts.EnableDHCP } if opts.Name != "" { s["name"] = opts.Name } if opts.GatewayIP != "" { s["gateway_ip"] = opts.GatewayIP } if opts.TenantID != "" { s["tenant_id"] = opts.TenantID } if opts.IPVersion != 0 { s["ip_version"] = opts.IPVersion } if len(opts.AllocationPools) != 0 { s["allocation_pools"] = opts.AllocationPools } if len(opts.DNSNameservers) != 0 { s["dns_nameservers"] = opts.DNSNameservers } if len(opts.HostRoutes) != 0 { s["host_routes"] = opts.HostRoutes } return map[string]interface{}{"subnet": s}, nil } // Create accepts a CreateOpts struct and creates a new subnet using the values // provided. You must remember to provide a valid NetworkID, CIDR and IP version. func Create(c *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult { var res CreateResult reqBody, err := opts.ToSubnetCreateMap() if err != nil { res.Err = err return res } _, res.Err = c.Post(createURL(c), reqBody, &res.Body, nil) return res } // UpdateOptsBuilder allows extensions to add additional parameters to the // Update request. type UpdateOptsBuilder interface { ToSubnetUpdateMap() (map[string]interface{}, error) } // UpdateOpts represents the attributes used when updating an existing subnet. type UpdateOpts struct { Name string GatewayIP string DNSNameservers []string HostRoutes []HostRoute EnableDHCP *bool } // ToSubnetUpdateMap casts an UpdateOpts struct to a map. func (opts UpdateOpts) ToSubnetUpdateMap() (map[string]interface{}, error) { s := make(map[string]interface{}) if opts.EnableDHCP != nil { s["enable_dhcp"] = &opts.EnableDHCP } if opts.Name != "" { s["name"] = opts.Name } if opts.GatewayIP != "" { s["gateway_ip"] = opts.GatewayIP } if opts.DNSNameservers != nil { s["dns_nameservers"] = opts.DNSNameservers } if opts.HostRoutes != nil { s["host_routes"] = opts.HostRoutes } return map[string]interface{}{"subnet": s}, nil } // Update accepts a UpdateOpts struct and updates an existing subnet using the // values provided. func Update(c *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) UpdateResult { var res UpdateResult reqBody, err := opts.ToSubnetUpdateMap() if err != nil { res.Err = err return res } _, res.Err = c.Put(updateURL(c, id), reqBody, &res.Body, &gophercloud.RequestOpts{ OkCodes: []int{200, 201}, }) return res } // Delete accepts a unique ID and deletes the subnet associated with it. func Delete(c *gophercloud.ServiceClient, id string) DeleteResult { var res DeleteResult _, res.Err = c.Delete(deleteURL(c, id), nil) return res } // IDFromName is a convenience function that returns a subnet's ID given its name. func IDFromName(client *gophercloud.ServiceClient, name string) (string, error) { subnetCount := 0 subnetID := "" if name == "" { return "", fmt.Errorf("A subnet name must be provided.") } pager := List(client, nil) pager.EachPage(func(page pagination.Page) (bool, error) { subnetList, err := ExtractSubnets(page) if err != nil { return false, err } for _, s := range subnetList { if s.Name == name { subnetCount++ subnetID = s.ID } } return true, nil }) switch subnetCount { case 0: return "", fmt.Errorf("Unable to find subnet: %s", name) case 1: return subnetID, nil default: return "", fmt.Errorf("Found %d subnets matching %s", subnetCount, name) } }
Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/requests.go
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.0020299020688980818, 0.0002906271838583052, 0.00016486425010953099, 0.0001704133755993098, 0.0003636404580902308 ]
{ "id": 2, "code_window": [ "\n", "Displays merged kubeconfig settings or a specified kubeconfig file.\n", "\n", "You can use --output=template --template=TEMPLATE to extract specific values.\n", "\n", "```\n", "kubectl config view\n", "```\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "You can use --output jsonpath={...} to extract specific values using a jsonpath expression.\n" ], "file_path": "docs/user-guide/kubectl/kubectl_config_view.md", "type": "replace", "edit_start_line_idx": 43 }
/* Copyright 2015 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package metrics import ( "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/runtime" ) func AddToScheme(scheme *runtime.Scheme) { // Add the API to Scheme. addKnownTypes(scheme) } // GroupName is the group name use in this package const GroupName = "metrics" // SchemeGroupVersion is group version used to register these objects var SchemeGroupVersion = unversioned.GroupVersion{Group: GroupName, Version: runtime.APIVersionInternal} // Kind takes an unqualified kind and returns back a Group qualified GroupKind func Kind(kind string) unversioned.GroupKind { return SchemeGroupVersion.WithKind(kind).GroupKind() } // Resource takes an unqualified resource and returns back a Group qualified GroupResource func Resource(resource string) unversioned.GroupResource { return SchemeGroupVersion.WithResource(resource).GroupResource() } // Adds the list of known types to api.Scheme. func addKnownTypes(scheme *runtime.Scheme) { // TODO this will get cleaned up with the scheme types are fixed scheme.AddKnownTypes(SchemeGroupVersion, &RawNode{}, &RawPod{}, ) } func (obj *RawNode) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } func (obj *RawPod) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta }
pkg/apis/metrics/register.go
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.00021812014165334404, 0.00018137354345526546, 0.0001674750674283132, 0.0001747508067637682, 0.000016884714568732306 ]
{ "id": 2, "code_window": [ "\n", "Displays merged kubeconfig settings or a specified kubeconfig file.\n", "\n", "You can use --output=template --template=TEMPLATE to extract specific values.\n", "\n", "```\n", "kubectl config view\n", "```\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "You can use --output jsonpath={...} to extract specific values using a jsonpath expression.\n" ], "file_path": "docs/user-guide/kubectl/kubectl_config_view.md", "type": "replace", "edit_start_line_idx": 43 }
# TYPE metric bla
Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_15
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.0003080950409639627, 0.0003080950409639627, 0.0003080950409639627, 0.0003080950409639627, 0 ]
{ "id": 3, "code_window": [ "# Show Merged kubeconfig settings.\n", "$ kubectl config view\n", "\n", "# Get the password for the e2e user\n", "$ kubectl config view -o template --template='{{range .users}}{{ if eq .name \"e2e\" }}{{ index .user.password }}{{end}}{{end}}'\n", "```\n", "\n", "### Options\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "$ kubectl config view -o jsonpath='{.users[?(@.name == \"e2e\")].user.password}'\n" ], "file_path": "docs/user-guide/kubectl/kubectl_config_view.md", "type": "replace", "edit_start_line_idx": 56 }
<!-- BEGIN MUNGE: UNVERSIONED_WARNING --> <!-- BEGIN STRIP_FOR_RELEASE --> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <h2>PLEASE NOTE: This document applies to the HEAD of the source tree</h2> If you are using a released version of Kubernetes, you should refer to the docs that go with that version. <!-- TAG RELEASE_LINK, added by the munger automatically --> <strong> The latest release of this document can be found [here](http://releases.k8s.io/release-1.1/docs/user-guide/kubectl/kubectl_config_view.md). Documentation for other releases can be found at [releases.k8s.io](http://releases.k8s.io). </strong> -- <!-- END STRIP_FOR_RELEASE --> <!-- END MUNGE: UNVERSIONED_WARNING --> ## kubectl config view Displays merged kubeconfig settings or a specified kubeconfig file. ### Synopsis Displays merged kubeconfig settings or a specified kubeconfig file. You can use --output=template --template=TEMPLATE to extract specific values. ``` kubectl config view ``` ### Examples ``` # Show Merged kubeconfig settings. $ kubectl config view # Get the password for the e2e user $ kubectl config view -o template --template='{{range .users}}{{ if eq .name "e2e" }}{{ index .user.password }}{{end}}{{end}}' ``` ### Options ``` --flatten[=false]: flatten the resulting kubeconfig file into self contained output (useful for creating portable kubeconfig files) --merge[=true]: merge together the full hierarchy of kubeconfig files --minify[=false]: remove all information not used by current-context from the output --no-headers[=false]: When using the default output, don't print headers. -o, --output="": Output format. One of: json|yaml|wide|name|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=... See golang template [http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template [http://releases.k8s.io/HEAD/docs/user-guide/jsonpath.md]. --output-version="": Output the formatted object with the given version (default api-version). --raw[=false]: display raw byte data -a, --show-all[=false]: When printing, show all resources (default hide terminated pods.) --sort-by="": If non-empty, sort list types using this field specification. The field specification is expressed as a JSONPath expression (e.g. 'ObjectMeta.Name'). The field in the API resource specified by this JSONPath expression must be an integer or a string. --template="": Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview]. ``` ### Options inherited from parent commands ``` --alsologtostderr[=false]: log to standard error as well as files --api-version="": The API version to use when talking to the server --certificate-authority="": Path to a cert. file for the certificate authority. --client-certificate="": Path to a client certificate file for TLS. --client-key="": Path to a client key file for TLS. --cluster="": The name of the kubeconfig cluster to use --context="": The name of the kubeconfig context to use --insecure-skip-tls-verify[=false]: If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure. --kubeconfig="": use a particular kubeconfig file --log-backtrace-at=:0: when logging hits line file:N, emit a stack trace --log-dir="": If non-empty, write log files in this directory --log-flush-frequency=5s: Maximum number of seconds between log flushes --logtostderr[=true]: log to standard error instead of files --match-server-version[=false]: Require server version to match client version --namespace="": If present, the namespace scope for this CLI request. --password="": Password for basic authentication to the API server. -s, --server="": The address and port of the Kubernetes API server --stderrthreshold=2: logs at or above this threshold go to stderr --token="": Bearer token for authentication to the API server. --user="": The name of the kubeconfig user to use --username="": Username for basic authentication to the API server. --v=0: log level for V logs --vmodule=: comma-separated list of pattern=N settings for file-filtered logging ``` ### SEE ALSO * [kubectl config](kubectl_config.md) - config modifies kubeconfig files ###### Auto generated by spf13/cobra on 8-Jan-2016 <!-- BEGIN MUNGE: GENERATED_ANALYTICS --> [![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/kubectl/kubectl_config_view.md?pixel)]() <!-- END MUNGE: GENERATED_ANALYTICS -->
docs/user-guide/kubectl/kubectl_config_view.md
1
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.9937625527381897, 0.08364176005125046, 0.0001642159913899377, 0.0002933177165687084, 0.2744165062904358 ]
{ "id": 3, "code_window": [ "# Show Merged kubeconfig settings.\n", "$ kubectl config view\n", "\n", "# Get the password for the e2e user\n", "$ kubectl config view -o template --template='{{range .users}}{{ if eq .name \"e2e\" }}{{ index .user.password }}{{end}}{{end}}'\n", "```\n", "\n", "### Options\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "$ kubectl config view -o jsonpath='{.users[?(@.name == \"e2e\")].user.password}'\n" ], "file_path": "docs/user-guide/kubectl/kubectl_config_view.md", "type": "replace", "edit_start_line_idx": 56 }
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package static const bootstrapCss = ` /*! * Bootstrap v3.1.1 (http://getbootstrap.com) * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ /*! normalize.css v3.0.0 | MIT License | git.io/normalize */html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background:0 0}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}h1{font-size:2em;margin:.67em 0}mark{background:#ff0;color:#000}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}button,input,optgroup,select,textarea{color:inherit;font:inherit;margin:0}button{overflow:visible}button,select{text-transform:none}button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}input{line-height:normal}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button{height:auto}input[type=search]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{border:0;padding:0}textarea{overflow:auto}optgroup{font-weight:700}table{border-collapse:collapse;border-spacing:0}td,th{padding:0}@media print{*{text-shadow:none!important;color:#000!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}select{background:#fff!important}.navbar{display:none}.table td,.table th{background-color:#fff!important}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table-bordered th,.table-bordered td{border:1px solid #ddd!important}}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}:before,:after{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:62.5%;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857143;color:#333;background-color:#fff}input,button,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#428bca;text-decoration:none}a:hover,a:focus{color:#2a6496;text-decoration:underline}a:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}figure{margin:0}img{vertical-align:middle}.img-responsive,.thumbnail>img,.thumbnail a>img,.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:block;max-width:100%;height:auto}.img-rounded{border-radius:6px}.img-thumbnail{padding:4px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out;display:inline-block;max-width:100%;height:auto}.img-circle{border-radius:50%}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}.sr-only{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);border:0}h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6{font-family:inherit;font-weight:500;line-height:1.1;color:inherit}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small,.h1 small,.h2 small,.h3 small,.h4 small,.h5 small,.h6 small,h1 .small,h2 .small,h3 .small,h4 .small,h5 .small,h6 .small,.h1 .small,.h2 .small,.h3 .small,.h4 .small,.h5 .small,.h6 .small{font-weight:400;line-height:1;color:#999}h1,.h1,h2,.h2,h3,.h3{margin-top:20px;margin-bottom:10px}h1 small,.h1 small,h2 small,.h2 small,h3 small,.h3 small,h1 .small,.h1 .small,h2 .small,.h2 .small,h3 .small,.h3 .small{font-size:65%}h4,.h4,h5,.h5,h6,.h6{margin-top:10px;margin-bottom:10px}h4 small,.h4 small,h5 small,.h5 small,h6 small,.h6 small,h4 .small,.h4 .small,h5 .small,.h5 .small,h6 .small,.h6 .small{font-size:75%}h1,.h1{font-size:36px}h2,.h2{font-size:30px}h3,.h3{font-size:24px}h4,.h4{font-size:18px}h5,.h5{font-size:14px}h6,.h6{font-size:12px}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16px;font-weight:200;line-height:1.4}@media (min-width:768px){.lead{font-size:21px}}small,.small{font-size:85%}cite{font-style:normal}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}.text-justify{text-align:justify}.text-muted{color:#999}.text-primary{color:#428bca}a.text-primary:hover{color:#3071a9}.text-success{color:#3c763d}a.text-success:hover{color:#2b542c}.text-info{color:#31708f}a.text-info:hover{color:#245269}.text-warning{color:#8a6d3b}a.text-warning:hover{color:#66512c}.text-danger{color:#a94442}a.text-danger:hover{color:#843534}.bg-primary{color:#fff;background-color:#428bca}a.bg-primary:hover{background-color:#3071a9}.bg-success{background-color:#dff0d8}a.bg-success:hover{background-color:#c1e2b3}.bg-info{background-color:#d9edf7}a.bg-info:hover{background-color:#afd9ee}.bg-warning{background-color:#fcf8e3}a.bg-warning:hover{background-color:#f7ecb5}.bg-danger{background-color:#f2dede}a.bg-danger:hover{background-color:#e4b9b9}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ul,ol{margin-top:0;margin-bottom:10px}ul ul,ol ul,ul ol,ol ol{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none;margin-left:-5px}.list-inline>li{display:inline-block;padding-left:5px;padding-right:5px}dl{margin-top:0;margin-bottom:20px}dt,dd{line-height:1.42857143}dt{font-weight:700}dd{margin-left:0}@media (min-width:768px){.dl-horizontal dt{float:left;width:160px;clear:left;text-align:right;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999}.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;font-size:17.5px;border-left:5px solid #eee}blockquote p:last-child,blockquote ul:last-child,blockquote ol:last-child{margin-bottom:0}blockquote footer,blockquote small,blockquote .small{display:block;font-size:80%;line-height:1.42857143;color:#999}blockquote footer:before,blockquote small:before,blockquote .small:before{content:'\2014 \00A0'}.blockquote-reverse,blockquote.pull-right{padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0;text-align:right}.blockquote-reverse footer:before,blockquote.pull-right footer:before,.blockquote-reverse small:before,blockquote.pull-right small:before,.blockquote-reverse .small:before,blockquote.pull-right .small:before{content:''}.blockquote-reverse footer:after,blockquote.pull-right footer:after,.blockquote-reverse small:after,blockquote.pull-right small:after,.blockquote-reverse .small:after,blockquote.pull-right .small:after{content:'\00A0 \2014'}blockquote:before,blockquote:after{content:""}address{margin-bottom:20px;font-style:normal;line-height:1.42857143}code,kbd,pre,samp{font-family:Menlo,Monaco,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;background-color:#f9f2f4;white-space:nowrap;border-radius:4px}kbd{padding:2px 4px;font-size:90%;color:#fff;background-color:#333;border-radius:3px;box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.42857143;word-break:break-all;word-wrap:break-word;color:#333;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{margin-right:auto;margin-left:auto;padding-left:15px;padding-right:15px}@media (min-width:768px){.container{width:750px}}@media (min-width:992px){.container{width:970px}}@media (min-width:1200px){.container{width:1170px}}.container-fluid{margin-right:auto;margin-left:auto;padding-left:15px;padding-right:15px}.row{margin-left:-15px;margin-right:-15px}.col-xs-1,.col-sm-1,.col-md-1,.col-lg-1,.col-xs-2,.col-sm-2,.col-md-2,.col-lg-2,.col-xs-3,.col-sm-3,.col-md-3,.col-lg-3,.col-xs-4,.col-sm-4,.col-md-4,.col-lg-4,.col-xs-5,.col-sm-5,.col-md-5,.col-lg-5,.col-xs-6,.col-sm-6,.col-md-6,.col-lg-6,.col-xs-7,.col-sm-7,.col-md-7,.col-lg-7,.col-xs-8,.col-sm-8,.col-md-8,.col-lg-8,.col-xs-9,.col-sm-9,.col-md-9,.col-lg-9,.col-xs-10,.col-sm-10,.col-md-10,.col-lg-10,.col-xs-11,.col-sm-11,.col-md-11,.col-lg-11,.col-xs-12,.col-sm-12,.col-md-12,.col-lg-12{position:relative;min-height:1px;padding-left:15px;padding-right:15px}.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11,.col-xs-12{float:left}.col-xs-12{width:100%}.col-xs-11{width:91.66666667%}.col-xs-10{width:83.33333333%}.col-xs-9{width:75%}.col-xs-8{width:66.66666667%}.col-xs-7{width:58.33333333%}.col-xs-6{width:50%}.col-xs-5{width:41.66666667%}.col-xs-4{width:33.33333333%}.col-xs-3{width:25%}.col-xs-2{width:16.66666667%}.col-xs-1{width:8.33333333%}.col-xs-pull-12{right:100%}.col-xs-pull-11{right:91.66666667%}.col-xs-pull-10{right:83.33333333%}.col-xs-pull-9{right:75%}.col-xs-pull-8{right:66.66666667%}.col-xs-pull-7{right:58.33333333%}.col-xs-pull-6{right:50%}.col-xs-pull-5{right:41.66666667%}.col-xs-pull-4{right:33.33333333%}.col-xs-pull-3{right:25%}.col-xs-pull-2{right:16.66666667%}.col-xs-pull-1{right:8.33333333%}.col-xs-pull-0{right:0}.col-xs-push-12{left:100%}.col-xs-push-11{left:91.66666667%}.col-xs-push-10{left:83.33333333%}.col-xs-push-9{left:75%}.col-xs-push-8{left:66.66666667%}.col-xs-push-7{left:58.33333333%}.col-xs-push-6{left:50%}.col-xs-push-5{left:41.66666667%}.col-xs-push-4{left:33.33333333%}.col-xs-push-3{left:25%}.col-xs-push-2{left:16.66666667%}.col-xs-push-1{left:8.33333333%}.col-xs-push-0{left:0}.col-xs-offset-12{margin-left:100%}.col-xs-offset-11{margin-left:91.66666667%}.col-xs-offset-10{margin-left:83.33333333%}.col-xs-offset-9{margin-left:75%}.col-xs-offset-8{margin-left:66.66666667%}.col-xs-offset-7{margin-left:58.33333333%}.col-xs-offset-6{margin-left:50%}.col-xs-offset-5{margin-left:41.66666667%}.col-xs-offset-4{margin-left:33.33333333%}.col-xs-offset-3{margin-left:25%}.col-xs-offset-2{margin-left:16.66666667%}.col-xs-offset-1{margin-left:8.33333333%}.col-xs-offset-0{margin-left:0}@media (min-width:768px){.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12{float:left}.col-sm-12{width:100%}.col-sm-11{width:91.66666667%}.col-sm-10{width:83.33333333%}.col-sm-9{width:75%}.col-sm-8{width:66.66666667%}.col-sm-7{width:58.33333333%}.col-sm-6{width:50%}.col-sm-5{width:41.66666667%}.col-sm-4{width:33.33333333%}.col-sm-3{width:25%}.col-sm-2{width:16.66666667%}.col-sm-1{width:8.33333333%}.col-sm-pull-12{right:100%}.col-sm-pull-11{right:91.66666667%}.col-sm-pull-10{right:83.33333333%}.col-sm-pull-9{right:75%}.col-sm-pull-8{right:66.66666667%}.col-sm-pull-7{right:58.33333333%}.col-sm-pull-6{right:50%}.col-sm-pull-5{right:41.66666667%}.col-sm-pull-4{right:33.33333333%}.col-sm-pull-3{right:25%}.col-sm-pull-2{right:16.66666667%}.col-sm-pull-1{right:8.33333333%}.col-sm-pull-0{right:0}.col-sm-push-12{left:100%}.col-sm-push-11{left:91.66666667%}.col-sm-push-10{left:83.33333333%}.col-sm-push-9{left:75%}.col-sm-push-8{left:66.66666667%}.col-sm-push-7{left:58.33333333%}.col-sm-push-6{left:50%}.col-sm-push-5{left:41.66666667%}.col-sm-push-4{left:33.33333333%}.col-sm-push-3{left:25%}.col-sm-push-2{left:16.66666667%}.col-sm-push-1{left:8.33333333%}.col-sm-push-0{left:0}.col-sm-offset-12{margin-left:100%}.col-sm-offset-11{margin-left:91.66666667%}.col-sm-offset-10{margin-left:83.33333333%}.col-sm-offset-9{margin-left:75%}.col-sm-offset-8{margin-left:66.66666667%}.col-sm-offset-7{margin-left:58.33333333%}.col-sm-offset-6{margin-left:50%}.col-sm-offset-5{margin-left:41.66666667%}.col-sm-offset-4{margin-left:33.33333333%}.col-sm-offset-3{margin-left:25%}.col-sm-offset-2{margin-left:16.66666667%}.col-sm-offset-1{margin-left:8.33333333%}.col-sm-offset-0{margin-left:0}}@media (min-width:992px){.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11,.col-md-12{float:left}.col-md-12{width:100%}.col-md-11{width:91.66666667%}.col-md-10{width:83.33333333%}.col-md-9{width:75%}.col-md-8{width:66.66666667%}.col-md-7{width:58.33333333%}.col-md-6{width:50%}.col-md-5{width:41.66666667%}.col-md-4{width:33.33333333%}.col-md-3{width:25%}.col-md-2{width:16.66666667%}.col-md-1{width:8.33333333%}.col-md-pull-12{right:100%}.col-md-pull-11{right:91.66666667%}.col-md-pull-10{right:83.33333333%}.col-md-pull-9{right:75%}.col-md-pull-8{right:66.66666667%}.col-md-pull-7{right:58.33333333%}.col-md-pull-6{right:50%}.col-md-pull-5{right:41.66666667%}.col-md-pull-4{right:33.33333333%}.col-md-pull-3{right:25%}.col-md-pull-2{right:16.66666667%}.col-md-pull-1{right:8.33333333%}.col-md-pull-0{right:0}.col-md-push-12{left:100%}.col-md-push-11{left:91.66666667%}.col-md-push-10{left:83.33333333%}.col-md-push-9{left:75%}.col-md-push-8{left:66.66666667%}.col-md-push-7{left:58.33333333%}.col-md-push-6{left:50%}.col-md-push-5{left:41.66666667%}.col-md-push-4{left:33.33333333%}.col-md-push-3{left:25%}.col-md-push-2{left:16.66666667%}.col-md-push-1{left:8.33333333%}.col-md-push-0{left:0}.col-md-offset-12{margin-left:100%}.col-md-offset-11{margin-left:91.66666667%}.col-md-offset-10{margin-left:83.33333333%}.col-md-offset-9{margin-left:75%}.col-md-offset-8{margin-left:66.66666667%}.col-md-offset-7{margin-left:58.33333333%}.col-md-offset-6{margin-left:50%}.col-md-offset-5{margin-left:41.66666667%}.col-md-offset-4{margin-left:33.33333333%}.col-md-offset-3{margin-left:25%}.col-md-offset-2{margin-left:16.66666667%}.col-md-offset-1{margin-left:8.33333333%}.col-md-offset-0{margin-left:0}}@media (min-width:1200px){.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{float:left}.col-lg-12{width:100%}.col-lg-11{width:91.66666667%}.col-lg-10{width:83.33333333%}.col-lg-9{width:75%}.col-lg-8{width:66.66666667%}.col-lg-7{width:58.33333333%}.col-lg-6{width:50%}.col-lg-5{width:41.66666667%}.col-lg-4{width:33.33333333%}.col-lg-3{width:25%}.col-lg-2{width:16.66666667%}.col-lg-1{width:8.33333333%}.col-lg-pull-12{right:100%}.col-lg-pull-11{right:91.66666667%}.col-lg-pull-10{right:83.33333333%}.col-lg-pull-9{right:75%}.col-lg-pull-8{right:66.66666667%}.col-lg-pull-7{right:58.33333333%}.col-lg-pull-6{right:50%}.col-lg-pull-5{right:41.66666667%}.col-lg-pull-4{right:33.33333333%}.col-lg-pull-3{right:25%}.col-lg-pull-2{right:16.66666667%}.col-lg-pull-1{right:8.33333333%}.col-lg-pull-0{right:0}.col-lg-push-12{left:100%}.col-lg-push-11{left:91.66666667%}.col-lg-push-10{left:83.33333333%}.col-lg-push-9{left:75%}.col-lg-push-8{left:66.66666667%}.col-lg-push-7{left:58.33333333%}.col-lg-push-6{left:50%}.col-lg-push-5{left:41.66666667%}.col-lg-push-4{left:33.33333333%}.col-lg-push-3{left:25%}.col-lg-push-2{left:16.66666667%}.col-lg-push-1{left:8.33333333%}.col-lg-push-0{left:0}.col-lg-offset-12{margin-left:100%}.col-lg-offset-11{margin-left:91.66666667%}.col-lg-offset-10{margin-left:83.33333333%}.col-lg-offset-9{margin-left:75%}.col-lg-offset-8{margin-left:66.66666667%}.col-lg-offset-7{margin-left:58.33333333%}.col-lg-offset-6{margin-left:50%}.col-lg-offset-5{margin-left:41.66666667%}.col-lg-offset-4{margin-left:33.33333333%}.col-lg-offset-3{margin-left:25%}.col-lg-offset-2{margin-left:16.66666667%}.col-lg-offset-1{margin-left:8.33333333%}.col-lg-offset-0{margin-left:0}}table{max-width:100%;background-color:transparent}th{text-align:left}.table{width:100%;margin-bottom:20px}.table>thead>tr>th,.table>tbody>tr>th,.table>tfoot>tr>th,.table>thead>tr>td,.table>tbody>tr>td,.table>tfoot>tr>td{padding:8px;line-height:1.42857143;vertical-align:top;border-top:1px solid #ddd}.table>thead>tr>th{vertical-align:bottom;border-bottom:2px solid #ddd}.table>caption+thead>tr:first-child>th,.table>colgroup+thead>tr:first-child>th,.table>thead:first-child>tr:first-child>th,.table>caption+thead>tr:first-child>td,.table>colgroup+thead>tr:first-child>td,.table>thead:first-child>tr:first-child>td{border-top:0}.table>tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed>thead>tr>th,.table-condensed>tbody>tr>th,.table-condensed>tfoot>tr>th,.table-condensed>thead>tr>td,.table-condensed>tbody>tr>td,.table-condensed>tfoot>tr>td{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>tbody>tr>td,.table-bordered>tfoot>tr>td{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>thead>tr>td{border-bottom-width:2px}.table-striped>tbody>tr:nth-child(odd)>td,.table-striped>tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.table-hover>tbody>tr:hover>td,.table-hover>tbody>tr:hover>th{background-color:#f5f5f5}table col[class*=col-]{position:static;float:none;display:table-column}table td[class*=col-],table th[class*=col-]{position:static;float:none;display:table-cell}.table>thead>tr>td.active,.table>tbody>tr>td.active,.table>tfoot>tr>td.active,.table>thead>tr>th.active,.table>tbody>tr>th.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>tbody>tr.active>td,.table>tfoot>tr.active>td,.table>thead>tr.active>th,.table>tbody>tr.active>th,.table>tfoot>tr.active>th{background-color:#f5f5f5}.table-hover>tbody>tr>td.active:hover,.table-hover>tbody>tr>th.active:hover,.table-hover>tbody>tr.active:hover>td,.table-hover>tbody>tr.active:hover>th{background-color:#e8e8e8}.table>thead>tr>td.success,.table>tbody>tr>td.success,.table>tfoot>tr>td.success,.table>thead>tr>th.success,.table>tbody>tr>th.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>tbody>tr.success>td,.table>tfoot>tr.success>td,.table>thead>tr.success>th,.table>tbody>tr.success>th,.table>tfoot>tr.success>th{background-color:#dff0d8}.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover,.table-hover>tbody>tr.success:hover>td,.table-hover>tbody>tr.success:hover>th{background-color:#d0e9c6}.table>thead>tr>td.info,.table>tbody>tr>td.info,.table>tfoot>tr>td.info,.table>thead>tr>th.info,.table>tbody>tr>th.info,.table>tfoot>tr>th.info,.table>thead>tr.info>td,.table>tbody>tr.info>td,.table>tfoot>tr.info>td,.table>thead>tr.info>th,.table>tbody>tr.info>th,.table>tfoot>tr.info>th{background-color:#d9edf7}.table-hover>tbody>tr>td.info:hover,.table-hover>tbody>tr>th.info:hover,.table-hover>tbody>tr.info:hover>td,.table-hover>tbody>tr.info:hover>th{background-color:#c4e3f3}.table>thead>tr>td.warning,.table>tbody>tr>td.warning,.table>tfoot>tr>td.warning,.table>thead>tr>th.warning,.table>tbody>tr>th.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>tbody>tr.warning>td,.table>tfoot>tr.warning>td,.table>thead>tr.warning>th,.table>tbody>tr.warning>th,.table>tfoot>tr.warning>th{background-color:#fcf8e3}.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover,.table-hover>tbody>tr.warning:hover>td,.table-hover>tbody>tr.warning:hover>th{background-color:#faf2cc}.table>thead>tr>td.danger,.table>tbody>tr>td.danger,.table>tfoot>tr>td.danger,.table>thead>tr>th.danger,.table>tbody>tr>th.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>tbody>tr.danger>td,.table>tfoot>tr.danger>td,.table>thead>tr.danger>th,.table>tbody>tr.danger>th,.table>tfoot>tr.danger>th{background-color:#f2dede}.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover,.table-hover>tbody>tr.danger:hover>td,.table-hover>tbody>tr.danger:hover>th{background-color:#ebcccc}@media (max-width:767px){.table-responsive{width:100%;margin-bottom:15px;overflow-y:hidden;overflow-x:scroll;-ms-overflow-style:-ms-autohiding-scrollbar;border:1px solid #ddd;-webkit-overflow-scrolling:touch}.table-responsive>.table{margin-bottom:0}.table-responsive>.table>thead>tr>th,.table-responsive>.table>tbody>tr>th,.table-responsive>.table>tfoot>tr>th,.table-responsive>.table>thead>tr>td,.table-responsive>.table>tbody>tr>td,.table-responsive>.table>tfoot>tr>td{white-space:nowrap}.table-responsive>.table-bordered{border:0}.table-responsive>.table-bordered>thead>tr>th:first-child,.table-responsive>.table-bordered>tbody>tr>th:first-child,.table-responsive>.table-bordered>tfoot>tr>th:first-child,.table-responsive>.table-bordered>thead>tr>td:first-child,.table-responsive>.table-bordered>tbody>tr>td:first-child,.table-responsive>.table-bordered>tfoot>tr>td:first-child{border-left:0}.table-responsive>.table-bordered>thead>tr>th:last-child,.table-responsive>.table-bordered>tbody>tr>th:last-child,.table-responsive>.table-bordered>tfoot>tr>th:last-child,.table-responsive>.table-bordered>thead>tr>td:last-child,.table-responsive>.table-bordered>tbody>tr>td:last-child,.table-responsive>.table-bordered>tfoot>tr>td:last-child{border-right:0}.table-responsive>.table-bordered>tbody>tr:last-child>th,.table-responsive>.table-bordered>tfoot>tr:last-child>th,.table-responsive>.table-bordered>tbody>tr:last-child>td,.table-responsive>.table-bordered>tfoot>tr:last-child>td{border-bottom:0}}fieldset{padding:0;margin:0;border:0;min-width:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;margin-bottom:5px;font-weight:700}input[type=search]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type=radio],input[type=checkbox]{margin:4px 0 0;margin-top:1px \9;line-height:normal}input[type=file]{display:block}input[type=range]{display:block;width:100%}select[multiple],select[size]{height:auto}input[type=file]:focus,input[type=radio]:focus,input[type=checkbox]:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}output{display:block;padding-top:7px;font-size:14px;line-height:1.42857143;color:#555}.form-control{display:block;width:100%;height:34px;padding:6px 12px;font-size:14px;line-height:1.42857143;color:#555;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.form-control::-moz-placeholder{color:#999;opacity:1}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee;opacity:1}textarea.form-control{height:auto}input[type=search]{-webkit-appearance:none}input[type=date]{line-height:34px}.form-group{margin-bottom:15px}.radio,.checkbox{display:block;min-height:20px;margin-top:10px;margin-bottom:10px;padding-left:20px}.radio label,.checkbox label{display:inline;font-weight:400;cursor:pointer}.radio input[type=radio],.radio-inline input[type=radio],.checkbox input[type=checkbox],.checkbox-inline input[type=checkbox]{float:left;margin-left:-20px}.radio+.radio,.checkbox+.checkbox{margin-top:-5px}.radio-inline,.checkbox-inline{display:inline-block;padding-left:20px;margin-bottom:0;vertical-align:middle;font-weight:400;cursor:pointer}.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline{margin-top:0;margin-left:10px}input[type=radio][disabled],input[type=checkbox][disabled],.radio[disabled],.radio-inline[disabled],.checkbox[disabled],.checkbox-inline[disabled],fieldset[disabled] input[type=radio],fieldset[disabled] input[type=checkbox],fieldset[disabled] .radio,fieldset[disabled] .radio-inline,fieldset[disabled] .checkbox,fieldset[disabled] .checkbox-inline{cursor:not-allowed}.input-sm{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-sm{height:30px;line-height:30px}textarea.input-sm,select[multiple].input-sm{height:auto}.input-lg{height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-lg{height:46px;line-height:46px}textarea.input-lg,select[multiple].input-lg{height:auto}.has-feedback{position:relative}.has-feedback .form-control{padding-right:42.5px}.has-feedback .form-control-feedback{position:absolute;top:25px;right:0;display:block;width:34px;height:34px;line-height:34px;text-align:center}.has-success .help-block,.has-success .control-label,.has-success .radio,.has-success .checkbox,.has-success .radio-inline,.has-success .checkbox-inline{color:#3c763d}.has-success .form-control{border-color:#3c763d;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-success .form-control:focus{border-color:#2b542c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168}.has-success .input-group-addon{color:#3c763d;border-color:#3c763d;background-color:#dff0d8}.has-success .form-control-feedback{color:#3c763d}.has-warning .help-block,.has-warning .control-label,.has-warning .radio,.has-warning .checkbox,.has-warning .radio-inline,.has-warning .checkbox-inline{color:#8a6d3b}.has-warning .form-control{border-color:#8a6d3b;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-warning .form-control:focus{border-color:#66512c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b}.has-warning .input-group-addon{color:#8a6d3b;border-color:#8a6d3b;background-color:#fcf8e3}.has-warning .form-control-feedback{color:#8a6d3b}.has-error .help-block,.has-error .control-label,.has-error .radio,.has-error .checkbox,.has-error .radio-inline,.has-error .checkbox-inline{color:#a94442}.has-error .form-control{border-color:#a94442;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-error .form-control:focus{border-color:#843534;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.has-error .input-group-addon{color:#a94442;border-color:#a94442;background-color:#f2dede}.has-error .form-control-feedback{color:#a94442}.form-control-static{margin-bottom:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}@media (min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .input-group>.form-control{width:100%}.form-inline .control-label{margin-bottom:0;vertical-align:middle}.form-inline .radio,.form-inline .checkbox{display:inline-block;margin-top:0;margin-bottom:0;padding-left:0;vertical-align:middle}.form-inline .radio input[type=radio],.form-inline .checkbox input[type=checkbox]{float:none;margin-left:0}.form-inline .has-feedback .form-control-feedback{top:0}}.form-horizontal .control-label,.form-horizontal .radio,.form-horizontal .checkbox,.form-horizontal .radio-inline,.form-horizontal .checkbox-inline{margin-top:0;margin-bottom:0;padding-top:7px}.form-horizontal .radio,.form-horizontal .checkbox{min-height:27px}.form-horizontal .form-group{margin-left:-15px;margin-right:-15px}.form-horizontal .form-control-static{padding-top:7px}@media (min-width:768px){.form-horizontal .control-label{text-align:right}}.form-horizontal .has-feedback .form-control-feedback{top:0;right:15px}.btn{display:inline-block;margin-bottom:0;font-weight:400;text-align:center;vertical-align:middle;cursor:pointer;background-image:none;border:1px solid transparent;white-space:nowrap;padding:6px 12px;font-size:14px;line-height:1.42857143;border-radius:4px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.btn:focus,.btn:active:focus,.btn.active:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn:hover,.btn:focus{color:#333;text-decoration:none}.btn:active,.btn.active{outline:0;background-image:none;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{cursor:not-allowed;pointer-events:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none}.btn-default{color:#333;background-color:#fff;border-color:#ccc}.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default{color:#333;background-color:#ebebeb;border-color:#adadad}.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default{background-image:none}.btn-default.disabled,.btn-default[disabled],fieldset[disabled] .btn-default,.btn-default.disabled:hover,.btn-default[disabled]:hover,fieldset[disabled] .btn-default:hover,.btn-default.disabled:focus,.btn-default[disabled]:focus,fieldset[disabled] .btn-default:focus,.btn-default.disabled:active,.btn-default[disabled]:active,fieldset[disabled] .btn-default:active,.btn-default.disabled.active,.btn-default[disabled].active,fieldset[disabled] .btn-default.active{background-color:#fff;border-color:#ccc}.btn-default .badge{color:#fff;background-color:#333}.btn-primary{color:#fff;background-color:#428bca;border-color:#357ebd}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary{color:#fff;background-color:#3276b1;border-color:#285e8e}.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary{background-image:none}.btn-primary.disabled,.btn-primary[disabled],fieldset[disabled] .btn-primary,.btn-primary.disabled:hover,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary:hover,.btn-primary.disabled:focus,.btn-primary[disabled]:focus,fieldset[disabled] .btn-primary:focus,.btn-primary.disabled:active,.btn-primary[disabled]:active,fieldset[disabled] .btn-primary:active,.btn-primary.disabled.active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary.active{background-color:#428bca;border-color:#357ebd}.btn-primary .badge{color:#428bca;background-color:#fff}.btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success{color:#fff;background-color:#47a447;border-color:#398439}.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success{background-image:none}.btn-success.disabled,.btn-success[disabled],fieldset[disabled] .btn-success,.btn-success.disabled:hover,.btn-success[disabled]:hover,fieldset[disabled] .btn-success:hover,.btn-success.disabled:focus,.btn-success[disabled]:focus,fieldset[disabled] .btn-success:focus,.btn-success.disabled:active,.btn-success[disabled]:active,fieldset[disabled] .btn-success:active,.btn-success.disabled.active,.btn-success[disabled].active,fieldset[disabled] .btn-success.active{background-color:#5cb85c;border-color:#4cae4c}.btn-success .badge{color:#5cb85c;background-color:#fff}.btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info{color:#fff;background-color:#39b3d7;border-color:#269abc}.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info{background-image:none}.btn-info.disabled,.btn-info[disabled],fieldset[disabled] .btn-info,.btn-info.disabled:hover,.btn-info[disabled]:hover,fieldset[disabled] .btn-info:hover,.btn-info.disabled:focus,.btn-info[disabled]:focus,fieldset[disabled] .btn-info:focus,.btn-info.disabled:active,.btn-info[disabled]:active,fieldset[disabled] .btn-info:active,.btn-info.disabled.active,.btn-info[disabled].active,fieldset[disabled] .btn-info.active{background-color:#5bc0de;border-color:#46b8da}.btn-info .badge{color:#5bc0de;background-color:#fff}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning{color:#fff;background-color:#ed9c28;border-color:#d58512}.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning{background-image:none}.btn-warning.disabled,.btn-warning[disabled],fieldset[disabled] .btn-warning,.btn-warning.disabled:hover,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning:hover,.btn-warning.disabled:focus,.btn-warning[disabled]:focus,fieldset[disabled] .btn-warning:focus,.btn-warning.disabled:active,.btn-warning[disabled]:active,fieldset[disabled] .btn-warning:active,.btn-warning.disabled.active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning.active{background-color:#f0ad4e;border-color:#eea236}.btn-warning .badge{color:#f0ad4e;background-color:#fff}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger{color:#fff;background-color:#d2322d;border-color:#ac2925}.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger{background-image:none}.btn-danger.disabled,.btn-danger[disabled],fieldset[disabled] .btn-danger,.btn-danger.disabled:hover,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger:hover,.btn-danger.disabled:focus,.btn-danger[disabled]:focus,fieldset[disabled] .btn-danger:focus,.btn-danger.disabled:active,.btn-danger[disabled]:active,fieldset[disabled] .btn-danger:active,.btn-danger.disabled.active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger.active{background-color:#d9534f;border-color:#d43f3a}.btn-danger .badge{color:#d9534f;background-color:#fff}.btn-link{color:#428bca;font-weight:400;cursor:pointer;border-radius:0}.btn-link,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active{border-color:transparent}.btn-link:hover,.btn-link:focus{color:#2a6496;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,fieldset[disabled] .btn-link:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:focus{color:#999;text-decoration:none}.btn-lg,.btn-group-lg>.btn{padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.btn-sm,.btn-group-sm>.btn{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-xs,.btn-group-xs>.btn{padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;transition:height .35s ease}@font-face{font-family:'Glyphicons Halflings';src:url(../fonts/glyphicons-halflings-regular.eot);src:url(../fonts/glyphicons-halflings-regular.eot?#iefix) format('embedded-opentype'),url(../fonts/glyphicons-halflings-regular.woff) format('woff'),url(../fonts/glyphicons-halflings-regular.ttf) format('truetype'),url(../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular) format('svg')}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.glyphicon-asterisk:before{content:"\2a"}.glyphicon-plus:before{content:"\2b"}.glyphicon-euro:before{content:"\20ac"}.glyphicon-minus:before{content:"\2212"}.glyphicon-cloud:before{content:"\2601"}.glyphicon-envelope:before{content:"\2709"}.glyphicon-pencil:before{content:"\270f"}.glyphicon-glass:before{content:"\e001"}.glyphicon-music:before{content:"\e002"}.glyphicon-search:before{content:"\e003"}.glyphicon-heart:before{content:"\e005"}.glyphicon-star:before{content:"\e006"}.glyphicon-star-empty:before{content:"\e007"}.glyphicon-user:before{content:"\e008"}.glyphicon-film:before{content:"\e009"}.glyphicon-th-large:before{content:"\e010"}.glyphicon-th:before{content:"\e011"}.glyphicon-th-list:before{content:"\e012"}.glyphicon-ok:before{content:"\e013"}.glyphicon-remove:before{content:"\e014"}.glyphicon-zoom-in:before{content:"\e015"}.glyphicon-zoom-out:before{content:"\e016"}.glyphicon-off:before{content:"\e017"}.glyphicon-signal:before{content:"\e018"}.glyphicon-cog:before{content:"\e019"}.glyphicon-trash:before{content:"\e020"}.glyphicon-home:before{content:"\e021"}.glyphicon-file:before{content:"\e022"}.glyphicon-time:before{content:"\e023"}.glyphicon-road:before{content:"\e024"}.glyphicon-download-alt:before{content:"\e025"}.glyphicon-download:before{content:"\e026"}.glyphicon-upload:before{content:"\e027"}.glyphicon-inbox:before{content:"\e028"}.glyphicon-play-circle:before{content:"\e029"}.glyphicon-repeat:before{content:"\e030"}.glyphicon-refresh:before{content:"\e031"}.glyphicon-list-alt:before{content:"\e032"}.glyphicon-lock:before{content:"\e033"}.glyphicon-flag:before{content:"\e034"}.glyphicon-headphones:before{content:"\e035"}.glyphicon-volume-off:before{content:"\e036"}.glyphicon-volume-down:before{content:"\e037"}.glyphicon-volume-up:before{content:"\e038"}.glyphicon-qrcode:before{content:"\e039"}.glyphicon-barcode:before{content:"\e040"}.glyphicon-tag:before{content:"\e041"}.glyphicon-tags:before{content:"\e042"}.glyphicon-book:before{content:"\e043"}.glyphicon-bookmark:before{content:"\e044"}.glyphicon-print:before{content:"\e045"}.glyphicon-camera:before{content:"\e046"}.glyphicon-font:before{content:"\e047"}.glyphicon-bold:before{content:"\e048"}.glyphicon-italic:before{content:"\e049"}.glyphicon-text-height:before{content:"\e050"}.glyphicon-text-width:before{content:"\e051"}.glyphicon-align-left:before{content:"\e052"}.glyphicon-align-center:before{content:"\e053"}.glyphicon-align-right:before{content:"\e054"}.glyphicon-align-justify:before{content:"\e055"}.glyphicon-list:before{content:"\e056"}.glyphicon-indent-left:before{content:"\e057"}.glyphicon-indent-right:before{content:"\e058"}.glyphicon-facetime-video:before{content:"\e059"}.glyphicon-picture:before{content:"\e060"}.glyphicon-map-marker:before{content:"\e062"}.glyphicon-adjust:before{content:"\e063"}.glyphicon-tint:before{content:"\e064"}.glyphicon-edit:before{content:"\e065"}.glyphicon-share:before{content:"\e066"}.glyphicon-check:before{content:"\e067"}.glyphicon-move:before{content:"\e068"}.glyphicon-step-backward:before{content:"\e069"}.glyphicon-fast-backward:before{content:"\e070"}.glyphicon-backward:before{content:"\e071"}.glyphicon-play:before{content:"\e072"}.glyphicon-pause:before{content:"\e073"}.glyphicon-stop:before{content:"\e074"}.glyphicon-forward:before{content:"\e075"}.glyphicon-fast-forward:before{content:"\e076"}.glyphicon-step-forward:before{content:"\e077"}.glyphicon-eject:before{content:"\e078"}.glyphicon-chevron-left:before{content:"\e079"}.glyphicon-chevron-right:before{content:"\e080"}.glyphicon-plus-sign:before{content:"\e081"}.glyphicon-minus-sign:before{content:"\e082"}.glyphicon-remove-sign:before{content:"\e083"}.glyphicon-ok-sign:before{content:"\e084"}.glyphicon-question-sign:before{content:"\e085"}.glyphicon-info-sign:before{content:"\e086"}.glyphicon-screenshot:before{content:"\e087"}.glyphicon-remove-circle:before{content:"\e088"}.glyphicon-ok-circle:before{content:"\e089"}.glyphicon-ban-circle:before{content:"\e090"}.glyphicon-arrow-left:before{content:"\e091"}.glyphicon-arrow-right:before{content:"\e092"}.glyphicon-arrow-up:before{content:"\e093"}.glyphicon-arrow-down:before{content:"\e094"}.glyphicon-share-alt:before{content:"\e095"}.glyphicon-resize-full:before{content:"\e096"}.glyphicon-resize-small:before{content:"\e097"}.glyphicon-exclamation-sign:before{content:"\e101"}.glyphicon-gift:before{content:"\e102"}.glyphicon-leaf:before{content:"\e103"}.glyphicon-fire:before{content:"\e104"}.glyphicon-eye-open:before{content:"\e105"}.glyphicon-eye-close:before{content:"\e106"}.glyphicon-warning-sign:before{content:"\e107"}.glyphicon-plane:before{content:"\e108"}.glyphicon-calendar:before{content:"\e109"}.glyphicon-random:before{content:"\e110"}.glyphicon-comment:before{content:"\e111"}.glyphicon-magnet:before{content:"\e112"}.glyphicon-chevron-up:before{content:"\e113"}.glyphicon-chevron-down:before{content:"\e114"}.glyphicon-retweet:before{content:"\e115"}.glyphicon-shopping-cart:before{content:"\e116"}.glyphicon-folder-close:before{content:"\e117"}.glyphicon-folder-open:before{content:"\e118"}.glyphicon-resize-vertical:before{content:"\e119"}.glyphicon-resize-horizontal:before{content:"\e120"}.glyphicon-hdd:before{content:"\e121"}.glyphicon-bullhorn:before{content:"\e122"}.glyphicon-bell:before{content:"\e123"}.glyphicon-certificate:before{content:"\e124"}.glyphicon-thumbs-up:before{content:"\e125"}.glyphicon-thumbs-down:before{content:"\e126"}.glyphicon-hand-right:before{content:"\e127"}.glyphicon-hand-left:before{content:"\e128"}.glyphicon-hand-up:before{content:"\e129"}.glyphicon-hand-down:before{content:"\e130"}.glyphicon-circle-arrow-right:before{content:"\e131"}.glyphicon-circle-arrow-left:before{content:"\e132"}.glyphicon-circle-arrow-up:before{content:"\e133"}.glyphicon-circle-arrow-down:before{content:"\e134"}.glyphicon-globe:before{content:"\e135"}.glyphicon-wrench:before{content:"\e136"}.glyphicon-tasks:before{content:"\e137"}.glyphicon-filter:before{content:"\e138"}.glyphicon-briefcase:before{content:"\e139"}.glyphicon-fullscreen:before{content:"\e140"}.glyphicon-dashboard:before{content:"\e141"}.glyphicon-paperclip:before{content:"\e142"}.glyphicon-heart-empty:before{content:"\e143"}.glyphicon-link:before{content:"\e144"}.glyphicon-phone:before{content:"\e145"}.glyphicon-pushpin:before{content:"\e146"}.glyphicon-usd:before{content:"\e148"}.glyphicon-gbp:before{content:"\e149"}.glyphicon-sort:before{content:"\e150"}.glyphicon-sort-by-alphabet:before{content:"\e151"}.glyphicon-sort-by-alphabet-alt:before{content:"\e152"}.glyphicon-sort-by-order:before{content:"\e153"}.glyphicon-sort-by-order-alt:before{content:"\e154"}.glyphicon-sort-by-attributes:before{content:"\e155"}.glyphicon-sort-by-attributes-alt:before{content:"\e156"}.glyphicon-unchecked:before{content:"\e157"}.glyphicon-expand:before{content:"\e158"}.glyphicon-collapse-down:before{content:"\e159"}.glyphicon-collapse-up:before{content:"\e160"}.glyphicon-log-in:before{content:"\e161"}.glyphicon-flash:before{content:"\e162"}.glyphicon-log-out:before{content:"\e163"}.glyphicon-new-window:before{content:"\e164"}.glyphicon-record:before{content:"\e165"}.glyphicon-save:before{content:"\e166"}.glyphicon-open:before{content:"\e167"}.glyphicon-saved:before{content:"\e168"}.glyphicon-import:before{content:"\e169"}.glyphicon-export:before{content:"\e170"}.glyphicon-send:before{content:"\e171"}.glyphicon-floppy-disk:before{content:"\e172"}.glyphicon-floppy-saved:before{content:"\e173"}.glyphicon-floppy-remove:before{content:"\e174"}.glyphicon-floppy-save:before{content:"\e175"}.glyphicon-floppy-open:before{content:"\e176"}.glyphicon-credit-card:before{content:"\e177"}.glyphicon-transfer:before{content:"\e178"}.glyphicon-cutlery:before{content:"\e179"}.glyphicon-header:before{content:"\e180"}.glyphicon-compressed:before{content:"\e181"}.glyphicon-earphone:before{content:"\e182"}.glyphicon-phone-alt:before{content:"\e183"}.glyphicon-tower:before{content:"\e184"}.glyphicon-stats:before{content:"\e185"}.glyphicon-sd-video:before{content:"\e186"}.glyphicon-hd-video:before{content:"\e187"}.glyphicon-subtitles:before{content:"\e188"}.glyphicon-sound-stereo:before{content:"\e189"}.glyphicon-sound-dolby:before{content:"\e190"}.glyphicon-sound-5-1:before{content:"\e191"}.glyphicon-sound-6-1:before{content:"\e192"}.glyphicon-sound-7-1:before{content:"\e193"}.glyphicon-copyright-mark:before{content:"\e194"}.glyphicon-registration-mark:before{content:"\e195"}.glyphicon-cloud-download:before{content:"\e197"}.glyphicon-cloud-upload:before{content:"\e198"}.glyphicon-tree-conifer:before{content:"\e199"}.glyphicon-tree-deciduous:before{content:"\e200"}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid;border-right:4px solid transparent;border-left:4px solid transparent}.dropdown{position:relative}.dropdown-toggle:focus{outline:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;font-size:14px;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,.175);box-shadow:0 6px 12px rgba(0,0,0,.175);background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:400;line-height:1.42857143;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus{text-decoration:none;color:#262626;background-color:#f5f5f5}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;outline:0;background-color:#428bca}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#999}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);cursor:not-allowed}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-menu-right{left:auto;right:0}.dropdown-menu-left{left:0;right:auto}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.42857143;color:#999}.dropdown-backdrop{position:fixed;left:0;right:0;bottom:0;top:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}@media (min-width:768px){.navbar-right .dropdown-menu{left:auto;right:0}.navbar-right .dropdown-menu-left{left:0;right:auto}}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group>.btn,.btn-group-vertical>.btn{position:relative;float:left}.btn-group>.btn:hover,.btn-group-vertical>.btn:hover,.btn-group>.btn:focus,.btn-group-vertical>.btn:focus,.btn-group>.btn:active,.btn-group-vertical>.btn:active,.btn-group>.btn.active,.btn-group-vertical>.btn.active{z-index:2}.btn-group>.btn:focus,.btn-group-vertical>.btn:focus{outline:0}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group{margin-left:-1px}.btn-toolbar{margin-left:-5px}.btn-toolbar .btn-group,.btn-toolbar .input-group{float:left}.btn-toolbar>.btn,.btn-toolbar>.btn-group,.btn-toolbar>.input-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-bottom-right-radius:0;border-top-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child>.btn:last-child,.btn-group>.btn-group:first-child>.dropdown-toggle{border-bottom-right-radius:0;border-top-right-radius:0}.btn-group>.btn-group:last-child>.btn:first-child{border-bottom-left-radius:0;border-top-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{padding-left:8px;padding-right:8px}.btn-group>.btn-lg+.dropdown-toggle{padding-left:12px;padding-right:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn-group.open .dropdown-toggle.btn-link{-webkit-box-shadow:none;box-shadow:none}.btn .caret{margin-left:0}.btn-lg .caret{border-width:5px 5px 0;border-bottom-width:0}.dropup .btn-lg .caret{border-width:0 5px 5px}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group,.btn-group-vertical>.btn-group>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn-group>.btn{float:none}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical>.btn:first-child:not(:last-child){border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn:last-child:not(:first-child){border-bottom-left-radius:4px;border-top-right-radius:0;border-top-left-radius:0}.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group-vertical>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group-vertical>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-right-radius:0;border-top-left-radius:0}.btn-group-justified{display:table;width:100%;table-layout:fixed;border-collapse:separate}.btn-group-justified>.btn,.btn-group-justified>.btn-group{float:none;display:table-cell;width:1%}.btn-group-justified>.btn-group .btn{width:100%}[data-toggle=buttons]>.btn>input[type=radio],[data-toggle=buttons]>.btn>input[type=checkbox]{display:none}.input-group{position:relative;display:table;border-collapse:separate}.input-group[class*=col-]{float:none;padding-left:0;padding-right:0}.input-group .form-control{position:relative;z-index:2;float:left;width:100%;margin-bottom:0}.input-group-lg>.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.btn{height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-group-lg>.form-control,select.input-group-lg>.input-group-addon,select.input-group-lg>.input-group-btn>.btn{height:46px;line-height:46px}textarea.input-group-lg>.form-control,textarea.input-group-lg>.input-group-addon,textarea.input-group-lg>.input-group-btn>.btn,select[multiple].input-group-lg>.form-control,select[multiple].input-group-lg>.input-group-addon,select[multiple].input-group-lg>.input-group-btn>.btn{height:auto}.input-group-sm>.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.btn{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-group-sm>.form-control,select.input-group-sm>.input-group-addon,select.input-group-sm>.input-group-btn>.btn{height:30px;line-height:30px}textarea.input-group-sm>.form-control,textarea.input-group-sm>.input-group-addon,textarea.input-group-sm>.input-group-btn>.btn,select[multiple].input-group-sm>.form-control,select[multiple].input-group-sm>.input-group-addon,select[multiple].input-group-sm>.input-group-btn>.btn{height:auto}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:6px 12px;font-size:14px;font-weight:400;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.input-group-addon.input-sm{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-lg{padding:10px 16px;font-size:18px;border-radius:6px}.input-group-addon input[type=radio],.input-group-addon input[type=checkbox]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle),.input-group-btn:last-child>.btn-group:not(:last-child)>.btn{border-bottom-right-radius:0;border-top-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child),.input-group-btn:first-child>.btn-group:not(:first-child)>.btn{border-bottom-left-radius:0;border-top-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;font-size:0;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-1px}.input-group-btn>.btn:hover,.input-group-btn>.btn:focus,.input-group-btn>.btn:active{z-index:2}.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group{margin-right:-1px}.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group{margin-left:-1px}.nav{margin-bottom:0;padding-left:0;list-style:none}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#999}.nav>li.disabled>a:hover,.nav>li.disabled>a:focus{color:#999;text-decoration:none;background-color:transparent;cursor:not-allowed}.nav .open>a,.nav .open>a:hover,.nav .open>a:focus{background-color:#eee;border-color:#428bca}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav>li>a>img{max-width:none}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.42857143;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee #eee #ddd}.nav-tabs>li.active>a,.nav-tabs>li.active>a:hover,.nav-tabs>li.active>a:focus{color:#555;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent;cursor:default}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{float:none}.nav-tabs.nav-justified>li>a{text-align:center;margin-bottom:5px}.nav-tabs.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-tabs.nav-justified>li{display:table-cell;width:1%}.nav-tabs.nav-justified>li>a{margin-bottom:0}}.nav-tabs.nav-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:hover,.nav-tabs.nav-justified>.active>a:focus{border:1px solid #ddd}@media (min-width:768px){.nav-tabs.nav-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:hover,.nav-tabs.nav-justified>.active>a:focus{border-bottom-color:#fff}}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:4px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:hover,.nav-pills>li.active>a:focus{color:#fff;background-color:#428bca}.nav-stacked>li{float:none}.nav-stacked>li+li{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{float:none}.nav-justified>li>a{text-align:center;margin-bottom:5px}.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-justified>li{display:table-cell;width:1%}.nav-justified>li>a{margin-bottom:0}}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:hover,.nav-tabs-justified>.active>a:focus{border:1px solid #ddd}@media (min-width:768px){.nav-tabs-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:hover,.nav-tabs-justified>.active>a:focus{border-bottom-color:#fff}}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-right-radius:0;border-top-left-radius:0}.navbar{position:relative;min-height:50px;margin-bottom:20px;border:1px solid transparent}@media (min-width:768px){.navbar{border-radius:4px}}@media (min-width:768px){.navbar-header{float:left}}.navbar-collapse{max-height:340px;overflow-x:visible;padding-right:15px;padding-left:15px;border-top:1px solid transparent;box-shadow:inset 0 1px 0 rgba(255,255,255,.1);-webkit-overflow-scrolling:touch}.navbar-collapse.in{overflow-y:auto}@media (min-width:768px){.navbar-collapse{width:auto;border-top:0;box-shadow:none}.navbar-collapse.collapse{display:block!important;height:auto!important;padding-bottom:0;overflow:visible!important}.navbar-collapse.in{overflow-y:visible}.navbar-fixed-top .navbar-collapse,.navbar-static-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse{padding-left:0;padding-right:0}}.container>.navbar-header,.container-fluid>.navbar-header,.container>.navbar-collapse,.container-fluid>.navbar-collapse{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.container>.navbar-header,.container-fluid>.navbar-header,.container>.navbar-collapse,.container-fluid>.navbar-collapse{margin-right:0;margin-left:0}}.navbar-static-top{z-index:1000;border-width:0 0 1px}@media (min-width:768px){.navbar-static-top{border-radius:0}}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030}@media (min-width:768px){.navbar-fixed-top,.navbar-fixed-bottom{border-radius:0}}.navbar-fixed-top{top:0;border-width:0 0 1px}.navbar-fixed-bottom{bottom:0;margin-bottom:0;border-width:1px 0 0}.navbar-brand{float:left;padding:15px;font-size:18px;line-height:20px;height:50px}.navbar-brand:hover,.navbar-brand:focus{text-decoration:none}@media (min-width:768px){.navbar>.container .navbar-brand,.navbar>.container-fluid .navbar-brand{margin-left:-15px}}.navbar-toggle{position:relative;float:right;margin-right:15px;padding:9px 10px;margin-top:8px;margin-bottom:8px;background-color:transparent;background-image:none;border:1px solid transparent;border-radius:4px}.navbar-toggle:focus{outline:0}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}@media (min-width:768px){.navbar-toggle{display:none}}.navbar-nav{margin:7.5px -15px}.navbar-nav>li>a{padding-top:10px;padding-bottom:10px;line-height:20px}@media (max-width:767px){.navbar-nav .open .dropdown-menu{position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;box-shadow:none}.navbar-nav .open .dropdown-menu>li>a,.navbar-nav .open .dropdown-menu .dropdown-header{padding:5px 15px 5px 25px}.navbar-nav .open .dropdown-menu>li>a{line-height:20px}.navbar-nav .open .dropdown-menu>li>a:hover,.navbar-nav .open .dropdown-menu>li>a:focus{background-image:none}}@media (min-width:768px){.navbar-nav{float:left;margin:0}.navbar-nav>li{float:left}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px}.navbar-nav.navbar-right:last-child{margin-right:-15px}}@media (min-width:768px){.navbar-left{float:left!important}.navbar-right{float:right!important}}.navbar-form{margin-left:-15px;margin-right:-15px;padding:10px 15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1);margin-top:8px;margin-bottom:8px}@media (min-width:768px){.navbar-form .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.navbar-form .form-control{display:inline-block;width:auto;vertical-align:middle}.navbar-form .input-group>.form-control{width:100%}.navbar-form .control-label{margin-bottom:0;vertical-align:middle}.navbar-form .radio,.navbar-form .checkbox{display:inline-block;margin-top:0;margin-bottom:0;padding-left:0;vertical-align:middle}.navbar-form .radio input[type=radio],.navbar-form .checkbox input[type=checkbox]{float:none;margin-left:0}.navbar-form .has-feedback .form-control-feedback{top:0}}@media (max-width:767px){.navbar-form .form-group{margin-bottom:5px}}@media (min-width:768px){.navbar-form{width:auto;border:0;margin-left:0;margin-right:0;padding-top:0;padding-bottom:0;-webkit-box-shadow:none;box-shadow:none}.navbar-form.navbar-right:last-child{margin-right:-15px}}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-right-radius:0;border-top-left-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-btn{margin-top:8px;margin-bottom:8px}.navbar-btn.btn-sm{margin-top:10px;margin-bottom:10px}.navbar-btn.btn-xs{margin-top:14px;margin-bottom:14px}.navbar-text{margin-top:15px;margin-bottom:15px}@media (min-width:768px){.navbar-text{float:left;margin-left:15px;margin-right:15px}.navbar-text.navbar-right:last-child{margin-right:0}}.navbar-default{background-color:#f8f8f8;border-color:#e7e7e7}.navbar-default .navbar-brand{color:#777}.navbar-default .navbar-brand:hover,.navbar-default .navbar-brand:focus{color:#5e5e5e;background-color:transparent}.navbar-default .navbar-text{color:#777}.navbar-default .navbar-nav>li>a{color:#777}.navbar-default .navbar-nav>li>a:hover,.navbar-default .navbar-nav>li>a:focus{color:#333;background-color:transparent}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:hover,.navbar-default .navbar-nav>.active>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:hover,.navbar-default .navbar-nav>.disabled>a:focus{color:#ccc;background-color:transparent}.navbar-default .navbar-toggle{border-color:#ddd}.navbar-default .navbar-toggle:hover,.navbar-default .navbar-toggle:focus{background-color:#ddd}.navbar-default .navbar-toggle .icon-bar{background-color:#888}.navbar-default .navbar-collapse,.navbar-default .navbar-form{border-color:#e7e7e7}.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:hover,.navbar-default .navbar-nav>.open>a:focus{background-color:#e7e7e7;color:#555}@media (max-width:767px){.navbar-default .navbar-nav .open .dropdown-menu>li>a{color:#777}.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus{color:#333;background-color:transparent}.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus{color:#ccc;background-color:transparent}}.navbar-default .navbar-link{color:#777}.navbar-default .navbar-link:hover{color:#333}.navbar-inverse{background-color:#222;border-color:#080808}.navbar-inverse .navbar-brand{color:#999}.navbar-inverse .navbar-brand:hover,.navbar-inverse .navbar-brand:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#999}.navbar-inverse .navbar-nav>li>a{color:#999}.navbar-inverse .navbar-nav>li>a:hover,.navbar-inverse .navbar-nav>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:hover,.navbar-inverse .navbar-nav>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:hover,.navbar-inverse .navbar-nav>.disabled>a:focus{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:hover,.navbar-inverse .navbar-toggle:focus{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form{border-color:#101010}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:hover,.navbar-inverse .navbar-nav>.open>a:focus{background-color:#080808;color:#fff}@media (max-width:767px){.navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header{border-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu .divider{background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a{color:#999}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus{color:#444;background-color:transparent}}.navbar-inverse .navbar-link{color:#999}.navbar-inverse .navbar-link:hover{color:#fff}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{content:"/\00a0";padding:0 5px;color:#ccc}.breadcrumb>.active{color:#999}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 12px;line-height:1.42857143;text-decoration:none;color:#428bca;background-color:#fff;border:1px solid #ddd;margin-left:-1px}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-bottom-left-radius:4px;border-top-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-bottom-right-radius:4px;border-top-right-radius:4px}.pagination>li>a:hover,.pagination>li>span:hover,.pagination>li>a:focus,.pagination>li>span:focus{color:#2a6496;background-color:#eee;border-color:#ddd}.pagination>.active>a,.pagination>.active>span,.pagination>.active>a:hover,.pagination>.active>span:hover,.pagination>.active>a:focus,.pagination>.active>span:focus{z-index:2;color:#fff;background-color:#428bca;border-color:#428bca;cursor:default}.pagination>.disabled>span,.pagination>.disabled>span:hover,.pagination>.disabled>span:focus,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus{color:#999;background-color:#fff;border-color:#ddd;cursor:not-allowed}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 16px;font-size:18px}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-bottom-left-radius:6px;border-top-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-bottom-right-radius:6px;border-top-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:12px}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-bottom-right-radius:3px;border-top-right-radius:3px}.pager{padding-left:0;margin:20px 0;list-style:none;text-align:center}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#eee}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#999;background-color:#fff;cursor:not-allowed}.label{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em}.label[href]:hover,.label[href]:focus{color:#fff;text-decoration:none;cursor:pointer}.label:empty{display:none}.btn .label{position:relative;top:-1px}.label-default{background-color:#999}.label-default[href]:hover,.label-default[href]:focus{background-color:gray}.label-primary{background-color:#428bca}.label-primary[href]:hover,.label-primary[href]:focus{background-color:#3071a9}.label-success{background-color:#5cb85c}.label-success[href]:hover,.label-success[href]:focus{background-color:#449d44}.label-info{background-color:#5bc0de}.label-info[href]:hover,.label-info[href]:focus{background-color:#31b0d5}.label-warning{background-color:#f0ad4e}.label-warning[href]:hover,.label-warning[href]:focus{background-color:#ec971f}.label-danger{background-color:#d9534f}.label-danger[href]:hover,.label-danger[href]:focus{background-color:#c9302c}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:700;color:#fff;line-height:1;vertical-align:baseline;white-space:nowrap;text-align:center;background-color:#999;border-radius:10px}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.btn-xs .badge{top:0;padding:1px 5px}a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}a.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#428bca;background-color:#fff}.nav-pills>li>a>.badge{margin-left:3px}.jumbotron{padding:30px;margin-bottom:30px;color:inherit;background-color:#eee}.jumbotron h1,.jumbotron .h1{color:inherit}.jumbotron p{margin-bottom:15px;font-size:21px;font-weight:200}.container .jumbotron{border-radius:6px}.jumbotron .container{max-width:100%}@media screen and (min-width:768px){.jumbotron{padding-top:48px;padding-bottom:48px}.container .jumbotron{padding-left:60px;padding-right:60px}.jumbotron h1,.jumbotron .h1{font-size:63px}}.thumbnail{display:block;padding:4px;margin-bottom:20px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.thumbnail>img,.thumbnail a>img{margin-left:auto;margin-right:auto}a.thumbnail:hover,a.thumbnail:focus,a.thumbnail.active{border-color:#428bca}.thumbnail .caption{padding:9px;color:#333}.alert{padding:15px;margin-bottom:20px;border:1px solid transparent;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert .alert-link{font-weight:700}.alert>p,.alert>ul{margin-bottom:0}.alert>p+p{margin-top:5px}.alert-dismissable{padding-right:35px}.alert-dismissable .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{background-color:#dff0d8;border-color:#d6e9c6;color:#3c763d}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#2b542c}.alert-info{background-color:#d9edf7;border-color:#bce8f1;color:#31708f}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#245269}.alert-warning{background-color:#fcf8e3;border-color:#faebcc;color:#8a6d3b}.alert-warning hr{border-top-color:#f7e1b5}.alert-warning .alert-link{color:#66512c}.alert-danger{background-color:#f2dede;border-color:#ebccd1;color:#a94442}.alert-danger hr{border-top-color:#e4b9c0}.alert-danger .alert-link{color:#843534}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{overflow:hidden;height:20px;margin-bottom:20px;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,.1);box-shadow:inset 0 1px 2px rgba(0,0,0,.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;line-height:20px;color:#fff;text-align:center;background-color:#428bca;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);-webkit-transition:width .6s ease;transition:width .6s ease}.progress-striped .progress-bar{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-size:40px 40px}.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.media,.media-body{overflow:hidden;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{padding-left:0;list-style:none}.list-group{margin-bottom:20px;padding-left:0}.list-group-item{position:relative;display:block;padding:10px 15px;margin-bottom:-1px;background-color:#fff;border:1px solid #ddd}.list-group-item:first-child{border-top-right-radius:4px;border-top-left-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.list-group-item>.badge{float:right}.list-group-item>.badge+.badge{margin-right:5px}a.list-group-item{color:#555}a.list-group-item .list-group-item-heading{color:#333}a.list-group-item:hover,a.list-group-item:focus{text-decoration:none;background-color:#f5f5f5}a.list-group-item.active,a.list-group-item.active:hover,a.list-group-item.active:focus{z-index:2;color:#fff;background-color:#428bca;border-color:#428bca}a.list-group-item.active .list-group-item-heading,a.list-group-item.active:hover .list-group-item-heading,a.list-group-item.active:focus .list-group-item-heading{color:inherit}a.list-group-item.active .list-group-item-text,a.list-group-item.active:hover .list-group-item-text,a.list-group-item.active:focus .list-group-item-text{color:#e1edf7}.list-group-item-success{color:#3c763d;background-color:#dff0d8}a.list-group-item-success{color:#3c763d}a.list-group-item-success .list-group-item-heading{color:inherit}a.list-group-item-success:hover,a.list-group-item-success:focus{color:#3c763d;background-color:#d0e9c6}a.list-group-item-success.active,a.list-group-item-success.active:hover,a.list-group-item-success.active:focus{color:#fff;background-color:#3c763d;border-color:#3c763d}.list-group-item-info{color:#31708f;background-color:#d9edf7}a.list-group-item-info{color:#31708f}a.list-group-item-info .list-group-item-heading{color:inherit}a.list-group-item-info:hover,a.list-group-item-info:focus{color:#31708f;background-color:#c4e3f3}a.list-group-item-info.active,a.list-group-item-info.active:hover,a.list-group-item-info.active:focus{color:#fff;background-color:#31708f;border-color:#31708f}.list-group-item-warning{color:#8a6d3b;background-color:#fcf8e3}a.list-group-item-warning{color:#8a6d3b}a.list-group-item-warning .list-group-item-heading{color:inherit}a.list-group-item-warning:hover,a.list-group-item-warning:focus{color:#8a6d3b;background-color:#faf2cc}a.list-group-item-warning.active,a.list-group-item-warning.active:hover,a.list-group-item-warning.active:focus{color:#fff;background-color:#8a6d3b;border-color:#8a6d3b}.list-group-item-danger{color:#a94442;background-color:#f2dede}a.list-group-item-danger{color:#a94442}a.list-group-item-danger .list-group-item-heading{color:inherit}a.list-group-item-danger:hover,a.list-group-item-danger:focus{color:#a94442;background-color:#ebcccc}a.list-group-item-danger.active,a.list-group-item-danger.active:hover,a.list-group-item-danger.active:focus{color:#fff;background-color:#a94442;border-color:#a94442}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}.panel{margin-bottom:20px;background-color:#fff;border:1px solid transparent;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.05);box-shadow:0 1px 1px rgba(0,0,0,.05)}.panel-body{padding:15px}.panel-heading{padding:10px 15px;border-bottom:1px solid transparent;border-top-right-radius:3px;border-top-left-radius:3px}.panel-heading>.dropdown .dropdown-toggle{color:inherit}.panel-title{margin-top:0;margin-bottom:0;font-size:16px;color:inherit}.panel-title>a{color:inherit}.panel-footer{padding:10px 15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.list-group{margin-bottom:0}.panel>.list-group .list-group-item{border-width:1px 0;border-radius:0}.panel>.list-group:first-child .list-group-item:first-child{border-top:0;border-top-right-radius:3px;border-top-left-radius:3px}.panel>.list-group:last-child .list-group-item:last-child{border-bottom:0;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel-heading+.list-group .list-group-item:first-child{border-top-width:0}.panel>.table,.panel>.table-responsive>.table{margin-bottom:0}.panel>.table:first-child,.panel>.table-responsive:first-child>.table:first-child{border-top-right-radius:3px;border-top-left-radius:3px}.panel>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table:first-child>thead:first-child>tr:first-child th:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:first-child{border-top-left-radius:3px}.panel>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table:first-child>thead:first-child>tr:first-child th:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:last-child{border-top-right-radius:3px}.panel>.table:last-child,.panel>.table-responsive:last-child>.table:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:first-child{border-bottom-left-radius:3px}.panel>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:last-child{border-bottom-right-radius:3px}.panel>.panel-body+.table,.panel>.panel-body+.table-responsive{border-top:1px solid #ddd}.panel>.table>tbody:first-child>tr:first-child th,.panel>.table>tbody:first-child>tr:first-child td{border-top:0}.panel>.table-bordered,.panel>.table-responsive>.table-bordered{border:0}.panel>.table-bordered>thead>tr>th:first-child,.panel>.table-responsive>.table-bordered>thead>tr>th:first-child,.panel>.table-bordered>tbody>tr>th:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:first-child,.panel>.table-bordered>tfoot>tr>th:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:first-child,.panel>.table-bordered>thead>tr>td:first-child,.panel>.table-responsive>.table-bordered>thead>tr>td:first-child,.panel>.table-bordered>tbody>tr>td:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:first-child,.panel>.table-bordered>tfoot>tr>td:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:first-child{border-left:0}.panel>.table-bordered>thead>tr>th:last-child,.panel>.table-responsive>.table-bordered>thead>tr>th:last-child,.panel>.table-bordered>tbody>tr>th:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:last-child,.panel>.table-bordered>tfoot>tr>th:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:last-child,.panel>.table-bordered>thead>tr>td:last-child,.panel>.table-responsive>.table-bordered>thead>tr>td:last-child,.panel>.table-bordered>tbody>tr>td:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:last-child,.panel>.table-bordered>tfoot>tr>td:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:last-child{border-right:0}.panel>.table-bordered>thead>tr:first-child>td,.panel>.table-responsive>.table-bordered>thead>tr:first-child>td,.panel>.table-bordered>tbody>tr:first-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>td,.panel>.table-bordered>thead>tr:first-child>th,.panel>.table-responsive>.table-bordered>thead>tr:first-child>th,.panel>.table-bordered>tbody>tr:first-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>th{border-bottom:0}.panel>.table-bordered>tbody>tr:last-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>td,.panel>.table-bordered>tfoot>tr:last-child>td,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>td,.panel>.table-bordered>tbody>tr:last-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>th,.panel>.table-bordered>tfoot>tr:last-child>th,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}.panel>.table-responsive{border:0;margin-bottom:0}.panel-group{margin-bottom:20px}.panel-group .panel{margin-bottom:0;border-radius:4px;overflow:hidden}.panel-group .panel+.panel{margin-top:5px}.panel-group .panel-heading{border-bottom:0}.panel-group .panel-heading+.panel-collapse .panel-body{border-top:1px solid #ddd}.panel-group .panel-footer{border-top:0}.panel-group .panel-footer+.panel-collapse .panel-body{border-bottom:1px solid #ddd}.panel-default{border-color:#ddd}.panel-default>.panel-heading{color:#333;background-color:#f5f5f5;border-color:#ddd}.panel-default>.panel-heading+.panel-collapse .panel-body{border-top-color:#ddd}.panel-default>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#ddd}.panel-primary{border-color:#428bca}.panel-primary>.panel-heading{color:#fff;background-color:#428bca;border-color:#428bca}.panel-primary>.panel-heading+.panel-collapse .panel-body{border-top-color:#428bca}.panel-primary>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#428bca}.panel-success{border-color:#d6e9c6}.panel-success>.panel-heading{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.panel-success>.panel-heading+.panel-collapse .panel-body{border-top-color:#d6e9c6}.panel-success>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#d6e9c6}.panel-info{border-color:#bce8f1}.panel-info>.panel-heading{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.panel-info>.panel-heading+.panel-collapse .panel-body{border-top-color:#bce8f1}.panel-info>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#bce8f1}.panel-warning{border-color:#faebcc}.panel-warning>.panel-heading{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.panel-warning>.panel-heading+.panel-collapse .panel-body{border-top-color:#faebcc}.panel-warning>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#faebcc}.panel-danger{border-color:#ebccd1}.panel-danger>.panel-heading{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.panel-danger>.panel-heading+.panel-collapse .panel-body{border-top-color:#ebccd1}.panel-danger>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#ebccd1}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.05);box-shadow:inset 0 1px 1px rgba(0,0,0,.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,.15)}.well-lg{padding:24px;border-radius:6px}.well-sm{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}button.close{padding:0;cursor:pointer;background:0 0;border:0;-webkit-appearance:none}.modal-open{overflow:hidden}.modal{display:none;overflow:auto;overflow-y:scroll;position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;-webkit-overflow-scrolling:touch;outline:0}.modal.fade .modal-dialog{-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);transform:translate(0,-25%);-webkit-transition:-webkit-transform .3s ease-out;-moz-transition:-moz-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out}.modal.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);transform:translate(0,0)}.modal-dialog{position:relative;width:auto;margin:10px}.modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,.2);border-radius:6px;-webkit-box-shadow:0 3px 9px rgba(0,0,0,.5);box-shadow:0 3px 9px rgba(0,0,0,.5);background-clip:padding-box;outline:0}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.modal-backdrop.in{opacity:.5;filter:alpha(opacity=50)}.modal-header{padding:15px;border-bottom:1px solid #e5e5e5;min-height:16.42857143px}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.42857143}.modal-body{position:relative;padding:20px}.modal-footer{margin-top:15px;padding:19px 20px 20px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer .btn+.btn{margin-left:5px;margin-bottom:0}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}@media (min-width:768px){.modal-dialog{width:600px;margin:30px auto}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,.5);box-shadow:0 5px 15px rgba(0,0,0,.5)}.modal-sm{width:300px}}@media (min-width:992px){.modal-lg{width:900px}}.tooltip{position:absolute;z-index:1030;display:block;visibility:visible;font-size:12px;line-height:1.4;opacity:0;filter:alpha(opacity=0)}.tooltip.in{opacity:.9;filter:alpha(opacity=90)}.tooltip.top{margin-top:-3px;padding:5px 0}.tooltip.right{margin-left:3px;padding:0 5px}.tooltip.bottom{margin-top:3px;padding:5px 0}.tooltip.left{margin-left:-3px;padding:0 5px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;text-decoration:none;background-color:#000;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-left .tooltip-arrow{bottom:0;left:5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-right .tooltip-arrow{bottom:0;right:5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-width:5px 5px 5px 0;border-right-color:#000}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-width:5px 0 5px 5px;border-left-color:#000}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-left .tooltip-arrow{top:0;left:5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-right .tooltip-arrow{top:0;right:5px;border-width:0 5px 5px;border-bottom-color:#000}.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;background-color:#fff;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,.2);box-shadow:0 5px 10px rgba(0,0,0,.2);white-space:normal}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{margin:0;padding:8px 14px;font-size:14px;font-weight:400;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover>.arrow,.popover>.arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover>.arrow{border-width:11px}.popover>.arrow:after{border-width:10px;content:""}.popover.top>.arrow{left:50%;margin-left:-11px;border-bottom-width:0;border-top-color:#999;border-top-color:rgba(0,0,0,.25);bottom:-11px}.popover.top>.arrow:after{content:" ";bottom:1px;margin-left:-10px;border-bottom-width:0;border-top-color:#fff}.popover.right>.arrow{top:50%;left:-11px;margin-top:-11px;border-left-width:0;border-right-color:#999;border-right-color:rgba(0,0,0,.25)}.popover.right>.arrow:after{content:" ";left:1px;bottom:-10px;border-left-width:0;border-right-color:#fff}.popover.bottom>.arrow{left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,.25);top:-11px}.popover.bottom>.arrow:after{content:" ";top:1px;margin-left:-10px;border-top-width:0;border-bottom-color:#fff}.popover.left>.arrow{top:50%;right:-11px;margin-top:-11px;border-right-width:0;border-left-color:#999;border-left-color:rgba(0,0,0,.25)}.popover.left>.arrow:after{content:" ";right:1px;border-right-width:0;border-left-color:#fff;bottom:-10px}.carousel{position:relative}.carousel-inner{position:relative;overflow:hidden;width:100%}.carousel-inner>.item{display:none;position:relative;-webkit-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;left:0;bottom:0;width:15%;opacity:.5;filter:alpha(opacity=50);font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.carousel-control.left{background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,.5) 0),color-stop(rgba(0,0,0,.0001) 100%));background-image:linear-gradient(to right,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1)}.carousel-control.right{left:auto;right:0;background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,.0001) 0),color-stop(rgba(0,0,0,.5) 100%));background-image:linear-gradient(to right,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1)}.carousel-control:hover,.carousel-control:focus{outline:0;color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.carousel-control .icon-prev,.carousel-control .icon-next,.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right{position:absolute;top:50%;z-index:5;display:inline-block}.carousel-control .icon-prev,.carousel-control .glyphicon-chevron-left{left:50%}.carousel-control .icon-next,.carousel-control .glyphicon-chevron-right{right:50%}.carousel-control .icon-prev,.carousel-control .icon-next{width:20px;height:20px;margin-top:-10px;margin-left:-10px;font-family:serif}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:60%;margin-left:-30%;padding-left:0;list-style:none;text-align:center}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;border:1px solid #fff;border-radius:10px;cursor:pointer;background-color:#000 \9;background-color:rgba(0,0,0,0)}.carousel-indicators .active{margin:0;width:12px;height:12px;background-color:#fff}.carousel-caption{position:absolute;left:15%;right:15%;bottom:20px;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-prev,.carousel-control .icon-next{width:30px;height:30px;margin-top:-15px;margin-left:-15px;font-size:30px}.carousel-caption{left:20%;right:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.clearfix:before,.clearfix:after,.container:before,.container:after,.container-fluid:before,.container-fluid:after,.row:before,.row:after,.form-horizontal .form-group:before,.form-horizontal .form-group:after,.btn-toolbar:before,.btn-toolbar:after,.btn-group-vertical>.btn-group:before,.btn-group-vertical>.btn-group:after,.nav:before,.nav:after,.navbar:before,.navbar:after,.navbar-header:before,.navbar-header:after,.navbar-collapse:before,.navbar-collapse:after,.pager:before,.pager:after,.panel-body:before,.panel-body:after,.modal-footer:before,.modal-footer:after{content:" ";display:table}.clearfix:after,.container:after,.container-fluid:after,.row:after,.form-horizontal .form-group:after,.btn-toolbar:after,.btn-group-vertical>.btn-group:after,.nav:after,.navbar:after,.navbar-header:after,.navbar-collapse:after,.pager:after,.panel-body:after,.modal-footer:after{clear:both}.center-block{display:block;margin-left:auto;margin-right:auto}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.hidden{display:none!important;visibility:hidden!important}.affix{position:fixed}@-ms-viewport{width:device-width}.visible-xs,.visible-sm,.visible-md,.visible-lg{display:none!important}@media (max-width:767px){.visible-xs{display:block!important}table.visible-xs{display:table}tr.visible-xs{display:table-row!important}th.visible-xs,td.visible-xs{display:table-cell!important}}@media (min-width:768px) and (max-width:991px){.visible-sm{display:block!important}table.visible-sm{display:table}tr.visible-sm{display:table-row!important}th.visible-sm,td.visible-sm{display:table-cell!important}}@media (min-width:992px) and (max-width:1199px){.visible-md{display:block!important}table.visible-md{display:table}tr.visible-md{display:table-row!important}th.visible-md,td.visible-md{display:table-cell!important}}@media (min-width:1200px){.visible-lg{display:block!important}table.visible-lg{display:table}tr.visible-lg{display:table-row!important}th.visible-lg,td.visible-lg{display:table-cell!important}}@media (max-width:767px){.hidden-xs{display:none!important}}@media (min-width:768px) and (max-width:991px){.hidden-sm{display:none!important}}@media (min-width:992px) and (max-width:1199px){.hidden-md{display:none!important}}@media (min-width:1200px){.hidden-lg{display:none!important}}.visible-print{display:none!important}@media print{.visible-print{display:block!important}table.visible-print{display:table}tr.visible-print{display:table-row!important}th.visible-print,td.visible-print{display:table-cell!important}}@media print{.hidden-print{display:none!important}} `
Godeps/_workspace/src/github.com/google/cadvisor/pages/static/bootstrap_min_css.go
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.0001785731001291424, 0.00017297269369009882, 0.00016936972679104656, 0.00017097528325393796, 0.000004013957550341729 ]
{ "id": 3, "code_window": [ "# Show Merged kubeconfig settings.\n", "$ kubectl config view\n", "\n", "# Get the password for the e2e user\n", "$ kubectl config view -o template --template='{{range .users}}{{ if eq .name \"e2e\" }}{{ index .user.password }}{{end}}{{end}}'\n", "```\n", "\n", "### Options\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "$ kubectl config view -o jsonpath='{.users[?(@.name == \"e2e\")].user.password}'\n" ], "file_path": "docs/user-guide/kubectl/kubectl_config_view.md", "type": "replace", "edit_start_line_idx": 56 }
/* Copyright 2015 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package endpoints import ( "bytes" "crypto/md5" "encoding/hex" "hash" "sort" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/types" hashutil "k8s.io/kubernetes/pkg/util/hash" ) // RepackSubsets takes a slice of EndpointSubset objects, expands it to the full // representation, and then repacks that into the canonical layout. This // ensures that code which operates on these objects can rely on the common // form for things like comparison. The result is a newly allocated slice. func RepackSubsets(subsets []api.EndpointSubset) []api.EndpointSubset { // First map each unique port definition to the sets of hosts that // offer it. allAddrs := map[addressKey]*api.EndpointAddress{} portToAddrReadyMap := map[api.EndpointPort]addressSet{} for i := range subsets { for _, port := range subsets[i].Ports { for k := range subsets[i].Addresses { mapAddressByPort(&subsets[i].Addresses[k], port, true, allAddrs, portToAddrReadyMap) } for k := range subsets[i].NotReadyAddresses { mapAddressByPort(&subsets[i].NotReadyAddresses[k], port, false, allAddrs, portToAddrReadyMap) } } } // Next, map the sets of hosts to the sets of ports they offer. // Go does not allow maps or slices as keys to maps, so we have // to synthesize an artificial key and do a sort of 2-part // associative entity. type keyString string keyToAddrReadyMap := map[keyString]addressSet{} addrReadyMapKeyToPorts := map[keyString][]api.EndpointPort{} for port, addrs := range portToAddrReadyMap { key := keyString(hashAddresses(addrs)) keyToAddrReadyMap[key] = addrs addrReadyMapKeyToPorts[key] = append(addrReadyMapKeyToPorts[key], port) } // Next, build the N-to-M association the API wants. final := []api.EndpointSubset{} for key, ports := range addrReadyMapKeyToPorts { var readyAddrs, notReadyAddrs []api.EndpointAddress for addr, ready := range keyToAddrReadyMap[key] { if ready { readyAddrs = append(readyAddrs, *addr) } else { notReadyAddrs = append(notReadyAddrs, *addr) } } final = append(final, api.EndpointSubset{Addresses: readyAddrs, NotReadyAddresses: notReadyAddrs, Ports: ports}) } // Finally, sort it. return SortSubsets(final) } // The sets of hosts must be de-duped, using IP+UID as the key. type addressKey struct { ip string uid types.UID } // mapAddressByPort adds an address into a map by its ports, registering the address with a unique pointer, and preserving // any existing ready state. func mapAddressByPort(addr *api.EndpointAddress, port api.EndpointPort, ready bool, allAddrs map[addressKey]*api.EndpointAddress, portToAddrReadyMap map[api.EndpointPort]addressSet) *api.EndpointAddress { // use addressKey to distinguish between two endpoints that are identical addresses // but may have come from different hosts, for attribution. For instance, Mesos // assigns pods the node IP, but the pods are distinct. key := addressKey{ip: addr.IP} if addr.TargetRef != nil { key.uid = addr.TargetRef.UID } // Accumulate the address. The full EndpointAddress structure is preserved for use when // we rebuild the subsets so that the final TargetRef has all of the necessary data. existingAddress := allAddrs[key] if existingAddress == nil { // Make a copy so we don't write to the // input args of this function. existingAddress = &api.EndpointAddress{} *existingAddress = *addr allAddrs[key] = existingAddress } // Remember that this port maps to this address. if _, found := portToAddrReadyMap[port]; !found { portToAddrReadyMap[port] = addressSet{} } // if we have not yet recorded this port for this address, or if the previous // state was ready, write the current ready state. not ready always trumps // ready. if wasReady, found := portToAddrReadyMap[port][existingAddress]; !found || wasReady { portToAddrReadyMap[port][existingAddress] = ready } return existingAddress } type addressSet map[*api.EndpointAddress]bool type addrReady struct { addr *api.EndpointAddress ready bool } func hashAddresses(addrs addressSet) string { // Flatten the list of addresses into a string so it can be used as a // map key. Unfortunately, DeepHashObject is implemented in terms of // spew, and spew does not handle non-primitive map keys well. So // first we collapse it into a slice, sort the slice, then hash that. slice := make([]addrReady, 0, len(addrs)) for k, ready := range addrs { slice = append(slice, addrReady{k, ready}) } sort.Sort(addrsReady(slice)) hasher := md5.New() hashutil.DeepHashObject(hasher, slice) return hex.EncodeToString(hasher.Sum(nil)[0:]) } func lessAddrReady(a, b addrReady) bool { // ready is not significant to hashing since we can't have duplicate addresses return LessEndpointAddress(a.addr, b.addr) } type addrsReady []addrReady func (sl addrsReady) Len() int { return len(sl) } func (sl addrsReady) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] } func (sl addrsReady) Less(i, j int) bool { return lessAddrReady(sl[i], sl[j]) } func LessEndpointAddress(a, b *api.EndpointAddress) bool { ipComparison := bytes.Compare([]byte(a.IP), []byte(b.IP)) if ipComparison != 0 { return ipComparison < 0 } if b.TargetRef == nil { return false } if a.TargetRef == nil { return true } return a.TargetRef.UID < b.TargetRef.UID } type addrPtrsByIpAndUID []*api.EndpointAddress func (sl addrPtrsByIpAndUID) Len() int { return len(sl) } func (sl addrPtrsByIpAndUID) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] } func (sl addrPtrsByIpAndUID) Less(i, j int) bool { return LessEndpointAddress(sl[i], sl[j]) } // SortSubsets sorts an array of EndpointSubset objects in place. For ease of // use it returns the input slice. func SortSubsets(subsets []api.EndpointSubset) []api.EndpointSubset { for i := range subsets { ss := &subsets[i] sort.Sort(addrsByIpAndUID(ss.Addresses)) sort.Sort(addrsByIpAndUID(ss.NotReadyAddresses)) sort.Sort(portsByHash(ss.Ports)) } sort.Sort(subsetsByHash(subsets)) return subsets } func hashObject(hasher hash.Hash, obj interface{}) []byte { hashutil.DeepHashObject(hasher, obj) return hasher.Sum(nil) } type subsetsByHash []api.EndpointSubset func (sl subsetsByHash) Len() int { return len(sl) } func (sl subsetsByHash) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] } func (sl subsetsByHash) Less(i, j int) bool { hasher := md5.New() h1 := hashObject(hasher, sl[i]) h2 := hashObject(hasher, sl[j]) return bytes.Compare(h1, h2) < 0 } type addrsByIpAndUID []api.EndpointAddress func (sl addrsByIpAndUID) Len() int { return len(sl) } func (sl addrsByIpAndUID) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] } func (sl addrsByIpAndUID) Less(i, j int) bool { return LessEndpointAddress(&sl[i], &sl[j]) } type portsByHash []api.EndpointPort func (sl portsByHash) Len() int { return len(sl) } func (sl portsByHash) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] } func (sl portsByHash) Less(i, j int) bool { hasher := md5.New() h1 := hashObject(hasher, sl[i]) h2 := hashObject(hasher, sl[j]) return bytes.Compare(h1, h2) < 0 }
pkg/api/endpoints/util.go
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.00023286460782401264, 0.00017351705173496157, 0.0001650635531404987, 0.00016998467617668211, 0.000013174254490877502 ]
{ "id": 3, "code_window": [ "# Show Merged kubeconfig settings.\n", "$ kubectl config view\n", "\n", "# Get the password for the e2e user\n", "$ kubectl config view -o template --template='{{range .users}}{{ if eq .name \"e2e\" }}{{ index .user.password }}{{end}}{{end}}'\n", "```\n", "\n", "### Options\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "$ kubectl config view -o jsonpath='{.users[?(@.name == \"e2e\")].user.password}'\n" ], "file_path": "docs/user-guide/kubectl/kubectl_config_view.md", "type": "replace", "edit_start_line_idx": 56 }
// Package rackconnect allows Rackspace cloud accounts to leverage version 3 of // RackConnect, Rackspace's hybrid connectivity solution connecting dedicated // and cloud servers. package rackconnect
Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/rackconnect/v3/doc.go
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.00016516320465598255, 0.00016516320465598255, 0.00016516320465598255, 0.00016516320465598255, 0 ]
{ "id": 4, "code_window": [ "\n", "* [kubectl config](kubectl_config.md)\t - config modifies kubeconfig files\n", "\n", "###### Auto generated by spf13/cobra on 8-Jan-2016\n", "\n", "<!-- BEGIN MUNGE: GENERATED_ANALYTICS -->\n", "[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/kubectl/kubectl_config_view.md?pixel)]()\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "###### Auto generated by spf13/cobra on 28-Jan-2016\n" ], "file_path": "docs/user-guide/kubectl/kubectl_config_view.md", "type": "replace", "edit_start_line_idx": 106 }
/* Copyright 2014 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package config import ( "errors" "io" "os" "path" "path/filepath" "reflect" "strconv" "github.com/golang/glog" "github.com/spf13/cobra" "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" ) type PathOptions struct { // GlobalFile is the full path to the file to load as the global (final) option GlobalFile string // EnvVar is the env var name that points to the list of kubeconfig files to load EnvVar string // ExplicitFileFlag is the name of the flag to use for prompting for the kubeconfig file ExplicitFileFlag string // GlobalFileSubpath is an optional value used for displaying help GlobalFileSubpath string LoadingRules *clientcmd.ClientConfigLoadingRules } // ConfigAccess is used by subcommands and methods in this package to load and modify the appropriate config files type ConfigAccess interface { // GetLoadingPrecedence returns the slice of files that should be used for loading and inspecting the config GetLoadingPrecedence() []string // GetStartingConfig returns the config that subcommands should being operating against. It may or may not be merged depending on loading rules GetStartingConfig() (*clientcmdapi.Config, error) // GetDefaultFilename returns the name of the file you should write into (create if necessary), if you're trying to create a new stanza as opposed to updating an existing one. GetDefaultFilename() string // IsExplicitFile indicates whether or not this command is interested in exactly one file. This implementation only ever does that via a flag, but implementations that handle local, global, and flags may have more IsExplicitFile() bool // GetExplicitFile returns the particular file this command is operating against. This implementation only ever has one, but implementations that handle local, global, and flags may have more GetExplicitFile() string } func NewCmdConfig(pathOptions *PathOptions, out io.Writer) *cobra.Command { if len(pathOptions.ExplicitFileFlag) == 0 { pathOptions.ExplicitFileFlag = clientcmd.RecommendedConfigPathFlag } cmd := &cobra.Command{ Use: "config SUBCOMMAND", Short: "config modifies kubeconfig files", Long: `config modifies kubeconfig files using subcommands like "kubectl config set current-context my-context" The loading order follows these rules: 1. If the --` + pathOptions.ExplicitFileFlag + ` flag is set, then only that file is loaded. The flag may only be set once and no merging takes place. 2. If $` + pathOptions.EnvVar + ` environment variable is set, then it is used a list of paths (normal path delimitting rules for your system). These paths are merged together. When a value is modified, it is modified in the file that defines the stanza. When a value is created, it is created in the first file that exists. If no files in the chain exist, then it creates the last file in the list. 3. Otherwise, ` + path.Join("${HOME}", pathOptions.GlobalFileSubpath) + ` is used and no merging takes place. `, Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, } // file paths are common to all sub commands cmd.PersistentFlags().StringVar(&pathOptions.LoadingRules.ExplicitPath, pathOptions.ExplicitFileFlag, pathOptions.LoadingRules.ExplicitPath, "use a particular kubeconfig file") cmd.AddCommand(NewCmdConfigView(out, pathOptions)) cmd.AddCommand(NewCmdConfigSetCluster(out, pathOptions)) cmd.AddCommand(NewCmdConfigSetAuthInfo(out, pathOptions)) cmd.AddCommand(NewCmdConfigSetContext(out, pathOptions)) cmd.AddCommand(NewCmdConfigSet(out, pathOptions)) cmd.AddCommand(NewCmdConfigUnset(out, pathOptions)) cmd.AddCommand(NewCmdConfigCurrentContext(out, pathOptions)) cmd.AddCommand(NewCmdConfigUseContext(out, pathOptions)) return cmd } func NewDefaultPathOptions() *PathOptions { ret := &PathOptions{ GlobalFile: clientcmd.RecommendedHomeFile, EnvVar: clientcmd.RecommendedConfigPathEnvVar, ExplicitFileFlag: clientcmd.RecommendedConfigPathFlag, GlobalFileSubpath: path.Join(clientcmd.RecommendedHomeDir, clientcmd.RecommendedFileName), LoadingRules: clientcmd.NewDefaultClientConfigLoadingRules(), } ret.LoadingRules.DoNotResolvePaths = true return ret } func (o *PathOptions) GetEnvVarFiles() []string { if len(o.EnvVar) == 0 { return []string{} } envVarValue := os.Getenv(o.EnvVar) if len(envVarValue) == 0 { return []string{} } return filepath.SplitList(envVarValue) } func (o *PathOptions) GetLoadingPrecedence() []string { if envVarFiles := o.GetEnvVarFiles(); len(envVarFiles) > 0 { return envVarFiles } return []string{o.GlobalFile} } func (o *PathOptions) GetStartingConfig() (*clientcmdapi.Config, error) { // don't mutate the original loadingRules := *o.LoadingRules loadingRules.Precedence = o.GetLoadingPrecedence() clientConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(&loadingRules, &clientcmd.ConfigOverrides{}) rawConfig, err := clientConfig.RawConfig() if os.IsNotExist(err) { return clientcmdapi.NewConfig(), nil } if err != nil { return nil, err } return &rawConfig, nil } func (o *PathOptions) GetDefaultFilename() string { if o.IsExplicitFile() { return o.GetExplicitFile() } if envVarFiles := o.GetEnvVarFiles(); len(envVarFiles) > 0 { if len(envVarFiles) == 1 { return envVarFiles[0] } // if any of the envvar files already exists, return it for _, envVarFile := range envVarFiles { if _, err := os.Stat(envVarFile); err == nil { return envVarFile } } // otherwise, return the last one in the list return envVarFiles[len(envVarFiles)-1] } return o.GlobalFile } func (o *PathOptions) IsExplicitFile() bool { if len(o.LoadingRules.ExplicitPath) > 0 { return true } return false } func (o *PathOptions) GetExplicitFile() string { return o.LoadingRules.ExplicitPath } // ModifyConfig takes a Config object, iterates through Clusters, AuthInfos, and Contexts, uses the LocationOfOrigin if specified or // uses the default destination file to write the results into. This results in multiple file reads, but it's very easy to follow. // Preferences and CurrentContext should always be set in the default destination file. Since we can't distinguish between empty and missing values // (no nil strings), we're forced have separate handling for them. In the kubeconfig cases, newConfig should have at most one difference, // that means that this code will only write into a single file. If you want to relativizePaths, you must provide a fully qualified path in any // modified element. func ModifyConfig(configAccess ConfigAccess, newConfig clientcmdapi.Config, relativizePaths bool) error { startingConfig, err := configAccess.GetStartingConfig() if err != nil { return err } // We need to find all differences, locate their original files, read a partial config to modify only that stanza and write out the file. // Special case the test for current context and preferences since those always write to the default file. if reflect.DeepEqual(*startingConfig, newConfig) { // nothing to do return nil } if startingConfig.CurrentContext != newConfig.CurrentContext { if err := writeCurrentContext(configAccess, newConfig.CurrentContext); err != nil { return err } } if !reflect.DeepEqual(startingConfig.Preferences, newConfig.Preferences) { if err := writePreferences(configAccess, newConfig.Preferences); err != nil { return err } } // Search every cluster, authInfo, and context. First from new to old for differences, then from old to new for deletions for key, cluster := range newConfig.Clusters { startingCluster, exists := startingConfig.Clusters[key] if !reflect.DeepEqual(cluster, startingCluster) || !exists { destinationFile := cluster.LocationOfOrigin if len(destinationFile) == 0 { destinationFile = configAccess.GetDefaultFilename() } configToWrite := getConfigFromFileOrDie(destinationFile) t := *cluster configToWrite.Clusters[key] = &t configToWrite.Clusters[key].LocationOfOrigin = destinationFile if relativizePaths { if err := clientcmd.RelativizeClusterLocalPaths(configToWrite.Clusters[key]); err != nil { return err } } if err := clientcmd.WriteToFile(*configToWrite, destinationFile); err != nil { return err } } } for key, context := range newConfig.Contexts { startingContext, exists := startingConfig.Contexts[key] if !reflect.DeepEqual(context, startingContext) || !exists { destinationFile := context.LocationOfOrigin if len(destinationFile) == 0 { destinationFile = configAccess.GetDefaultFilename() } configToWrite := getConfigFromFileOrDie(destinationFile) configToWrite.Contexts[key] = context if err := clientcmd.WriteToFile(*configToWrite, destinationFile); err != nil { return err } } } for key, authInfo := range newConfig.AuthInfos { startingAuthInfo, exists := startingConfig.AuthInfos[key] if !reflect.DeepEqual(authInfo, startingAuthInfo) || !exists { destinationFile := authInfo.LocationOfOrigin if len(destinationFile) == 0 { destinationFile = configAccess.GetDefaultFilename() } configToWrite := getConfigFromFileOrDie(destinationFile) t := *authInfo configToWrite.AuthInfos[key] = &t configToWrite.AuthInfos[key].LocationOfOrigin = destinationFile if relativizePaths { if err := clientcmd.RelativizeAuthInfoLocalPaths(configToWrite.AuthInfos[key]); err != nil { return err } } if err := clientcmd.WriteToFile(*configToWrite, destinationFile); err != nil { return err } } } for key, cluster := range startingConfig.Clusters { if _, exists := newConfig.Clusters[key]; !exists { destinationFile := cluster.LocationOfOrigin if len(destinationFile) == 0 { destinationFile = configAccess.GetDefaultFilename() } configToWrite := getConfigFromFileOrDie(destinationFile) delete(configToWrite.Clusters, key) if err := clientcmd.WriteToFile(*configToWrite, destinationFile); err != nil { return err } } } for key, context := range startingConfig.Contexts { if _, exists := newConfig.Contexts[key]; !exists { destinationFile := context.LocationOfOrigin if len(destinationFile) == 0 { destinationFile = configAccess.GetDefaultFilename() } configToWrite := getConfigFromFileOrDie(destinationFile) delete(configToWrite.Contexts, key) if err := clientcmd.WriteToFile(*configToWrite, destinationFile); err != nil { return err } } } for key, authInfo := range startingConfig.AuthInfos { if _, exists := newConfig.AuthInfos[key]; !exists { destinationFile := authInfo.LocationOfOrigin if len(destinationFile) == 0 { destinationFile = configAccess.GetDefaultFilename() } configToWrite := getConfigFromFileOrDie(destinationFile) delete(configToWrite.AuthInfos, key) if err := clientcmd.WriteToFile(*configToWrite, destinationFile); err != nil { return err } } } return nil } // writeCurrentContext takes three possible paths. // If newCurrentContext is the same as the startingConfig's current context, then we exit. // If newCurrentContext has a value, then that value is written into the default destination file. // If newCurrentContext is empty, then we find the config file that is setting the CurrentContext and clear the value from that file func writeCurrentContext(configAccess ConfigAccess, newCurrentContext string) error { if startingConfig, err := configAccess.GetStartingConfig(); err != nil { return err } else if startingConfig.CurrentContext == newCurrentContext { return nil } if configAccess.IsExplicitFile() { file := configAccess.GetExplicitFile() currConfig := getConfigFromFileOrDie(file) currConfig.CurrentContext = newCurrentContext if err := clientcmd.WriteToFile(*currConfig, file); err != nil { return err } return nil } if len(newCurrentContext) > 0 { destinationFile := configAccess.GetDefaultFilename() config := getConfigFromFileOrDie(destinationFile) config.CurrentContext = newCurrentContext if err := clientcmd.WriteToFile(*config, destinationFile); err != nil { return err } return nil } // we're supposed to be clearing the current context. We need to find the first spot in the chain that is setting it and clear it for _, file := range configAccess.GetLoadingPrecedence() { if _, err := os.Stat(file); err == nil { currConfig := getConfigFromFileOrDie(file) if len(currConfig.CurrentContext) > 0 { currConfig.CurrentContext = newCurrentContext if err := clientcmd.WriteToFile(*currConfig, file); err != nil { return err } return nil } } } return errors.New("no config found to write context") } func writePreferences(configAccess ConfigAccess, newPrefs clientcmdapi.Preferences) error { if startingConfig, err := configAccess.GetStartingConfig(); err != nil { return err } else if reflect.DeepEqual(startingConfig.Preferences, newPrefs) { return nil } if configAccess.IsExplicitFile() { file := configAccess.GetExplicitFile() currConfig := getConfigFromFileOrDie(file) currConfig.Preferences = newPrefs if err := clientcmd.WriteToFile(*currConfig, file); err != nil { return err } return nil } for _, file := range configAccess.GetLoadingPrecedence() { currConfig := getConfigFromFileOrDie(file) if !reflect.DeepEqual(currConfig.Preferences, newPrefs) { currConfig.Preferences = newPrefs if err := clientcmd.WriteToFile(*currConfig, file); err != nil { return err } return nil } } return errors.New("no config found to write preferences") } // getConfigFromFileOrDie tries to read a kubeconfig file and if it can't, it calls exit. One exception, missing files result in empty configs, not an exit func getConfigFromFileOrDie(filename string) *clientcmdapi.Config { config, err := clientcmd.LoadFromFile(filename) if err != nil && !os.IsNotExist(err) { glog.FatalDepth(1, err) } if config == nil { return clientcmdapi.NewConfig() } return config } func toBool(propertyValue string) (bool, error) { boolValue := false if len(propertyValue) != 0 { var err error boolValue, err = strconv.ParseBool(propertyValue) if err != nil { return false, err } } return boolValue, nil }
pkg/kubectl/cmd/config/config.go
1
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.0031179727520793676, 0.00028108368860557675, 0.00016460147162433714, 0.00016997754573822021, 0.0004386330838315189 ]
{ "id": 4, "code_window": [ "\n", "* [kubectl config](kubectl_config.md)\t - config modifies kubeconfig files\n", "\n", "###### Auto generated by spf13/cobra on 8-Jan-2016\n", "\n", "<!-- BEGIN MUNGE: GENERATED_ANALYTICS -->\n", "[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/kubectl/kubectl_config_view.md?pixel)]()\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "###### Auto generated by spf13/cobra on 28-Jan-2016\n" ], "file_path": "docs/user-guide/kubectl/kubectl_config_view.md", "type": "replace", "edit_start_line_idx": 106 }
#!/usr/bin/env python # Copyright 2015 The Kubernetes Authors All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The main hook file that is called by Juju. """ import os import socket import subprocess import sys import urlparse from charmhelpers.core import hookenv, host from kubernetes_installer import KubernetesInstaller from path import Path from lib.registrator import Registrator hooks = hookenv.Hooks() @hooks.hook('api-relation-changed') def api_relation_changed(): """ On the relation to the api server, this function determines the appropriate architecture and the configured version to copy the kubernetes binary files from the kubernetes-master charm and installs it locally on this machine. """ hookenv.log('Starting api-relation-changed') charm_dir = Path(hookenv.charm_dir()) # Get the package architecture, rather than the from the kernel (uname -m). arch = subprocess.check_output(['dpkg', '--print-architecture']).strip() kubernetes_bin_dir = Path('/opt/kubernetes/bin') # Get the version of kubernetes to install. version = subprocess.check_output(['relation-get', 'version']).strip() print('Relation version: ', version) if not version: print('No version present in the relation.') exit(0) version_file = charm_dir / '.version' if version_file.exists(): previous_version = version_file.text() print('Previous version: ', previous_version) if version == previous_version: exit(0) # Can not download binaries while the service is running, so stop it. # TODO: Figure out a better way to handle upgraded kubernetes binaries. for service in ('kubelet', 'proxy'): if host.service_running(service): host.service_stop(service) command = ['relation-get', 'private-address'] # Get the kubernetes-master address. server = subprocess.check_output(command).strip() print('Kubernetes master private address: ', server) installer = KubernetesInstaller(arch, version, server, kubernetes_bin_dir) installer.download() installer.install() # Write the most recently installed version number to the file. version_file.write_text(version) relation_changed() @hooks.hook('etcd-relation-changed', 'network-relation-changed') def relation_changed(): """Connect the parts and go :-) """ template_data = get_template_data() # Check required keys for k in ('etcd_servers', 'kubeapi_server'): if not template_data.get(k): print('Missing data for %s %s' % (k, template_data)) return print('Running with\n%s' % template_data) # Setup kubernetes supplemental group setup_kubernetes_group() # Register upstart managed services for n in ('kubelet', 'proxy'): if render_upstart(n, template_data) or not host.service_running(n): print('Starting %s' % n) host.service_restart(n) # Register machine via api print('Registering machine') register_machine(template_data['kubeapi_server']) # Save the marker (for restarts to detect prev install) template_data.save() def get_template_data(): rels = hookenv.relations() template_data = hookenv.Config() template_data.CONFIG_FILE_NAME = '.unit-state' overlay_type = get_scoped_rel_attr('network', rels, 'overlay_type') etcd_servers = get_rel_hosts('etcd', rels, ('hostname', 'port')) api_servers = get_rel_hosts('api', rels, ('hostname', 'port')) # kubernetes master isn't ha yet. if api_servers: api_info = api_servers.pop() api_servers = 'http://%s:%s' % (api_info[0], api_info[1]) template_data['overlay_type'] = overlay_type template_data['kubelet_bind_addr'] = _bind_addr( hookenv.unit_private_ip()) template_data['proxy_bind_addr'] = _bind_addr( hookenv.unit_get('public-address')) template_data['kubeapi_server'] = api_servers template_data['etcd_servers'] = ','.join([ 'http://%s:%s' % (s[0], s[1]) for s in sorted(etcd_servers)]) template_data['identifier'] = os.environ['JUJU_UNIT_NAME'].replace( '/', '-') return _encode(template_data) def _bind_addr(addr): if addr.replace('.', '').isdigit(): return addr try: return socket.gethostbyname(addr) except socket.error: raise ValueError('Could not resolve private address') def _encode(d): for k, v in d.items(): if isinstance(v, unicode): d[k] = v.encode('utf8') return d def get_scoped_rel_attr(rel_name, rels, attr): private_ip = hookenv.unit_private_ip() for r, data in rels.get(rel_name, {}).items(): for unit_id, unit_data in data.items(): if unit_data.get('private-address') != private_ip: continue if unit_data.get(attr): return unit_data.get(attr) def get_rel_hosts(rel_name, rels, keys=('private-address',)): hosts = [] for r, data in rels.get(rel_name, {}).items(): for unit_id, unit_data in data.items(): if unit_id == hookenv.local_unit(): continue values = [unit_data.get(k) for k in keys] if not all(values): continue hosts.append(len(values) == 1 and values[0] or values) return hosts def render_upstart(name, data): tmpl_path = os.path.join( os.environ.get('CHARM_DIR'), 'files', '%s.upstart.tmpl' % name) with open(tmpl_path) as fh: tmpl = fh.read() rendered = tmpl % data tgt_path = '/etc/init/%s.conf' % name if os.path.exists(tgt_path): with open(tgt_path) as fh: contents = fh.read() if contents == rendered: return False with open(tgt_path, 'w') as fh: fh.write(rendered) return True def register_machine(apiserver, retry=False): parsed = urlparse.urlparse(apiserver) # identity = hookenv.local_unit().replace('/', '-') private_address = hookenv.unit_private_ip() with open('/proc/meminfo') as fh: info = fh.readline() mem = info.strip().split(':')[1].strip().split()[0] cpus = os.sysconf('SC_NPROCESSORS_ONLN') # https://github.com/kubernetes/kubernetes/blob/master/docs/admin/node.md registration_request = Registrator() registration_request.data['kind'] = 'Node' registration_request.data['id'] = private_address registration_request.data['name'] = private_address registration_request.data['metadata']['name'] = private_address registration_request.data['spec']['capacity']['mem'] = mem + ' K' registration_request.data['spec']['capacity']['cpu'] = cpus registration_request.data['spec']['externalID'] = private_address registration_request.data['status']['hostIP'] = private_address try: response, result = registration_request.register(parsed.hostname, parsed.port, '/api/v1/nodes') except socket.error: hookenv.status_set('blocked', 'Error communicating with Kubenetes Master') return print(response) try: registration_request.command_succeeded(response, result) except ValueError: # This happens when we have already registered # for now this is OK pass def setup_kubernetes_group(): output = subprocess.check_output(['groups', 'kubernetes']) # TODO: check group exists if 'docker' not in output: subprocess.check_output( ['usermod', '-a', '-G', 'docker', 'kubernetes']) if __name__ == '__main__': hooks.execute(sys.argv)
cluster/juju/charms/trusty/kubernetes/hooks/hooks.py
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.00027424670406617224, 0.00017739151371642947, 0.0001655807573115453, 0.00016994545876514167, 0.000023020415028440766 ]
{ "id": 4, "code_window": [ "\n", "* [kubectl config](kubectl_config.md)\t - config modifies kubeconfig files\n", "\n", "###### Auto generated by spf13/cobra on 8-Jan-2016\n", "\n", "<!-- BEGIN MUNGE: GENERATED_ANALYTICS -->\n", "[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/kubectl/kubectl_config_view.md?pixel)]()\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "###### Auto generated by spf13/cobra on 28-Jan-2016\n" ], "file_path": "docs/user-guide/kubectl/kubectl_config_view.md", "type": "replace", "edit_start_line_idx": 106 }
// Copyright 2014 The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package prometheus // Collector is the interface implemented by anything that can be used by // Prometheus to collect metrics. A Collector has to be registered for // collection. See Register, MustRegister, RegisterOrGet, and MustRegisterOrGet. // // The stock metrics provided by this package (like Gauge, Counter, Summary) are // also Collectors (which only ever collect one metric, namely itself). An // implementer of Collector may, however, collect multiple metrics in a // coordinated fashion and/or create metrics on the fly. Examples for collectors // already implemented in this library are the metric vectors (i.e. collection // of multiple instances of the same Metric but with different label values) // like GaugeVec or SummaryVec, and the ExpvarCollector. type Collector interface { // Describe sends the super-set of all possible descriptors of metrics // collected by this Collector to the provided channel and returns once // the last descriptor has been sent. The sent descriptors fulfill the // consistency and uniqueness requirements described in the Desc // documentation. (It is valid if one and the same Collector sends // duplicate descriptors. Those duplicates are simply ignored. However, // two different Collectors must not send duplicate descriptors.) This // method idempotently sends the same descriptors throughout the // lifetime of the Collector. If a Collector encounters an error while // executing this method, it must send an invalid descriptor (created // with NewInvalidDesc) to signal the error to the registry. Describe(chan<- *Desc) // Collect is called by Prometheus when collecting metrics. The // implementation sends each collected metric via the provided channel // and returns once the last metric has been sent. The descriptor of // each sent metric is one of those returned by Describe. Returned // metrics that share the same descriptor must differ in their variable // label values. This method may be called concurrently and must // therefore be implemented in a concurrency safe way. Blocking occurs // at the expense of total performance of rendering all registered // metrics. Ideally, Collector implementations support concurrent // readers. Collect(chan<- Metric) } // SelfCollector implements Collector for a single Metric so that that the // Metric collects itself. Add it as an anonymous field to a struct that // implements Metric, and call Init with the Metric itself as an argument. type SelfCollector struct { self Metric } // Init provides the SelfCollector with a reference to the metric it is supposed // to collect. It is usually called within the factory function to create a // metric. See example. func (c *SelfCollector) Init(self Metric) { c.self = self } // Describe implements Collector. func (c *SelfCollector) Describe(ch chan<- *Desc) { ch <- c.self.Desc() } // Collect implements Collector. func (c *SelfCollector) Collect(ch chan<- Metric) { ch <- c.self }
Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/collector.go
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.0001731905504129827, 0.00016786198830232024, 0.0001600295363459736, 0.00016890479309950024, 0.000003777079200517619 ]
{ "id": 4, "code_window": [ "\n", "* [kubectl config](kubectl_config.md)\t - config modifies kubeconfig files\n", "\n", "###### Auto generated by spf13/cobra on 8-Jan-2016\n", "\n", "<!-- BEGIN MUNGE: GENERATED_ANALYTICS -->\n", "[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/kubectl/kubectl_config_view.md?pixel)]()\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "###### Auto generated by spf13/cobra on 28-Jan-2016\n" ], "file_path": "docs/user-guide/kubectl/kubectl_config_view.md", "type": "replace", "edit_start_line_idx": 106 }
// Copyright 2013 The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package model import ( "fmt" "sort" "strings" ) var separator = []byte{0} // A Metric is similar to a LabelSet, but the key difference is that a Metric is // a singleton and refers to one and only one stream of samples. type Metric LabelSet // Equal compares the metrics. func (m Metric) Equal(o Metric) bool { return LabelSet(m).Equal(LabelSet(o)) } // Before compares the metrics' underlying label sets. func (m Metric) Before(o Metric) bool { return LabelSet(m).Before(LabelSet(o)) } // Clone returns a copy of the Metric. func (m Metric) Clone() Metric { clone := Metric{} for k, v := range m { clone[k] = v } return clone } func (m Metric) String() string { metricName, hasName := m[MetricNameLabel] numLabels := len(m) - 1 if !hasName { numLabels = len(m) } labelStrings := make([]string, 0, numLabels) for label, value := range m { if label != MetricNameLabel { labelStrings = append(labelStrings, fmt.Sprintf("%s=%q", label, value)) } } switch numLabels { case 0: if hasName { return string(metricName) } return "{}" default: sort.Strings(labelStrings) return fmt.Sprintf("%s{%s}", metricName, strings.Join(labelStrings, ", ")) } } // Fingerprint returns a Metric's Fingerprint. func (m Metric) Fingerprint() Fingerprint { return LabelSet(m).Fingerprint() } // FastFingerprint returns a Metric's Fingerprint calculated by a faster hashing // algorithm, which is, however, more susceptible to hash collisions. func (m Metric) FastFingerprint() Fingerprint { return LabelSet(m).FastFingerprint() }
Godeps/_workspace/src/github.com/prometheus/common/model/metric.go
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.0001743058382999152, 0.00017013694741763175, 0.0001682820002315566, 0.00016926623356994241, 0.0000019879526007571258 ]
{ "id": 5, "code_window": [ "\t\tUse: \"config SUBCOMMAND\",\n", "\t\tShort: \"config modifies kubeconfig files\",\n", "\t\tLong: `config modifies kubeconfig files using subcommands like \"kubectl config set current-context my-context\"\n", "\n", "The loading order follows these rules:\n", " 1. If the --` + pathOptions.ExplicitFileFlag + ` flag is set, then only that file is loaded. The flag may only be set once and no merging takes place.\n", " 2. If $` + pathOptions.EnvVar + ` environment variable is set, then it is used a list of paths (normal path delimitting rules for your system). These paths are merged together. When a value is modified, it is modified in the file that defines the stanza. When a value is created, it is created in the first file that exists. If no files in the chain exist, then it creates the last file in the list.\n", " 3. Otherwise, ` + path.Join(\"${HOME}\", pathOptions.GlobalFileSubpath) + ` is used and no merging takes place.\n", "`,\n", "\t\tRun: func(cmd *cobra.Command, args []string) {\n", "\t\t\tcmd.Help()\n", "\t\t},\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "1. If the --` + pathOptions.ExplicitFileFlag + ` flag is set, then only that file is loaded. The flag may only be set once and no merging takes place.\n", "2. If $` + pathOptions.EnvVar + ` environment variable is set, then it is used a list of paths (normal path delimitting rules for your system). These paths are merged together. When a value is modified, it is modified in the file that defines the stanza. When a value is created, it is created in the first file that exists. If no files in the chain exist, then it creates the last file in the list.\n", "3. Otherwise, ` + path.Join(\"${HOME}\", pathOptions.GlobalFileSubpath) + ` is used and no merging takes place.\n" ], "file_path": "pkg/kubectl/cmd/config/config.go", "type": "replace", "edit_start_line_idx": 73 }
.TH "KUBERNETES" "1" " kubernetes User Manuals" "Eric Paris" "Jan 2015" "" .SH NAME .PP kubectl config view \- Displays merged kubeconfig settings or a specified kubeconfig file. .SH SYNOPSIS .PP \fBkubectl config view\fP [OPTIONS] .SH DESCRIPTION .PP Displays merged kubeconfig settings or a specified kubeconfig file. .PP You can use \-\-output=template \-\-template=TEMPLATE to extract specific values. .SH OPTIONS .PP \fB\-\-flatten\fP=false flatten the resulting kubeconfig file into self contained output (useful for creating portable kubeconfig files) .PP \fB\-\-merge\fP=true merge together the full hierarchy of kubeconfig files .PP \fB\-\-minify\fP=false remove all information not used by current\-context from the output .PP \fB\-\-no\-headers\fP=false When using the default output, don't print headers. .PP \fB\-o\fP, \fB\-\-output\fP="" Output format. One of: json|yaml|wide|name|go\-template=...|go\-template\-file=...|jsonpath=...|jsonpath\-file=... See golang template [ \[la]http://golang.org/pkg/text/template/#pkg-overview\[ra]] and jsonpath template [ \[la]http://releases.k8s.io/HEAD/docs/user-guide/jsonpath.md\[ra]]. .PP \fB\-\-output\-version\fP="" Output the formatted object with the given version (default api\-version). .PP \fB\-\-raw\fP=false display raw byte data .PP \fB\-a\fP, \fB\-\-show\-all\fP=false When printing, show all resources (default hide terminated pods.) .PP \fB\-\-sort\-by\fP="" If non\-empty, sort list types using this field specification. The field specification is expressed as a JSONPath expression (e.g. 'ObjectMeta.Name'). The field in the API resource specified by this JSONPath expression must be an integer or a string. .PP \fB\-\-template\fP="" Template string or path to template file to use when \-o=go\-template, \-o=go\-template\-file. The template format is golang templates [ \[la]http://golang.org/pkg/text/template/#pkg-overview\[ra]]. .SH OPTIONS INHERITED FROM PARENT COMMANDS .PP \fB\-\-alsologtostderr\fP=false log to standard error as well as files .PP \fB\-\-api\-version\fP="" The API version to use when talking to the server .PP \fB\-\-certificate\-authority\fP="" Path to a cert. file for the certificate authority. .PP \fB\-\-client\-certificate\fP="" Path to a client certificate file for TLS. .PP \fB\-\-client\-key\fP="" Path to a client key file for TLS. .PP \fB\-\-cluster\fP="" The name of the kubeconfig cluster to use .PP \fB\-\-context\fP="" The name of the kubeconfig context to use .PP \fB\-\-insecure\-skip\-tls\-verify\fP=false If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure. .PP \fB\-\-kubeconfig\fP="" use a particular kubeconfig file .PP \fB\-\-log\-backtrace\-at\fP=:0 when logging hits line file:N, emit a stack trace .PP \fB\-\-log\-dir\fP="" If non\-empty, write log files in this directory .PP \fB\-\-log\-flush\-frequency\fP=5s Maximum number of seconds between log flushes .PP \fB\-\-logtostderr\fP=true log to standard error instead of files .PP \fB\-\-match\-server\-version\fP=false Require server version to match client version .PP \fB\-\-namespace\fP="" If present, the namespace scope for this CLI request. .PP \fB\-\-password\fP="" Password for basic authentication to the API server. .PP \fB\-s\fP, \fB\-\-server\fP="" The address and port of the Kubernetes API server .PP \fB\-\-stderrthreshold\fP=2 logs at or above this threshold go to stderr .PP \fB\-\-token\fP="" Bearer token for authentication to the API server. .PP \fB\-\-user\fP="" The name of the kubeconfig user to use .PP \fB\-\-username\fP="" Username for basic authentication to the API server. .PP \fB\-\-v\fP=0 log level for V logs .PP \fB\-\-vmodule\fP= comma\-separated list of pattern=N settings for file\-filtered logging .SH EXAMPLE .PP .RS .nf # Show Merged kubeconfig settings. $ kubectl config view # Get the password for the e2e user $ kubectl config view \-o template \-\-template='{{range .users}}{{ if eq .name "e2e" }}{{ index .user.password }}{{end}}{{end}}' .fi .RE .SH SEE ALSO .PP \fBkubectl\-config(1)\fP, .SH HISTORY .PP January 2015, Originally compiled by Eric Paris (eparis at redhat dot com) based on the kubernetes source material, but hopefully they have been automatically generated since!
docs/man/man1/kubectl-config-view.1
1
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.0008624367765150964, 0.00023347379465121776, 0.0001658095425227657, 0.0001706422190181911, 0.00015684356912970543 ]
{ "id": 5, "code_window": [ "\t\tUse: \"config SUBCOMMAND\",\n", "\t\tShort: \"config modifies kubeconfig files\",\n", "\t\tLong: `config modifies kubeconfig files using subcommands like \"kubectl config set current-context my-context\"\n", "\n", "The loading order follows these rules:\n", " 1. If the --` + pathOptions.ExplicitFileFlag + ` flag is set, then only that file is loaded. The flag may only be set once and no merging takes place.\n", " 2. If $` + pathOptions.EnvVar + ` environment variable is set, then it is used a list of paths (normal path delimitting rules for your system). These paths are merged together. When a value is modified, it is modified in the file that defines the stanza. When a value is created, it is created in the first file that exists. If no files in the chain exist, then it creates the last file in the list.\n", " 3. Otherwise, ` + path.Join(\"${HOME}\", pathOptions.GlobalFileSubpath) + ` is used and no merging takes place.\n", "`,\n", "\t\tRun: func(cmd *cobra.Command, args []string) {\n", "\t\t\tcmd.Help()\n", "\t\t},\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "1. If the --` + pathOptions.ExplicitFileFlag + ` flag is set, then only that file is loaded. The flag may only be set once and no merging takes place.\n", "2. If $` + pathOptions.EnvVar + ` environment variable is set, then it is used a list of paths (normal path delimitting rules for your system). These paths are merged together. When a value is modified, it is modified in the file that defines the stanza. When a value is created, it is created in the first file that exists. If no files in the chain exist, then it creates the last file in the list.\n", "3. Otherwise, ` + path.Join(\"${HOME}\", pathOptions.GlobalFileSubpath) + ` is used and no merging takes place.\n" ], "file_path": "pkg/kubectl/cmd/config/config.go", "type": "replace", "edit_start_line_idx": 73 }
foo."-1"
Godeps/_workspace/src/github.com/jmespath/go-jmespath/fuzz/corpus/expr-17
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.00016629291349090636, 0.00016629291349090636, 0.00016629291349090636, 0.00016629291349090636, 0 ]
{ "id": 5, "code_window": [ "\t\tUse: \"config SUBCOMMAND\",\n", "\t\tShort: \"config modifies kubeconfig files\",\n", "\t\tLong: `config modifies kubeconfig files using subcommands like \"kubectl config set current-context my-context\"\n", "\n", "The loading order follows these rules:\n", " 1. If the --` + pathOptions.ExplicitFileFlag + ` flag is set, then only that file is loaded. The flag may only be set once and no merging takes place.\n", " 2. If $` + pathOptions.EnvVar + ` environment variable is set, then it is used a list of paths (normal path delimitting rules for your system). These paths are merged together. When a value is modified, it is modified in the file that defines the stanza. When a value is created, it is created in the first file that exists. If no files in the chain exist, then it creates the last file in the list.\n", " 3. Otherwise, ` + path.Join(\"${HOME}\", pathOptions.GlobalFileSubpath) + ` is used and no merging takes place.\n", "`,\n", "\t\tRun: func(cmd *cobra.Command, args []string) {\n", "\t\t\tcmd.Help()\n", "\t\t},\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "1. If the --` + pathOptions.ExplicitFileFlag + ` flag is set, then only that file is loaded. The flag may only be set once and no merging takes place.\n", "2. If $` + pathOptions.EnvVar + ` environment variable is set, then it is used a list of paths (normal path delimitting rules for your system). These paths are merged together. When a value is modified, it is modified in the file that defines the stanza. When a value is created, it is created in the first file that exists. If no files in the chain exist, then it creates the last file in the list.\n", "3. Otherwise, ` + path.Join(\"${HOME}\", pathOptions.GlobalFileSubpath) + ` is used and no merging takes place.\n" ], "file_path": "pkg/kubectl/cmd/config/config.go", "type": "replace", "edit_start_line_idx": 73 }
// +build proto /* Copyright 2015 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package protobuf import ( "fmt" "io" "net/url" "reflect" "github.com/gogo/protobuf/proto" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/runtime" ) // NewCodec func NewCodec(version string, creater runtime.ObjectCreater, typer runtime.ObjectTyper, convertor runtime.ObjectConvertor) runtime.Codec { return &codec{ version: version, creater: creater, typer: typer, convertor: convertor, } } // codec decodes protobuf objects type codec struct { version string outputVersion string creater runtime.ObjectCreater typer runtime.ObjectTyper convertor runtime.ObjectConvertor } var _ runtime.Codec = codec{} func (c codec) Decode(data []byte) (runtime.Object, error) { unknown := &runtime.Unknown{} if err := proto.Unmarshal(data, unknown); err != nil { return nil, err } obj, err := c.creater.New(unknown.APIVersion, unknown.Kind) if err != nil { return nil, err } pobj, ok := obj.(proto.Message) if !ok { return nil, fmt.Errorf("runtime object is not a proto.Message: %v", reflect.TypeOf(obj)) } if err := proto.Unmarshal(unknown.RawJSON, pobj); err != nil { return nil, err } if unknown.APIVersion != c.outputVersion { out, err := c.convertor.ConvertToVersion(obj, c.outputVersion) if err != nil { return nil, err } obj = out } return obj, nil } func (c codec) DecodeToVersion(data []byte, version unversioned.GroupVersion) (runtime.Object, error) { return nil, fmt.Errorf("unimplemented") } func (c codec) DecodeInto(data []byte, obj runtime.Object) error { version, kind, err := c.typer.ObjectVersionAndKind(obj) if err != nil { return err } unknown := &runtime.Unknown{} if err := proto.Unmarshal(data, unknown); err != nil { return err } if unknown.APIVersion == version && unknown.Kind == kind { pobj, ok := obj.(proto.Message) if !ok { return fmt.Errorf("runtime object is not a proto.Message: %v", reflect.TypeOf(obj)) } return proto.Unmarshal(unknown.RawJSON, pobj) } versioned, err := c.creater.New(unknown.APIVersion, unknown.Kind) if err != nil { return err } pobj, ok := versioned.(proto.Message) if !ok { return fmt.Errorf("runtime object is not a proto.Message: %v", reflect.TypeOf(obj)) } if err := proto.Unmarshal(unknown.RawJSON, pobj); err != nil { return err } return c.convertor.Convert(versioned, obj) } func (c codec) DecodeIntoWithSpecifiedVersionKind(data []byte, obj runtime.Object, kind unversioned.GroupVersionKind) error { return fmt.Errorf("unimplemented") } func (c codec) DecodeParametersInto(parameters url.Values, obj runtime.Object) error { return fmt.Errorf("unimplemented") } func (c codec) Encode(obj runtime.Object) (data []byte, err error) { version, kind, err := c.typer.ObjectVersionAndKind(obj) if err != nil { return nil, err } if len(version) == 0 { version = c.version converted, err := c.convertor.ConvertToVersion(obj, version) if err != nil { return nil, err } obj = converted } m, ok := obj.(proto.Marshaler) if !ok { return nil, fmt.Errorf("object %v (kind: %s in version: %s) does not implement ProtoBuf marshalling", reflect.TypeOf(obj), kind, c.version) } b, err := m.Marshal() if err != nil { return nil, err } return (&runtime.Unknown{ TypeMeta: runtime.TypeMeta{ Kind: kind, APIVersion: version, }, RawJSON: b, }).Marshal() } func (c codec) EncodeToStream(obj runtime.Object, stream io.Writer) error { return fmt.Errorf("unimplemented") }
pkg/runtime/protobuf/protobuf.go
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.00017560103151481599, 0.00016804953338578343, 0.0001602170232217759, 0.000168689526617527, 0.000003911833573511103 ]
{ "id": 5, "code_window": [ "\t\tUse: \"config SUBCOMMAND\",\n", "\t\tShort: \"config modifies kubeconfig files\",\n", "\t\tLong: `config modifies kubeconfig files using subcommands like \"kubectl config set current-context my-context\"\n", "\n", "The loading order follows these rules:\n", " 1. If the --` + pathOptions.ExplicitFileFlag + ` flag is set, then only that file is loaded. The flag may only be set once and no merging takes place.\n", " 2. If $` + pathOptions.EnvVar + ` environment variable is set, then it is used a list of paths (normal path delimitting rules for your system). These paths are merged together. When a value is modified, it is modified in the file that defines the stanza. When a value is created, it is created in the first file that exists. If no files in the chain exist, then it creates the last file in the list.\n", " 3. Otherwise, ` + path.Join(\"${HOME}\", pathOptions.GlobalFileSubpath) + ` is used and no merging takes place.\n", "`,\n", "\t\tRun: func(cmd *cobra.Command, args []string) {\n", "\t\t\tcmd.Help()\n", "\t\t},\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "1. If the --` + pathOptions.ExplicitFileFlag + ` flag is set, then only that file is loaded. The flag may only be set once and no merging takes place.\n", "2. If $` + pathOptions.EnvVar + ` environment variable is set, then it is used a list of paths (normal path delimitting rules for your system). These paths are merged together. When a value is modified, it is modified in the file that defines the stanza. When a value is created, it is created in the first file that exists. If no files in the chain exist, then it creates the last file in the list.\n", "3. Otherwise, ` + path.Join(\"${HOME}\", pathOptions.GlobalFileSubpath) + ` is used and no merging takes place.\n" ], "file_path": "pkg/kubectl/cmd/config/config.go", "type": "replace", "edit_start_line_idx": 73 }
/* Copyright 2015 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "bytes" "net/http" "strings" "testing" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/client/unversioned/fake" "k8s.io/kubernetes/pkg/kubectl" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/intstr" ) func TestRunExposeService(t *testing.T) { tests := []struct { name string args []string ns string calls map[string]string input runtime.Object flags map[string]string output runtime.Object expected string status int }{ { name: "expose-service-from-service-no-selector-defined", args: []string{"service", "baz"}, ns: "test", calls: map[string]string{ "GET": "/namespaces/test/services/baz", "POST": "/namespaces/test/services", }, input: &api.Service{ ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test", ResourceVersion: "12"}, Spec: api.ServiceSpec{ Selector: map[string]string{"app": "go"}, }, }, flags: map[string]string{"protocol": "UDP", "port": "14", "name": "foo", "labels": "svc=test"}, output: &api.Service{ ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "", Labels: map[string]string{"svc": "test"}}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{ { Protocol: api.ProtocolUDP, Port: 14, TargetPort: intstr.FromInt(14), }, }, Selector: map[string]string{"app": "go"}, }, }, expected: "service \"foo\" exposed", status: 200, }, { name: "expose-service-from-service", args: []string{"service", "baz"}, ns: "test", calls: map[string]string{ "GET": "/namespaces/test/services/baz", "POST": "/namespaces/test/services", }, input: &api.Service{ ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test", ResourceVersion: "12"}, Spec: api.ServiceSpec{ Selector: map[string]string{"app": "go"}, }, }, flags: map[string]string{"selector": "func=stream", "protocol": "UDP", "port": "14", "name": "foo", "labels": "svc=test"}, output: &api.Service{ ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "", Labels: map[string]string{"svc": "test"}}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{ { Protocol: api.ProtocolUDP, Port: 14, TargetPort: intstr.FromInt(14), }, }, Selector: map[string]string{"func": "stream"}, }, }, expected: "service \"foo\" exposed", status: 200, }, { name: "no-name-passed-from-the-cli", args: []string{"service", "mayor"}, ns: "default", calls: map[string]string{ "GET": "/namespaces/default/services/mayor", "POST": "/namespaces/default/services", }, input: &api.Service{ ObjectMeta: api.ObjectMeta{Name: "mayor", Namespace: "default", ResourceVersion: "12"}, Spec: api.ServiceSpec{ Selector: map[string]string{"run": "this"}, }, }, // No --name flag specified below. Service will use the rc's name passed via the 'default-name' parameter flags: map[string]string{"selector": "run=this", "port": "80", "labels": "runas=amayor"}, output: &api.Service{ ObjectMeta: api.ObjectMeta{Name: "mayor", Namespace: "", Labels: map[string]string{"runas": "amayor"}}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{ { Protocol: api.ProtocolTCP, Port: 80, TargetPort: intstr.FromInt(80), }, }, Selector: map[string]string{"run": "this"}, }, }, expected: "service \"mayor\" exposed", status: 200, }, { name: "expose-service", args: []string{"service", "baz"}, ns: "test", calls: map[string]string{ "GET": "/namespaces/test/services/baz", "POST": "/namespaces/test/services", }, input: &api.Service{ ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test", ResourceVersion: "12"}, Spec: api.ServiceSpec{ Selector: map[string]string{"app": "go"}, }, }, flags: map[string]string{"selector": "func=stream", "protocol": "UDP", "port": "14", "name": "foo", "labels": "svc=test", "type": "LoadBalancer", "dry-run": "true"}, output: &api.Service{ ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "", Labels: map[string]string{"svc": "test"}}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{ { Protocol: api.ProtocolUDP, Port: 14, TargetPort: intstr.FromInt(14), }, }, Selector: map[string]string{"func": "stream"}, Type: api.ServiceTypeLoadBalancer, }, }, status: 200, }, { name: "expose-affinity-service", args: []string{"service", "baz"}, ns: "test", calls: map[string]string{ "GET": "/namespaces/test/services/baz", "POST": "/namespaces/test/services", }, input: &api.Service{ ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test", ResourceVersion: "12"}, Spec: api.ServiceSpec{ Selector: map[string]string{"app": "go"}, }, }, flags: map[string]string{"selector": "func=stream", "protocol": "UDP", "port": "14", "name": "foo", "labels": "svc=test", "type": "LoadBalancer", "session-affinity": "ClientIP", "dry-run": "true"}, output: &api.Service{ ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "", Labels: map[string]string{"svc": "test"}}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{ { Protocol: api.ProtocolUDP, Port: 14, TargetPort: intstr.FromInt(14), }, }, Selector: map[string]string{"func": "stream"}, Type: api.ServiceTypeLoadBalancer, SessionAffinity: api.ServiceAffinityClientIP, }, }, status: 200, }, { name: "expose-from-file", args: []string{}, ns: "test", calls: map[string]string{ "GET": "/namespaces/test/services/redis-master", "POST": "/namespaces/test/services", }, input: &api.Service{ ObjectMeta: api.ObjectMeta{Name: "redis-master", Namespace: "test", ResourceVersion: "12"}, Spec: api.ServiceSpec{ Selector: map[string]string{"app": "go"}, }, }, flags: map[string]string{"filename": "../../../examples/guestbook/redis-master-service.yaml", "selector": "func=stream", "protocol": "UDP", "port": "14", "name": "foo", "labels": "svc=test", "dry-run": "true"}, output: &api.Service{ ObjectMeta: api.ObjectMeta{Name: "foo", Labels: map[string]string{"svc": "test"}}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{ { Protocol: api.ProtocolUDP, Port: 14, TargetPort: intstr.FromInt(14), }, }, Selector: map[string]string{"func": "stream"}, }, }, status: 200, }, { name: "truncate-name", args: []string{"pod", "a-name-that-is-toooo-big-for-a-service"}, ns: "test", calls: map[string]string{ "GET": "/namespaces/test/pods/a-name-that-is-toooo-big-for-a-service", "POST": "/namespaces/test/services", }, input: &api.Pod{ ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test", ResourceVersion: "12"}, }, flags: map[string]string{"selector": "svc=frompod", "port": "90", "labels": "svc=frompod", "generator": "service/v2"}, output: &api.Service{ ObjectMeta: api.ObjectMeta{Name: "a-name-that-is-toooo-big", Namespace: "", Labels: map[string]string{"svc": "frompod"}}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{ { Protocol: api.ProtocolTCP, Port: 90, TargetPort: intstr.FromInt(90), }, }, Selector: map[string]string{"svc": "frompod"}, }, }, expected: "service \"a-name-that-is-toooo-big\" exposed", status: 200, }, { name: "expose-multiport-object", args: []string{"service", "foo"}, ns: "test", calls: map[string]string{ "GET": "/namespaces/test/services/foo", "POST": "/namespaces/test/services", }, input: &api.Service{ ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "", Labels: map[string]string{"svc": "multiport"}}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{ { Protocol: api.ProtocolTCP, Port: 80, TargetPort: intstr.FromInt(80), }, { Protocol: api.ProtocolTCP, Port: 443, TargetPort: intstr.FromInt(443), }, }, }, }, flags: map[string]string{"selector": "svc=fromfoo", "generator": "service/v2", "name": "fromfoo", "dry-run": "true"}, output: &api.Service{ ObjectMeta: api.ObjectMeta{Name: "fromfoo", Namespace: "", Labels: map[string]string{"svc": "multiport"}}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{ { Name: "port-1", Protocol: api.ProtocolTCP, Port: 80, TargetPort: intstr.FromInt(80), }, { Name: "port-2", Protocol: api.ProtocolTCP, Port: 443, TargetPort: intstr.FromInt(443), }, }, Selector: map[string]string{"svc": "fromfoo"}, }, }, status: 200, }, } for _, test := range tests { f, tf, codec := NewAPIFactory() tf.Printer = &kubectl.JSONPrinter{} tf.Client = &fake.RESTClient{ Codec: codec, Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { switch p, m := req.URL.Path, req.Method; { case p == test.calls[m] && m == "GET": return &http.Response{StatusCode: test.status, Body: objBody(codec, test.input)}, nil case p == test.calls[m] && m == "POST": return &http.Response{StatusCode: test.status, Body: objBody(codec, test.output)}, nil default: t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) return nil, nil } }), } tf.Namespace = test.ns buf := bytes.NewBuffer([]byte{}) cmd := NewCmdExposeService(f, buf) cmd.SetOutput(buf) for flag, value := range test.flags { cmd.Flags().Set(flag, value) } cmd.Run(cmd, test.args) out := buf.String() if _, ok := test.flags["dry-run"]; ok { buf.Reset() if err := tf.Printer.PrintObj(test.output, buf); err != nil { t.Errorf("%s: Unexpected error: %v", test.name, err) continue } test.expected = buf.String() } if !strings.Contains(out, test.expected) { t.Errorf("%s: Unexpected output! Expected\n%s\ngot\n%s", test.name, test.expected, out) } } }
pkg/kubectl/cmd/expose_test.go
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.0011329979170113802, 0.0001943746756296605, 0.000163353601237759, 0.00016729591879993677, 0.00015868328046053648 ]
{ "id": 6, "code_window": [ "}\n", "\n", "const (\n", "\tview_long = `Displays merged kubeconfig settings or a specified kubeconfig file.\n", "\n", "You can use --output=template --template=TEMPLATE to extract specific values.`\n", "\tview_example = `# Show Merged kubeconfig settings.\n", "$ kubectl config view\n", "\n", "# Get the password for the e2e user\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "You can use --output jsonpath={...} to extract specific values using a jsonpath expression.`\n" ], "file_path": "pkg/kubectl/cmd/config/view.go", "type": "replace", "edit_start_line_idx": 44 }
/* Copyright 2014 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package config import ( "errors" "io" "os" "path" "path/filepath" "reflect" "strconv" "github.com/golang/glog" "github.com/spf13/cobra" "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" ) type PathOptions struct { // GlobalFile is the full path to the file to load as the global (final) option GlobalFile string // EnvVar is the env var name that points to the list of kubeconfig files to load EnvVar string // ExplicitFileFlag is the name of the flag to use for prompting for the kubeconfig file ExplicitFileFlag string // GlobalFileSubpath is an optional value used for displaying help GlobalFileSubpath string LoadingRules *clientcmd.ClientConfigLoadingRules } // ConfigAccess is used by subcommands and methods in this package to load and modify the appropriate config files type ConfigAccess interface { // GetLoadingPrecedence returns the slice of files that should be used for loading and inspecting the config GetLoadingPrecedence() []string // GetStartingConfig returns the config that subcommands should being operating against. It may or may not be merged depending on loading rules GetStartingConfig() (*clientcmdapi.Config, error) // GetDefaultFilename returns the name of the file you should write into (create if necessary), if you're trying to create a new stanza as opposed to updating an existing one. GetDefaultFilename() string // IsExplicitFile indicates whether or not this command is interested in exactly one file. This implementation only ever does that via a flag, but implementations that handle local, global, and flags may have more IsExplicitFile() bool // GetExplicitFile returns the particular file this command is operating against. This implementation only ever has one, but implementations that handle local, global, and flags may have more GetExplicitFile() string } func NewCmdConfig(pathOptions *PathOptions, out io.Writer) *cobra.Command { if len(pathOptions.ExplicitFileFlag) == 0 { pathOptions.ExplicitFileFlag = clientcmd.RecommendedConfigPathFlag } cmd := &cobra.Command{ Use: "config SUBCOMMAND", Short: "config modifies kubeconfig files", Long: `config modifies kubeconfig files using subcommands like "kubectl config set current-context my-context" The loading order follows these rules: 1. If the --` + pathOptions.ExplicitFileFlag + ` flag is set, then only that file is loaded. The flag may only be set once and no merging takes place. 2. If $` + pathOptions.EnvVar + ` environment variable is set, then it is used a list of paths (normal path delimitting rules for your system). These paths are merged together. When a value is modified, it is modified in the file that defines the stanza. When a value is created, it is created in the first file that exists. If no files in the chain exist, then it creates the last file in the list. 3. Otherwise, ` + path.Join("${HOME}", pathOptions.GlobalFileSubpath) + ` is used and no merging takes place. `, Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, } // file paths are common to all sub commands cmd.PersistentFlags().StringVar(&pathOptions.LoadingRules.ExplicitPath, pathOptions.ExplicitFileFlag, pathOptions.LoadingRules.ExplicitPath, "use a particular kubeconfig file") cmd.AddCommand(NewCmdConfigView(out, pathOptions)) cmd.AddCommand(NewCmdConfigSetCluster(out, pathOptions)) cmd.AddCommand(NewCmdConfigSetAuthInfo(out, pathOptions)) cmd.AddCommand(NewCmdConfigSetContext(out, pathOptions)) cmd.AddCommand(NewCmdConfigSet(out, pathOptions)) cmd.AddCommand(NewCmdConfigUnset(out, pathOptions)) cmd.AddCommand(NewCmdConfigCurrentContext(out, pathOptions)) cmd.AddCommand(NewCmdConfigUseContext(out, pathOptions)) return cmd } func NewDefaultPathOptions() *PathOptions { ret := &PathOptions{ GlobalFile: clientcmd.RecommendedHomeFile, EnvVar: clientcmd.RecommendedConfigPathEnvVar, ExplicitFileFlag: clientcmd.RecommendedConfigPathFlag, GlobalFileSubpath: path.Join(clientcmd.RecommendedHomeDir, clientcmd.RecommendedFileName), LoadingRules: clientcmd.NewDefaultClientConfigLoadingRules(), } ret.LoadingRules.DoNotResolvePaths = true return ret } func (o *PathOptions) GetEnvVarFiles() []string { if len(o.EnvVar) == 0 { return []string{} } envVarValue := os.Getenv(o.EnvVar) if len(envVarValue) == 0 { return []string{} } return filepath.SplitList(envVarValue) } func (o *PathOptions) GetLoadingPrecedence() []string { if envVarFiles := o.GetEnvVarFiles(); len(envVarFiles) > 0 { return envVarFiles } return []string{o.GlobalFile} } func (o *PathOptions) GetStartingConfig() (*clientcmdapi.Config, error) { // don't mutate the original loadingRules := *o.LoadingRules loadingRules.Precedence = o.GetLoadingPrecedence() clientConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(&loadingRules, &clientcmd.ConfigOverrides{}) rawConfig, err := clientConfig.RawConfig() if os.IsNotExist(err) { return clientcmdapi.NewConfig(), nil } if err != nil { return nil, err } return &rawConfig, nil } func (o *PathOptions) GetDefaultFilename() string { if o.IsExplicitFile() { return o.GetExplicitFile() } if envVarFiles := o.GetEnvVarFiles(); len(envVarFiles) > 0 { if len(envVarFiles) == 1 { return envVarFiles[0] } // if any of the envvar files already exists, return it for _, envVarFile := range envVarFiles { if _, err := os.Stat(envVarFile); err == nil { return envVarFile } } // otherwise, return the last one in the list return envVarFiles[len(envVarFiles)-1] } return o.GlobalFile } func (o *PathOptions) IsExplicitFile() bool { if len(o.LoadingRules.ExplicitPath) > 0 { return true } return false } func (o *PathOptions) GetExplicitFile() string { return o.LoadingRules.ExplicitPath } // ModifyConfig takes a Config object, iterates through Clusters, AuthInfos, and Contexts, uses the LocationOfOrigin if specified or // uses the default destination file to write the results into. This results in multiple file reads, but it's very easy to follow. // Preferences and CurrentContext should always be set in the default destination file. Since we can't distinguish between empty and missing values // (no nil strings), we're forced have separate handling for them. In the kubeconfig cases, newConfig should have at most one difference, // that means that this code will only write into a single file. If you want to relativizePaths, you must provide a fully qualified path in any // modified element. func ModifyConfig(configAccess ConfigAccess, newConfig clientcmdapi.Config, relativizePaths bool) error { startingConfig, err := configAccess.GetStartingConfig() if err != nil { return err } // We need to find all differences, locate their original files, read a partial config to modify only that stanza and write out the file. // Special case the test for current context and preferences since those always write to the default file. if reflect.DeepEqual(*startingConfig, newConfig) { // nothing to do return nil } if startingConfig.CurrentContext != newConfig.CurrentContext { if err := writeCurrentContext(configAccess, newConfig.CurrentContext); err != nil { return err } } if !reflect.DeepEqual(startingConfig.Preferences, newConfig.Preferences) { if err := writePreferences(configAccess, newConfig.Preferences); err != nil { return err } } // Search every cluster, authInfo, and context. First from new to old for differences, then from old to new for deletions for key, cluster := range newConfig.Clusters { startingCluster, exists := startingConfig.Clusters[key] if !reflect.DeepEqual(cluster, startingCluster) || !exists { destinationFile := cluster.LocationOfOrigin if len(destinationFile) == 0 { destinationFile = configAccess.GetDefaultFilename() } configToWrite := getConfigFromFileOrDie(destinationFile) t := *cluster configToWrite.Clusters[key] = &t configToWrite.Clusters[key].LocationOfOrigin = destinationFile if relativizePaths { if err := clientcmd.RelativizeClusterLocalPaths(configToWrite.Clusters[key]); err != nil { return err } } if err := clientcmd.WriteToFile(*configToWrite, destinationFile); err != nil { return err } } } for key, context := range newConfig.Contexts { startingContext, exists := startingConfig.Contexts[key] if !reflect.DeepEqual(context, startingContext) || !exists { destinationFile := context.LocationOfOrigin if len(destinationFile) == 0 { destinationFile = configAccess.GetDefaultFilename() } configToWrite := getConfigFromFileOrDie(destinationFile) configToWrite.Contexts[key] = context if err := clientcmd.WriteToFile(*configToWrite, destinationFile); err != nil { return err } } } for key, authInfo := range newConfig.AuthInfos { startingAuthInfo, exists := startingConfig.AuthInfos[key] if !reflect.DeepEqual(authInfo, startingAuthInfo) || !exists { destinationFile := authInfo.LocationOfOrigin if len(destinationFile) == 0 { destinationFile = configAccess.GetDefaultFilename() } configToWrite := getConfigFromFileOrDie(destinationFile) t := *authInfo configToWrite.AuthInfos[key] = &t configToWrite.AuthInfos[key].LocationOfOrigin = destinationFile if relativizePaths { if err := clientcmd.RelativizeAuthInfoLocalPaths(configToWrite.AuthInfos[key]); err != nil { return err } } if err := clientcmd.WriteToFile(*configToWrite, destinationFile); err != nil { return err } } } for key, cluster := range startingConfig.Clusters { if _, exists := newConfig.Clusters[key]; !exists { destinationFile := cluster.LocationOfOrigin if len(destinationFile) == 0 { destinationFile = configAccess.GetDefaultFilename() } configToWrite := getConfigFromFileOrDie(destinationFile) delete(configToWrite.Clusters, key) if err := clientcmd.WriteToFile(*configToWrite, destinationFile); err != nil { return err } } } for key, context := range startingConfig.Contexts { if _, exists := newConfig.Contexts[key]; !exists { destinationFile := context.LocationOfOrigin if len(destinationFile) == 0 { destinationFile = configAccess.GetDefaultFilename() } configToWrite := getConfigFromFileOrDie(destinationFile) delete(configToWrite.Contexts, key) if err := clientcmd.WriteToFile(*configToWrite, destinationFile); err != nil { return err } } } for key, authInfo := range startingConfig.AuthInfos { if _, exists := newConfig.AuthInfos[key]; !exists { destinationFile := authInfo.LocationOfOrigin if len(destinationFile) == 0 { destinationFile = configAccess.GetDefaultFilename() } configToWrite := getConfigFromFileOrDie(destinationFile) delete(configToWrite.AuthInfos, key) if err := clientcmd.WriteToFile(*configToWrite, destinationFile); err != nil { return err } } } return nil } // writeCurrentContext takes three possible paths. // If newCurrentContext is the same as the startingConfig's current context, then we exit. // If newCurrentContext has a value, then that value is written into the default destination file. // If newCurrentContext is empty, then we find the config file that is setting the CurrentContext and clear the value from that file func writeCurrentContext(configAccess ConfigAccess, newCurrentContext string) error { if startingConfig, err := configAccess.GetStartingConfig(); err != nil { return err } else if startingConfig.CurrentContext == newCurrentContext { return nil } if configAccess.IsExplicitFile() { file := configAccess.GetExplicitFile() currConfig := getConfigFromFileOrDie(file) currConfig.CurrentContext = newCurrentContext if err := clientcmd.WriteToFile(*currConfig, file); err != nil { return err } return nil } if len(newCurrentContext) > 0 { destinationFile := configAccess.GetDefaultFilename() config := getConfigFromFileOrDie(destinationFile) config.CurrentContext = newCurrentContext if err := clientcmd.WriteToFile(*config, destinationFile); err != nil { return err } return nil } // we're supposed to be clearing the current context. We need to find the first spot in the chain that is setting it and clear it for _, file := range configAccess.GetLoadingPrecedence() { if _, err := os.Stat(file); err == nil { currConfig := getConfigFromFileOrDie(file) if len(currConfig.CurrentContext) > 0 { currConfig.CurrentContext = newCurrentContext if err := clientcmd.WriteToFile(*currConfig, file); err != nil { return err } return nil } } } return errors.New("no config found to write context") } func writePreferences(configAccess ConfigAccess, newPrefs clientcmdapi.Preferences) error { if startingConfig, err := configAccess.GetStartingConfig(); err != nil { return err } else if reflect.DeepEqual(startingConfig.Preferences, newPrefs) { return nil } if configAccess.IsExplicitFile() { file := configAccess.GetExplicitFile() currConfig := getConfigFromFileOrDie(file) currConfig.Preferences = newPrefs if err := clientcmd.WriteToFile(*currConfig, file); err != nil { return err } return nil } for _, file := range configAccess.GetLoadingPrecedence() { currConfig := getConfigFromFileOrDie(file) if !reflect.DeepEqual(currConfig.Preferences, newPrefs) { currConfig.Preferences = newPrefs if err := clientcmd.WriteToFile(*currConfig, file); err != nil { return err } return nil } } return errors.New("no config found to write preferences") } // getConfigFromFileOrDie tries to read a kubeconfig file and if it can't, it calls exit. One exception, missing files result in empty configs, not an exit func getConfigFromFileOrDie(filename string) *clientcmdapi.Config { config, err := clientcmd.LoadFromFile(filename) if err != nil && !os.IsNotExist(err) { glog.FatalDepth(1, err) } if config == nil { return clientcmdapi.NewConfig() } return config } func toBool(propertyValue string) (bool, error) { boolValue := false if len(propertyValue) != 0 { var err error boolValue, err = strconv.ParseBool(propertyValue) if err != nil { return false, err } } return boolValue, nil }
pkg/kubectl/cmd/config/config.go
1
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.23836594820022583, 0.006500231102108955, 0.00016523394151590765, 0.0001721623120829463, 0.03513965755701065 ]
{ "id": 6, "code_window": [ "}\n", "\n", "const (\n", "\tview_long = `Displays merged kubeconfig settings or a specified kubeconfig file.\n", "\n", "You can use --output=template --template=TEMPLATE to extract specific values.`\n", "\tview_example = `# Show Merged kubeconfig settings.\n", "$ kubectl config view\n", "\n", "# Get the password for the e2e user\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "You can use --output jsonpath={...} to extract specific values using a jsonpath expression.`\n" ], "file_path": "pkg/kubectl/cmd/config/view.go", "type": "replace", "edit_start_line_idx": 44 }
// mkerrors.sh -m64 // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,solaris // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -m64 _const.go package unix import "syscall" const ( AF_802 = 0x12 AF_APPLETALK = 0x10 AF_CCITT = 0xa AF_CHAOS = 0x5 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_ECMA = 0x8 AF_FILE = 0x1 AF_GOSIP = 0x16 AF_HYLINK = 0xf AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x1a AF_INET_OFFLOAD = 0x1e AF_IPX = 0x17 AF_KEY = 0x1b AF_LAT = 0xe AF_LINK = 0x19 AF_LOCAL = 0x1 AF_MAX = 0x20 AF_NBS = 0x7 AF_NCA = 0x1c AF_NIT = 0x11 AF_NS = 0x6 AF_OSI = 0x13 AF_OSINET = 0x15 AF_PACKET = 0x20 AF_POLICY = 0x1d AF_PUP = 0x4 AF_ROUTE = 0x18 AF_SNA = 0xb AF_TRILL = 0x1f AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_X25 = 0x14 ARPHRD_ARCNET = 0x7 ARPHRD_ATM = 0x10 ARPHRD_AX25 = 0x3 ARPHRD_CHAOS = 0x5 ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_FC = 0x12 ARPHRD_FRAME = 0xf ARPHRD_HDLC = 0x11 ARPHRD_IB = 0x20 ARPHRD_IEEE802 = 0x6 ARPHRD_IPATM = 0x13 ARPHRD_METRICOM = 0x17 ARPHRD_TUNNEL = 0x1f B0 = 0x0 B110 = 0x3 B115200 = 0x12 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B153600 = 0x13 B1800 = 0xa B19200 = 0xe B200 = 0x6 B230400 = 0x14 B2400 = 0xb B300 = 0x7 B307200 = 0x15 B38400 = 0xf B460800 = 0x16 B4800 = 0xc B50 = 0x1 B57600 = 0x10 B600 = 0x8 B75 = 0x2 B76800 = 0x11 B921600 = 0x17 B9600 = 0xd BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDLT = 0x4004426a BIOCGDLTLIST = -0x3fefbd89 BIOCGDLTLIST32 = -0x3ff7bd89 BIOCGETIF = 0x4020426b BIOCGETLIF = 0x4078426b BIOCGHDRCMPLT = 0x40044274 BIOCGRTIMEOUT = 0x4010427b BIOCGRTIMEOUT32 = 0x4008427b BIOCGSEESENT = 0x40044278 BIOCGSTATS = 0x4080426f BIOCGSTATSOLD = 0x4008426f BIOCIMMEDIATE = -0x7ffbbd90 BIOCPROMISC = 0x20004269 BIOCSBLEN = -0x3ffbbd9a BIOCSDLT = -0x7ffbbd8a BIOCSETF = -0x7fefbd99 BIOCSETF32 = -0x7ff7bd99 BIOCSETIF = -0x7fdfbd94 BIOCSETLIF = -0x7f87bd94 BIOCSHDRCMPLT = -0x7ffbbd8b BIOCSRTIMEOUT = -0x7fefbd86 BIOCSRTIMEOUT32 = -0x7ff7bd86 BIOCSSEESENT = -0x7ffbbd87 BIOCSTCPF = -0x7fefbd8e BIOCSUDPF = -0x7fefbd8d BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x4 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DFLTBUFSIZE = 0x100000 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x1000000 BPF_MAXINSNS = 0x200 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 CFLUSH = 0xf CLOCAL = 0x800 CLOCK_HIGHRES = 0x4 CLOCK_LEVEL = 0xa CLOCK_MONOTONIC = 0x4 CLOCK_PROCESS_CPUTIME_ID = 0x5 CLOCK_PROF = 0x2 CLOCK_REALTIME = 0x3 CLOCK_THREAD_CPUTIME_ID = 0x2 CLOCK_VIRTUAL = 0x1 CREAD = 0x80 CS5 = 0x0 CS6 = 0x10 CS7 = 0x20 CS8 = 0x30 CSIZE = 0x30 CSTART = 0x11 CSTATUS = 0x14 CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a CSWTCH = 0x1a DLT_AIRONET_HEADER = 0x78 DLT_APPLE_IP_OVER_IEEE1394 = 0x8a DLT_ARCNET = 0x7 DLT_ARCNET_LINUX = 0x81 DLT_ATM_CLIP = 0x13 DLT_ATM_RFC1483 = 0xb DLT_AURORA = 0x7e DLT_AX25 = 0x3 DLT_BACNET_MS_TP = 0xa5 DLT_CHAOS = 0x5 DLT_CISCO_IOS = 0x76 DLT_C_HDLC = 0x68 DLT_DOCSIS = 0x8f DLT_ECONET = 0x73 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_ENC = 0x6d DLT_ERF_ETH = 0xaf DLT_ERF_POS = 0xb0 DLT_FDDI = 0xa DLT_FRELAY = 0x6b DLT_GCOM_SERIAL = 0xad DLT_GCOM_T1E1 = 0xac DLT_GPF_F = 0xab DLT_GPF_T = 0xaa DLT_GPRS_LLC = 0xa9 DLT_HDLC = 0x10 DLT_HHDLC = 0x79 DLT_HIPPI = 0xf DLT_IBM_SN = 0x92 DLT_IBM_SP = 0x91 DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_IEEE802_11_RADIO_AVS = 0xa3 DLT_IPNET = 0xe2 DLT_IPOIB = 0xa2 DLT_IP_OVER_FC = 0x7a DLT_JUNIPER_ATM1 = 0x89 DLT_JUNIPER_ATM2 = 0x87 DLT_JUNIPER_CHDLC = 0xb5 DLT_JUNIPER_ES = 0x84 DLT_JUNIPER_ETHER = 0xb2 DLT_JUNIPER_FRELAY = 0xb4 DLT_JUNIPER_GGSN = 0x85 DLT_JUNIPER_MFR = 0x86 DLT_JUNIPER_MLFR = 0x83 DLT_JUNIPER_MLPPP = 0x82 DLT_JUNIPER_MONITOR = 0xa4 DLT_JUNIPER_PIC_PEER = 0xae DLT_JUNIPER_PPP = 0xb3 DLT_JUNIPER_PPPOE = 0xa7 DLT_JUNIPER_PPPOE_ATM = 0xa8 DLT_JUNIPER_SERVICES = 0x88 DLT_LINUX_IRDA = 0x90 DLT_LINUX_LAPD = 0xb1 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c DLT_LTALK = 0x72 DLT_MTP2 = 0x8c DLT_MTP2_WITH_PHDR = 0x8b DLT_MTP3 = 0x8d DLT_NULL = 0x0 DLT_PCI_EXP = 0x7d DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0xe DLT_PPP_PPPD = 0xa6 DLT_PRISM_HEADER = 0x77 DLT_PRONET = 0x4 DLT_RAW = 0xc DLT_RAWAF_MASK = 0x2240000 DLT_RIO = 0x7c DLT_SCCP = 0x8e DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xd DLT_SUNATM = 0x7b DLT_SYMANTEC_FIREWALL = 0x63 DLT_TZSP = 0x80 ECHO = 0x8 ECHOCTL = 0x200 ECHOE = 0x10 ECHOK = 0x20 ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 EMPTY_SET = 0x0 EMT_CPCOVF = 0x1 EQUALITY_CHECK = 0x0 EXTA = 0xe EXTB = 0xf FD_CLOEXEC = 0x1 FD_NFDBITS = 0x40 FD_SETSIZE = 0x10000 FLUSHALL = 0x1 FLUSHDATA = 0x0 FLUSHO = 0x2000 F_ALLOCSP = 0xa F_ALLOCSP64 = 0xa F_BADFD = 0x2e F_BLKSIZE = 0x13 F_BLOCKS = 0x12 F_CHKFL = 0x8 F_COMPAT = 0x8 F_DUP2FD = 0x9 F_DUP2FD_CLOEXEC = 0x24 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x25 F_FREESP = 0xb F_FREESP64 = 0xb F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0xe F_GETLK64 = 0xe F_GETOWN = 0x17 F_GETXFL = 0x2d F_HASREMOTELOCKS = 0x1a F_ISSTREAM = 0xd F_MANDDNY = 0x10 F_MDACC = 0x20 F_NODNY = 0x0 F_NPRIV = 0x10 F_PRIV = 0xf F_QUOTACTL = 0x11 F_RDACC = 0x1 F_RDDNY = 0x1 F_RDLCK = 0x1 F_REVOKE = 0x19 F_RMACC = 0x4 F_RMDNY = 0x4 F_RWACC = 0x3 F_RWDNY = 0x3 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0x6 F_SETLK64 = 0x6 F_SETLK64_NBMAND = 0x2a F_SETLKW = 0x7 F_SETLKW64 = 0x7 F_SETLK_NBMAND = 0x2a F_SETOWN = 0x18 F_SHARE = 0x28 F_SHARE_NBMAND = 0x2b F_UNLCK = 0x3 F_UNLKSYS = 0x4 F_UNSHARE = 0x29 F_WRACC = 0x2 F_WRDNY = 0x2 F_WRLCK = 0x2 HUPCL = 0x400 ICANON = 0x2 ICRNL = 0x100 IEXTEN = 0x8000 IFF_ADDRCONF = 0x80000 IFF_ALLMULTI = 0x200 IFF_ANYCAST = 0x400000 IFF_BROADCAST = 0x2 IFF_CANTCHANGE = 0x7f203003b5a IFF_COS_ENABLED = 0x200000000 IFF_DEBUG = 0x4 IFF_DEPRECATED = 0x40000 IFF_DHCPRUNNING = 0x4000 IFF_DUPLICATE = 0x4000000000 IFF_FAILED = 0x10000000 IFF_FIXEDMTU = 0x1000000000 IFF_INACTIVE = 0x40000000 IFF_INTELLIGENT = 0x400 IFF_IPMP = 0x8000000000 IFF_IPMP_CANTCHANGE = 0x10000000 IFF_IPMP_INVALID = 0x1ec200080 IFF_IPV4 = 0x1000000 IFF_IPV6 = 0x2000000 IFF_L3PROTECT = 0x40000000000 IFF_LOOPBACK = 0x8 IFF_MULTICAST = 0x800 IFF_MULTI_BCAST = 0x1000 IFF_NOACCEPT = 0x4000000 IFF_NOARP = 0x80 IFF_NOFAILOVER = 0x8000000 IFF_NOLINKLOCAL = 0x20000000000 IFF_NOLOCAL = 0x20000 IFF_NONUD = 0x200000 IFF_NORTEXCH = 0x800000 IFF_NOTRAILERS = 0x20 IFF_NOXMIT = 0x10000 IFF_OFFLINE = 0x80000000 IFF_POINTOPOINT = 0x10 IFF_PREFERRED = 0x400000000 IFF_PRIVATE = 0x8000 IFF_PROMISC = 0x100 IFF_ROUTER = 0x100000 IFF_RUNNING = 0x40 IFF_STANDBY = 0x20000000 IFF_TEMPORARY = 0x800000000 IFF_UNNUMBERED = 0x2000 IFF_UP = 0x1 IFF_VIRTUAL = 0x2000000000 IFF_VRRP = 0x10000000000 IFF_XRESOLV = 0x100000000 IFNAMSIZ = 0x10 IFT_1822 = 0x2 IFT_6TO4 = 0xca IFT_AAL5 = 0x31 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ATM = 0x25 IFT_CEPT = 0x13 IFT_DS3 = 0x1e IFT_EON = 0x19 IFT_ETHER = 0x6 IFT_FDDI = 0xf IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_HDH1822 = 0x3 IFT_HIPPI = 0x2f IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IB = 0xc7 IFT_IPV4 = 0xc8 IFT_IPV6 = 0xc9 IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88026 = 0xa IFT_LAPB = 0x10 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_NSIP = 0x1b IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PPP = 0x17 IFT_PROPMUX = 0x36 IFT_PROPVIRTUAL = 0x35 IFT_PTPSERIAL = 0x16 IFT_RS232 = 0x21 IFT_SDLC = 0x11 IFT_SIP = 0x1f IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_STARLAN = 0xb IFT_T1 = 0x12 IFT_ULTRA = 0x1d IFT_V35 = 0x2d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_AUTOCONF_MASK = 0xffff0000 IN_AUTOCONF_NET = 0xa9fe0000 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_CLASSE_NET = 0xffffffff IN_LOOPBACKNET = 0x7f IN_PRIVATE12_MASK = 0xfff00000 IN_PRIVATE12_NET = 0xac100000 IN_PRIVATE16_MASK = 0xffff0000 IN_PRIVATE16_NET = 0xc0a80000 IN_PRIVATE8_MASK = 0xff000000 IN_PRIVATE8_NET = 0xa000000 IPPROTO_AH = 0x33 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x4 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_HELLO = 0x3f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPV6 = 0x29 IPPROTO_MAX = 0x100 IPPROTO_ND = 0x4d IPPROTO_NONE = 0x3b IPPROTO_OSPF = 0x59 IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_UDP = 0x11 IPV6_ADD_MEMBERSHIP = 0x9 IPV6_BOUND_IF = 0x41 IPV6_CHECKSUM = 0x18 IPV6_DONTFRAG = 0x21 IPV6_DROP_MEMBERSHIP = 0xa IPV6_DSTOPTS = 0xf IPV6_FLOWINFO_FLOWLABEL = 0xffff0f00 IPV6_FLOWINFO_TCLASS = 0xf00f IPV6_HOPLIMIT = 0xc IPV6_HOPOPTS = 0xe IPV6_JOIN_GROUP = 0x9 IPV6_LEAVE_GROUP = 0xa IPV6_MULTICAST_HOPS = 0x7 IPV6_MULTICAST_IF = 0x6 IPV6_MULTICAST_LOOP = 0x8 IPV6_NEXTHOP = 0xd IPV6_PAD1_OPT = 0x0 IPV6_PATHMTU = 0x25 IPV6_PKTINFO = 0xb IPV6_PREFER_SRC_CGA = 0x20 IPV6_PREFER_SRC_CGADEFAULT = 0x10 IPV6_PREFER_SRC_CGAMASK = 0x30 IPV6_PREFER_SRC_COA = 0x2 IPV6_PREFER_SRC_DEFAULT = 0x15 IPV6_PREFER_SRC_HOME = 0x1 IPV6_PREFER_SRC_MASK = 0x3f IPV6_PREFER_SRC_MIPDEFAULT = 0x1 IPV6_PREFER_SRC_MIPMASK = 0x3 IPV6_PREFER_SRC_NONCGA = 0x10 IPV6_PREFER_SRC_PUBLIC = 0x4 IPV6_PREFER_SRC_TMP = 0x8 IPV6_PREFER_SRC_TMPDEFAULT = 0x4 IPV6_PREFER_SRC_TMPMASK = 0xc IPV6_RECVDSTOPTS = 0x28 IPV6_RECVHOPLIMIT = 0x13 IPV6_RECVHOPOPTS = 0x14 IPV6_RECVPATHMTU = 0x24 IPV6_RECVPKTINFO = 0x12 IPV6_RECVRTHDR = 0x16 IPV6_RECVRTHDRDSTOPTS = 0x17 IPV6_RECVTCLASS = 0x19 IPV6_RTHDR = 0x10 IPV6_RTHDRDSTOPTS = 0x11 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SEC_OPT = 0x22 IPV6_SRC_PREFERENCES = 0x23 IPV6_TCLASS = 0x26 IPV6_UNICAST_HOPS = 0x5 IPV6_UNSPEC_SRC = 0x42 IPV6_USE_MIN_MTU = 0x20 IPV6_V6ONLY = 0x27 IP_ADD_MEMBERSHIP = 0x13 IP_ADD_SOURCE_MEMBERSHIP = 0x17 IP_BLOCK_SOURCE = 0x15 IP_BOUND_IF = 0x41 IP_BROADCAST = 0x106 IP_BROADCAST_TTL = 0x43 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DHCPINIT_IF = 0x45 IP_DONTFRAG = 0x1b IP_DONTROUTE = 0x105 IP_DROP_MEMBERSHIP = 0x14 IP_DROP_SOURCE_MEMBERSHIP = 0x18 IP_HDRINCL = 0x2 IP_MAXPACKET = 0xffff IP_MF = 0x2000 IP_MSS = 0x240 IP_MULTICAST_IF = 0x10 IP_MULTICAST_LOOP = 0x12 IP_MULTICAST_TTL = 0x11 IP_NEXTHOP = 0x19 IP_OPTIONS = 0x1 IP_PKTINFO = 0x1a IP_RECVDSTADDR = 0x7 IP_RECVIF = 0x9 IP_RECVOPTS = 0x5 IP_RECVPKTINFO = 0x1a IP_RECVRETOPTS = 0x6 IP_RECVSLLA = 0xa IP_RECVTTL = 0xb IP_RETOPTS = 0x8 IP_REUSEADDR = 0x104 IP_SEC_OPT = 0x22 IP_TOS = 0x3 IP_TTL = 0x4 IP_UNBLOCK_SOURCE = 0x16 IP_UNSPEC_SRC = 0x42 ISIG = 0x1 ISTRIP = 0x20 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 MADV_ACCESS_DEFAULT = 0x6 MADV_ACCESS_LWP = 0x7 MADV_ACCESS_MANY = 0x8 MADV_DONTNEED = 0x4 MADV_FREE = 0x5 MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_WILLNEED = 0x3 MAP_32BIT = 0x80 MAP_ALIGN = 0x200 MAP_ANON = 0x100 MAP_ANONYMOUS = 0x100 MAP_FIXED = 0x10 MAP_INITDATA = 0x800 MAP_NORESERVE = 0x40 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 MAP_SHARED = 0x1 MAP_TEXT = 0x400 MAP_TYPE = 0xf MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MSG_CTRUNC = 0x10 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_DUPCTRL = 0x800 MSG_EOR = 0x8 MSG_MAXIOVLEN = 0x10 MSG_NOTIFICATION = 0x100 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_TRUNC = 0x20 MSG_WAITALL = 0x40 MSG_XPG4_2 = 0x8000 MS_ASYNC = 0x1 MS_INVALIDATE = 0x2 MS_OLDSYNC = 0x0 MS_SYNC = 0x4 M_FLUSH = 0x86 NOFLSH = 0x80 OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 OPENFAIL = -0x1 OPOST = 0x1 O_ACCMODE = 0x600003 O_APPEND = 0x8 O_CLOEXEC = 0x800000 O_CREAT = 0x100 O_DSYNC = 0x40 O_EXCL = 0x400 O_EXEC = 0x400000 O_LARGEFILE = 0x2000 O_NDELAY = 0x4 O_NOCTTY = 0x800 O_NOFOLLOW = 0x20000 O_NOLINKS = 0x40000 O_NONBLOCK = 0x80 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x8000 O_SEARCH = 0x200000 O_SIOCGIFCONF = -0x3ff796ec O_SIOCGLIFCONF = -0x3fef9688 O_SYNC = 0x10 O_TRUNC = 0x200 O_WRONLY = 0x1 O_XATTR = 0x4000 PARENB = 0x100 PAREXT = 0x100000 PARMRK = 0x8 PARODD = 0x200 PENDIN = 0x4000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 RLIMIT_AS = 0x6 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_NOFILE = 0x5 RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x3 RTAX_AUTHOR = 0x6 RTAX_BRD = 0x7 RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_MAX = 0x9 RTAX_NETMASK = 0x2 RTAX_SRC = 0x8 RTA_AUTHOR = 0x40 RTA_BRD = 0x80 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_NETMASK = 0x4 RTA_NUMBITS = 0x9 RTA_SRC = 0x100 RTF_BLACKHOLE = 0x1000 RTF_CLONING = 0x100 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_INDIRECT = 0x40000 RTF_KERNEL = 0x80000 RTF_LLINFO = 0x400 RTF_MASK = 0x80 RTF_MODIFIED = 0x20 RTF_MULTIRT = 0x10000 RTF_PRIVATE = 0x2000 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_REJECT = 0x8 RTF_SETSRC = 0x20000 RTF_STATIC = 0x800 RTF_UP = 0x1 RTF_XRESOLVE = 0x200 RTF_ZONE = 0x100000 RTM_ADD = 0x1 RTM_CHANGE = 0x3 RTM_CHGADDR = 0xf RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_FREEADDR = 0x10 RTM_GET = 0x4 RTM_IFINFO = 0xe RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_OLDADD = 0x9 RTM_OLDDEL = 0xa RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_VERSION = 0x3 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RT_AWARE = 0x1 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 SCM_RIGHTS = 0x1010 SCM_TIMESTAMP = 0x1013 SCM_UCRED = 0x1012 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIG2STR_MAX = 0x20 SIOCADDMULTI = -0x7fdf96cf SIOCADDRT = -0x7fcf8df6 SIOCATMARK = 0x40047307 SIOCDARP = -0x7fdb96e0 SIOCDELMULTI = -0x7fdf96ce SIOCDELRT = -0x7fcf8df5 SIOCDXARP = -0x7fff9658 SIOCGARP = -0x3fdb96e1 SIOCGDSTINFO = -0x3fff965c SIOCGENADDR = -0x3fdf96ab SIOCGENPSTATS = -0x3fdf96c7 SIOCGETLSGCNT = -0x3fef8deb SIOCGETNAME = 0x40107334 SIOCGETPEER = 0x40107335 SIOCGETPROP = -0x3fff8f44 SIOCGETSGCNT = -0x3feb8deb SIOCGETSYNC = -0x3fdf96d3 SIOCGETVIFCNT = -0x3feb8dec SIOCGHIWAT = 0x40047301 SIOCGIFADDR = -0x3fdf96f3 SIOCGIFBRDADDR = -0x3fdf96e9 SIOCGIFCONF = -0x3ff796a4 SIOCGIFDSTADDR = -0x3fdf96f1 SIOCGIFFLAGS = -0x3fdf96ef SIOCGIFHWADDR = -0x3fdf9647 SIOCGIFINDEX = -0x3fdf96a6 SIOCGIFMEM = -0x3fdf96ed SIOCGIFMETRIC = -0x3fdf96e5 SIOCGIFMTU = -0x3fdf96ea SIOCGIFMUXID = -0x3fdf96a8 SIOCGIFNETMASK = -0x3fdf96e7 SIOCGIFNUM = 0x40046957 SIOCGIP6ADDRPOLICY = -0x3fff965e SIOCGIPMSFILTER = -0x3ffb964c SIOCGLIFADDR = -0x3f87968f SIOCGLIFBINDING = -0x3f879666 SIOCGLIFBRDADDR = -0x3f879685 SIOCGLIFCONF = -0x3fef965b SIOCGLIFDADSTATE = -0x3f879642 SIOCGLIFDSTADDR = -0x3f87968d SIOCGLIFFLAGS = -0x3f87968b SIOCGLIFGROUPINFO = -0x3f4b9663 SIOCGLIFGROUPNAME = -0x3f879664 SIOCGLIFHWADDR = -0x3f879640 SIOCGLIFINDEX = -0x3f87967b SIOCGLIFLNKINFO = -0x3f879674 SIOCGLIFMETRIC = -0x3f879681 SIOCGLIFMTU = -0x3f879686 SIOCGLIFMUXID = -0x3f87967d SIOCGLIFNETMASK = -0x3f879683 SIOCGLIFNUM = -0x3ff3967e SIOCGLIFSRCOF = -0x3fef964f SIOCGLIFSUBNET = -0x3f879676 SIOCGLIFTOKEN = -0x3f879678 SIOCGLIFUSESRC = -0x3f879651 SIOCGLIFZONE = -0x3f879656 SIOCGLOWAT = 0x40047303 SIOCGMSFILTER = -0x3ffb964e SIOCGPGRP = 0x40047309 SIOCGSTAMP = -0x3fef9646 SIOCGXARP = -0x3fff9659 SIOCIFDETACH = -0x7fdf96c8 SIOCILB = -0x3ffb9645 SIOCLIFADDIF = -0x3f879691 SIOCLIFDELND = -0x7f879673 SIOCLIFGETND = -0x3f879672 SIOCLIFREMOVEIF = -0x7f879692 SIOCLIFSETND = -0x7f879671 SIOCLOWER = -0x7fdf96d7 SIOCSARP = -0x7fdb96e2 SIOCSCTPGOPT = -0x3fef9653 SIOCSCTPPEELOFF = -0x3ffb9652 SIOCSCTPSOPT = -0x7fef9654 SIOCSENABLESDP = -0x3ffb9649 SIOCSETPROP = -0x7ffb8f43 SIOCSETSYNC = -0x7fdf96d4 SIOCSHIWAT = -0x7ffb8d00 SIOCSIFADDR = -0x7fdf96f4 SIOCSIFBRDADDR = -0x7fdf96e8 SIOCSIFDSTADDR = -0x7fdf96f2 SIOCSIFFLAGS = -0x7fdf96f0 SIOCSIFINDEX = -0x7fdf96a5 SIOCSIFMEM = -0x7fdf96ee SIOCSIFMETRIC = -0x7fdf96e4 SIOCSIFMTU = -0x7fdf96eb SIOCSIFMUXID = -0x7fdf96a7 SIOCSIFNAME = -0x7fdf96b7 SIOCSIFNETMASK = -0x7fdf96e6 SIOCSIP6ADDRPOLICY = -0x7fff965d SIOCSIPMSFILTER = -0x7ffb964b SIOCSLGETREQ = -0x3fdf96b9 SIOCSLIFADDR = -0x7f879690 SIOCSLIFBRDADDR = -0x7f879684 SIOCSLIFDSTADDR = -0x7f87968e SIOCSLIFFLAGS = -0x7f87968c SIOCSLIFGROUPNAME = -0x7f879665 SIOCSLIFINDEX = -0x7f87967a SIOCSLIFLNKINFO = -0x7f879675 SIOCSLIFMETRIC = -0x7f879680 SIOCSLIFMTU = -0x7f879687 SIOCSLIFMUXID = -0x7f87967c SIOCSLIFNAME = -0x3f87967f SIOCSLIFNETMASK = -0x7f879682 SIOCSLIFPREFIX = -0x3f879641 SIOCSLIFSUBNET = -0x7f879677 SIOCSLIFTOKEN = -0x7f879679 SIOCSLIFUSESRC = -0x7f879650 SIOCSLIFZONE = -0x7f879655 SIOCSLOWAT = -0x7ffb8cfe SIOCSLSTAT = -0x7fdf96b8 SIOCSMSFILTER = -0x7ffb964d SIOCSPGRP = -0x7ffb8cf8 SIOCSPROMISC = -0x7ffb96d0 SIOCSQPTR = -0x3ffb9648 SIOCSSDSTATS = -0x3fdf96d2 SIOCSSESTATS = -0x3fdf96d1 SIOCSXARP = -0x7fff965a SIOCTMYADDR = -0x3ff79670 SIOCTMYSITE = -0x3ff7966e SIOCTONLINK = -0x3ff7966f SIOCUPPER = -0x7fdf96d8 SIOCX25RCV = -0x3fdf96c4 SIOCX25TBL = -0x3fdf96c3 SIOCX25XMT = -0x3fdf96c5 SIOCXPROTO = 0x20007337 SOCK_CLOEXEC = 0x80000 SOCK_DGRAM = 0x1 SOCK_NDELAY = 0x200000 SOCK_NONBLOCK = 0x100000 SOCK_RAW = 0x4 SOCK_RDM = 0x5 SOCK_SEQPACKET = 0x6 SOCK_STREAM = 0x2 SOCK_TYPE_MASK = 0xffff SOL_FILTER = 0xfffc SOL_PACKET = 0xfffd SOL_ROUTE = 0xfffe SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_ALL = 0x3f SO_ALLZONES = 0x1014 SO_ANON_MLP = 0x100a SO_ATTACH_FILTER = 0x40000001 SO_BAND = 0x4000 SO_BROADCAST = 0x20 SO_COPYOPT = 0x80000 SO_DEBUG = 0x1 SO_DELIM = 0x8000 SO_DETACH_FILTER = 0x40000002 SO_DGRAM_ERRIND = 0x200 SO_DOMAIN = 0x100c SO_DONTLINGER = -0x81 SO_DONTROUTE = 0x10 SO_ERROPT = 0x40000 SO_ERROR = 0x1007 SO_EXCLBIND = 0x1015 SO_HIWAT = 0x10 SO_ISNTTY = 0x800 SO_ISTTY = 0x400 SO_KEEPALIVE = 0x8 SO_LINGER = 0x80 SO_LOWAT = 0x20 SO_MAC_EXEMPT = 0x100b SO_MAC_IMPLICIT = 0x1016 SO_MAXBLK = 0x100000 SO_MAXPSZ = 0x8 SO_MINPSZ = 0x4 SO_MREADOFF = 0x80 SO_MREADON = 0x40 SO_NDELOFF = 0x200 SO_NDELON = 0x100 SO_NODELIM = 0x10000 SO_OOBINLINE = 0x100 SO_PROTOTYPE = 0x1009 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVPSH = 0x100d SO_RCVTIMEO = 0x1006 SO_READOPT = 0x1 SO_RECVUCRED = 0x400 SO_REUSEADDR = 0x4 SO_SECATTR = 0x1011 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_STRHOLD = 0x20000 SO_TAIL = 0x200000 SO_TIMESTAMP = 0x1013 SO_TONSTOP = 0x2000 SO_TOSTOP = 0x1000 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 SO_VRRP = 0x1017 SO_WROFF = 0x2 TCFLSH = 0x5407 TCGETA = 0x5401 TCGETS = 0x540d TCIFLUSH = 0x0 TCIOFLUSH = 0x2 TCOFLUSH = 0x1 TCP_ABORT_THRESHOLD = 0x11 TCP_ANONPRIVBIND = 0x20 TCP_CONN_ABORT_THRESHOLD = 0x13 TCP_CONN_NOTIFY_THRESHOLD = 0x12 TCP_CORK = 0x18 TCP_EXCLBIND = 0x21 TCP_INIT_CWND = 0x15 TCP_KEEPALIVE = 0x8 TCP_KEEPALIVE_ABORT_THRESHOLD = 0x17 TCP_KEEPALIVE_THRESHOLD = 0x16 TCP_KEEPCNT = 0x23 TCP_KEEPIDLE = 0x22 TCP_KEEPINTVL = 0x24 TCP_LINGER2 = 0x1c TCP_MAXSEG = 0x2 TCP_MSS = 0x218 TCP_NODELAY = 0x1 TCP_NOTIFY_THRESHOLD = 0x10 TCP_RECVDSTADDR = 0x14 TCP_RTO_INITIAL = 0x19 TCP_RTO_MAX = 0x1b TCP_RTO_MIN = 0x1a TCSAFLUSH = 0x5410 TCSBRK = 0x5405 TCSETA = 0x5402 TCSETAF = 0x5404 TCSETAW = 0x5403 TCSETS = 0x540e TCSETSF = 0x5410 TCSETSW = 0x540f TCXONC = 0x5406 TIOC = 0x5400 TIOCCBRK = 0x747a TIOCCDTR = 0x7478 TIOCCILOOP = 0x746c TIOCEXCL = 0x740d TIOCFLUSH = 0x7410 TIOCGETC = 0x7412 TIOCGETD = 0x7400 TIOCGETP = 0x7408 TIOCGLTC = 0x7474 TIOCGPGRP = 0x7414 TIOCGPPS = 0x547d TIOCGPPSEV = 0x547f TIOCGSID = 0x7416 TIOCGSOFTCAR = 0x5469 TIOCGWINSZ = 0x5468 TIOCHPCL = 0x7402 TIOCKBOF = 0x5409 TIOCKBON = 0x5408 TIOCLBIC = 0x747e TIOCLBIS = 0x747f TIOCLGET = 0x747c TIOCLSET = 0x747d TIOCMBIC = 0x741c TIOCMBIS = 0x741b TIOCMGET = 0x741d TIOCMSET = 0x741a TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x7471 TIOCNXCL = 0x740e TIOCOUTQ = 0x7473 TIOCREMOTE = 0x741e TIOCSBRK = 0x747b TIOCSCTTY = 0x7484 TIOCSDTR = 0x7479 TIOCSETC = 0x7411 TIOCSETD = 0x7401 TIOCSETN = 0x740a TIOCSETP = 0x7409 TIOCSIGNAL = 0x741f TIOCSILOOP = 0x746d TIOCSLTC = 0x7475 TIOCSPGRP = 0x7415 TIOCSPPS = 0x547e TIOCSSOFTCAR = 0x546a TIOCSTART = 0x746e TIOCSTI = 0x7417 TIOCSTOP = 0x746f TIOCSWINSZ = 0x5467 TOSTOP = 0x100 VCEOF = 0x8 VCEOL = 0x9 VDISCARD = 0xd VDSUSP = 0xb VEOF = 0x4 VEOL = 0x5 VEOL2 = 0x6 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMIN = 0x4 VQUIT = 0x1 VREPRINT = 0xc VSTART = 0x8 VSTATUS = 0x10 VSTOP = 0x9 VSUSP = 0xa VSWTCH = 0x7 VT0 = 0x0 VT1 = 0x4000 VTDLY = 0x4000 VTIME = 0x5 VWERASE = 0xe WCONTFLG = 0xffff WCONTINUED = 0x8 WCOREFLG = 0x80 WEXITED = 0x1 WNOHANG = 0x40 WNOWAIT = 0x80 WOPTMASK = 0xcf WRAP = 0x20000 WSIGMASK = 0x7f WSTOPFLG = 0x7f WSTOPPED = 0x4 WTRAPPED = 0x2 WUNTRACED = 0x4 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x7d) EADDRNOTAVAIL = syscall.Errno(0x7e) EADV = syscall.Errno(0x44) EAFNOSUPPORT = syscall.Errno(0x7c) EAGAIN = syscall.Errno(0xb) EALREADY = syscall.Errno(0x95) EBADE = syscall.Errno(0x32) EBADF = syscall.Errno(0x9) EBADFD = syscall.Errno(0x51) EBADMSG = syscall.Errno(0x4d) EBADR = syscall.Errno(0x33) EBADRQC = syscall.Errno(0x36) EBADSLT = syscall.Errno(0x37) EBFONT = syscall.Errno(0x39) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x2f) ECHILD = syscall.Errno(0xa) ECHRNG = syscall.Errno(0x25) ECOMM = syscall.Errno(0x46) ECONNABORTED = syscall.Errno(0x82) ECONNREFUSED = syscall.Errno(0x92) ECONNRESET = syscall.Errno(0x83) EDEADLK = syscall.Errno(0x2d) EDEADLOCK = syscall.Errno(0x38) EDESTADDRREQ = syscall.Errno(0x60) EDOM = syscall.Errno(0x21) EDQUOT = syscall.Errno(0x31) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EHOSTDOWN = syscall.Errno(0x93) EHOSTUNREACH = syscall.Errno(0x94) EIDRM = syscall.Errno(0x24) EILSEQ = syscall.Errno(0x58) EINPROGRESS = syscall.Errno(0x96) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x85) EISDIR = syscall.Errno(0x15) EL2HLT = syscall.Errno(0x2c) EL2NSYNC = syscall.Errno(0x26) EL3HLT = syscall.Errno(0x27) EL3RST = syscall.Errno(0x28) ELIBACC = syscall.Errno(0x53) ELIBBAD = syscall.Errno(0x54) ELIBEXEC = syscall.Errno(0x57) ELIBMAX = syscall.Errno(0x56) ELIBSCN = syscall.Errno(0x55) ELNRNG = syscall.Errno(0x29) ELOCKUNMAPPED = syscall.Errno(0x48) ELOOP = syscall.Errno(0x5a) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x61) EMULTIHOP = syscall.Errno(0x4a) ENAMETOOLONG = syscall.Errno(0x4e) ENETDOWN = syscall.Errno(0x7f) ENETRESET = syscall.Errno(0x81) ENETUNREACH = syscall.Errno(0x80) ENFILE = syscall.Errno(0x17) ENOANO = syscall.Errno(0x35) ENOBUFS = syscall.Errno(0x84) ENOCSI = syscall.Errno(0x2b) ENODATA = syscall.Errno(0x3d) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x2e) ENOLINK = syscall.Errno(0x43) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x23) ENONET = syscall.Errno(0x40) ENOPKG = syscall.Errno(0x41) ENOPROTOOPT = syscall.Errno(0x63) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x3f) ENOSTR = syscall.Errno(0x3c) ENOSYS = syscall.Errno(0x59) ENOTACTIVE = syscall.Errno(0x49) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x86) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x5d) ENOTRECOVERABLE = syscall.Errno(0x3b) ENOTSOCK = syscall.Errno(0x5f) ENOTSUP = syscall.Errno(0x30) ENOTTY = syscall.Errno(0x19) ENOTUNIQ = syscall.Errno(0x50) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x7a) EOVERFLOW = syscall.Errno(0x4f) EOWNERDEAD = syscall.Errno(0x3a) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x7b) EPIPE = syscall.Errno(0x20) EPROTO = syscall.Errno(0x47) EPROTONOSUPPORT = syscall.Errno(0x78) EPROTOTYPE = syscall.Errno(0x62) ERANGE = syscall.Errno(0x22) EREMCHG = syscall.Errno(0x52) EREMOTE = syscall.Errno(0x42) ERESTART = syscall.Errno(0x5b) EROFS = syscall.Errno(0x1e) ESHUTDOWN = syscall.Errno(0x8f) ESOCKTNOSUPPORT = syscall.Errno(0x79) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESRMNT = syscall.Errno(0x45) ESTALE = syscall.Errno(0x97) ESTRPIPE = syscall.Errno(0x5c) ETIME = syscall.Errno(0x3e) ETIMEDOUT = syscall.Errno(0x91) ETOOMANYREFS = syscall.Errno(0x90) ETXTBSY = syscall.Errno(0x1a) EUNATCH = syscall.Errno(0x2a) EUSERS = syscall.Errno(0x5e) EWOULDBLOCK = syscall.Errno(0xb) EXDEV = syscall.Errno(0x12) EXFULL = syscall.Errno(0x34) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCANCEL = syscall.Signal(0x24) SIGCHLD = syscall.Signal(0x12) SIGCLD = syscall.Signal(0x12) SIGCONT = syscall.Signal(0x19) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGFREEZE = syscall.Signal(0x22) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x29) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x16) SIGIOT = syscall.Signal(0x6) SIGJVM1 = syscall.Signal(0x27) SIGJVM2 = syscall.Signal(0x28) SIGKILL = syscall.Signal(0x9) SIGLOST = syscall.Signal(0x25) SIGLWP = syscall.Signal(0x21) SIGPIPE = syscall.Signal(0xd) SIGPOLL = syscall.Signal(0x16) SIGPROF = syscall.Signal(0x1d) SIGPWR = syscall.Signal(0x13) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x17) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTHAW = syscall.Signal(0x23) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x18) SIGTTIN = syscall.Signal(0x1a) SIGTTOU = syscall.Signal(0x1b) SIGURG = syscall.Signal(0x15) SIGUSR1 = syscall.Signal(0x10) SIGUSR2 = syscall.Signal(0x11) SIGVTALRM = syscall.Signal(0x1c) SIGWAITING = syscall.Signal(0x20) SIGWINCH = syscall.Signal(0x14) SIGXCPU = syscall.Signal(0x1e) SIGXFSZ = syscall.Signal(0x1f) SIGXRES = syscall.Signal(0x26) ) // Error table var errors = [...]string{ 1: "not owner", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "I/O error", 6: "no such device or address", 7: "arg list too long", 8: "exec format error", 9: "bad file number", 10: "no child processes", 11: "resource temporarily unavailable", 12: "not enough space", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device busy", 17: "file exists", 18: "cross-device link", 19: "no such device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "file table overflow", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "argument out of domain", 34: "result too large", 35: "no message of desired type", 36: "identifier removed", 37: "channel number out of range", 38: "level 2 not synchronized", 39: "level 3 halted", 40: "level 3 reset", 41: "link number out of range", 42: "protocol driver not attached", 43: "no CSI structure available", 44: "level 2 halted", 45: "deadlock situation detected/avoided", 46: "no record locks available", 47: "operation canceled", 48: "operation not supported", 49: "disc quota exceeded", 50: "bad exchange descriptor", 51: "bad request descriptor", 52: "message tables full", 53: "anode table overflow", 54: "bad request code", 55: "invalid slot", 56: "file locking deadlock", 57: "bad font file format", 58: "owner of the lock died", 59: "lock is not recoverable", 60: "not a stream device", 61: "no data available", 62: "timer expired", 63: "out of stream resources", 64: "machine is not on the network", 65: "package not installed", 66: "object is remote", 67: "link has been severed", 68: "advertise error", 69: "srmount error", 70: "communication error on send", 71: "protocol error", 72: "locked lock was unmapped ", 73: "facility is not active", 74: "multihop attempted", 77: "not a data message", 78: "file name too long", 79: "value too large for defined data type", 80: "name not unique on network", 81: "file descriptor in bad state", 82: "remote address changed", 83: "can not access a needed shared library", 84: "accessing a corrupted shared library", 85: ".lib section in a.out corrupted", 86: "attempting to link in more shared libraries than system limit", 87: "can not exec a shared library directly", 88: "illegal byte sequence", 89: "operation not applicable", 90: "number of symbolic links encountered during path name traversal exceeds MAXSYMLINKS", 91: "error 91", 92: "error 92", 93: "directory not empty", 94: "too many users", 95: "socket operation on non-socket", 96: "destination address required", 97: "message too long", 98: "protocol wrong type for socket", 99: "option not supported by protocol", 120: "protocol not supported", 121: "socket type not supported", 122: "operation not supported on transport endpoint", 123: "protocol family not supported", 124: "address family not supported by protocol family", 125: "address already in use", 126: "cannot assign requested address", 127: "network is down", 128: "network is unreachable", 129: "network dropped connection because of reset", 130: "software caused connection abort", 131: "connection reset by peer", 132: "no buffer space available", 133: "transport endpoint is already connected", 134: "transport endpoint is not connected", 143: "cannot send after socket shutdown", 144: "too many references: cannot splice", 145: "connection timed out", 146: "connection refused", 147: "host is down", 148: "no route to host", 149: "operation already in progress", 150: "operation now in progress", 151: "stale NFS file handle", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal Instruction", 5: "trace/Breakpoint Trap", 6: "abort", 7: "emulation Trap", 8: "arithmetic Exception", 9: "killed", 10: "bus Error", 11: "segmentation Fault", 12: "bad System Call", 13: "broken Pipe", 14: "alarm Clock", 15: "terminated", 16: "user Signal 1", 17: "user Signal 2", 18: "child Status Changed", 19: "power-Fail/Restart", 20: "window Size Change", 21: "urgent Socket Condition", 22: "pollable Event", 23: "stopped (signal)", 24: "stopped (user)", 25: "continued", 26: "stopped (tty input)", 27: "stopped (tty output)", 28: "virtual Timer Expired", 29: "profiling Timer Expired", 30: "cpu Limit Exceeded", 31: "file Size Limit Exceeded", 32: "no runnable lwp", 33: "inter-lwp signal", 34: "checkpoint Freeze", 35: "checkpoint Thaw", 36: "thread Cancellation", 37: "resource Lost", 38: "resource Control Exceeded", 39: "reserved for JVM 1", 40: "reserved for JVM 2", 41: "information Request", }
Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_solaris_amd64.go
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.024957353249192238, 0.0006988560780882835, 0.00016450324619654566, 0.00021158155868761241, 0.0027110285591334105 ]
{ "id": 6, "code_window": [ "}\n", "\n", "const (\n", "\tview_long = `Displays merged kubeconfig settings or a specified kubeconfig file.\n", "\n", "You can use --output=template --template=TEMPLATE to extract specific values.`\n", "\tview_example = `# Show Merged kubeconfig settings.\n", "$ kubectl config view\n", "\n", "# Get the password for the e2e user\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "You can use --output jsonpath={...} to extract specific values using a jsonpath expression.`\n" ], "file_path": "pkg/kubectl/cmd/config/view.go", "type": "replace", "edit_start_line_idx": 44 }
/* Copyright 2014 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package userspace import ( "net" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/proxy" ) // LoadBalancer is an interface for distributing incoming requests to service endpoints. type LoadBalancer interface { // NextEndpoint returns the endpoint to handle a request for the given // service-port and source address. NextEndpoint(service proxy.ServicePortName, srcAddr net.Addr) (string, error) NewService(service proxy.ServicePortName, sessionAffinityType api.ServiceAffinity, stickyMaxAgeMinutes int) error CleanupStaleStickySessions(service proxy.ServicePortName) }
pkg/proxy/userspace/loadbalancer.go
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.00022061055642552674, 0.0001849006221164018, 0.00016726824105717242, 0.00017586187459528446, 0.000020913721527904272 ]
{ "id": 6, "code_window": [ "}\n", "\n", "const (\n", "\tview_long = `Displays merged kubeconfig settings or a specified kubeconfig file.\n", "\n", "You can use --output=template --template=TEMPLATE to extract specific values.`\n", "\tview_example = `# Show Merged kubeconfig settings.\n", "$ kubectl config view\n", "\n", "# Get the password for the e2e user\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "You can use --output jsonpath={...} to extract specific values using a jsonpath expression.`\n" ], "file_path": "pkg/kubectl/cmd/config/view.go", "type": "replace", "edit_start_line_idx": 44 }
package dns // These raw* functions do not use reflection, they directly set the values // in the buffer. There are faster than their reflection counterparts. // RawSetId sets the message id in buf. func rawSetId(msg []byte, i uint16) bool { if len(msg) < 2 { return false } msg[0], msg[1] = packUint16(i) return true } // rawSetQuestionLen sets the length of the question section. func rawSetQuestionLen(msg []byte, i uint16) bool { if len(msg) < 6 { return false } msg[4], msg[5] = packUint16(i) return true } // rawSetAnswerLen sets the lenght of the answer section. func rawSetAnswerLen(msg []byte, i uint16) bool { if len(msg) < 8 { return false } msg[6], msg[7] = packUint16(i) return true } // rawSetsNsLen sets the lenght of the authority section. func rawSetNsLen(msg []byte, i uint16) bool { if len(msg) < 10 { return false } msg[8], msg[9] = packUint16(i) return true } // rawSetExtraLen sets the lenght of the additional section. func rawSetExtraLen(msg []byte, i uint16) bool { if len(msg) < 12 { return false } msg[10], msg[11] = packUint16(i) return true } // rawSetRdlength sets the rdlength in the header of // the RR. The offset 'off' must be positioned at the // start of the header of the RR, 'end' must be the // end of the RR. func rawSetRdlength(msg []byte, off, end int) bool { l := len(msg) Loop: for { if off+1 > l { return false } c := int(msg[off]) off++ switch c & 0xC0 { case 0x00: if c == 0x00 { // End of the domainname break Loop } if off+c > l { return false } off += c case 0xC0: // pointer, next byte included, ends domainname off++ break Loop } } // The domainname has been seen, we at the start of the fixed part in the header. // Type is 2 bytes, class is 2 bytes, ttl 4 and then 2 bytes for the length. off += 2 + 2 + 4 if off+2 > l { return false } //off+1 is the end of the header, 'end' is the end of the rr //so 'end' - 'off+2' is the length of the rdata rdatalen := end - (off + 2) if rdatalen > 0xFFFF { return false } msg[off], msg[off+1] = packUint16(uint16(rdatalen)) return true }
Godeps/_workspace/src/github.com/miekg/dns/rawmsg.go
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.00017121608834713697, 0.000168681624927558, 0.00016625328862573951, 0.00016868718375917524, 0.0000014721905472470098 ]
{ "id": 7, "code_window": [ "\tview_example = `# Show Merged kubeconfig settings.\n", "$ kubectl config view\n", "\n", "# Get the password for the e2e user\n", "$ kubectl config view -o template --template='{{range .users}}{{ if eq .name \"e2e\" }}{{ index .user.password }}{{end}}{{end}}'`\n", ")\n", "\n", "func NewCmdConfigView(out io.Writer, ConfigAccess ConfigAccess) *cobra.Command {\n", "\toptions := &ViewOptions{ConfigAccess: ConfigAccess}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "$ kubectl config view -o jsonpath='{.users[?(@.name == \"e2e\")].user.password}'`\n" ], "file_path": "pkg/kubectl/cmd/config/view.go", "type": "replace", "edit_start_line_idx": 49 }
<!-- BEGIN MUNGE: UNVERSIONED_WARNING --> <!-- BEGIN STRIP_FOR_RELEASE --> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <h2>PLEASE NOTE: This document applies to the HEAD of the source tree</h2> If you are using a released version of Kubernetes, you should refer to the docs that go with that version. <!-- TAG RELEASE_LINK, added by the munger automatically --> <strong> The latest release of this document can be found [here](http://releases.k8s.io/release-1.1/docs/user-guide/kubectl/kubectl_config_view.md). Documentation for other releases can be found at [releases.k8s.io](http://releases.k8s.io). </strong> -- <!-- END STRIP_FOR_RELEASE --> <!-- END MUNGE: UNVERSIONED_WARNING --> ## kubectl config view Displays merged kubeconfig settings or a specified kubeconfig file. ### Synopsis Displays merged kubeconfig settings or a specified kubeconfig file. You can use --output=template --template=TEMPLATE to extract specific values. ``` kubectl config view ``` ### Examples ``` # Show Merged kubeconfig settings. $ kubectl config view # Get the password for the e2e user $ kubectl config view -o template --template='{{range .users}}{{ if eq .name "e2e" }}{{ index .user.password }}{{end}}{{end}}' ``` ### Options ``` --flatten[=false]: flatten the resulting kubeconfig file into self contained output (useful for creating portable kubeconfig files) --merge[=true]: merge together the full hierarchy of kubeconfig files --minify[=false]: remove all information not used by current-context from the output --no-headers[=false]: When using the default output, don't print headers. -o, --output="": Output format. One of: json|yaml|wide|name|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=... See golang template [http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template [http://releases.k8s.io/HEAD/docs/user-guide/jsonpath.md]. --output-version="": Output the formatted object with the given version (default api-version). --raw[=false]: display raw byte data -a, --show-all[=false]: When printing, show all resources (default hide terminated pods.) --sort-by="": If non-empty, sort list types using this field specification. The field specification is expressed as a JSONPath expression (e.g. 'ObjectMeta.Name'). The field in the API resource specified by this JSONPath expression must be an integer or a string. --template="": Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview]. ``` ### Options inherited from parent commands ``` --alsologtostderr[=false]: log to standard error as well as files --api-version="": The API version to use when talking to the server --certificate-authority="": Path to a cert. file for the certificate authority. --client-certificate="": Path to a client certificate file for TLS. --client-key="": Path to a client key file for TLS. --cluster="": The name of the kubeconfig cluster to use --context="": The name of the kubeconfig context to use --insecure-skip-tls-verify[=false]: If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure. --kubeconfig="": use a particular kubeconfig file --log-backtrace-at=:0: when logging hits line file:N, emit a stack trace --log-dir="": If non-empty, write log files in this directory --log-flush-frequency=5s: Maximum number of seconds between log flushes --logtostderr[=true]: log to standard error instead of files --match-server-version[=false]: Require server version to match client version --namespace="": If present, the namespace scope for this CLI request. --password="": Password for basic authentication to the API server. -s, --server="": The address and port of the Kubernetes API server --stderrthreshold=2: logs at or above this threshold go to stderr --token="": Bearer token for authentication to the API server. --user="": The name of the kubeconfig user to use --username="": Username for basic authentication to the API server. --v=0: log level for V logs --vmodule=: comma-separated list of pattern=N settings for file-filtered logging ``` ### SEE ALSO * [kubectl config](kubectl_config.md) - config modifies kubeconfig files ###### Auto generated by spf13/cobra on 8-Jan-2016 <!-- BEGIN MUNGE: GENERATED_ANALYTICS --> [![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/kubectl/kubectl_config_view.md?pixel)]() <!-- END MUNGE: GENERATED_ANALYTICS -->
docs/user-guide/kubectl/kubectl_config_view.md
1
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.10558909177780151, 0.009806179441511631, 0.00016621002578176558, 0.0003034200635738671, 0.028953775763511658 ]
{ "id": 7, "code_window": [ "\tview_example = `# Show Merged kubeconfig settings.\n", "$ kubectl config view\n", "\n", "# Get the password for the e2e user\n", "$ kubectl config view -o template --template='{{range .users}}{{ if eq .name \"e2e\" }}{{ index .user.password }}{{end}}{{end}}'`\n", ")\n", "\n", "func NewCmdConfigView(out io.Writer, ConfigAccess ConfigAccess) *cobra.Command {\n", "\toptions := &ViewOptions{ConfigAccess: ConfigAccess}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "$ kubectl config view -o jsonpath='{.users[?(@.name == \"e2e\")].user.password}'`\n" ], "file_path": "pkg/kubectl/cmd/config/view.go", "type": "replace", "edit_start_line_idx": 49 }
#!/bin/bash # Copyright 2015 The Kubernetes Authors All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. curl https://sdk.cloud.google.com | bash sudo gcloud components update kubectl -q sudo ln -s /usr/local/share/google/google-cloud-sdk/bin/kubectl /bin/ kubectl config set-cluster hollow-cluster --server=http://localhost:8080 --insecure-skip-tls-verify=true kubectl config set-credentials $(whoami) kubectl config set-context hollow-context --cluster=hollow-cluster --user=$(whoami)
test/kubemark/configure-kubectl.sh
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.0011607795022428036, 0.0005003153346478939, 0.0001643657305976376, 0.00017580072744749486, 0.0004670420312322676 ]
{ "id": 7, "code_window": [ "\tview_example = `# Show Merged kubeconfig settings.\n", "$ kubectl config view\n", "\n", "# Get the password for the e2e user\n", "$ kubectl config view -o template --template='{{range .users}}{{ if eq .name \"e2e\" }}{{ index .user.password }}{{end}}{{end}}'`\n", ")\n", "\n", "func NewCmdConfigView(out io.Writer, ConfigAccess ConfigAccess) *cobra.Command {\n", "\toptions := &ViewOptions{ConfigAccess: ConfigAccess}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "$ kubectl config view -o jsonpath='{.users[?(@.name == \"e2e\")].user.password}'`\n" ], "file_path": "pkg/kubectl/cmd/config/view.go", "type": "replace", "edit_start_line_idx": 49 }
/* Copyright 2015 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package leaderelection implements leader election of a set of endpoints. // It uses an annotation in the endpoints object to store the record of the // election state. // // This implementation does not guarantee that only one client is acting as a // leader (a.k.a. fencing). A client observes timestamps captured locally to // infer the state of the leader election. Thus the implementation is tolerant // to arbitrary clock skew, but is not tolerant to arbitrary clock skew rate. // // However the level of tolerance to skew rate can be configured by setting // RenewDeadline and LeaseDuration appropriately. The tolerance expressed as a // maximum tolerated ratio of time passed on the fastest node to time passed on // the slowest node can be approximately achieved with a configuration that sets // the same ratio of LeaseDuration to RenewDeadline. For example if a user wanted // to tolerate some nodes progressing forward in time twice as fast as other nodes, // the user could set LeaseDuration to 60 seconds and RenewDeadline to 30 seconds. // // While not required, some method of clock synchronization between nodes in the // cluster is highly recommended. It's important to keep in mind when configuring // this client that the tolerance to skew rate varies inversely to master // availability. // // Larger clusters often have a more lenient SLA for API latency. This should be // taken into account when configuring the client. The rate of leader transistions // should be monitored and RetryPeriod and LeaseDuration should be increased // until the rate is stable and acceptably low. It's important to keep in mind // when configuring this client that the tolerance to API latency varies inversely // to master availability. // // DISCLAIMER: this is an alpha API. This library will likely change significantly // or even be removed entirely in subsequent releases. Depend on this API at // your own risk. package leaderelection import ( "encoding/json" "fmt" "reflect" "time" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apis/componentconfig" "k8s.io/kubernetes/pkg/client/record" client "k8s.io/kubernetes/pkg/client/unversioned" "k8s.io/kubernetes/pkg/util" "k8s.io/kubernetes/pkg/util/wait" "github.com/golang/glog" "github.com/spf13/pflag" ) const ( JitterFactor = 1.2 LeaderElectionRecordAnnotationKey = "control-plane.alpha.kubernetes.io/leader" DefaultLeaseDuration = 15 * time.Second DefaultRenewDeadline = 10 * time.Second DefaultRetryPeriod = 2 * time.Second ) // NewLeadereElector creates a LeaderElector from a LeaderElecitionConfig func NewLeaderElector(lec LeaderElectionConfig) (*LeaderElector, error) { if lec.LeaseDuration <= lec.RenewDeadline { return nil, fmt.Errorf("leaseDuration must be greater than renewDeadline") } if lec.RenewDeadline <= time.Duration(JitterFactor*float64(lec.RetryPeriod)) { return nil, fmt.Errorf("renewDeadline must be greater than retryPeriod*JitterFactor") } if lec.Client == nil { return nil, fmt.Errorf("Client must not be nil.") } if lec.EventRecorder == nil { return nil, fmt.Errorf("EventRecorder must not be nil.") } return &LeaderElector{ config: lec, }, nil } type LeaderElectionConfig struct { // EndpointsMeta should contain a Name and a Namespace of an // Endpoints object that the LeaderElector will attempt to lead. EndpointsMeta api.ObjectMeta // Identity is a unique identifier of the leader elector. Identity string Client client.Interface EventRecorder record.EventRecorder // LeaseDuration is the duration that non-leader candidates will // wait to force acquire leadership. This is measured against time of // last observed ack. LeaseDuration time.Duration // RenewDeadline is the duration that the acting master will retry // refreshing leadership before giving up. RenewDeadline time.Duration // RetryPeriod is the duration the LeaderElector clients should wait // between tries of actions. RetryPeriod time.Duration // Callbacks are callbacks that are triggered during certain lifecycle // events of the LeaderElector Callbacks LeaderCallbacks } // LeaderCallbacks are callbacks that are triggered during certain // lifecycle events of the LeaderElector. These are invoked asynchronously. // // possible future callbacks: // * OnChallenge() type LeaderCallbacks struct { // OnStartedLeading is called when a LeaderElector client starts leading OnStartedLeading func(stop <-chan struct{}) // OnStoppedLeading is called when a LeaderElector client stops leading OnStoppedLeading func() // OnNewLeader is called when the client observes a leader that is // not the previously observed leader. This includes the first observed // leader when the client starts. OnNewLeader func(identity string) } // LeaderElector is a leader election client. // // possible future methods: // * (le *LeaderElector) IsLeader() // * (le *LeaderElector) GetLeader() type LeaderElector struct { config LeaderElectionConfig // internal bookkeeping observedRecord LeaderElectionRecord observedTime time.Time // used to implement OnNewLeader(), may lag slightly from the // value observedRecord.HolderIdentity if the transistion has // not yet been reported. reportedLeader string } // LeaderElectionRecord is the record that is stored in the leader election annotation. // This information should be used for observational purposes only and could be replaced // with a random string (e.g. UUID) with only slight modification of this code. // TODO(mikedanese): this should potentially be versioned type LeaderElectionRecord struct { HolderIdentity string `json:"holderIdentity"` LeaseDurationSeconds int `json:"leaseDurationSeconds"` AcquireTime unversioned.Time `json:"acquireTime"` RenewTime unversioned.Time `json:"renewTime"` LeaderTransitions int `json:"leaderTransitions"` } // Run starts the leader election loop func (le *LeaderElector) Run() { defer func() { util.HandleCrash() le.config.Callbacks.OnStoppedLeading() }() le.acquire() stop := make(chan struct{}) go le.config.Callbacks.OnStartedLeading(stop) le.renew() close(stop) } // RunOrDie starts a client with the provided config or panics if the config // fails to validate. func RunOrDie(lec LeaderElectionConfig) { le, err := NewLeaderElector(lec) if err != nil { panic(err) } le.Run() } // GetLeader returns the identity of the last observed leader or returns the empty string if // no leader has yet been observed. func (le *LeaderElector) GetLeader() string { return le.observedRecord.HolderIdentity } // IsLeader returns true if the last observed leader was this client else returns false. func (le *LeaderElector) IsLeader() bool { return le.observedRecord.HolderIdentity == le.config.Identity } // acquire loops calling tryAcquireOrRenew and returns immediately when tryAcquireOrRenew succeeds. func (le *LeaderElector) acquire() { stop := make(chan struct{}) util.Until(func() { succeeded := le.tryAcquireOrRenew() le.maybeReportTransition() if !succeeded { glog.V(4).Infof("failed to renew lease %v/%v", le.config.EndpointsMeta.Namespace, le.config.EndpointsMeta.Name) time.Sleep(wait.Jitter(le.config.RetryPeriod, JitterFactor)) return } le.config.EventRecorder.Eventf(&api.Endpoints{ObjectMeta: le.config.EndpointsMeta}, api.EventTypeNormal, "%v became leader", le.config.Identity) glog.Infof("sucessfully acquired lease %v/%v", le.config.EndpointsMeta.Namespace, le.config.EndpointsMeta.Name) close(stop) }, 0, stop) } // renew loops calling tryAcquireOrRenew and returns immediately when tryAcquireOrRenew fails. func (le *LeaderElector) renew() { stop := make(chan struct{}) util.Until(func() { err := wait.Poll(le.config.RetryPeriod, le.config.RenewDeadline, func() (bool, error) { return le.tryAcquireOrRenew(), nil }) le.maybeReportTransition() if err == nil { glog.V(4).Infof("succesfully renewed lease %v/%v", le.config.EndpointsMeta.Namespace, le.config.EndpointsMeta.Name) return } le.config.EventRecorder.Eventf(&api.Endpoints{ObjectMeta: le.config.EndpointsMeta}, api.EventTypeNormal, "%v stopped leading", le.config.Identity) glog.Infof("failed to renew lease %v/%v", le.config.EndpointsMeta.Namespace, le.config.EndpointsMeta.Name) close(stop) }, 0, stop) } // tryAcquireOrRenew tries to acquire a leader lease if it is not already acquired, // else it tries to renew the lease if it has already been acquired. Returns true // on success else returns false. func (le *LeaderElector) tryAcquireOrRenew() bool { now := unversioned.Now() leaderElectionRecord := LeaderElectionRecord{ HolderIdentity: le.config.Identity, LeaseDurationSeconds: int(le.config.LeaseDuration / time.Second), RenewTime: now, AcquireTime: now, } e, err := le.config.Client.Endpoints(le.config.EndpointsMeta.Namespace).Get(le.config.EndpointsMeta.Name) if err != nil { if !errors.IsNotFound(err) { return false } leaderElectionRecordBytes, err := json.Marshal(leaderElectionRecord) if err != nil { return false } _, err = le.config.Client.Endpoints(le.config.EndpointsMeta.Namespace).Create(&api.Endpoints{ ObjectMeta: api.ObjectMeta{ Name: le.config.EndpointsMeta.Name, Namespace: le.config.EndpointsMeta.Namespace, Annotations: map[string]string{ LeaderElectionRecordAnnotationKey: string(leaderElectionRecordBytes), }, }, }) if err != nil { glog.Errorf("error initially creating endpoints: %v", err) return false } le.observedRecord = leaderElectionRecord le.observedTime = time.Now() return true } if e.Annotations == nil { e.Annotations = make(map[string]string) } var oldLeaderElectionRecord LeaderElectionRecord if oldLeaderElectionRecordBytes, found := e.Annotations[LeaderElectionRecordAnnotationKey]; found { if err := json.Unmarshal([]byte(oldLeaderElectionRecordBytes), &oldLeaderElectionRecord); err != nil { glog.Errorf("error unmarshaling leader election record: %v", err) return false } if !reflect.DeepEqual(le.observedRecord, oldLeaderElectionRecord) { le.observedRecord = oldLeaderElectionRecord le.observedTime = time.Now() } if le.observedTime.Add(le.config.LeaseDuration).After(now.Time) && oldLeaderElectionRecord.HolderIdentity != le.config.Identity { glog.Infof("lock is held by %v and has not yet expired", oldLeaderElectionRecord.HolderIdentity) return false } } // We're going to try to update. The leaderElectionRecord is set to it's default // here. Let's correct it before updating. if oldLeaderElectionRecord.HolderIdentity == le.config.Identity { leaderElectionRecord.AcquireTime = oldLeaderElectionRecord.AcquireTime } else { leaderElectionRecord.LeaderTransitions = oldLeaderElectionRecord.LeaderTransitions + 1 } leaderElectionRecordBytes, err := json.Marshal(leaderElectionRecord) if err != nil { glog.Errorf("err marshaling leader election record: %v", err) return false } e.Annotations[LeaderElectionRecordAnnotationKey] = string(leaderElectionRecordBytes) _, err = le.config.Client.Endpoints(le.config.EndpointsMeta.Namespace).Update(e) if err != nil { glog.Errorf("err: %v", err) return false } le.observedRecord = leaderElectionRecord le.observedTime = time.Now() return true } func (l *LeaderElector) maybeReportTransition() { if l.observedRecord.HolderIdentity == l.reportedLeader { return } l.reportedLeader = l.observedRecord.HolderIdentity if l.config.Callbacks.OnNewLeader != nil { go l.config.Callbacks.OnNewLeader(l.reportedLeader) } } func DefaultLeaderElectionConfiguration() componentconfig.LeaderElectionConfiguration { return componentconfig.LeaderElectionConfiguration{ LeaderElect: false, LeaseDuration: unversioned.Duration{DefaultLeaseDuration}, RenewDeadline: unversioned.Duration{DefaultRenewDeadline}, RetryPeriod: unversioned.Duration{DefaultRetryPeriod}, } } // BindFlags binds the common LeaderElectionCLIConfig flags to a flagset func BindFlags(l *componentconfig.LeaderElectionConfiguration, fs *pflag.FlagSet) { fs.BoolVar(&l.LeaderElect, "leader-elect", l.LeaderElect, ""+ "Start a leader election client and gain leadership before "+ "executing the main loop. Enable this when running replicated "+ "components for high availability.") fs.DurationVar(&l.LeaseDuration.Duration, "leader-elect-lease-duration", l.LeaseDuration.Duration, ""+ "The duration that non-leader candidates will wait after observing a leadership "+ "renewal until attempting to acquire leadership of a led but unrenewed leader "+ "slot. This is effectively the maximum duration that a leader can be stopped "+ "before it is replaced by another candidate. This is only applicable if leader "+ "election is enabled.") fs.DurationVar(&l.RenewDeadline.Duration, "leader-elect-renew-deadline", l.RenewDeadline.Duration, ""+ "The interval between attempts by the acting master to renew a leadership slot "+ "before it stops leading. This must be less than or equal to the lease duration. "+ "This is only applicable if leader election is enabled.") fs.DurationVar(&l.RetryPeriod.Duration, "leader-elect-retry-period", l.RetryPeriod.Duration, ""+ "The duration the clients should wait between attempting acquisition and renewal "+ "of a leadership. This is only applicable if leader election is enabled.") }
pkg/client/leaderelection/leaderelection.go
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.00029956235084682703, 0.0001774206612026319, 0.00016438346938230097, 0.00016981037333607674, 0.00002613599099277053 ]
{ "id": 7, "code_window": [ "\tview_example = `# Show Merged kubeconfig settings.\n", "$ kubectl config view\n", "\n", "# Get the password for the e2e user\n", "$ kubectl config view -o template --template='{{range .users}}{{ if eq .name \"e2e\" }}{{ index .user.password }}{{end}}{{end}}'`\n", ")\n", "\n", "func NewCmdConfigView(out io.Writer, ConfigAccess ConfigAccess) *cobra.Command {\n", "\toptions := &ViewOptions{ConfigAccess: ConfigAccess}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "$ kubectl config view -o jsonpath='{.users[?(@.name == \"e2e\")].user.password}'`\n" ], "file_path": "pkg/kubectl/cmd/config/view.go", "type": "replace", "edit_start_line_idx": 49 }
foo.bar[*].baz[2]
Godeps/_workspace/src/github.com/jmespath/go-jmespath/fuzz/corpus/expr-599
0
https://github.com/kubernetes/kubernetes/commit/734a8c060266da144b6a7c25f7322d108c856034
[ 0.00017375922470819205, 0.00017375922470819205, 0.00017375922470819205, 0.00017375922470819205, 0 ]
{ "id": 0, "code_window": [ "\t\tAddress: d.Get(\"address\").(string),\n", "\t\tProtocolPort: d.Get(\"port\").(int),\n", "\t}\n", "\n", "\tlog.Printf(\"[DEBUG] Create Options: %#v\", createOpts)\n", "\tm, err := members.Create(networkingClient, createOpts).Extract()\n", "\tif err != nil {\n", "\t\treturn fmt.Errorf(\"Error creating OpenStack LB member: %s\", err)\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tlog.Printf(\"[DEBUG] OpenStack LB Member Create Options: %#v\", createOpts)\n" ], "file_path": "builtin/providers/openstack/resource_openstack_lb_member_v1.go", "type": "replace", "edit_start_line_idx": 77 }
package openstack import ( "fmt" "log" "time" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" "github.com/rackspace/gophercloud" "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/members" ) func resourceLBMemberV1() *schema.Resource { return &schema.Resource{ Create: resourceLBMemberV1Create, Read: resourceLBMemberV1Read, Update: resourceLBMemberV1Update, Delete: resourceLBMemberV1Delete, Schema: map[string]*schema.Schema{ "region": &schema.Schema{ Type: schema.TypeString, Required: true, ForceNew: true, DefaultFunc: schema.EnvDefaultFunc("OS_REGION_NAME", ""), }, "tenant_id": &schema.Schema{ Type: schema.TypeString, Optional: true, ForceNew: true, }, "pool_id": &schema.Schema{ Type: schema.TypeString, Required: true, ForceNew: true, }, "address": &schema.Schema{ Type: schema.TypeString, Required: true, ForceNew: true, }, "port": &schema.Schema{ Type: schema.TypeInt, Required: true, ForceNew: true, }, "weight": &schema.Schema{ Type: schema.TypeInt, Optional: true, Computed: true, }, "admin_state_up": &schema.Schema{ Type: schema.TypeBool, Optional: true, ForceNew: false, Computed: true, }, }, } } func resourceLBMemberV1Create(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) networkingClient, err := config.networkingV2Client(d.Get("region").(string)) if err != nil { return fmt.Errorf("Error creating OpenStack networking client: %s", err) } createOpts := members.CreateOpts{ TenantID: d.Get("tenant_id").(string), PoolID: d.Get("pool_id").(string), Address: d.Get("address").(string), ProtocolPort: d.Get("port").(int), } log.Printf("[DEBUG] Create Options: %#v", createOpts) m, err := members.Create(networkingClient, createOpts).Extract() if err != nil { return fmt.Errorf("Error creating OpenStack LB member: %s", err) } log.Printf("[INFO] LB member ID: %s", m.ID) log.Printf("[DEBUG] Waiting for OpenStack LB member (%s) to become available.", m.ID) stateConf := &resource.StateChangeConf{ Pending: []string{"PENDING_CREATE"}, Target: []string{"ACTIVE"}, Refresh: waitForLBMemberActive(networkingClient, m.ID), Timeout: 2 * time.Minute, Delay: 5 * time.Second, MinTimeout: 3 * time.Second, } _, err = stateConf.WaitForState() if err != nil { return err } d.SetId(m.ID) return resourceLBMemberV1Read(d, meta) } func resourceLBMemberV1Read(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) networkingClient, err := config.networkingV2Client(d.Get("region").(string)) if err != nil { return fmt.Errorf("Error creating OpenStack networking client: %s", err) } m, err := members.Get(networkingClient, d.Id()).Extract() if err != nil { return CheckDeleted(d, err, "LB member") } log.Printf("[DEBUG] Retreived OpenStack LB member %s: %+v", d.Id(), m) d.Set("weight", m.Weight) d.Set("admin_state_up", m.AdminStateUp) return nil } func resourceLBMemberV1Update(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) networkingClient, err := config.networkingV2Client(d.Get("region").(string)) if err != nil { return fmt.Errorf("Error creating OpenStack networking client: %s", err) } var updateOpts members.UpdateOpts if d.HasChange("admin_state_up") { asu := d.Get("admin_state_up").(bool) updateOpts.AdminStateUp = asu } log.Printf("[DEBUG] Updating LB member %s with options: %+v", d.Id(), updateOpts) _, err = members.Update(networkingClient, d.Id(), updateOpts).Extract() if err != nil { return fmt.Errorf("Error updating OpenStack LB member: %s", err) } return resourceLBMemberV1Read(d, meta) } func resourceLBMemberV1Delete(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) networkingClient, err := config.networkingV2Client(d.Get("region").(string)) if err != nil { return fmt.Errorf("Error creating OpenStack networking client: %s", err) } err = members.Delete(networkingClient, d.Id()).ExtractErr() if err != nil { CheckDeleted(d, err, "LB member") } stateConf := &resource.StateChangeConf{ Pending: []string{"ACTIVE", "PENDING_DELETE"}, Target: []string{"DELETED"}, Refresh: waitForLBMemberDelete(networkingClient, d.Id()), Timeout: 2 * time.Minute, Delay: 5 * time.Second, MinTimeout: 3 * time.Second, } _, err = stateConf.WaitForState() if err != nil { return fmt.Errorf("Error deleting OpenStack LB member: %s", err) } d.SetId("") return nil } func waitForLBMemberActive(networkingClient *gophercloud.ServiceClient, memberId string) resource.StateRefreshFunc { return func() (interface{}, string, error) { m, err := members.Get(networkingClient, memberId).Extract() if err != nil { return nil, "", err } log.Printf("[DEBUG] OpenStack LB member: %+v", m) if m.Status == "ACTIVE" { return m, "ACTIVE", nil } return m, m.Status, nil } } func waitForLBMemberDelete(networkingClient *gophercloud.ServiceClient, memberId string) resource.StateRefreshFunc { return func() (interface{}, string, error) { log.Printf("[DEBUG] Attempting to delete OpenStack LB member %s", memberId) m, err := members.Get(networkingClient, memberId).Extract() if err != nil { errCode, ok := err.(*gophercloud.UnexpectedResponseCodeError) if !ok { return m, "ACTIVE", err } if errCode.Actual == 404 { log.Printf("[DEBUG] Successfully deleted OpenStack LB member %s", memberId) return m, "DELETED", nil } } log.Printf("[DEBUG] OpenStack LB member %s still active.", memberId) return m, "ACTIVE", nil } }
builtin/providers/openstack/resource_openstack_lb_member_v1.go
1
https://github.com/hashicorp/terraform/commit/62a744a45e1ce80211ff134c195a8b7cb70949af
[ 0.9984326958656311, 0.4251822531223297, 0.00016315824177581817, 0.09325330704450607, 0.471351683139801 ]
{ "id": 0, "code_window": [ "\t\tAddress: d.Get(\"address\").(string),\n", "\t\tProtocolPort: d.Get(\"port\").(int),\n", "\t}\n", "\n", "\tlog.Printf(\"[DEBUG] Create Options: %#v\", createOpts)\n", "\tm, err := members.Create(networkingClient, createOpts).Extract()\n", "\tif err != nil {\n", "\t\treturn fmt.Errorf(\"Error creating OpenStack LB member: %s\", err)\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tlog.Printf(\"[DEBUG] OpenStack LB Member Create Options: %#v\", createOpts)\n" ], "file_path": "builtin/providers/openstack/resource_openstack_lb_member_v1.go", "type": "replace", "edit_start_line_idx": 77 }
--- layout: "postgresql" page_title: "Provider: PostgreSQL" sidebar_current: "docs-postgresql-index" description: |- A provider for PostgreSQL Server. --- # PostgreSQL Provider The PostgreSQL provider gives the ability to deploy and configure resources in a PostgreSQL server. Use the navigation to the left to read about the available resources. ## Usage ``` provider "postgresql" { host = "postgres_server_ip" port = 5432 username = "postgres_user" password = "postgres_password" ssl_mode = "require" } ``` Configuring multiple servers can be done by specifying the alias option. ``` provider "postgresql" { alias = "pg1" host = "postgres_server_ip1" username = "postgres_user1" password = "postgres_password1" } provider "postgresql" { alias = "pg2" host = "postgres_server_ip2" username = "postgres_user2" password = "postgres_password2" } resource "postgresql_database" "my_db1" { provider = "postgresql.pg1" name = "my_db1" } resource "postgresql_database" "my_db2" { provider = "postgresql.pg2" name = "my_db2" } ``` ## Argument Reference The following arguments are supported: * `host` - (Required) The address for the postgresql server connection. * `port` - (Optional) The port for the postgresql server connection. The default is `5432`. * `username` - (Required) Username for the server connection. * `password` - (Optional) Password for the server connection. * `ssl_mode` - (Optional) Set the priority for an SSL connection to the server. The default is `prefer`; the full set of options and their implications can be seen [in the libpq SSL guide](http://www.postgresql.org/docs/9.4/static/libpq-ssl.html#LIBPQ-SSL-PROTECTION).
website/source/docs/providers/postgresql/index.html.markdown
0
https://github.com/hashicorp/terraform/commit/62a744a45e1ce80211ff134c195a8b7cb70949af
[ 0.00017497291264589876, 0.00017136397946160287, 0.00016381328168790787, 0.00017290955292992294, 0.0000036640260532294633 ]
{ "id": 0, "code_window": [ "\t\tAddress: d.Get(\"address\").(string),\n", "\t\tProtocolPort: d.Get(\"port\").(int),\n", "\t}\n", "\n", "\tlog.Printf(\"[DEBUG] Create Options: %#v\", createOpts)\n", "\tm, err := members.Create(networkingClient, createOpts).Extract()\n", "\tif err != nil {\n", "\t\treturn fmt.Errorf(\"Error creating OpenStack LB member: %s\", err)\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tlog.Printf(\"[DEBUG] OpenStack LB Member Create Options: %#v\", createOpts)\n" ], "file_path": "builtin/providers/openstack/resource_openstack_lb_member_v1.go", "type": "replace", "edit_start_line_idx": 77 }
package google import ( "fmt" "log" "net" "regexp" "time" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" "google.golang.org/api/container/v1" "google.golang.org/api/googleapi" ) func resourceContainerCluster() *schema.Resource { return &schema.Resource{ Create: resourceContainerClusterCreate, Read: resourceContainerClusterRead, Update: resourceContainerClusterUpdate, Delete: resourceContainerClusterDelete, Schema: map[string]*schema.Schema{ "initial_node_count": &schema.Schema{ Type: schema.TypeInt, Required: true, ForceNew: true, }, "master_auth": &schema.Schema{ Type: schema.TypeList, Required: true, ForceNew: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "client_certificate": &schema.Schema{ Type: schema.TypeString, Computed: true, }, "client_key": &schema.Schema{ Type: schema.TypeString, Computed: true, }, "cluster_ca_certificate": &schema.Schema{ Type: schema.TypeString, Computed: true, }, "password": &schema.Schema{ Type: schema.TypeString, Required: true, ForceNew: true, }, "username": &schema.Schema{ Type: schema.TypeString, Required: true, ForceNew: true, }, }, }, }, "name": &schema.Schema{ Type: schema.TypeString, Required: true, ForceNew: true, ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { value := v.(string) if len(value) > 40 { errors = append(errors, fmt.Errorf( "%q cannot be longer than 40 characters", k)) } if !regexp.MustCompile("^[a-z0-9-]+$").MatchString(value) { errors = append(errors, fmt.Errorf( "%q can only contain lowercase letters, numbers and hyphens", k)) } if !regexp.MustCompile("^[a-z]").MatchString(value) { errors = append(errors, fmt.Errorf( "%q must start with a letter", k)) } if !regexp.MustCompile("[a-z0-9]$").MatchString(value) { errors = append(errors, fmt.Errorf( "%q must end with a number or a letter", k)) } return }, }, "zone": &schema.Schema{ Type: schema.TypeString, Required: true, ForceNew: true, }, "cluster_ipv4_cidr": &schema.Schema{ Type: schema.TypeString, Optional: true, Computed: true, ForceNew: true, ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { value := v.(string) _, ipnet, err := net.ParseCIDR(value) if err != nil || ipnet == nil || value != ipnet.String() { errors = append(errors, fmt.Errorf( "%q must contain a valid CIDR", k)) } return }, }, "description": &schema.Schema{ Type: schema.TypeString, Optional: true, ForceNew: true, }, "endpoint": &schema.Schema{ Type: schema.TypeString, Computed: true, }, "instance_group_urls": &schema.Schema{ Type: schema.TypeList, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, "logging_service": &schema.Schema{ Type: schema.TypeString, Optional: true, Computed: true, ForceNew: true, }, "monitoring_service": &schema.Schema{ Type: schema.TypeString, Optional: true, Computed: true, ForceNew: true, }, "network": &schema.Schema{ Type: schema.TypeString, Optional: true, Default: "default", ForceNew: true, }, "subnetwork": &schema.Schema{ Type: schema.TypeString, Optional: true, ForceNew: true, }, "addons_config": &schema.Schema{ Type: schema.TypeList, Optional: true, ForceNew: true, MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "http_load_balancing": &schema.Schema{ Type: schema.TypeList, Optional: true, ForceNew: true, MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "disabled": &schema.Schema{ Type: schema.TypeBool, Optional: true, ForceNew: true, }, }, }, }, "horizontal_pod_autoscaling": &schema.Schema{ Type: schema.TypeList, Optional: true, ForceNew: true, MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "disabled": &schema.Schema{ Type: schema.TypeBool, Optional: true, ForceNew: true, }, }, }, }, }, }, }, "node_config": &schema.Schema{ Type: schema.TypeList, Optional: true, Computed: true, ForceNew: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "machine_type": &schema.Schema{ Type: schema.TypeString, Optional: true, Computed: true, ForceNew: true, }, "disk_size_gb": &schema.Schema{ Type: schema.TypeInt, Optional: true, Computed: true, ForceNew: true, ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { value := v.(int) if value < 10 { errors = append(errors, fmt.Errorf( "%q cannot be less than 10", k)) } return }, }, "oauth_scopes": &schema.Schema{ Type: schema.TypeList, Elem: &schema.Schema{Type: schema.TypeString}, Optional: true, Computed: true, ForceNew: true, }, }, }, }, "node_version": &schema.Schema{ Type: schema.TypeString, Optional: true, Computed: true, }, "project": &schema.Schema{ Type: schema.TypeString, Optional: true, ForceNew: true, }, }, } } func resourceContainerClusterCreate(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) project, err := getProject(d, config) if err != nil { return err } zoneName := d.Get("zone").(string) clusterName := d.Get("name").(string) masterAuths := d.Get("master_auth").([]interface{}) if len(masterAuths) > 1 { return fmt.Errorf("Cannot specify more than one master_auth.") } masterAuth := masterAuths[0].(map[string]interface{}) cluster := &container.Cluster{ MasterAuth: &container.MasterAuth{ Password: masterAuth["password"].(string), Username: masterAuth["username"].(string), }, Name: clusterName, InitialNodeCount: int64(d.Get("initial_node_count").(int)), } if v, ok := d.GetOk("cluster_ipv4_cidr"); ok { cluster.ClusterIpv4Cidr = v.(string) } if v, ok := d.GetOk("description"); ok { cluster.Description = v.(string) } if v, ok := d.GetOk("logging_service"); ok { cluster.LoggingService = v.(string) } if v, ok := d.GetOk("monitoring_service"); ok { cluster.MonitoringService = v.(string) } if v, ok := d.GetOk("network"); ok { cluster.Network = v.(string) } if v, ok := d.GetOk("subnetwork"); ok { cluster.Subnetwork = v.(string) } if v, ok := d.GetOk("addons_config"); ok { addonsConfig := v.([]interface{})[0].(map[string]interface{}) cluster.AddonsConfig = &container.AddonsConfig{} if v, ok := addonsConfig["http_load_balancing"]; ok { addon := v.([]interface{})[0].(map[string]interface{}) cluster.AddonsConfig.HttpLoadBalancing = &container.HttpLoadBalancing{ Disabled: addon["disabled"].(bool), } } if v, ok := addonsConfig["horizontal_pod_autoscaling"]; ok { addon := v.([]interface{})[0].(map[string]interface{}) cluster.AddonsConfig.HorizontalPodAutoscaling = &container.HorizontalPodAutoscaling{ Disabled: addon["disabled"].(bool), } } } if v, ok := d.GetOk("node_config"); ok { nodeConfigs := v.([]interface{}) if len(nodeConfigs) > 1 { return fmt.Errorf("Cannot specify more than one node_config.") } nodeConfig := nodeConfigs[0].(map[string]interface{}) cluster.NodeConfig = &container.NodeConfig{} if v, ok = nodeConfig["machine_type"]; ok { cluster.NodeConfig.MachineType = v.(string) } if v, ok = nodeConfig["disk_size_gb"]; ok { cluster.NodeConfig.DiskSizeGb = int64(v.(int)) } if v, ok := nodeConfig["oauth_scopes"]; ok { scopesList := v.([]interface{}) scopes := []string{} for _, v := range scopesList { scopes = append(scopes, v.(string)) } cluster.NodeConfig.OauthScopes = scopes } } req := &container.CreateClusterRequest{ Cluster: cluster, } op, err := config.clientContainer.Projects.Zones.Clusters.Create( project, zoneName, req).Do() if err != nil { return err } // Wait until it's created wait := resource.StateChangeConf{ Pending: []string{"PENDING", "RUNNING"}, Target: []string{"DONE"}, Timeout: 30 * time.Minute, MinTimeout: 3 * time.Second, Refresh: func() (interface{}, string, error) { resp, err := config.clientContainer.Projects.Zones.Operations.Get( project, zoneName, op.Name).Do() log.Printf("[DEBUG] Progress of creating GKE cluster %s: %s", clusterName, resp.Status) return resp, resp.Status, err }, } _, err = wait.WaitForState() if err != nil { return err } log.Printf("[INFO] GKE cluster %s has been created", clusterName) d.SetId(clusterName) return resourceContainerClusterRead(d, meta) } func resourceContainerClusterRead(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) project, err := getProject(d, config) if err != nil { return err } zoneName := d.Get("zone").(string) cluster, err := config.clientContainer.Projects.Zones.Clusters.Get( project, zoneName, d.Get("name").(string)).Do() if err != nil { if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 { log.Printf("[WARN] Removing Container Cluster %q because it's gone", d.Get("name").(string)) // The resource doesn't exist anymore d.SetId("") return nil } return err } d.Set("name", cluster.Name) d.Set("zone", cluster.Zone) d.Set("endpoint", cluster.Endpoint) masterAuth := []map[string]interface{}{ map[string]interface{}{ "username": cluster.MasterAuth.Username, "password": cluster.MasterAuth.Password, "client_certificate": cluster.MasterAuth.ClientCertificate, "client_key": cluster.MasterAuth.ClientKey, "cluster_ca_certificate": cluster.MasterAuth.ClusterCaCertificate, }, } d.Set("master_auth", masterAuth) d.Set("initial_node_count", cluster.InitialNodeCount) d.Set("node_version", cluster.CurrentNodeVersion) d.Set("cluster_ipv4_cidr", cluster.ClusterIpv4Cidr) d.Set("description", cluster.Description) d.Set("logging_service", cluster.LoggingService) d.Set("monitoring_service", cluster.MonitoringService) d.Set("network", cluster.Network) d.Set("subnetwork", cluster.Subnetwork) d.Set("node_config", flattenClusterNodeConfig(cluster.NodeConfig)) d.Set("instance_group_urls", cluster.InstanceGroupUrls) return nil } func resourceContainerClusterUpdate(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) project, err := getProject(d, config) if err != nil { return err } zoneName := d.Get("zone").(string) clusterName := d.Get("name").(string) desiredNodeVersion := d.Get("node_version").(string) req := &container.UpdateClusterRequest{ Update: &container.ClusterUpdate{ DesiredNodeVersion: desiredNodeVersion, }, } op, err := config.clientContainer.Projects.Zones.Clusters.Update( project, zoneName, clusterName, req).Do() if err != nil { return err } // Wait until it's updated wait := resource.StateChangeConf{ Pending: []string{"PENDING", "RUNNING"}, Target: []string{"DONE"}, Timeout: 10 * time.Minute, MinTimeout: 2 * time.Second, Refresh: func() (interface{}, string, error) { log.Printf("[DEBUG] Checking if GKE cluster %s is updated", clusterName) resp, err := config.clientContainer.Projects.Zones.Operations.Get( project, zoneName, op.Name).Do() log.Printf("[DEBUG] Progress of updating GKE cluster %s: %s", clusterName, resp.Status) return resp, resp.Status, err }, } _, err = wait.WaitForState() if err != nil { return err } log.Printf("[INFO] GKE cluster %s has been updated to %s", d.Id(), desiredNodeVersion) return resourceContainerClusterRead(d, meta) } func resourceContainerClusterDelete(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) project, err := getProject(d, config) if err != nil { return err } zoneName := d.Get("zone").(string) clusterName := d.Get("name").(string) log.Printf("[DEBUG] Deleting GKE cluster %s", d.Get("name").(string)) op, err := config.clientContainer.Projects.Zones.Clusters.Delete( project, zoneName, clusterName).Do() if err != nil { return err } // Wait until it's deleted wait := resource.StateChangeConf{ Pending: []string{"PENDING", "RUNNING"}, Target: []string{"DONE"}, Timeout: 10 * time.Minute, MinTimeout: 3 * time.Second, Refresh: func() (interface{}, string, error) { log.Printf("[DEBUG] Checking if GKE cluster %s is deleted", clusterName) resp, err := config.clientContainer.Projects.Zones.Operations.Get( project, zoneName, op.Name).Do() log.Printf("[DEBUG] Progress of deleting GKE cluster %s: %s", clusterName, resp.Status) return resp, resp.Status, err }, } _, err = wait.WaitForState() if err != nil { return err } log.Printf("[INFO] GKE cluster %s has been deleted", d.Id()) d.SetId("") return nil } func flattenClusterNodeConfig(c *container.NodeConfig) []map[string]interface{} { config := []map[string]interface{}{ map[string]interface{}{ "machine_type": c.MachineType, "disk_size_gb": c.DiskSizeGb, }, } if len(c.OauthScopes) > 0 { config[0]["oauth_scopes"] = c.OauthScopes } return config }
builtin/providers/google/resource_container_cluster.go
0
https://github.com/hashicorp/terraform/commit/62a744a45e1ce80211ff134c195a8b7cb70949af
[ 0.0027728069107979536, 0.0002448685991112143, 0.0001655106752878055, 0.0001739719300530851, 0.0003579141048248857 ]
{ "id": 0, "code_window": [ "\t\tAddress: d.Get(\"address\").(string),\n", "\t\tProtocolPort: d.Get(\"port\").(int),\n", "\t}\n", "\n", "\tlog.Printf(\"[DEBUG] Create Options: %#v\", createOpts)\n", "\tm, err := members.Create(networkingClient, createOpts).Extract()\n", "\tif err != nil {\n", "\t\treturn fmt.Errorf(\"Error creating OpenStack LB member: %s\", err)\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tlog.Printf(\"[DEBUG] OpenStack LB Member Create Options: %#v\", createOpts)\n" ], "file_path": "builtin/providers/openstack/resource_openstack_lb_member_v1.go", "type": "replace", "edit_start_line_idx": 77 }
package main import ( "github.com/hashicorp/terraform/builtin/providers/ultradns" "github.com/hashicorp/terraform/plugin" ) func main() { plugin.Serve(&plugin.ServeOpts{ ProviderFunc: ultradns.Provider, }) }
builtin/bins/provider-ultradns/main.go
0
https://github.com/hashicorp/terraform/commit/62a744a45e1ce80211ff134c195a8b7cb70949af
[ 0.00017548217147123069, 0.00017408595886081457, 0.00017268974625039846, 0.00017408595886081457, 0.0000013962126104161143 ]
{ "id": 1, "code_window": [ "\tlog.Printf(\"[DEBUG] Waiting for OpenStack LB member (%s) to become available.\", m.ID)\n", "\n", "\tstateConf := &resource.StateChangeConf{\n", "\t\tPending: []string{\"PENDING_CREATE\"},\n", "\t\tTarget: []string{\"ACTIVE\"},\n", "\t\tRefresh: waitForLBMemberActive(networkingClient, m.ID),\n", "\t\tTimeout: 2 * time.Minute,\n", "\t\tDelay: 5 * time.Second,\n", "\t\tMinTimeout: 3 * time.Second,\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tTarget: []string{\"ACTIVE\", \"INACTIVE\"},\n" ], "file_path": "builtin/providers/openstack/resource_openstack_lb_member_v1.go", "type": "replace", "edit_start_line_idx": 88 }
package openstack import ( "fmt" "log" "time" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" "github.com/rackspace/gophercloud" "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/members" ) func resourceLBMemberV1() *schema.Resource { return &schema.Resource{ Create: resourceLBMemberV1Create, Read: resourceLBMemberV1Read, Update: resourceLBMemberV1Update, Delete: resourceLBMemberV1Delete, Schema: map[string]*schema.Schema{ "region": &schema.Schema{ Type: schema.TypeString, Required: true, ForceNew: true, DefaultFunc: schema.EnvDefaultFunc("OS_REGION_NAME", ""), }, "tenant_id": &schema.Schema{ Type: schema.TypeString, Optional: true, ForceNew: true, }, "pool_id": &schema.Schema{ Type: schema.TypeString, Required: true, ForceNew: true, }, "address": &schema.Schema{ Type: schema.TypeString, Required: true, ForceNew: true, }, "port": &schema.Schema{ Type: schema.TypeInt, Required: true, ForceNew: true, }, "weight": &schema.Schema{ Type: schema.TypeInt, Optional: true, Computed: true, }, "admin_state_up": &schema.Schema{ Type: schema.TypeBool, Optional: true, ForceNew: false, Computed: true, }, }, } } func resourceLBMemberV1Create(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) networkingClient, err := config.networkingV2Client(d.Get("region").(string)) if err != nil { return fmt.Errorf("Error creating OpenStack networking client: %s", err) } createOpts := members.CreateOpts{ TenantID: d.Get("tenant_id").(string), PoolID: d.Get("pool_id").(string), Address: d.Get("address").(string), ProtocolPort: d.Get("port").(int), } log.Printf("[DEBUG] Create Options: %#v", createOpts) m, err := members.Create(networkingClient, createOpts).Extract() if err != nil { return fmt.Errorf("Error creating OpenStack LB member: %s", err) } log.Printf("[INFO] LB member ID: %s", m.ID) log.Printf("[DEBUG] Waiting for OpenStack LB member (%s) to become available.", m.ID) stateConf := &resource.StateChangeConf{ Pending: []string{"PENDING_CREATE"}, Target: []string{"ACTIVE"}, Refresh: waitForLBMemberActive(networkingClient, m.ID), Timeout: 2 * time.Minute, Delay: 5 * time.Second, MinTimeout: 3 * time.Second, } _, err = stateConf.WaitForState() if err != nil { return err } d.SetId(m.ID) return resourceLBMemberV1Read(d, meta) } func resourceLBMemberV1Read(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) networkingClient, err := config.networkingV2Client(d.Get("region").(string)) if err != nil { return fmt.Errorf("Error creating OpenStack networking client: %s", err) } m, err := members.Get(networkingClient, d.Id()).Extract() if err != nil { return CheckDeleted(d, err, "LB member") } log.Printf("[DEBUG] Retreived OpenStack LB member %s: %+v", d.Id(), m) d.Set("weight", m.Weight) d.Set("admin_state_up", m.AdminStateUp) return nil } func resourceLBMemberV1Update(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) networkingClient, err := config.networkingV2Client(d.Get("region").(string)) if err != nil { return fmt.Errorf("Error creating OpenStack networking client: %s", err) } var updateOpts members.UpdateOpts if d.HasChange("admin_state_up") { asu := d.Get("admin_state_up").(bool) updateOpts.AdminStateUp = asu } log.Printf("[DEBUG] Updating LB member %s with options: %+v", d.Id(), updateOpts) _, err = members.Update(networkingClient, d.Id(), updateOpts).Extract() if err != nil { return fmt.Errorf("Error updating OpenStack LB member: %s", err) } return resourceLBMemberV1Read(d, meta) } func resourceLBMemberV1Delete(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) networkingClient, err := config.networkingV2Client(d.Get("region").(string)) if err != nil { return fmt.Errorf("Error creating OpenStack networking client: %s", err) } err = members.Delete(networkingClient, d.Id()).ExtractErr() if err != nil { CheckDeleted(d, err, "LB member") } stateConf := &resource.StateChangeConf{ Pending: []string{"ACTIVE", "PENDING_DELETE"}, Target: []string{"DELETED"}, Refresh: waitForLBMemberDelete(networkingClient, d.Id()), Timeout: 2 * time.Minute, Delay: 5 * time.Second, MinTimeout: 3 * time.Second, } _, err = stateConf.WaitForState() if err != nil { return fmt.Errorf("Error deleting OpenStack LB member: %s", err) } d.SetId("") return nil } func waitForLBMemberActive(networkingClient *gophercloud.ServiceClient, memberId string) resource.StateRefreshFunc { return func() (interface{}, string, error) { m, err := members.Get(networkingClient, memberId).Extract() if err != nil { return nil, "", err } log.Printf("[DEBUG] OpenStack LB member: %+v", m) if m.Status == "ACTIVE" { return m, "ACTIVE", nil } return m, m.Status, nil } } func waitForLBMemberDelete(networkingClient *gophercloud.ServiceClient, memberId string) resource.StateRefreshFunc { return func() (interface{}, string, error) { log.Printf("[DEBUG] Attempting to delete OpenStack LB member %s", memberId) m, err := members.Get(networkingClient, memberId).Extract() if err != nil { errCode, ok := err.(*gophercloud.UnexpectedResponseCodeError) if !ok { return m, "ACTIVE", err } if errCode.Actual == 404 { log.Printf("[DEBUG] Successfully deleted OpenStack LB member %s", memberId) return m, "DELETED", nil } } log.Printf("[DEBUG] OpenStack LB member %s still active.", memberId) return m, "ACTIVE", nil } }
builtin/providers/openstack/resource_openstack_lb_member_v1.go
1
https://github.com/hashicorp/terraform/commit/62a744a45e1ce80211ff134c195a8b7cb70949af
[ 0.9983586668968201, 0.12940658628940582, 0.00016283807053696364, 0.0018658386543393135, 0.32207876443862915 ]
{ "id": 1, "code_window": [ "\tlog.Printf(\"[DEBUG] Waiting for OpenStack LB member (%s) to become available.\", m.ID)\n", "\n", "\tstateConf := &resource.StateChangeConf{\n", "\t\tPending: []string{\"PENDING_CREATE\"},\n", "\t\tTarget: []string{\"ACTIVE\"},\n", "\t\tRefresh: waitForLBMemberActive(networkingClient, m.ID),\n", "\t\tTimeout: 2 * time.Minute,\n", "\t\tDelay: 5 * time.Second,\n", "\t\tMinTimeout: 3 * time.Second,\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tTarget: []string{\"ACTIVE\", \"INACTIVE\"},\n" ], "file_path": "builtin/providers/openstack/resource_openstack_lb_member_v1.go", "type": "replace", "edit_start_line_idx": 88 }
package docker import ( "fmt" "regexp" "testing" dc "github.com/fsouza/go-dockerclient" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) var contentDigestRegexp = regexp.MustCompile(`\A[A-Za-z0-9_\+\.-]+:[A-Fa-f0-9]+\z`) func TestAccDockerImage_basic(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccDockerImageDestroy, Steps: []resource.TestStep{ resource.TestStep{ Config: testAccDockerImageConfig, Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr("docker_image.foo", "latest", contentDigestRegexp), ), }, }, }) } func TestAccDockerImage_private(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccDockerImageDestroy, Steps: []resource.TestStep{ resource.TestStep{ Config: testAddDockerPrivateImageConfig, Check: resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr("docker_image.foobar", "latest", contentDigestRegexp), ), }, }, }) } func testAccDockerImageDestroy(s *terraform.State) error { //client := testAccProvider.Meta().(*dc.Client) for _, rs := range s.RootModule().Resources { if rs.Type != "docker_image" { continue } client := testAccProvider.Meta().(*dc.Client) _, err := client.InspectImage(rs.Primary.Attributes["latest"]) if err == nil { return fmt.Errorf("Image still exists") } else if err != dc.ErrNoSuchImage { return err } } return nil } const testAccDockerImageConfig = ` resource "docker_image" "foo" { name = "alpine:3.1" keep_updated = false } ` const testAddDockerPrivateImageConfig = ` resource "docker_image" "foobar" { name = "gcr.io:443/google_containers/pause:0.8.0" keep_updated = true } `
builtin/providers/docker/resource_docker_image_test.go
0
https://github.com/hashicorp/terraform/commit/62a744a45e1ce80211ff134c195a8b7cb70949af
[ 0.00017178778944071382, 0.0001693953963695094, 0.0001667915639700368, 0.00016972926096059382, 0.0000015251036984409438 ]
{ "id": 1, "code_window": [ "\tlog.Printf(\"[DEBUG] Waiting for OpenStack LB member (%s) to become available.\", m.ID)\n", "\n", "\tstateConf := &resource.StateChangeConf{\n", "\t\tPending: []string{\"PENDING_CREATE\"},\n", "\t\tTarget: []string{\"ACTIVE\"},\n", "\t\tRefresh: waitForLBMemberActive(networkingClient, m.ID),\n", "\t\tTimeout: 2 * time.Minute,\n", "\t\tDelay: 5 * time.Second,\n", "\t\tMinTimeout: 3 * time.Second,\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tTarget: []string{\"ACTIVE\", \"INACTIVE\"},\n" ], "file_path": "builtin/providers/openstack/resource_openstack_lb_member_v1.go", "type": "replace", "edit_start_line_idx": 88 }
package cloudstack import ( "fmt" "log" "net" "strconv" "strings" "github.com/hashicorp/terraform/helper/schema" "github.com/xanzy/go-cloudstack/cloudstack" ) func resourceCloudStackNetwork() *schema.Resource { return &schema.Resource{ Create: resourceCloudStackNetworkCreate, Read: resourceCloudStackNetworkRead, Update: resourceCloudStackNetworkUpdate, Delete: resourceCloudStackNetworkDelete, Schema: map[string]*schema.Schema{ "name": &schema.Schema{ Type: schema.TypeString, Required: true, }, "display_text": &schema.Schema{ Type: schema.TypeString, Optional: true, Computed: true, }, "cidr": &schema.Schema{ Type: schema.TypeString, Required: true, ForceNew: true, }, "gateway": &schema.Schema{ Type: schema.TypeString, Optional: true, Computed: true, ForceNew: true, }, "startip": &schema.Schema{ Type: schema.TypeString, Optional: true, Computed: true, ForceNew: true, }, "endip": &schema.Schema{ Type: schema.TypeString, Optional: true, Computed: true, ForceNew: true, }, "network_offering": &schema.Schema{ Type: schema.TypeString, Required: true, }, "vlan": &schema.Schema{ Type: schema.TypeInt, Optional: true, ForceNew: true, }, "vpc_id": &schema.Schema{ Type: schema.TypeString, Optional: true, Computed: true, ForceNew: true, }, "vpc": &schema.Schema{ Type: schema.TypeString, Optional: true, ForceNew: true, Deprecated: "Please use the `vpc_id` field instead", }, "acl_id": &schema.Schema{ Type: schema.TypeString, Optional: true, Computed: true, ForceNew: true, ConflictsWith: []string{"aclid"}, }, "aclid": &schema.Schema{ Type: schema.TypeString, Optional: true, ForceNew: true, Deprecated: "Please use the `acl_id` field instead", }, "project": &schema.Schema{ Type: schema.TypeString, Optional: true, ForceNew: true, }, "zone": &schema.Schema{ Type: schema.TypeString, Required: true, ForceNew: true, }, "tags": tagsSchema(), }, } } func resourceCloudStackNetworkCreate(d *schema.ResourceData, meta interface{}) error { cs := meta.(*cloudstack.CloudStackClient) name := d.Get("name").(string) // Retrieve the network_offering ID networkofferingid, e := retrieveID(cs, "network_offering", d.Get("network_offering").(string)) if e != nil { return e.Error() } // Retrieve the zone ID zoneid, e := retrieveID(cs, "zone", d.Get("zone").(string)) if e != nil { return e.Error() } // Compute/set the display text displaytext, ok := d.GetOk("display_text") if !ok { displaytext = name } // Create a new parameter struct p := cs.Network.NewCreateNetworkParams(displaytext.(string), name, networkofferingid, zoneid) m, err := parseCIDR(d) if err != nil { return err } // Set the needed IP config p.SetStartip(m["startip"]) p.SetGateway(m["gateway"]) p.SetEndip(m["endip"]) p.SetNetmask(m["netmask"]) if vlan, ok := d.GetOk("vlan"); ok { p.SetVlan(strconv.Itoa(vlan.(int))) } // Check is this network needs to be created in a VPC vpc, ok := d.GetOk("vpc_id") if !ok { vpc, ok = d.GetOk("vpc") } if ok { // Retrieve the vpc ID vpcid, e := retrieveID(cs, "vpc", vpc.(string)) if e != nil { return e.Error() } // Set the vpcid p.SetVpcid(vpcid) // Since we're in a VPC, check if we want to assiciate an ACL list aclid, ok := d.GetOk("acl_id") if !ok { aclid, ok = d.GetOk("acl") } if ok { // Set the acl ID p.SetAclid(aclid.(string)) } } // If there is a project supplied, we retrieve and set the project id if err := setProjectid(p, cs, d); err != nil { return err } // Create the new network r, err := cs.Network.CreateNetwork(p) if err != nil { return fmt.Errorf("Error creating network %s: %s", name, err) } d.SetId(r.Id) err = setTags(cs, d, "network") if err != nil { return fmt.Errorf("Error setting tags: %s", err) } return resourceCloudStackNetworkRead(d, meta) } func resourceCloudStackNetworkRead(d *schema.ResourceData, meta interface{}) error { cs := meta.(*cloudstack.CloudStackClient) // Get the virtual machine details n, count, err := cs.Network.GetNetworkByID(d.Id()) if err != nil { if count == 0 { log.Printf( "[DEBUG] Network %s does no longer exist", d.Get("name").(string)) d.SetId("") return nil } return err } d.Set("name", n.Name) d.Set("display_text", n.Displaytext) d.Set("cidr", n.Cidr) d.Set("gateway", n.Gateway) _, vpcID := d.GetOk("vpc_id") _, vpc := d.GetOk("vpc") if vpcID || vpc { d.Set("vpc_id", n.Vpcid) } _, aclID := d.GetOk("acl_id") _, acl := d.GetOk("aclid") if aclID || acl { d.Set("acl_id", n.Aclid) } // Read the tags and store them in a map tags := make(map[string]interface{}) for item := range n.Tags { tags[n.Tags[item].Key] = n.Tags[item].Value } d.Set("tags", tags) setValueOrID(d, "network_offering", n.Networkofferingname, n.Networkofferingid) setValueOrID(d, "project", n.Project, n.Projectid) setValueOrID(d, "zone", n.Zonename, n.Zoneid) return nil } func resourceCloudStackNetworkUpdate(d *schema.ResourceData, meta interface{}) error { cs := meta.(*cloudstack.CloudStackClient) name := d.Get("name").(string) // Create a new parameter struct p := cs.Network.NewUpdateNetworkParams(d.Id()) // Check if the name or display text is changed if d.HasChange("name") || d.HasChange("display_text") { p.SetName(name) // Compute/set the display text displaytext := d.Get("display_text").(string) if displaytext == "" { displaytext = name } p.SetDisplaytext(displaytext) } // Check if the cidr is changed if d.HasChange("cidr") { p.SetGuestvmcidr(d.Get("cidr").(string)) } // Check if the network offering is changed if d.HasChange("network_offering") { // Retrieve the network_offering ID networkofferingid, e := retrieveID(cs, "network_offering", d.Get("network_offering").(string)) if e != nil { return e.Error() } // Set the new network offering p.SetNetworkofferingid(networkofferingid) } // Update the network _, err := cs.Network.UpdateNetwork(p) if err != nil { return fmt.Errorf( "Error updating network %s: %s", name, err) } // Update tags if they have changed if d.HasChange("tags") { err = setTags(cs, d, "network") if err != nil { return fmt.Errorf("Error updating tags: %s", err) } } return resourceCloudStackNetworkRead(d, meta) } func resourceCloudStackNetworkDelete(d *schema.ResourceData, meta interface{}) error { cs := meta.(*cloudstack.CloudStackClient) // Create a new parameter struct p := cs.Network.NewDeleteNetworkParams(d.Id()) // Delete the network _, err := cs.Network.DeleteNetwork(p) if err != nil { // This is a very poor way to be told the ID does no longer exist :( if strings.Contains(err.Error(), fmt.Sprintf( "Invalid parameter id value=%s due to incorrect long value format, "+ "or entity does not exist", d.Id())) { return nil } return fmt.Errorf("Error deleting network %s: %s", d.Get("name").(string), err) } return nil } func parseCIDR(d *schema.ResourceData) (map[string]string, error) { m := make(map[string]string, 4) cidr := d.Get("cidr").(string) ip, ipnet, err := net.ParseCIDR(cidr) if err != nil { return nil, fmt.Errorf("Unable to parse cidr %s: %s", cidr, err) } msk := ipnet.Mask sub := ip.Mask(msk) m["netmask"] = fmt.Sprintf("%d.%d.%d.%d", msk[0], msk[1], msk[2], msk[3]) if gateway, ok := d.GetOk("gateway"); ok { m["gateway"] = gateway.(string) } else { m["gateway"] = fmt.Sprintf("%d.%d.%d.%d", sub[0], sub[1], sub[2], sub[3]+1) } if startip, ok := d.GetOk("startip"); ok { m["startip"] = startip.(string) } else { m["startip"] = fmt.Sprintf("%d.%d.%d.%d", sub[0], sub[1], sub[2], sub[3]+2) } if endip, ok := d.GetOk("endip"); ok { m["endip"] = endip.(string) } else { m["endip"] = fmt.Sprintf("%d.%d.%d.%d", sub[0]+(0xff-msk[0]), sub[1]+(0xff-msk[1]), sub[2]+(0xff-msk[2]), sub[3]+(0xff-msk[3]-1)) } return m, nil }
builtin/providers/cloudstack/resource_cloudstack_network.go
0
https://github.com/hashicorp/terraform/commit/62a744a45e1ce80211ff134c195a8b7cb70949af
[ 0.0023844356182962656, 0.0003183287917636335, 0.0001638457615626976, 0.0001716473780106753, 0.00042986980406567454 ]
{ "id": 1, "code_window": [ "\tlog.Printf(\"[DEBUG] Waiting for OpenStack LB member (%s) to become available.\", m.ID)\n", "\n", "\tstateConf := &resource.StateChangeConf{\n", "\t\tPending: []string{\"PENDING_CREATE\"},\n", "\t\tTarget: []string{\"ACTIVE\"},\n", "\t\tRefresh: waitForLBMemberActive(networkingClient, m.ID),\n", "\t\tTimeout: 2 * time.Minute,\n", "\t\tDelay: 5 * time.Second,\n", "\t\tMinTimeout: 3 * time.Second,\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tTarget: []string{\"ACTIVE\", \"INACTIVE\"},\n" ], "file_path": "builtin/providers/openstack/resource_openstack_lb_member_v1.go", "type": "replace", "edit_start_line_idx": 88 }
// mksyscall.pl syscall_bsd.go syscall_darwin.go syscall_darwin_amd64.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,darwin package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { _p0 = unsafe.Pointer(&mib[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe() (r int, w int, err error) { r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) r = int(r0) w = int(r1) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kill(pid int, signum int, posix int) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), uintptr(posix)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exchangedata(path1 string, path2 string, options int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path1) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(path2) if err != nil { return } _, _, e1 := Syscall(SYS_EXCHANGEDATA, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options)) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETDIRENTRIES64, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdtablesize() (size int) { r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0) size = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) pgrp = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { r0, _, _ := RawSyscall(SYS_ISSETUGID, 0, 0, 0) tainted = bool(r0 != 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) use(unsafe.Pointer(_p0)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) newoffset = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { _, _, e1 := Syscall(SYS_SETEGID, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(name) if err != nil { return } _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setprivexec(flag int) (err error) { _, _, e1 := Syscall(SYS_SETPRIVEXEC, uintptr(flag), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Undelete(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func gettimeofday(tp *Timeval) (sec int64, usec int32, err error) { r0, r1, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) sec = int64(r0) usec = int32(r1) if e1 != 0 { err = errnoErr(e1) } return }
vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go
0
https://github.com/hashicorp/terraform/commit/62a744a45e1ce80211ff134c195a8b7cb70949af
[ 0.0012643014779314399, 0.00018667943368200213, 0.0001607178128324449, 0.000168970029335469, 0.0001134326375904493 ]
{ "id": 2, "code_window": [ "\t}\n", "\n", "\td.SetId(m.ID)\n", "\n", "\treturn resourceLBMemberV1Read(d, meta)\n", "}\n", "\n", "func resourceLBMemberV1Read(d *schema.ResourceData, meta interface{}) error {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t// Due to the way Gophercloud is currently set up, AdminStateUp must be set post-create\n", "\tupdateOpts := members.UpdateOpts{\n", "\t\tAdminStateUp: d.Get(\"admin_state_up\").(bool),\n", "\t}\n", "\n", "\tlog.Printf(\"[DEBUG] OpenStack LB Member Update Options: %#v\", createOpts)\n", "\tm, err = members.Update(networkingClient, m.ID, updateOpts).Extract()\n", "\tif err != nil {\n", "\t\treturn fmt.Errorf(\"Error updating OpenStack LB member: %s\", err)\n", "\t}\n", "\n" ], "file_path": "builtin/providers/openstack/resource_openstack_lb_member_v1.go", "type": "add", "edit_start_line_idx": 102 }
package openstack import ( "fmt" "log" "time" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" "github.com/rackspace/gophercloud" "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/members" ) func resourceLBMemberV1() *schema.Resource { return &schema.Resource{ Create: resourceLBMemberV1Create, Read: resourceLBMemberV1Read, Update: resourceLBMemberV1Update, Delete: resourceLBMemberV1Delete, Schema: map[string]*schema.Schema{ "region": &schema.Schema{ Type: schema.TypeString, Required: true, ForceNew: true, DefaultFunc: schema.EnvDefaultFunc("OS_REGION_NAME", ""), }, "tenant_id": &schema.Schema{ Type: schema.TypeString, Optional: true, ForceNew: true, }, "pool_id": &schema.Schema{ Type: schema.TypeString, Required: true, ForceNew: true, }, "address": &schema.Schema{ Type: schema.TypeString, Required: true, ForceNew: true, }, "port": &schema.Schema{ Type: schema.TypeInt, Required: true, ForceNew: true, }, "weight": &schema.Schema{ Type: schema.TypeInt, Optional: true, Computed: true, }, "admin_state_up": &schema.Schema{ Type: schema.TypeBool, Optional: true, ForceNew: false, Computed: true, }, }, } } func resourceLBMemberV1Create(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) networkingClient, err := config.networkingV2Client(d.Get("region").(string)) if err != nil { return fmt.Errorf("Error creating OpenStack networking client: %s", err) } createOpts := members.CreateOpts{ TenantID: d.Get("tenant_id").(string), PoolID: d.Get("pool_id").(string), Address: d.Get("address").(string), ProtocolPort: d.Get("port").(int), } log.Printf("[DEBUG] Create Options: %#v", createOpts) m, err := members.Create(networkingClient, createOpts).Extract() if err != nil { return fmt.Errorf("Error creating OpenStack LB member: %s", err) } log.Printf("[INFO] LB member ID: %s", m.ID) log.Printf("[DEBUG] Waiting for OpenStack LB member (%s) to become available.", m.ID) stateConf := &resource.StateChangeConf{ Pending: []string{"PENDING_CREATE"}, Target: []string{"ACTIVE"}, Refresh: waitForLBMemberActive(networkingClient, m.ID), Timeout: 2 * time.Minute, Delay: 5 * time.Second, MinTimeout: 3 * time.Second, } _, err = stateConf.WaitForState() if err != nil { return err } d.SetId(m.ID) return resourceLBMemberV1Read(d, meta) } func resourceLBMemberV1Read(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) networkingClient, err := config.networkingV2Client(d.Get("region").(string)) if err != nil { return fmt.Errorf("Error creating OpenStack networking client: %s", err) } m, err := members.Get(networkingClient, d.Id()).Extract() if err != nil { return CheckDeleted(d, err, "LB member") } log.Printf("[DEBUG] Retreived OpenStack LB member %s: %+v", d.Id(), m) d.Set("weight", m.Weight) d.Set("admin_state_up", m.AdminStateUp) return nil } func resourceLBMemberV1Update(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) networkingClient, err := config.networkingV2Client(d.Get("region").(string)) if err != nil { return fmt.Errorf("Error creating OpenStack networking client: %s", err) } var updateOpts members.UpdateOpts if d.HasChange("admin_state_up") { asu := d.Get("admin_state_up").(bool) updateOpts.AdminStateUp = asu } log.Printf("[DEBUG] Updating LB member %s with options: %+v", d.Id(), updateOpts) _, err = members.Update(networkingClient, d.Id(), updateOpts).Extract() if err != nil { return fmt.Errorf("Error updating OpenStack LB member: %s", err) } return resourceLBMemberV1Read(d, meta) } func resourceLBMemberV1Delete(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) networkingClient, err := config.networkingV2Client(d.Get("region").(string)) if err != nil { return fmt.Errorf("Error creating OpenStack networking client: %s", err) } err = members.Delete(networkingClient, d.Id()).ExtractErr() if err != nil { CheckDeleted(d, err, "LB member") } stateConf := &resource.StateChangeConf{ Pending: []string{"ACTIVE", "PENDING_DELETE"}, Target: []string{"DELETED"}, Refresh: waitForLBMemberDelete(networkingClient, d.Id()), Timeout: 2 * time.Minute, Delay: 5 * time.Second, MinTimeout: 3 * time.Second, } _, err = stateConf.WaitForState() if err != nil { return fmt.Errorf("Error deleting OpenStack LB member: %s", err) } d.SetId("") return nil } func waitForLBMemberActive(networkingClient *gophercloud.ServiceClient, memberId string) resource.StateRefreshFunc { return func() (interface{}, string, error) { m, err := members.Get(networkingClient, memberId).Extract() if err != nil { return nil, "", err } log.Printf("[DEBUG] OpenStack LB member: %+v", m) if m.Status == "ACTIVE" { return m, "ACTIVE", nil } return m, m.Status, nil } } func waitForLBMemberDelete(networkingClient *gophercloud.ServiceClient, memberId string) resource.StateRefreshFunc { return func() (interface{}, string, error) { log.Printf("[DEBUG] Attempting to delete OpenStack LB member %s", memberId) m, err := members.Get(networkingClient, memberId).Extract() if err != nil { errCode, ok := err.(*gophercloud.UnexpectedResponseCodeError) if !ok { return m, "ACTIVE", err } if errCode.Actual == 404 { log.Printf("[DEBUG] Successfully deleted OpenStack LB member %s", memberId) return m, "DELETED", nil } } log.Printf("[DEBUG] OpenStack LB member %s still active.", memberId) return m, "ACTIVE", nil } }
builtin/providers/openstack/resource_openstack_lb_member_v1.go
1
https://github.com/hashicorp/terraform/commit/62a744a45e1ce80211ff134c195a8b7cb70949af
[ 0.9986252784729004, 0.14374133944511414, 0.00016764027532190084, 0.0013611402828246355, 0.3376738131046295 ]
{ "id": 2, "code_window": [ "\t}\n", "\n", "\td.SetId(m.ID)\n", "\n", "\treturn resourceLBMemberV1Read(d, meta)\n", "}\n", "\n", "func resourceLBMemberV1Read(d *schema.ResourceData, meta interface{}) error {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t// Due to the way Gophercloud is currently set up, AdminStateUp must be set post-create\n", "\tupdateOpts := members.UpdateOpts{\n", "\t\tAdminStateUp: d.Get(\"admin_state_up\").(bool),\n", "\t}\n", "\n", "\tlog.Printf(\"[DEBUG] OpenStack LB Member Update Options: %#v\", createOpts)\n", "\tm, err = members.Update(networkingClient, m.ID, updateOpts).Extract()\n", "\tif err != nil {\n", "\t\treturn fmt.Errorf(\"Error updating OpenStack LB member: %s\", err)\n", "\t}\n", "\n" ], "file_path": "builtin/providers/openstack/resource_openstack_lb_member_v1.go", "type": "add", "edit_start_line_idx": 102 }
# Hello
config/module/test-fixtures/basic-parent/c/c.tf
0
https://github.com/hashicorp/terraform/commit/62a744a45e1ce80211ff134c195a8b7cb70949af
[ 0.00017166874022223055, 0.00017166874022223055, 0.00017166874022223055, 0.00017166874022223055, 0 ]
{ "id": 2, "code_window": [ "\t}\n", "\n", "\td.SetId(m.ID)\n", "\n", "\treturn resourceLBMemberV1Read(d, meta)\n", "}\n", "\n", "func resourceLBMemberV1Read(d *schema.ResourceData, meta interface{}) error {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t// Due to the way Gophercloud is currently set up, AdminStateUp must be set post-create\n", "\tupdateOpts := members.UpdateOpts{\n", "\t\tAdminStateUp: d.Get(\"admin_state_up\").(bool),\n", "\t}\n", "\n", "\tlog.Printf(\"[DEBUG] OpenStack LB Member Update Options: %#v\", createOpts)\n", "\tm, err = members.Update(networkingClient, m.ID, updateOpts).Extract()\n", "\tif err != nil {\n", "\t\treturn fmt.Errorf(\"Error updating OpenStack LB member: %s\", err)\n", "\t}\n", "\n" ], "file_path": "builtin/providers/openstack/resource_openstack_lb_member_v1.go", "type": "add", "edit_start_line_idx": 102 }
package main
builtin/bins/provider-powerdns/main_test.go
0
https://github.com/hashicorp/terraform/commit/62a744a45e1ce80211ff134c195a8b7cb70949af
[ 0.00017295422730967402, 0.00017295422730967402, 0.00017295422730967402, 0.00017295422730967402, 0 ]
{ "id": 2, "code_window": [ "\t}\n", "\n", "\td.SetId(m.ID)\n", "\n", "\treturn resourceLBMemberV1Read(d, meta)\n", "}\n", "\n", "func resourceLBMemberV1Read(d *schema.ResourceData, meta interface{}) error {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t// Due to the way Gophercloud is currently set up, AdminStateUp must be set post-create\n", "\tupdateOpts := members.UpdateOpts{\n", "\t\tAdminStateUp: d.Get(\"admin_state_up\").(bool),\n", "\t}\n", "\n", "\tlog.Printf(\"[DEBUG] OpenStack LB Member Update Options: %#v\", createOpts)\n", "\tm, err = members.Update(networkingClient, m.ID, updateOpts).Extract()\n", "\tif err != nil {\n", "\t\treturn fmt.Errorf(\"Error updating OpenStack LB member: %s\", err)\n", "\t}\n", "\n" ], "file_path": "builtin/providers/openstack/resource_openstack_lb_member_v1.go", "type": "add", "edit_start_line_idx": 102 }
sudo: false language: go go: - 1.5.1 branches: only: - master script: make updatedeps test
vendor/github.com/hashicorp/go-retryablehttp/.travis.yml
0
https://github.com/hashicorp/terraform/commit/62a744a45e1ce80211ff134c195a8b7cb70949af
[ 0.00017551063501741737, 0.0001723439054330811, 0.0001691771758487448, 0.0001723439054330811, 0.000003166729584336281 ]