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": 2, "code_window": [ "\t\t\t\tArgs: \"\",\n", "\t\t\t},\n", "\t\t\tLog: LogConfig{\n", "\t\t\t\tOrder: \"topo-order\",\n", "\t\t\t\tShowGraph: \"when-maximised\",\n", "\t\t\t},\n", "\t\t\tSkipHookPrefix: \"WIP\",\n", "\t\t\tAutoFetch: true,\n", "\t\t\tAutoRefresh: true,\n", "\t\t\tBranchLogCmd: \"git log --graph --color=always --abbrev-commit --decorate --date=relative --pretty=medium {{branchName}} --\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tShowWholeGraph: false,\n" ], "file_path": "pkg/config/user_config.go", "type": "add", "edit_start_line_idx": 387 }
# User Config Default path for the config file: - Linux: `~/.config/lazygit/config.yml` - MacOS: `~/Library/Application Support/lazygit/config.yml` - Windows: `%APPDATA%\lazygit\config.yml` For old installations (slightly embarrassing: I didn't realise at the time that you didn't need to supply a vendor name to the path so I just used my name): - Linux: `~/.config/jesseduffield/lazygit/config.yml` - MacOS: `~/Library/Application Support/jesseduffield/lazygit/config.yml` - Windows: `%APPDATA%\jesseduffield\lazygit\config.yml` ## Default ```yaml gui: # stuff relating to the UI scrollHeight: 2 # how many lines you scroll by scrollPastBottom: true # enable scrolling past the bottom sidePanelWidth: 0.3333 # number from 0 to 1 expandFocusedSidePanel: false mainPanelSplitMode: 'flexible' # one of 'horizontal' | 'flexible' | 'vertical' language: 'auto' # one of 'auto' | 'en' | 'zh' | 'pl' | 'nl' | 'ja' timeFormat: '02 Jan 06 15:04 MST' # https://pkg.go.dev/time#Time.Format theme: lightTheme: false # For terminals with a light background activeBorderColor: - green - bold inactiveBorderColor: - white optionsTextColor: - blue selectedLineBgColor: - blue # set to `default` to have no background colour selectedRangeBgColor: - blue cherryPickedCommitBgColor: - cyan cherryPickedCommitFgColor: - blue unstagedChangesColor: - red commitLength: show: true mouseEvents: true skipUnstageLineWarning: false skipStashWarning: false showFileTree: true # for rendering changes files in a tree format showListFooter: true # for seeing the '5 of 20' message in list panels showRandomTip: true showBottomLine: true # for hiding the bottom information line (unless it has important information to tell you) showCommandLog: true showIcons: false commandLogSize: 8 splitDiff: 'auto' # one of 'auto' | 'always' git: paging: colorArg: always useConfig: false commit: signOff: false merging: # only applicable to unix users manualCommit: false # extra args passed to `git merge`, e.g. --no-ff args: '' log: # one of date-order, author-date-order, topo-order. # topo-order makes it easier to read the git log graph, but commits may not # appear chronologically. See https://git-scm.com/docs/git-log#_commit_ordering order: 'topo-order' # one of always, never, when-maximised # this determines whether the git graph is rendered in the commits panel showGraph: 'when-maximised' skipHookPrefix: WIP autoFetch: true autoRefresh: true branchLogCmd: 'git log --graph --color=always --abbrev-commit --decorate --date=relative --pretty=medium {{branchName}} --' allBranchesLogCmd: 'git log --graph --all --color=always --abbrev-commit --decorate --date=relative --pretty=medium' overrideGpg: false # prevents lazygit from spawning a separate process when using GPG disableForcePushing: false parseEmoji: false diffContextSize: 3 # how many lines of context are shown around a change in diffs os: editCommand: '' # see 'Configuring File Editing' section editCommandTemplate: '' openCommand: '' refresher: refreshInterval: 10 # File/submodule refresh interval in seconds. Auto-refresh can be disabled via option 'git.autoRefresh'. fetchInterval: 60 # Re-fetch interval in seconds. Auto-fetch can be disabled via option 'git.autoFetch'. update: method: prompt # can be: prompt | background | never days: 14 # how often an update is checked for reporting: 'undetermined' # one of: 'on' | 'off' | 'undetermined' confirmOnQuit: false # determines whether hitting 'esc' will quit the application when there is nothing to cancel/close quitOnTopLevelReturn: false disableStartupPopups: false notARepository: 'prompt' # one of: 'prompt' | 'create' | 'skip' promptToReturnFromSubprocess: true # display confirmation when subprocess terminates keybinding: universal: quit: 'q' quit-alt1: '<c-c>' # alternative/alias of quit return: '<esc>' # return to previous menu, will quit if there's nowhere to return quitWithoutChangingDirectory: 'Q' togglePanel: '<tab>' # goto the next panel prevItem: '<up>' # go one line up nextItem: '<down>' # go one line down prevItem-alt: 'k' # go one line up nextItem-alt: 'j' # go one line down prevPage: ',' # go to next page in list nextPage: '.' # go to previous page in list gotoTop: '<' # go to top of list gotoBottom: '>' # go to bottom of list scrollLeft: 'H' # scroll left within list view scrollRight: 'L' # scroll right within list view prevBlock: '<left>' # goto the previous block / panel nextBlock: '<right>' # goto the next block / panel prevBlock-alt: 'h' # goto the previous block / panel nextBlock-alt: 'l' # goto the next block / panel jumpToBlock: ['1', '2', '3', '4', '5'] # goto the Nth block / panel nextMatch: 'n' prevMatch: 'N' optionMenu: 'x' # show help menu optionMenu-alt1: '?' # show help menu select: '<space>' goInto: '<enter>' openRecentRepos: '<c-r>' confirm: '<enter>' confirm-alt1: 'y' remove: 'd' new: 'n' edit: 'e' openFile: 'o' scrollUpMain: '<pgup>' # main panel scroll up scrollDownMain: '<pgdown>' # main panel scroll down scrollUpMain-alt1: 'K' # main panel scroll up scrollDownMain-alt1: 'J' # main panel scroll down scrollUpMain-alt2: '<c-u>' # main panel scroll up scrollDownMain-alt2: '<c-d>' # main panel scroll down executeCustomCommand: ':' createRebaseOptionsMenu: 'm' pushFiles: 'P' pullFiles: 'p' refresh: 'R' createPatchOptionsMenu: '<c-p>' nextTab: ']' prevTab: '[' nextScreenMode: '+' prevScreenMode: '_' undo: 'z' redo: '<c-z>' filteringMenu: '<c-s>' diffingMenu: 'W' diffingMenu-alt: '<c-e>' # deprecated copyToClipboard: '<c-o>' submitEditorText: '<enter>' appendNewline: '<a-enter>' extrasMenu: '@' toggleWhitespaceInDiffView: '<c-w>' increaseContextInDiffView: '}' decreaseContextInDiffView: '{' status: checkForUpdate: 'u' recentRepos: '<enter>' files: commitChanges: 'c' commitChangesWithoutHook: 'w' # commit changes without pre-commit hook amendLastCommit: 'A' commitChangesWithEditor: 'C' ignoreFile: 'i' refreshFiles: 'r' stashAllChanges: 's' viewStashOptions: 'S' toggleStagedAll: 'a' # stage/unstage all viewResetOptions: 'D' fetch: 'f' toggleTreeView: '`' branches: createPullRequest: 'o' viewPullRequestOptions: 'O' checkoutBranchByName: 'c' forceCheckoutBranch: 'F' rebaseBranch: 'r' mergeIntoCurrentBranch: 'M' viewGitFlowOptions: 'i' fastForward: 'f' # fast-forward this branch from its upstream pushTag: 'P' setUpstream: 'u' # set as upstream of checked-out branch fetchRemote: 'f' commits: squashDown: 's' renameCommit: 'r' renameCommitWithEditor: 'R' viewResetOptions: 'g' markCommitAsFixup: 'f' createFixupCommit: 'F' # create fixup commit for this commit squashAboveCommits: 'S' moveDownCommit: '<c-j>' # move commit down one moveUpCommit: '<c-k>' # move commit up one amendToCommit: 'A' pickCommit: 'p' # pick commit (when mid-rebase) revertCommit: 't' cherryPickCopy: 'c' cherryPickCopyRange: 'C' pasteCommits: 'v' tagCommit: 'T' checkoutCommit: '<space>' resetCherryPick: '<c-R>' copyCommitMessageToClipboard: '<c-y>' openLogMenu: '<c-l>' viewBisectOptions: 'b' stash: popStash: 'g' commitFiles: checkoutCommitFile: 'c' main: toggleDragSelect: 'v' toggleDragSelect-alt: 'V' toggleSelectHunk: 'a' pickBothHunks: 'b' submodules: init: 'i' update: 'u' bulkMenu: 'b' ``` ## Platform Defaults ### Windows ```yaml os: openCommand: 'start "" {{filename}}' ``` ### Linux ```yaml os: openCommand: 'xdg-open {{filename}} >/dev/null' ``` ### OSX ```yaml os: openCommand: 'open {{filename}}' ``` ### Configuring File Editing Lazygit will edit a file with the first set editor in the following: 1. config.yaml ```yaml os: editCommand: 'vim' # as an example ``` 2. \$(git config core.editor) 3. \$GIT_EDITOR 4. \$VISUAL 5. \$EDITOR 6. \$(which vi) Lazygit will log an error if none of these options are set. You can specify a line number you are currently at when in the line-by-line mode. ```yaml os: editCommand: 'vim' editCommandTemplate: '{{editor}} +{{line}} -- {{filename}}' ``` or ```yaml os: editCommand: 'code' editCommandTemplate: '{{editor}} --goto -- {{filename}}:{{line}}' ``` `{{editor}}` in `editCommandTemplate` is replaced with the value of `editCommand`. ### Overriding default config file location To override the default config directory, use `$CONFIG_DIR="~/.config/lazygit"`. This directory contains the config file in addition to some other files lazygit uses to keep track of state across sessions. To override the individual config file used, use the `--use-config-file` arg or the `LG_CONFIG_FILE` env var. If you want to merge a specific config file into a more general config file, perhaps for the sake of setting some theme-specific options, you can supply a list of comma-separated config file paths, like so: ```sh lazygit --use-config-file=~/.base_lg_conf,~/.light_theme_lg_conf or LG_CONFIG_FILE="~/.base_lg_conf,~/.light_theme_lg_conf" lazygit ``` ### Recommended Config Values for users of VSCode ```yaml os: openCommand: 'code -rg {{filename}}' ``` ## Color Attributes For color attributes you can choose an array of attributes (with max one color attribute) The available attributes are: **Colors** - black - red - green - yellow - blue - magenta - cyan - white - '#ff00ff' **Modifiers** - bold - default - reverse # useful for high-contrast - underline ## Light terminal theme If you have issues with a light terminal theme where you can't read / see the text add these settings ```yaml gui: theme: lightTheme: true activeBorderColor: - black - bold inactiveBorderColor: - black selectedLineBgColor: - default ``` ## Highlighting the selected line If you don't like the default behaviour of highlighting the selected line with a blue background, you can use the `selectedLineBgColor` and `selectedRangeBgColor` keys to customise the behaviour. If you just want to embolden the selected line (this was the original default), you can do the following: ```yaml gui: theme: selectedLineBgColor: - default selectedRangeBgColor: - default ``` You can also use the reverse attribute like so: ```yaml gui: theme: selectedLineBgColor: - reverse selectedRangeBgColor: - reverse ``` ## Custom Author Color Lazygit will assign a random color for every commit author in the commits pane by default. You can customize the color in case you're not happy with the randomly assigned one: ```yaml gui: authorColors: 'John Smith': 'red' # use red for John Smith 'Alan Smithee': '#00ff00' # use green for Alan Smithee ``` You can use wildcard to set a unified color in case your are lazy to customize the color for every author or you just want a single color for all/other authors: ```yaml gui: authorColors: # use red for John Smith 'John Smith': 'red' # use blue for other authors '*': '#0000ff' ``` ## Custom Branch Color You can customize the color of branches based on the branch prefix: ```yaml gui: branchColors: 'docs': '#11aaff' # use a light blue for branches beginning with 'docs/' ``` ## Example Coloring ![border example](../../assets/colored-border-example.png) ## Display Nerd Fonts Icons If you are using [Nerd Fonts](https://www.nerdfonts.com), you can display icons. ```yaml gui: showIcons: true ``` ## Keybindings For all possible keybinding options, check [Custom_Keybindings.md](https://github.com/jesseduffield/lazygit/blob/master/docs/keybindings/Custom_Keybindings.md) ### Example Keybindings For Colemak Users ```yaml keybinding: universal: prevItem-alt: 'u' nextItem-alt: 'e' prevBlock-alt: 'n' nextBlock-alt: 'i' nextMatch: '=' prevMatch: '-' new: 'k' edit: 'o' openFile: 'O' scrollUpMain-alt1: 'U' scrollDownMain-alt1: 'E' scrollUpMain-alt2: '<c-u>' scrollDownMain-alt2: '<c-e>' undo: 'l' redo: '<c-r>' diffingMenu: 'M' filteringMenu: '<c-f>' files: ignoreFile: 'I' commits: moveDownCommit: '<c-e>' moveUpCommit: '<c-u>' branches: viewGitFlowOptions: 'I' setUpstream: 'U' ``` ## Custom pull request URLs Some git provider setups (e.g. on-premises GitLab) can have distinct URLs for git-related calls and the web interface/API itself. To work with those, Lazygit needs to know where it needs to create the pull request. You can do so on your `config.yml` file using the following syntax: ```yaml services: '<gitDomain>': '<provider>:<webDomain>' ``` Where: - `gitDomain` stands for the domain used by git itself (i.e. the one present on clone URLs), e.g. `git.work.com` - `provider` is one of `github`, `bitbucket`, `bitbucketServer`, `azuredevops` or `gitlab` - `webDomain` is the URL where your git service exposes a web interface and APIs, e.g. `gitservice.work.com` ## Predefined commit message prefix In situations where certain naming pattern is used for branches and commits, pattern can be used to populate commit message with prefix that is parsed from the branch name. Example: - Branch name: feature/AB-123 - Commit message: [AB-123] Adding feature ```yaml git: commitPrefixes: my_project: # This is repository folder name pattern: "^\\w+\\/(\\w+-\\w+).*" replace: '[$1] ' ``` ## Custom git log command You can override the `git log` command that's used to render the log of the selected branch like so: ``` git: branchLogCmd: "git log --graph --color=always --abbrev-commit --decorate --date=relative --pretty=medium --oneline {{branchName}} --" ``` Result: ![](https://i.imgur.com/Nibq35B.png) ## Launching not in a repository behaviour By default, when launching lazygit from a directory that is not a repository, you will be prompted to choose if you would like to initialize a repo. You can override this behaviour in the config with one of the following: ```yaml # for default prompting behaviour notARepository: 'prompt' ``` ```yaml # to skip and initialize a new repo notARepository: 'create' ``` ```yaml # to skip without creating a new repo notARepository: 'skip' ```
docs/Config.md
1
https://github.com/jesseduffield/lazygit/commit/666180cfd02f7ff69faa7425caa5eef358955827
[ 0.006660872139036655, 0.0003942014300264418, 0.0001627956808079034, 0.00016906674136407673, 0.0009632192086428404 ]
{ "id": 2, "code_window": [ "\t\t\t\tArgs: \"\",\n", "\t\t\t},\n", "\t\t\tLog: LogConfig{\n", "\t\t\t\tOrder: \"topo-order\",\n", "\t\t\t\tShowGraph: \"when-maximised\",\n", "\t\t\t},\n", "\t\t\tSkipHookPrefix: \"WIP\",\n", "\t\t\tAutoFetch: true,\n", "\t\t\tAutoRefresh: true,\n", "\t\t\tBranchLogCmd: \"git log --graph --color=always --abbrev-commit --decorate --date=relative --pretty=medium {{branchName}} --\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tShowWholeGraph: false,\n" ], "file_path": "pkg/config/user_config.go", "type": "add", "edit_start_line_idx": 387 }
package oscommands import ( "github.com/jesseduffield/lazygit/pkg/common" "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/utils" ) // NewDummyOSCommand creates a new dummy OSCommand for testing func NewDummyOSCommand() *OSCommand { osCmd := NewOSCommand(utils.NewDummyCommon(), config.NewDummyAppConfig(), dummyPlatform, NewNullGuiIO(utils.NewDummyLog())) return osCmd } type OSCommandDeps struct { Common *common.Common Platform *Platform GetenvFn func(string) string RemoveFileFn func(string) error Cmd *CmdObjBuilder } func NewDummyOSCommandWithDeps(deps OSCommandDeps) *OSCommand { common := deps.Common if common == nil { common = utils.NewDummyCommon() } platform := deps.Platform if platform == nil { platform = dummyPlatform } return &OSCommand{ Common: common, Platform: platform, getenvFn: deps.GetenvFn, removeFileFn: deps.RemoveFileFn, guiIO: NewNullGuiIO(utils.NewDummyLog()), } } func NewDummyCmdObjBuilder(runner ICmdObjRunner) *CmdObjBuilder { return &CmdObjBuilder{ runner: runner, platform: dummyPlatform, } } var dummyPlatform = &Platform{ OS: "darwin", Shell: "bash", ShellArg: "-c", OpenCommand: "open {{filename}}", OpenLinkCommand: "open {{link}}", } func NewDummyOSCommandWithRunner(runner *FakeCmdObjRunner) *OSCommand { osCommand := NewOSCommand(utils.NewDummyCommon(), config.NewDummyAppConfig(), dummyPlatform, NewNullGuiIO(utils.NewDummyLog())) osCommand.Cmd = NewDummyCmdObjBuilder(runner) return osCommand }
pkg/commands/oscommands/dummies.go
0
https://github.com/jesseduffield/lazygit/commit/666180cfd02f7ff69faa7425caa5eef358955827
[ 0.001443934626877308, 0.00041987717850133777, 0.00016510873683728278, 0.00019294310186523944, 0.00043534798896871507 ]
{ "id": 2, "code_window": [ "\t\t\t\tArgs: \"\",\n", "\t\t\t},\n", "\t\t\tLog: LogConfig{\n", "\t\t\t\tOrder: \"topo-order\",\n", "\t\t\t\tShowGraph: \"when-maximised\",\n", "\t\t\t},\n", "\t\t\tSkipHookPrefix: \"WIP\",\n", "\t\t\tAutoFetch: true,\n", "\t\t\tAutoRefresh: true,\n", "\t\t\tBranchLogCmd: \"git log --graph --color=always --abbrev-commit --decorate --date=relative --pretty=medium {{branchName}} --\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tShowWholeGraph: false,\n" ], "file_path": "pkg/config/user_config.go", "type": "add", "edit_start_line_idx": 387 }
package config import ( yaml "github.com/jesseduffield/yaml" ) // NewDummyAppConfig creates a new dummy AppConfig for testing func NewDummyAppConfig() *AppConfig { appConfig := &AppConfig{ Name: "lazygit", Version: "unversioned", Commit: "", BuildDate: "", Debug: false, BuildSource: "", UserConfig: GetDefaultConfig(), AppState: &AppState{}, } _ = yaml.Unmarshal([]byte{}, appConfig.AppState) return appConfig }
pkg/config/dummies.go
0
https://github.com/jesseduffield/lazygit/commit/666180cfd02f7ff69faa7425caa5eef358955827
[ 0.00017178615962620825, 0.00016927358228713274, 0.00016639141540508717, 0.00016964320093393326, 0.0000022178480776346987 ]
{ "id": 2, "code_window": [ "\t\t\t\tArgs: \"\",\n", "\t\t\t},\n", "\t\t\tLog: LogConfig{\n", "\t\t\t\tOrder: \"topo-order\",\n", "\t\t\t\tShowGraph: \"when-maximised\",\n", "\t\t\t},\n", "\t\t\tSkipHookPrefix: \"WIP\",\n", "\t\t\tAutoFetch: true,\n", "\t\t\tAutoRefresh: true,\n", "\t\t\tBranchLogCmd: \"git log --graph --color=always --abbrev-commit --decorate --date=relative --pretty=medium {{branchName}} --\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tShowWholeGraph: false,\n" ], "file_path": "pkg/config/user_config.go", "type": "add", "edit_start_line_idx": 387 }
# git ls-files --others --exclude-from=.git/info/exclude # Lines that start with '#' are comments. # For a project mostly in C, the following would be a good set of # exclude patterns (uncomment them if you want to use them): # *.[oa] # *~ .DS_Store
test/integration/pullRebaseConflict/expected/origin/info/exclude
0
https://github.com/jesseduffield/lazygit/commit/666180cfd02f7ff69faa7425caa5eef358955827
[ 0.00016570885782130063, 0.00016570885782130063, 0.00016570885782130063, 0.00016570885782130063, 0 ]
{ "id": 3, "code_window": [ "\n", "\tc *types.HelperCommon,\n", ") *LocalCommitsContext {\n", "\tviewModel := NewLocalCommitsViewModel(getModel)\n", "\n", "\treturn &LocalCommitsContext{\n", "\t\tLocalCommitsViewModel: viewModel,\n", "\t\tViewportListContextTrait: &ViewportListContextTrait{\n", "\t\t\tListContextTrait: &ListContextTrait{\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tviewModel := NewLocalCommitsViewModel(getModel, c)\n" ], "file_path": "pkg/gui/context/local_commits_context.go", "type": "replace", "edit_start_line_idx": 26 }
package config import ( "time" ) type UserConfig struct { Gui GuiConfig `yaml:"gui"` Git GitConfig `yaml:"git"` Update UpdateConfig `yaml:"update"` Refresher RefresherConfig `yaml:"refresher"` Reporting string `yaml:"reporting"` SplashUpdatesIndex int `yaml:"splashUpdatesIndex"` ConfirmOnQuit bool `yaml:"confirmOnQuit"` QuitOnTopLevelReturn bool `yaml:"quitOnTopLevelReturn"` Keybinding KeybindingConfig `yaml:"keybinding"` // OS determines what defaults are set for opening files and links OS OSConfig `yaml:"os,omitempty"` DisableStartupPopups bool `yaml:"disableStartupPopups"` CustomCommands []CustomCommand `yaml:"customCommands"` Services map[string]string `yaml:"services"` NotARepository string `yaml:"notARepository"` PromptToReturnFromSubprocess bool `yaml:"promptToReturnFromSubprocess"` } type RefresherConfig struct { RefreshInterval int `yaml:"refreshInterval"` FetchInterval int `yaml:"fetchInterval"` } type GuiConfig struct { AuthorColors map[string]string `yaml:"authorColors"` BranchColors map[string]string `yaml:"branchColors"` ScrollHeight int `yaml:"scrollHeight"` ScrollPastBottom bool `yaml:"scrollPastBottom"` MouseEvents bool `yaml:"mouseEvents"` SkipUnstageLineWarning bool `yaml:"skipUnstageLineWarning"` SkipStashWarning bool `yaml:"skipStashWarning"` SidePanelWidth float64 `yaml:"sidePanelWidth"` ExpandFocusedSidePanel bool `yaml:"expandFocusedSidePanel"` MainPanelSplitMode string `yaml:"mainPanelSplitMode"` Language string `yaml:"language"` TimeFormat string `yaml:"timeFormat"` Theme ThemeConfig `yaml:"theme"` CommitLength CommitLengthConfig `yaml:"commitLength"` SkipNoStagedFilesWarning bool `yaml:"skipNoStagedFilesWarning"` ShowListFooter bool `yaml:"showListFooter"` ShowFileTree bool `yaml:"showFileTree"` ShowRandomTip bool `yaml:"showRandomTip"` ShowCommandLog bool `yaml:"showCommandLog"` ShowBottomLine bool `yaml:"showBottomLine"` ShowIcons bool `yaml:"showIcons"` CommandLogSize int `yaml:"commandLogSize"` SplitDiff string `yaml:"splitDiff"` } type ThemeConfig struct { LightTheme bool `yaml:"lightTheme"` ActiveBorderColor []string `yaml:"activeBorderColor"` InactiveBorderColor []string `yaml:"inactiveBorderColor"` OptionsTextColor []string `yaml:"optionsTextColor"` SelectedLineBgColor []string `yaml:"selectedLineBgColor"` SelectedRangeBgColor []string `yaml:"selectedRangeBgColor"` CherryPickedCommitBgColor []string `yaml:"cherryPickedCommitBgColor"` CherryPickedCommitFgColor []string `yaml:"cherryPickedCommitFgColor"` UnstagedChangesColor []string `yaml:"unstagedChangesColor"` } type CommitLengthConfig struct { Show bool `yaml:"show"` } type GitConfig struct { Paging PagingConfig `yaml:"paging"` Commit CommitConfig `yaml:"commit"` Merging MergingConfig `yaml:"merging"` SkipHookPrefix string `yaml:"skipHookPrefix"` AutoFetch bool `yaml:"autoFetch"` AutoRefresh bool `yaml:"autoRefresh"` BranchLogCmd string `yaml:"branchLogCmd"` AllBranchesLogCmd string `yaml:"allBranchesLogCmd"` OverrideGpg bool `yaml:"overrideGpg"` DisableForcePushing bool `yaml:"disableForcePushing"` CommitPrefixes map[string]CommitPrefixConfig `yaml:"commitPrefixes"` // this should really be under 'gui', not 'git' ParseEmoji bool `yaml:"parseEmoji"` Log LogConfig `yaml:"log"` DiffContextSize int `yaml:"diffContextSize"` } type PagingConfig struct { ColorArg string `yaml:"colorArg"` Pager string `yaml:"pager"` UseConfig bool `yaml:"useConfig"` } type CommitConfig struct { SignOff bool `yaml:"signOff"` } type MergingConfig struct { ManualCommit bool `yaml:"manualCommit"` Args string `yaml:"args"` } type LogConfig struct { Order string `yaml:"order"` // one of date-order, author-date-order, topo-order ShowGraph string `yaml:"showGraph"` // one of always, never, when-maximised } type CommitPrefixConfig struct { Pattern string `yaml:"pattern"` Replace string `yaml:"replace"` } type UpdateConfig struct { Method string `yaml:"method"` Days int64 `yaml:"days"` } type KeybindingConfig struct { Universal KeybindingUniversalConfig `yaml:"universal"` Status KeybindingStatusConfig `yaml:"status"` Files KeybindingFilesConfig `yaml:"files"` Branches KeybindingBranchesConfig `yaml:"branches"` Commits KeybindingCommitsConfig `yaml:"commits"` Stash KeybindingStashConfig `yaml:"stash"` CommitFiles KeybindingCommitFilesConfig `yaml:"commitFiles"` Main KeybindingMainConfig `yaml:"main"` Submodules KeybindingSubmodulesConfig `yaml:"submodules"` } // damn looks like we have some inconsistencies here with -alt and -alt1 type KeybindingUniversalConfig struct { Quit string `yaml:"quit"` QuitAlt1 string `yaml:"quit-alt1"` Return string `yaml:"return"` QuitWithoutChangingDirectory string `yaml:"quitWithoutChangingDirectory"` TogglePanel string `yaml:"togglePanel"` PrevItem string `yaml:"prevItem"` NextItem string `yaml:"nextItem"` PrevItemAlt string `yaml:"prevItem-alt"` NextItemAlt string `yaml:"nextItem-alt"` PrevPage string `yaml:"prevPage"` NextPage string `yaml:"nextPage"` ScrollLeft string `yaml:"scrollLeft"` ScrollRight string `yaml:"scrollRight"` GotoTop string `yaml:"gotoTop"` GotoBottom string `yaml:"gotoBottom"` PrevBlock string `yaml:"prevBlock"` NextBlock string `yaml:"nextBlock"` PrevBlockAlt string `yaml:"prevBlock-alt"` NextBlockAlt string `yaml:"nextBlock-alt"` NextBlockAlt2 string `yaml:"nextBlock-alt2"` PrevBlockAlt2 string `yaml:"prevBlock-alt2"` JumpToBlock []string `yaml:"jumpToBlock"` NextMatch string `yaml:"nextMatch"` PrevMatch string `yaml:"prevMatch"` StartSearch string `yaml:"startSearch"` OptionMenu string `yaml:"optionMenu"` OptionMenuAlt1 string `yaml:"optionMenu-alt1"` Select string `yaml:"select"` GoInto string `yaml:"goInto"` Confirm string `yaml:"confirm"` ConfirmAlt1 string `yaml:"confirm-alt1"` Remove string `yaml:"remove"` New string `yaml:"new"` Edit string `yaml:"edit"` OpenFile string `yaml:"openFile"` ScrollUpMain string `yaml:"scrollUpMain"` ScrollDownMain string `yaml:"scrollDownMain"` ScrollUpMainAlt1 string `yaml:"scrollUpMain-alt1"` ScrollDownMainAlt1 string `yaml:"scrollDownMain-alt1"` ScrollUpMainAlt2 string `yaml:"scrollUpMain-alt2"` ScrollDownMainAlt2 string `yaml:"scrollDownMain-alt2"` ExecuteCustomCommand string `yaml:"executeCustomCommand"` CreateRebaseOptionsMenu string `yaml:"createRebaseOptionsMenu"` PushFiles string `yaml:"pushFiles"` PullFiles string `yaml:"pullFiles"` Refresh string `yaml:"refresh"` CreatePatchOptionsMenu string `yaml:"createPatchOptionsMenu"` NextTab string `yaml:"nextTab"` PrevTab string `yaml:"prevTab"` NextScreenMode string `yaml:"nextScreenMode"` PrevScreenMode string `yaml:"prevScreenMode"` Undo string `yaml:"undo"` Redo string `yaml:"redo"` FilteringMenu string `yaml:"filteringMenu"` DiffingMenu string `yaml:"diffingMenu"` DiffingMenuAlt string `yaml:"diffingMenu-alt"` CopyToClipboard string `yaml:"copyToClipboard"` OpenRecentRepos string `yaml:"openRecentRepos"` SubmitEditorText string `yaml:"submitEditorText"` AppendNewline string `yaml:"appendNewline"` ExtrasMenu string `yaml:"extrasMenu"` ToggleWhitespaceInDiffView string `yaml:"toggleWhitespaceInDiffView"` IncreaseContextInDiffView string `yaml:"increaseContextInDiffView"` DecreaseContextInDiffView string `yaml:"decreaseContextInDiffView"` } type KeybindingStatusConfig struct { CheckForUpdate string `yaml:"checkForUpdate"` RecentRepos string `yaml:"recentRepos"` AllBranchesLogGraph string `yaml:"allBranchesLogGraph"` } type KeybindingFilesConfig struct { CommitChanges string `yaml:"commitChanges"` CommitChangesWithoutHook string `yaml:"commitChangesWithoutHook"` AmendLastCommit string `yaml:"amendLastCommit"` CommitChangesWithEditor string `yaml:"commitChangesWithEditor"` IgnoreFile string `yaml:"ignoreFile"` RefreshFiles string `yaml:"refreshFiles"` StashAllChanges string `yaml:"stashAllChanges"` ViewStashOptions string `yaml:"viewStashOptions"` ToggleStagedAll string `yaml:"toggleStagedAll"` ViewResetOptions string `yaml:"viewResetOptions"` Fetch string `yaml:"fetch"` ToggleTreeView string `yaml:"toggleTreeView"` OpenMergeTool string `yaml:"openMergeTool"` OpenStatusFilter string `yaml:"openStatusFilter"` } type KeybindingBranchesConfig struct { CreatePullRequest string `yaml:"createPullRequest"` ViewPullRequestOptions string `yaml:"viewPullRequestOptions"` CopyPullRequestURL string `yaml:"copyPullRequestURL"` CheckoutBranchByName string `yaml:"checkoutBranchByName"` ForceCheckoutBranch string `yaml:"forceCheckoutBranch"` RebaseBranch string `yaml:"rebaseBranch"` RenameBranch string `yaml:"renameBranch"` MergeIntoCurrentBranch string `yaml:"mergeIntoCurrentBranch"` ViewGitFlowOptions string `yaml:"viewGitFlowOptions"` FastForward string `yaml:"fastForward"` PushTag string `yaml:"pushTag"` SetUpstream string `yaml:"setUpstream"` FetchRemote string `yaml:"fetchRemote"` } type KeybindingCommitsConfig struct { SquashDown string `yaml:"squashDown"` RenameCommit string `yaml:"renameCommit"` RenameCommitWithEditor string `yaml:"renameCommitWithEditor"` ViewResetOptions string `yaml:"viewResetOptions"` MarkCommitAsFixup string `yaml:"markCommitAsFixup"` CreateFixupCommit string `yaml:"createFixupCommit"` SquashAboveCommits string `yaml:"squashAboveCommits"` MoveDownCommit string `yaml:"moveDownCommit"` MoveUpCommit string `yaml:"moveUpCommit"` AmendToCommit string `yaml:"amendToCommit"` ResetCommitAuthor string `yaml:"resetCommitAuthor"` PickCommit string `yaml:"pickCommit"` RevertCommit string `yaml:"revertCommit"` CherryPickCopy string `yaml:"cherryPickCopy"` CherryPickCopyRange string `yaml:"cherryPickCopyRange"` PasteCommits string `yaml:"pasteCommits"` TagCommit string `yaml:"tagCommit"` CheckoutCommit string `yaml:"checkoutCommit"` ResetCherryPick string `yaml:"resetCherryPick"` CopyCommitAttributeToClipboard string `yaml:"copyCommitAttributeToClipboard"` OpenLogMenu string `yaml:"openLogMenu"` OpenInBrowser string `yaml:"openInBrowser"` ViewBisectOptions string `yaml:"viewBisectOptions"` } type KeybindingStashConfig struct { PopStash string `yaml:"popStash"` } type KeybindingCommitFilesConfig struct { CheckoutCommitFile string `yaml:"checkoutCommitFile"` } type KeybindingMainConfig struct { ToggleDragSelect string `yaml:"toggleDragSelect"` ToggleDragSelectAlt string `yaml:"toggleDragSelect-alt"` ToggleSelectHunk string `yaml:"toggleSelectHunk"` PickBothHunks string `yaml:"pickBothHunks"` EditSelectHunk string `yaml:"editSelectHunk"` } type KeybindingSubmodulesConfig struct { Init string `yaml:"init"` Update string `yaml:"update"` BulkMenu string `yaml:"bulkMenu"` } // OSConfig contains config on the level of the os type OSConfig struct { // EditCommand is the command for editing a file EditCommand string `yaml:"editCommand,omitempty"` // EditCommandTemplate is the command template for editing a file EditCommandTemplate string `yaml:"editCommandTemplate,omitempty"` // OpenCommand is the command for opening a file OpenCommand string `yaml:"openCommand,omitempty"` // OpenCommand is the command for opening a link OpenLinkCommand string `yaml:"openLinkCommand,omitempty"` } type CustomCommand struct { Key string `yaml:"key"` Context string `yaml:"context"` Command string `yaml:"command"` Subprocess bool `yaml:"subprocess"` Prompts []CustomCommandPrompt `yaml:"prompts"` LoadingText string `yaml:"loadingText"` Description string `yaml:"description"` Stream bool `yaml:"stream"` } type CustomCommandPrompt struct { Type string `yaml:"type"` // one of 'input' and 'menu' Title string `yaml:"title"` // this only apply to prompts InitialValue string `yaml:"initialValue"` // this only applies to menus Options []CustomCommandMenuOption // this only applies to menuFromCommand Command string `yaml:"command"` Filter string `yaml:"filter"` ValueFormat string `yaml:"valueFormat"` LabelFormat string `yaml:"labelFormat"` } type CustomCommandMenuOption struct { Name string `yaml:"name"` Description string `yaml:"description"` Value string `yaml:"value"` } func GetDefaultConfig() *UserConfig { return &UserConfig{ Gui: GuiConfig{ ScrollHeight: 2, ScrollPastBottom: true, MouseEvents: true, SkipUnstageLineWarning: false, SkipStashWarning: false, SidePanelWidth: 0.3333, ExpandFocusedSidePanel: false, MainPanelSplitMode: "flexible", Language: "auto", TimeFormat: time.RFC822, Theme: ThemeConfig{ LightTheme: false, ActiveBorderColor: []string{"green", "bold"}, InactiveBorderColor: []string{"white"}, OptionsTextColor: []string{"blue"}, SelectedLineBgColor: []string{"blue"}, SelectedRangeBgColor: []string{"blue"}, CherryPickedCommitBgColor: []string{"cyan"}, CherryPickedCommitFgColor: []string{"blue"}, UnstagedChangesColor: []string{"red"}, }, CommitLength: CommitLengthConfig{Show: true}, SkipNoStagedFilesWarning: false, ShowListFooter: true, ShowCommandLog: true, ShowBottomLine: true, ShowFileTree: true, ShowRandomTip: true, ShowIcons: false, CommandLogSize: 8, SplitDiff: "auto", }, Git: GitConfig{ Paging: PagingConfig{ ColorArg: "always", Pager: "", UseConfig: false, }, Commit: CommitConfig{ SignOff: false, }, Merging: MergingConfig{ ManualCommit: false, Args: "", }, Log: LogConfig{ Order: "topo-order", ShowGraph: "when-maximised", }, SkipHookPrefix: "WIP", AutoFetch: true, AutoRefresh: true, BranchLogCmd: "git log --graph --color=always --abbrev-commit --decorate --date=relative --pretty=medium {{branchName}} --", AllBranchesLogCmd: "git log --graph --all --color=always --abbrev-commit --decorate --date=relative --pretty=medium", DisableForcePushing: false, CommitPrefixes: map[string]CommitPrefixConfig(nil), ParseEmoji: false, DiffContextSize: 3, }, Refresher: RefresherConfig{ RefreshInterval: 10, FetchInterval: 60, }, Update: UpdateConfig{ Method: "prompt", Days: 14, }, Reporting: "undetermined", SplashUpdatesIndex: 0, ConfirmOnQuit: false, QuitOnTopLevelReturn: false, Keybinding: KeybindingConfig{ Universal: KeybindingUniversalConfig{ Quit: "q", QuitAlt1: "<c-c>", Return: "<esc>", QuitWithoutChangingDirectory: "Q", TogglePanel: "<tab>", PrevItem: "<up>", NextItem: "<down>", PrevItemAlt: "k", NextItemAlt: "j", PrevPage: ",", NextPage: ".", ScrollLeft: "H", ScrollRight: "L", GotoTop: "<", GotoBottom: ">", PrevBlock: "<left>", NextBlock: "<right>", PrevBlockAlt: "h", NextBlockAlt: "l", PrevBlockAlt2: "<backtab>", NextBlockAlt2: "<tab>", JumpToBlock: []string{"1", "2", "3", "4", "5"}, NextMatch: "n", PrevMatch: "N", StartSearch: "/", OptionMenu: "x", OptionMenuAlt1: "?", Select: "<space>", GoInto: "<enter>", Confirm: "<enter>", ConfirmAlt1: "y", Remove: "d", New: "n", Edit: "e", OpenFile: "o", OpenRecentRepos: "<c-r>", ScrollUpMain: "<pgup>", ScrollDownMain: "<pgdown>", ScrollUpMainAlt1: "K", ScrollDownMainAlt1: "J", ScrollUpMainAlt2: "<c-u>", ScrollDownMainAlt2: "<c-d>", ExecuteCustomCommand: ":", CreateRebaseOptionsMenu: "m", PushFiles: "P", PullFiles: "p", Refresh: "R", CreatePatchOptionsMenu: "<c-p>", NextTab: "]", PrevTab: "[", NextScreenMode: "+", PrevScreenMode: "_", Undo: "z", Redo: "<c-z>", FilteringMenu: "<c-s>", DiffingMenu: "W", DiffingMenuAlt: "<c-e>", CopyToClipboard: "<c-o>", SubmitEditorText: "<enter>", AppendNewline: "<a-enter>", ExtrasMenu: "@", ToggleWhitespaceInDiffView: "<c-w>", IncreaseContextInDiffView: "}", DecreaseContextInDiffView: "{", }, Status: KeybindingStatusConfig{ CheckForUpdate: "u", RecentRepos: "<enter>", AllBranchesLogGraph: "a", }, Files: KeybindingFilesConfig{ CommitChanges: "c", CommitChangesWithoutHook: "w", AmendLastCommit: "A", CommitChangesWithEditor: "C", IgnoreFile: "i", RefreshFiles: "r", StashAllChanges: "s", ViewStashOptions: "S", ToggleStagedAll: "a", ViewResetOptions: "D", Fetch: "f", ToggleTreeView: "`", OpenMergeTool: "M", OpenStatusFilter: "<c-b>", }, Branches: KeybindingBranchesConfig{ CopyPullRequestURL: "<c-y>", CreatePullRequest: "o", ViewPullRequestOptions: "O", CheckoutBranchByName: "c", ForceCheckoutBranch: "F", RebaseBranch: "r", RenameBranch: "R", MergeIntoCurrentBranch: "M", ViewGitFlowOptions: "i", FastForward: "f", PushTag: "P", SetUpstream: "u", FetchRemote: "f", }, Commits: KeybindingCommitsConfig{ SquashDown: "s", RenameCommit: "r", RenameCommitWithEditor: "R", ViewResetOptions: "g", MarkCommitAsFixup: "f", CreateFixupCommit: "F", SquashAboveCommits: "S", MoveDownCommit: "<c-j>", MoveUpCommit: "<c-k>", AmendToCommit: "A", ResetCommitAuthor: "a", PickCommit: "p", RevertCommit: "t", CherryPickCopy: "c", CherryPickCopyRange: "C", PasteCommits: "v", TagCommit: "T", CheckoutCommit: "<space>", ResetCherryPick: "<c-R>", CopyCommitAttributeToClipboard: "y", OpenLogMenu: "<c-l>", OpenInBrowser: "o", ViewBisectOptions: "b", }, Stash: KeybindingStashConfig{ PopStash: "g", }, CommitFiles: KeybindingCommitFilesConfig{ CheckoutCommitFile: "c", }, Main: KeybindingMainConfig{ ToggleDragSelect: "v", ToggleDragSelectAlt: "V", ToggleSelectHunk: "a", PickBothHunks: "b", EditSelectHunk: "E", }, Submodules: KeybindingSubmodulesConfig{ Init: "i", Update: "u", BulkMenu: "b", }, }, OS: GetPlatformDefaultConfig(), DisableStartupPopups: false, CustomCommands: []CustomCommand(nil), Services: map[string]string(nil), NotARepository: "prompt", PromptToReturnFromSubprocess: true, } }
pkg/config/user_config.go
1
https://github.com/jesseduffield/lazygit/commit/666180cfd02f7ff69faa7425caa5eef358955827
[ 0.0010757467243820429, 0.00020544652943499386, 0.0001647977769607678, 0.00017123992438428104, 0.00012573407730087638 ]
{ "id": 3, "code_window": [ "\n", "\tc *types.HelperCommon,\n", ") *LocalCommitsContext {\n", "\tviewModel := NewLocalCommitsViewModel(getModel)\n", "\n", "\treturn &LocalCommitsContext{\n", "\t\tLocalCommitsViewModel: viewModel,\n", "\t\tViewportListContextTrait: &ViewportListContextTrait{\n", "\t\t\tListContextTrait: &ListContextTrait{\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tviewModel := NewLocalCommitsViewModel(getModel, c)\n" ], "file_path": "pkg/gui/context/local_commits_context.go", "type": "replace", "edit_start_line_idx": 26 }
ref: refs/heads/master
test/integration/stashAllChanges/expected/repo/.git_keep/HEAD
0
https://github.com/jesseduffield/lazygit/commit/666180cfd02f7ff69faa7425caa5eef358955827
[ 0.00017725618090480566, 0.00017725618090480566, 0.00017725618090480566, 0.00017725618090480566, 0 ]
{ "id": 3, "code_window": [ "\n", "\tc *types.HelperCommon,\n", ") *LocalCommitsContext {\n", "\tviewModel := NewLocalCommitsViewModel(getModel)\n", "\n", "\treturn &LocalCommitsContext{\n", "\t\tLocalCommitsViewModel: viewModel,\n", "\t\tViewportListContextTrait: &ViewportListContextTrait{\n", "\t\t\tListContextTrait: &ListContextTrait{\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tviewModel := NewLocalCommitsViewModel(getModel, c)\n" ], "file_path": "pkg/gui/context/local_commits_context.go", "type": "replace", "edit_start_line_idx": 26 }
#!/bin/sh set -e cd $1 git init git config user.email "[email protected]" git config user.name "CI" echo test0 > file0 git add . git commit -am file0 echo test1 > file1 git add . git commit -am file1 echo test2 > file2 git add . git commit -am file2 echo test3 > file3 git add .
test/integration/rebaseRewordOldCommit/setup.sh
0
https://github.com/jesseduffield/lazygit/commit/666180cfd02f7ff69faa7425caa5eef358955827
[ 0.00017579049745108932, 0.0001748922950355336, 0.0001735590340103954, 0.00017532732454128563, 9.61527121035033e-7 ]
{ "id": 3, "code_window": [ "\n", "\tc *types.HelperCommon,\n", ") *LocalCommitsContext {\n", "\tviewModel := NewLocalCommitsViewModel(getModel)\n", "\n", "\treturn &LocalCommitsContext{\n", "\t\tLocalCommitsViewModel: viewModel,\n", "\t\tViewportListContextTrait: &ViewportListContextTrait{\n", "\t\t\tListContextTrait: &ListContextTrait{\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tviewModel := NewLocalCommitsViewModel(getModel, c)\n" ], "file_path": "pkg/gui/context/local_commits_context.go", "type": "replace", "edit_start_line_idx": 26 }
/* * CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen * THIS FILE MUST NOT BE EDITED BY HAND */ package assert import ( http "net/http" url "net/url" time "time" ) // Conditionf uses a Comparison to assert a complex condition. func Conditionf(t TestingT, comp Comparison, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Condition(t, comp, append([]interface{}{msg}, args...)...) } // Containsf asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // assert.Containsf(t, "Hello World", "World", "error message %s", "formatted") // assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") // assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Contains(t, s, contains, append([]interface{}{msg}, args...)...) } // DirExistsf checks whether a directory exists in the given path. It also fails // if the path is a file rather a directory or there is an error checking whether it exists. func DirExistsf(t TestingT, path string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return DirExists(t, path, append([]interface{}{msg}, args...)...) } // ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // // assert.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return ElementsMatch(t, listA, listB, append([]interface{}{msg}, args...)...) } // Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // assert.Emptyf(t, obj, "error message %s", "formatted") func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Empty(t, object, append([]interface{}{msg}, args...)...) } // Equalf asserts that two objects are equal. // // assert.Equalf(t, 123, 123, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Equal(t, expected, actual, append([]interface{}{msg}, args...)...) } // EqualErrorf asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return EqualError(t, theError, errString, append([]interface{}{msg}, args...)...) } // EqualValuesf asserts that two objects are equal or convertable to the same types // and equal. // // assert.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted") func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return EqualValues(t, expected, actual, append([]interface{}{msg}, args...)...) } // Errorf asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if assert.Errorf(t, err, "error message %s", "formatted") { // assert.Equal(t, expectedErrorf, err) // } func Errorf(t TestingT, err error, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Error(t, err, append([]interface{}{msg}, args...)...) } // ErrorAsf asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value. // This is a wrapper for errors.As. func ErrorAsf(t TestingT, err error, target interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return ErrorAs(t, err, target, append([]interface{}{msg}, args...)...) } // ErrorIsf asserts that at least one of the errors in err's chain matches target. // This is a wrapper for errors.Is. func ErrorIsf(t TestingT, err error, target error, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return ErrorIs(t, err, target, append([]interface{}{msg}, args...)...) } // Eventuallyf asserts that given condition will be met in waitFor time, // periodically checking target function each tick. // // assert.Eventuallyf(t, func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Eventually(t, condition, waitFor, tick, append([]interface{}{msg}, args...)...) } // Exactlyf asserts that two objects are equal in value and type. // // assert.Exactlyf(t, int32(123), int64(123), "error message %s", "formatted") func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Exactly(t, expected, actual, append([]interface{}{msg}, args...)...) } // Failf reports a failure through func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Fail(t, failureMessage, append([]interface{}{msg}, args...)...) } // FailNowf fails test func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return FailNow(t, failureMessage, append([]interface{}{msg}, args...)...) } // Falsef asserts that the specified value is false. // // assert.Falsef(t, myBool, "error message %s", "formatted") func Falsef(t TestingT, value bool, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return False(t, value, append([]interface{}{msg}, args...)...) } // FileExistsf checks whether a file exists in the given path. It also fails if // the path points to a directory or there is an error when trying to check the file. func FileExistsf(t TestingT, path string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return FileExists(t, path, append([]interface{}{msg}, args...)...) } // Greaterf asserts that the first element is greater than the second // // assert.Greaterf(t, 2, 1, "error message %s", "formatted") // assert.Greaterf(t, float64(2), float64(1), "error message %s", "formatted") // assert.Greaterf(t, "b", "a", "error message %s", "formatted") func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Greater(t, e1, e2, append([]interface{}{msg}, args...)...) } // GreaterOrEqualf asserts that the first element is greater than or equal to the second // // assert.GreaterOrEqualf(t, 2, 1, "error message %s", "formatted") // assert.GreaterOrEqualf(t, 2, 2, "error message %s", "formatted") // assert.GreaterOrEqualf(t, "b", "a", "error message %s", "formatted") // assert.GreaterOrEqualf(t, "b", "b", "error message %s", "formatted") func GreaterOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return GreaterOrEqual(t, e1, e2, append([]interface{}{msg}, args...)...) } // HTTPBodyContainsf asserts that a specified handler returns a // body that contains a string. // // assert.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return HTTPBodyContains(t, handler, method, url, values, str, append([]interface{}{msg}, args...)...) } // HTTPBodyNotContainsf asserts that a specified handler returns a // body that does not contain a string. // // assert.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return HTTPBodyNotContains(t, handler, method, url, values, str, append([]interface{}{msg}, args...)...) } // HTTPErrorf asserts that a specified handler returns an error status code. // // assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return HTTPError(t, handler, method, url, values, append([]interface{}{msg}, args...)...) } // HTTPRedirectf asserts that a specified handler returns a redirect status code. // // assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return HTTPRedirect(t, handler, method, url, values, append([]interface{}{msg}, args...)...) } // HTTPStatusCodef asserts that a specified handler returns a specified status code. // // assert.HTTPStatusCodef(t, myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return HTTPStatusCode(t, handler, method, url, values, statuscode, append([]interface{}{msg}, args...)...) } // HTTPSuccessf asserts that a specified handler returns a success status code. // // assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return HTTPSuccess(t, handler, method, url, values, append([]interface{}{msg}, args...)...) } // Implementsf asserts that an object is implemented by the specified interface. // // assert.Implementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted") func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Implements(t, interfaceObject, object, append([]interface{}{msg}, args...)...) } // InDeltaf asserts that the two numerals are within delta of each other. // // assert.InDeltaf(t, math.Pi, 22/7.0, 0.01, "error message %s", "formatted") func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return InDelta(t, expected, actual, delta, append([]interface{}{msg}, args...)...) } // InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. func InDeltaMapValuesf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return InDeltaMapValues(t, expected, actual, delta, append([]interface{}{msg}, args...)...) } // InDeltaSlicef is the same as InDelta, except it compares two slices. func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return InDeltaSlice(t, expected, actual, delta, append([]interface{}{msg}, args...)...) } // InEpsilonf asserts that expected and actual have a relative error less than epsilon func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return InEpsilon(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...) } // InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. func InEpsilonSlicef(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return InEpsilonSlice(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...) } // IsDecreasingf asserts that the collection is decreasing // // assert.IsDecreasingf(t, []int{2, 1, 0}, "error message %s", "formatted") // assert.IsDecreasingf(t, []float{2, 1}, "error message %s", "formatted") // assert.IsDecreasingf(t, []string{"b", "a"}, "error message %s", "formatted") func IsDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return IsDecreasing(t, object, append([]interface{}{msg}, args...)...) } // IsIncreasingf asserts that the collection is increasing // // assert.IsIncreasingf(t, []int{1, 2, 3}, "error message %s", "formatted") // assert.IsIncreasingf(t, []float{1, 2}, "error message %s", "formatted") // assert.IsIncreasingf(t, []string{"a", "b"}, "error message %s", "formatted") func IsIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return IsIncreasing(t, object, append([]interface{}{msg}, args...)...) } // IsNonDecreasingf asserts that the collection is not decreasing // // assert.IsNonDecreasingf(t, []int{1, 1, 2}, "error message %s", "formatted") // assert.IsNonDecreasingf(t, []float{1, 2}, "error message %s", "formatted") // assert.IsNonDecreasingf(t, []string{"a", "b"}, "error message %s", "formatted") func IsNonDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return IsNonDecreasing(t, object, append([]interface{}{msg}, args...)...) } // IsNonIncreasingf asserts that the collection is not increasing // // assert.IsNonIncreasingf(t, []int{2, 1, 1}, "error message %s", "formatted") // assert.IsNonIncreasingf(t, []float{2, 1}, "error message %s", "formatted") // assert.IsNonIncreasingf(t, []string{"b", "a"}, "error message %s", "formatted") func IsNonIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return IsNonIncreasing(t, object, append([]interface{}{msg}, args...)...) } // IsTypef asserts that the specified objects are of the same type. func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return IsType(t, expectedType, object, append([]interface{}{msg}, args...)...) } // JSONEqf asserts that two JSON strings are equivalent. // // assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return JSONEq(t, expected, actual, append([]interface{}{msg}, args...)...) } // Lenf asserts that the specified object has specific length. // Lenf also fails if the object has a type that len() not accept. // // assert.Lenf(t, mySlice, 3, "error message %s", "formatted") func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Len(t, object, length, append([]interface{}{msg}, args...)...) } // Lessf asserts that the first element is less than the second // // assert.Lessf(t, 1, 2, "error message %s", "formatted") // assert.Lessf(t, float64(1), float64(2), "error message %s", "formatted") // assert.Lessf(t, "a", "b", "error message %s", "formatted") func Lessf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Less(t, e1, e2, append([]interface{}{msg}, args...)...) } // LessOrEqualf asserts that the first element is less than or equal to the second // // assert.LessOrEqualf(t, 1, 2, "error message %s", "formatted") // assert.LessOrEqualf(t, 2, 2, "error message %s", "formatted") // assert.LessOrEqualf(t, "a", "b", "error message %s", "formatted") // assert.LessOrEqualf(t, "b", "b", "error message %s", "formatted") func LessOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return LessOrEqual(t, e1, e2, append([]interface{}{msg}, args...)...) } // Negativef asserts that the specified element is negative // // assert.Negativef(t, -1, "error message %s", "formatted") // assert.Negativef(t, -1.23, "error message %s", "formatted") func Negativef(t TestingT, e interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Negative(t, e, append([]interface{}{msg}, args...)...) } // Neverf asserts that the given condition doesn't satisfy in waitFor time, // periodically checking the target function each tick. // // assert.Neverf(t, func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") func Neverf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Never(t, condition, waitFor, tick, append([]interface{}{msg}, args...)...) } // Nilf asserts that the specified object is nil. // // assert.Nilf(t, err, "error message %s", "formatted") func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Nil(t, object, append([]interface{}{msg}, args...)...) } // NoDirExistsf checks whether a directory does not exist in the given path. // It fails if the path points to an existing _directory_ only. func NoDirExistsf(t TestingT, path string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NoDirExists(t, path, append([]interface{}{msg}, args...)...) } // NoErrorf asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if assert.NoErrorf(t, err, "error message %s", "formatted") { // assert.Equal(t, expectedObj, actualObj) // } func NoErrorf(t TestingT, err error, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NoError(t, err, append([]interface{}{msg}, args...)...) } // NoFileExistsf checks whether a file does not exist in a given path. It fails // if the path points to an existing _file_ only. func NoFileExistsf(t TestingT, path string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NoFileExists(t, path, append([]interface{}{msg}, args...)...) } // NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") // assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") // assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotContains(t, s, contains, append([]interface{}{msg}, args...)...) } // NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if assert.NotEmptyf(t, obj, "error message %s", "formatted") { // assert.Equal(t, "two", obj[1]) // } func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotEmpty(t, object, append([]interface{}{msg}, args...)...) } // NotEqualf asserts that the specified values are NOT equal. // // assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotEqual(t, expected, actual, append([]interface{}{msg}, args...)...) } // NotEqualValuesf asserts that two objects are not equal even when converted to the same type // // assert.NotEqualValuesf(t, obj1, obj2, "error message %s", "formatted") func NotEqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotEqualValues(t, expected, actual, append([]interface{}{msg}, args...)...) } // NotErrorIsf asserts that at none of the errors in err's chain matches target. // This is a wrapper for errors.Is. func NotErrorIsf(t TestingT, err error, target error, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotErrorIs(t, err, target, append([]interface{}{msg}, args...)...) } // NotNilf asserts that the specified object is not nil. // // assert.NotNilf(t, err, "error message %s", "formatted") func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotNil(t, object, append([]interface{}{msg}, args...)...) } // NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. // // assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") func NotPanicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotPanics(t, f, append([]interface{}{msg}, args...)...) } // NotRegexpf asserts that a specified regexp does not match a string. // // assert.NotRegexpf(t, regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted") // assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotRegexp(t, rx, str, append([]interface{}{msg}, args...)...) } // NotSamef asserts that two pointers do not reference the same object. // // assert.NotSamef(t, ptr1, ptr2, "error message %s", "formatted") // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. func NotSamef(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotSame(t, expected, actual, append([]interface{}{msg}, args...)...) } // NotSubsetf asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // // assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotSubset(t, list, subset, append([]interface{}{msg}, args...)...) } // NotZerof asserts that i is not the zero value for its type. func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotZero(t, i, append([]interface{}{msg}, args...)...) } // Panicsf asserts that the code inside the specified PanicTestFunc panics. // // assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") func Panicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Panics(t, f, append([]interface{}{msg}, args...)...) } // PanicsWithErrorf asserts that the code inside the specified PanicTestFunc // panics, and that the recovered panic value is an error that satisfies the // EqualError comparison. // // assert.PanicsWithErrorf(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") func PanicsWithErrorf(t TestingT, errString string, f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return PanicsWithError(t, errString, f, append([]interface{}{msg}, args...)...) } // PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // // assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") func PanicsWithValuef(t TestingT, expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return PanicsWithValue(t, expected, f, append([]interface{}{msg}, args...)...) } // Positivef asserts that the specified element is positive // // assert.Positivef(t, 1, "error message %s", "formatted") // assert.Positivef(t, 1.23, "error message %s", "formatted") func Positivef(t TestingT, e interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Positive(t, e, append([]interface{}{msg}, args...)...) } // Regexpf asserts that a specified regexp matches a string. // // assert.Regexpf(t, regexp.MustCompile("start"), "it's starting", "error message %s", "formatted") // assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Regexp(t, rx, str, append([]interface{}{msg}, args...)...) } // Samef asserts that two pointers reference the same object. // // assert.Samef(t, ptr1, ptr2, "error message %s", "formatted") // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. func Samef(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Same(t, expected, actual, append([]interface{}{msg}, args...)...) } // Subsetf asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Subset(t, list, subset, append([]interface{}{msg}, args...)...) } // Truef asserts that the specified value is true. // // assert.Truef(t, myBool, "error message %s", "formatted") func Truef(t TestingT, value bool, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return True(t, value, append([]interface{}{msg}, args...)...) } // WithinDurationf asserts that the two times are within duration delta of each other. // // assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return WithinDuration(t, expected, actual, delta, append([]interface{}{msg}, args...)...) } // YAMLEqf asserts that two YAML strings are equivalent. func YAMLEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return YAMLEq(t, expected, actual, append([]interface{}{msg}, args...)...) } // Zerof asserts that i is the zero value for its type. func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Zero(t, i, append([]interface{}{msg}, args...)...) }
vendor/github.com/stretchr/testify/assert/assertion_format.go
0
https://github.com/jesseduffield/lazygit/commit/666180cfd02f7ff69faa7425caa5eef358955827
[ 0.004642541985958815, 0.00024233385920524597, 0.00016508449334651232, 0.00016914974548853934, 0.0005132742808200419 ]
{ "id": 4, "code_window": [ "\tshowWholeGitGraph bool\n", "}\n", "\n", "func NewLocalCommitsViewModel(getModel func() []*models.Commit) *LocalCommitsViewModel {\n", "\tself := &LocalCommitsViewModel{\n", "\t\tBasicViewModel: NewBasicViewModel(getModel),\n", "\t\tlimitCommits: true,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "func NewLocalCommitsViewModel(getModel func() []*models.Commit, c *types.HelperCommon) *LocalCommitsViewModel {\n" ], "file_path": "pkg/gui/context/local_commits_context.go", "type": "replace", "edit_start_line_idx": 72 }
package context import ( "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type LocalCommitsContext struct { *LocalCommitsViewModel *ViewportListContextTrait } var _ types.IListContext = (*LocalCommitsContext)(nil) func NewLocalCommitsContext( getModel func() []*models.Commit, view *gocui.View, getDisplayStrings func(startIdx int, length int) [][]string, onFocus func(...types.OnFocusOpts) error, onRenderToMain func(...types.OnFocusOpts) error, onFocusLost func() error, c *types.HelperCommon, ) *LocalCommitsContext { viewModel := NewLocalCommitsViewModel(getModel) return &LocalCommitsContext{ LocalCommitsViewModel: viewModel, ViewportListContextTrait: &ViewportListContextTrait{ ListContextTrait: &ListContextTrait{ Context: NewSimpleContext(NewBaseContext(NewBaseContextOpts{ ViewName: "commits", WindowName: "commits", Key: LOCAL_COMMITS_CONTEXT_KEY, Kind: types.SIDE_CONTEXT, Focusable: true, }), ContextCallbackOpts{ OnFocus: onFocus, OnFocusLost: onFocusLost, OnRenderToMain: onRenderToMain, }), list: viewModel, viewTrait: NewViewTrait(view), getDisplayStrings: getDisplayStrings, c: c, }, }, } } func (self *LocalCommitsContext) GetSelectedItemId() string { item := self.GetSelected() if item == nil { return "" } return item.ID() } type LocalCommitsViewModel struct { *BasicViewModel[*models.Commit] // If this is true we limit the amount of commits we load, for the sake of keeping things fast. // If the user attempts to scroll past the end of the list, we will load more commits. limitCommits bool // If this is true we'll use git log --all when fetching the commits. showWholeGitGraph bool } func NewLocalCommitsViewModel(getModel func() []*models.Commit) *LocalCommitsViewModel { self := &LocalCommitsViewModel{ BasicViewModel: NewBasicViewModel(getModel), limitCommits: true, } return self } func (self *LocalCommitsContext) CanRebase() bool { return true } func (self *LocalCommitsContext) GetSelectedRef() types.Ref { commit := self.GetSelected() if commit == nil { return nil } return commit } func (self *LocalCommitsViewModel) SetLimitCommits(value bool) { self.limitCommits = value } func (self *LocalCommitsViewModel) GetLimitCommits() bool { return self.limitCommits } func (self *LocalCommitsViewModel) SetShowWholeGitGraph(value bool) { self.showWholeGitGraph = value } func (self *LocalCommitsViewModel) GetShowWholeGitGraph() bool { return self.showWholeGitGraph } func (self *LocalCommitsViewModel) GetCommits() []*models.Commit { return self.getModel() }
pkg/gui/context/local_commits_context.go
1
https://github.com/jesseduffield/lazygit/commit/666180cfd02f7ff69faa7425caa5eef358955827
[ 0.9992884397506714, 0.5490089058876038, 0.00022152469318825752, 0.7807497978210449, 0.45917412638664246 ]
{ "id": 4, "code_window": [ "\tshowWholeGitGraph bool\n", "}\n", "\n", "func NewLocalCommitsViewModel(getModel func() []*models.Commit) *LocalCommitsViewModel {\n", "\tself := &LocalCommitsViewModel{\n", "\t\tBasicViewModel: NewBasicViewModel(getModel),\n", "\t\tlimitCommits: true,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "func NewLocalCommitsViewModel(getModel func() []*models.Commit, c *types.HelperCommon) *LocalCommitsViewModel {\n" ], "file_path": "pkg/gui/context/local_commits_context.go", "type": "replace", "edit_start_line_idx": 72 }
test2
test/integration/reflogCheckout/expected/repo/file2
0
https://github.com/jesseduffield/lazygit/commit/666180cfd02f7ff69faa7425caa5eef358955827
[ 0.0001758753351168707, 0.0001758753351168707, 0.0001758753351168707, 0.0001758753351168707, 0 ]
{ "id": 4, "code_window": [ "\tshowWholeGitGraph bool\n", "}\n", "\n", "func NewLocalCommitsViewModel(getModel func() []*models.Commit) *LocalCommitsViewModel {\n", "\tself := &LocalCommitsViewModel{\n", "\t\tBasicViewModel: NewBasicViewModel(getModel),\n", "\t\tlimitCommits: true,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "func NewLocalCommitsViewModel(getModel func() []*models.Commit, c *types.HelperCommon) *LocalCommitsViewModel {\n" ], "file_path": "pkg/gui/context/local_commits_context.go", "type": "replace", "edit_start_line_idx": 72 }
// 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. package packet import ( "crypto" "crypto/rand" "io" "time" ) // Config collects a number of parameters along with sensible defaults. // A nil *Config is valid and results in all default values. type Config struct { // Rand provides the source of entropy. // If nil, the crypto/rand Reader is used. Rand io.Reader // DefaultHash is the default hash function to be used. // If zero, SHA-256 is used. DefaultHash crypto.Hash // DefaultCipher is the cipher to be used. // If zero, AES-128 is used. DefaultCipher CipherFunction // Time returns the current time as the number of seconds since the // epoch. If Time is nil, time.Now is used. Time func() time.Time // DefaultCompressionAlgo is the compression algorithm to be // applied to the plaintext before encryption. If zero, no // compression is done. DefaultCompressionAlgo CompressionAlgo // CompressionConfig configures the compression settings. CompressionConfig *CompressionConfig // S2KCount is only used for symmetric encryption. It // determines the strength of the passphrase stretching when // the said passphrase is hashed to produce a key. S2KCount // should be between 1024 and 65011712, inclusive. If Config // is nil or S2KCount is 0, the value 65536 used. Not all // values in the above range can be represented. S2KCount will // be rounded up to the next representable value if it cannot // be encoded exactly. When set, it is strongly encrouraged to // use a value that is at least 65536. See RFC 4880 Section // 3.7.1.3. S2KCount int // RSABits is the number of bits in new RSA keys made with NewEntity. // If zero, then 2048 bit keys are created. RSABits int } func (c *Config) Random() io.Reader { if c == nil || c.Rand == nil { return rand.Reader } return c.Rand } func (c *Config) Hash() crypto.Hash { if c == nil || uint(c.DefaultHash) == 0 { return crypto.SHA256 } return c.DefaultHash } func (c *Config) Cipher() CipherFunction { if c == nil || uint8(c.DefaultCipher) == 0 { return CipherAES128 } return c.DefaultCipher } func (c *Config) Now() time.Time { if c == nil || c.Time == nil { return time.Now() } return c.Time() } func (c *Config) Compression() CompressionAlgo { if c == nil { return CompressionNone } return c.DefaultCompressionAlgo } func (c *Config) PasswordHashIterations() int { if c == nil || c.S2KCount == 0 { return 0 } return c.S2KCount }
vendor/golang.org/x/crypto/openpgp/packet/config.go
0
https://github.com/jesseduffield/lazygit/commit/666180cfd02f7ff69faa7425caa5eef358955827
[ 0.00017632397066336125, 0.00016953906742855906, 0.00016455173317808658, 0.00016936977044679224, 0.0000043302516132825986 ]
{ "id": 4, "code_window": [ "\tshowWholeGitGraph bool\n", "}\n", "\n", "func NewLocalCommitsViewModel(getModel func() []*models.Commit) *LocalCommitsViewModel {\n", "\tself := &LocalCommitsViewModel{\n", "\t\tBasicViewModel: NewBasicViewModel(getModel),\n", "\t\tlimitCommits: true,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "func NewLocalCommitsViewModel(getModel func() []*models.Commit, c *types.HelperCommon) *LocalCommitsViewModel {\n" ], "file_path": "pkg/gui/context/local_commits_context.go", "type": "replace", "edit_start_line_idx": 72 }
// Generated automatically. DO NOT HAND-EDIT. package vt420 import "github.com/gdamore/tcell/v2/terminfo" func init() { // DEC VT420 terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "vt420", Columns: 80, Lines: 24, Bell: "\a", Clear: "\x1b[H\x1b[2J$<50>", ShowCursor: "\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[m\x1b(B$<2>", Underline: "\x1b[4m", Bold: "\x1b[1m$<2>", Blink: "\x1b[5m$<2>", Reverse: "\x1b[7m$<2>", EnterKeypad: "\x1b=", ExitKeypad: "\x1b>", PadChar: "\x00", AltChars: "``aaffggjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x1b(0$<2>", ExitAcs: "\x1b(B$<4>", EnableAcs: "\x1b)0", SetCursor: "\x1b[%i%p1%d;%p2%dH$<10>", CursorBack1: "\b", CursorUp1: "\x1b[A", KeyUp: "\x1b[A", KeyDown: "\x1b[B", KeyRight: "\x1b[C", KeyLeft: "\x1b[D", KeyInsert: "\x1b[2~", KeyDelete: "\x1b[3~", KeyBackspace: "\b", KeyPgUp: "\x1b[5~", KeyPgDn: "\x1b[6~", KeyF1: "\x1bOP", KeyF2: "\x1bOQ", KeyF3: "\x1bOR", KeyF4: "\x1bOS", KeyF5: "\x1b[17~", KeyF6: "\x1b[18~", KeyF7: "\x1b[19~", KeyF8: "\x1b[20~", KeyF9: "\x1b[21~", KeyF10: "\x1b[29~", AutoMargin: true, }) }
vendor/github.com/gdamore/tcell/v2/terminfo/v/vt420/term.go
0
https://github.com/jesseduffield/lazygit/commit/666180cfd02f7ff69faa7425caa5eef358955827
[ 0.00017097496311180294, 0.00016962717927526683, 0.00016845602658577263, 0.00016962946392595768, 8.563973210584663e-7 ]
{ "id": 5, "code_window": [ "\tself := &LocalCommitsViewModel{\n", "\t\tBasicViewModel: NewBasicViewModel(getModel),\n", "\t\tlimitCommits: true,\n", "\t}\n", "\n", "\treturn self\n", "}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tshowWholeGitGraph: c.UserConfig.Git.Log.ShowWholeGraph,\n" ], "file_path": "pkg/gui/context/local_commits_context.go", "type": "add", "edit_start_line_idx": 76 }
package context import ( "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type LocalCommitsContext struct { *LocalCommitsViewModel *ViewportListContextTrait } var _ types.IListContext = (*LocalCommitsContext)(nil) func NewLocalCommitsContext( getModel func() []*models.Commit, view *gocui.View, getDisplayStrings func(startIdx int, length int) [][]string, onFocus func(...types.OnFocusOpts) error, onRenderToMain func(...types.OnFocusOpts) error, onFocusLost func() error, c *types.HelperCommon, ) *LocalCommitsContext { viewModel := NewLocalCommitsViewModel(getModel) return &LocalCommitsContext{ LocalCommitsViewModel: viewModel, ViewportListContextTrait: &ViewportListContextTrait{ ListContextTrait: &ListContextTrait{ Context: NewSimpleContext(NewBaseContext(NewBaseContextOpts{ ViewName: "commits", WindowName: "commits", Key: LOCAL_COMMITS_CONTEXT_KEY, Kind: types.SIDE_CONTEXT, Focusable: true, }), ContextCallbackOpts{ OnFocus: onFocus, OnFocusLost: onFocusLost, OnRenderToMain: onRenderToMain, }), list: viewModel, viewTrait: NewViewTrait(view), getDisplayStrings: getDisplayStrings, c: c, }, }, } } func (self *LocalCommitsContext) GetSelectedItemId() string { item := self.GetSelected() if item == nil { return "" } return item.ID() } type LocalCommitsViewModel struct { *BasicViewModel[*models.Commit] // If this is true we limit the amount of commits we load, for the sake of keeping things fast. // If the user attempts to scroll past the end of the list, we will load more commits. limitCommits bool // If this is true we'll use git log --all when fetching the commits. showWholeGitGraph bool } func NewLocalCommitsViewModel(getModel func() []*models.Commit) *LocalCommitsViewModel { self := &LocalCommitsViewModel{ BasicViewModel: NewBasicViewModel(getModel), limitCommits: true, } return self } func (self *LocalCommitsContext) CanRebase() bool { return true } func (self *LocalCommitsContext) GetSelectedRef() types.Ref { commit := self.GetSelected() if commit == nil { return nil } return commit } func (self *LocalCommitsViewModel) SetLimitCommits(value bool) { self.limitCommits = value } func (self *LocalCommitsViewModel) GetLimitCommits() bool { return self.limitCommits } func (self *LocalCommitsViewModel) SetShowWholeGitGraph(value bool) { self.showWholeGitGraph = value } func (self *LocalCommitsViewModel) GetShowWholeGitGraph() bool { return self.showWholeGitGraph } func (self *LocalCommitsViewModel) GetCommits() []*models.Commit { return self.getModel() }
pkg/gui/context/local_commits_context.go
1
https://github.com/jesseduffield/lazygit/commit/666180cfd02f7ff69faa7425caa5eef358955827
[ 0.9968525767326355, 0.08823692798614502, 0.0001672329963184893, 0.00493871234357357, 0.2740183472633362 ]
{ "id": 5, "code_window": [ "\tself := &LocalCommitsViewModel{\n", "\t\tBasicViewModel: NewBasicViewModel(getModel),\n", "\t\tlimitCommits: true,\n", "\t}\n", "\n", "\treturn self\n", "}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tshowWholeGitGraph: c.UserConfig.Git.Log.ShowWholeGraph,\n" ], "file_path": "pkg/gui/context/local_commits_context.go", "type": "add", "edit_start_line_idx": 76 }
package git_config type FakeGitConfig struct { mockResponses map[string]string } func NewFakeGitConfig(mockResponses map[string]string) *FakeGitConfig { return &FakeGitConfig{ mockResponses: mockResponses, } } func (self *FakeGitConfig) Get(key string) string { if self.mockResponses == nil { return "" } return self.mockResponses[key] } func (self *FakeGitConfig) GetGeneral(args string) string { if self.mockResponses == nil { return "" } return self.mockResponses[args] } func (self *FakeGitConfig) GetBool(key string) bool { return isTruthy(self.Get(key)) }
pkg/commands/git_config/fake_git_config.go
0
https://github.com/jesseduffield/lazygit/commit/666180cfd02f7ff69faa7425caa5eef358955827
[ 0.00020038035290781409, 0.0001786978536983952, 0.0001664950541453436, 0.00016921813949011266, 0.00001537209755042568 ]
{ "id": 5, "code_window": [ "\tself := &LocalCommitsViewModel{\n", "\t\tBasicViewModel: NewBasicViewModel(getModel),\n", "\t\tlimitCommits: true,\n", "\t}\n", "\n", "\treturn self\n", "}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tshowWholeGitGraph: c.UserConfig.Git.Log.ShowWholeGraph,\n" ], "file_path": "pkg/gui/context/local_commits_context.go", "type": "add", "edit_start_line_idx": 76 }
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "crypto" "crypto/md5" "crypto/rsa" "encoding/binary" "fmt" "hash" "io" "math/big" "strconv" "time" "golang.org/x/crypto/openpgp/errors" ) // PublicKeyV3 represents older, version 3 public keys. These keys are less secure and // should not be used for signing or encrypting. They are supported here only for // parsing version 3 key material and validating signatures. // See RFC 4880, section 5.5.2. type PublicKeyV3 struct { CreationTime time.Time DaysToExpire uint16 PubKeyAlgo PublicKeyAlgorithm PublicKey *rsa.PublicKey Fingerprint [16]byte KeyId uint64 IsSubkey bool n, e parsedMPI } // newRSAPublicKeyV3 returns a PublicKey that wraps the given rsa.PublicKey. // Included here for testing purposes only. RFC 4880, section 5.5.2: // "an implementation MUST NOT generate a V3 key, but MAY accept it." func newRSAPublicKeyV3(creationTime time.Time, pub *rsa.PublicKey) *PublicKeyV3 { pk := &PublicKeyV3{ CreationTime: creationTime, PublicKey: pub, n: fromBig(pub.N), e: fromBig(big.NewInt(int64(pub.E))), } pk.setFingerPrintAndKeyId() return pk } func (pk *PublicKeyV3) parse(r io.Reader) (err error) { // RFC 4880, section 5.5.2 var buf [8]byte if _, err = readFull(r, buf[:]); err != nil { return } if buf[0] < 2 || buf[0] > 3 { return errors.UnsupportedError("public key version") } pk.CreationTime = time.Unix(int64(uint32(buf[1])<<24|uint32(buf[2])<<16|uint32(buf[3])<<8|uint32(buf[4])), 0) pk.DaysToExpire = binary.BigEndian.Uint16(buf[5:7]) pk.PubKeyAlgo = PublicKeyAlgorithm(buf[7]) switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: err = pk.parseRSA(r) default: err = errors.UnsupportedError("public key type: " + strconv.Itoa(int(pk.PubKeyAlgo))) } if err != nil { return } pk.setFingerPrintAndKeyId() return } func (pk *PublicKeyV3) setFingerPrintAndKeyId() { // RFC 4880, section 12.2 fingerPrint := md5.New() fingerPrint.Write(pk.n.bytes) fingerPrint.Write(pk.e.bytes) fingerPrint.Sum(pk.Fingerprint[:0]) pk.KeyId = binary.BigEndian.Uint64(pk.n.bytes[len(pk.n.bytes)-8:]) } // parseRSA parses RSA public key material from the given Reader. See RFC 4880, // section 5.5.2. func (pk *PublicKeyV3) parseRSA(r io.Reader) (err error) { if pk.n.bytes, pk.n.bitLength, err = readMPI(r); err != nil { return } if pk.e.bytes, pk.e.bitLength, err = readMPI(r); err != nil { return } // RFC 4880 Section 12.2 requires the low 8 bytes of the // modulus to form the key id. if len(pk.n.bytes) < 8 { return errors.StructuralError("v3 public key modulus is too short") } if len(pk.e.bytes) > 3 { err = errors.UnsupportedError("large public exponent") return } rsa := &rsa.PublicKey{N: new(big.Int).SetBytes(pk.n.bytes)} for i := 0; i < len(pk.e.bytes); i++ { rsa.E <<= 8 rsa.E |= int(pk.e.bytes[i]) } pk.PublicKey = rsa return } // SerializeSignaturePrefix writes the prefix for this public key to the given Writer. // The prefix is used when calculating a signature over this public key. See // RFC 4880, section 5.2.4. func (pk *PublicKeyV3) SerializeSignaturePrefix(w io.Writer) { var pLength uint16 switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: pLength += 2 + uint16(len(pk.n.bytes)) pLength += 2 + uint16(len(pk.e.bytes)) default: panic("unknown public key algorithm") } pLength += 6 w.Write([]byte{0x99, byte(pLength >> 8), byte(pLength)}) return } func (pk *PublicKeyV3) Serialize(w io.Writer) (err error) { length := 8 // 8 byte header switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: length += 2 + len(pk.n.bytes) length += 2 + len(pk.e.bytes) default: panic("unknown public key algorithm") } packetType := packetTypePublicKey if pk.IsSubkey { packetType = packetTypePublicSubkey } if err = serializeHeader(w, packetType, length); err != nil { return } return pk.serializeWithoutHeaders(w) } // serializeWithoutHeaders marshals the PublicKey to w in the form of an // OpenPGP public key packet, not including the packet header. func (pk *PublicKeyV3) serializeWithoutHeaders(w io.Writer) (err error) { var buf [8]byte // Version 3 buf[0] = 3 // Creation time t := uint32(pk.CreationTime.Unix()) buf[1] = byte(t >> 24) buf[2] = byte(t >> 16) buf[3] = byte(t >> 8) buf[4] = byte(t) // Days to expire buf[5] = byte(pk.DaysToExpire >> 8) buf[6] = byte(pk.DaysToExpire) // Public key algorithm buf[7] = byte(pk.PubKeyAlgo) if _, err = w.Write(buf[:]); err != nil { return } switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: return writeMPIs(w, pk.n, pk.e) } return errors.InvalidArgumentError("bad public-key algorithm") } // CanSign returns true iff this public key can generate signatures func (pk *PublicKeyV3) CanSign() bool { return pk.PubKeyAlgo != PubKeyAlgoRSAEncryptOnly } // VerifySignatureV3 returns nil iff sig is a valid signature, made by this // public key, of the data hashed into signed. signed is mutated by this call. func (pk *PublicKeyV3) VerifySignatureV3(signed hash.Hash, sig *SignatureV3) (err error) { if !pk.CanSign() { return errors.InvalidArgumentError("public key cannot generate signatures") } suffix := make([]byte, 5) suffix[0] = byte(sig.SigType) binary.BigEndian.PutUint32(suffix[1:], uint32(sig.CreationTime.Unix())) signed.Write(suffix) hashBytes := signed.Sum(nil) if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] { return errors.SignatureError("hash tag doesn't match") } if pk.PubKeyAlgo != sig.PubKeyAlgo { return errors.InvalidArgumentError("public key and signature use different algorithms") } switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: if err = rsa.VerifyPKCS1v15(pk.PublicKey, sig.Hash, hashBytes, sig.RSASignature.bytes); err != nil { return errors.SignatureError("RSA verification failure") } return default: // V3 public keys only support RSA. panic("shouldn't happen") } } // VerifyUserIdSignatureV3 returns nil iff sig is a valid signature, made by this // public key, that id is the identity of pub. func (pk *PublicKeyV3) VerifyUserIdSignatureV3(id string, pub *PublicKeyV3, sig *SignatureV3) (err error) { h, err := userIdSignatureV3Hash(id, pk, sig.Hash) if err != nil { return err } return pk.VerifySignatureV3(h, sig) } // VerifyKeySignatureV3 returns nil iff sig is a valid signature, made by this // public key, of signed. func (pk *PublicKeyV3) VerifyKeySignatureV3(signed *PublicKeyV3, sig *SignatureV3) (err error) { h, err := keySignatureHash(pk, signed, sig.Hash) if err != nil { return err } return pk.VerifySignatureV3(h, sig) } // userIdSignatureV3Hash returns a Hash of the message that needs to be signed // to assert that pk is a valid key for id. func userIdSignatureV3Hash(id string, pk signingKey, hfn crypto.Hash) (h hash.Hash, err error) { if !hfn.Available() { return nil, errors.UnsupportedError("hash function") } h = hfn.New() // RFC 4880, section 5.2.4 pk.SerializeSignaturePrefix(h) pk.serializeWithoutHeaders(h) h.Write([]byte(id)) return } // KeyIdString returns the public key's fingerprint in capital hex // (e.g. "6C7EE1B8621CC013"). func (pk *PublicKeyV3) KeyIdString() string { return fmt.Sprintf("%X", pk.KeyId) } // KeyIdShortString returns the short form of public key's fingerprint // in capital hex, as shown by gpg --list-keys (e.g. "621CC013"). func (pk *PublicKeyV3) KeyIdShortString() string { return fmt.Sprintf("%X", pk.KeyId&0xFFFFFFFF) } // BitLength returns the bit length for the given public key. func (pk *PublicKeyV3) BitLength() (bitLength uint16, err error) { switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: bitLength = pk.n.bitLength default: err = errors.InvalidArgumentError("bad public-key algorithm") } return }
vendor/golang.org/x/crypto/openpgp/packet/public_key_v3.go
0
https://github.com/jesseduffield/lazygit/commit/666180cfd02f7ff69faa7425caa5eef358955827
[ 0.000368313369108364, 0.00017796180327422917, 0.00016332650557160378, 0.0001707390765659511, 0.000036795467167394236 ]
{ "id": 5, "code_window": [ "\tself := &LocalCommitsViewModel{\n", "\t\tBasicViewModel: NewBasicViewModel(getModel),\n", "\t\tlimitCommits: true,\n", "\t}\n", "\n", "\treturn self\n", "}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tshowWholeGitGraph: c.UserConfig.Git.Log.ShowWholeGraph,\n" ], "file_path": "pkg/gui/context/local_commits_context.go", "type": "add", "edit_start_line_idx": 76 }
# Contributing to Go Go is an open source project. It is the work of hundreds of contributors. We appreciate your help! ## Filing issues When [filing an issue](https://golang.org/issue/new), make sure to answer these five questions: 1. What version of Go are you using (`go version`)? 2. What operating system and processor architecture are you using? 3. What did you do? 4. What did you expect to see? 5. What did you see instead? General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker. The gophers there will answer or ask you to file an issue if you've tripped over a bug. ## Contributing code Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html) before sending patches. Unless otherwise noted, the Go source files are distributed under the BSD-style license found in the LICENSE file.
vendor/golang.org/x/term/CONTRIBUTING.md
0
https://github.com/jesseduffield/lazygit/commit/666180cfd02f7ff69faa7425caa5eef358955827
[ 0.0001775362907210365, 0.00017653877148404717, 0.0001752275275066495, 0.000176852525328286, 9.683055850473465e-7 ]
{ "id": 0, "code_window": [ "func checkJSON(input []byte) (raw []byte, err error) {\n", "\tif !isString(input) {\n", "\t\treturn nil, errNonString\n", "\t}\n", "\tif len(input) == 2 {\n", "\t\treturn nil, ErrEmptyString\n", "\t}\n", "\tif !bytesHave0xPrefix(input[1:]) {\n", "\t\treturn nil, ErrMissingPrefix\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn nil, nil // empty strings are allowed\n" ], "file_path": "common/hexutil/json.go", "type": "replace", "edit_start_line_idx": 239 }
// Copyright 2016 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package hexutil import ( "bytes" "encoding/hex" "math/big" "testing" ) func checkError(t *testing.T, input string, got, want error) bool { if got == nil { if want != nil { t.Errorf("input %s: got no error, want %q", input, want) return false } return true } if want == nil { t.Errorf("input %s: unexpected error %q", input, got) } else if got.Error() != want.Error() { t.Errorf("input %s: got error %q, want %q", input, got, want) } return false } func referenceBig(s string) *big.Int { b, ok := new(big.Int).SetString(s, 16) if !ok { panic("invalid") } return b } func referenceBytes(s string) []byte { b, err := hex.DecodeString(s) if err != nil { panic(err) } return b } var unmarshalBytesTests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x0"`, wantErr: ErrOddLength}, {input: `"0xxx"`, wantErr: ErrSyntax}, {input: `"0x01zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x"`, want: referenceBytes("")}, {input: `"0x02"`, want: referenceBytes("02")}, {input: `"0X02"`, want: referenceBytes("02")}, {input: `"0xffffffffff"`, want: referenceBytes("ffffffffff")}, { input: `"0xffffffffffffffffffffffffffffffffffff"`, want: referenceBytes("ffffffffffffffffffffffffffffffffffff"), }, } func TestUnmarshalBytes(t *testing.T) { for _, test := range unmarshalBytesTests { var v Bytes err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if !bytes.Equal(test.want.([]byte), []byte(v)) { t.Errorf("input %s: value mismatch: got %x, want %x", test.input, &v, test.want) continue } } } func BenchmarkUnmarshalBytes(b *testing.B) { input := []byte(`"0x123456789abcdef123456789abcdef"`) for i := 0; i < b.N; i++ { var v Bytes if err := v.UnmarshalJSON(input); err != nil { b.Fatal(err) } } } func TestMarshalBytes(t *testing.T) { for _, test := range encodeBytesTests { in := test.input.([]byte) out, err := Bytes(in).MarshalJSON() if err != nil { t.Errorf("%x: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%x: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := Bytes(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } } var unmarshalBigTests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x"`, wantErr: ErrEmptyNumber}, {input: `"0x01"`, wantErr: ErrLeadingZero}, {input: `"0xx"`, wantErr: ErrSyntax}, {input: `"0x1zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x0"`, want: big.NewInt(0)}, {input: `"0x2"`, want: big.NewInt(0x2)}, {input: `"0x2F2"`, want: big.NewInt(0x2f2)}, {input: `"0X2F2"`, want: big.NewInt(0x2f2)}, {input: `"0x1122aaff"`, want: big.NewInt(0x1122aaff)}, {input: `"0xbBb"`, want: big.NewInt(0xbbb)}, {input: `"0xfffffffff"`, want: big.NewInt(0xfffffffff)}, { input: `"0x112233445566778899aabbccddeeff"`, want: referenceBig("112233445566778899aabbccddeeff"), }, { input: `"0xffffffffffffffffffffffffffffffffffff"`, want: referenceBig("ffffffffffffffffffffffffffffffffffff"), }, } func TestUnmarshalBig(t *testing.T) { for _, test := range unmarshalBigTests { var v Big err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if test.want != nil && test.want.(*big.Int).Cmp((*big.Int)(&v)) != 0 { t.Errorf("input %s: value mismatch: got %x, want %x", test.input, (*big.Int)(&v), test.want) continue } } } func BenchmarkUnmarshalBig(b *testing.B) { input := []byte(`"0x123456789abcdef123456789abcdef"`) for i := 0; i < b.N; i++ { var v Big if err := v.UnmarshalJSON(input); err != nil { b.Fatal(err) } } } func TestMarshalBig(t *testing.T) { for _, test := range encodeBigTests { in := test.input.(*big.Int) out, err := (*Big)(in).MarshalJSON() if err != nil { t.Errorf("%d: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%d: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := (*Big)(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } } var unmarshalUint64Tests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x"`, wantErr: ErrEmptyNumber}, {input: `"0x01"`, wantErr: ErrLeadingZero}, {input: `"0xfffffffffffffffff"`, wantErr: ErrUint64Range}, {input: `"0xx"`, wantErr: ErrSyntax}, {input: `"0x1zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x0"`, want: uint64(0)}, {input: `"0x2"`, want: uint64(0x2)}, {input: `"0x2F2"`, want: uint64(0x2f2)}, {input: `"0X2F2"`, want: uint64(0x2f2)}, {input: `"0x1122aaff"`, want: uint64(0x1122aaff)}, {input: `"0xbbb"`, want: uint64(0xbbb)}, {input: `"0xffffffffffffffff"`, want: uint64(0xffffffffffffffff)}, } func TestUnmarshalUint64(t *testing.T) { for _, test := range unmarshalUint64Tests { var v Uint64 err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if uint64(v) != test.want.(uint64) { t.Errorf("input %s: value mismatch: got %d, want %d", test.input, v, test.want) continue } } } func BenchmarkUnmarshalUint64(b *testing.B) { input := []byte(`"0x123456789abcdf"`) for i := 0; i < b.N; i++ { var v Uint64 v.UnmarshalJSON(input) } } func TestMarshalUint64(t *testing.T) { for _, test := range encodeUint64Tests { in := test.input.(uint64) out, err := Uint64(in).MarshalJSON() if err != nil { t.Errorf("%d: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%d: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := (Uint64)(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } }
common/hexutil/json_test.go
1
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.9980927109718323, 0.21419358253479004, 0.00016999327635858208, 0.0027624862268567085, 0.36915984749794006 ]
{ "id": 0, "code_window": [ "func checkJSON(input []byte) (raw []byte, err error) {\n", "\tif !isString(input) {\n", "\t\treturn nil, errNonString\n", "\t}\n", "\tif len(input) == 2 {\n", "\t\treturn nil, ErrEmptyString\n", "\t}\n", "\tif !bytesHave0xPrefix(input[1:]) {\n", "\t\treturn nil, ErrMissingPrefix\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn nil, nil // empty strings are allowed\n" ], "file_path": "common/hexutil/json.go", "type": "replace", "edit_start_line_idx": 239 }
- Assert(slice, Contains, item) - Parallel test support
vendor/gopkg.in/check.v1/TODO
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.00017292998381890357, 0.00017292998381890357, 0.00017292998381890357, 0.00017292998381890357, 0 ]
{ "id": 0, "code_window": [ "func checkJSON(input []byte) (raw []byte, err error) {\n", "\tif !isString(input) {\n", "\t\treturn nil, errNonString\n", "\t}\n", "\tif len(input) == 2 {\n", "\t\treturn nil, ErrEmptyString\n", "\t}\n", "\tif !bytesHave0xPrefix(input[1:]) {\n", "\t\treturn nil, ErrMissingPrefix\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn nil, nil // empty strings are allowed\n" ], "file_path": "common/hexutil/json.go", "type": "replace", "edit_start_line_idx": 239 }
// Copyright 2015 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package tests import ( "bytes" "fmt" "io" "math/big" "strconv" "testing" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/logger/glog" "github.com/ethereum/go-ethereum/params" ) func RunVmTestWithReader(r io.Reader, skipTests []string) error { tests := make(map[string]VmTest) err := readJson(r, &tests) if err != nil { return err } if err != nil { return err } if err := runVmTests(tests, skipTests); err != nil { return err } return nil } type bconf struct { name string precomp bool jit bool } func BenchVmTest(p string, conf bconf, b *testing.B) error { tests := make(map[string]VmTest) err := readJsonFile(p, &tests) if err != nil { return err } test, ok := tests[conf.name] if !ok { return fmt.Errorf("test not found: %s", conf.name) } env := make(map[string]string) env["currentCoinbase"] = test.Env.CurrentCoinbase env["currentDifficulty"] = test.Env.CurrentDifficulty env["currentGasLimit"] = test.Env.CurrentGasLimit env["currentNumber"] = test.Env.CurrentNumber env["previousHash"] = test.Env.PreviousHash if n, ok := test.Env.CurrentTimestamp.(float64); ok { env["currentTimestamp"] = strconv.Itoa(int(n)) } else { env["currentTimestamp"] = test.Env.CurrentTimestamp.(string) } /* if conf.precomp { program := vm.NewProgram(test.code) err := vm.AttachProgram(program) if err != nil { return err } } */ b.ResetTimer() for i := 0; i < b.N; i++ { benchVmTest(test, env, b) } return nil } func benchVmTest(test VmTest, env map[string]string, b *testing.B) { b.StopTimer() db, _ := ethdb.NewMemDatabase() statedb := makePreState(db, test.Pre) b.StartTimer() RunVm(statedb, env, test.Exec) } func RunVmTest(p string, skipTests []string) error { tests := make(map[string]VmTest) err := readJsonFile(p, &tests) if err != nil { return err } if err := runVmTests(tests, skipTests); err != nil { return err } return nil } func runVmTests(tests map[string]VmTest, skipTests []string) error { skipTest := make(map[string]bool, len(skipTests)) for _, name := range skipTests { skipTest[name] = true } for name, test := range tests { if skipTest[name] /*|| name != "loop_stacklimit_1021"*/ { glog.Infoln("Skipping VM test", name) continue } if err := runVmTest(test); err != nil { return fmt.Errorf("%s %s", name, err.Error()) } glog.Infoln("VM test passed: ", name) //fmt.Println(string(statedb.Dump())) } return nil } func runVmTest(test VmTest) error { db, _ := ethdb.NewMemDatabase() statedb := makePreState(db, test.Pre) // XXX Yeah, yeah... env := make(map[string]string) env["currentCoinbase"] = test.Env.CurrentCoinbase env["currentDifficulty"] = test.Env.CurrentDifficulty env["currentGasLimit"] = test.Env.CurrentGasLimit env["currentNumber"] = test.Env.CurrentNumber env["previousHash"] = test.Env.PreviousHash if n, ok := test.Env.CurrentTimestamp.(float64); ok { env["currentTimestamp"] = strconv.Itoa(int(n)) } else { env["currentTimestamp"] = test.Env.CurrentTimestamp.(string) } var ( ret []byte gas *big.Int err error logs []*types.Log ) ret, logs, gas, err = RunVm(statedb, env, test.Exec) // Compare expected and actual return rexp := common.FromHex(test.Out) if !bytes.Equal(rexp, ret) { return fmt.Errorf("return failed. Expected %x, got %x\n", rexp, ret) } // Check gas usage if len(test.Gas) == 0 && err == nil { return fmt.Errorf("gas unspecified, indicating an error. VM returned (incorrectly) successful") } else { gexp := common.Big(test.Gas) if gexp.Cmp(gas) != 0 { return fmt.Errorf("gas failed. Expected %v, got %v\n", gexp, gas) } } // check post state for addr, account := range test.Post { obj := statedb.GetStateObject(common.HexToAddress(addr)) if obj == nil { continue } for addr, value := range account.Storage { v := statedb.GetState(obj.Address(), common.HexToHash(addr)) vexp := common.HexToHash(value) if v != vexp { return fmt.Errorf("(%x: %s) storage failed. Expected %x, got %x (%v %v)\n", obj.Address().Bytes()[0:4], addr, vexp, v, vexp.Big(), v.Big()) } } } // check logs if len(test.Logs) > 0 { lerr := checkLogs(test.Logs, logs) if lerr != nil { return lerr } } return nil } func RunVm(statedb *state.StateDB, env, exec map[string]string) ([]byte, []*types.Log, *big.Int, error) { chainConfig := &params.ChainConfig{ HomesteadBlock: params.MainNetHomesteadBlock, DAOForkBlock: params.MainNetDAOForkBlock, DAOForkSupport: true, } var ( to = common.HexToAddress(exec["address"]) from = common.HexToAddress(exec["caller"]) data = common.FromHex(exec["data"]) gas = common.Big(exec["gas"]) value = common.Big(exec["value"]) ) caller := statedb.GetOrNewStateObject(from) vm.PrecompiledContracts = make(map[common.Address]vm.PrecompiledContract) environment, _ := NewEVMEnvironment(true, chainConfig, statedb, env, exec) ret, err := environment.Call(caller, to, data, gas, value) return ret, statedb.Logs(), gas, err }
tests/vm_test_util.go
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.003834273898974061, 0.0003510313981678337, 0.00016890639381017536, 0.00017275393474847078, 0.0007349103107117116 ]
{ "id": 0, "code_window": [ "func checkJSON(input []byte) (raw []byte, err error) {\n", "\tif !isString(input) {\n", "\t\treturn nil, errNonString\n", "\t}\n", "\tif len(input) == 2 {\n", "\t\treturn nil, ErrEmptyString\n", "\t}\n", "\tif !bytesHave0xPrefix(input[1:]) {\n", "\t\treturn nil, ErrMissingPrefix\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn nil, nil // empty strings are allowed\n" ], "file_path": "common/hexutil/json.go", "type": "replace", "edit_start_line_idx": 239 }
/********************************************************************** * Copyright (c) 2015 Andrew Poelstra * * Distributed under the MIT software license, see the accompanying * * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ #ifndef _SECP256K1_ECMULT_CONST_ #define _SECP256K1_ECMULT_CONST_ #include "scalar.h" #include "group.h" static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *q); #endif
crypto/secp256k1/libsecp256k1/src/ecmult_const.h
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.00017402069352101535, 0.00017019717779476196, 0.00016637366206850857, 0.00017019717779476196, 0.00000382351572625339 ]
{ "id": 1, "code_window": [ "\t\treturn nil, errNonString\n", "\t}\n", "\tinput = input[1 : len(input)-1]\n", "\tif len(input) == 0 {\n", "\t\treturn nil, ErrEmptyString\n", "\t}\n", "\tif !bytesHave0xPrefix(input) {\n", "\t\treturn nil, ErrMissingPrefix\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn nil, nil // empty strings are allowed\n" ], "file_path": "common/hexutil/json.go", "type": "replace", "edit_start_line_idx": 257 }
// Copyright 2016 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package hexutil import ( "encoding/hex" "errors" "fmt" "math/big" "strconv" ) var ( jsonNull = []byte("null") jsonZero = []byte(`"0x0"`) errNonString = errors.New("cannot unmarshal non-string as hex data") errNegativeBigInt = errors.New("hexutil.Big: can't marshal negative integer") ) // Bytes marshals/unmarshals as a JSON string with 0x prefix. // The empty slice marshals as "0x". type Bytes []byte // MarshalJSON implements json.Marshaler. func (b Bytes) MarshalJSON() ([]byte, error) { result := make([]byte, len(b)*2+4) copy(result, `"0x`) hex.Encode(result[3:], b) result[len(result)-1] = '"' return result, nil } // UnmarshalJSON implements json.Unmarshaler. func (b *Bytes) UnmarshalJSON(input []byte) error { raw, err := checkJSON(input) if err != nil { return err } dec := make([]byte, len(raw)/2) if _, err = hex.Decode(dec, raw); err != nil { err = mapError(err) } else { *b = dec } return err } // String returns the hex encoding of b. func (b Bytes) String() string { return Encode(b) } // UnmarshalJSON decodes input as a JSON string with 0x prefix. The length of out // determines the required input length. This function is commonly used to implement the // UnmarshalJSON method for fixed-size types: // // type Foo [8]byte // // func (f *Foo) UnmarshalJSON(input []byte) error { // return hexutil.UnmarshalJSON("Foo", input, f[:]) // } func UnmarshalJSON(typname string, input, out []byte) error { raw, err := checkJSON(input) if err != nil { return err } if len(raw)/2 != len(out) { return fmt.Errorf("hex string has length %d, want %d for %s", len(raw), len(out)*2, typname) } // Pre-verify syntax before modifying out. for _, b := range raw { if decodeNibble(b) == badNibble { return ErrSyntax } } hex.Decode(out, raw) return nil } // Big marshals/unmarshals as a JSON string with 0x prefix. The zero value marshals as // "0x0". Negative integers are not supported at this time. Attempting to marshal them // will return an error. type Big big.Int // MarshalJSON implements json.Marshaler. func (b *Big) MarshalJSON() ([]byte, error) { if b == nil { return jsonNull, nil } bigint := (*big.Int)(b) if bigint.Sign() == -1 { return nil, errNegativeBigInt } nbits := bigint.BitLen() if nbits == 0 { return jsonZero, nil } enc := make([]byte, 3, (nbits/8)*2+4) copy(enc, `"0x`) for i := len(bigint.Bits()) - 1; i >= 0; i-- { enc = strconv.AppendUint(enc, uint64(bigint.Bits()[i]), 16) } enc = append(enc, '"') return enc, nil } // UnmarshalJSON implements json.Unmarshaler. func (b *Big) UnmarshalJSON(input []byte) error { raw, err := checkNumberJSON(input) if err != nil { return err } words := make([]big.Word, len(raw)/bigWordNibbles+1) end := len(raw) for i := range words { start := end - bigWordNibbles if start < 0 { start = 0 } for ri := start; ri < end; ri++ { nib := decodeNibble(raw[ri]) if nib == badNibble { return ErrSyntax } words[i] *= 16 words[i] += big.Word(nib) } end = start } var dec big.Int dec.SetBits(words) *b = (Big)(dec) return nil } // ToInt converts b to a big.Int. func (b *Big) ToInt() *big.Int { return (*big.Int)(b) } // String returns the hex encoding of b. func (b *Big) String() string { return EncodeBig(b.ToInt()) } // Uint64 marshals/unmarshals as a JSON string with 0x prefix. // The zero value marshals as "0x0". type Uint64 uint64 // MarshalJSON implements json.Marshaler. func (b Uint64) MarshalJSON() ([]byte, error) { buf := make([]byte, 3, 12) copy(buf, `"0x`) buf = strconv.AppendUint(buf, uint64(b), 16) buf = append(buf, '"') return buf, nil } // UnmarshalJSON implements json.Unmarshaler. func (b *Uint64) UnmarshalJSON(input []byte) error { raw, err := checkNumberJSON(input) if err != nil { return err } if len(raw) > 16 { return ErrUint64Range } var dec uint64 for _, byte := range raw { nib := decodeNibble(byte) if nib == badNibble { return ErrSyntax } dec *= 16 dec += uint64(nib) } *b = Uint64(dec) return nil } // String returns the hex encoding of b. func (b Uint64) String() string { return EncodeUint64(uint64(b)) } // Uint marshals/unmarshals as a JSON string with 0x prefix. // The zero value marshals as "0x0". type Uint uint // MarshalJSON implements json.Marshaler. func (b Uint) MarshalJSON() ([]byte, error) { return Uint64(b).MarshalJSON() } // UnmarshalJSON implements json.Unmarshaler. func (b *Uint) UnmarshalJSON(input []byte) error { var u64 Uint64 err := u64.UnmarshalJSON(input) if err != nil { return err } else if u64 > Uint64(^uint(0)) { return ErrUintRange } *b = Uint(u64) return nil } // String returns the hex encoding of b. func (b Uint) String() string { return EncodeUint64(uint64(b)) } func isString(input []byte) bool { return len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"' } func bytesHave0xPrefix(input []byte) bool { return len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X') } func checkJSON(input []byte) (raw []byte, err error) { if !isString(input) { return nil, errNonString } if len(input) == 2 { return nil, ErrEmptyString } if !bytesHave0xPrefix(input[1:]) { return nil, ErrMissingPrefix } input = input[3 : len(input)-1] if len(input)%2 != 0 { return nil, ErrOddLength } return input, nil } func checkNumberJSON(input []byte) (raw []byte, err error) { if !isString(input) { return nil, errNonString } input = input[1 : len(input)-1] if len(input) == 0 { return nil, ErrEmptyString } if !bytesHave0xPrefix(input) { return nil, ErrMissingPrefix } input = input[2:] if len(input) == 0 { return nil, ErrEmptyNumber } if len(input) > 1 && input[0] == '0' { return nil, ErrLeadingZero } return input, nil }
common/hexutil/json.go
1
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.9981979727745056, 0.14250889420509338, 0.00016344506002496928, 0.0009592033457010984, 0.3399401009082794 ]
{ "id": 1, "code_window": [ "\t\treturn nil, errNonString\n", "\t}\n", "\tinput = input[1 : len(input)-1]\n", "\tif len(input) == 0 {\n", "\t\treturn nil, ErrEmptyString\n", "\t}\n", "\tif !bytesHave0xPrefix(input) {\n", "\t\treturn nil, ErrMissingPrefix\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn nil, nil // empty strings are allowed\n" ], "file_path": "common/hexutil/json.go", "type": "replace", "edit_start_line_idx": 257 }
{ "randomStatetest" : { "env" : { "currentCoinbase" : "945304eb96065b2a98b57a48a06ae28d285a71b5", "currentDifficulty" : "0x051d6a3cd647", "currentGasLimit" : "0x7fffffffffffffff", "currentNumber" : "0x00", "currentTimestamp" : "0x01", "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6" }, "logs" : [ ], "out" : "0x", "post" : { "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { "balance" : "0x462204c5", "code" : "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000000000000000000000000000000000000000007f000000000000000000000000945304eb96065b2a98b57a48a06ae28d285a71b57f000000000000000000000000ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000000000000000000000000000000000000000017f000000000000000000000000945304eb96065b2a98b57a48a06ae28d285a71b56f108fa27475689e44993a528752a152335955", "nonce" : "0x00", "storage" : { "0x00" : "0x108fa27475689e44993a528752a15233" } }, "945304eb96065b2a98b57a48a06ae28d285a71b5" : { "balance" : "0xc10d", "code" : "0x6000355415600957005b60203560003555", "nonce" : "0x00", "storage" : { } }, "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { "balance" : "0x0de0b6b361413a5c", "code" : "0x", "nonce" : "0x01", "storage" : { } } }, "postStateRoot" : "8fe48b64e997e6f8b1c8c85c33a610d5496af7b64e0dee5b709bed7d5486a8ae", "pre" : { "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { "balance" : "0x00", "code" : "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000000000000000000000000000000000000000007f000000000000000000000000945304eb96065b2a98b57a48a06ae28d285a71b57f000000000000000000000000ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000000000000000000000000000000000000000017f000000000000000000000000945304eb96065b2a98b57a48a06ae28d285a71b56f108fa27475689e44993a528752a152335955", "nonce" : "0x00", "storage" : { } }, "945304eb96065b2a98b57a48a06ae28d285a71b5" : { "balance" : "0x2e", "code" : "0x6000355415600957005b60203560003555", "nonce" : "0x00", "storage" : { } }, "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { "balance" : "0x0de0b6b3a7640000", "code" : "0x", "nonce" : "0x00", "storage" : { } } }, "transaction" : { "data" : "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000000000000000000000000000000000000000007f000000000000000000000000945304eb96065b2a98b57a48a06ae28d285a71b57f000000000000000000000000ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000000000000000000000000000000000000000017f000000000000000000000000945304eb96065b2a98b57a48a06ae28d285a71b56f108fa27475689e44993a528752a1523359", "gasLimit" : "0x2d195619", "gasPrice" : "0x01", "nonce" : "0x00", "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", "value" : "0x462204c5" } } }
tests/files/StateTests/RandomTests/st201503181547GO.json
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.00017676351126283407, 0.00016744836466386914, 0.00016490419511683285, 0.00016599723312538117, 0.0000036766323319170624 ]
{ "id": 1, "code_window": [ "\t\treturn nil, errNonString\n", "\t}\n", "\tinput = input[1 : len(input)-1]\n", "\tif len(input) == 0 {\n", "\t\treturn nil, ErrEmptyString\n", "\t}\n", "\tif !bytesHave0xPrefix(input) {\n", "\t\treturn nil, ErrMissingPrefix\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn nil, nil // empty strings are allowed\n" ], "file_path": "common/hexutil/json.go", "type": "replace", "edit_start_line_idx": 257 }
// Copyright 2016 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package types import ( "crypto/ecdsa" "errors" "fmt" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/params" ) var ErrInvalidChainId = errors.New("invalid chaid id for signer") // sigCache is used to cache the derived sender and contains // the signer used to derive it. type sigCache struct { signer Signer from common.Address } // MakeSigner returns a Signer based on the given chain config and block number. func MakeSigner(config *params.ChainConfig, blockNumber *big.Int) Signer { var signer Signer switch { case config.IsEIP155(blockNumber): signer = NewEIP155Signer(config.ChainId) case config.IsHomestead(blockNumber): signer = HomesteadSigner{} default: signer = FrontierSigner{} } return signer } // SignTx signs the transaction using the given signer and private key func SignTx(tx *Transaction, s Signer, prv *ecdsa.PrivateKey) (*Transaction, error) { h := s.Hash(tx) sig, err := crypto.Sign(h[:], prv) if err != nil { return nil, err } return s.WithSignature(tx, sig) } // Sender derives the sender from the tx using the signer derivation // functions. // Sender returns the address derived from the signature (V, R, S) using secp256k1 // elliptic curve and an error if it failed deriving or upon an incorrect // signature. // // Sender may cache the address, allowing it to be used regardless of // signing method. The cache is invalidated if the cached signer does // not match the signer used in the current call. func Sender(signer Signer, tx *Transaction) (common.Address, error) { if sc := tx.from.Load(); sc != nil { sigCache := sc.(sigCache) // If the signer used to derive from in a previous // call is not the same as used current, invalidate // the cache. if sigCache.signer.Equal(signer) { return sigCache.from, nil } } pubkey, err := signer.PublicKey(tx) if err != nil { return common.Address{}, err } var addr common.Address copy(addr[:], crypto.Keccak256(pubkey[1:])[12:]) tx.from.Store(sigCache{signer: signer, from: addr}) return addr, nil } type Signer interface { // Hash returns the rlp encoded hash for signatures Hash(tx *Transaction) common.Hash // PubilcKey returns the public key derived from the signature PublicKey(tx *Transaction) ([]byte, error) // WithSignature returns a copy of the transaction with the given signature. // The signature must be encoded in [R || S || V] format where V is 0 or 1. WithSignature(tx *Transaction, sig []byte) (*Transaction, error) // Checks for equality on the signers Equal(Signer) bool } // EIP155Transaction implements TransactionInterface using the // EIP155 rules type EIP155Signer struct { HomesteadSigner chainId, chainIdMul *big.Int } func NewEIP155Signer(chainId *big.Int) EIP155Signer { return EIP155Signer{ chainId: chainId, chainIdMul: new(big.Int).Mul(chainId, big.NewInt(2)), } } func (s EIP155Signer) Equal(s2 Signer) bool { eip155, ok := s2.(EIP155Signer) return ok && eip155.chainId.Cmp(s.chainId) == 0 } func (s EIP155Signer) PublicKey(tx *Transaction) ([]byte, error) { // if the transaction is not protected fall back to homestead signer if !tx.Protected() { return (HomesteadSigner{}).PublicKey(tx) } if tx.ChainId().Cmp(s.chainId) != 0 { return nil, ErrInvalidChainId } V := byte(new(big.Int).Sub(tx.data.V, s.chainIdMul).Uint64() - 35) if !crypto.ValidateSignatureValues(V, tx.data.R, tx.data.S, true) { return nil, ErrInvalidSig } // encode the signature in uncompressed format R, S := tx.data.R.Bytes(), tx.data.S.Bytes() sig := make([]byte, 65) copy(sig[32-len(R):32], R) copy(sig[64-len(S):64], S) sig[64] = V // recover the public key from the signature hash := s.Hash(tx) pub, err := crypto.Ecrecover(hash[:], sig) if err != nil { return nil, err } if len(pub) == 0 || pub[0] != 4 { return nil, errors.New("invalid public key") } return pub, nil } // WithSignature returns a new transaction with the given signature. This signature // needs to be in the [R || S || V] format where V is 0 or 1. func (s EIP155Signer) WithSignature(tx *Transaction, sig []byte) (*Transaction, error) { if len(sig) != 65 { panic(fmt.Sprintf("wrong size for snature: got %d, want 65", len(sig))) } cpy := &Transaction{data: tx.data} cpy.data.R = new(big.Int).SetBytes(sig[:32]) cpy.data.S = new(big.Int).SetBytes(sig[32:64]) cpy.data.V = new(big.Int).SetBytes([]byte{sig[64]}) if s.chainId.BitLen() > 0 { cpy.data.V = big.NewInt(int64(sig[64] + 35)) cpy.data.V.Add(cpy.data.V, s.chainIdMul) } return cpy, nil } // Hash returns the hash to be signed by the sender. // It does not uniquely identify the transaction. func (s EIP155Signer) Hash(tx *Transaction) common.Hash { return rlpHash([]interface{}{ tx.data.AccountNonce, tx.data.Price, tx.data.GasLimit, tx.data.Recipient, tx.data.Amount, tx.data.Payload, s.chainId, uint(0), uint(0), }) } // HomesteadTransaction implements TransactionInterface using the // homestead rules. type HomesteadSigner struct{ FrontierSigner } func (s HomesteadSigner) Equal(s2 Signer) bool { _, ok := s2.(HomesteadSigner) return ok } // WithSignature returns a new transaction with the given signature. This signature // needs to be in the [R || S || V] format where V is 0 or 1. func (hs HomesteadSigner) WithSignature(tx *Transaction, sig []byte) (*Transaction, error) { if len(sig) != 65 { panic(fmt.Sprintf("wrong size for snature: got %d, want 65", len(sig))) } cpy := &Transaction{data: tx.data} cpy.data.R = new(big.Int).SetBytes(sig[:32]) cpy.data.S = new(big.Int).SetBytes(sig[32:64]) cpy.data.V = new(big.Int).SetBytes([]byte{sig[64] + 27}) return cpy, nil } func (hs HomesteadSigner) PublicKey(tx *Transaction) ([]byte, error) { if tx.data.V.BitLen() > 8 { return nil, ErrInvalidSig } V := byte(tx.data.V.Uint64() - 27) if !crypto.ValidateSignatureValues(V, tx.data.R, tx.data.S, true) { return nil, ErrInvalidSig } // encode the snature in uncompressed format r, s := tx.data.R.Bytes(), tx.data.S.Bytes() sig := make([]byte, 65) copy(sig[32-len(r):32], r) copy(sig[64-len(s):64], s) sig[64] = V // recover the public key from the snature hash := hs.Hash(tx) pub, err := crypto.Ecrecover(hash[:], sig) if err != nil { return nil, err } if len(pub) == 0 || pub[0] != 4 { return nil, errors.New("invalid public key") } return pub, nil } type FrontierSigner struct{} func (s FrontierSigner) Equal(s2 Signer) bool { _, ok := s2.(FrontierSigner) return ok } // WithSignature returns a new transaction with the given signature. This signature // needs to be in the [R || S || V] format where V is 0 or 1. func (fs FrontierSigner) WithSignature(tx *Transaction, sig []byte) (*Transaction, error) { if len(sig) != 65 { panic(fmt.Sprintf("wrong size for snature: got %d, want 65", len(sig))) } cpy := &Transaction{data: tx.data} cpy.data.R = new(big.Int).SetBytes(sig[:32]) cpy.data.S = new(big.Int).SetBytes(sig[32:64]) cpy.data.V = new(big.Int).SetBytes([]byte{sig[64] + 27}) return cpy, nil } // Hash returns the hash to be sned by the sender. // It does not uniquely identify the transaction. func (fs FrontierSigner) Hash(tx *Transaction) common.Hash { return rlpHash([]interface{}{ tx.data.AccountNonce, tx.data.Price, tx.data.GasLimit, tx.data.Recipient, tx.data.Amount, tx.data.Payload, }) } func (fs FrontierSigner) PublicKey(tx *Transaction) ([]byte, error) { if tx.data.V.BitLen() > 8 { return nil, ErrInvalidSig } V := byte(tx.data.V.Uint64() - 27) if !crypto.ValidateSignatureValues(V, tx.data.R, tx.data.S, false) { return nil, ErrInvalidSig } // encode the snature in uncompressed format r, s := tx.data.R.Bytes(), tx.data.S.Bytes() sig := make([]byte, 65) copy(sig[32-len(r):32], r) copy(sig[64-len(s):64], s) sig[64] = V // recover the public key from the snature hash := fs.Hash(tx) pub, err := crypto.Ecrecover(hash[:], sig) if err != nil { return nil, err } if len(pub) == 0 || pub[0] != 4 { return nil, errors.New("invalid public key") } return pub, nil } // deriveChainId derives the chain id from the given v parameter func deriveChainId(v *big.Int) *big.Int { if v.BitLen() <= 64 { v := v.Uint64() if v == 27 || v == 28 { return new(big.Int) } return new(big.Int).SetUint64((v - 35) / 2) } v = new(big.Int).Sub(v, big.NewInt(35)) return v.Div(v, big.NewInt(2)) }
core/types/transaction_signing.go
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.0007629439351148903, 0.0002044210268650204, 0.0001638281246414408, 0.00017125552403740585, 0.00010869392281165347 ]
{ "id": 1, "code_window": [ "\t\treturn nil, errNonString\n", "\t}\n", "\tinput = input[1 : len(input)-1]\n", "\tif len(input) == 0 {\n", "\t\treturn nil, ErrEmptyString\n", "\t}\n", "\tif !bytesHave0xPrefix(input) {\n", "\t\treturn nil, ErrMissingPrefix\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn nil, nil // empty strings are allowed\n" ], "file_path": "common/hexutil/json.go", "type": "replace", "edit_start_line_idx": 257 }
Pod::Spec.new do |spec| spec.name = 'Geth' spec.version = '{{.Version}}' spec.license = { :type => 'GNU Lesser General Public License, Version 3.0' } spec.homepage = 'https://github.com/ethereum/go-ethereum' spec.authors = { {{range .Contributors}} '{{.Name}}' => '{{.Email}}',{{end}} } spec.summary = 'iOS Ethereum Client' spec.source = { :git => 'https://github.com/ethereum/go-ethereum.git', :commit => '{{.Commit}}' } spec.platform = :ios spec.ios.deployment_target = '9.0' spec.ios.vendored_frameworks = 'Frameworks/Geth.framework' spec.prepare_command = <<-CMD curl https://gethstore.blob.core.windows.net/builds/{{.Archive}}.tar.gz | tar -xvz mkdir Frameworks mv {{.Archive}}/Geth.framework Frameworks rm -rf {{.Archive}} CMD end
build/pod.podspec
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.0001777791912900284, 0.00017429717991035432, 0.0001714665413601324, 0.00017364576342515647, 0.0000026179673113801982 ]
{ "id": 2, "code_window": [ "var unmarshalBytesTests = []unmarshalTest{\n", "\t// invalid encoding\n", "\t{input: \"\", wantErr: errNonString},\n", "\t{input: \"null\", wantErr: errNonString},\n", "\t{input: \"10\", wantErr: errNonString},\n", "\t{input: `\"\"`, wantErr: ErrEmptyString},\n", "\t{input: `\"0\"`, wantErr: ErrMissingPrefix},\n", "\t{input: `\"0x0\"`, wantErr: ErrOddLength},\n", "\t{input: `\"0xxx\"`, wantErr: ErrSyntax},\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "common/hexutil/json_test.go", "type": "replace", "edit_start_line_idx": 62 }
// Copyright 2016 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package hexutil import ( "bytes" "encoding/hex" "math/big" "testing" ) func checkError(t *testing.T, input string, got, want error) bool { if got == nil { if want != nil { t.Errorf("input %s: got no error, want %q", input, want) return false } return true } if want == nil { t.Errorf("input %s: unexpected error %q", input, got) } else if got.Error() != want.Error() { t.Errorf("input %s: got error %q, want %q", input, got, want) } return false } func referenceBig(s string) *big.Int { b, ok := new(big.Int).SetString(s, 16) if !ok { panic("invalid") } return b } func referenceBytes(s string) []byte { b, err := hex.DecodeString(s) if err != nil { panic(err) } return b } var unmarshalBytesTests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x0"`, wantErr: ErrOddLength}, {input: `"0xxx"`, wantErr: ErrSyntax}, {input: `"0x01zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x"`, want: referenceBytes("")}, {input: `"0x02"`, want: referenceBytes("02")}, {input: `"0X02"`, want: referenceBytes("02")}, {input: `"0xffffffffff"`, want: referenceBytes("ffffffffff")}, { input: `"0xffffffffffffffffffffffffffffffffffff"`, want: referenceBytes("ffffffffffffffffffffffffffffffffffff"), }, } func TestUnmarshalBytes(t *testing.T) { for _, test := range unmarshalBytesTests { var v Bytes err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if !bytes.Equal(test.want.([]byte), []byte(v)) { t.Errorf("input %s: value mismatch: got %x, want %x", test.input, &v, test.want) continue } } } func BenchmarkUnmarshalBytes(b *testing.B) { input := []byte(`"0x123456789abcdef123456789abcdef"`) for i := 0; i < b.N; i++ { var v Bytes if err := v.UnmarshalJSON(input); err != nil { b.Fatal(err) } } } func TestMarshalBytes(t *testing.T) { for _, test := range encodeBytesTests { in := test.input.([]byte) out, err := Bytes(in).MarshalJSON() if err != nil { t.Errorf("%x: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%x: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := Bytes(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } } var unmarshalBigTests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x"`, wantErr: ErrEmptyNumber}, {input: `"0x01"`, wantErr: ErrLeadingZero}, {input: `"0xx"`, wantErr: ErrSyntax}, {input: `"0x1zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x0"`, want: big.NewInt(0)}, {input: `"0x2"`, want: big.NewInt(0x2)}, {input: `"0x2F2"`, want: big.NewInt(0x2f2)}, {input: `"0X2F2"`, want: big.NewInt(0x2f2)}, {input: `"0x1122aaff"`, want: big.NewInt(0x1122aaff)}, {input: `"0xbBb"`, want: big.NewInt(0xbbb)}, {input: `"0xfffffffff"`, want: big.NewInt(0xfffffffff)}, { input: `"0x112233445566778899aabbccddeeff"`, want: referenceBig("112233445566778899aabbccddeeff"), }, { input: `"0xffffffffffffffffffffffffffffffffffff"`, want: referenceBig("ffffffffffffffffffffffffffffffffffff"), }, } func TestUnmarshalBig(t *testing.T) { for _, test := range unmarshalBigTests { var v Big err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if test.want != nil && test.want.(*big.Int).Cmp((*big.Int)(&v)) != 0 { t.Errorf("input %s: value mismatch: got %x, want %x", test.input, (*big.Int)(&v), test.want) continue } } } func BenchmarkUnmarshalBig(b *testing.B) { input := []byte(`"0x123456789abcdef123456789abcdef"`) for i := 0; i < b.N; i++ { var v Big if err := v.UnmarshalJSON(input); err != nil { b.Fatal(err) } } } func TestMarshalBig(t *testing.T) { for _, test := range encodeBigTests { in := test.input.(*big.Int) out, err := (*Big)(in).MarshalJSON() if err != nil { t.Errorf("%d: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%d: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := (*Big)(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } } var unmarshalUint64Tests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x"`, wantErr: ErrEmptyNumber}, {input: `"0x01"`, wantErr: ErrLeadingZero}, {input: `"0xfffffffffffffffff"`, wantErr: ErrUint64Range}, {input: `"0xx"`, wantErr: ErrSyntax}, {input: `"0x1zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x0"`, want: uint64(0)}, {input: `"0x2"`, want: uint64(0x2)}, {input: `"0x2F2"`, want: uint64(0x2f2)}, {input: `"0X2F2"`, want: uint64(0x2f2)}, {input: `"0x1122aaff"`, want: uint64(0x1122aaff)}, {input: `"0xbbb"`, want: uint64(0xbbb)}, {input: `"0xffffffffffffffff"`, want: uint64(0xffffffffffffffff)}, } func TestUnmarshalUint64(t *testing.T) { for _, test := range unmarshalUint64Tests { var v Uint64 err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if uint64(v) != test.want.(uint64) { t.Errorf("input %s: value mismatch: got %d, want %d", test.input, v, test.want) continue } } } func BenchmarkUnmarshalUint64(b *testing.B) { input := []byte(`"0x123456789abcdf"`) for i := 0; i < b.N; i++ { var v Uint64 v.UnmarshalJSON(input) } } func TestMarshalUint64(t *testing.T) { for _, test := range encodeUint64Tests { in := test.input.(uint64) out, err := Uint64(in).MarshalJSON() if err != nil { t.Errorf("%d: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%d: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := (Uint64)(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } }
common/hexutil/json_test.go
1
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.998496413230896, 0.1294110119342804, 0.00016297833644784987, 0.0016033956781029701, 0.29089051485061646 ]
{ "id": 2, "code_window": [ "var unmarshalBytesTests = []unmarshalTest{\n", "\t// invalid encoding\n", "\t{input: \"\", wantErr: errNonString},\n", "\t{input: \"null\", wantErr: errNonString},\n", "\t{input: \"10\", wantErr: errNonString},\n", "\t{input: `\"\"`, wantErr: ErrEmptyString},\n", "\t{input: `\"0\"`, wantErr: ErrMissingPrefix},\n", "\t{input: `\"0x0\"`, wantErr: ErrOddLength},\n", "\t{input: `\"0xxx\"`, wantErr: ErrSyntax},\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "common/hexutil/json_test.go", "type": "replace", "edit_start_line_idx": 62 }
// Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_netbsd.go // +build arm,netbsd package unix const ( sizeofPtr = 0x4 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x4 sizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int32 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int32 Pad_cgo_0 [4]byte } type Timeval struct { Sec int64 Usec int32 Pad_cgo_0 [4]byte } type Rusage struct { Utime Timeval Stime Timeval Maxrss int32 Ixrss int32 Idrss int32 Isrss int32 Minflt int32 Majflt int32 Nswap int32 Inblock int32 Oublock int32 Msgsnd int32 Msgrcv int32 Nsignals int32 Nvcsw int32 Nivcsw int32 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev uint64 Mode uint32 Pad_cgo_0 [4]byte Ino uint64 Nlink uint32 Uid uint32 Gid uint32 Pad_cgo_1 [4]byte Rdev uint64 Atimespec Timespec Mtimespec Timespec Ctimespec Timespec Birthtimespec Timespec Size int64 Blocks int64 Blksize uint32 Flags uint32 Gen uint32 Spare [2]uint32 Pad_cgo_2 [4]byte } type Statfs_t [0]byte type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 } type Dirent struct { Fileno uint64 Reclen uint16 Namlen uint16 Type uint8 Name [512]int8 Pad_cgo_0 [3]byte } type Fsid struct { X__fsid_val [2]int32 } type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [12]int8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint32 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Iov *Iovec Iovlen int32 Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x14 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x1c SizeofCmsghdr = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_TRACEME = 0x0 PTRACE_CONT = 0x7 PTRACE_KILL = 0x8 ) type Kevent_t struct { Ident uint32 Filter uint32 Flags uint32 Fflags uint32 Data int64 Udata int32 Pad_cgo_0 [4]byte } type FdSet struct { Bits [8]uint32 } const ( SizeofIfMsghdr = 0x98 SizeofIfData = 0x88 SizeofIfaMsghdr = 0x18 SizeofIfAnnounceMsghdr = 0x18 SizeofRtMsghdr = 0x78 SizeofRtMetrics = 0x50 ) type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Data IfData } type IfData struct { Type uint8 Addrlen uint8 Hdrlen uint8 Pad_cgo_0 [1]byte Link_state int32 Mtu uint64 Metric uint64 Baudrate uint64 Ipackets uint64 Ierrors uint64 Opackets uint64 Oerrors uint64 Collisions uint64 Ibytes uint64 Obytes uint64 Imcasts uint64 Omcasts uint64 Iqdrops uint64 Noproto uint64 Lastchange Timespec } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Metric int32 Index uint16 Pad_cgo_0 [6]byte } type IfAnnounceMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Name [16]int8 What uint16 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Pad_cgo_0 [2]byte Flags int32 Addrs int32 Pid int32 Seq int32 Errno int32 Use int32 Inits int32 Pad_cgo_1 [4]byte Rmx RtMetrics } type RtMetrics struct { Locks uint64 Mtu uint64 Hopcount uint64 Recvpipe uint64 Sendpipe uint64 Ssthresh uint64 Rtt uint64 Rttvar uint64 Expire int64 Pksent int64 } type Mclpool [0]byte const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x80 SizeofBpfProgram = 0x8 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x14 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint64 Drop uint64 Capt uint64 Padding [13]uint64 } type BpfProgram struct { Len uint32 Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp BpfTimeval Caplen uint32 Datalen uint32 Hdrlen uint16 Pad_cgo_0 [2]byte } type BpfTimeval struct { Sec int32 Usec int32 } type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [20]uint8 Ispeed int32 Ospeed int32 } type Sysctlnode struct { Flags uint32 Num int32 Name [32]int8 Ver uint32 X__rsvd uint32 Un [16]byte X_sysctl_size [8]byte X_sysctl_func [8]byte X_sysctl_parent [8]byte X_sysctl_desc [8]byte }
vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.00022128869022708386, 0.00017171043145935982, 0.00016018998576328158, 0.00017005050904117525, 0.000010854105312319007 ]
{ "id": 2, "code_window": [ "var unmarshalBytesTests = []unmarshalTest{\n", "\t// invalid encoding\n", "\t{input: \"\", wantErr: errNonString},\n", "\t{input: \"null\", wantErr: errNonString},\n", "\t{input: \"10\", wantErr: errNonString},\n", "\t{input: `\"\"`, wantErr: ErrEmptyString},\n", "\t{input: `\"0\"`, wantErr: ErrMissingPrefix},\n", "\t{input: `\"0x0\"`, wantErr: ErrOddLength},\n", "\t{input: `\"0xxx\"`, wantErr: ErrSyntax},\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "common/hexutil/json_test.go", "type": "replace", "edit_start_line_idx": 62 }
// Copyright 2015 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. // Package fetcher contains the block announcement based synchronisation. package fetcher import ( "errors" "fmt" "math/rand" "time" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger/glog" "gopkg.in/karalabe/cookiejar.v2/collections/prque" ) const ( arriveTimeout = 500 * time.Millisecond // Time allowance before an announced block is explicitly requested gatherSlack = 100 * time.Millisecond // Interval used to collate almost-expired announces with fetches fetchTimeout = 5 * time.Second // Maximum allotted time to return an explicitly requested block maxUncleDist = 7 // Maximum allowed backward distance from the chain head maxQueueDist = 32 // Maximum allowed distance from the chain head to queue hashLimit = 256 // Maximum number of unique blocks a peer may have announced blockLimit = 64 // Maximum number of unique blocks a peer may have delivered ) var ( errTerminated = errors.New("terminated") ) // blockRetrievalFn is a callback type for retrieving a block from the local chain. type blockRetrievalFn func(common.Hash) *types.Block // headerRequesterFn is a callback type for sending a header retrieval request. type headerRequesterFn func(common.Hash) error // bodyRequesterFn is a callback type for sending a body retrieval request. type bodyRequesterFn func([]common.Hash) error // blockValidatorFn is a callback type to verify a block's header for fast propagation. type blockValidatorFn func(block *types.Block, parent *types.Block) error // blockBroadcasterFn is a callback type for broadcasting a block to connected peers. type blockBroadcasterFn func(block *types.Block, propagate bool) // chainHeightFn is a callback type to retrieve the current chain height. type chainHeightFn func() uint64 // chainInsertFn is a callback type to insert a batch of blocks into the local chain. type chainInsertFn func(types.Blocks) (int, error) // peerDropFn is a callback type for dropping a peer detected as malicious. type peerDropFn func(id string) // announce is the hash notification of the availability of a new block in the // network. type announce struct { hash common.Hash // Hash of the block being announced number uint64 // Number of the block being announced (0 = unknown | old protocol) header *types.Header // Header of the block partially reassembled (new protocol) time time.Time // Timestamp of the announcement origin string // Identifier of the peer originating the notification fetchHeader headerRequesterFn // [eth/62] Fetcher function to retrieve the header of an announced block fetchBodies bodyRequesterFn // [eth/62] Fetcher function to retrieve the body of an announced block } // headerFilterTask represents a batch of headers needing fetcher filtering. type headerFilterTask struct { headers []*types.Header // Collection of headers to filter time time.Time // Arrival time of the headers } // headerFilterTask represents a batch of block bodies (transactions and uncles) // needing fetcher filtering. type bodyFilterTask struct { transactions [][]*types.Transaction // Collection of transactions per block bodies uncles [][]*types.Header // Collection of uncles per block bodies time time.Time // Arrival time of the blocks' contents } // inject represents a schedules import operation. type inject struct { origin string block *types.Block } // Fetcher is responsible for accumulating block announcements from various peers // and scheduling them for retrieval. type Fetcher struct { // Various event channels notify chan *announce inject chan *inject blockFilter chan chan []*types.Block headerFilter chan chan *headerFilterTask bodyFilter chan chan *bodyFilterTask done chan common.Hash quit chan struct{} // Announce states announces map[string]int // Per peer announce counts to prevent memory exhaustion announced map[common.Hash][]*announce // Announced blocks, scheduled for fetching fetching map[common.Hash]*announce // Announced blocks, currently fetching fetched map[common.Hash][]*announce // Blocks with headers fetched, scheduled for body retrieval completing map[common.Hash]*announce // Blocks with headers, currently body-completing // Block cache queue *prque.Prque // Queue containing the import operations (block number sorted) queues map[string]int // Per peer block counts to prevent memory exhaustion queued map[common.Hash]*inject // Set of already queued blocks (to dedup imports) // Callbacks getBlock blockRetrievalFn // Retrieves a block from the local chain validateBlock blockValidatorFn // Checks if a block's headers have a valid proof of work broadcastBlock blockBroadcasterFn // Broadcasts a block to connected peers chainHeight chainHeightFn // Retrieves the current chain's height insertChain chainInsertFn // Injects a batch of blocks into the chain dropPeer peerDropFn // Drops a peer for misbehaving // Testing hooks announceChangeHook func(common.Hash, bool) // Method to call upon adding or deleting a hash from the announce list queueChangeHook func(common.Hash, bool) // Method to call upon adding or deleting a block from the import queue fetchingHook func([]common.Hash) // Method to call upon starting a block (eth/61) or header (eth/62) fetch completingHook func([]common.Hash) // Method to call upon starting a block body fetch (eth/62) importedHook func(*types.Block) // Method to call upon successful block import (both eth/61 and eth/62) } // New creates a block fetcher to retrieve blocks based on hash announcements. func New(getBlock blockRetrievalFn, validateBlock blockValidatorFn, broadcastBlock blockBroadcasterFn, chainHeight chainHeightFn, insertChain chainInsertFn, dropPeer peerDropFn) *Fetcher { return &Fetcher{ notify: make(chan *announce), inject: make(chan *inject), blockFilter: make(chan chan []*types.Block), headerFilter: make(chan chan *headerFilterTask), bodyFilter: make(chan chan *bodyFilterTask), done: make(chan common.Hash), quit: make(chan struct{}), announces: make(map[string]int), announced: make(map[common.Hash][]*announce), fetching: make(map[common.Hash]*announce), fetched: make(map[common.Hash][]*announce), completing: make(map[common.Hash]*announce), queue: prque.New(), queues: make(map[string]int), queued: make(map[common.Hash]*inject), getBlock: getBlock, validateBlock: validateBlock, broadcastBlock: broadcastBlock, chainHeight: chainHeight, insertChain: insertChain, dropPeer: dropPeer, } } // Start boots up the announcement based synchroniser, accepting and processing // hash notifications and block fetches until termination requested. func (f *Fetcher) Start() { go f.loop() } // Stop terminates the announcement based synchroniser, canceling all pending // operations. func (f *Fetcher) Stop() { close(f.quit) } // Notify announces the fetcher of the potential availability of a new block in // the network. func (f *Fetcher) Notify(peer string, hash common.Hash, number uint64, time time.Time, headerFetcher headerRequesterFn, bodyFetcher bodyRequesterFn) error { block := &announce{ hash: hash, number: number, time: time, origin: peer, fetchHeader: headerFetcher, fetchBodies: bodyFetcher, } select { case f.notify <- block: return nil case <-f.quit: return errTerminated } } // Enqueue tries to fill gaps the the fetcher's future import queue. func (f *Fetcher) Enqueue(peer string, block *types.Block) error { op := &inject{ origin: peer, block: block, } select { case f.inject <- op: return nil case <-f.quit: return errTerminated } } // FilterHeaders extracts all the headers that were explicitly requested by the fetcher, // returning those that should be handled differently. func (f *Fetcher) FilterHeaders(headers []*types.Header, time time.Time) []*types.Header { glog.V(logger.Detail).Infof("[eth/62] filtering %d headers", len(headers)) // Send the filter channel to the fetcher filter := make(chan *headerFilterTask) select { case f.headerFilter <- filter: case <-f.quit: return nil } // Request the filtering of the header list select { case filter <- &headerFilterTask{headers: headers, time: time}: case <-f.quit: return nil } // Retrieve the headers remaining after filtering select { case task := <-filter: return task.headers case <-f.quit: return nil } } // FilterBodies extracts all the block bodies that were explicitly requested by // the fetcher, returning those that should be handled differently. func (f *Fetcher) FilterBodies(transactions [][]*types.Transaction, uncles [][]*types.Header, time time.Time) ([][]*types.Transaction, [][]*types.Header) { glog.V(logger.Detail).Infof("[eth/62] filtering %d:%d bodies", len(transactions), len(uncles)) // Send the filter channel to the fetcher filter := make(chan *bodyFilterTask) select { case f.bodyFilter <- filter: case <-f.quit: return nil, nil } // Request the filtering of the body list select { case filter <- &bodyFilterTask{transactions: transactions, uncles: uncles, time: time}: case <-f.quit: return nil, nil } // Retrieve the bodies remaining after filtering select { case task := <-filter: return task.transactions, task.uncles case <-f.quit: return nil, nil } } // Loop is the main fetcher loop, checking and processing various notification // events. func (f *Fetcher) loop() { // Iterate the block fetching until a quit is requested fetchTimer := time.NewTimer(0) completeTimer := time.NewTimer(0) for { // Clean up any expired block fetches for hash, announce := range f.fetching { if time.Since(announce.time) > fetchTimeout { f.forgetHash(hash) } } // Import any queued blocks that could potentially fit height := f.chainHeight() for !f.queue.Empty() { op := f.queue.PopItem().(*inject) if f.queueChangeHook != nil { f.queueChangeHook(op.block.Hash(), false) } // If too high up the chain or phase, continue later number := op.block.NumberU64() if number > height+1 { f.queue.Push(op, -float32(op.block.NumberU64())) if f.queueChangeHook != nil { f.queueChangeHook(op.block.Hash(), true) } break } // Otherwise if fresh and still unknown, try and import hash := op.block.Hash() if number+maxUncleDist < height || f.getBlock(hash) != nil { f.forgetBlock(hash) continue } f.insert(op.origin, op.block) } // Wait for an outside event to occur select { case <-f.quit: // Fetcher terminating, abort all operations return case notification := <-f.notify: // A block was announced, make sure the peer isn't DOSing us propAnnounceInMeter.Mark(1) count := f.announces[notification.origin] + 1 if count > hashLimit { glog.V(logger.Debug).Infof("Peer %s: exceeded outstanding announces (%d)", notification.origin, hashLimit) propAnnounceDOSMeter.Mark(1) break } // If we have a valid block number, check that it's potentially useful if notification.number > 0 { if dist := int64(notification.number) - int64(f.chainHeight()); dist < -maxUncleDist || dist > maxQueueDist { glog.V(logger.Debug).Infof("[eth/62] Peer %s: discarded announcement #%d [%x…], distance %d", notification.origin, notification.number, notification.hash[:4], dist) propAnnounceDropMeter.Mark(1) break } } // All is well, schedule the announce if block's not yet downloading if _, ok := f.fetching[notification.hash]; ok { break } if _, ok := f.completing[notification.hash]; ok { break } f.announces[notification.origin] = count f.announced[notification.hash] = append(f.announced[notification.hash], notification) if f.announceChangeHook != nil && len(f.announced[notification.hash]) == 1 { f.announceChangeHook(notification.hash, true) } if len(f.announced) == 1 { f.rescheduleFetch(fetchTimer) } case op := <-f.inject: // A direct block insertion was requested, try and fill any pending gaps propBroadcastInMeter.Mark(1) f.enqueue(op.origin, op.block) case hash := <-f.done: // A pending import finished, remove all traces of the notification f.forgetHash(hash) f.forgetBlock(hash) case <-fetchTimer.C: // At least one block's timer ran out, check for needing retrieval request := make(map[string][]common.Hash) for hash, announces := range f.announced { if time.Since(announces[0].time) > arriveTimeout-gatherSlack { // Pick a random peer to retrieve from, reset all others announce := announces[rand.Intn(len(announces))] f.forgetHash(hash) // If the block still didn't arrive, queue for fetching if f.getBlock(hash) == nil { request[announce.origin] = append(request[announce.origin], hash) f.fetching[hash] = announce } } } // Send out all block header requests for peer, hashes := range request { if glog.V(logger.Detail) && len(hashes) > 0 { list := "[" for _, hash := range hashes { list += fmt.Sprintf("%x…, ", hash[:4]) } list = list[:len(list)-2] + "]" glog.V(logger.Detail).Infof("[eth/62] Peer %s: fetching headers %s", peer, list) } // Create a closure of the fetch and schedule in on a new thread fetchHeader, hashes := f.fetching[hashes[0]].fetchHeader, hashes go func() { if f.fetchingHook != nil { f.fetchingHook(hashes) } for _, hash := range hashes { headerFetchMeter.Mark(1) fetchHeader(hash) // Suboptimal, but protocol doesn't allow batch header retrievals } }() } // Schedule the next fetch if blocks are still pending f.rescheduleFetch(fetchTimer) case <-completeTimer.C: // At least one header's timer ran out, retrieve everything request := make(map[string][]common.Hash) for hash, announces := range f.fetched { // Pick a random peer to retrieve from, reset all others announce := announces[rand.Intn(len(announces))] f.forgetHash(hash) // If the block still didn't arrive, queue for completion if f.getBlock(hash) == nil { request[announce.origin] = append(request[announce.origin], hash) f.completing[hash] = announce } } // Send out all block body requests for peer, hashes := range request { if glog.V(logger.Detail) && len(hashes) > 0 { list := "[" for _, hash := range hashes { list += fmt.Sprintf("%x…, ", hash[:4]) } list = list[:len(list)-2] + "]" glog.V(logger.Detail).Infof("[eth/62] Peer %s: fetching bodies %s", peer, list) } // Create a closure of the fetch and schedule in on a new thread if f.completingHook != nil { f.completingHook(hashes) } bodyFetchMeter.Mark(int64(len(hashes))) go f.completing[hashes[0]].fetchBodies(hashes) } // Schedule the next fetch if blocks are still pending f.rescheduleComplete(completeTimer) case filter := <-f.headerFilter: // Headers arrived from a remote peer. Extract those that were explicitly // requested by the fetcher, and return everything else so it's delivered // to other parts of the system. var task *headerFilterTask select { case task = <-filter: case <-f.quit: return } headerFilterInMeter.Mark(int64(len(task.headers))) // Split the batch of headers into unknown ones (to return to the caller), // known incomplete ones (requiring body retrievals) and completed blocks. unknown, incomplete, complete := []*types.Header{}, []*announce{}, []*types.Block{} for _, header := range task.headers { hash := header.Hash() // Filter fetcher-requested headers from other synchronisation algorithms if announce := f.fetching[hash]; announce != nil && f.fetched[hash] == nil && f.completing[hash] == nil && f.queued[hash] == nil { // If the delivered header does not match the promised number, drop the announcer if header.Number.Uint64() != announce.number { glog.V(logger.Detail).Infof("[eth/62] Peer %s: invalid block number for [%x…]: announced %d, provided %d", announce.origin, header.Hash().Bytes()[:4], announce.number, header.Number.Uint64()) f.dropPeer(announce.origin) f.forgetHash(hash) continue } // Only keep if not imported by other means if f.getBlock(hash) == nil { announce.header = header announce.time = task.time // If the block is empty (header only), short circuit into the final import queue if header.TxHash == types.DeriveSha(types.Transactions{}) && header.UncleHash == types.CalcUncleHash([]*types.Header{}) { glog.V(logger.Detail).Infof("[eth/62] Peer %s: block #%d [%x…] empty, skipping body retrieval", announce.origin, header.Number.Uint64(), header.Hash().Bytes()[:4]) block := types.NewBlockWithHeader(header) block.ReceivedAt = task.time complete = append(complete, block) f.completing[hash] = announce continue } // Otherwise add to the list of blocks needing completion incomplete = append(incomplete, announce) } else { glog.V(logger.Detail).Infof("[eth/62] Peer %s: block #%d [%x…] already imported, discarding header", announce.origin, header.Number.Uint64(), header.Hash().Bytes()[:4]) f.forgetHash(hash) } } else { // Fetcher doesn't know about it, add to the return list unknown = append(unknown, header) } } headerFilterOutMeter.Mark(int64(len(unknown))) select { case filter <- &headerFilterTask{headers: unknown, time: task.time}: case <-f.quit: return } // Schedule the retrieved headers for body completion for _, announce := range incomplete { hash := announce.header.Hash() if _, ok := f.completing[hash]; ok { continue } f.fetched[hash] = append(f.fetched[hash], announce) if len(f.fetched) == 1 { f.rescheduleComplete(completeTimer) } } // Schedule the header-only blocks for import for _, block := range complete { if announce := f.completing[block.Hash()]; announce != nil { f.enqueue(announce.origin, block) } } case filter := <-f.bodyFilter: // Block bodies arrived, extract any explicitly requested blocks, return the rest var task *bodyFilterTask select { case task = <-filter: case <-f.quit: return } bodyFilterInMeter.Mark(int64(len(task.transactions))) blocks := []*types.Block{} for i := 0; i < len(task.transactions) && i < len(task.uncles); i++ { // Match up a body to any possible completion request matched := false for hash, announce := range f.completing { if f.queued[hash] == nil { txnHash := types.DeriveSha(types.Transactions(task.transactions[i])) uncleHash := types.CalcUncleHash(task.uncles[i]) if txnHash == announce.header.TxHash && uncleHash == announce.header.UncleHash { // Mark the body matched, reassemble if still unknown matched = true if f.getBlock(hash) == nil { block := types.NewBlockWithHeader(announce.header).WithBody(task.transactions[i], task.uncles[i]) block.ReceivedAt = task.time blocks = append(blocks, block) } else { f.forgetHash(hash) } } } } if matched { task.transactions = append(task.transactions[:i], task.transactions[i+1:]...) task.uncles = append(task.uncles[:i], task.uncles[i+1:]...) i-- continue } } bodyFilterOutMeter.Mark(int64(len(task.transactions))) select { case filter <- task: case <-f.quit: return } // Schedule the retrieved blocks for ordered import for _, block := range blocks { if announce := f.completing[block.Hash()]; announce != nil { f.enqueue(announce.origin, block) } } } } } // rescheduleFetch resets the specified fetch timer to the next announce timeout. func (f *Fetcher) rescheduleFetch(fetch *time.Timer) { // Short circuit if no blocks are announced if len(f.announced) == 0 { return } // Otherwise find the earliest expiring announcement earliest := time.Now() for _, announces := range f.announced { if earliest.After(announces[0].time) { earliest = announces[0].time } } fetch.Reset(arriveTimeout - time.Since(earliest)) } // rescheduleComplete resets the specified completion timer to the next fetch timeout. func (f *Fetcher) rescheduleComplete(complete *time.Timer) { // Short circuit if no headers are fetched if len(f.fetched) == 0 { return } // Otherwise find the earliest expiring announcement earliest := time.Now() for _, announces := range f.fetched { if earliest.After(announces[0].time) { earliest = announces[0].time } } complete.Reset(gatherSlack - time.Since(earliest)) } // enqueue schedules a new future import operation, if the block to be imported // has not yet been seen. func (f *Fetcher) enqueue(peer string, block *types.Block) { hash := block.Hash() // Ensure the peer isn't DOSing us count := f.queues[peer] + 1 if count > blockLimit { glog.V(logger.Debug).Infof("Peer %s: discarded block #%d [%x…], exceeded allowance (%d)", peer, block.NumberU64(), hash.Bytes()[:4], blockLimit) propBroadcastDOSMeter.Mark(1) f.forgetHash(hash) return } // Discard any past or too distant blocks if dist := int64(block.NumberU64()) - int64(f.chainHeight()); dist < -maxUncleDist || dist > maxQueueDist { glog.V(logger.Debug).Infof("Peer %s: discarded block #%d [%x…], distance %d", peer, block.NumberU64(), hash.Bytes()[:4], dist) propBroadcastDropMeter.Mark(1) f.forgetHash(hash) return } // Schedule the block for future importing if _, ok := f.queued[hash]; !ok { op := &inject{ origin: peer, block: block, } f.queues[peer] = count f.queued[hash] = op f.queue.Push(op, -float32(block.NumberU64())) if f.queueChangeHook != nil { f.queueChangeHook(op.block.Hash(), true) } if glog.V(logger.Debug) { glog.Infof("Peer %s: queued block #%d [%x…], total %v", peer, block.NumberU64(), hash.Bytes()[:4], f.queue.Size()) } } } // insert spawns a new goroutine to run a block insertion into the chain. If the // block's number is at the same height as the current import phase, if updates // the phase states accordingly. func (f *Fetcher) insert(peer string, block *types.Block) { hash := block.Hash() // Run the import on a new thread glog.V(logger.Debug).Infof("Peer %s: importing block #%d [%x…]", peer, block.NumberU64(), hash[:4]) go func() { defer func() { f.done <- hash }() // If the parent's unknown, abort insertion parent := f.getBlock(block.ParentHash()) if parent == nil { glog.V(logger.Debug).Infof("Peer %s: parent [%x…] of block #%d [%x…] unknown", peer, block.ParentHash().Bytes()[:4], block.NumberU64(), hash[:4]) return } // Quickly validate the header and propagate the block if it passes switch err := f.validateBlock(block, parent); err { case nil: // All ok, quickly propagate to our peers propBroadcastOutTimer.UpdateSince(block.ReceivedAt) go f.broadcastBlock(block, true) case core.BlockFutureErr: // Weird future block, don't fail, but neither propagate default: // Something went very wrong, drop the peer glog.V(logger.Debug).Infof("Peer %s: block #%d [%x…] verification failed: %v", peer, block.NumberU64(), hash[:4], err) f.dropPeer(peer) return } // Run the actual import and log any issues if _, err := f.insertChain(types.Blocks{block}); err != nil { glog.V(logger.Warn).Infof("Peer %s: block #%d [%x…] import failed: %v", peer, block.NumberU64(), hash[:4], err) return } // If import succeeded, broadcast the block propAnnounceOutTimer.UpdateSince(block.ReceivedAt) go f.broadcastBlock(block, false) // Invoke the testing hook if needed if f.importedHook != nil { f.importedHook(block) } }() } // forgetHash removes all traces of a block announcement from the fetcher's // internal state. func (f *Fetcher) forgetHash(hash common.Hash) { // Remove all pending announces and decrement DOS counters for _, announce := range f.announced[hash] { f.announces[announce.origin]-- if f.announces[announce.origin] == 0 { delete(f.announces, announce.origin) } } delete(f.announced, hash) if f.announceChangeHook != nil { f.announceChangeHook(hash, false) } // Remove any pending fetches and decrement the DOS counters if announce := f.fetching[hash]; announce != nil { f.announces[announce.origin]-- if f.announces[announce.origin] == 0 { delete(f.announces, announce.origin) } delete(f.fetching, hash) } // Remove any pending completion requests and decrement the DOS counters for _, announce := range f.fetched[hash] { f.announces[announce.origin]-- if f.announces[announce.origin] == 0 { delete(f.announces, announce.origin) } } delete(f.fetched, hash) // Remove any pending completions and decrement the DOS counters if announce := f.completing[hash]; announce != nil { f.announces[announce.origin]-- if f.announces[announce.origin] == 0 { delete(f.announces, announce.origin) } delete(f.completing, hash) } } // forgetBlock removes all traces of a queued block from the fetcher's internal // state. func (f *Fetcher) forgetBlock(hash common.Hash) { if insert := f.queued[hash]; insert != nil { f.queues[insert.origin]-- if f.queues[insert.origin] == 0 { delete(f.queues, insert.origin) } delete(f.queued, hash) } }
eth/fetcher/fetcher.go
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.0011285056825727224, 0.00019158754730597138, 0.00016084661183413118, 0.00016970337310340255, 0.0001292108790948987 ]
{ "id": 2, "code_window": [ "var unmarshalBytesTests = []unmarshalTest{\n", "\t// invalid encoding\n", "\t{input: \"\", wantErr: errNonString},\n", "\t{input: \"null\", wantErr: errNonString},\n", "\t{input: \"10\", wantErr: errNonString},\n", "\t{input: `\"\"`, wantErr: ErrEmptyString},\n", "\t{input: `\"0\"`, wantErr: ErrMissingPrefix},\n", "\t{input: `\"0x0\"`, wantErr: ErrOddLength},\n", "\t{input: `\"0xxx\"`, wantErr: ErrSyntax},\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "common/hexutil/json_test.go", "type": "replace", "edit_start_line_idx": 62 }
/********************************************************************** * Copyright (c) 2013, 2014 Pieter Wuille * * Distributed under the MIT software license, see the accompanying * * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ #ifndef _SECP256K1_NUM_REPR_ #define _SECP256K1_NUM_REPR_ #include <gmp.h> #define NUM_LIMBS ((256+GMP_NUMB_BITS-1)/GMP_NUMB_BITS) typedef struct { mp_limb_t data[2*NUM_LIMBS]; int neg; int limbs; } secp256k1_num; #endif
crypto/secp256k1/libsecp256k1/src/num_gmp.h
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.00017299891624134034, 0.000168876358657144, 0.00016249761392828077, 0.00017113251669798046, 0.000004574352715280838 ]
{ "id": 3, "code_window": [ "\t{input: `\"0x01zz01\"`, wantErr: ErrSyntax},\n", "\n", "\t// valid encoding\n", "\t{input: `\"0x\"`, want: referenceBytes(\"\")},\n", "\t{input: `\"0x02\"`, want: referenceBytes(\"02\")},\n", "\t{input: `\"0X02\"`, want: referenceBytes(\"02\")},\n", "\t{input: `\"0xffffffffff\"`, want: referenceBytes(\"ffffffffff\")},\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t{input: `\"\"`, want: referenceBytes(\"\")},\n" ], "file_path": "common/hexutil/json_test.go", "type": "add", "edit_start_line_idx": 69 }
// Copyright 2016 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package hexutil import ( "bytes" "encoding/hex" "math/big" "testing" ) func checkError(t *testing.T, input string, got, want error) bool { if got == nil { if want != nil { t.Errorf("input %s: got no error, want %q", input, want) return false } return true } if want == nil { t.Errorf("input %s: unexpected error %q", input, got) } else if got.Error() != want.Error() { t.Errorf("input %s: got error %q, want %q", input, got, want) } return false } func referenceBig(s string) *big.Int { b, ok := new(big.Int).SetString(s, 16) if !ok { panic("invalid") } return b } func referenceBytes(s string) []byte { b, err := hex.DecodeString(s) if err != nil { panic(err) } return b } var unmarshalBytesTests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x0"`, wantErr: ErrOddLength}, {input: `"0xxx"`, wantErr: ErrSyntax}, {input: `"0x01zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x"`, want: referenceBytes("")}, {input: `"0x02"`, want: referenceBytes("02")}, {input: `"0X02"`, want: referenceBytes("02")}, {input: `"0xffffffffff"`, want: referenceBytes("ffffffffff")}, { input: `"0xffffffffffffffffffffffffffffffffffff"`, want: referenceBytes("ffffffffffffffffffffffffffffffffffff"), }, } func TestUnmarshalBytes(t *testing.T) { for _, test := range unmarshalBytesTests { var v Bytes err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if !bytes.Equal(test.want.([]byte), []byte(v)) { t.Errorf("input %s: value mismatch: got %x, want %x", test.input, &v, test.want) continue } } } func BenchmarkUnmarshalBytes(b *testing.B) { input := []byte(`"0x123456789abcdef123456789abcdef"`) for i := 0; i < b.N; i++ { var v Bytes if err := v.UnmarshalJSON(input); err != nil { b.Fatal(err) } } } func TestMarshalBytes(t *testing.T) { for _, test := range encodeBytesTests { in := test.input.([]byte) out, err := Bytes(in).MarshalJSON() if err != nil { t.Errorf("%x: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%x: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := Bytes(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } } var unmarshalBigTests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x"`, wantErr: ErrEmptyNumber}, {input: `"0x01"`, wantErr: ErrLeadingZero}, {input: `"0xx"`, wantErr: ErrSyntax}, {input: `"0x1zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x0"`, want: big.NewInt(0)}, {input: `"0x2"`, want: big.NewInt(0x2)}, {input: `"0x2F2"`, want: big.NewInt(0x2f2)}, {input: `"0X2F2"`, want: big.NewInt(0x2f2)}, {input: `"0x1122aaff"`, want: big.NewInt(0x1122aaff)}, {input: `"0xbBb"`, want: big.NewInt(0xbbb)}, {input: `"0xfffffffff"`, want: big.NewInt(0xfffffffff)}, { input: `"0x112233445566778899aabbccddeeff"`, want: referenceBig("112233445566778899aabbccddeeff"), }, { input: `"0xffffffffffffffffffffffffffffffffffff"`, want: referenceBig("ffffffffffffffffffffffffffffffffffff"), }, } func TestUnmarshalBig(t *testing.T) { for _, test := range unmarshalBigTests { var v Big err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if test.want != nil && test.want.(*big.Int).Cmp((*big.Int)(&v)) != 0 { t.Errorf("input %s: value mismatch: got %x, want %x", test.input, (*big.Int)(&v), test.want) continue } } } func BenchmarkUnmarshalBig(b *testing.B) { input := []byte(`"0x123456789abcdef123456789abcdef"`) for i := 0; i < b.N; i++ { var v Big if err := v.UnmarshalJSON(input); err != nil { b.Fatal(err) } } } func TestMarshalBig(t *testing.T) { for _, test := range encodeBigTests { in := test.input.(*big.Int) out, err := (*Big)(in).MarshalJSON() if err != nil { t.Errorf("%d: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%d: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := (*Big)(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } } var unmarshalUint64Tests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x"`, wantErr: ErrEmptyNumber}, {input: `"0x01"`, wantErr: ErrLeadingZero}, {input: `"0xfffffffffffffffff"`, wantErr: ErrUint64Range}, {input: `"0xx"`, wantErr: ErrSyntax}, {input: `"0x1zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x0"`, want: uint64(0)}, {input: `"0x2"`, want: uint64(0x2)}, {input: `"0x2F2"`, want: uint64(0x2f2)}, {input: `"0X2F2"`, want: uint64(0x2f2)}, {input: `"0x1122aaff"`, want: uint64(0x1122aaff)}, {input: `"0xbbb"`, want: uint64(0xbbb)}, {input: `"0xffffffffffffffff"`, want: uint64(0xffffffffffffffff)}, } func TestUnmarshalUint64(t *testing.T) { for _, test := range unmarshalUint64Tests { var v Uint64 err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if uint64(v) != test.want.(uint64) { t.Errorf("input %s: value mismatch: got %d, want %d", test.input, v, test.want) continue } } } func BenchmarkUnmarshalUint64(b *testing.B) { input := []byte(`"0x123456789abcdf"`) for i := 0; i < b.N; i++ { var v Uint64 v.UnmarshalJSON(input) } } func TestMarshalUint64(t *testing.T) { for _, test := range encodeUint64Tests { in := test.input.(uint64) out, err := Uint64(in).MarshalJSON() if err != nil { t.Errorf("%d: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%d: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := (Uint64)(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } }
common/hexutil/json_test.go
1
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.13770326972007751, 0.00841501634567976, 0.00016410859825555235, 0.00023357506142929196, 0.02672940492630005 ]
{ "id": 3, "code_window": [ "\t{input: `\"0x01zz01\"`, wantErr: ErrSyntax},\n", "\n", "\t// valid encoding\n", "\t{input: `\"0x\"`, want: referenceBytes(\"\")},\n", "\t{input: `\"0x02\"`, want: referenceBytes(\"02\")},\n", "\t{input: `\"0X02\"`, want: referenceBytes(\"02\")},\n", "\t{input: `\"0xffffffffff\"`, want: referenceBytes(\"ffffffffff\")},\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t{input: `\"\"`, want: referenceBytes(\"\")},\n" ], "file_path": "common/hexutil/json_test.go", "type": "add", "edit_start_line_idx": 69 }
{ "randomStatetest" : { "env" : { "currentCoinbase" : "945304eb96065b2a98b57a48a06ae28d285a71b5", "currentDifficulty" : "0x051d6a3cd647", "currentGasLimit" : "0x7fffffffffffffff", "currentNumber" : "0x00", "currentTimestamp" : "0x01", "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6" }, "logs" : [ ], "out" : "0x", "post" : { "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { "balance" : "0x6bf5e61f", "code" : "0x7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe427f000000000000000000000000000000000000000000000000000000000000c3507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000000000000000000000000000000000000000c3507f000000000000000000000000945304eb96065b2a98b57a48a06ae28d285a71b57f00000000000000000000000000000000000000000000000000000000000000017f00000000000000000000000000000000000000000000000000000000000000006f7d41a29934035b748e96a3135b69645560005155", "nonce" : "0x00", "storage" : { "0x00" : "0x7d41a29934035b748e96a3135b696455" } }, "945304eb96065b2a98b57a48a06ae28d285a71b5" : { "balance" : "0xc099", "code" : "0x6000355415600957005b60203560003555", "nonce" : "0x00", "storage" : { } }, "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { "balance" : "0x0de0b6b33b6d5976", "code" : "0x", "nonce" : "0x01", "storage" : { } } }, "postStateRoot" : "49808120b60f2a2e9c0b3b90dd509f877f8582c764d88e8984c307a502667ad3", "pre" : { "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { "balance" : "0x00", "code" : "0x7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe427f000000000000000000000000000000000000000000000000000000000000c3507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000000000000000000000000000000000000000c3507f000000000000000000000000945304eb96065b2a98b57a48a06ae28d285a71b57f00000000000000000000000000000000000000000000000000000000000000017f00000000000000000000000000000000000000000000000000000000000000006f7d41a29934035b748e96a3135b69645560005155", "nonce" : "0x00", "storage" : { } }, "945304eb96065b2a98b57a48a06ae28d285a71b5" : { "balance" : "0x2e", "code" : "0x6000355415600957005b60203560003555", "nonce" : "0x00", "storage" : { } }, "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { "balance" : "0x0de0b6b3a7640000", "code" : "0x", "nonce" : "0x00", "storage" : { } } }, "transaction" : { "data" : "0x7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe427f000000000000000000000000000000000000000000000000000000000000c3507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000000000000000000000000000000000000000c3507f000000000000000000000000945304eb96065b2a98b57a48a06ae28d285a71b57f00000000000000000000000000000000000000000000000000000000000000017f00000000000000000000000000000000000000000000000000000000000000006f7d41a29934035b748e96a3135b6964", "gasLimit" : "0x607daefc", "gasPrice" : "0x01", "nonce" : "0x00", "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", "value" : "0x6bf5e61f" } } }
tests/files/StateTests/RandomTests/st201503181358GO.json
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.0005558424745686352, 0.00022146131959743798, 0.00016409890668001026, 0.00016697992396075279, 0.00012726294517051429 ]
{ "id": 3, "code_window": [ "\t{input: `\"0x01zz01\"`, wantErr: ErrSyntax},\n", "\n", "\t// valid encoding\n", "\t{input: `\"0x\"`, want: referenceBytes(\"\")},\n", "\t{input: `\"0x02\"`, want: referenceBytes(\"02\")},\n", "\t{input: `\"0X02\"`, want: referenceBytes(\"02\")},\n", "\t{input: `\"0xffffffffff\"`, want: referenceBytes(\"ffffffffff\")},\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t{input: `\"\"`, want: referenceBytes(\"\")},\n" ], "file_path": "common/hexutil/json_test.go", "type": "add", "edit_start_line_idx": 69 }
{ "randomStatetest" : { "env" : { "currentCoinbase" : "945304eb96065b2a98b57a48a06ae28d285a71b5", "currentDifficulty" : "0x051d6a3cd647", "currentGasLimit" : "0x7fffffffffffffff", "currentNumber" : "0x00", "currentTimestamp" : "0x01", "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6" }, "logs" : [ ], "out" : "0x", "post" : { "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { "balance" : "0x0de0b6b3a76586a0", "code" : "0x4142", "nonce" : "0x00", "storage" : { } }, "945304eb96065b2a98b57a48a06ae28d285a71b5" : { "balance" : "0x527e", "code" : "0x6000355415600957005b60203560003555", "nonce" : "0x00", "storage" : { } }, "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { "balance" : "0x0de0b6b3a7622710", "code" : "0x", "nonce" : "0x01", "storage" : { } } }, "postStateRoot" : "7397124f53f97e2feb584a04b7216775fcfe101d1460853b392ae38c671b4793", "pre" : { "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { "balance" : "0x0de0b6b3a7640000", "code" : "0x4142", "nonce" : "0x00", "storage" : { } }, "945304eb96065b2a98b57a48a06ae28d285a71b5" : { "balance" : "0x2e", "code" : "0x6000355415600957005b60203560003555", "nonce" : "0x00", "storage" : { } }, "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { "balance" : "0x0de0b6b3a7640000", "code" : "0x", "nonce" : "0x00", "storage" : { } } }, "transaction" : { "data" : "0x42", "gasLimit" : "0x061a80", "gasPrice" : "0x01", "nonce" : "0x00", "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", "value" : "0x0186a0" } } }
tests/files/StateTests/RandomTests/st201503130752PYTHON.json
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.00017558209947310388, 0.00016884083743207157, 0.00016441982006654143, 0.00016839144518598914, 0.0000035782331906375475 ]
{ "id": 3, "code_window": [ "\t{input: `\"0x01zz01\"`, wantErr: ErrSyntax},\n", "\n", "\t// valid encoding\n", "\t{input: `\"0x\"`, want: referenceBytes(\"\")},\n", "\t{input: `\"0x02\"`, want: referenceBytes(\"02\")},\n", "\t{input: `\"0X02\"`, want: referenceBytes(\"02\")},\n", "\t{input: `\"0xffffffffff\"`, want: referenceBytes(\"ffffffffff\")},\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t{input: `\"\"`, want: referenceBytes(\"\")},\n" ], "file_path": "common/hexutil/json_test.go", "type": "add", "edit_start_line_idx": 69 }
// Copyright 2009 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. // Solaris system calls. // This file is compiled as ordinary Go code, // but it is also input to mksyscall, // which parses the //sys lines and generates system call stubs. // Note that sometimes we use a lowercase //sys name and wrap // it in our own nicer implementation, either here or in // syscall_solaris.go or syscall_unix.go. package unix import ( "sync/atomic" "syscall" "unsafe" ) // Implemented in runtime/syscall_solaris.go. type syscallFunc uintptr func rawSysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) func sysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) type SockaddrDatalink struct { Family uint16 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [244]int8 raw RawSockaddrDatalink } func clen(n []byte) int { for i := 0; i < len(n); i++ { if n[i] == 0 { return i } } return len(n) } // ParseDirent parses up to max directory entries in buf, // appending the names to names. It returns the number // bytes consumed from buf, the number of entries added // to names, and the new names slice. func ParseDirent(buf []byte, max int, names []string) (consumed int, count int, newnames []string) { origlen := len(buf) for max != 0 && len(buf) > 0 { dirent := (*Dirent)(unsafe.Pointer(&buf[0])) if dirent.Reclen == 0 { buf = nil break } buf = buf[dirent.Reclen:] if dirent.Ino == 0 { // File absent in directory. continue } bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) var name = string(bytes[0:clen(bytes[:])]) if name == "." || name == ".." { // Useless names continue } max-- count++ names = append(names, name) } return origlen - len(buf), count, names } //sysnb pipe(p *[2]_C_int) (n int, err error) func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int n, err := pipe(&pp) if n != 0 { return err } p[0] = int(pp[0]) p[1] = int(pp[1]) return nil } func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) { if sa.Port < 0 || sa.Port > 0xFFFF { return nil, 0, EINVAL } sa.raw.Family = AF_INET p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) p[0] = byte(sa.Port >> 8) p[1] = byte(sa.Port) for i := 0; i < len(sa.Addr); i++ { sa.raw.Addr[i] = sa.Addr[i] } return unsafe.Pointer(&sa.raw), SizeofSockaddrInet4, nil } func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) { if sa.Port < 0 || sa.Port > 0xFFFF { return nil, 0, EINVAL } sa.raw.Family = AF_INET6 p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) p[0] = byte(sa.Port >> 8) p[1] = byte(sa.Port) sa.raw.Scope_id = sa.ZoneId for i := 0; i < len(sa.Addr); i++ { sa.raw.Addr[i] = sa.Addr[i] } return unsafe.Pointer(&sa.raw), SizeofSockaddrInet6, nil } func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) { name := sa.Name n := len(name) if n >= len(sa.raw.Path) { return nil, 0, EINVAL } sa.raw.Family = AF_UNIX for i := 0; i < n; i++ { sa.raw.Path[i] = int8(name[i]) } // length is family (uint16), name, NUL. sl := _Socklen(2) if n > 0 { sl += _Socklen(n) + 1 } if sa.raw.Path[0] == '@' { sa.raw.Path[0] = 0 // Don't count trailing NUL for abstract address. sl-- } return unsafe.Pointer(&sa.raw), sl, nil } //sys getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) = libsocket.getsockname func Getsockname(fd int) (sa Sockaddr, err error) { var rsa RawSockaddrAny var len _Socklen = SizeofSockaddrAny if err = getsockname(fd, &rsa, &len); err != nil { return } return anyToSockaddr(&rsa) } const ImplementsGetwd = true //sys Getcwd(buf []byte) (n int, err error) func Getwd() (wd string, err error) { var buf [PathMax]byte // Getcwd will return an error if it failed for any reason. _, err = Getcwd(buf[0:]) if err != nil { return "", err } n := clen(buf[:]) if n < 1 { return "", EINVAL } return string(buf[:n]), nil } /* * Wrapped */ //sysnb getgroups(ngid int, gid *_Gid_t) (n int, err error) //sysnb setgroups(ngid int, gid *_Gid_t) (err error) func Getgroups() (gids []int, err error) { n, err := getgroups(0, nil) // Check for error and sanity check group count. Newer versions of // Solaris allow up to 1024 (NGROUPS_MAX). if n < 0 || n > 1024 { if err != nil { return nil, err } return nil, EINVAL } else if n == 0 { return nil, nil } a := make([]_Gid_t, n) n, err = getgroups(n, &a[0]) if n == -1 { return nil, err } gids = make([]int, n) for i, v := range a[0:n] { gids[i] = int(v) } return } func Setgroups(gids []int) (err error) { if len(gids) == 0 { return setgroups(0, nil) } a := make([]_Gid_t, len(gids)) for i, v := range gids { a[i] = _Gid_t(v) } return setgroups(len(a), &a[0]) } func ReadDirent(fd int, buf []byte) (n int, err error) { // Final argument is (basep *uintptr) and the syscall doesn't take nil. // TODO(rsc): Can we use a single global basep for all calls? return Getdents(fd, buf, new(uintptr)) } // Wait status is 7 bits at bottom, either 0 (exited), // 0x7F (stopped), or a signal number that caused an exit. // The 0x80 bit is whether there was a core dump. // An extra number (exit code, signal causing a stop) // is in the high bits. type WaitStatus uint32 const ( mask = 0x7F core = 0x80 shift = 8 exited = 0 stopped = 0x7F ) func (w WaitStatus) Exited() bool { return w&mask == exited } func (w WaitStatus) ExitStatus() int { if w&mask != exited { return -1 } return int(w >> shift) } func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != 0 } func (w WaitStatus) Signal() syscall.Signal { sig := syscall.Signal(w & mask) if sig == stopped || sig == 0 { return -1 } return sig } func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 } func (w WaitStatus) Stopped() bool { return w&mask == stopped && syscall.Signal(w>>shift) != SIGSTOP } func (w WaitStatus) Continued() bool { return w&mask == stopped && syscall.Signal(w>>shift) == SIGSTOP } func (w WaitStatus) StopSignal() syscall.Signal { if !w.Stopped() { return -1 } return syscall.Signal(w>>shift) & 0xFF } func (w WaitStatus) TrapCause() int { return -1 } //sys wait4(pid int32, statusp *_C_int, options int, rusage *Rusage) (wpid int32, err error) func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (int, error) { var status _C_int rpid, err := wait4(int32(pid), &status, options, rusage) wpid := int(rpid) if wpid == -1 { return wpid, err } if wstatus != nil { *wstatus = WaitStatus(status) } return wpid, nil } //sys gethostname(buf []byte) (n int, err error) func Gethostname() (name string, err error) { var buf [MaxHostNameLen]byte n, err := gethostname(buf[:]) if n != 0 { return "", err } n = clen(buf[:]) if n < 1 { return "", EFAULT } return string(buf[:n]), nil } //sys utimes(path string, times *[2]Timeval) (err error) func Utimes(path string, tv []Timeval) (err error) { if tv == nil { return utimes(path, nil) } if len(tv) != 2 { return EINVAL } return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) } //sys utimensat(fd int, path string, times *[2]Timespec, flag int) (err error) func UtimesNano(path string, ts []Timespec) error { if ts == nil { return utimensat(AT_FDCWD, path, nil, 0) } if len(ts) != 2 { return EINVAL } return utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0) } func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error { if ts == nil { return utimensat(dirfd, path, nil, flags) } if len(ts) != 2 { return EINVAL } return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags) } //sys fcntl(fd int, cmd int, arg int) (val int, err error) // FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command. func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(unsafe.Pointer(lk)), 0, 0, 0) if e1 != 0 { return e1 } return nil } //sys futimesat(fildes int, path *byte, times *[2]Timeval) (err error) func Futimesat(dirfd int, path string, tv []Timeval) error { pathp, err := BytePtrFromString(path) if err != nil { return err } if tv == nil { return futimesat(dirfd, pathp, nil) } if len(tv) != 2 { return EINVAL } return futimesat(dirfd, pathp, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) } // Solaris doesn't have an futimes function because it allows NULL to be // specified as the path for futimesat. However, Go doesn't like // NULL-style string interfaces, so this simple wrapper is provided. func Futimes(fd int, tv []Timeval) error { if tv == nil { return futimesat(fd, nil, nil) } if len(tv) != 2 { return EINVAL } return futimesat(fd, nil, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) } func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) { switch rsa.Addr.Family { case AF_UNIX: pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa)) sa := new(SockaddrUnix) // Assume path ends at NUL. // This is not technically the Solaris semantics for // abstract Unix domain sockets -- they are supposed // to be uninterpreted fixed-size binary blobs -- but // everyone uses this convention. n := 0 for n < len(pp.Path) && pp.Path[n] != 0 { n++ } bytes := (*[10000]byte)(unsafe.Pointer(&pp.Path[0]))[0:n] sa.Name = string(bytes) return sa, nil case AF_INET: pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa)) sa := new(SockaddrInet4) p := (*[2]byte)(unsafe.Pointer(&pp.Port)) sa.Port = int(p[0])<<8 + int(p[1]) for i := 0; i < len(sa.Addr); i++ { sa.Addr[i] = pp.Addr[i] } return sa, nil case AF_INET6: pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa)) sa := new(SockaddrInet6) p := (*[2]byte)(unsafe.Pointer(&pp.Port)) sa.Port = int(p[0])<<8 + int(p[1]) sa.ZoneId = pp.Scope_id for i := 0; i < len(sa.Addr); i++ { sa.Addr[i] = pp.Addr[i] } return sa, nil } return nil, EAFNOSUPPORT } //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) = libsocket.accept func Accept(fd int) (nfd int, sa Sockaddr, err error) { var rsa RawSockaddrAny var len _Socklen = SizeofSockaddrAny nfd, err = accept(fd, &rsa, &len) if nfd == -1 { return } sa, err = anyToSockaddr(&rsa) if err != nil { Close(nfd) nfd = 0 } return } //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) = libsocket.recvmsg func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) { var msg Msghdr var rsa RawSockaddrAny msg.Name = (*byte)(unsafe.Pointer(&rsa)) msg.Namelen = uint32(SizeofSockaddrAny) var iov Iovec if len(p) > 0 { iov.Base = (*int8)(unsafe.Pointer(&p[0])) iov.SetLen(len(p)) } var dummy int8 if len(oob) > 0 { // receive at least one normal byte if len(p) == 0 { iov.Base = &dummy iov.SetLen(1) } msg.Accrights = (*int8)(unsafe.Pointer(&oob[0])) } msg.Iov = &iov msg.Iovlen = 1 if n, err = recvmsg(fd, &msg, flags); n == -1 { return } oobn = int(msg.Accrightslen) // source address is only specified if the socket is unconnected if rsa.Addr.Family != AF_UNSPEC { from, err = anyToSockaddr(&rsa) } return } func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) { _, err = SendmsgN(fd, p, oob, to, flags) return } //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) = libsocket.sendmsg func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) { var ptr unsafe.Pointer var salen _Socklen if to != nil { ptr, salen, err = to.sockaddr() if err != nil { return 0, err } } var msg Msghdr msg.Name = (*byte)(unsafe.Pointer(ptr)) msg.Namelen = uint32(salen) var iov Iovec if len(p) > 0 { iov.Base = (*int8)(unsafe.Pointer(&p[0])) iov.SetLen(len(p)) } var dummy int8 if len(oob) > 0 { // send at least one normal byte if len(p) == 0 { iov.Base = &dummy iov.SetLen(1) } msg.Accrights = (*int8)(unsafe.Pointer(&oob[0])) } msg.Iov = &iov msg.Iovlen = 1 if n, err = sendmsg(fd, &msg, flags); err != nil { return 0, err } if len(oob) > 0 && len(p) == 0 { n = 0 } return n, nil } //sys acct(path *byte) (err error) func Acct(path string) (err error) { if len(path) == 0 { // Assume caller wants to disable accounting. return acct(nil) } pathp, err := BytePtrFromString(path) if err != nil { return err } return acct(pathp) } /* * Expose the ioctl function */ //sys ioctl(fd int, req int, arg uintptr) (err error) func IoctlSetInt(fd int, req int, value int) (err error) { return ioctl(fd, req, uintptr(value)) } func IoctlSetWinsize(fd int, req int, value *Winsize) (err error) { return ioctl(fd, req, uintptr(unsafe.Pointer(value))) } func IoctlSetTermios(fd int, req int, value *Termios) (err error) { return ioctl(fd, req, uintptr(unsafe.Pointer(value))) } func IoctlSetTermio(fd int, req int, value *Termio) (err error) { return ioctl(fd, req, uintptr(unsafe.Pointer(value))) } func IoctlGetInt(fd int, req int) (int, error) { var value int err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return value, err } func IoctlGetWinsize(fd int, req int) (*Winsize, error) { var value Winsize err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return &value, err } func IoctlGetTermios(fd int, req int) (*Termios, error) { var value Termios err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return &value, err } func IoctlGetTermio(fd int, req int) (*Termio, error) { var value Termio err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return &value, err } /* * Exposed directly */ //sys Access(path string, mode uint32) (err error) //sys Adjtime(delta *Timeval, olddelta *Timeval) (err error) //sys Chdir(path string) (err error) //sys Chmod(path string, mode uint32) (err error) //sys Chown(path string, uid int, gid int) (err error) //sys Chroot(path string) (err error) //sys Close(fd int) (err error) //sys Creat(path string, mode uint32) (fd int, err error) //sys Dup(fd int) (nfd int, err error) //sys Dup2(oldfd int, newfd int) (err error) //sys Exit(code int) //sys Fchdir(fd int) (err error) //sys Fchmod(fd int, mode uint32) (err error) //sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) //sys Fchown(fd int, uid int, gid int) (err error) //sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) //sys Fdatasync(fd int) (err error) //sys Fpathconf(fd int, name int) (val int, err error) //sys Fstat(fd int, stat *Stat_t) (err error) //sys Getdents(fd int, buf []byte, basep *uintptr) (n int, err error) //sysnb Getgid() (gid int) //sysnb Getpid() (pid int) //sysnb Getpgid(pid int) (pgid int, err error) //sysnb Getpgrp() (pgid int, err error) //sys Geteuid() (euid int) //sys Getegid() (egid int) //sys Getppid() (ppid int) //sys Getpriority(which int, who int) (n int, err error) //sysnb Getrlimit(which int, lim *Rlimit) (err error) //sysnb Getrusage(who int, rusage *Rusage) (err error) //sysnb Gettimeofday(tv *Timeval) (err error) //sysnb Getuid() (uid int) //sys Kill(pid int, signum syscall.Signal) (err error) //sys Lchown(path string, uid int, gid int) (err error) //sys Link(path string, link string) (err error) //sys Listen(s int, backlog int) (err error) = libsocket.listen //sys Lstat(path string, stat *Stat_t) (err error) //sys Madvise(b []byte, advice int) (err error) //sys Mkdir(path string, mode uint32) (err error) //sys Mkdirat(dirfd int, path string, mode uint32) (err error) //sys Mkfifo(path string, mode uint32) (err error) //sys Mkfifoat(dirfd int, path string, mode uint32) (err error) //sys Mknod(path string, mode uint32, dev int) (err error) //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error) //sys Mlock(b []byte) (err error) //sys Mlockall(flags int) (err error) //sys Mprotect(b []byte, prot int) (err error) //sys Munlock(b []byte) (err error) //sys Munlockall() (err error) //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) //sys Open(path string, mode int, perm uint32) (fd int, err error) //sys Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) //sys Pathconf(path string, name int) (val int, err error) //sys Pause() (err error) //sys Pread(fd int, p []byte, offset int64) (n int, err error) //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) //sys read(fd int, p []byte) (n int, err error) //sys Readlink(path string, buf []byte) (n int, err error) //sys Rename(from string, to string) (err error) //sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) //sys Rmdir(path string) (err error) //sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = lseek //sysnb Setegid(egid int) (err error) //sysnb Seteuid(euid int) (err error) //sysnb Setgid(gid int) (err error) //sys Sethostname(p []byte) (err error) //sysnb Setpgid(pid int, pgid int) (err error) //sys Setpriority(which int, who int, prio int) (err error) //sysnb Setregid(rgid int, egid int) (err error) //sysnb Setreuid(ruid int, euid int) (err error) //sysnb Setrlimit(which int, lim *Rlimit) (err error) //sysnb Setsid() (pid int, err error) //sysnb Setuid(uid int) (err error) //sys Shutdown(s int, how int) (err error) = libsocket.shutdown //sys Stat(path string, stat *Stat_t) (err error) //sys Symlink(path string, link string) (err error) //sys Sync() (err error) //sysnb Times(tms *Tms) (ticks uintptr, err error) //sys Truncate(path string, length int64) (err error) //sys Fsync(fd int) (err error) //sys Ftruncate(fd int, length int64) (err error) //sys Umask(mask int) (oldmask int) //sysnb Uname(buf *Utsname) (err error) //sys Unmount(target string, flags int) (err error) = libc.umount //sys Unlink(path string) (err error) //sys Unlinkat(dirfd int, path string, flags int) (err error) //sys Ustat(dev int, ubuf *Ustat_t) (err error) //sys Utime(path string, buf *Utimbuf) (err error) //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.bind //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.connect //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) //sys munmap(addr uintptr, length uintptr) (err error) //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.sendto //sys socket(domain int, typ int, proto int) (fd int, err error) = libsocket.socket //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) = libsocket.socketpair //sys write(fd int, p []byte) (n int, err error) //sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) = libsocket.getsockopt //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) = libsocket.getpeername //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) = libsocket.setsockopt //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) = libsocket.recvfrom func readlen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procread)), 3, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf), 0, 0, 0) n = int(r0) if e1 != 0 { err = e1 } return } func writelen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procwrite)), 3, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf), 0, 0, 0) n = int(r0) if e1 != 0 { err = e1 } return } var mapper = &mmapper{ active: make(map[*byte][]byte), mmap: mmap, munmap: munmap, } func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { return mapper.Mmap(fd, offset, length, prot, flags) } func Munmap(b []byte) (err error) { return mapper.Munmap(b) } //sys sysconf(name int) (n int64, err error) // pageSize caches the value of Getpagesize, since it can't change // once the system is booted. var pageSize int64 // accessed atomically func Getpagesize() int { n := atomic.LoadInt64(&pageSize) if n == 0 { n, _ = sysconf(_SC_PAGESIZE) atomic.StoreInt64(&pageSize, n) } return int(n) }
vendor/golang.org/x/sys/unix/syscall_solaris.go
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.0006406169850379229, 0.00018615440058056265, 0.00016135690384544432, 0.00016982429951895028, 0.00006334588397294283 ]
{ "id": 4, "code_window": [ "\t// invalid encoding\n", "\t{input: \"\", wantErr: errNonString},\n", "\t{input: \"null\", wantErr: errNonString},\n", "\t{input: \"10\", wantErr: errNonString},\n", "\t{input: `\"\"`, wantErr: ErrEmptyString},\n", "\t{input: `\"0\"`, wantErr: ErrMissingPrefix},\n", "\t{input: `\"0x\"`, wantErr: ErrEmptyNumber},\n", "\t{input: `\"0x01\"`, wantErr: ErrLeadingZero},\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "common/hexutil/json_test.go", "type": "replace", "edit_start_line_idx": 127 }
// Copyright 2016 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package hexutil import ( "bytes" "encoding/hex" "math/big" "testing" ) func checkError(t *testing.T, input string, got, want error) bool { if got == nil { if want != nil { t.Errorf("input %s: got no error, want %q", input, want) return false } return true } if want == nil { t.Errorf("input %s: unexpected error %q", input, got) } else if got.Error() != want.Error() { t.Errorf("input %s: got error %q, want %q", input, got, want) } return false } func referenceBig(s string) *big.Int { b, ok := new(big.Int).SetString(s, 16) if !ok { panic("invalid") } return b } func referenceBytes(s string) []byte { b, err := hex.DecodeString(s) if err != nil { panic(err) } return b } var unmarshalBytesTests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x0"`, wantErr: ErrOddLength}, {input: `"0xxx"`, wantErr: ErrSyntax}, {input: `"0x01zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x"`, want: referenceBytes("")}, {input: `"0x02"`, want: referenceBytes("02")}, {input: `"0X02"`, want: referenceBytes("02")}, {input: `"0xffffffffff"`, want: referenceBytes("ffffffffff")}, { input: `"0xffffffffffffffffffffffffffffffffffff"`, want: referenceBytes("ffffffffffffffffffffffffffffffffffff"), }, } func TestUnmarshalBytes(t *testing.T) { for _, test := range unmarshalBytesTests { var v Bytes err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if !bytes.Equal(test.want.([]byte), []byte(v)) { t.Errorf("input %s: value mismatch: got %x, want %x", test.input, &v, test.want) continue } } } func BenchmarkUnmarshalBytes(b *testing.B) { input := []byte(`"0x123456789abcdef123456789abcdef"`) for i := 0; i < b.N; i++ { var v Bytes if err := v.UnmarshalJSON(input); err != nil { b.Fatal(err) } } } func TestMarshalBytes(t *testing.T) { for _, test := range encodeBytesTests { in := test.input.([]byte) out, err := Bytes(in).MarshalJSON() if err != nil { t.Errorf("%x: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%x: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := Bytes(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } } var unmarshalBigTests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x"`, wantErr: ErrEmptyNumber}, {input: `"0x01"`, wantErr: ErrLeadingZero}, {input: `"0xx"`, wantErr: ErrSyntax}, {input: `"0x1zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x0"`, want: big.NewInt(0)}, {input: `"0x2"`, want: big.NewInt(0x2)}, {input: `"0x2F2"`, want: big.NewInt(0x2f2)}, {input: `"0X2F2"`, want: big.NewInt(0x2f2)}, {input: `"0x1122aaff"`, want: big.NewInt(0x1122aaff)}, {input: `"0xbBb"`, want: big.NewInt(0xbbb)}, {input: `"0xfffffffff"`, want: big.NewInt(0xfffffffff)}, { input: `"0x112233445566778899aabbccddeeff"`, want: referenceBig("112233445566778899aabbccddeeff"), }, { input: `"0xffffffffffffffffffffffffffffffffffff"`, want: referenceBig("ffffffffffffffffffffffffffffffffffff"), }, } func TestUnmarshalBig(t *testing.T) { for _, test := range unmarshalBigTests { var v Big err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if test.want != nil && test.want.(*big.Int).Cmp((*big.Int)(&v)) != 0 { t.Errorf("input %s: value mismatch: got %x, want %x", test.input, (*big.Int)(&v), test.want) continue } } } func BenchmarkUnmarshalBig(b *testing.B) { input := []byte(`"0x123456789abcdef123456789abcdef"`) for i := 0; i < b.N; i++ { var v Big if err := v.UnmarshalJSON(input); err != nil { b.Fatal(err) } } } func TestMarshalBig(t *testing.T) { for _, test := range encodeBigTests { in := test.input.(*big.Int) out, err := (*Big)(in).MarshalJSON() if err != nil { t.Errorf("%d: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%d: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := (*Big)(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } } var unmarshalUint64Tests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x"`, wantErr: ErrEmptyNumber}, {input: `"0x01"`, wantErr: ErrLeadingZero}, {input: `"0xfffffffffffffffff"`, wantErr: ErrUint64Range}, {input: `"0xx"`, wantErr: ErrSyntax}, {input: `"0x1zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x0"`, want: uint64(0)}, {input: `"0x2"`, want: uint64(0x2)}, {input: `"0x2F2"`, want: uint64(0x2f2)}, {input: `"0X2F2"`, want: uint64(0x2f2)}, {input: `"0x1122aaff"`, want: uint64(0x1122aaff)}, {input: `"0xbbb"`, want: uint64(0xbbb)}, {input: `"0xffffffffffffffff"`, want: uint64(0xffffffffffffffff)}, } func TestUnmarshalUint64(t *testing.T) { for _, test := range unmarshalUint64Tests { var v Uint64 err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if uint64(v) != test.want.(uint64) { t.Errorf("input %s: value mismatch: got %d, want %d", test.input, v, test.want) continue } } } func BenchmarkUnmarshalUint64(b *testing.B) { input := []byte(`"0x123456789abcdf"`) for i := 0; i < b.N; i++ { var v Uint64 v.UnmarshalJSON(input) } } func TestMarshalUint64(t *testing.T) { for _, test := range encodeUint64Tests { in := test.input.(uint64) out, err := Uint64(in).MarshalJSON() if err != nil { t.Errorf("%d: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%d: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := (Uint64)(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } }
common/hexutil/json_test.go
1
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.7433958649635315, 0.04190244898200035, 0.00016417886945419014, 0.00017555493104737252, 0.14917293190956116 ]
{ "id": 4, "code_window": [ "\t// invalid encoding\n", "\t{input: \"\", wantErr: errNonString},\n", "\t{input: \"null\", wantErr: errNonString},\n", "\t{input: \"10\", wantErr: errNonString},\n", "\t{input: `\"\"`, wantErr: ErrEmptyString},\n", "\t{input: `\"0\"`, wantErr: ErrMissingPrefix},\n", "\t{input: `\"0x\"`, wantErr: ErrEmptyNumber},\n", "\t{input: `\"0x01\"`, wantErr: ErrLeadingZero},\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "common/hexutil/json_test.go", "type": "replace", "edit_start_line_idx": 127 }
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo #include "textflag.h" // // System call support for ARM, NetBSD // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-28 B syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-40 B syscall·Syscall6(SB) TEXT ·Syscall9(SB),NOSPLIT,$0-52 B syscall·Syscall9(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-28 B syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 B syscall·RawSyscall6(SB)
vendor/golang.org/x/sys/unix/asm_netbsd_arm.s
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.0001760457962518558, 0.00017453280452173203, 0.000173520966200158, 0.0001740316511131823, 0.0000010899717608481296 ]
{ "id": 4, "code_window": [ "\t// invalid encoding\n", "\t{input: \"\", wantErr: errNonString},\n", "\t{input: \"null\", wantErr: errNonString},\n", "\t{input: \"10\", wantErr: errNonString},\n", "\t{input: `\"\"`, wantErr: ErrEmptyString},\n", "\t{input: `\"0\"`, wantErr: ErrMissingPrefix},\n", "\t{input: `\"0x\"`, wantErr: ErrEmptyNumber},\n", "\t{input: `\"0x01\"`, wantErr: ErrLeadingZero},\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "common/hexutil/json_test.go", "type": "replace", "edit_start_line_idx": 127 }
// Copyright 2009 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 ( "bufio" "fmt" "io" "net/http" ) func newServerConn(rwc io.ReadWriteCloser, buf *bufio.ReadWriter, req *http.Request, config *Config, handshake func(*Config, *http.Request) error) (conn *Conn, err error) { var hs serverHandshaker = &hybiServerHandshaker{Config: config} code, err := hs.ReadHandshake(buf.Reader, req) if err == ErrBadWebSocketVersion { fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) fmt.Fprintf(buf, "Sec-WebSocket-Version: %s\r\n", SupportedProtocolVersion) buf.WriteString("\r\n") buf.WriteString(err.Error()) buf.Flush() return } if err != nil { fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) buf.WriteString("\r\n") buf.WriteString(err.Error()) buf.Flush() return } if handshake != nil { err = handshake(config, req) if err != nil { code = http.StatusForbidden fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) buf.WriteString("\r\n") buf.Flush() return } } err = hs.AcceptHandshake(buf.Writer) if err != nil { code = http.StatusBadRequest fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) buf.WriteString("\r\n") buf.Flush() return } conn = hs.NewServerConn(buf, rwc, req) return } // Server represents a server of a WebSocket. type Server struct { // Config is a WebSocket configuration for new WebSocket connection. Config // Handshake is an optional function in WebSocket handshake. // For example, you can check, or don't check Origin header. // Another example, you can select config.Protocol. Handshake func(*Config, *http.Request) error // Handler handles a WebSocket connection. Handler } // ServeHTTP implements the http.Handler interface for a WebSocket func (s Server) ServeHTTP(w http.ResponseWriter, req *http.Request) { s.serveWebSocket(w, req) } func (s Server) serveWebSocket(w http.ResponseWriter, req *http.Request) { rwc, buf, err := w.(http.Hijacker).Hijack() if err != nil { panic("Hijack failed: " + err.Error()) } // The server should abort the WebSocket connection if it finds // the client did not send a handshake that matches with protocol // specification. defer rwc.Close() conn, err := newServerConn(rwc, buf, req, &s.Config, s.Handshake) if err != nil { return } if conn == nil { panic("unexpected nil conn") } s.Handler(conn) } // Handler is a simple interface to a WebSocket browser client. // It checks if Origin header is valid URL by default. // You might want to verify websocket.Conn.Config().Origin in the func. // If you use Server instead of Handler, you could call websocket.Origin and // check the origin in your Handshake func. So, if you want to accept // non-browser clients, which do not send an Origin header, set a // Server.Handshake that does not check the origin. type Handler func(*Conn) func checkOrigin(config *Config, req *http.Request) (err error) { config.Origin, err = Origin(config, req) if err == nil && config.Origin == nil { return fmt.Errorf("null origin") } return err } // ServeHTTP implements the http.Handler interface for a WebSocket func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) { s := Server{Handler: h, Handshake: checkOrigin} s.serveWebSocket(w, req) }
vendor/golang.org/x/net/websocket/server.go
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.0015245249960571527, 0.00029547230224125087, 0.00016439741011708975, 0.00017067733278963715, 0.00037197835627011955 ]
{ "id": 4, "code_window": [ "\t// invalid encoding\n", "\t{input: \"\", wantErr: errNonString},\n", "\t{input: \"null\", wantErr: errNonString},\n", "\t{input: \"10\", wantErr: errNonString},\n", "\t{input: `\"\"`, wantErr: ErrEmptyString},\n", "\t{input: `\"0\"`, wantErr: ErrMissingPrefix},\n", "\t{input: `\"0x\"`, wantErr: ErrEmptyNumber},\n", "\t{input: `\"0x01\"`, wantErr: ErrLeadingZero},\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "common/hexutil/json_test.go", "type": "replace", "edit_start_line_idx": 127 }
{ "randomStatetest" : { "env" : { "currentCoinbase" : "945304eb96065b2a98b57a48a06ae28d285a71b5", "currentDifficulty" : "0x051d6a3cd647", "currentGasLimit" : "0x7fffffffffffffff", "currentNumber" : "0x00", "currentTimestamp" : "0x01", "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6" }, "logs" : [ ], "out" : "0x", "post" : { "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { "balance" : "0x32532e89", "code" : "0x7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001447f00000000000000000000000000000000000000000000000000000000000000007f00000000000000000000000100000000000000000000000000000000000000007f000000000000000000000000000000000000000000000000000000000000c3507f000000000000000000000000000000000000000000000000000000000000c3507f1606588a909558021569", "nonce" : "0x00", "storage" : { } }, "945304eb96065b2a98b57a48a06ae28d285a71b5" : { "balance" : "0x649c", "code" : "0x6000355415600957005b60203560003555", "nonce" : "0x00", "storage" : { } }, "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { "balance" : "0x0de0b6b375106d09", "code" : "0x", "nonce" : "0x01", "storage" : { } } }, "postStateRoot" : "1b827147bee0055ef753387d41f23fc8e5599501ec201dc57e209e9da6ced93d", "pre" : { "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { "balance" : "0x00", "code" : "0x7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001447f00000000000000000000000000000000000000000000000000000000000000007f00000000000000000000000100000000000000000000000000000000000000007f000000000000000000000000000000000000000000000000000000000000c3507f000000000000000000000000000000000000000000000000000000000000c3507f1606588a909558021569", "nonce" : "0x00", "storage" : { } }, "945304eb96065b2a98b57a48a06ae28d285a71b5" : { "balance" : "0x2e", "code" : "0x6000355415600957005b60203560003555", "nonce" : "0x00", "storage" : { } }, "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { "balance" : "0x0de0b6b3a7640000", "code" : "0x", "nonce" : "0x00", "storage" : { } } }, "transaction" : { "data" : "0x7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001447f00000000000000000000000000000000000000000000000000000000000000007f00000000000000000000000100000000000000000000000000000000000000007f000000000000000000000000000000000000000000000000000000000000c3507f000000000000000000000000000000000000000000000000000000000000c3507f1606588a909558021569", "gasLimit" : "0x0d3c510a", "gasPrice" : "0x01", "nonce" : "0x00", "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", "value" : "0x32532e89" } } }
tests/files/StateTests/RandomTests/st201504090553CPPJIT.json
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.00017385170212946832, 0.00016693765064701438, 0.00016405072528868914, 0.0001661995192989707, 0.000002929585207311902 ]
{ "id": 5, "code_window": [ "\t{input: `\"0x1zz01\"`, wantErr: ErrSyntax},\n", "\n", "\t// valid encoding\n", "\t{input: `\"0x0\"`, want: big.NewInt(0)},\n", "\t{input: `\"0x2\"`, want: big.NewInt(0x2)},\n", "\t{input: `\"0x2F2\"`, want: big.NewInt(0x2f2)},\n", "\t{input: `\"0X2F2\"`, want: big.NewInt(0x2f2)},\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t{input: `\"\"`, want: big.NewInt(0)},\n" ], "file_path": "common/hexutil/json_test.go", "type": "add", "edit_start_line_idx": 135 }
// Copyright 2016 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package hexutil import ( "bytes" "encoding/hex" "math/big" "testing" ) func checkError(t *testing.T, input string, got, want error) bool { if got == nil { if want != nil { t.Errorf("input %s: got no error, want %q", input, want) return false } return true } if want == nil { t.Errorf("input %s: unexpected error %q", input, got) } else if got.Error() != want.Error() { t.Errorf("input %s: got error %q, want %q", input, got, want) } return false } func referenceBig(s string) *big.Int { b, ok := new(big.Int).SetString(s, 16) if !ok { panic("invalid") } return b } func referenceBytes(s string) []byte { b, err := hex.DecodeString(s) if err != nil { panic(err) } return b } var unmarshalBytesTests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x0"`, wantErr: ErrOddLength}, {input: `"0xxx"`, wantErr: ErrSyntax}, {input: `"0x01zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x"`, want: referenceBytes("")}, {input: `"0x02"`, want: referenceBytes("02")}, {input: `"0X02"`, want: referenceBytes("02")}, {input: `"0xffffffffff"`, want: referenceBytes("ffffffffff")}, { input: `"0xffffffffffffffffffffffffffffffffffff"`, want: referenceBytes("ffffffffffffffffffffffffffffffffffff"), }, } func TestUnmarshalBytes(t *testing.T) { for _, test := range unmarshalBytesTests { var v Bytes err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if !bytes.Equal(test.want.([]byte), []byte(v)) { t.Errorf("input %s: value mismatch: got %x, want %x", test.input, &v, test.want) continue } } } func BenchmarkUnmarshalBytes(b *testing.B) { input := []byte(`"0x123456789abcdef123456789abcdef"`) for i := 0; i < b.N; i++ { var v Bytes if err := v.UnmarshalJSON(input); err != nil { b.Fatal(err) } } } func TestMarshalBytes(t *testing.T) { for _, test := range encodeBytesTests { in := test.input.([]byte) out, err := Bytes(in).MarshalJSON() if err != nil { t.Errorf("%x: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%x: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := Bytes(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } } var unmarshalBigTests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x"`, wantErr: ErrEmptyNumber}, {input: `"0x01"`, wantErr: ErrLeadingZero}, {input: `"0xx"`, wantErr: ErrSyntax}, {input: `"0x1zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x0"`, want: big.NewInt(0)}, {input: `"0x2"`, want: big.NewInt(0x2)}, {input: `"0x2F2"`, want: big.NewInt(0x2f2)}, {input: `"0X2F2"`, want: big.NewInt(0x2f2)}, {input: `"0x1122aaff"`, want: big.NewInt(0x1122aaff)}, {input: `"0xbBb"`, want: big.NewInt(0xbbb)}, {input: `"0xfffffffff"`, want: big.NewInt(0xfffffffff)}, { input: `"0x112233445566778899aabbccddeeff"`, want: referenceBig("112233445566778899aabbccddeeff"), }, { input: `"0xffffffffffffffffffffffffffffffffffff"`, want: referenceBig("ffffffffffffffffffffffffffffffffffff"), }, } func TestUnmarshalBig(t *testing.T) { for _, test := range unmarshalBigTests { var v Big err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if test.want != nil && test.want.(*big.Int).Cmp((*big.Int)(&v)) != 0 { t.Errorf("input %s: value mismatch: got %x, want %x", test.input, (*big.Int)(&v), test.want) continue } } } func BenchmarkUnmarshalBig(b *testing.B) { input := []byte(`"0x123456789abcdef123456789abcdef"`) for i := 0; i < b.N; i++ { var v Big if err := v.UnmarshalJSON(input); err != nil { b.Fatal(err) } } } func TestMarshalBig(t *testing.T) { for _, test := range encodeBigTests { in := test.input.(*big.Int) out, err := (*Big)(in).MarshalJSON() if err != nil { t.Errorf("%d: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%d: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := (*Big)(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } } var unmarshalUint64Tests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x"`, wantErr: ErrEmptyNumber}, {input: `"0x01"`, wantErr: ErrLeadingZero}, {input: `"0xfffffffffffffffff"`, wantErr: ErrUint64Range}, {input: `"0xx"`, wantErr: ErrSyntax}, {input: `"0x1zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x0"`, want: uint64(0)}, {input: `"0x2"`, want: uint64(0x2)}, {input: `"0x2F2"`, want: uint64(0x2f2)}, {input: `"0X2F2"`, want: uint64(0x2f2)}, {input: `"0x1122aaff"`, want: uint64(0x1122aaff)}, {input: `"0xbbb"`, want: uint64(0xbbb)}, {input: `"0xffffffffffffffff"`, want: uint64(0xffffffffffffffff)}, } func TestUnmarshalUint64(t *testing.T) { for _, test := range unmarshalUint64Tests { var v Uint64 err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if uint64(v) != test.want.(uint64) { t.Errorf("input %s: value mismatch: got %d, want %d", test.input, v, test.want) continue } } } func BenchmarkUnmarshalUint64(b *testing.B) { input := []byte(`"0x123456789abcdf"`) for i := 0; i < b.N; i++ { var v Uint64 v.UnmarshalJSON(input) } } func TestMarshalUint64(t *testing.T) { for _, test := range encodeUint64Tests { in := test.input.(uint64) out, err := Uint64(in).MarshalJSON() if err != nil { t.Errorf("%d: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%d: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := (Uint64)(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } }
common/hexutil/json_test.go
1
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.680288553237915, 0.029079534113407135, 0.0001663985603954643, 0.0003639168571680784, 0.13058684766292572 ]
{ "id": 5, "code_window": [ "\t{input: `\"0x1zz01\"`, wantErr: ErrSyntax},\n", "\n", "\t// valid encoding\n", "\t{input: `\"0x0\"`, want: big.NewInt(0)},\n", "\t{input: `\"0x2\"`, want: big.NewInt(0x2)},\n", "\t{input: `\"0x2F2\"`, want: big.NewInt(0x2f2)},\n", "\t{input: `\"0X2F2\"`, want: big.NewInt(0x2f2)},\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t{input: `\"\"`, want: big.NewInt(0)},\n" ], "file_path": "common/hexutil/json_test.go", "type": "add", "edit_start_line_idx": 135 }
// Copyright 2015 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package downloader import ( "sync" ethereum "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/rpc" "golang.org/x/net/context" ) // PublicDownloaderAPI provides an API which gives information about the current synchronisation status. // It offers only methods that operates on data that can be available to anyone without security risks. type PublicDownloaderAPI struct { d *Downloader mux *event.TypeMux installSyncSubscription chan chan interface{} uninstallSyncSubscription chan *uninstallSyncSubscriptionRequest } // NewPublicDownloaderAPI create a new PublicDownloaderAPI. The API has an internal event loop that // listens for events from the downloader through the global event mux. In case it receives one of // these events it broadcasts it to all syncing subscriptions that are installed through the // installSyncSubscription channel. func NewPublicDownloaderAPI(d *Downloader, m *event.TypeMux) *PublicDownloaderAPI { api := &PublicDownloaderAPI{ d: d, mux: m, installSyncSubscription: make(chan chan interface{}), uninstallSyncSubscription: make(chan *uninstallSyncSubscriptionRequest), } go api.eventLoop() return api } // eventLoop runs an loop until the event mux closes. It will install and uninstall new // sync subscriptions and broadcasts sync status updates to the installed sync subscriptions. func (api *PublicDownloaderAPI) eventLoop() { var ( sub = api.mux.Subscribe(StartEvent{}, DoneEvent{}, FailedEvent{}) syncSubscriptions = make(map[chan interface{}]struct{}) ) for { select { case i := <-api.installSyncSubscription: syncSubscriptions[i] = struct{}{} case u := <-api.uninstallSyncSubscription: delete(syncSubscriptions, u.c) close(u.uninstalled) case event := <-sub.Chan(): if event == nil { return } var notification interface{} switch event.Data.(type) { case StartEvent: notification = &SyncingResult{ Syncing: true, Status: api.d.Progress(), } case DoneEvent, FailedEvent: notification = false } // broadcast for c := range syncSubscriptions { c <- notification } } } } // Syncing provides information when this nodes starts synchronising with the Ethereum network and when it's finished. func (api *PublicDownloaderAPI) Syncing(ctx context.Context) (*rpc.Subscription, error) { notifier, supported := rpc.NotifierFromContext(ctx) if !supported { return &rpc.Subscription{}, rpc.ErrNotificationsUnsupported } rpcSub := notifier.CreateSubscription() go func() { statuses := make(chan interface{}) sub := api.SubscribeSyncStatus(statuses) for { select { case status := <-statuses: notifier.Notify(rpcSub.ID, status) case <-rpcSub.Err(): sub.Unsubscribe() return case <-notifier.Closed(): sub.Unsubscribe() return } } }() return rpcSub, nil } // SyncingResult provides information about the current synchronisation status for this node. type SyncingResult struct { Syncing bool `json:"syncing"` Status ethereum.SyncProgress `json:"status"` } // uninstallSyncSubscriptionRequest uninstalles a syncing subscription in the API event loop. type uninstallSyncSubscriptionRequest struct { c chan interface{} uninstalled chan interface{} } // SyncStatusSubscription represents a syncing subscription. type SyncStatusSubscription struct { api *PublicDownloaderAPI // register subscription in event loop of this api instance c chan interface{} // channel where events are broadcasted to unsubOnce sync.Once // make sure unsubscribe logic is executed once } // Unsubscribe uninstalls the subscription from the DownloadAPI event loop. // The status channel that was passed to subscribeSyncStatus isn't used anymore // after this method returns. func (s *SyncStatusSubscription) Unsubscribe() { s.unsubOnce.Do(func() { req := uninstallSyncSubscriptionRequest{s.c, make(chan interface{})} s.api.uninstallSyncSubscription <- &req for { select { case <-s.c: // drop new status events until uninstall confirmation continue case <-req.uninstalled: return } } }) } // SubscribeSyncStatus creates a subscription that will broadcast new synchronisation updates. // The given channel must receive interface values, the result can either func (api *PublicDownloaderAPI) SubscribeSyncStatus(status chan interface{}) *SyncStatusSubscription { api.installSyncSubscription <- status return &SyncStatusSubscription{api: api, c: status} }
eth/downloader/api.go
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.00030264342785812914, 0.00017636845586821437, 0.00016261154087260365, 0.00016761294682510197, 0.00003173591539962217 ]
{ "id": 5, "code_window": [ "\t{input: `\"0x1zz01\"`, wantErr: ErrSyntax},\n", "\n", "\t// valid encoding\n", "\t{input: `\"0x0\"`, want: big.NewInt(0)},\n", "\t{input: `\"0x2\"`, want: big.NewInt(0x2)},\n", "\t{input: `\"0x2F2\"`, want: big.NewInt(0x2f2)},\n", "\t{input: `\"0X2F2\"`, want: big.NewInt(0x2f2)},\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t{input: `\"\"`, want: big.NewInt(0)},\n" ], "file_path": "common/hexutil/json_test.go", "type": "add", "edit_start_line_idx": 135 }
// Copyright (c) 2012, Suryandaru Triandana <[email protected]> // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package comparer import "bytes" type bytesComparer struct{} func (bytesComparer) Compare(a, b []byte) int { return bytes.Compare(a, b) } func (bytesComparer) Name() string { return "leveldb.BytewiseComparator" } func (bytesComparer) Separator(dst, a, b []byte) []byte { i, n := 0, len(a) if n > len(b) { n = len(b) } for ; i < n && a[i] == b[i]; i++ { } if i >= n { // Do not shorten if one string is a prefix of the other } else if c := a[i]; c < 0xff && c+1 < b[i] { dst = append(dst, a[:i+1]...) dst[i]++ return dst } return nil } func (bytesComparer) Successor(dst, b []byte) []byte { for i, c := range b { if c != 0xff { dst = append(dst, b[:i+1]...) dst[i]++ return dst } } return nil } // DefaultComparer are default implementation of the Comparer interface. // It uses the natural ordering, consistent with bytes.Compare. var DefaultComparer = bytesComparer{}
vendor/github.com/syndtr/goleveldb/leveldb/comparer/bytes_comparer.go
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.0005808256100863218, 0.00029143484425731003, 0.00016623616102151573, 0.00018709039431996644, 0.00016576828784309328 ]
{ "id": 5, "code_window": [ "\t{input: `\"0x1zz01\"`, wantErr: ErrSyntax},\n", "\n", "\t// valid encoding\n", "\t{input: `\"0x0\"`, want: big.NewInt(0)},\n", "\t{input: `\"0x2\"`, want: big.NewInt(0x2)},\n", "\t{input: `\"0x2F2\"`, want: big.NewInt(0x2f2)},\n", "\t{input: `\"0X2F2\"`, want: big.NewInt(0x2f2)},\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t{input: `\"\"`, want: big.NewInt(0)},\n" ], "file_path": "common/hexutil/json_test.go", "type": "add", "edit_start_line_idx": 135 }
// Copyright 2016 Zack Guo <[email protected]>. All rights reserved. // Use of this source code is governed by a MIT license that can // be found in the LICENSE file. package termui // Par displays a paragraph. /* par := termui.NewPar("Simple Text") par.Height = 3 par.Width = 17 par.BorderLabel = "Label" */ type Par struct { Block Text string TextFgColor Attribute TextBgColor Attribute WrapLength int // words wrap limit. Note it may not work properly with multi-width char } // NewPar returns a new *Par with given text as its content. func NewPar(s string) *Par { return &Par{ Block: *NewBlock(), Text: s, TextFgColor: ThemeAttr("par.text.fg"), TextBgColor: ThemeAttr("par.text.bg"), WrapLength: 0, } } // Buffer implements Bufferer interface. func (p *Par) Buffer() Buffer { buf := p.Block.Buffer() fg, bg := p.TextFgColor, p.TextBgColor cs := DefaultTxBuilder.Build(p.Text, fg, bg) // wrap if WrapLength set if p.WrapLength < 0 { cs = wrapTx(cs, p.Width-2) } else if p.WrapLength > 0 { cs = wrapTx(cs, p.WrapLength) } y, x, n := 0, 0, 0 for y < p.innerArea.Dy() && n < len(cs) { w := cs[n].Width() if cs[n].Ch == '\n' || x+w > p.innerArea.Dx() { y++ x = 0 // set x = 0 if cs[n].Ch == '\n' { n++ } if y >= p.innerArea.Dy() { buf.Set(p.innerArea.Min.X+p.innerArea.Dx()-1, p.innerArea.Min.Y+p.innerArea.Dy()-1, Cell{Ch: '…', Fg: p.TextFgColor, Bg: p.TextBgColor}) break } continue } buf.Set(p.innerArea.Min.X+x, p.innerArea.Min.Y+y, cs[n]) n++ x += w } return buf }
vendor/github.com/gizak/termui/par.go
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.00017640470468904823, 0.00017076515359804034, 0.00016038698959164321, 0.00017102962010540068, 0.000004495866960496642 ]
{ "id": 6, "code_window": [ "\t// invalid encoding\n", "\t{input: \"\", wantErr: errNonString},\n", "\t{input: \"null\", wantErr: errNonString},\n", "\t{input: \"10\", wantErr: errNonString},\n", "\t{input: `\"\"`, wantErr: ErrEmptyString},\n", "\t{input: `\"0\"`, wantErr: ErrMissingPrefix},\n", "\t{input: `\"0x\"`, wantErr: ErrEmptyNumber},\n", "\t{input: `\"0x01\"`, wantErr: ErrLeadingZero},\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "common/hexutil/json_test.go", "type": "replace", "edit_start_line_idx": 200 }
// Copyright 2016 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package hexutil import ( "bytes" "encoding/hex" "math/big" "testing" ) func checkError(t *testing.T, input string, got, want error) bool { if got == nil { if want != nil { t.Errorf("input %s: got no error, want %q", input, want) return false } return true } if want == nil { t.Errorf("input %s: unexpected error %q", input, got) } else if got.Error() != want.Error() { t.Errorf("input %s: got error %q, want %q", input, got, want) } return false } func referenceBig(s string) *big.Int { b, ok := new(big.Int).SetString(s, 16) if !ok { panic("invalid") } return b } func referenceBytes(s string) []byte { b, err := hex.DecodeString(s) if err != nil { panic(err) } return b } var unmarshalBytesTests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x0"`, wantErr: ErrOddLength}, {input: `"0xxx"`, wantErr: ErrSyntax}, {input: `"0x01zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x"`, want: referenceBytes("")}, {input: `"0x02"`, want: referenceBytes("02")}, {input: `"0X02"`, want: referenceBytes("02")}, {input: `"0xffffffffff"`, want: referenceBytes("ffffffffff")}, { input: `"0xffffffffffffffffffffffffffffffffffff"`, want: referenceBytes("ffffffffffffffffffffffffffffffffffff"), }, } func TestUnmarshalBytes(t *testing.T) { for _, test := range unmarshalBytesTests { var v Bytes err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if !bytes.Equal(test.want.([]byte), []byte(v)) { t.Errorf("input %s: value mismatch: got %x, want %x", test.input, &v, test.want) continue } } } func BenchmarkUnmarshalBytes(b *testing.B) { input := []byte(`"0x123456789abcdef123456789abcdef"`) for i := 0; i < b.N; i++ { var v Bytes if err := v.UnmarshalJSON(input); err != nil { b.Fatal(err) } } } func TestMarshalBytes(t *testing.T) { for _, test := range encodeBytesTests { in := test.input.([]byte) out, err := Bytes(in).MarshalJSON() if err != nil { t.Errorf("%x: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%x: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := Bytes(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } } var unmarshalBigTests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x"`, wantErr: ErrEmptyNumber}, {input: `"0x01"`, wantErr: ErrLeadingZero}, {input: `"0xx"`, wantErr: ErrSyntax}, {input: `"0x1zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x0"`, want: big.NewInt(0)}, {input: `"0x2"`, want: big.NewInt(0x2)}, {input: `"0x2F2"`, want: big.NewInt(0x2f2)}, {input: `"0X2F2"`, want: big.NewInt(0x2f2)}, {input: `"0x1122aaff"`, want: big.NewInt(0x1122aaff)}, {input: `"0xbBb"`, want: big.NewInt(0xbbb)}, {input: `"0xfffffffff"`, want: big.NewInt(0xfffffffff)}, { input: `"0x112233445566778899aabbccddeeff"`, want: referenceBig("112233445566778899aabbccddeeff"), }, { input: `"0xffffffffffffffffffffffffffffffffffff"`, want: referenceBig("ffffffffffffffffffffffffffffffffffff"), }, } func TestUnmarshalBig(t *testing.T) { for _, test := range unmarshalBigTests { var v Big err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if test.want != nil && test.want.(*big.Int).Cmp((*big.Int)(&v)) != 0 { t.Errorf("input %s: value mismatch: got %x, want %x", test.input, (*big.Int)(&v), test.want) continue } } } func BenchmarkUnmarshalBig(b *testing.B) { input := []byte(`"0x123456789abcdef123456789abcdef"`) for i := 0; i < b.N; i++ { var v Big if err := v.UnmarshalJSON(input); err != nil { b.Fatal(err) } } } func TestMarshalBig(t *testing.T) { for _, test := range encodeBigTests { in := test.input.(*big.Int) out, err := (*Big)(in).MarshalJSON() if err != nil { t.Errorf("%d: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%d: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := (*Big)(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } } var unmarshalUint64Tests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x"`, wantErr: ErrEmptyNumber}, {input: `"0x01"`, wantErr: ErrLeadingZero}, {input: `"0xfffffffffffffffff"`, wantErr: ErrUint64Range}, {input: `"0xx"`, wantErr: ErrSyntax}, {input: `"0x1zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x0"`, want: uint64(0)}, {input: `"0x2"`, want: uint64(0x2)}, {input: `"0x2F2"`, want: uint64(0x2f2)}, {input: `"0X2F2"`, want: uint64(0x2f2)}, {input: `"0x1122aaff"`, want: uint64(0x1122aaff)}, {input: `"0xbbb"`, want: uint64(0xbbb)}, {input: `"0xffffffffffffffff"`, want: uint64(0xffffffffffffffff)}, } func TestUnmarshalUint64(t *testing.T) { for _, test := range unmarshalUint64Tests { var v Uint64 err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if uint64(v) != test.want.(uint64) { t.Errorf("input %s: value mismatch: got %d, want %d", test.input, v, test.want) continue } } } func BenchmarkUnmarshalUint64(b *testing.B) { input := []byte(`"0x123456789abcdf"`) for i := 0; i < b.N; i++ { var v Uint64 v.UnmarshalJSON(input) } } func TestMarshalUint64(t *testing.T) { for _, test := range encodeUint64Tests { in := test.input.(uint64) out, err := Uint64(in).MarshalJSON() if err != nil { t.Errorf("%d: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%d: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := (Uint64)(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } }
common/hexutil/json_test.go
1
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.7433958649635315, 0.04190244898200035, 0.00016417886945419014, 0.00017555493104737252, 0.14917293190956116 ]
{ "id": 6, "code_window": [ "\t// invalid encoding\n", "\t{input: \"\", wantErr: errNonString},\n", "\t{input: \"null\", wantErr: errNonString},\n", "\t{input: \"10\", wantErr: errNonString},\n", "\t{input: `\"\"`, wantErr: ErrEmptyString},\n", "\t{input: `\"0\"`, wantErr: ErrMissingPrefix},\n", "\t{input: `\"0x\"`, wantErr: ErrEmptyNumber},\n", "\t{input: `\"0x01\"`, wantErr: ErrLeadingZero},\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "common/hexutil/json_test.go", "type": "replace", "edit_start_line_idx": 200 }
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,solaris package unix // TODO(aram): remove these before Go 1.3. const ( SYS_EXECVE = 59 SYS_FCNTL = 62 )
vendor/golang.org/x/sys/unix/zsysnum_solaris_amd64.go
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.00017592866788618267, 0.00017308822134509683, 0.000170247774804011, 0.00017308822134509683, 0.0000028404465410858393 ]
{ "id": 6, "code_window": [ "\t// invalid encoding\n", "\t{input: \"\", wantErr: errNonString},\n", "\t{input: \"null\", wantErr: errNonString},\n", "\t{input: \"10\", wantErr: errNonString},\n", "\t{input: `\"\"`, wantErr: ErrEmptyString},\n", "\t{input: `\"0\"`, wantErr: ErrMissingPrefix},\n", "\t{input: `\"0x\"`, wantErr: ErrEmptyNumber},\n", "\t{input: `\"0x01\"`, wantErr: ErrLeadingZero},\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "common/hexutil/json_test.go", "type": "replace", "edit_start_line_idx": 200 }
{ "randomStatetest" : { "env" : { "currentCoinbase" : "945304eb96065b2a98b57a48a06ae28d285a71b5", "currentDifficulty" : "0x051d6a3cd647", "currentGasLimit" : "0x7fffffffffffffff", "currentNumber" : "0x00", "currentTimestamp" : "0x01", "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6" }, "logs" : [ ], "out" : "0x", "post" : { "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { "balance" : "0x0de0b6b3a76586a0", "code" : "0x43424244457943455409635939", "nonce" : "0x00", "storage" : { } }, "945304eb96065b2a98b57a48a06ae28d285a71b5" : { "balance" : "0x5287", "code" : "0x6000355415600957005b60203560003555", "nonce" : "0x00", "storage" : { } }, "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { "balance" : "0x0de0b6b3a7622707", "code" : "0x", "nonce" : "0x01", "storage" : { } } }, "postStateRoot" : "68ffa9dca5523569e248a9eea9d426c5a155f3a1e942187d6487ab3b5c8e949e", "pre" : { "095e7baea6a6c7c4c2dfeb977efac326af552d87" : { "balance" : "0x0de0b6b3a7640000", "code" : "0x43424244457943455409635939", "nonce" : "0x00", "storage" : { } }, "945304eb96065b2a98b57a48a06ae28d285a71b5" : { "balance" : "0x2e", "code" : "0x6000355415600957005b60203560003555", "nonce" : "0x00", "storage" : { } }, "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { "balance" : "0x0de0b6b3a7640000", "code" : "0x", "nonce" : "0x00", "storage" : { } } }, "transaction" : { "data" : "0x42", "gasLimit" : "0x061a80", "gasPrice" : "0x01", "nonce" : "0x00", "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", "to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87", "value" : "0x0186a0" } } }
tests/files/StateTests/RandomTests/st201503140002PYTHON.json
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.00017385170212946832, 0.0001682250149315223, 0.00016405072528868914, 0.00016758040874265134, 0.000003722032261066488 ]
{ "id": 6, "code_window": [ "\t// invalid encoding\n", "\t{input: \"\", wantErr: errNonString},\n", "\t{input: \"null\", wantErr: errNonString},\n", "\t{input: \"10\", wantErr: errNonString},\n", "\t{input: `\"\"`, wantErr: ErrEmptyString},\n", "\t{input: `\"0\"`, wantErr: ErrMissingPrefix},\n", "\t{input: `\"0x\"`, wantErr: ErrEmptyNumber},\n", "\t{input: `\"0x01\"`, wantErr: ErrLeadingZero},\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "common/hexutil/json_test.go", "type": "replace", "edit_start_line_idx": 200 }
package: github.com/gizak/termui import: - package: github.com/mattn/go-runewidth - package: github.com/mitchellh/go-wordwrap - package: github.com/nsf/termbox-go - package: golang.org/x/net subpackages: - websocket - package: github.com/maruel/panicparse
vendor/github.com/gizak/termui/glide.yaml
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.00017518927052151412, 0.00017518927052151412, 0.00017518927052151412, 0.00017518927052151412, 0 ]
{ "id": 7, "code_window": [ "\t{input: `\"0xfffffffffffffffff\"`, wantErr: ErrUint64Range},\n", "\t{input: `\"0xx\"`, wantErr: ErrSyntax},\n", "\t{input: `\"0x1zz01\"`, wantErr: ErrSyntax},\n", "\n", "\t// valid encoding\n", "\t{input: `\"0x0\"`, want: uint64(0)},\n", "\t{input: `\"0x2\"`, want: uint64(0x2)},\n", "\t{input: `\"0x2F2\"`, want: uint64(0x2f2)},\n", "\t{input: `\"0X2F2\"`, want: uint64(0x2f2)},\n", "\t{input: `\"0x1122aaff\"`, want: uint64(0x1122aaff)},\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t{input: `\"\"`, want: uint64(0)},\n" ], "file_path": "common/hexutil/json_test.go", "type": "add", "edit_start_line_idx": 209 }
// Copyright 2016 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package hexutil import ( "bytes" "encoding/hex" "math/big" "testing" ) func checkError(t *testing.T, input string, got, want error) bool { if got == nil { if want != nil { t.Errorf("input %s: got no error, want %q", input, want) return false } return true } if want == nil { t.Errorf("input %s: unexpected error %q", input, got) } else if got.Error() != want.Error() { t.Errorf("input %s: got error %q, want %q", input, got, want) } return false } func referenceBig(s string) *big.Int { b, ok := new(big.Int).SetString(s, 16) if !ok { panic("invalid") } return b } func referenceBytes(s string) []byte { b, err := hex.DecodeString(s) if err != nil { panic(err) } return b } var unmarshalBytesTests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x0"`, wantErr: ErrOddLength}, {input: `"0xxx"`, wantErr: ErrSyntax}, {input: `"0x01zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x"`, want: referenceBytes("")}, {input: `"0x02"`, want: referenceBytes("02")}, {input: `"0X02"`, want: referenceBytes("02")}, {input: `"0xffffffffff"`, want: referenceBytes("ffffffffff")}, { input: `"0xffffffffffffffffffffffffffffffffffff"`, want: referenceBytes("ffffffffffffffffffffffffffffffffffff"), }, } func TestUnmarshalBytes(t *testing.T) { for _, test := range unmarshalBytesTests { var v Bytes err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if !bytes.Equal(test.want.([]byte), []byte(v)) { t.Errorf("input %s: value mismatch: got %x, want %x", test.input, &v, test.want) continue } } } func BenchmarkUnmarshalBytes(b *testing.B) { input := []byte(`"0x123456789abcdef123456789abcdef"`) for i := 0; i < b.N; i++ { var v Bytes if err := v.UnmarshalJSON(input); err != nil { b.Fatal(err) } } } func TestMarshalBytes(t *testing.T) { for _, test := range encodeBytesTests { in := test.input.([]byte) out, err := Bytes(in).MarshalJSON() if err != nil { t.Errorf("%x: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%x: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := Bytes(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } } var unmarshalBigTests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x"`, wantErr: ErrEmptyNumber}, {input: `"0x01"`, wantErr: ErrLeadingZero}, {input: `"0xx"`, wantErr: ErrSyntax}, {input: `"0x1zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x0"`, want: big.NewInt(0)}, {input: `"0x2"`, want: big.NewInt(0x2)}, {input: `"0x2F2"`, want: big.NewInt(0x2f2)}, {input: `"0X2F2"`, want: big.NewInt(0x2f2)}, {input: `"0x1122aaff"`, want: big.NewInt(0x1122aaff)}, {input: `"0xbBb"`, want: big.NewInt(0xbbb)}, {input: `"0xfffffffff"`, want: big.NewInt(0xfffffffff)}, { input: `"0x112233445566778899aabbccddeeff"`, want: referenceBig("112233445566778899aabbccddeeff"), }, { input: `"0xffffffffffffffffffffffffffffffffffff"`, want: referenceBig("ffffffffffffffffffffffffffffffffffff"), }, } func TestUnmarshalBig(t *testing.T) { for _, test := range unmarshalBigTests { var v Big err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if test.want != nil && test.want.(*big.Int).Cmp((*big.Int)(&v)) != 0 { t.Errorf("input %s: value mismatch: got %x, want %x", test.input, (*big.Int)(&v), test.want) continue } } } func BenchmarkUnmarshalBig(b *testing.B) { input := []byte(`"0x123456789abcdef123456789abcdef"`) for i := 0; i < b.N; i++ { var v Big if err := v.UnmarshalJSON(input); err != nil { b.Fatal(err) } } } func TestMarshalBig(t *testing.T) { for _, test := range encodeBigTests { in := test.input.(*big.Int) out, err := (*Big)(in).MarshalJSON() if err != nil { t.Errorf("%d: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%d: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := (*Big)(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } } var unmarshalUint64Tests = []unmarshalTest{ // invalid encoding {input: "", wantErr: errNonString}, {input: "null", wantErr: errNonString}, {input: "10", wantErr: errNonString}, {input: `""`, wantErr: ErrEmptyString}, {input: `"0"`, wantErr: ErrMissingPrefix}, {input: `"0x"`, wantErr: ErrEmptyNumber}, {input: `"0x01"`, wantErr: ErrLeadingZero}, {input: `"0xfffffffffffffffff"`, wantErr: ErrUint64Range}, {input: `"0xx"`, wantErr: ErrSyntax}, {input: `"0x1zz01"`, wantErr: ErrSyntax}, // valid encoding {input: `"0x0"`, want: uint64(0)}, {input: `"0x2"`, want: uint64(0x2)}, {input: `"0x2F2"`, want: uint64(0x2f2)}, {input: `"0X2F2"`, want: uint64(0x2f2)}, {input: `"0x1122aaff"`, want: uint64(0x1122aaff)}, {input: `"0xbbb"`, want: uint64(0xbbb)}, {input: `"0xffffffffffffffff"`, want: uint64(0xffffffffffffffff)}, } func TestUnmarshalUint64(t *testing.T) { for _, test := range unmarshalUint64Tests { var v Uint64 err := v.UnmarshalJSON([]byte(test.input)) if !checkError(t, test.input, err, test.wantErr) { continue } if uint64(v) != test.want.(uint64) { t.Errorf("input %s: value mismatch: got %d, want %d", test.input, v, test.want) continue } } } func BenchmarkUnmarshalUint64(b *testing.B) { input := []byte(`"0x123456789abcdf"`) for i := 0; i < b.N; i++ { var v Uint64 v.UnmarshalJSON(input) } } func TestMarshalUint64(t *testing.T) { for _, test := range encodeUint64Tests { in := test.input.(uint64) out, err := Uint64(in).MarshalJSON() if err != nil { t.Errorf("%d: %v", in, err) continue } if want := `"` + test.want + `"`; string(out) != want { t.Errorf("%d: MarshalJSON output mismatch: got %q, want %q", in, out, want) continue } if out := (Uint64)(in).String(); out != test.want { t.Errorf("%x: String mismatch: got %q, want %q", in, out, test.want) continue } } }
common/hexutil/json_test.go
1
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.9253779053688049, 0.04621094465255737, 0.00016076456813607365, 0.00019501050701364875, 0.17996755242347717 ]
{ "id": 7, "code_window": [ "\t{input: `\"0xfffffffffffffffff\"`, wantErr: ErrUint64Range},\n", "\t{input: `\"0xx\"`, wantErr: ErrSyntax},\n", "\t{input: `\"0x1zz01\"`, wantErr: ErrSyntax},\n", "\n", "\t// valid encoding\n", "\t{input: `\"0x0\"`, want: uint64(0)},\n", "\t{input: `\"0x2\"`, want: uint64(0x2)},\n", "\t{input: `\"0x2F2\"`, want: uint64(0x2f2)},\n", "\t{input: `\"0X2F2\"`, want: uint64(0x2f2)},\n", "\t{input: `\"0x1122aaff\"`, want: uint64(0x1122aaff)},\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t{input: `\"\"`, want: uint64(0)},\n" ], "file_path": "common/hexutil/json_test.go", "type": "add", "edit_start_line_idx": 209 }
// 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. // +build ignore package main // This program generates table.go and table_test.go. // Invoke as // // go run gen.go |gofmt >table.go // go run gen.go -test |gofmt >table_test.go import ( "flag" "fmt" "math/rand" "os" "sort" "strings" ) // identifier converts s to a Go exported identifier. // It converts "div" to "Div" and "accept-charset" to "AcceptCharset". func identifier(s string) string { b := make([]byte, 0, len(s)) cap := true for _, c := range s { if c == '-' { cap = true continue } if cap && 'a' <= c && c <= 'z' { c -= 'a' - 'A' } cap = false b = append(b, byte(c)) } return string(b) } var test = flag.Bool("test", false, "generate table_test.go") func main() { flag.Parse() var all []string all = append(all, elements...) all = append(all, attributes...) all = append(all, eventHandlers...) all = append(all, extra...) sort.Strings(all) if *test { fmt.Printf("// generated by go run gen.go -test; DO NOT EDIT\n\n") fmt.Printf("package atom\n\n") fmt.Printf("var testAtomList = []string{\n") for _, s := range all { fmt.Printf("\t%q,\n", s) } fmt.Printf("}\n") return } // uniq - lists have dups // compute max len too maxLen := 0 w := 0 for _, s := range all { if w == 0 || all[w-1] != s { if maxLen < len(s) { maxLen = len(s) } all[w] = s w++ } } all = all[:w] // Find hash that minimizes table size. var best *table for i := 0; i < 1000000; i++ { if best != nil && 1<<(best.k-1) < len(all) { break } h := rand.Uint32() for k := uint(0); k <= 16; k++ { if best != nil && k >= best.k { break } var t table if t.init(h, k, all) { best = &t break } } } if best == nil { fmt.Fprintf(os.Stderr, "failed to construct string table\n") os.Exit(1) } // Lay out strings, using overlaps when possible. layout := append([]string{}, all...) // Remove strings that are substrings of other strings for changed := true; changed; { changed = false for i, s := range layout { if s == "" { continue } for j, t := range layout { if i != j && t != "" && strings.Contains(s, t) { changed = true layout[j] = "" } } } } // Join strings where one suffix matches another prefix. for { // Find best i, j, k such that layout[i][len-k:] == layout[j][:k], // maximizing overlap length k. besti := -1 bestj := -1 bestk := 0 for i, s := range layout { if s == "" { continue } for j, t := range layout { if i == j { continue } for k := bestk + 1; k <= len(s) && k <= len(t); k++ { if s[len(s)-k:] == t[:k] { besti = i bestj = j bestk = k } } } } if bestk > 0 { layout[besti] += layout[bestj][bestk:] layout[bestj] = "" continue } break } text := strings.Join(layout, "") atom := map[string]uint32{} for _, s := range all { off := strings.Index(text, s) if off < 0 { panic("lost string " + s) } atom[s] = uint32(off<<8 | len(s)) } // Generate the Go code. fmt.Printf("// generated by go run gen.go; DO NOT EDIT\n\n") fmt.Printf("package atom\n\nconst (\n") for _, s := range all { fmt.Printf("\t%s Atom = %#x\n", identifier(s), atom[s]) } fmt.Printf(")\n\n") fmt.Printf("const hash0 = %#x\n\n", best.h0) fmt.Printf("const maxAtomLen = %d\n\n", maxLen) fmt.Printf("var table = [1<<%d]Atom{\n", best.k) for i, s := range best.tab { if s == "" { continue } fmt.Printf("\t%#x: %#x, // %s\n", i, atom[s], s) } fmt.Printf("}\n") datasize := (1 << best.k) * 4 fmt.Printf("const atomText =\n") textsize := len(text) for len(text) > 60 { fmt.Printf("\t%q +\n", text[:60]) text = text[60:] } fmt.Printf("\t%q\n\n", text) fmt.Fprintf(os.Stderr, "%d atoms; %d string bytes + %d tables = %d total data\n", len(all), textsize, datasize, textsize+datasize) } type byLen []string func (x byLen) Less(i, j int) bool { return len(x[i]) > len(x[j]) } func (x byLen) Swap(i, j int) { x[i], x[j] = x[j], x[i] } func (x byLen) Len() int { return len(x) } // fnv computes the FNV hash with an arbitrary starting value h. func fnv(h uint32, s string) uint32 { for i := 0; i < len(s); i++ { h ^= uint32(s[i]) h *= 16777619 } return h } // A table represents an attempt at constructing the lookup table. // The lookup table uses cuckoo hashing, meaning that each string // can be found in one of two positions. type table struct { h0 uint32 k uint mask uint32 tab []string } // hash returns the two hashes for s. func (t *table) hash(s string) (h1, h2 uint32) { h := fnv(t.h0, s) h1 = h & t.mask h2 = (h >> 16) & t.mask return } // init initializes the table with the given parameters. // h0 is the initial hash value, // k is the number of bits of hash value to use, and // x is the list of strings to store in the table. // init returns false if the table cannot be constructed. func (t *table) init(h0 uint32, k uint, x []string) bool { t.h0 = h0 t.k = k t.tab = make([]string, 1<<k) t.mask = 1<<k - 1 for _, s := range x { if !t.insert(s) { return false } } return true } // insert inserts s in the table. func (t *table) insert(s string) bool { h1, h2 := t.hash(s) if t.tab[h1] == "" { t.tab[h1] = s return true } if t.tab[h2] == "" { t.tab[h2] = s return true } if t.push(h1, 0) { t.tab[h1] = s return true } if t.push(h2, 0) { t.tab[h2] = s return true } return false } // push attempts to push aside the entry in slot i. func (t *table) push(i uint32, depth int) bool { if depth > len(t.tab) { return false } s := t.tab[i] h1, h2 := t.hash(s) j := h1 + h2 - i if t.tab[j] != "" && !t.push(j, depth+1) { return false } t.tab[j] = s return true } // The lists of element names and attribute keys were taken from // https://html.spec.whatwg.org/multipage/indices.html#index // as of the "HTML Living Standard - Last Updated 21 February 2015" version. var elements = []string{ "a", "abbr", "address", "area", "article", "aside", "audio", "b", "base", "bdi", "bdo", "blockquote", "body", "br", "button", "canvas", "caption", "cite", "code", "col", "colgroup", "command", "data", "datalist", "dd", "del", "details", "dfn", "dialog", "div", "dl", "dt", "em", "embed", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "iframe", "img", "input", "ins", "kbd", "keygen", "label", "legend", "li", "link", "map", "mark", "menu", "menuitem", "meta", "meter", "nav", "noscript", "object", "ol", "optgroup", "option", "output", "p", "param", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "script", "section", "select", "small", "source", "span", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "track", "u", "ul", "var", "video", "wbr", } // https://html.spec.whatwg.org/multipage/indices.html#attributes-3 var attributes = []string{ "abbr", "accept", "accept-charset", "accesskey", "action", "alt", "async", "autocomplete", "autofocus", "autoplay", "challenge", "charset", "checked", "cite", "class", "cols", "colspan", "command", "content", "contenteditable", "contextmenu", "controls", "coords", "crossorigin", "data", "datetime", "default", "defer", "dir", "dirname", "disabled", "download", "draggable", "dropzone", "enctype", "for", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "headers", "height", "hidden", "high", "href", "hreflang", "http-equiv", "icon", "id", "inputmode", "ismap", "itemid", "itemprop", "itemref", "itemscope", "itemtype", "keytype", "kind", "label", "lang", "list", "loop", "low", "manifest", "max", "maxlength", "media", "mediagroup", "method", "min", "minlength", "multiple", "muted", "name", "novalidate", "open", "optimum", "pattern", "ping", "placeholder", "poster", "preload", "radiogroup", "readonly", "rel", "required", "reversed", "rows", "rowspan", "sandbox", "spellcheck", "scope", "scoped", "seamless", "selected", "shape", "size", "sizes", "sortable", "sorted", "span", "src", "srcdoc", "srclang", "start", "step", "style", "tabindex", "target", "title", "translate", "type", "typemustmatch", "usemap", "value", "width", "wrap", } var eventHandlers = []string{ "onabort", "onautocomplete", "onautocompleteerror", "onafterprint", "onbeforeprint", "onbeforeunload", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "onhashchange", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onlanguagechange", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmessage", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onoffline", "ononline", "onpagehide", "onpageshow", "onpause", "onplay", "onplaying", "onpopstate", "onprogress", "onratechange", "onreset", "onresize", "onscroll", "onseeked", "onseeking", "onselect", "onshow", "onsort", "onstalled", "onstorage", "onsubmit", "onsuspend", "ontimeupdate", "ontoggle", "onunload", "onvolumechange", "onwaiting", } // extra are ad-hoc values not covered by any of the lists above. var extra = []string{ "align", "annotation", "annotation-xml", "applet", "basefont", "bgsound", "big", "blink", "center", "color", "desc", "face", "font", "foreignObject", // HTML is case-insensitive, but SVG-embedded-in-HTML is case-sensitive. "foreignobject", "frame", "frameset", "image", "isindex", "listing", "malignmark", "marquee", "math", "mglyph", "mi", "mn", "mo", "ms", "mtext", "nobr", "noembed", "noframes", "plaintext", "prompt", "public", "spacer", "strike", "svg", "system", "tt", "xmp", }
vendor/golang.org/x/net/html/atom/gen.go
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.00017801990907173604, 0.0001686133909970522, 0.00016067108663264662, 0.00016835903807077557, 0.0000032194714094657684 ]
{ "id": 7, "code_window": [ "\t{input: `\"0xfffffffffffffffff\"`, wantErr: ErrUint64Range},\n", "\t{input: `\"0xx\"`, wantErr: ErrSyntax},\n", "\t{input: `\"0x1zz01\"`, wantErr: ErrSyntax},\n", "\n", "\t// valid encoding\n", "\t{input: `\"0x0\"`, want: uint64(0)},\n", "\t{input: `\"0x2\"`, want: uint64(0x2)},\n", "\t{input: `\"0x2F2\"`, want: uint64(0x2f2)},\n", "\t{input: `\"0X2F2\"`, want: uint64(0x2f2)},\n", "\t{input: `\"0x1122aaff\"`, want: uint64(0x1122aaff)},\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t{input: `\"\"`, want: uint64(0)},\n" ], "file_path": "common/hexutil/json_test.go", "type": "add", "edit_start_line_idx": 209 }
// Copyright 2016 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package abi import ( "fmt" "reflect" ) // formatSliceString formats the reflection kind with the given slice size // and returns a formatted string representation. func formatSliceString(kind reflect.Kind, sliceSize int) string { if sliceSize == -1 { return fmt.Sprintf("[]%v", kind) } return fmt.Sprintf("[%d]%v", sliceSize, kind) } // sliceTypeCheck checks that the given slice can by assigned to the reflection // type in t. func sliceTypeCheck(t Type, val reflect.Value) error { if val.Kind() != reflect.Slice && val.Kind() != reflect.Array { return typeErr(formatSliceString(t.Kind, t.SliceSize), val.Type()) } if t.IsArray && val.Len() != t.SliceSize { return typeErr(formatSliceString(t.Elem.Kind, t.SliceSize), formatSliceString(val.Type().Elem().Kind(), val.Len())) } if t.Elem.IsSlice { if val.Len() > 0 { return sliceTypeCheck(*t.Elem, val.Index(0)) } } else if t.Elem.IsArray { return sliceTypeCheck(*t.Elem, val.Index(0)) } if elemKind := val.Type().Elem().Kind(); elemKind != t.Elem.Kind { return typeErr(formatSliceString(t.Elem.Kind, t.SliceSize), val.Type()) } return nil } // typeCheck checks that the given reflection value can be assigned to the reflection // type in t. func typeCheck(t Type, value reflect.Value) error { if t.IsSlice || t.IsArray { return sliceTypeCheck(t, value) } // Check base type validity. Element types will be checked later on. if t.Kind != value.Kind() { return typeErr(t.Kind, value.Kind()) } return nil } // varErr returns a formatted error. func varErr(expected, got reflect.Kind) error { return typeErr(expected, got) } // typeErr returns a formatted type casting error. func typeErr(expected, got interface{}) error { return fmt.Errorf("abi: cannot use %v as type %v as argument", got, expected) }
accounts/abi/error.go
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.0013044545194134116, 0.00031136826146394014, 0.0001639539113966748, 0.00017021983512677252, 0.00037537567550316453 ]
{ "id": 7, "code_window": [ "\t{input: `\"0xfffffffffffffffff\"`, wantErr: ErrUint64Range},\n", "\t{input: `\"0xx\"`, wantErr: ErrSyntax},\n", "\t{input: `\"0x1zz01\"`, wantErr: ErrSyntax},\n", "\n", "\t// valid encoding\n", "\t{input: `\"0x0\"`, want: uint64(0)},\n", "\t{input: `\"0x2\"`, want: uint64(0x2)},\n", "\t{input: `\"0x2F2\"`, want: uint64(0x2f2)},\n", "\t{input: `\"0X2F2\"`, want: uint64(0x2f2)},\n", "\t{input: `\"0x1122aaff\"`, want: uint64(0x1122aaff)},\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t{input: `\"\"`, want: uint64(0)},\n" ], "file_path": "common/hexutil/json_test.go", "type": "add", "edit_start_line_idx": 209 }
// Copyright 2016 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package storage // this is a clone of an earlier state of the ethereum ethdb/database // no need for queueing/caching import ( "fmt" "github.com/ethereum/go-ethereum/compression/rle" "github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb/iterator" "github.com/syndtr/goleveldb/leveldb/opt" ) const openFileLimit = 128 type LDBDatabase struct { db *leveldb.DB comp bool } func NewLDBDatabase(file string) (*LDBDatabase, error) { // Open the db db, err := leveldb.OpenFile(file, &opt.Options{OpenFilesCacheCapacity: openFileLimit}) if err != nil { return nil, err } database := &LDBDatabase{db: db, comp: false} return database, nil } func (self *LDBDatabase) Put(key []byte, value []byte) { if self.comp { value = rle.Compress(value) } err := self.db.Put(key, value, nil) if err != nil { fmt.Println("Error put", err) } } func (self *LDBDatabase) Get(key []byte) ([]byte, error) { dat, err := self.db.Get(key, nil) if err != nil { return nil, err } if self.comp { return rle.Decompress(dat) } return dat, nil } func (self *LDBDatabase) Delete(key []byte) error { return self.db.Delete(key, nil) } func (self *LDBDatabase) LastKnownTD() []byte { data, _ := self.Get([]byte("LTD")) if len(data) == 0 { data = []byte{0x0} } return data } func (self *LDBDatabase) NewIterator() iterator.Iterator { return self.db.NewIterator(nil, nil) } func (self *LDBDatabase) Write(batch *leveldb.Batch) error { return self.db.Write(batch, nil) } func (self *LDBDatabase) Close() { // Close the leveldb database self.db.Close() }
swarm/storage/database.go
0
https://github.com/ethereum/go-ethereum/commit/01f6f2d741e717f669b7ba1d6b88991f28e30c72
[ 0.00019717674877028912, 0.00017135719826910645, 0.0001583723205840215, 0.00016748590860515833, 0.000010125201697519515 ]
{ "id": 0, "code_window": [ "\t}\n", "\tif body != expectedBody {\n", "\t\tt.Errorf(\"Expected body: '%s', saw: '%s'\", expectedBody, body)\n", "\t}\n", "\tfakeHandler.ValidateRequest(t, \"/foo/bar\", \"GET\", &fakeHandler.ResponseBody)\n", "}\n", "\n", "func TestRunController(t *testing.T) {\n", "\tfakeClient := FakeKubeClient{}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tfakeHandler.ValidateRequest(t, \"/foo/bar\", \"GET\", nil)\n" ], "file_path": "pkg/cloudcfg/cloudcfg_test.go", "type": "replace", "edit_start_line_idx": 168 }
/* 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 cloudcfg import ( "encoding/json" "io/ioutil" "net/http" "net/http/httptest" "testing" "github.com/GoogleCloudPlatform/kubernetes/pkg/api" "github.com/GoogleCloudPlatform/kubernetes/pkg/client" "github.com/GoogleCloudPlatform/kubernetes/pkg/util" ) // TODO: This doesn't reduce typing enough to make it worth the less readable errors. Remove. func expectNoError(t *testing.T, err error) { if err != nil { t.Errorf("Unexpected error: %#v", err) } } type Action struct { action string value interface{} } type FakeKubeClient struct { actions []Action pods api.PodList ctrl api.ReplicationController } func (client *FakeKubeClient) ListPods(labelQuery map[string]string) (api.PodList, error) { client.actions = append(client.actions, Action{action: "list-pods"}) return client.pods, nil } func (client *FakeKubeClient) GetPod(name string) (api.Pod, error) { client.actions = append(client.actions, Action{action: "get-pod", value: name}) return api.Pod{}, nil } func (client *FakeKubeClient) DeletePod(name string) error { client.actions = append(client.actions, Action{action: "delete-pod", value: name}) return nil } func (client *FakeKubeClient) CreatePod(pod api.Pod) (api.Pod, error) { client.actions = append(client.actions, Action{action: "create-pod"}) return api.Pod{}, nil } func (client *FakeKubeClient) UpdatePod(pod api.Pod) (api.Pod, error) { client.actions = append(client.actions, Action{action: "update-pod", value: pod.ID}) return api.Pod{}, nil } func (client *FakeKubeClient) GetReplicationController(name string) (api.ReplicationController, error) { client.actions = append(client.actions, Action{action: "get-controller", value: name}) return client.ctrl, nil } func (client *FakeKubeClient) CreateReplicationController(controller api.ReplicationController) (api.ReplicationController, error) { client.actions = append(client.actions, Action{action: "create-controller", value: controller}) return api.ReplicationController{}, nil } func (client *FakeKubeClient) UpdateReplicationController(controller api.ReplicationController) (api.ReplicationController, error) { client.actions = append(client.actions, Action{action: "update-controller", value: controller}) return api.ReplicationController{}, nil } func (client *FakeKubeClient) DeleteReplicationController(controller string) error { client.actions = append(client.actions, Action{action: "delete-controller", value: controller}) return nil } func (client *FakeKubeClient) GetService(name string) (api.Service, error) { client.actions = append(client.actions, Action{action: "get-controller", value: name}) return api.Service{}, nil } func (client *FakeKubeClient) CreateService(controller api.Service) (api.Service, error) { client.actions = append(client.actions, Action{action: "create-service", value: controller}) return api.Service{}, nil } func (client *FakeKubeClient) UpdateService(controller api.Service) (api.Service, error) { client.actions = append(client.actions, Action{action: "update-service", value: controller}) return api.Service{}, nil } func (client *FakeKubeClient) DeleteService(controller string) error { client.actions = append(client.actions, Action{action: "delete-service", value: controller}) return nil } func validateAction(expectedAction, actualAction Action, t *testing.T) { if expectedAction != actualAction { t.Errorf("Unexpected action: %#v, expected: %#v", actualAction, expectedAction) } } func TestUpdateWithPods(t *testing.T) { client := FakeKubeClient{ pods: api.PodList{ Items: []api.Pod{ {JSONBase: api.JSONBase{ID: "pod-1"}}, {JSONBase: api.JSONBase{ID: "pod-2"}}, }, }, } Update("foo", &client, 0) if len(client.actions) != 4 { t.Errorf("Unexpected action list %#v", client.actions) } validateAction(Action{action: "get-controller", value: "foo"}, client.actions[0], t) validateAction(Action{action: "list-pods"}, client.actions[1], t) validateAction(Action{action: "update-pod", value: "pod-1"}, client.actions[2], t) validateAction(Action{action: "update-pod", value: "pod-2"}, client.actions[3], t) } func TestUpdateNoPods(t *testing.T) { client := FakeKubeClient{} Update("foo", &client, 0) if len(client.actions) != 2 { t.Errorf("Unexpected action list %#v", client.actions) } validateAction(Action{action: "get-controller", value: "foo"}, client.actions[0], t) validateAction(Action{action: "list-pods"}, client.actions[1], t) } func TestDoRequest(t *testing.T) { expectedBody := `{ "items": []}` fakeHandler := util.FakeHandler{ StatusCode: 200, ResponseBody: expectedBody, T: t, } testServer := httptest.NewTLSServer(&fakeHandler) request, _ := http.NewRequest("GET", testServer.URL+"/foo/bar", nil) auth := client.AuthInfo{User: "user", Password: "pass"} body, err := DoRequest(request, &auth) if request.Header["Authorization"] == nil { t.Errorf("Request is missing authorization header: %#v", *request) } if err != nil { t.Error("Unexpected error") } if body != expectedBody { t.Errorf("Expected body: '%s', saw: '%s'", expectedBody, body) } fakeHandler.ValidateRequest(t, "/foo/bar", "GET", &fakeHandler.ResponseBody) } func TestRunController(t *testing.T) { fakeClient := FakeKubeClient{} name := "name" image := "foo/bar" replicas := 3 RunController(image, name, replicas, &fakeClient, "8080:80", -1) if len(fakeClient.actions) != 1 || fakeClient.actions[0].action != "create-controller" { t.Errorf("Unexpected actions: %#v", fakeClient.actions) } controller := fakeClient.actions[0].value.(api.ReplicationController) if controller.ID != name || controller.DesiredState.Replicas != replicas || controller.DesiredState.PodTemplate.DesiredState.Manifest.Containers[0].Image != image { t.Errorf("Unexpected controller: %#v", controller) } } func TestRunControllerWithService(t *testing.T) { fakeClient := FakeKubeClient{} name := "name" image := "foo/bar" replicas := 3 RunController(image, name, replicas, &fakeClient, "", 8000) if len(fakeClient.actions) != 2 || fakeClient.actions[0].action != "create-controller" || fakeClient.actions[1].action != "create-service" { t.Errorf("Unexpected actions: %#v", fakeClient.actions) } controller := fakeClient.actions[0].value.(api.ReplicationController) if controller.ID != name || controller.DesiredState.Replicas != replicas || controller.DesiredState.PodTemplate.DesiredState.Manifest.Containers[0].Image != image { t.Errorf("Unexpected controller: %#v", controller) } } func TestStopController(t *testing.T) { fakeClient := FakeKubeClient{} name := "name" StopController(name, &fakeClient) if len(fakeClient.actions) != 2 { t.Errorf("Unexpected actions: %#v", fakeClient.actions) } if fakeClient.actions[0].action != "get-controller" || fakeClient.actions[0].value.(string) != name { t.Errorf("Unexpected action: %#v", fakeClient.actions[0]) } controller := fakeClient.actions[1].value.(api.ReplicationController) if fakeClient.actions[1].action != "update-controller" || controller.DesiredState.Replicas != 0 { t.Errorf("Unexpected action: %#v", fakeClient.actions[1]) } } func TestResizeController(t *testing.T) { fakeClient := FakeKubeClient{} name := "name" replicas := 17 ResizeController(name, replicas, &fakeClient) if len(fakeClient.actions) != 2 { t.Errorf("Unexpected actions: %#v", fakeClient.actions) } if fakeClient.actions[0].action != "get-controller" || fakeClient.actions[0].value.(string) != name { t.Errorf("Unexpected action: %#v", fakeClient.actions[0]) } controller := fakeClient.actions[1].value.(api.ReplicationController) if fakeClient.actions[1].action != "update-controller" || controller.DesiredState.Replicas != 17 { t.Errorf("Unexpected action: %#v", fakeClient.actions[1]) } } func TestCloudCfgDeleteController(t *testing.T) { fakeClient := FakeKubeClient{} name := "name" err := DeleteController(name, &fakeClient) expectNoError(t, err) if len(fakeClient.actions) != 2 { t.Errorf("Unexpected actions: %#v", fakeClient.actions) } if fakeClient.actions[0].action != "get-controller" || fakeClient.actions[0].value.(string) != name { t.Errorf("Unexpected action: %#v", fakeClient.actions[0]) } if fakeClient.actions[1].action != "delete-controller" || fakeClient.actions[1].value.(string) != name { t.Errorf("Unexpected action: %#v", fakeClient.actions[1]) } } func TestCloudCfgDeleteControllerWithReplicas(t *testing.T) { fakeClient := FakeKubeClient{ ctrl: api.ReplicationController{ DesiredState: api.ReplicationControllerState{ Replicas: 2, }, }, } name := "name" err := DeleteController(name, &fakeClient) if len(fakeClient.actions) != 1 { t.Errorf("Unexpected actions: %#v", fakeClient.actions) } if fakeClient.actions[0].action != "get-controller" || fakeClient.actions[0].value.(string) != name { t.Errorf("Unexpected action: %#v", fakeClient.actions[0]) } if err == nil { t.Errorf("Unexpected non-error.") } } func TestRequestWithBodyNoSuchFile(t *testing.T) { request, err := RequestWithBody("non/existent/file.json", "http://www.google.com", "GET") if request != nil { t.Error("Unexpected non-nil result") } if err == nil { t.Error("Unexpected non-error") } } func TestRequestWithBody(t *testing.T) { file, err := ioutil.TempFile("", "foo") expectNoError(t, err) data, err := json.Marshal(api.Pod{JSONBase: api.JSONBase{ID: "foo"}}) expectNoError(t, err) _, err = file.Write(data) expectNoError(t, err) request, err := RequestWithBody(file.Name(), "http://www.google.com", "GET") if request == nil { t.Error("Unexpected nil result") } if err != nil { t.Errorf("Unexpected error: %#v") } dataOut, err := ioutil.ReadAll(request.Body) expectNoError(t, err) if string(data) != string(dataOut) { t.Errorf("Mismatched data. Expected %s, got %s", data, dataOut) } } func validatePort(t *testing.T, p api.Port, external int, internal int) { if p.HostPort != external || p.ContainerPort != internal { t.Errorf("Unexpected port: %#v != (%d, %d)", p, external, internal) } } func TestMakePorts(t *testing.T) { ports := makePorts("8080:80,8081:8081,443:444") if len(ports) != 3 { t.Errorf("Unexpected ports: %#v", ports) } validatePort(t, ports[0], 8080, 80) validatePort(t, ports[1], 8081, 8081) validatePort(t, ports[2], 443, 444) }
pkg/cloudcfg/cloudcfg_test.go
1
https://github.com/kubernetes/kubernetes/commit/b6a260940c7661baea30599c5f5ad370de3c9633
[ 0.9867398738861084, 0.0871405228972435, 0.00016621730173937976, 0.0008565459866076708, 0.23837310075759888 ]
{ "id": 0, "code_window": [ "\t}\n", "\tif body != expectedBody {\n", "\t\tt.Errorf(\"Expected body: '%s', saw: '%s'\", expectedBody, body)\n", "\t}\n", "\tfakeHandler.ValidateRequest(t, \"/foo/bar\", \"GET\", &fakeHandler.ResponseBody)\n", "}\n", "\n", "func TestRunController(t *testing.T) {\n", "\tfakeClient := FakeKubeClient{}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tfakeHandler.ValidateRequest(t, \"/foo/bar\", \"GET\", nil)\n" ], "file_path": "pkg/cloudcfg/cloudcfg_test.go", "type": "replace", "edit_start_line_idx": 168 }
// Package drive provides access to the Drive API. // // See https://developers.google.com/drive/ // // Usage example: // // import "code.google.com/p/google-api-go-client/drive/v1" // ... // driveService, err := drive.New(oauthHttpClient) package drive import ( "bytes" "code.google.com/p/google-api-go-client/googleapi" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "strconv" "strings" ) // Always reference these packages, just in case the auto-generated code // below doesn't. var _ = bytes.NewBuffer var _ = strconv.Itoa var _ = fmt.Sprintf var _ = json.NewDecoder var _ = io.Copy var _ = url.Parse var _ = googleapi.Version var _ = errors.New var _ = strings.Replace const apiId = "drive:v1" const apiName = "drive" const apiVersion = "v1" const basePath = "https://www.googleapis.com/drive/v1/" // OAuth2 scopes used by this API. const ( // View and manage Google Drive files that you have opened or created // with this app DriveFileScope = "https://www.googleapis.com/auth/drive.file" ) func New(client *http.Client) (*Service, error) { if client == nil { return nil, errors.New("client is nil") } s := &Service{client: client, BasePath: basePath} s.Files = NewFilesService(s) return s, nil } type Service struct { client *http.Client BasePath string // API endpoint base URL Files *FilesService } func NewFilesService(s *Service) *FilesService { rs := &FilesService{s: s} return rs } type FilesService struct { s *Service } type File struct { // CreatedDate: Create time for this file (formatted ISO8601 timestamp). CreatedDate string `json:"createdDate,omitempty"` // Description: A short description of the file Description string `json:"description,omitempty"` // DownloadUrl: Short term download URL for the file. This will only be // populated on files with content stored in Drive. DownloadUrl string `json:"downloadUrl,omitempty"` // Etag: ETag of the file. Etag string `json:"etag,omitempty"` // FileExtension: The file extension used when downloading this file. // This field is read only. To set the extension, include it on title // when creating the file. This will only be populated on files with // content stored in Drive. FileExtension string `json:"fileExtension,omitempty"` // FileSize: The size of the file in bytes. This will only be populated // on files with content stored in Drive. FileSize int64 `json:"fileSize,omitempty,string"` // Id: The id of the file. Id string `json:"id,omitempty"` // IndexableText: Indexable text attributes for the file (can only be // written) IndexableText *FileIndexableText `json:"indexableText,omitempty"` // Kind: The type of file. This is always drive#file Kind string `json:"kind,omitempty"` // Labels: Labels for the file. Labels *FileLabels `json:"labels,omitempty"` // LastViewedDate: Last time this file was viewed by the user (formatted // RFC 3339 timestamp). LastViewedDate string `json:"lastViewedDate,omitempty"` // Md5Checksum: An MD5 checksum for the content of this file. This will // only be populated on files with content stored in Drive. Md5Checksum string `json:"md5Checksum,omitempty"` // MimeType: The mimetype of the file MimeType string `json:"mimeType,omitempty"` // ModifiedByMeDate: Last time this file was modified by the user // (formatted RFC 3339 timestamp). ModifiedByMeDate string `json:"modifiedByMeDate,omitempty"` // ModifiedDate: Last time this file was modified by anyone (formatted // RFC 3339 timestamp). ModifiedDate string `json:"modifiedDate,omitempty"` // ParentsCollection: Collection of parent folders which contain this // file. // On insert, setting this field will put the file in all of the // provided folders. If no folders are provided, the file will be placed // in the default root folder. On update, this field is ignored. ParentsCollection []*FileParentsCollection `json:"parentsCollection,omitempty"` // SelfLink: A link back to this file. SelfLink string `json:"selfLink,omitempty"` // Title: The title of this file. Title string `json:"title,omitempty"` // UserPermission: The permissions for the authenticated user on this // file. UserPermission *Permission `json:"userPermission,omitempty"` } type FileIndexableText struct { // Text: The text to be indexed for this file Text string `json:"text,omitempty"` } type FileLabels struct { // Hidden: Whether this file is hidden from the user Hidden bool `json:"hidden,omitempty"` // Starred: Whether this file is starred by the user. Starred bool `json:"starred,omitempty"` // Trashed: Whether this file has been trashed. Trashed bool `json:"trashed,omitempty"` } type FileParentsCollection struct { // Id: The id of this parent Id string `json:"id,omitempty"` // ParentLink: A link to get the metadata for this parent ParentLink string `json:"parentLink,omitempty"` } type Permission struct { // AdditionalRoles: Any additional roles that this permission describes. AdditionalRoles []string `json:"additionalRoles,omitempty"` // Etag: An etag for this permission. Etag string `json:"etag,omitempty"` // Kind: The kind of this permission. This is always drive#permission Kind string `json:"kind,omitempty"` // Role: The role that this permission describes. (For example: reader, // writer, owner) Role string `json:"role,omitempty"` // Type: The type of permission (For example: user, group etc). Type string `json:"type,omitempty"` } // method id "drive.files.get": type FilesGetCall struct { s *Service id string opt_ map[string]interface{} } // Get: Gets a file's metadata by id. func (r *FilesService) Get(id string) *FilesGetCall { c := &FilesGetCall{s: r.s, opt_: make(map[string]interface{})} c.id = id return c } // Projection sets the optional parameter "projection": This parameter // is deprecated and has no function. func (c *FilesGetCall) Projection(projection string) *FilesGetCall { c.opt_["projection"] = projection return c } // UpdateViewedDate sets the optional parameter "updateViewedDate": // Whether to update the view date after successfully retrieving the // file. func (c *FilesGetCall) UpdateViewedDate(updateViewedDate bool) *FilesGetCall { c.opt_["updateViewedDate"] = updateViewedDate return c } func (c *FilesGetCall) Do() (*File, error) { var body io.Reader = nil params := make(url.Values) params.Set("alt", "json") if v, ok := c.opt_["projection"]; ok { params.Set("projection", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["updateViewedDate"]; ok { params.Set("updateViewedDate", fmt.Sprintf("%v", v)) } urls := googleapi.ResolveRelative(c.s.BasePath, "files/{id}") urls += "?" + params.Encode() req, _ := http.NewRequest("GET", urls, body) req.URL.Path = strings.Replace(req.URL.Path, "{id}", url.QueryEscape(c.id), 1) googleapi.SetOpaque(req.URL) req.Header.Set("User-Agent", "google-api-go-client/0.5") res, err := c.s.client.Do(req) if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := new(File) if err := json.NewDecoder(res.Body).Decode(ret); err != nil { return nil, err } return ret, nil // { // "description": "Gets a file's metadata by id.", // "httpMethod": "GET", // "id": "drive.files.get", // "parameterOrder": [ // "id" // ], // "parameters": { // "id": { // "description": "The id for the file in question.", // "location": "path", // "required": true, // "type": "string" // }, // "projection": { // "description": "This parameter is deprecated and has no function.", // "enum": [ // "BASIC", // "FULL" // ], // "enumDescriptions": [ // "Deprecated", // "Deprecated" // ], // "location": "query", // "type": "string" // }, // "updateViewedDate": { // "default": "true", // "description": "Whether to update the view date after successfully retrieving the file.", // "location": "query", // "type": "boolean" // } // }, // "path": "files/{id}", // "response": { // "$ref": "File" // }, // "scopes": [ // "https://www.googleapis.com/auth/drive.file" // ] // } } // method id "drive.files.insert": type FilesInsertCall struct { s *Service file *File opt_ map[string]interface{} media_ io.Reader } // Insert: Inserts a file, and any settable metadata or blob content // sent with the request. func (r *FilesService) Insert(file *File) *FilesInsertCall { c := &FilesInsertCall{s: r.s, opt_: make(map[string]interface{})} c.file = file return c } func (c *FilesInsertCall) Media(r io.Reader) *FilesInsertCall { c.media_ = r return c } func (c *FilesInsertCall) Do() (*File, error) { var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.file) if err != nil { return nil, err } ctype := "application/json" params := make(url.Values) params.Set("alt", "json") urls := googleapi.ResolveRelative(c.s.BasePath, "files") if c.media_ != nil { urls = strings.Replace(urls, "https://www.googleapis.com/", "https://www.googleapis.com/upload/", 1) params.Set("uploadType", "multipart") } urls += "?" + params.Encode() contentLength_, hasMedia_ := googleapi.ConditionallyIncludeMedia(c.media_, &body, &ctype) req, _ := http.NewRequest("POST", urls, body) googleapi.SetOpaque(req.URL) if hasMedia_ { req.ContentLength = contentLength_ } req.Header.Set("Content-Type", ctype) req.Header.Set("User-Agent", "google-api-go-client/0.5") res, err := c.s.client.Do(req) if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := new(File) if err := json.NewDecoder(res.Body).Decode(ret); err != nil { return nil, err } return ret, nil // { // "description": "Inserts a file, and any settable metadata or blob content sent with the request.", // "httpMethod": "POST", // "id": "drive.files.insert", // "mediaUpload": { // "accept": [ // "*/*" // ], // "maxSize": "1024GB", // "protocols": { // "resumable": { // "multipart": true, // "path": "/resumable/upload/drive/v1/files" // }, // "simple": { // "multipart": true, // "path": "/upload/drive/v1/files" // } // } // }, // "path": "files", // "request": { // "$ref": "File" // }, // "response": { // "$ref": "File" // }, // "scopes": [ // "https://www.googleapis.com/auth/drive.file" // ], // "supportsMediaUpload": true // } } // method id "drive.files.patch": type FilesPatchCall struct { s *Service id string file *File opt_ map[string]interface{} } // Patch: Updates file metadata and/or content. This method supports // patch semantics. func (r *FilesService) Patch(id string, file *File) *FilesPatchCall { c := &FilesPatchCall{s: r.s, opt_: make(map[string]interface{})} c.id = id c.file = file return c } // NewRevision sets the optional parameter "newRevision": Whether a blob // upload should create a new revision. If false, the blob data in the // current head revision is replaced. If not set or true, a new blob is // created as head revision, and previous revisions are preserved // (causing increased use of the user's data storage quota). func (c *FilesPatchCall) NewRevision(newRevision bool) *FilesPatchCall { c.opt_["newRevision"] = newRevision return c } // UpdateModifiedDate sets the optional parameter "updateModifiedDate": // Controls updating the modified date of the file. If true, the // modified date will be updated to the current time, regardless of // whether other changes are being made. If false, the modified date // will only be updated to the current time if other changes are also // being made (changing the title, for example). func (c *FilesPatchCall) UpdateModifiedDate(updateModifiedDate bool) *FilesPatchCall { c.opt_["updateModifiedDate"] = updateModifiedDate return c } // UpdateViewedDate sets the optional parameter "updateViewedDate": // Whether to update the view date after successfully updating the file. func (c *FilesPatchCall) UpdateViewedDate(updateViewedDate bool) *FilesPatchCall { c.opt_["updateViewedDate"] = updateViewedDate return c } func (c *FilesPatchCall) Do() (*File, error) { var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.file) if err != nil { return nil, err } ctype := "application/json" params := make(url.Values) params.Set("alt", "json") if v, ok := c.opt_["newRevision"]; ok { params.Set("newRevision", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["updateModifiedDate"]; ok { params.Set("updateModifiedDate", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["updateViewedDate"]; ok { params.Set("updateViewedDate", fmt.Sprintf("%v", v)) } urls := googleapi.ResolveRelative(c.s.BasePath, "files/{id}") urls += "?" + params.Encode() req, _ := http.NewRequest("PATCH", urls, body) req.URL.Path = strings.Replace(req.URL.Path, "{id}", url.QueryEscape(c.id), 1) googleapi.SetOpaque(req.URL) req.Header.Set("Content-Type", ctype) req.Header.Set("User-Agent", "google-api-go-client/0.5") res, err := c.s.client.Do(req) if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := new(File) if err := json.NewDecoder(res.Body).Decode(ret); err != nil { return nil, err } return ret, nil // { // "description": "Updates file metadata and/or content. This method supports patch semantics.", // "httpMethod": "PATCH", // "id": "drive.files.patch", // "parameterOrder": [ // "id" // ], // "parameters": { // "id": { // "description": "The id for the file in question.", // "location": "path", // "required": true, // "type": "string" // }, // "newRevision": { // "default": "true", // "description": "Whether a blob upload should create a new revision. If false, the blob data in the current head revision is replaced. If not set or true, a new blob is created as head revision, and previous revisions are preserved (causing increased use of the user's data storage quota).", // "location": "query", // "type": "boolean" // }, // "updateModifiedDate": { // "default": "false", // "description": "Controls updating the modified date of the file. If true, the modified date will be updated to the current time, regardless of whether other changes are being made. If false, the modified date will only be updated to the current time if other changes are also being made (changing the title, for example).", // "location": "query", // "type": "boolean" // }, // "updateViewedDate": { // "default": "true", // "description": "Whether to update the view date after successfully updating the file.", // "location": "query", // "type": "boolean" // } // }, // "path": "files/{id}", // "request": { // "$ref": "File" // }, // "response": { // "$ref": "File" // }, // "scopes": [ // "https://www.googleapis.com/auth/drive.file" // ] // } } // method id "drive.files.update": type FilesUpdateCall struct { s *Service id string file *File opt_ map[string]interface{} media_ io.Reader } // Update: Updates file metadata and/or content func (r *FilesService) Update(id string, file *File) *FilesUpdateCall { c := &FilesUpdateCall{s: r.s, opt_: make(map[string]interface{})} c.id = id c.file = file return c } // NewRevision sets the optional parameter "newRevision": Whether a blob // upload should create a new revision. If false, the blob data in the // current head revision is replaced. If not set or true, a new blob is // created as head revision, and previous revisions are preserved // (causing increased use of the user's data storage quota). func (c *FilesUpdateCall) NewRevision(newRevision bool) *FilesUpdateCall { c.opt_["newRevision"] = newRevision return c } // UpdateModifiedDate sets the optional parameter "updateModifiedDate": // Controls updating the modified date of the file. If true, the // modified date will be updated to the current time, regardless of // whether other changes are being made. If false, the modified date // will only be updated to the current time if other changes are also // being made (changing the title, for example). func (c *FilesUpdateCall) UpdateModifiedDate(updateModifiedDate bool) *FilesUpdateCall { c.opt_["updateModifiedDate"] = updateModifiedDate return c } // UpdateViewedDate sets the optional parameter "updateViewedDate": // Whether to update the view date after successfully updating the file. func (c *FilesUpdateCall) UpdateViewedDate(updateViewedDate bool) *FilesUpdateCall { c.opt_["updateViewedDate"] = updateViewedDate return c } func (c *FilesUpdateCall) Media(r io.Reader) *FilesUpdateCall { c.media_ = r return c } func (c *FilesUpdateCall) Do() (*File, error) { var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.file) if err != nil { return nil, err } ctype := "application/json" params := make(url.Values) params.Set("alt", "json") if v, ok := c.opt_["newRevision"]; ok { params.Set("newRevision", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["updateModifiedDate"]; ok { params.Set("updateModifiedDate", fmt.Sprintf("%v", v)) } if v, ok := c.opt_["updateViewedDate"]; ok { params.Set("updateViewedDate", fmt.Sprintf("%v", v)) } urls := googleapi.ResolveRelative(c.s.BasePath, "files/{id}") if c.media_ != nil { urls = strings.Replace(urls, "https://www.googleapis.com/", "https://www.googleapis.com/upload/", 1) params.Set("uploadType", "multipart") } urls += "?" + params.Encode() contentLength_, hasMedia_ := googleapi.ConditionallyIncludeMedia(c.media_, &body, &ctype) req, _ := http.NewRequest("PUT", urls, body) req.URL.Path = strings.Replace(req.URL.Path, "{id}", url.QueryEscape(c.id), 1) googleapi.SetOpaque(req.URL) if hasMedia_ { req.ContentLength = contentLength_ } req.Header.Set("Content-Type", ctype) req.Header.Set("User-Agent", "google-api-go-client/0.5") res, err := c.s.client.Do(req) if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := new(File) if err := json.NewDecoder(res.Body).Decode(ret); err != nil { return nil, err } return ret, nil // { // "description": "Updates file metadata and/or content", // "httpMethod": "PUT", // "id": "drive.files.update", // "mediaUpload": { // "accept": [ // "*/*" // ], // "maxSize": "1024GB", // "protocols": { // "resumable": { // "multipart": true, // "path": "/resumable/upload/drive/v1/files/{id}" // }, // "simple": { // "multipart": true, // "path": "/upload/drive/v1/files/{id}" // } // } // }, // "parameterOrder": [ // "id" // ], // "parameters": { // "id": { // "description": "The id for the file in question.", // "location": "path", // "required": true, // "type": "string" // }, // "newRevision": { // "default": "true", // "description": "Whether a blob upload should create a new revision. If false, the blob data in the current head revision is replaced. If not set or true, a new blob is created as head revision, and previous revisions are preserved (causing increased use of the user's data storage quota).", // "location": "query", // "type": "boolean" // }, // "updateModifiedDate": { // "default": "false", // "description": "Controls updating the modified date of the file. If true, the modified date will be updated to the current time, regardless of whether other changes are being made. If false, the modified date will only be updated to the current time if other changes are also being made (changing the title, for example).", // "location": "query", // "type": "boolean" // }, // "updateViewedDate": { // "default": "true", // "description": "Whether to update the view date after successfully updating the file.", // "location": "query", // "type": "boolean" // } // }, // "path": "files/{id}", // "request": { // "$ref": "File" // }, // "response": { // "$ref": "File" // }, // "scopes": [ // "https://www.googleapis.com/auth/drive.file" // ], // "supportsMediaUpload": true // } }
third_party/src/code.google.com/p/google-api-go-client/drive/v1/drive-gen.go
0
https://github.com/kubernetes/kubernetes/commit/b6a260940c7661baea30599c5f5ad370de3c9633
[ 0.0013985843397676945, 0.00024266693799290806, 0.00016075445455498993, 0.00017430052685085684, 0.00027168000815436244 ]
{ "id": 0, "code_window": [ "\t}\n", "\tif body != expectedBody {\n", "\t\tt.Errorf(\"Expected body: '%s', saw: '%s'\", expectedBody, body)\n", "\t}\n", "\tfakeHandler.ValidateRequest(t, \"/foo/bar\", \"GET\", &fakeHandler.ResponseBody)\n", "}\n", "\n", "func TestRunController(t *testing.T) {\n", "\tfakeClient := FakeKubeClient{}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tfakeHandler.ValidateRequest(t, \"/foo/bar\", \"GET\", nil)\n" ], "file_path": "pkg/cloudcfg/cloudcfg_test.go", "type": "replace", "edit_start_line_idx": 168 }
// Copyright 2014 Docker authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the DOCKER-LICENSE file. package engine import ( "os" "testing" ) func TestJobStatusOK(t *testing.T) { eng := newTestEngine(t) defer os.RemoveAll(eng.Root()) eng.Register("return_ok", func(job *Job) Status { return StatusOK }) err := eng.Job("return_ok").Run() if err != nil { t.Fatalf("Expected: err=%v\nReceived: err=%v", nil, err) } } func TestJobStatusErr(t *testing.T) { eng := newTestEngine(t) defer os.RemoveAll(eng.Root()) eng.Register("return_err", func(job *Job) Status { return StatusErr }) err := eng.Job("return_err").Run() if err == nil { t.Fatalf("When a job returns StatusErr, Run() should return an error") } } func TestJobStatusNotFound(t *testing.T) { eng := newTestEngine(t) defer os.RemoveAll(eng.Root()) eng.Register("return_not_found", func(job *Job) Status { return StatusNotFound }) err := eng.Job("return_not_found").Run() if err == nil { t.Fatalf("When a job returns StatusNotFound, Run() should return an error") } } func TestJobStdoutString(t *testing.T) { eng := newTestEngine(t) defer os.RemoveAll(eng.Root()) // FIXME: test multiple combinations of output and status eng.Register("say_something_in_stdout", func(job *Job) Status { job.Printf("Hello world\n") return StatusOK }) job := eng.Job("say_something_in_stdout") var output string if err := job.Stdout.AddString(&output); err != nil { t.Fatal(err) } if err := job.Run(); err != nil { t.Fatal(err) } if expectedOutput := "Hello world"; output != expectedOutput { t.Fatalf("Stdout last line:\nExpected: %v\nReceived: %v", expectedOutput, output) } } func TestJobStderrString(t *testing.T) { eng := newTestEngine(t) defer os.RemoveAll(eng.Root()) // FIXME: test multiple combinations of output and status eng.Register("say_something_in_stderr", func(job *Job) Status { job.Errorf("Warning, something might happen\nHere it comes!\nOh no...\nSomething happened\n") return StatusOK }) job := eng.Job("say_something_in_stderr") var output string if err := job.Stderr.AddString(&output); err != nil { t.Fatal(err) } if err := job.Run(); err != nil { t.Fatal(err) } if expectedOutput := "Something happened"; output != expectedOutput { t.Fatalf("Stderr last line:\nExpected: %v\nReceived: %v", expectedOutput, output) } }
third_party/src/github.com/fsouza/go-dockerclient/engine/job_test.go
0
https://github.com/kubernetes/kubernetes/commit/b6a260940c7661baea30599c5f5ad370de3c9633
[ 0.00030074993264861405, 0.00020560807024594396, 0.00016644377319607884, 0.0002060775295831263, 0.00004115623596590012 ]
{ "id": 0, "code_window": [ "\t}\n", "\tif body != expectedBody {\n", "\t\tt.Errorf(\"Expected body: '%s', saw: '%s'\", expectedBody, body)\n", "\t}\n", "\tfakeHandler.ValidateRequest(t, \"/foo/bar\", \"GET\", &fakeHandler.ResponseBody)\n", "}\n", "\n", "func TestRunController(t *testing.T) {\n", "\tfakeClient := FakeKubeClient{}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tfakeHandler.ValidateRequest(t, \"/foo/bar\", \"GET\", nil)\n" ], "file_path": "pkg/cloudcfg/cloudcfg_test.go", "type": "replace", "edit_start_line_idx": 168 }
package yaml import ( "math" "strconv" "strings" ) // TODO: merge, timestamps, base 60 floats, omap. type resolveMapItem struct { value interface{} tag string } var resolveTable = make([]byte, 256) var resolveMap = make(map[string]resolveMapItem) func init() { t := resolveTable t[int('+')] = 'S' // Sign t[int('-')] = 'S' for _, c := range "0123456789" { t[int(c)] = 'D' // Digit } for _, c := range "yYnNtTfFoO~" { t[int(c)] = 'M' // In map } t[int('.')] = '.' // Float (potentially in map) t[int('<')] = '<' // Merge var resolveMapList = []struct { v interface{} tag string l []string }{ {true, "!!bool", []string{"y", "Y", "yes", "Yes", "YES"}}, {true, "!!bool", []string{"true", "True", "TRUE"}}, {true, "!!bool", []string{"on", "On", "ON"}}, {false, "!!bool", []string{"n", "N", "no", "No", "NO"}}, {false, "!!bool", []string{"false", "False", "FALSE"}}, {false, "!!bool", []string{"off", "Off", "OFF"}}, {nil, "!!null", []string{"~", "null", "Null", "NULL"}}, {math.NaN(), "!!float", []string{".nan", ".NaN", ".NAN"}}, {math.Inf(+1), "!!float", []string{".inf", ".Inf", ".INF"}}, {math.Inf(+1), "!!float", []string{"+.inf", "+.Inf", "+.INF"}}, {math.Inf(-1), "!!float", []string{"-.inf", "-.Inf", "-.INF"}}, {"<<", "!!merge", []string{"<<"}}, } m := resolveMap for _, item := range resolveMapList { for _, s := range item.l { m[s] = resolveMapItem{item.v, item.tag} } } } const longTagPrefix = "tag:yaml.org,2002:" func shortTag(tag string) string { if strings.HasPrefix(tag, longTagPrefix) { return "!!" + tag[len(longTagPrefix):] } return tag } func resolvableTag(tag string) bool { switch tag { case "", "!!str", "!!bool", "!!int", "!!float", "!!null": return true } return false } func resolve(tag string, in string) (rtag string, out interface{}) { tag = shortTag(tag) if !resolvableTag(tag) { return tag, in } defer func() { if tag != "" && tag != rtag { panic("Can't decode " + rtag + " '" + in + "' as a " + tag) } }() if in == "" { return "!!null", nil } c := resolveTable[in[0]] if c == 0 { // It's a string for sure. Nothing to do. return "!!str", in } // Handle things we can lookup in a map. if item, ok := resolveMap[in]; ok { return item.tag, item.value } switch c { case 'M': // We've already checked the map above. case '.': // Not in the map, so maybe a normal float. floatv, err := strconv.ParseFloat(in, 64) if err == nil { return "!!float", floatv } // XXX Handle base 60 floats here (WTF!) case 'D', 'S': // Int, float, or timestamp. plain := strings.Replace(in, "_", "", -1) intv, err := strconv.ParseInt(plain, 0, 64) if err == nil { if intv == int64(int(intv)) { return "!!int", int(intv) } else { return "!!int", intv } } floatv, err := strconv.ParseFloat(plain, 64) if err == nil { return "!!float", floatv } if strings.HasPrefix(plain, "0b") { intv, err := strconv.ParseInt(plain[2:], 2, 64) if err == nil { return "!!int", int(intv) } } else if strings.HasPrefix(plain, "-0b") { intv, err := strconv.ParseInt(plain[3:], 2, 64) if err == nil { return "!!int", -int(intv) } } // XXX Handle timestamps here. default: panic("resolveTable item not yet handled: " + string([]byte{c}) + " (with " + in + ")") } return "!!str", in }
third_party/src/gonuts.org/v1/yaml/resolve.go
0
https://github.com/kubernetes/kubernetes/commit/b6a260940c7661baea30599c5f5ad370de3c9633
[ 0.0007012292044237256, 0.00020840684010181576, 0.00016871595289558172, 0.00017368649423588067, 0.00013173872139304876 ]
{ "id": 1, "code_window": [ "}\n", "\n", "// FakeHandler is to assist in testing HTTP requests.\n", "type FakeHandler struct {\n", "\tRequestReceived *http.Request\n", "\tStatusCode int\n", "\tResponseBody string\n", "\t// For logging - you can use a *testing.T\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tRequestBody string\n" ], "file_path": "pkg/util/fake_handler.go", "type": "add", "edit_start_line_idx": 34 }
/* 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 util import ( "io/ioutil" "net/http" ) // TestInterface is a simple interface providing Errorf, to make injection for // testing easier (insert 'yo dawg' meme here) type TestInterface interface { Errorf(format string, args ...interface{}) } type LogInterface interface { Logf(format string, args ...interface{}) } // FakeHandler is to assist in testing HTTP requests. type FakeHandler struct { RequestReceived *http.Request StatusCode int ResponseBody string // For logging - you can use a *testing.T // This will keep log messages associated with the test. T LogInterface } func (f *FakeHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) { f.RequestReceived = request response.WriteHeader(f.StatusCode) response.Write([]byte(f.ResponseBody)) bodyReceived, err := ioutil.ReadAll(request.Body) if err != nil && f.T != nil { f.T.Logf("Received read error: %#v", err) } f.ResponseBody = string(bodyReceived) } func (f FakeHandler) ValidateRequest(t TestInterface, expectedPath, expectedMethod string, body *string) { if f.RequestReceived.URL.Path != expectedPath { t.Errorf("Unexpected request path: %s", f.RequestReceived.URL.Path) } if f.RequestReceived.Method != expectedMethod { t.Errorf("Unexpected method: %s", f.RequestReceived.Method) } if body != nil { if *body != f.ResponseBody { t.Errorf("Received body:\n%s\n Doesn't match expected body:\n%s", f.ResponseBody, *body) } } }
pkg/util/fake_handler.go
1
https://github.com/kubernetes/kubernetes/commit/b6a260940c7661baea30599c5f5ad370de3c9633
[ 0.9969383478164673, 0.42801469564437866, 0.00017122473218478262, 0.007774427533149719, 0.490446001291275 ]
{ "id": 1, "code_window": [ "}\n", "\n", "// FakeHandler is to assist in testing HTTP requests.\n", "type FakeHandler struct {\n", "\tRequestReceived *http.Request\n", "\tStatusCode int\n", "\tResponseBody string\n", "\t// For logging - you can use a *testing.T\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tRequestBody string\n" ], "file_path": "pkg/util/fake_handler.go", "type": "add", "edit_start_line_idx": 34 }
{ "items": [ { "id": "testRun", "desiredState": { "replicas": 2, "replicasInSet": { "name": "testRun" }, "podTemplate": { "desiredState": { "image": "dockerfile/nginx", "networkPorts": [ { "hostPort": 8080, "containerPort": 80 } ] }, "labels": { "name": "testRun" } } }, "labels": { "name": "testRun" } } ] }
api/examples/controller-list.json
0
https://github.com/kubernetes/kubernetes/commit/b6a260940c7661baea30599c5f5ad370de3c9633
[ 0.0005825826083309948, 0.00029022464877925813, 0.0001781844621291384, 0.0002000657987082377, 0.00016940275963861495 ]
{ "id": 1, "code_window": [ "}\n", "\n", "// FakeHandler is to assist in testing HTTP requests.\n", "type FakeHandler struct {\n", "\tRequestReceived *http.Request\n", "\tStatusCode int\n", "\tResponseBody string\n", "\t// For logging - you can use a *testing.T\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tRequestBody string\n" ], "file_path": "pkg/util/fake_handler.go", "type": "add", "edit_start_line_idx": 34 }
{ "kind": "discovery#restDescription", "etag": "\"kEk3sFj6Ef5_yR1-H3bAO6qw9mI/UNFMI_ENJ3hAFRWSi4GLSerTeFg\"", "discoveryVersion": "v1", "id": "discovery:v1", "name": "discovery", "version": "v1", "title": "APIs Discovery Service", "description": "Lets you discover information about other Google APIs, such as what APIs are available, the resource and method details for each API.", "ownerDomain": "google.com", "ownerName": "Google", "icons": { "x16": "http://www.google.com/images/icons/feature/filing_cabinet_search-g16.png", "x32": "http://www.google.com/images/icons/feature/filing_cabinet_search-g32.png" }, "documentationLink": "https://developers.google.com/discovery/", "protocol": "rest", "baseUrl": "https://www.googleapis.com/discovery/v1/", "basePath": "/discovery/v1/", "rootUrl": "https://www.googleapis.com/", "servicePath": "discovery/v1/", "batchPath": "batch", "parameters": { "alt": { "type": "string", "description": "Data format for the response.", "default": "json", "enum": [ "json" ], "enumDescriptions": [ "Responses with Content-Type of application/json" ], "location": "query" }, "fields": { "type": "string", "description": "Selector specifying which fields to include in a partial response.", "location": "query" }, "key": { "type": "string", "description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.", "location": "query" }, "oauth_token": { "type": "string", "description": "OAuth 2.0 token for the current user.", "location": "query" }, "prettyPrint": { "type": "boolean", "description": "Returns response with indentations and line breaks.", "default": "true", "location": "query" }, "quotaUser": { "type": "string", "description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.", "location": "query" }, "userIp": { "type": "string", "description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.", "location": "query" } }, "schemas": { "DirectoryList": { "id": "DirectoryList", "type": "object", "properties": { "discoveryVersion": { "type": "string", "description": "Indicate the version of the Discovery API used to generate this doc.", "default": "v1" }, "items": { "type": "array", "description": "The individual directory entries. One entry per api/version pair.", "items": { "type": "object", "properties": { "description": { "type": "string", "description": "The description of this API." }, "discoveryLink": { "type": "string", "description": "A link to the discovery document." }, "discoveryRestUrl": { "type": "string", "description": "The URL for the discovery REST document." }, "documentationLink": { "type": "string", "description": "A link to human readable documentation for the API." }, "icons": { "type": "object", "description": "Links to 16x16 and 32x32 icons representing the API.", "properties": { "x16": { "type": "string", "description": "The URL of the 16x16 icon." }, "x32": { "type": "string", "description": "The URL of the 32x32 icon." } } }, "id": { "type": "string", "description": "The id of this API." }, "kind": { "type": "string", "description": "The kind for this response.", "default": "discovery#directoryItem" }, "labels": { "type": "array", "description": "Labels for the status of this API, such as labs or deprecated.", "items": { "type": "string" } }, "name": { "type": "string", "description": "The name of the API." }, "preferred": { "type": "boolean", "description": "True if this version is the preferred version to use." }, "title": { "type": "string", "description": "The title of this API." }, "version": { "type": "string", "description": "The version of the API." } } } }, "kind": { "type": "string", "description": "The kind for this response.", "default": "discovery#directoryList" } } }, "JsonSchema": { "id": "JsonSchema", "type": "object", "properties": { "$ref": { "type": "string", "description": "A reference to another schema. The value of this property is the \"id\" of another schema." }, "additionalProperties": { "$ref": "JsonSchema", "description": "If this is a schema for an object, this property is the schema for any additional properties with dynamic keys on this object." }, "annotations": { "type": "object", "description": "Additional information about this property.", "properties": { "required": { "type": "array", "description": "A list of methods for which this property is required on requests.", "items": { "type": "string" } } } }, "default": { "type": "string", "description": "The default value of this property (if one exists)." }, "description": { "type": "string", "description": "A description of this object." }, "enum": { "type": "array", "description": "Values this parameter may take (if it is an enum).", "items": { "type": "string" } }, "enumDescriptions": { "type": "array", "description": "The descriptions for the enums. Each position maps to the corresponding value in the \"enum\" array.", "items": { "type": "string" } }, "format": { "type": "string", "description": "An additional regular expression or key that helps constrain the value. For more details see: http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.23" }, "id": { "type": "string", "description": "Unique identifier for this schema." }, "items": { "$ref": "JsonSchema", "description": "If this is a schema for an array, this property is the schema for each element in the array." }, "location": { "type": "string", "description": "Whether this parameter goes in the query or the path for REST requests." }, "maximum": { "type": "string", "description": "The maximum value of this parameter." }, "minimum": { "type": "string", "description": "The minimum value of this parameter." }, "pattern": { "type": "string", "description": "The regular expression this parameter must conform to. Uses Java 6 regex format: http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html" }, "properties": { "type": "object", "description": "If this is a schema for an object, list the schema for each property of this object.", "additionalProperties": { "$ref": "JsonSchema", "description": "A single property of this object. The value is itself a JSON Schema object describing this property." } }, "readOnly": { "type": "boolean", "description": "The value is read-only, generated by the service. The value cannot be modified by the client. If the value is included in a POST, PUT, or PATCH request, it is ignored by the service." }, "repeated": { "type": "boolean", "description": "Whether this parameter may appear multiple times." }, "required": { "type": "boolean", "description": "Whether the parameter is required." }, "type": { "type": "string", "description": "The value type for this schema. A list of values can be found here: http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1" }, "variant": { "type": "object", "description": "In a variant data type, the value of one property is used to determine how to interpret the entire entity. Its value must exist in a map of descriminant values to schema names.", "properties": { "discriminant": { "type": "string", "description": "The name of the type discriminant property." }, "map": { "type": "array", "description": "The map of discriminant value to schema to use for parsing..", "items": { "type": "object", "properties": { "$ref": { "type": "string" }, "type_value": { "type": "string" } } } } } } } }, "RestDescription": { "id": "RestDescription", "type": "object", "properties": { "auth": { "type": "object", "description": "Authentication information.", "properties": { "oauth2": { "type": "object", "description": "OAuth 2.0 authentication information.", "properties": { "scopes": { "type": "object", "description": "Available OAuth 2.0 scopes.", "additionalProperties": { "type": "object", "description": "The scope value.", "properties": { "description": { "type": "string", "description": "Description of scope." } } } } } } } }, "basePath": { "type": "string", "description": "[DEPRECATED] The base path for REST requests." }, "baseUrl": { "type": "string", "description": "[DEPRECATED] The base URL for REST requests." }, "batchPath": { "type": "string", "description": "The path for REST batch requests.", "default": "batch" }, "canonicalName": { "type": "string", "description": "Indicates how the API name should be capitalized and split into various parts. Useful for generating pretty class names." }, "description": { "type": "string", "description": "The description of this API." }, "discoveryVersion": { "type": "string", "description": "Indicate the version of the Discovery API used to generate this doc.", "default": "v1" }, "documentationLink": { "type": "string", "description": "A link to human readable documentation for the API." }, "etag": { "type": "string", "description": "The ETag for this response.", "readOnly": true }, "features": { "type": "array", "description": "A list of supported features for this API.", "items": { "type": "string" } }, "icons": { "type": "object", "description": "Links to 16x16 and 32x32 icons representing the API.", "properties": { "x16": { "type": "string", "description": "The URL of the 16x16 icon." }, "x32": { "type": "string", "description": "The URL of the 32x32 icon." } } }, "id": { "type": "string", "description": "The ID of this API." }, "kind": { "type": "string", "description": "The kind for this response.", "default": "discovery#restDescription" }, "labels": { "type": "array", "description": "Labels for the status of this API, such as labs or deprecated.", "items": { "type": "string" } }, "methods": { "type": "object", "description": "API-level methods for this API.", "additionalProperties": { "$ref": "RestMethod", "description": "An individual method description." } }, "name": { "type": "string", "description": "The name of this API." }, "ownerDomain": { "type": "string", "description": "The domain of the owner of this API. Together with the ownerName and a packagePath values, this can be used to generate a library for this API which would have a unique fully qualified name." }, "ownerName": { "type": "string", "description": "The name of the owner of this API. See ownerDomain." }, "packagePath": { "type": "string", "description": "The package of the owner of this API. See ownerDomain." }, "parameters": { "type": "object", "description": "Common parameters that apply across all apis.", "additionalProperties": { "$ref": "JsonSchema", "description": "Description of a single parameter." } }, "protocol": { "type": "string", "description": "The protocol described by this document.", "default": "rest" }, "resources": { "type": "object", "description": "The resources in this API.", "additionalProperties": { "$ref": "RestResource", "description": "An individual resource description. Contains methods and sub-resources related to this resource." } }, "revision": { "type": "string", "description": "The version of this API." }, "rootUrl": { "type": "string", "description": "The root URL under which all API services live." }, "schemas": { "type": "object", "description": "The schemas for this API.", "additionalProperties": { "$ref": "JsonSchema", "description": "An individual schema description." } }, "servicePath": { "type": "string", "description": "The base path for all REST requests." }, "title": { "type": "string", "description": "The title of this API." }, "version": { "type": "string", "description": "The version of this API." } } }, "RestMethod": { "id": "RestMethod", "type": "object", "properties": { "description": { "type": "string", "description": "Description of this method." }, "etagRequired": { "type": "boolean", "description": "Whether this method requires an ETag to be specified. The ETag is sent as an HTTP If-Match or If-None-Match header." }, "httpMethod": { "type": "string", "description": "HTTP method used by this method." }, "id": { "type": "string", "description": "A unique ID for this method. This property can be used to match methods between different versions of Discovery." }, "mediaUpload": { "type": "object", "description": "Media upload parameters.", "properties": { "accept": { "type": "array", "description": "MIME Media Ranges for acceptable media uploads to this method.", "items": { "type": "string" } }, "maxSize": { "type": "string", "description": "Maximum size of a media upload, such as \"1MB\", \"2GB\" or \"3TB\"." }, "protocols": { "type": "object", "description": "Supported upload protocols.", "properties": { "resumable": { "type": "object", "description": "Supports the Resumable Media Upload protocol.", "properties": { "multipart": { "type": "boolean", "description": "True if this endpoint supports uploading multipart media.", "default": "true" }, "path": { "type": "string", "description": "The URI path to be used for upload. Should be used in conjunction with the basePath property at the api-level." } } }, "simple": { "type": "object", "description": "Supports uploading as a single HTTP request.", "properties": { "multipart": { "type": "boolean", "description": "True if this endpoint supports upload multipart media.", "default": "true" }, "path": { "type": "string", "description": "The URI path to be used for upload. Should be used in conjunction with the basePath property at the api-level." } } } } } } }, "parameterOrder": { "type": "array", "description": "Ordered list of required parameters, serves as a hint to clients on how to structure their method signatures. The array is ordered such that the \"most-significant\" parameter appears first.", "items": { "type": "string" } }, "parameters": { "type": "object", "description": "Details for all parameters in this method.", "additionalProperties": { "$ref": "JsonSchema", "description": "Details for a single parameter in this method." } }, "path": { "type": "string", "description": "The URI path of this REST method. Should be used in conjunction with the basePath property at the api-level." }, "request": { "type": "object", "description": "The schema for the request.", "properties": { "$ref": { "type": "string", "description": "Schema ID for the request schema." }, "parameterName": { "type": "string", "description": "parameter name." } } }, "response": { "type": "object", "description": "The schema for the response.", "properties": { "$ref": { "type": "string", "description": "Schema ID for the response schema." } } }, "scopes": { "type": "array", "description": "OAuth 2.0 scopes applicable to this method.", "items": { "type": "string" } }, "supportsMediaDownload": { "type": "boolean", "description": "Whether this method supports media downloads." }, "supportsMediaUpload": { "type": "boolean", "description": "Whether this method supports media uploads." }, "supportsSubscription": { "type": "boolean", "description": "Whether this method supports subscriptions." } } }, "RestResource": { "id": "RestResource", "type": "object", "properties": { "methods": { "type": "object", "description": "Methods on this resource.", "additionalProperties": { "$ref": "RestMethod", "description": "Description for any methods on this resource." } }, "resources": { "type": "object", "description": "Sub-resources on this resource.", "additionalProperties": { "$ref": "RestResource", "description": "Description for any sub-resources on this resource." } } } } }, "resources": { "apis": { "methods": { "getRest": { "id": "discovery.apis.getRest", "path": "apis/{api}/{version}/rest", "httpMethod": "GET", "description": "Retrieve the description of a particular version of an api.", "parameters": { "api": { "type": "string", "description": "The name of the API.", "required": true, "location": "path" }, "version": { "type": "string", "description": "The version of the API.", "required": true, "location": "path" } }, "parameterOrder": [ "api", "version" ], "response": { "$ref": "RestDescription" } }, "list": { "id": "discovery.apis.list", "path": "apis", "httpMethod": "GET", "description": "Retrieve the list of APIs supported at this endpoint.", "parameters": { "name": { "type": "string", "description": "Only include APIs with the given name.", "location": "query" }, "preferred": { "type": "boolean", "description": "Return only the preferred version of an API.", "default": "false", "location": "query" } }, "response": { "$ref": "DirectoryList" } } } } } }
third_party/src/code.google.com/p/google-api-go-client/discovery/v1/discovery-api.json
0
https://github.com/kubernetes/kubernetes/commit/b6a260940c7661baea30599c5f5ad370de3c9633
[ 0.0010089267743751407, 0.0002774458553176373, 0.0001675828971201554, 0.00020960596157237887, 0.00016742391744628549 ]
{ "id": 1, "code_window": [ "}\n", "\n", "// FakeHandler is to assist in testing HTTP requests.\n", "type FakeHandler struct {\n", "\tRequestReceived *http.Request\n", "\tStatusCode int\n", "\tResponseBody string\n", "\t// For logging - you can use a *testing.T\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tRequestBody string\n" ], "file_path": "pkg/util/fake_handler.go", "type": "add", "edit_start_line_idx": 34 }
{ "id": "php", "desiredState": { "manifest": { "containers": [{ "image": "dockerfile/nginx", "ports": [{ "containerPort": 80, "hostPort": 8080 }] }] } }, "labels": { "name": "foo" } }
api/examples/pod.json
0
https://github.com/kubernetes/kubernetes/commit/b6a260940c7661baea30599c5f5ad370de3c9633
[ 0.00017390758148394525, 0.0001720332948025316, 0.00017015900812111795, 0.0001720332948025316, 0.0000018742866814136505 ]
{ "id": 2, "code_window": [ "\n", "\tbodyReceived, err := ioutil.ReadAll(request.Body)\n", "\tif err != nil && f.T != nil {\n", "\t\tf.T.Logf(\"Received read error: %#v\", err)\n", "\t}\n", "\tf.ResponseBody = string(bodyReceived)\n", "}\n", "\n", "func (f FakeHandler) ValidateRequest(t TestInterface, expectedPath, expectedMethod string, body *string) {\n", "\tif f.RequestReceived.URL.Path != expectedPath {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tf.RequestBody = string(bodyReceived)\n" ], "file_path": "pkg/util/fake_handler.go", "type": "replace", "edit_start_line_idx": 50 }
/* 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 util import ( "io/ioutil" "net/http" ) // TestInterface is a simple interface providing Errorf, to make injection for // testing easier (insert 'yo dawg' meme here) type TestInterface interface { Errorf(format string, args ...interface{}) } type LogInterface interface { Logf(format string, args ...interface{}) } // FakeHandler is to assist in testing HTTP requests. type FakeHandler struct { RequestReceived *http.Request StatusCode int ResponseBody string // For logging - you can use a *testing.T // This will keep log messages associated with the test. T LogInterface } func (f *FakeHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) { f.RequestReceived = request response.WriteHeader(f.StatusCode) response.Write([]byte(f.ResponseBody)) bodyReceived, err := ioutil.ReadAll(request.Body) if err != nil && f.T != nil { f.T.Logf("Received read error: %#v", err) } f.ResponseBody = string(bodyReceived) } func (f FakeHandler) ValidateRequest(t TestInterface, expectedPath, expectedMethod string, body *string) { if f.RequestReceived.URL.Path != expectedPath { t.Errorf("Unexpected request path: %s", f.RequestReceived.URL.Path) } if f.RequestReceived.Method != expectedMethod { t.Errorf("Unexpected method: %s", f.RequestReceived.Method) } if body != nil { if *body != f.ResponseBody { t.Errorf("Received body:\n%s\n Doesn't match expected body:\n%s", f.ResponseBody, *body) } } }
pkg/util/fake_handler.go
1
https://github.com/kubernetes/kubernetes/commit/b6a260940c7661baea30599c5f5ad370de3c9633
[ 0.9973766803741455, 0.38436153531074524, 0.00017870886949822307, 0.003889276646077633, 0.4521389305591583 ]
{ "id": 2, "code_window": [ "\n", "\tbodyReceived, err := ioutil.ReadAll(request.Body)\n", "\tif err != nil && f.T != nil {\n", "\t\tf.T.Logf(\"Received read error: %#v\", err)\n", "\t}\n", "\tf.ResponseBody = string(bodyReceived)\n", "}\n", "\n", "func (f FakeHandler) ValidateRequest(t TestInterface, expectedPath, expectedMethod string, body *string) {\n", "\tif f.RequestReceived.URL.Path != expectedPath {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tf.RequestBody = string(bodyReceived)\n" ], "file_path": "pkg/util/fake_handler.go", "type": "replace", "edit_start_line_idx": 50 }
/* 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 client import ( "encoding/json" "net/http" "net/http/httptest" "net/url" "strconv" "strings" "testing" "github.com/GoogleCloudPlatform/kubernetes/pkg/util" ) func TestHTTPContainerInfo(t *testing.T) { body := `{"items":[]}` fakeHandler := util.FakeHandler{ StatusCode: 200, ResponseBody: body, } testServer := httptest.NewServer(&fakeHandler) hostUrl, err := url.Parse(testServer.URL) expectNoError(t, err) parts := strings.Split(hostUrl.Host, ":") port, err := strconv.Atoi(parts[1]) expectNoError(t, err) containerInfo := &HTTPContainerInfo{ Client: http.DefaultClient, Port: uint(port), } data, err := containerInfo.GetContainerInfo(parts[0], "foo") expectNoError(t, err) dataString, _ := json.Marshal(data) if string(dataString) != body { t.Errorf("Unexpected response. Expected: %s, received %s", body, string(dataString)) } }
pkg/client/container_info_test.go
0
https://github.com/kubernetes/kubernetes/commit/b6a260940c7661baea30599c5f5ad370de3c9633
[ 0.013504328206181526, 0.002833303064107895, 0.00017040206876117736, 0.00017951559857465327, 0.004866850562393665 ]
{ "id": 2, "code_window": [ "\n", "\tbodyReceived, err := ioutil.ReadAll(request.Body)\n", "\tif err != nil && f.T != nil {\n", "\t\tf.T.Logf(\"Received read error: %#v\", err)\n", "\t}\n", "\tf.ResponseBody = string(bodyReceived)\n", "}\n", "\n", "func (f FakeHandler) ValidateRequest(t TestInterface, expectedPath, expectedMethod string, body *string) {\n", "\tif f.RequestReceived.URL.Path != expectedPath {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tf.RequestBody = string(bodyReceived)\n" ], "file_path": "pkg/util/fake_handler.go", "type": "replace", "edit_start_line_idx": 50 }
// Copyright 2014 Docker authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the DOCKER-LICENSE file. package utils import ( "errors" ) type Utsname struct { Release [65]byte } func uname() (*Utsname, error) { return nil, errors.New("Kernel version detection is not available on windows") }
third_party/src/github.com/fsouza/go-dockerclient/utils/utils_windows.go
0
https://github.com/kubernetes/kubernetes/commit/b6a260940c7661baea30599c5f5ad370de3c9633
[ 0.00017784938972909003, 0.00017485421267338097, 0.00017185905016958714, 0.00017485421267338097, 0.00000299516977975145 ]
{ "id": 2, "code_window": [ "\n", "\tbodyReceived, err := ioutil.ReadAll(request.Body)\n", "\tif err != nil && f.T != nil {\n", "\t\tf.T.Logf(\"Received read error: %#v\", err)\n", "\t}\n", "\tf.ResponseBody = string(bodyReceived)\n", "}\n", "\n", "func (f FakeHandler) ValidateRequest(t TestInterface, expectedPath, expectedMethod string, body *string) {\n", "\tif f.RequestReceived.URL.Path != expectedPath {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tf.RequestBody = string(bodyReceived)\n" ], "file_path": "pkg/util/fake_handler.go", "type": "replace", "edit_start_line_idx": 50 }
{ "kind": "discovery#restDescription", "etag": "\"kEk3sFj6Ef5_yR1-H3bAO6qw9mI/WlcQEurGo0sEddzjdUrIBdx9npM\"", "discoveryVersion": "v1", "id": "oauth2:v1", "name": "oauth2", "version": "v1", "title": "Google OAuth2 API", "description": "Lets you access OAuth2 protocol related APIs.", "ownerDomain": "google.com", "ownerName": "Google", "icons": { "x16": "http://www.google.com/images/icons/product/search-16.gif", "x32": "http://www.google.com/images/icons/product/search-32.gif" }, "documentationLink": "https://developers.google.com/accounts/docs/OAuth2", "protocol": "rest", "baseUrl": "https://www.googleapis.com/", "basePath": "/", "rootUrl": "https://www.googleapis.com/", "servicePath": "", "batchPath": "batch", "parameters": { "alt": { "type": "string", "description": "Data format for the response.", "default": "json", "enum": [ "json" ], "enumDescriptions": [ "Responses with Content-Type of application/json" ], "location": "query" }, "fields": { "type": "string", "description": "Selector specifying which fields to include in a partial response.", "location": "query" }, "key": { "type": "string", "description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.", "location": "query" }, "oauth_token": { "type": "string", "description": "OAuth 2.0 token for the current user.", "location": "query" }, "prettyPrint": { "type": "boolean", "description": "Returns response with indentations and line breaks.", "default": "true", "location": "query" }, "quotaUser": { "type": "string", "description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.", "location": "query" }, "userIp": { "type": "string", "description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.", "location": "query" } }, "auth": { "oauth2": { "scopes": { "https://www.googleapis.com/auth/plus.login": { "description": "Know your basic profile info and list of people in your circles." }, "https://www.googleapis.com/auth/plus.me": { "description": "Know who you are on Google" }, "https://www.googleapis.com/auth/userinfo.email": { "description": "View your email address" }, "https://www.googleapis.com/auth/userinfo.profile": { "description": "View basic information about your account" } } } }, "schemas": { "Tokeninfo": { "id": "Tokeninfo", "type": "object", "properties": { "access_type": { "type": "string", "description": "The access type granted with this token. It can be offline or online." }, "audience": { "type": "string", "description": "Who is the intended audience for this token. In general the same as issued_to." }, "email": { "type": "string", "description": "The email address of the user. Present only if the email scope is present in the request." }, "email_verified": { "type": "boolean", "description": "Boolean flag which is true if the email address is verified. Present only if the email scope is present in the request." }, "expires_in": { "type": "integer", "description": "The expiry time of the token, as number of seconds left until expiry.", "format": "int32" }, "issued_at": { "type": "integer", "description": "The issue time of the token, as number of seconds.", "format": "int32" }, "issued_to": { "type": "string", "description": "To whom was the token issued to. In general the same as audience." }, "issuer": { "type": "string", "description": "Who issued the token." }, "nonce": { "type": "string", "description": "Nonce of the id token." }, "scope": { "type": "string", "description": "The space separated list of scopes granted to this token." }, "user_id": { "type": "string", "description": "The Gaia obfuscated user id." }, "verified_email": { "type": "boolean", "description": "Boolean flag which is true if the email address is verified. Present only if the email scope is present in the request." } } }, "Userinfoplus": { "id": "Userinfoplus", "type": "object", "properties": { "email": { "type": "string", "description": "The user's email address." }, "family_name": { "type": "string", "description": "The user's last name." }, "gender": { "type": "string", "description": "The user's gender." }, "given_name": { "type": "string", "description": "The user's first name." }, "hd": { "type": "string", "description": "The hosted domain e.g. example.com if the user is Google apps user." }, "id": { "type": "string", "description": "The focus obfuscated gaia id of the user." }, "link": { "type": "string", "description": "URL of the profile page." }, "locale": { "type": "string", "description": "The user's preferred locale." }, "name": { "type": "string", "description": "The user's full name." }, "picture": { "type": "string", "description": "URL of the user's picture image." }, "verified_email": { "type": "boolean", "description": "Boolean flag which is true if the email address is verified. Always verified because we only return the user's primary email address.", "default": "true" } } } }, "methods": { "tokeninfo": { "id": "oauth2.tokeninfo", "path": "oauth2/v1/tokeninfo", "httpMethod": "POST", "description": "Get token info", "parameters": { "access_token": { "type": "string", "description": "The oauth2 access token", "location": "query" }, "id_token": { "type": "string", "description": "The ID token", "location": "query" } }, "response": { "$ref": "Tokeninfo" } } }, "resources": { "userinfo": { "methods": { "get": { "id": "oauth2.userinfo.get", "path": "oauth2/v1/userinfo", "httpMethod": "GET", "description": "Get user info", "response": { "$ref": "Userinfoplus" }, "scopes": [ "https://www.googleapis.com/auth/plus.login", "https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile" ] } }, "resources": { "v2": { "resources": { "me": { "methods": { "get": { "id": "oauth2.userinfo.v2.me.get", "path": "userinfo/v2/me", "httpMethod": "GET", "description": "Get user info", "response": { "$ref": "Userinfoplus" }, "scopes": [ "https://www.googleapis.com/auth/plus.login", "https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile" ] } } } } } } } } }
third_party/src/code.google.com/p/google-api-go-client/oauth2/v1/oauth2-api.json
0
https://github.com/kubernetes/kubernetes/commit/b6a260940c7661baea30599c5f5ad370de3c9633
[ 0.00017702662444207817, 0.00017326381930615753, 0.00016928526747506112, 0.00017374464368913323, 0.000001998044808715349 ]
{ "id": 3, "code_window": [ "\t\tt.Errorf(\"Unexpected method: %s\", f.RequestReceived.Method)\n", "\t}\n", "\tif body != nil {\n", "\t\tif *body != f.ResponseBody {\n", "\t\t\tt.Errorf(\"Received body:\\n%s\\n Doesn't match expected body:\\n%s\", f.ResponseBody, *body)\n", "\t\t}\n", "\t}\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tif *body != f.RequestBody {\n", "\t\t\tt.Errorf(\"Received body:\\n%s\\n Doesn't match expected body:\\n%s\", f.RequestBody, *body)\n" ], "file_path": "pkg/util/fake_handler.go", "type": "replace", "edit_start_line_idx": 61 }
/* 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 util import ( "io/ioutil" "net/http" ) // TestInterface is a simple interface providing Errorf, to make injection for // testing easier (insert 'yo dawg' meme here) type TestInterface interface { Errorf(format string, args ...interface{}) } type LogInterface interface { Logf(format string, args ...interface{}) } // FakeHandler is to assist in testing HTTP requests. type FakeHandler struct { RequestReceived *http.Request StatusCode int ResponseBody string // For logging - you can use a *testing.T // This will keep log messages associated with the test. T LogInterface } func (f *FakeHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) { f.RequestReceived = request response.WriteHeader(f.StatusCode) response.Write([]byte(f.ResponseBody)) bodyReceived, err := ioutil.ReadAll(request.Body) if err != nil && f.T != nil { f.T.Logf("Received read error: %#v", err) } f.ResponseBody = string(bodyReceived) } func (f FakeHandler) ValidateRequest(t TestInterface, expectedPath, expectedMethod string, body *string) { if f.RequestReceived.URL.Path != expectedPath { t.Errorf("Unexpected request path: %s", f.RequestReceived.URL.Path) } if f.RequestReceived.Method != expectedMethod { t.Errorf("Unexpected method: %s", f.RequestReceived.Method) } if body != nil { if *body != f.ResponseBody { t.Errorf("Received body:\n%s\n Doesn't match expected body:\n%s", f.ResponseBody, *body) } } }
pkg/util/fake_handler.go
1
https://github.com/kubernetes/kubernetes/commit/b6a260940c7661baea30599c5f5ad370de3c9633
[ 0.9910218119621277, 0.1434735208749771, 0.0001785319036571309, 0.0029613683000206947, 0.346015065908432 ]
{ "id": 3, "code_window": [ "\t\tt.Errorf(\"Unexpected method: %s\", f.RequestReceived.Method)\n", "\t}\n", "\tif body != nil {\n", "\t\tif *body != f.ResponseBody {\n", "\t\t\tt.Errorf(\"Received body:\\n%s\\n Doesn't match expected body:\\n%s\", f.ResponseBody, *body)\n", "\t\t}\n", "\t}\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tif *body != f.RequestBody {\n", "\t\t\tt.Errorf(\"Received body:\\n%s\\n Doesn't match expected body:\\n%s\", f.RequestBody, *body)\n" ], "file_path": "pkg/util/fake_handler.go", "type": "replace", "edit_start_line_idx": 61 }
// Copyright 2011 The goauth2 Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // The oauth package provides support for making // OAuth2-authenticated HTTP requests. // // Example usage: // // // Specify your configuration. (typically as a global variable) // var config = &oauth.Config{ // ClientId: YOUR_CLIENT_ID, // ClientSecret: YOUR_CLIENT_SECRET, // Scope: "https://www.googleapis.com/auth/buzz", // AuthURL: "https://accounts.google.com/o/oauth2/auth", // TokenURL: "https://accounts.google.com/o/oauth2/token", // RedirectURL: "http://you.example.org/handler", // } // // // A landing page redirects to the OAuth provider to get the auth code. // func landing(w http.ResponseWriter, r *http.Request) { // http.Redirect(w, r, config.AuthCodeURL("foo"), http.StatusFound) // } // // // The user will be redirected back to this handler, that takes the // // "code" query parameter and Exchanges it for an access token. // func handler(w http.ResponseWriter, r *http.Request) { // t := &oauth.Transport{Config: config} // t.Exchange(r.FormValue("code")) // // The Transport now has a valid Token. Create an *http.Client // // with which we can make authenticated API requests. // c := t.Client() // c.Post(...) // // ... // // btw, r.FormValue("state") == "foo" // } // package oauth import ( "encoding/json" "io/ioutil" "mime" "net/http" "net/url" "os" "strings" "time" ) type OAuthError struct { prefix string msg string } func (oe OAuthError) Error() string { return "OAuthError: " + oe.prefix + ": " + oe.msg } // Cache specifies the methods that implement a Token cache. type Cache interface { Token() (*Token, error) PutToken(*Token) error } // CacheFile implements Cache. Its value is the name of the file in which // the Token is stored in JSON format. type CacheFile string func (f CacheFile) Token() (*Token, error) { file, err := os.Open(string(f)) if err != nil { return nil, OAuthError{"CacheFile.Token", err.Error()} } defer file.Close() tok := &Token{} if err := json.NewDecoder(file).Decode(tok); err != nil { return nil, OAuthError{"CacheFile.Token", err.Error()} } return tok, nil } func (f CacheFile) PutToken(tok *Token) error { file, err := os.OpenFile(string(f), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return OAuthError{"CacheFile.PutToken", err.Error()} } if err := json.NewEncoder(file).Encode(tok); err != nil { file.Close() return OAuthError{"CacheFile.PutToken", err.Error()} } if err := file.Close(); err != nil { return OAuthError{"CacheFile.PutToken", err.Error()} } return nil } // Config is the configuration of an OAuth consumer. type Config struct { // ClientId is the OAuth client identifier used when communicating with // the configured OAuth provider. ClientId string // ClientSecret is the OAuth client secret used when communicating with // the configured OAuth provider. ClientSecret string // Scope identifies the level of access being requested. Multiple scope // values should be provided as a space-delimited string. Scope string // AuthURL is the URL the user will be directed to in order to grant // access. AuthURL string // TokenURL is the URL used to retrieve OAuth tokens. TokenURL string // RedirectURL is the URL to which the user will be returned after // granting (or denying) access. RedirectURL string // TokenCache allows tokens to be cached for subsequent requests. TokenCache Cache AccessType string // Optional, "online" (default) or "offline", no refresh token if "online" // ApprovalPrompt indicates whether the user should be // re-prompted for consent. If set to "auto" (default) the // user will be prompted only if they haven't previously // granted consent and the code can only be exchanged for an // access token. // If set to "force" the user will always be prompted, and the // code can be exchanged for a refresh token. ApprovalPrompt string } // Token contains an end-user's tokens. // This is the data you must store to persist authentication. type Token struct { AccessToken string RefreshToken string Expiry time.Time // If zero the token has no (known) expiry time. Extra map[string]string // May be nil. } func (t *Token) Expired() bool { if t.Expiry.IsZero() { return false } return t.Expiry.Before(time.Now()) } // Transport implements http.RoundTripper. When configured with a valid // Config and Token it can be used to make authenticated HTTP requests. // // t := &oauth.Transport{config} // t.Exchange(code) // // t now contains a valid Token // r, _, err := t.Client().Get("http://example.org/url/requiring/auth") // // It will automatically refresh the Token if it can, // updating the supplied Token in place. type Transport struct { *Config *Token // Transport is the HTTP transport to use when making requests. // It will default to http.DefaultTransport if nil. // (It should never be an oauth.Transport.) Transport http.RoundTripper } // Client returns an *http.Client that makes OAuth-authenticated requests. func (t *Transport) Client() *http.Client { return &http.Client{Transport: t} } func (t *Transport) transport() http.RoundTripper { if t.Transport != nil { return t.Transport } return http.DefaultTransport } // AuthCodeURL returns a URL that the end-user should be redirected to, // so that they may obtain an authorization code. func (c *Config) AuthCodeURL(state string) string { url_, err := url.Parse(c.AuthURL) if err != nil { panic("AuthURL malformed: " + err.Error()) } q := url.Values{ "response_type": {"code"}, "client_id": {c.ClientId}, "redirect_uri": {c.RedirectURL}, "scope": {c.Scope}, "state": {state}, "access_type": {c.AccessType}, "approval_prompt": {c.ApprovalPrompt}, }.Encode() if url_.RawQuery == "" { url_.RawQuery = q } else { url_.RawQuery += "&" + q } return url_.String() } // Exchange takes a code and gets access Token from the remote server. func (t *Transport) Exchange(code string) (*Token, error) { if t.Config == nil { return nil, OAuthError{"Exchange", "no Config supplied"} } // If the transport or the cache already has a token, it is // passed to `updateToken` to preserve existing refresh token. tok := t.Token if tok == nil && t.TokenCache != nil { tok, _ = t.TokenCache.Token() } if tok == nil { tok = new(Token) } err := t.updateToken(tok, url.Values{ "grant_type": {"authorization_code"}, "redirect_uri": {t.RedirectURL}, "scope": {t.Scope}, "code": {code}, }) if err != nil { return nil, err } t.Token = tok if t.TokenCache != nil { return tok, t.TokenCache.PutToken(tok) } return tok, nil } // RoundTrip executes a single HTTP transaction using the Transport's // Token as authorization headers. // // This method will attempt to renew the Token if it has expired and may return // an error related to that Token renewal before attempting the client request. // If the Token cannot be renewed a non-nil os.Error value will be returned. // If the Token is invalid callers should expect HTTP-level errors, // as indicated by the Response's StatusCode. func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { if t.Token == nil { if t.Config == nil { return nil, OAuthError{"RoundTrip", "no Config supplied"} } if t.TokenCache == nil { return nil, OAuthError{"RoundTrip", "no Token supplied"} } var err error t.Token, err = t.TokenCache.Token() if err != nil { return nil, err } } // Refresh the Token if it has expired. if t.Expired() { if err := t.Refresh(); err != nil { return nil, err } } // To set the Authorization header, we must make a copy of the Request // so that we don't modify the Request we were given. // This is required by the specification of http.RoundTripper. req = cloneRequest(req) req.Header.Set("Authorization", "Bearer "+t.AccessToken) // Make the HTTP request. return t.transport().RoundTrip(req) } // cloneRequest returns a clone of the provided *http.Request. // The clone is a shallow copy of the struct and its Header map. func cloneRequest(r *http.Request) *http.Request { // shallow copy of the struct r2 := new(http.Request) *r2 = *r // deep copy of the Header r2.Header = make(http.Header) for k, s := range r.Header { r2.Header[k] = s } return r2 } // Refresh renews the Transport's AccessToken using its RefreshToken. func (t *Transport) Refresh() error { if t.Token == nil { return OAuthError{"Refresh", "no existing Token"} } if t.RefreshToken == "" { return OAuthError{"Refresh", "Token expired; no Refresh Token"} } if t.Config == nil { return OAuthError{"Refresh", "no Config supplied"} } err := t.updateToken(t.Token, url.Values{ "grant_type": {"refresh_token"}, "refresh_token": {t.RefreshToken}, }) if err != nil { return err } if t.TokenCache != nil { return t.TokenCache.PutToken(t.Token) } return nil } func (t *Transport) updateToken(tok *Token, v url.Values) error { v.Set("client_id", t.ClientId) v.Set("client_secret", t.ClientSecret) client := &http.Client{Transport: t.transport()} req, err := http.NewRequest("POST", t.TokenURL, strings.NewReader(v.Encode())) if err != nil { return err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.SetBasicAuth(t.ClientId, t.ClientSecret) r, err := client.Do(req) if err != nil { return err } defer r.Body.Close() if r.StatusCode != 200 { return OAuthError{"updateToken", r.Status} } var b struct { Access string `json:"access_token"` Refresh string `json:"refresh_token"` ExpiresIn time.Duration `json:"expires_in"` Id string `json:"id_token"` } content, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")) switch content { case "application/x-www-form-urlencoded", "text/plain": body, err := ioutil.ReadAll(r.Body) if err != nil { return err } vals, err := url.ParseQuery(string(body)) if err != nil { return err } b.Access = vals.Get("access_token") b.Refresh = vals.Get("refresh_token") b.ExpiresIn, _ = time.ParseDuration(vals.Get("expires_in") + "s") b.Id = vals.Get("id_token") default: if err = json.NewDecoder(r.Body).Decode(&b); err != nil { return err } // The JSON parser treats the unitless ExpiresIn like 'ns' instead of 's' as above, // so compensate here. b.ExpiresIn *= time.Second } tok.AccessToken = b.Access // Don't overwrite `RefreshToken` with an empty value if len(b.Refresh) > 0 { tok.RefreshToken = b.Refresh } if b.ExpiresIn == 0 { tok.Expiry = time.Time{} } else { tok.Expiry = time.Now().Add(b.ExpiresIn) } if b.Id != "" { if tok.Extra == nil { tok.Extra = make(map[string]string) } tok.Extra["id_token"] = b.Id } return nil }
third_party/src/code.google.com/p/goauth2/oauth/oauth.go
0
https://github.com/kubernetes/kubernetes/commit/b6a260940c7661baea30599c5f5ad370de3c9633
[ 0.002233373699709773, 0.0002994972746819258, 0.00016238066018559039, 0.00017354663577862084, 0.0003727477160282433 ]
{ "id": 3, "code_window": [ "\t\tt.Errorf(\"Unexpected method: %s\", f.RequestReceived.Method)\n", "\t}\n", "\tif body != nil {\n", "\t\tif *body != f.ResponseBody {\n", "\t\t\tt.Errorf(\"Received body:\\n%s\\n Doesn't match expected body:\\n%s\", f.ResponseBody, *body)\n", "\t\t}\n", "\t}\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tif *body != f.RequestBody {\n", "\t\t\tt.Errorf(\"Received body:\\n%s\\n Doesn't match expected body:\\n%s\", f.RequestBody, *body)\n" ], "file_path": "pkg/util/fake_handler.go", "type": "replace", "edit_start_line_idx": 61 }
{ "kind": "discovery#restDescription", "etag": "\"kEk3sFj6Ef5_yR1-H3bAO6qw9mI/5fAOCCT-EMDzKZ0hPKCYdJUAc9k\"", "discoveryVersion": "v1", "id": "customsearch:v1", "name": "customsearch", "version": "v1", "title": "CustomSearch API", "description": "Lets you search over a website or collection of websites", "ownerDomain": "google.com", "ownerName": "Google", "icons": { "x16": "http://www.google.com/images/icons/product/search-16.gif", "x32": "http://www.google.com/images/icons/product/search-32.gif" }, "documentationLink": "https://developers.google.com/custom-search/v1/using_rest", "protocol": "rest", "baseUrl": "https://www.googleapis.com/customsearch/", "basePath": "/customsearch/", "rootUrl": "https://www.googleapis.com/", "servicePath": "customsearch/", "batchPath": "batch", "parameters": { "alt": { "type": "string", "description": "Data format for the response.", "default": "json", "enum": [ "atom", "json" ], "enumDescriptions": [ "Responses with Content-Type of application/atom+xml", "Responses with Content-Type of application/json" ], "location": "query" }, "fields": { "type": "string", "description": "Selector specifying which fields to include in a partial response.", "location": "query" }, "key": { "type": "string", "description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.", "location": "query" }, "oauth_token": { "type": "string", "description": "OAuth 2.0 token for the current user.", "location": "query" }, "prettyPrint": { "type": "boolean", "description": "Returns response with indentations and line breaks.", "default": "true", "location": "query" }, "quotaUser": { "type": "string", "description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.", "location": "query" }, "userIp": { "type": "string", "description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.", "location": "query" } }, "schemas": { "Context": { "id": "Context", "type": "object", "properties": { "facets": { "type": "array", "items": { "type": "array", "items": { "type": "object", "properties": { "anchor": { "type": "string" }, "label": { "type": "string" }, "label_with_op": { "type": "string" } } } } }, "title": { "type": "string" } } }, "Promotion": { "id": "Promotion", "type": "object", "properties": { "bodyLines": { "type": "array", "items": { "type": "object", "properties": { "htmlTitle": { "type": "string" }, "link": { "type": "string" }, "title": { "type": "string" }, "url": { "type": "string" } } } }, "displayLink": { "type": "string" }, "htmlTitle": { "type": "string" }, "image": { "type": "object", "properties": { "height": { "type": "integer", "format": "int32" }, "source": { "type": "string" }, "width": { "type": "integer", "format": "int32" } } }, "link": { "type": "string" }, "title": { "type": "string" } } }, "Query": { "id": "Query", "type": "object", "properties": { "count": { "type": "integer", "format": "int32" }, "cr": { "type": "string" }, "cref": { "type": "string" }, "cx": { "type": "string" }, "dateRestrict": { "type": "string" }, "disableCnTwTranslation": { "type": "string" }, "exactTerms": { "type": "string" }, "excludeTerms": { "type": "string" }, "fileType": { "type": "string" }, "filter": { "type": "string" }, "gl": { "type": "string" }, "googleHost": { "type": "string" }, "highRange": { "type": "string" }, "hl": { "type": "string" }, "hq": { "type": "string" }, "imgColorType": { "type": "string" }, "imgDominantColor": { "type": "string" }, "imgSize": { "type": "string" }, "imgType": { "type": "string" }, "inputEncoding": { "type": "string" }, "language": { "type": "string" }, "linkSite": { "type": "string" }, "lowRange": { "type": "string" }, "orTerms": { "type": "string" }, "outputEncoding": { "type": "string" }, "relatedSite": { "type": "string" }, "rights": { "type": "string" }, "safe": { "type": "string" }, "searchTerms": { "type": "string" }, "searchType": { "type": "string" }, "siteSearch": { "type": "string" }, "siteSearchFilter": { "type": "string" }, "sort": { "type": "string" }, "startIndex": { "type": "integer", "format": "int32" }, "startPage": { "type": "integer", "format": "int32" }, "title": { "type": "string" }, "totalResults": { "type": "string", "format": "int64" } } }, "Result": { "id": "Result", "type": "object", "properties": { "cacheId": { "type": "string" }, "displayLink": { "type": "string" }, "fileFormat": { "type": "string" }, "formattedUrl": { "type": "string" }, "htmlFormattedUrl": { "type": "string" }, "htmlSnippet": { "type": "string" }, "htmlTitle": { "type": "string" }, "image": { "type": "object", "properties": { "byteSize": { "type": "integer", "format": "int32" }, "contextLink": { "type": "string" }, "height": { "type": "integer", "format": "int32" }, "thumbnailHeight": { "type": "integer", "format": "int32" }, "thumbnailLink": { "type": "string" }, "thumbnailWidth": { "type": "integer", "format": "int32" }, "width": { "type": "integer", "format": "int32" } } }, "kind": { "type": "string", "default": "customsearch#result" }, "labels": { "type": "array", "items": { "type": "object", "properties": { "displayName": { "type": "string" }, "label_with_op": { "type": "string" }, "name": { "type": "string" } } } }, "link": { "type": "string" }, "mime": { "type": "string" }, "pagemap": { "type": "object", "additionalProperties": { "type": "array", "items": { "type": "object", "additionalProperties": { "type": "any" } } } }, "snippet": { "type": "string" }, "title": { "type": "string" } } }, "Search": { "id": "Search", "type": "object", "properties": { "context": { "$ref": "Context" }, "items": { "type": "array", "items": { "$ref": "Result" } }, "kind": { "type": "string", "default": "customsearch#search" }, "promotions": { "type": "array", "items": { "$ref": "Promotion" } }, "queries": { "type": "object", "additionalProperties": { "type": "array", "items": { "$ref": "Query" } } }, "searchInformation": { "type": "object", "properties": { "formattedSearchTime": { "type": "string" }, "formattedTotalResults": { "type": "string" }, "searchTime": { "type": "number", "format": "double" }, "totalResults": { "type": "string", "format": "int64" } } }, "spelling": { "type": "object", "properties": { "correctedQuery": { "type": "string" }, "htmlCorrectedQuery": { "type": "string" } } }, "url": { "type": "object", "properties": { "template": { "type": "string", "default": "https://www.googleapis.com/customsearch/v1?q={searchTerms}&num={count?}&start={startIndex?}&lr={language?}&safe={safe?}&cx={cx?}&cref={cref?}&sort={sort?}&filter={filter?}&gl={gl?}&cr={cr?}&googlehost={googleHost?}&c2coff={disableCnTwTranslation?}&hq={hq?}&hl={hl?}&siteSearch={siteSearch?}&siteSearchFilter={siteSearchFilter?}&exactTerms={exactTerms?}&excludeTerms={excludeTerms?}&linkSite={linkSite?}&orTerms={orTerms?}&relatedSite={relatedSite?}&dateRestrict={dateRestrict?}&lowRange={lowRange?}&highRange={highRange?}&searchType={searchType}&fileType={fileType?}&rights={rights?}&imgSize={imgSize?}&imgType={imgType?}&imgColorType={imgColorType?}&imgDominantColor={imgDominantColor?}&alt=json" }, "type": { "type": "string", "default": "application/json" } } } } } }, "resources": { "cse": { "methods": { "list": { "id": "search.cse.list", "path": "v1", "httpMethod": "GET", "description": "Returns metadata about the search performed, metadata about the custom search engine used for the search, and the search results.", "parameters": { "c2coff": { "type": "string", "description": "Turns off the translation between zh-CN and zh-TW.", "location": "query" }, "cr": { "type": "string", "description": "Country restrict(s).", "location": "query" }, "cref": { "type": "string", "description": "The URL of a linked custom search engine", "location": "query" }, "cx": { "type": "string", "description": "The custom search engine ID to scope this search query", "location": "query" }, "dateRestrict": { "type": "string", "description": "Specifies all search results are from a time period", "location": "query" }, "exactTerms": { "type": "string", "description": "Identifies a phrase that all documents in the search results must contain", "location": "query" }, "excludeTerms": { "type": "string", "description": "Identifies a word or phrase that should not appear in any documents in the search results", "location": "query" }, "fileType": { "type": "string", "description": "Returns images of a specified type. Some of the allowed values are: bmp, gif, png, jpg, svg, pdf, ...", "location": "query" }, "filter": { "type": "string", "description": "Controls turning on or off the duplicate content filter.", "enum": [ "0", "1" ], "enumDescriptions": [ "Turns off duplicate content filter.", "Turns on duplicate content filter." ], "location": "query" }, "gl": { "type": "string", "description": "Geolocation of end user.", "location": "query" }, "googlehost": { "type": "string", "description": "The local Google domain to use to perform the search.", "location": "query" }, "highRange": { "type": "string", "description": "Creates a range in form as_nlo value..as_nhi value and attempts to append it to query", "location": "query" }, "hl": { "type": "string", "description": "Sets the user interface language.", "location": "query" }, "hq": { "type": "string", "description": "Appends the extra query terms to the query.", "location": "query" }, "imgColorType": { "type": "string", "description": "Returns black and white, grayscale, or color images: mono, gray, and color.", "enum": [ "color", "gray", "mono" ], "enumDescriptions": [ "color", "gray", "mono" ], "location": "query" }, "imgDominantColor": { "type": "string", "description": "Returns images of a specific dominant color: yellow, green, teal, blue, purple, pink, white, gray, black and brown.", "enum": [ "black", "blue", "brown", "gray", "green", "pink", "purple", "teal", "white", "yellow" ], "enumDescriptions": [ "black", "blue", "brown", "gray", "green", "pink", "purple", "teal", "white", "yellow" ], "location": "query" }, "imgSize": { "type": "string", "description": "Returns images of a specified size, where size can be one of: icon, small, medium, large, xlarge, xxlarge, and huge.", "enum": [ "huge", "icon", "large", "medium", "small", "xlarge", "xxlarge" ], "enumDescriptions": [ "huge", "icon", "large", "medium", "small", "xlarge", "xxlarge" ], "location": "query" }, "imgType": { "type": "string", "description": "Returns images of a type, which can be one of: clipart, face, lineart, news, and photo.", "enum": [ "clipart", "face", "lineart", "news", "photo" ], "enumDescriptions": [ "clipart", "face", "lineart", "news", "photo" ], "location": "query" }, "linkSite": { "type": "string", "description": "Specifies that all search results should contain a link to a particular URL", "location": "query" }, "lowRange": { "type": "string", "description": "Creates a range in form as_nlo value..as_nhi value and attempts to append it to query", "location": "query" }, "lr": { "type": "string", "description": "The language restriction for the search results", "enum": [ "lang_ar", "lang_bg", "lang_ca", "lang_cs", "lang_da", "lang_de", "lang_el", "lang_en", "lang_es", "lang_et", "lang_fi", "lang_fr", "lang_hr", "lang_hu", "lang_id", "lang_is", "lang_it", "lang_iw", "lang_ja", "lang_ko", "lang_lt", "lang_lv", "lang_nl", "lang_no", "lang_pl", "lang_pt", "lang_ro", "lang_ru", "lang_sk", "lang_sl", "lang_sr", "lang_sv", "lang_tr", "lang_zh-CN", "lang_zh-TW" ], "enumDescriptions": [ "Arabic", "Bulgarian", "Catalan", "Czech", "Danish", "German", "Greek", "English", "Spanish", "Estonian", "Finnish", "French", "Croatian", "Hungarian", "Indonesian", "Icelandic", "Italian", "Hebrew", "Japanese", "Korean", "Lithuanian", "Latvian", "Dutch", "Norwegian", "Polish", "Portuguese", "Romanian", "Russian", "Slovak", "Slovenian", "Serbian", "Swedish", "Turkish", "Chinese (Simplified)", "Chinese (Traditional)" ], "location": "query" }, "num": { "type": "integer", "description": "Number of search results to return", "default": "10", "format": "uint32", "location": "query" }, "orTerms": { "type": "string", "description": "Provides additional search terms to check for in a document, where each document in the search results must contain at least one of the additional search terms", "location": "query" }, "q": { "type": "string", "description": "Query", "required": true, "location": "query" }, "relatedSite": { "type": "string", "description": "Specifies that all search results should be pages that are related to the specified URL", "location": "query" }, "rights": { "type": "string", "description": "Filters based on licensing. Supported values include: cc_publicdomain, cc_attribute, cc_sharealike, cc_noncommercial, cc_nonderived and combinations of these.", "location": "query" }, "safe": { "type": "string", "description": "Search safety level", "default": "off", "enum": [ "high", "medium", "off" ], "enumDescriptions": [ "Enables highest level of safe search filtering.", "Enables moderate safe search filtering.", "Disables safe search filtering." ], "location": "query" }, "searchType": { "type": "string", "description": "Specifies the search type: image.", "enum": [ "image" ], "enumDescriptions": [ "custom image search" ], "location": "query" }, "siteSearch": { "type": "string", "description": "Specifies all search results should be pages from a given site", "location": "query" }, "siteSearchFilter": { "type": "string", "description": "Controls whether to include or exclude results from the site named in the as_sitesearch parameter", "enum": [ "e", "i" ], "enumDescriptions": [ "exclude", "include" ], "location": "query" }, "sort": { "type": "string", "description": "The sort expression to apply to the results", "location": "query" }, "start": { "type": "integer", "description": "The index of the first result to return", "format": "uint32", "location": "query" } }, "parameterOrder": [ "q" ], "response": { "$ref": "Search" } } } } } }
third_party/src/code.google.com/p/google-api-go-client/customsearch/v1/customsearch-api.json
0
https://github.com/kubernetes/kubernetes/commit/b6a260940c7661baea30599c5f5ad370de3c9633
[ 0.0001789197704056278, 0.00017561142158228904, 0.00016965693794190884, 0.0001757655991241336, 0.000001678367993918073 ]
{ "id": 3, "code_window": [ "\t\tt.Errorf(\"Unexpected method: %s\", f.RequestReceived.Method)\n", "\t}\n", "\tif body != nil {\n", "\t\tif *body != f.ResponseBody {\n", "\t\t\tt.Errorf(\"Received body:\\n%s\\n Doesn't match expected body:\\n%s\", f.ResponseBody, *body)\n", "\t\t}\n", "\t}\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tif *body != f.RequestBody {\n", "\t\t\tt.Errorf(\"Received body:\\n%s\\n Doesn't match expected body:\\n%s\", f.RequestBody, *body)\n" ], "file_path": "pkg/util/fake_handler.go", "type": "replace", "edit_start_line_idx": 61 }
/* Copyright 2013 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 journal provides write bindings to the systemd journal package journal import ( "bytes" "encoding/binary" "errors" "fmt" "io" "io/ioutil" "net" "os" "strconv" "strings" "syscall" ) // Priority of a journal message type Priority int const ( PriEmerg Priority = iota PriAlert PriCrit PriErr PriWarning PriNotice PriInfo PriDebug ) var conn net.Conn func init() { var err error conn, err = net.Dial("unixgram", "/run/systemd/journal/socket") if err != nil { conn = nil } } // Enabled returns true iff the systemd journal is available for logging func Enabled() bool { return conn != nil } // Send a message to the systemd journal. vars is a map of journald fields to // values. Fields must be composed of uppercase letters, numbers, and // underscores, but must not start with an underscore. Within these // restrictions, any arbitrary field name may be used. Some names have special // significance: see the journalctl documentation // (http://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html) // for more details. vars may be nil. func Send(message string, priority Priority, vars map[string]string) error { if conn == nil { return journalError("could not connect to journald socket") } data := new(bytes.Buffer) appendVariable(data, "PRIORITY", strconv.Itoa(int(priority))) appendVariable(data, "MESSAGE", message) for k, v := range vars { appendVariable(data, k, v) } _, err := io.Copy(conn, data) if err != nil && isSocketSpaceError(err) { file, err := tempFd() if err != nil { return journalError(err.Error()) } _, err = io.Copy(file, data) if err != nil { return journalError(err.Error()) } rights := syscall.UnixRights(int(file.Fd())) /* this connection should always be a UnixConn, but better safe than sorry */ unixConn, ok := conn.(*net.UnixConn) if !ok { return journalError("can't send file through non-Unix connection") } unixConn.WriteMsgUnix([]byte{}, rights, nil) } else if err != nil { return journalError(err.Error()) } return nil } func appendVariable(w io.Writer, name, value string) { if !validVarName(name) { journalError("variable name contains invalid character, ignoring") } if strings.ContainsRune(value, '\n') { /* When the value contains a newline, we write: * - the variable name, followed by a newline * - the size (in 64bit little endian format) * - the data, followed by a newline */ fmt.Fprintln(w, name) binary.Write(w, binary.LittleEndian, uint64(len(value))) fmt.Fprintln(w, value) } else { /* just write the variable and value all on one line */ fmt.Fprintf(w, "%s=%s\n", name, value) } } func validVarName(name string) bool { /* The variable name must be in uppercase and consist only of characters, * numbers and underscores, and may not begin with an underscore. (from the docs) */ valid := name[0] != '_' for _, c := range name { valid = valid && ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') || c == '_' } return valid } func isSocketSpaceError(err error) bool { opErr, ok := err.(*net.OpError) if !ok { return false } sysErr, ok := opErr.Err.(syscall.Errno) if !ok { return false } return sysErr == syscall.EMSGSIZE || sysErr == syscall.ENOBUFS } func tempFd() (*os.File, error) { file, err := ioutil.TempFile("/dev/shm/", "journal.XXXXX") if err != nil { return nil, err } syscall.Unlink(file.Name()) if err != nil { return nil, err } return file, nil } func journalError(s string) error { s = "journal error: " + s fmt.Fprintln(os.Stderr, s) return errors.New(s) }
third_party/src/github.com/coreos/go-systemd/journal/send.go
0
https://github.com/kubernetes/kubernetes/commit/b6a260940c7661baea30599c5f5ad370de3c9633
[ 0.00017922882398124784, 0.00017203176685143262, 0.00016506874817423522, 0.000171849547768943, 0.000003982055659434991 ]
{ "id": 0, "code_window": [ "func countAvailablePods(pods []api.Pod, minReadySeconds int32) int32 {\n", "\tavailablePodCount := int32(0)\n", "\tfor _, pod := range pods {\n", "\t\t// TODO: Make the time.Now() as argument to allow unit test this.\n", "\t\tif IsPodAvailable(&pod, minReadySeconds, time.Now()) {\n", "\t\t\tglog.V(4).Infof(\"Pod %s/%s is available.\", pod.Namespace, pod.Name)\n", "\t\t\tavailablePodCount++\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// FIXME: avoid using time.Now\n" ], "file_path": "pkg/controller/deployment/util/deployment_util.go", "type": "add", "edit_start_line_idx": 607 }
/* 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 e2e import ( "fmt" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/annotations" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apis/extensions" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" client "k8s.io/kubernetes/pkg/client/unversioned" adapter "k8s.io/kubernetes/pkg/client/unversioned/adapters/internalclientset" deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util" "k8s.io/kubernetes/pkg/kubectl" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/watch" "k8s.io/kubernetes/test/e2e/framework" ) const ( // nginxImage defined in kubectl.go nginxImageName = "nginx" redisImage = "gcr.io/google_containers/redis:e2e" redisImageName = "redis" ) var _ = framework.KubeDescribe("Deployment", func() { f := framework.NewDefaultFramework("deployment") It("deployment should create new pods", func() { testNewDeployment(f) }) It("RollingUpdateDeployment should delete old pods and create new ones", func() { testRollingUpdateDeployment(f) }) It("RollingUpdateDeployment should scale up and down in the right order", func() { testRollingUpdateDeploymentEvents(f) }) It("RecreateDeployment should delete old pods and create new ones", func() { testRecreateDeployment(f) }) It("deployment should delete old replica sets", func() { testDeploymentCleanUpPolicy(f) }) It("deployment should support rollover", func() { testRolloverDeployment(f) }) It("paused deployment should be ignored by the controller", func() { testPausedDeployment(f) }) It("deployment should support rollback", func() { testRollbackDeployment(f) }) It("deployment should support rollback when there's replica set with no revision", func() { testRollbackDeploymentRSNoRevision(f) }) It("deployment should label adopted RSs and pods", func() { testDeploymentLabelAdopted(f) }) It("paused deployment should be able to scale", func() { testScalePausedDeployment(f) }) It("scaled rollout should not block on annotation check", func() { testScaledRolloutDeployment(f) }) }) func newRS(rsName string, replicas int32, rsPodLabels map[string]string, imageName string, image string) *extensions.ReplicaSet { zero := int64(0) return &extensions.ReplicaSet{ ObjectMeta: api.ObjectMeta{ Name: rsName, }, Spec: extensions.ReplicaSetSpec{ Replicas: replicas, Selector: &unversioned.LabelSelector{MatchLabels: rsPodLabels}, Template: api.PodTemplateSpec{ ObjectMeta: api.ObjectMeta{ Labels: rsPodLabels, }, Spec: api.PodSpec{ TerminationGracePeriodSeconds: &zero, Containers: []api.Container{ { Name: imageName, Image: image, }, }, }, }, }, } } func newDeployment(deploymentName string, replicas int32, podLabels map[string]string, imageName string, image string, strategyType extensions.DeploymentStrategyType, revisionHistoryLimit *int32) *extensions.Deployment { zero := int64(0) return &extensions.Deployment{ ObjectMeta: api.ObjectMeta{ Name: deploymentName, }, Spec: extensions.DeploymentSpec{ Replicas: replicas, Selector: &unversioned.LabelSelector{MatchLabels: podLabels}, Strategy: extensions.DeploymentStrategy{ Type: strategyType, }, RevisionHistoryLimit: revisionHistoryLimit, Template: api.PodTemplateSpec{ ObjectMeta: api.ObjectMeta{ Labels: podLabels, }, Spec: api.PodSpec{ TerminationGracePeriodSeconds: &zero, Containers: []api.Container{ { Name: imageName, Image: image, }, }, }, }, }, } } func newDeploymentRollback(name string, annotations map[string]string, revision int64) *extensions.DeploymentRollback { return &extensions.DeploymentRollback{ Name: name, UpdatedAnnotations: annotations, RollbackTo: extensions.RollbackConfig{Revision: revision}, } } // checkDeploymentRevision checks if the input deployment's and its new replica set's revision and images are as expected. func checkDeploymentRevision(c *clientset.Clientset, ns, deploymentName, revision, imageName, image string) (*extensions.Deployment, *extensions.ReplicaSet) { deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) // Check revision of the new replica set of this deployment newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(newRS.Annotations).NotTo(Equal(nil)) Expect(newRS.Annotations[deploymentutil.RevisionAnnotation]).Should(Equal(revision)) // Check revision of This deployment Expect(deployment.Annotations).NotTo(Equal(nil)) Expect(deployment.Annotations[deploymentutil.RevisionAnnotation]).Should(Equal(revision)) if len(imageName) > 0 { // Check the image the new replica set creates Expect(newRS.Spec.Template.Spec.Containers[0].Name).Should(Equal(imageName)) Expect(newRS.Spec.Template.Spec.Containers[0].Image).Should(Equal(image)) // Check the image the deployment creates Expect(deployment.Spec.Template.Spec.Containers[0].Name).Should(Equal(imageName)) Expect(deployment.Spec.Template.Spec.Containers[0].Image).Should(Equal(image)) } return deployment, newRS } func stopDeployment(c *clientset.Clientset, oldC client.Interface, ns, deploymentName string) { deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) framework.Logf("Deleting deployment %s", deploymentName) reaper, err := kubectl.ReaperFor(extensions.Kind("Deployment"), oldC) Expect(err).NotTo(HaveOccurred()) timeout := 1 * time.Minute err = reaper.Stop(ns, deployment.Name, timeout, api.NewDeleteOptions(0)) Expect(err).NotTo(HaveOccurred()) framework.Logf("Ensuring deployment %s was deleted", deploymentName) _, err = c.Extensions().Deployments(ns).Get(deployment.Name) Expect(err).To(HaveOccurred()) Expect(errors.IsNotFound(err)).To(BeTrue()) framework.Logf("Ensuring deployment %s's RSes were deleted", deploymentName) selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) Expect(err).NotTo(HaveOccurred()) options := api.ListOptions{LabelSelector: selector} rss, err := c.Extensions().ReplicaSets(ns).List(options) Expect(err).NotTo(HaveOccurred()) Expect(rss.Items).Should(HaveLen(0)) framework.Logf("Ensuring deployment %s's Pods were deleted", deploymentName) var pods *api.PodList if err := wait.PollImmediate(time.Second, timeout, func() (bool, error) { pods, err = c.Core().Pods(ns).List(api.ListOptions{}) if err != nil { return false, err } if len(pods.Items) == 0 { return true, nil } return false, nil }); err != nil { framework.Failf("Err : %s\n. Failed to remove deployment %s pods : %+v", err, deploymentName, pods) } } func testNewDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. c := adapter.FromUnversionedClient(f.Client) deploymentName := "test-new-deployment" podLabels := map[string]string{"name": nginxImageName} replicas := int32(1) framework.Logf("Creating simple deployment %s", deploymentName) d := newDeployment(deploymentName, replicas, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) d.Annotations = map[string]string{"test": "should-copy-to-replica-set", annotations.LastAppliedConfigAnnotation: "should-not-copy-to-replica-set"} deploy, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", nginxImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) // Check new RS annotations Expect(newRS.Annotations["test"]).Should(Equal("should-copy-to-replica-set")) Expect(newRS.Annotations[annotations.LastAppliedConfigAnnotation]).Should(Equal("")) Expect(deployment.Annotations["test"]).Should(Equal("should-copy-to-replica-set")) Expect(deployment.Annotations[annotations.LastAppliedConfigAnnotation]).Should(Equal("should-not-copy-to-replica-set")) } func testRollingUpdateDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "sample-pod"} rsPodLabels := map[string]string{ "name": "sample-pod", "pod": nginxImageName, } rsName := "test-rolling-update-controller" replicas := int32(3) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "sample-pod", false, 3) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-rolling-update-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RollingUpdateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", redisImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // There should be 1 old RS (nginx-controller, which is adopted) deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) _, allOldRSs, err := deploymentutil.GetOldReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(len(allOldRSs)).Should(Equal(1)) // The old RS should contain pod-template-hash in its selector, label, and template label Expect(len(allOldRSs[0].Labels[extensions.DefaultDeploymentUniqueLabelKey])).Should(BeNumerically(">", 0)) Expect(len(allOldRSs[0].Spec.Selector.MatchLabels[extensions.DefaultDeploymentUniqueLabelKey])).Should(BeNumerically(">", 0)) Expect(len(allOldRSs[0].Spec.Template.Labels[extensions.DefaultDeploymentUniqueLabelKey])).Should(BeNumerically(">", 0)) } func testRollingUpdateDeploymentEvents(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "sample-pod-2"} rsPodLabels := map[string]string{ "name": "sample-pod-2", "pod": nginxImageName, } rsName := "test-rolling-scale-controller" replicas := int32(1) rsRevision := "3546343826724305832" annotations := make(map[string]string) annotations[deploymentutil.RevisionAnnotation] = rsRevision rs := newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage) rs.Annotations = annotations _, err := c.Extensions().ReplicaSets(ns).Create(rs) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "sample-pod-2", false, 1) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-rolling-scale-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RollingUpdateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 3546343826724305833 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "3546343826724305833", redisImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Verify that the pods were scaled up and down as expected. We use events to verify that. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) framework.WaitForEvents(unversionedClient, ns, deployment, 2) events, err := c.Core().Events(ns).Search(deployment) if err != nil { framework.Logf("error in listing events: %s", err) Expect(err).NotTo(HaveOccurred()) } // There should be 2 events, one to scale up the new ReplicaSet and then to scale down // the old ReplicaSet. Expect(len(events.Items)).Should(Equal(2)) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(newRS).NotTo(Equal(nil)) Expect(events.Items[0].Message).Should(Equal(fmt.Sprintf("Scaled up replica set %s to 1", newRS.Name))) Expect(events.Items[1].Message).Should(Equal(fmt.Sprintf("Scaled down replica set %s to 0", rsName))) } func testRecreateDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "sample-pod-3"} rsPodLabels := map[string]string{ "name": "sample-pod-3", "pod": nginxImageName, } rsName := "test-recreate-controller" replicas := int32(3) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "sample-pod-3", false, 3) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-recreate-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RecreateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", redisImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Verify that the pods were scaled up and down as expected. We use events to verify that. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) framework.WaitForEvents(unversionedClient, ns, deployment, 2) events, err := c.Core().Events(ns).Search(deployment) if err != nil { framework.Logf("error in listing events: %s", err) Expect(err).NotTo(HaveOccurred()) } // There should be 2 events, one to scale up the new ReplicaSet and then to scale down the old ReplicaSet. Expect(len(events.Items)).Should(Equal(2)) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(newRS).NotTo(Equal(nil)) Expect(events.Items[0].Message).Should(Equal(fmt.Sprintf("Scaled down replica set %s to 0", rsName))) Expect(events.Items[1].Message).Should(Equal(fmt.Sprintf("Scaled up replica set %s to 3", newRS.Name))) } // testDeploymentCleanUpPolicy tests that deployment supports cleanup policy func testDeploymentCleanUpPolicy(f *framework.Framework) { ns := f.Namespace.Name unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "cleanup-pod"} rsPodLabels := map[string]string{ "name": "cleanup-pod", "pod": nginxImageName, } rsName := "test-cleanup-controller" replicas := int32(1) revisionHistoryLimit := util.Int32Ptr(0) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "cleanup-pod", false, 1) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-cleanup-deployment" framework.Logf("Creating deployment %s", deploymentName) pods, err := c.Pods(ns).List(api.ListOptions{LabelSelector: labels.Everything()}) if err != nil { Expect(err).NotTo(HaveOccurred(), "Failed to query for pods: %v", err) } options := api.ListOptions{ ResourceVersion: pods.ListMeta.ResourceVersion, } stopCh := make(chan struct{}) w, err := c.Pods(ns).Watch(options) go func() { // There should be only one pod being created, which is the pod with the redis image. // The old RS shouldn't create new pod when deployment controller adding pod template hash label to its selector. numPodCreation := 1 for { select { case event, _ := <-w.ResultChan(): if event.Type != watch.Added { continue } numPodCreation-- if numPodCreation < 0 { framework.Failf("Expect only one pod creation, the second creation event: %#v\n", event) } pod, ok := event.Object.(*api.Pod) if !ok { Fail("Expect event Object to be a pod") } if pod.Spec.Containers[0].Name != redisImageName { framework.Failf("Expect the created pod to have container name %s, got pod %#v\n", redisImageName, pod) } case <-stopCh: return } } }() _, err = c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RollingUpdateDeploymentStrategyType, revisionHistoryLimit)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) err = framework.WaitForDeploymentOldRSsNum(c, ns, deploymentName, int(*revisionHistoryLimit)) Expect(err).NotTo(HaveOccurred()) close(stopCh) } // testRolloverDeployment tests that deployment supports rollover. // i.e. we can change desired state and kick off rolling update, then change desired state again before it finishes. func testRolloverDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) podName := "rollover-pod" deploymentPodLabels := map[string]string{"name": podName} rsPodLabels := map[string]string{ "name": podName, "pod": nginxImageName, } rsName := "test-rollover-controller" rsReplicas := int32(4) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, rsReplicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, podName, false, rsReplicas) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Wait for the required pods to be ready for at least minReadySeconds (be available) deploymentMinReadySeconds := int32(5) err = framework.WaitForPodsReady(c, ns, podName, int(deploymentMinReadySeconds)) Expect(err).NotTo(HaveOccurred()) // Create a deployment to delete nginx pods and instead bring up redis-slave pods. deploymentName, deploymentImageName := "test-rollover-deployment", "redis-slave" deploymentReplicas := int32(4) deploymentImage := "gcr.io/google_samples/gb-redisslave:v1" deploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType framework.Logf("Creating deployment %s", deploymentName) newDeployment := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil) newDeployment.Spec.MinReadySeconds = deploymentMinReadySeconds newDeployment.Spec.Strategy.RollingUpdate = &extensions.RollingUpdateDeployment{ MaxUnavailable: intstr.FromInt(1), MaxSurge: intstr.FromInt(1), } _, err = c.Extensions().Deployments(ns).Create(newDeployment) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Verify that the pods were scaled up and down as expected. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) // Make sure the deployment starts to scale up and down replica sets by checking if its updated replicas >= 1 err = framework.WaitForDeploymentUpdatedReplicasLTE(c, ns, deploymentName, 1, deployment.Generation) // Check if it's updated to revision 1 correctly _, newRS := checkDeploymentRevision(c, ns, deploymentName, "1", deploymentImageName, deploymentImage) // Before the deployment finishes, update the deployment to rollover the above 2 ReplicaSets and bring up redis pods. // If the deployment already finished here, the test would fail. When this happens, increase its minReadySeconds or replicas to prevent it. Expect(newRS.Spec.Replicas).Should(BeNumerically("<", deploymentReplicas)) updatedDeploymentImageName, updatedDeploymentImage := redisImageName, redisImage deployment, err = framework.UpdateDeploymentWithRetries(c, ns, newDeployment.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName update.Spec.Template.Spec.Containers[0].Image = updatedDeploymentImage }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pod template update. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 2 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "2", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) } func testPausedDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) deploymentName := "test-paused-deployment" podLabels := map[string]string{"name": nginxImageName} d := newDeployment(deploymentName, 1, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) d.Spec.Paused = true tgps := int64(20) d.Spec.Template.Spec.TerminationGracePeriodSeconds = &tgps framework.Logf("Creating paused deployment %s", deploymentName) _, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Check that deployment is created fine. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) // Verify that there is no latest state realized for the new deployment. rs, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) if rs != nil { err = fmt.Errorf("unexpected new rs/%s for deployment/%s", rs.Name, deployment.Name) Expect(err).NotTo(HaveOccurred()) } // Update the deployment to run deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Paused = false }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the resume. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) if err != nil { Expect(err).NotTo(HaveOccurred()) } opts := api.ListOptions{LabelSelector: selector} w, err := c.Extensions().ReplicaSets(ns).Watch(opts) Expect(err).NotTo(HaveOccurred()) select { case <-w.ResultChan(): // this is it case <-time.After(time.Minute): err = fmt.Errorf("expected a new replica set to be created") Expect(err).NotTo(HaveOccurred()) } // Pause the deployment and delete the replica set. // The paused deployment shouldn't recreate a new one. deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Paused = true }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pause. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Update the deployment template - the new replicaset should stay the same framework.Logf("Updating paused deployment %q", deploymentName) newTGPS := int64(40) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.TerminationGracePeriodSeconds = &newTGPS }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) framework.Logf("Looking for new replicaset for paused deployment %q (there should be none)", deploymentName) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) if newRS != nil { err = fmt.Errorf("No replica set should match the deployment template but there is %q", newRS.Name) Expect(err).NotTo(HaveOccurred()) } _, allOldRs, err := deploymentutil.GetOldReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) if len(allOldRs) != 1 { err = fmt.Errorf("expected an old replica set") Expect(err).NotTo(HaveOccurred()) } framework.Logf("Comparing deployment diff with old replica set %q", allOldRs[0].Name) if *allOldRs[0].Spec.Template.Spec.TerminationGracePeriodSeconds == newTGPS { err = fmt.Errorf("TerminationGracePeriodSeconds on the replica set should be %d but is %d", tgps, newTGPS) Expect(err).NotTo(HaveOccurred()) } } // testRollbackDeployment tests that a deployment is created (revision 1) and updated (revision 2), and // then rollback to revision 1 (should update template to revision 1, and then update revision 1 to 3), // and then rollback to last revision. func testRollbackDeployment(f *framework.Framework) { ns := f.Namespace.Name unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) podName := "nginx" deploymentPodLabels := map[string]string{"name": podName} // 1. Create a deployment to create nginx pods. deploymentName, deploymentImageName := "test-rollback-deployment", nginxImageName deploymentReplicas := int32(1) deploymentImage := nginxImage deploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType framework.Logf("Creating deployment %s", deploymentName) d := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil) createAnnotation := map[string]string{"action": "create", "author": "minion"} d.Annotations = createAnnotation deploy, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "create" err = framework.CheckNewRSAnnotations(c, ns, deploymentName, createAnnotation) Expect(err).NotTo(HaveOccurred()) // 2. Update the deployment to create redis pods. updatedDeploymentImage := redisImage updatedDeploymentImageName := redisImageName updateAnnotation := map[string]string{"action": "update", "log": "I need to update it"} deployment, err := framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName update.Spec.Template.Spec.Containers[0].Image = updatedDeploymentImage update.Annotations = updateAnnotation }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pod template update. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 2 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "2", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "update" err = framework.CheckNewRSAnnotations(c, ns, deploymentName, updateAnnotation) Expect(err).NotTo(HaveOccurred()) // 3. Update the deploymentRollback to rollback to revision 1 revision := int64(1) framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback := newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackDone in deployment status and check it here // Wait for it to be updated to revision 3 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "3", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "create", after the rollback err = framework.CheckNewRSAnnotations(c, ns, deploymentName, createAnnotation) Expect(err).NotTo(HaveOccurred()) // 4. Update the deploymentRollback to rollback to last revision revision = 0 framework.Logf("rolling back deployment %s to last revision", deploymentName) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 4 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "4", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "update", after the rollback err = framework.CheckNewRSAnnotations(c, ns, deploymentName, updateAnnotation) Expect(err).NotTo(HaveOccurred()) } // testRollbackDeploymentRSNoRevision tests that deployment supports rollback even when there's old replica set without revision. // An old replica set without revision is created, and then a deployment is created (v1). The deployment shouldn't add revision // annotation to the old replica set. Then rollback the deployment to last revision, and it should fail. // Then update the deployment to v2 and rollback it to v1 should succeed, now the deployment // becomes v3. Then rollback the deployment to v10 (doesn't exist in history) should fail. // Finally, rollback the deployment (v3) to v3 should be no-op. // TODO: When we finished reporting rollback status in deployment status, check the rollback status here in each case. func testRollbackDeploymentRSNoRevision(f *framework.Framework) { ns := f.Namespace.Name c := adapter.FromUnversionedClient(f.Client) podName := "nginx" deploymentPodLabels := map[string]string{"name": podName} rsPodLabels := map[string]string{ "name": podName, "pod": nginxImageName, } // Create an old RS without revision rsName := "test-rollback-no-revision-controller" rsReplicas := int32(0) rs := newRS(rsName, rsReplicas, rsPodLabels, nginxImageName, nginxImage) rs.Annotations = make(map[string]string) rs.Annotations["make"] = "difference" _, err := c.Extensions().ReplicaSets(ns).Create(rs) Expect(err).NotTo(HaveOccurred()) // 1. Create a deployment to create nginx pods, which have different template than the replica set created above. deploymentName, deploymentImageName := "test-rollback-no-revision-deployment", nginxImageName deploymentReplicas := int32(1) deploymentImage := nginxImage deploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType framework.Logf("Creating deployment %s", deploymentName) d := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil) deploy, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Check that the replica set we created still doesn't contain revision information rs, err = c.Extensions().ReplicaSets(ns).Get(rsName) Expect(err).NotTo(HaveOccurred()) Expect(rs.Annotations[deploymentutil.RevisionAnnotation]).Should(Equal("")) // 2. Update the deploymentRollback to rollback to last revision // Since there's only 1 revision in history, it should stay as revision 1 revision := int64(0) framework.Logf("rolling back deployment %s to last revision", deploymentName) rollback := newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackRevisionNotFound in deployment status and check it here // The pod template shouldn't change since there's no last revision // Check if the deployment is still revision 1 and still has the old pod template checkDeploymentRevision(c, ns, deploymentName, "1", deploymentImageName, deploymentImage) // 3. Update the deployment to create redis pods. updatedDeploymentImage := redisImage updatedDeploymentImageName := redisImageName deployment, err := framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName update.Spec.Template.Spec.Containers[0].Image = updatedDeploymentImage }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pod template update. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 2 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "2", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // 4. Update the deploymentRollback to rollback to revision 1 revision = 1 framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackDone in deployment status and check it here // The pod template should be updated to the one in revision 1 // Wait for it to be updated to revision 3 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "3", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // 5. Update the deploymentRollback to rollback to revision 10 // Since there's no revision 10 in history, it should stay as revision 3 revision = 10 framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackRevisionNotFound in deployment status and check it here // The pod template shouldn't change since there's no revision 10 // Check if it's still revision 3 and still has the old pod template checkDeploymentRevision(c, ns, deploymentName, "3", deploymentImageName, deploymentImage) // 6. Update the deploymentRollback to rollback to revision 3 // Since it's already revision 3, it should be no-op revision = 3 framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackTemplateUnchanged in deployment status and check it here // The pod template shouldn't change since it's already revision 3 // Check if it's still revision 3 and still has the old pod template checkDeploymentRevision(c, ns, deploymentName, "3", deploymentImageName, deploymentImage) } func testDeploymentLabelAdopted(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. podName := "nginx" podLabels := map[string]string{"name": podName} rsName := "test-adopted-controller" replicas := int32(3) image := nginxImage _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, podLabels, podName, image)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, podName, false, 3) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a nginx deployment to adopt the old rs. deploymentName := "test-adopted-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, podLabels, podName, image, extensions.RollingUpdateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", image) Expect(err).NotTo(HaveOccurred()) // The RS and pods should be relabeled before the status is updated by syncRollingUpdateDeployment err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // There should be no old RSs (overlapping RS) deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) oldRSs, allOldRSs, newRS, err := deploymentutil.GetAllReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(len(oldRSs)).Should(Equal(0)) Expect(len(allOldRSs)).Should(Equal(0)) // New RS should contain pod-template-hash in its selector, label, and template label err = framework.CheckRSHashLabel(newRS) Expect(err).NotTo(HaveOccurred()) // All pods targeted by the deployment should contain pod-template-hash in their labels, and there should be only 3 pods selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) Expect(err).NotTo(HaveOccurred()) options := api.ListOptions{LabelSelector: selector} pods, err := c.Core().Pods(ns).List(options) Expect(err).NotTo(HaveOccurred()) err = framework.CheckPodHashLabel(pods) Expect(err).NotTo(HaveOccurred()) Expect(int32(len(pods.Items))).Should(Equal(replicas)) } func testScalePausedDeployment(f *framework.Framework) { ns := f.Namespace.Name c := adapter.FromUnversionedClient(f.Client) podLabels := map[string]string{"name": nginxImageName} replicas := int32(3) // Create a nginx deployment. deploymentName := "nginx-deployment" d := newDeployment(deploymentName, replicas, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) framework.Logf("Creating deployment %q", deploymentName) _, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Check that deployment is created fine. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) rs, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) // Pause the deployment and try to scale it. deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Paused = true }) Expect(err).NotTo(HaveOccurred()) // Scale the paused deployment. framework.Logf("Scaling up the paused deployment %q", deploymentName) newReplicas := int32(5) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { update.Spec.Replicas = newReplicas }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) rs, err = deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) if rs.Spec.Replicas != newReplicas { err = fmt.Errorf("Expected %d replicas for the new replica set, got %d", newReplicas, rs.Spec.Replicas) Expect(err).NotTo(HaveOccurred()) } } func testScaledRolloutDeployment(f *framework.Framework) { ns := f.Namespace.Name c := adapter.FromUnversionedClient(f.Client) podLabels := map[string]string{"name": nginxImageName} replicas := int32(10) // Create a nginx deployment. deploymentName := "nginx" d := newDeployment(deploymentName, replicas, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) d.Spec.Strategy.RollingUpdate = new(extensions.RollingUpdateDeployment) d.Spec.Strategy.RollingUpdate.MaxSurge = intstr.FromInt(3) d.Spec.Strategy.RollingUpdate.MaxUnavailable = intstr.FromInt(2) By(fmt.Sprintf("Creating deployment %q", deploymentName)) _, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Check that deployment is created fine. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for observed generation %d", deployment.Generation)) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) deployment, err = c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) first, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) // Update the deployment with a non-existent image so that the new replica set will be blocked. By(fmt.Sprintf("Updating deployment %q with a non-existent image", deploymentName)) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Image = "nginx:404" }) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for observed generation %d", deployment.Generation)) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) deployment, err = c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, false) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Checking that the replica sets for %q are synced", deploymentName)) second, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) first, err = c.Extensions().ReplicaSets(first.Namespace).Get(first.Name) Expect(err).NotTo(HaveOccurred()) firstCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), first) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, firstCond) secondCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), second) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, secondCond) By(fmt.Sprintf("Updating the size (up) and template at the same time for deployment %q", deploymentName)) newReplicas := int32(20) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { update.Spec.Replicas = newReplicas update.Spec.Template.Spec.Containers[0].Image = nautilusImage }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) oldRSs, _, rs, err := deploymentutil.GetAllReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) for _, rs := range append(oldRSs, rs) { By(fmt.Sprintf("Ensuring replica set %q has the correct desiredReplicas annotation", rs.Name)) desired, ok := deploymentutil.GetDesiredReplicasAnnotation(rs) if !ok || desired == deployment.Spec.Replicas { continue } err = fmt.Errorf("unexpected desiredReplicas annotation %d for replica set %q", desired, rs.Name) Expect(err).NotTo(HaveOccurred()) } By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Update the deployment with a non-existent image so that the new replica set will be blocked. By(fmt.Sprintf("Updating deployment %q with a non-existent image", deploymentName)) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Image = "nginx:404" }) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for observed generation %d", deployment.Generation)) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) deployment, err = c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, false) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Checking that the replica sets for %q are synced", deploymentName)) oldRs, err := c.Extensions().ReplicaSets(rs.Namespace).Get(rs.Name) Expect(err).NotTo(HaveOccurred()) newRs, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) oldCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), oldRs) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, oldCond) newCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), newRs) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, newCond) By(fmt.Sprintf("Updating the size (down) and template at the same time for deployment %q", deploymentName)) newReplicas = int32(5) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { update.Spec.Replicas = newReplicas update.Spec.Template.Spec.Containers[0].Image = kittenImage }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) oldRSs, _, rs, err = deploymentutil.GetAllReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) for _, rs := range append(oldRSs, rs) { By(fmt.Sprintf("Ensuring replica set %q has the correct desiredReplicas annotation", rs.Name)) desired, ok := deploymentutil.GetDesiredReplicasAnnotation(rs) if !ok || desired == deployment.Spec.Replicas { continue } err = fmt.Errorf("unexpected desiredReplicas annotation %d for replica set %q", desired, rs.Name) Expect(err).NotTo(HaveOccurred()) } By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) }
test/e2e/deployment.go
1
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.07605889439582825, 0.0016146426787599921, 0.00016501634672749788, 0.000174592700204812, 0.007400323636829853 ]
{ "id": 0, "code_window": [ "func countAvailablePods(pods []api.Pod, minReadySeconds int32) int32 {\n", "\tavailablePodCount := int32(0)\n", "\tfor _, pod := range pods {\n", "\t\t// TODO: Make the time.Now() as argument to allow unit test this.\n", "\t\tif IsPodAvailable(&pod, minReadySeconds, time.Now()) {\n", "\t\t\tglog.V(4).Infof(\"Pod %s/%s is available.\", pod.Namespace, pod.Name)\n", "\t\t\tavailablePodCount++\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// FIXME: avoid using time.Now\n" ], "file_path": "pkg/controller/deployment/util/deployment_util.go", "type": "add", "edit_start_line_idx": 607 }
### flannel This is used mostly for the `docker-multinode` config, but also in other places where flannel runs in a container. For `amd64`, this image equals to `quay.io/coreos/flannel` to maintain official support. For other architectures, `flannel` is cross-compiled. The `debian-iptables` image serves as base image. #### How to release ```console # Build for linux/amd64 (default) $ make push ARCH=amd64 # ---> gcr.io/google_containers/flannel-amd64:TAG $ make push ARCH=arm # ---> gcr.io/google_containers/flannel-arm:TAG $ make push ARCH=arm64 # ---> gcr.io/google_containers/flannel-arm64:TAG $ make push ARCH=ppc64le # ---> gcr.io/google_containers/flannel-ppc64le:TAG ``` If you don't want to push the images, run `make` or `make build` instead [![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/cluster/images/flannel/README.md?pixel)]()
cluster/images/flannel/README.md
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.00017324024520348758, 0.00017238158034160733, 0.00017161063442472368, 0.00017229386139661074, 6.681710260636464e-7 ]
{ "id": 0, "code_window": [ "func countAvailablePods(pods []api.Pod, minReadySeconds int32) int32 {\n", "\tavailablePodCount := int32(0)\n", "\tfor _, pod := range pods {\n", "\t\t// TODO: Make the time.Now() as argument to allow unit test this.\n", "\t\tif IsPodAvailable(&pod, minReadySeconds, time.Now()) {\n", "\t\t\tglog.V(4).Infof(\"Pod %s/%s is available.\", pod.Namespace, pod.Name)\n", "\t\t\tavailablePodCount++\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// FIXME: avoid using time.Now\n" ], "file_path": "pkg/controller/deployment/util/deployment_util.go", "type": "add", "edit_start_line_idx": 607 }
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2012 The Go Authors. All rights reserved. // https://github.com/golang/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. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // +build !appengine // This file contains the implementation of the proto field accesses using package unsafe. package proto import ( "reflect" "unsafe" ) // NOTE: These type_Foo functions would more idiomatically be methods, // but Go does not allow methods on pointer types, and we must preserve // some pointer type for the garbage collector. We use these // funcs with clunky names as our poor approximation to methods. // // An alternative would be // type structPointer struct { p unsafe.Pointer } // but that does not registerize as well. // A structPointer is a pointer to a struct. type structPointer unsafe.Pointer // toStructPointer returns a structPointer equivalent to the given reflect value. func toStructPointer(v reflect.Value) structPointer { return structPointer(unsafe.Pointer(v.Pointer())) } // IsNil reports whether p is nil. func structPointer_IsNil(p structPointer) bool { return p == nil } // Interface returns the struct pointer, assumed to have element type t, // as an interface value. func structPointer_Interface(p structPointer, t reflect.Type) interface{} { return reflect.NewAt(t, unsafe.Pointer(p)).Interface() } // A field identifies a field in a struct, accessible from a structPointer. // In this implementation, a field is identified by its byte offset from the start of the struct. type field uintptr // toField returns a field equivalent to the given reflect field. func toField(f *reflect.StructField) field { return field(f.Offset) } // invalidField is an invalid field identifier. const invalidField = ^field(0) // IsValid reports whether the field identifier is valid. func (f field) IsValid() bool { return f != ^field(0) } // Bytes returns the address of a []byte field in the struct. func structPointer_Bytes(p structPointer, f field) *[]byte { return (*[]byte)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // BytesSlice returns the address of a [][]byte field in the struct. func structPointer_BytesSlice(p structPointer, f field) *[][]byte { return (*[][]byte)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // Bool returns the address of a *bool field in the struct. func structPointer_Bool(p structPointer, f field) **bool { return (**bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // BoolVal returns the address of a bool field in the struct. func structPointer_BoolVal(p structPointer, f field) *bool { return (*bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // BoolSlice returns the address of a []bool field in the struct. func structPointer_BoolSlice(p structPointer, f field) *[]bool { return (*[]bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // String returns the address of a *string field in the struct. func structPointer_String(p structPointer, f field) **string { return (**string)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // StringVal returns the address of a string field in the struct. func structPointer_StringVal(p structPointer, f field) *string { return (*string)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // StringSlice returns the address of a []string field in the struct. func structPointer_StringSlice(p structPointer, f field) *[]string { return (*[]string)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // ExtMap returns the address of an extension map field in the struct. func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { return (*map[int32]Extension)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // NewAt returns the reflect.Value for a pointer to a field in the struct. func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value { return reflect.NewAt(typ, unsafe.Pointer(uintptr(p)+uintptr(f))) } // SetStructPointer writes a *struct field in the struct. func structPointer_SetStructPointer(p structPointer, f field, q structPointer) { *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) = q } // GetStructPointer reads a *struct field in the struct. func structPointer_GetStructPointer(p structPointer, f field) structPointer { return *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // StructPointerSlice the address of a []*struct field in the struct. func structPointer_StructPointerSlice(p structPointer, f field) *structPointerSlice { return (*structPointerSlice)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // A structPointerSlice represents a slice of pointers to structs (themselves submessages or groups). type structPointerSlice []structPointer func (v *structPointerSlice) Len() int { return len(*v) } func (v *structPointerSlice) Index(i int) structPointer { return (*v)[i] } func (v *structPointerSlice) Append(p structPointer) { *v = append(*v, p) } // A word32 is the address of a "pointer to 32-bit value" field. type word32 **uint32 // IsNil reports whether *v is nil. func word32_IsNil(p word32) bool { return *p == nil } // Set sets *v to point at a newly allocated word set to x. func word32_Set(p word32, o *Buffer, x uint32) { if len(o.uint32s) == 0 { o.uint32s = make([]uint32, uint32PoolSize) } o.uint32s[0] = x *p = &o.uint32s[0] o.uint32s = o.uint32s[1:] } // Get gets the value pointed at by *v. func word32_Get(p word32) uint32 { return **p } // Word32 returns the address of a *int32, *uint32, *float32, or *enum field in the struct. func structPointer_Word32(p structPointer, f field) word32 { return word32((**uint32)(unsafe.Pointer(uintptr(p) + uintptr(f)))) } // A word32Val is the address of a 32-bit value field. type word32Val *uint32 // Set sets *p to x. func word32Val_Set(p word32Val, x uint32) { *p = x } // Get gets the value pointed at by p. func word32Val_Get(p word32Val) uint32 { return *p } // Word32Val returns the address of a *int32, *uint32, *float32, or *enum field in the struct. func structPointer_Word32Val(p structPointer, f field) word32Val { return word32Val((*uint32)(unsafe.Pointer(uintptr(p) + uintptr(f)))) } // A word32Slice is a slice of 32-bit values. type word32Slice []uint32 func (v *word32Slice) Append(x uint32) { *v = append(*v, x) } func (v *word32Slice) Len() int { return len(*v) } func (v *word32Slice) Index(i int) uint32 { return (*v)[i] } // Word32Slice returns the address of a []int32, []uint32, []float32, or []enum field in the struct. func structPointer_Word32Slice(p structPointer, f field) *word32Slice { return (*word32Slice)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // word64 is like word32 but for 64-bit values. type word64 **uint64 func word64_Set(p word64, o *Buffer, x uint64) { if len(o.uint64s) == 0 { o.uint64s = make([]uint64, uint64PoolSize) } o.uint64s[0] = x *p = &o.uint64s[0] o.uint64s = o.uint64s[1:] } func word64_IsNil(p word64) bool { return *p == nil } func word64_Get(p word64) uint64 { return **p } func structPointer_Word64(p structPointer, f field) word64 { return word64((**uint64)(unsafe.Pointer(uintptr(p) + uintptr(f)))) } // word64Val is like word32Val but for 64-bit values. type word64Val *uint64 func word64Val_Set(p word64Val, o *Buffer, x uint64) { *p = x } func word64Val_Get(p word64Val) uint64 { return *p } func structPointer_Word64Val(p structPointer, f field) word64Val { return word64Val((*uint64)(unsafe.Pointer(uintptr(p) + uintptr(f)))) } // word64Slice is like word32Slice but for 64-bit values. type word64Slice []uint64 func (v *word64Slice) Append(x uint64) { *v = append(*v, x) } func (v *word64Slice) Len() int { return len(*v) } func (v *word64Slice) Index(i int) uint64 { return (*v)[i] } func structPointer_Word64Slice(p structPointer, f field) *word64Slice { return (*word64Slice)(unsafe.Pointer(uintptr(p) + uintptr(f))) }
vendor/github.com/gogo/protobuf/proto/pointer_unsafe.go
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.0005717574968002737, 0.00026546159642748535, 0.0001633806969039142, 0.00018452011863701046, 0.00013289396883919835 ]
{ "id": 0, "code_window": [ "func countAvailablePods(pods []api.Pod, minReadySeconds int32) int32 {\n", "\tavailablePodCount := int32(0)\n", "\tfor _, pod := range pods {\n", "\t\t// TODO: Make the time.Now() as argument to allow unit test this.\n", "\t\tif IsPodAvailable(&pod, minReadySeconds, time.Now()) {\n", "\t\t\tglog.V(4).Infof(\"Pod %s/%s is available.\", pod.Namespace, pod.Name)\n", "\t\t\tavailablePodCount++\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// FIXME: avoid using time.Now\n" ], "file_path": "pkg/controller/deployment/util/deployment_util.go", "type": "add", "edit_start_line_idx": 607 }
// 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 dbus import ( "errors" "time" "github.com/godbus/dbus" ) const ( cleanIgnoreInterval = int64(10 * time.Second) ignoreInterval = int64(30 * time.Millisecond) ) // Subscribe sets up this connection to subscribe to all systemd dbus events. // This is required before calling SubscribeUnits. When the connection closes // systemd will automatically stop sending signals so there is no need to // explicitly call Unsubscribe(). func (c *Conn) Subscribe() error { c.sigconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, "type='signal',interface='org.freedesktop.systemd1.Manager',member='UnitNew'") c.sigconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, "type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged'") err := c.sigobj.Call("org.freedesktop.systemd1.Manager.Subscribe", 0).Store() if err != nil { return err } return nil } // Unsubscribe this connection from systemd dbus events. func (c *Conn) Unsubscribe() error { err := c.sigobj.Call("org.freedesktop.systemd1.Manager.Unsubscribe", 0).Store() if err != nil { return err } return nil } func (c *Conn) dispatch() { ch := make(chan *dbus.Signal, signalBuffer) c.sigconn.Signal(ch) go func() { for { signal, ok := <-ch if !ok { return } if signal.Name == "org.freedesktop.systemd1.Manager.JobRemoved" { c.jobComplete(signal) } if c.subscriber.updateCh == nil { continue } var unitPath dbus.ObjectPath switch signal.Name { case "org.freedesktop.systemd1.Manager.JobRemoved": unitName := signal.Body[2].(string) c.sysobj.Call("org.freedesktop.systemd1.Manager.GetUnit", 0, unitName).Store(&unitPath) case "org.freedesktop.systemd1.Manager.UnitNew": unitPath = signal.Body[1].(dbus.ObjectPath) case "org.freedesktop.DBus.Properties.PropertiesChanged": if signal.Body[0].(string) == "org.freedesktop.systemd1.Unit" { unitPath = signal.Path } } if unitPath == dbus.ObjectPath("") { continue } c.sendSubStateUpdate(unitPath) } }() } // Returns two unbuffered channels which will receive all changed units every // interval. Deleted units are sent as nil. func (c *Conn) SubscribeUnits(interval time.Duration) (<-chan map[string]*UnitStatus, <-chan error) { return c.SubscribeUnitsCustom(interval, 0, func(u1, u2 *UnitStatus) bool { return *u1 != *u2 }, nil) } // SubscribeUnitsCustom is like SubscribeUnits but lets you specify the buffer // size of the channels, the comparison function for detecting changes and a filter // function for cutting down on the noise that your channel receives. func (c *Conn) SubscribeUnitsCustom(interval time.Duration, buffer int, isChanged func(*UnitStatus, *UnitStatus) bool, filterUnit func(string) bool) (<-chan map[string]*UnitStatus, <-chan error) { old := make(map[string]*UnitStatus) statusChan := make(chan map[string]*UnitStatus, buffer) errChan := make(chan error, buffer) go func() { for { timerChan := time.After(interval) units, err := c.ListUnits() if err == nil { cur := make(map[string]*UnitStatus) for i := range units { if filterUnit != nil && filterUnit(units[i].Name) { continue } cur[units[i].Name] = &units[i] } // add all new or changed units changed := make(map[string]*UnitStatus) for n, u := range cur { if oldU, ok := old[n]; !ok || isChanged(oldU, u) { changed[n] = u } delete(old, n) } // add all deleted units for oldN := range old { changed[oldN] = nil } old = cur if len(changed) != 0 { statusChan <- changed } } else { errChan <- err } <-timerChan } }() return statusChan, errChan } type SubStateUpdate struct { UnitName string SubState string } // SetSubStateSubscriber writes to updateCh when any unit's substate changes. // Although this writes to updateCh on every state change, the reported state // may be more recent than the change that generated it (due to an unavoidable // race in the systemd dbus interface). That is, this method provides a good // way to keep a current view of all units' states, but is not guaranteed to // show every state transition they go through. Furthermore, state changes // will only be written to the channel with non-blocking writes. If updateCh // is full, it attempts to write an error to errCh; if errCh is full, the error // passes silently. func (c *Conn) SetSubStateSubscriber(updateCh chan<- *SubStateUpdate, errCh chan<- error) { c.subscriber.Lock() defer c.subscriber.Unlock() c.subscriber.updateCh = updateCh c.subscriber.errCh = errCh } func (c *Conn) sendSubStateUpdate(path dbus.ObjectPath) { c.subscriber.Lock() defer c.subscriber.Unlock() if c.shouldIgnore(path) { return } info, err := c.GetUnitProperties(string(path)) if err != nil { select { case c.subscriber.errCh <- err: default: } } name := info["Id"].(string) substate := info["SubState"].(string) update := &SubStateUpdate{name, substate} select { case c.subscriber.updateCh <- update: default: select { case c.subscriber.errCh <- errors.New("update channel full!"): default: } } c.updateIgnore(path, info) } // The ignore functions work around a wart in the systemd dbus interface. // Requesting the properties of an unloaded unit will cause systemd to send a // pair of UnitNew/UnitRemoved signals. Because we need to get a unit's // properties on UnitNew (as that's the only indication of a new unit coming up // for the first time), we would enter an infinite loop if we did not attempt // to detect and ignore these spurious signals. The signal themselves are // indistinguishable from relevant ones, so we (somewhat hackishly) ignore an // unloaded unit's signals for a short time after requesting its properties. // This means that we will miss e.g. a transient unit being restarted // *immediately* upon failure and also a transient unit being started // immediately after requesting its status (with systemctl status, for example, // because this causes a UnitNew signal to be sent which then causes us to fetch // the properties). func (c *Conn) shouldIgnore(path dbus.ObjectPath) bool { t, ok := c.subscriber.ignore[path] return ok && t >= time.Now().UnixNano() } func (c *Conn) updateIgnore(path dbus.ObjectPath, info map[string]interface{}) { c.cleanIgnore() // unit is unloaded - it will trigger bad systemd dbus behavior if info["LoadState"].(string) == "not-found" { c.subscriber.ignore[path] = time.Now().UnixNano() + ignoreInterval } } // without this, ignore would grow unboundedly over time func (c *Conn) cleanIgnore() { now := time.Now().UnixNano() if c.subscriber.cleanIgnore < now { c.subscriber.cleanIgnore = now + cleanIgnoreInterval for p, t := range c.subscriber.ignore { if t < now { delete(c.subscriber.ignore, p) } } } }
vendor/github.com/coreos/go-systemd/dbus/subscription.go
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.0001781549071893096, 0.000169500257470645, 0.00016311438230331987, 0.0001689915225142613, 0.0000036230278510629432 ]
{ "id": 1, "code_window": [ "\t\ttestScalePausedDeployment(f)\n", "\t})\n", "\tIt(\"scaled rollout should not block on annotation check\", func() {\n", "\t\ttestScaledRolloutDeployment(f)\n", "\t})\n", "})\n", "\n", "func newRS(rsName string, replicas int32, rsPodLabels map[string]string, imageName string, image string) *extensions.ReplicaSet {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t// TODO: add tests that cover deployment.Spec.MinReadySeconds once we solved clock-skew issues\n" ], "file_path": "test/e2e/deployment.go", "type": "add", "edit_start_line_idx": 88 }
/* 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 e2e import ( "fmt" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/annotations" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apis/extensions" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" client "k8s.io/kubernetes/pkg/client/unversioned" adapter "k8s.io/kubernetes/pkg/client/unversioned/adapters/internalclientset" deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util" "k8s.io/kubernetes/pkg/kubectl" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/watch" "k8s.io/kubernetes/test/e2e/framework" ) const ( // nginxImage defined in kubectl.go nginxImageName = "nginx" redisImage = "gcr.io/google_containers/redis:e2e" redisImageName = "redis" ) var _ = framework.KubeDescribe("Deployment", func() { f := framework.NewDefaultFramework("deployment") It("deployment should create new pods", func() { testNewDeployment(f) }) It("RollingUpdateDeployment should delete old pods and create new ones", func() { testRollingUpdateDeployment(f) }) It("RollingUpdateDeployment should scale up and down in the right order", func() { testRollingUpdateDeploymentEvents(f) }) It("RecreateDeployment should delete old pods and create new ones", func() { testRecreateDeployment(f) }) It("deployment should delete old replica sets", func() { testDeploymentCleanUpPolicy(f) }) It("deployment should support rollover", func() { testRolloverDeployment(f) }) It("paused deployment should be ignored by the controller", func() { testPausedDeployment(f) }) It("deployment should support rollback", func() { testRollbackDeployment(f) }) It("deployment should support rollback when there's replica set with no revision", func() { testRollbackDeploymentRSNoRevision(f) }) It("deployment should label adopted RSs and pods", func() { testDeploymentLabelAdopted(f) }) It("paused deployment should be able to scale", func() { testScalePausedDeployment(f) }) It("scaled rollout should not block on annotation check", func() { testScaledRolloutDeployment(f) }) }) func newRS(rsName string, replicas int32, rsPodLabels map[string]string, imageName string, image string) *extensions.ReplicaSet { zero := int64(0) return &extensions.ReplicaSet{ ObjectMeta: api.ObjectMeta{ Name: rsName, }, Spec: extensions.ReplicaSetSpec{ Replicas: replicas, Selector: &unversioned.LabelSelector{MatchLabels: rsPodLabels}, Template: api.PodTemplateSpec{ ObjectMeta: api.ObjectMeta{ Labels: rsPodLabels, }, Spec: api.PodSpec{ TerminationGracePeriodSeconds: &zero, Containers: []api.Container{ { Name: imageName, Image: image, }, }, }, }, }, } } func newDeployment(deploymentName string, replicas int32, podLabels map[string]string, imageName string, image string, strategyType extensions.DeploymentStrategyType, revisionHistoryLimit *int32) *extensions.Deployment { zero := int64(0) return &extensions.Deployment{ ObjectMeta: api.ObjectMeta{ Name: deploymentName, }, Spec: extensions.DeploymentSpec{ Replicas: replicas, Selector: &unversioned.LabelSelector{MatchLabels: podLabels}, Strategy: extensions.DeploymentStrategy{ Type: strategyType, }, RevisionHistoryLimit: revisionHistoryLimit, Template: api.PodTemplateSpec{ ObjectMeta: api.ObjectMeta{ Labels: podLabels, }, Spec: api.PodSpec{ TerminationGracePeriodSeconds: &zero, Containers: []api.Container{ { Name: imageName, Image: image, }, }, }, }, }, } } func newDeploymentRollback(name string, annotations map[string]string, revision int64) *extensions.DeploymentRollback { return &extensions.DeploymentRollback{ Name: name, UpdatedAnnotations: annotations, RollbackTo: extensions.RollbackConfig{Revision: revision}, } } // checkDeploymentRevision checks if the input deployment's and its new replica set's revision and images are as expected. func checkDeploymentRevision(c *clientset.Clientset, ns, deploymentName, revision, imageName, image string) (*extensions.Deployment, *extensions.ReplicaSet) { deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) // Check revision of the new replica set of this deployment newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(newRS.Annotations).NotTo(Equal(nil)) Expect(newRS.Annotations[deploymentutil.RevisionAnnotation]).Should(Equal(revision)) // Check revision of This deployment Expect(deployment.Annotations).NotTo(Equal(nil)) Expect(deployment.Annotations[deploymentutil.RevisionAnnotation]).Should(Equal(revision)) if len(imageName) > 0 { // Check the image the new replica set creates Expect(newRS.Spec.Template.Spec.Containers[0].Name).Should(Equal(imageName)) Expect(newRS.Spec.Template.Spec.Containers[0].Image).Should(Equal(image)) // Check the image the deployment creates Expect(deployment.Spec.Template.Spec.Containers[0].Name).Should(Equal(imageName)) Expect(deployment.Spec.Template.Spec.Containers[0].Image).Should(Equal(image)) } return deployment, newRS } func stopDeployment(c *clientset.Clientset, oldC client.Interface, ns, deploymentName string) { deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) framework.Logf("Deleting deployment %s", deploymentName) reaper, err := kubectl.ReaperFor(extensions.Kind("Deployment"), oldC) Expect(err).NotTo(HaveOccurred()) timeout := 1 * time.Minute err = reaper.Stop(ns, deployment.Name, timeout, api.NewDeleteOptions(0)) Expect(err).NotTo(HaveOccurred()) framework.Logf("Ensuring deployment %s was deleted", deploymentName) _, err = c.Extensions().Deployments(ns).Get(deployment.Name) Expect(err).To(HaveOccurred()) Expect(errors.IsNotFound(err)).To(BeTrue()) framework.Logf("Ensuring deployment %s's RSes were deleted", deploymentName) selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) Expect(err).NotTo(HaveOccurred()) options := api.ListOptions{LabelSelector: selector} rss, err := c.Extensions().ReplicaSets(ns).List(options) Expect(err).NotTo(HaveOccurred()) Expect(rss.Items).Should(HaveLen(0)) framework.Logf("Ensuring deployment %s's Pods were deleted", deploymentName) var pods *api.PodList if err := wait.PollImmediate(time.Second, timeout, func() (bool, error) { pods, err = c.Core().Pods(ns).List(api.ListOptions{}) if err != nil { return false, err } if len(pods.Items) == 0 { return true, nil } return false, nil }); err != nil { framework.Failf("Err : %s\n. Failed to remove deployment %s pods : %+v", err, deploymentName, pods) } } func testNewDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. c := adapter.FromUnversionedClient(f.Client) deploymentName := "test-new-deployment" podLabels := map[string]string{"name": nginxImageName} replicas := int32(1) framework.Logf("Creating simple deployment %s", deploymentName) d := newDeployment(deploymentName, replicas, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) d.Annotations = map[string]string{"test": "should-copy-to-replica-set", annotations.LastAppliedConfigAnnotation: "should-not-copy-to-replica-set"} deploy, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", nginxImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) // Check new RS annotations Expect(newRS.Annotations["test"]).Should(Equal("should-copy-to-replica-set")) Expect(newRS.Annotations[annotations.LastAppliedConfigAnnotation]).Should(Equal("")) Expect(deployment.Annotations["test"]).Should(Equal("should-copy-to-replica-set")) Expect(deployment.Annotations[annotations.LastAppliedConfigAnnotation]).Should(Equal("should-not-copy-to-replica-set")) } func testRollingUpdateDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "sample-pod"} rsPodLabels := map[string]string{ "name": "sample-pod", "pod": nginxImageName, } rsName := "test-rolling-update-controller" replicas := int32(3) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "sample-pod", false, 3) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-rolling-update-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RollingUpdateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", redisImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // There should be 1 old RS (nginx-controller, which is adopted) deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) _, allOldRSs, err := deploymentutil.GetOldReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(len(allOldRSs)).Should(Equal(1)) // The old RS should contain pod-template-hash in its selector, label, and template label Expect(len(allOldRSs[0].Labels[extensions.DefaultDeploymentUniqueLabelKey])).Should(BeNumerically(">", 0)) Expect(len(allOldRSs[0].Spec.Selector.MatchLabels[extensions.DefaultDeploymentUniqueLabelKey])).Should(BeNumerically(">", 0)) Expect(len(allOldRSs[0].Spec.Template.Labels[extensions.DefaultDeploymentUniqueLabelKey])).Should(BeNumerically(">", 0)) } func testRollingUpdateDeploymentEvents(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "sample-pod-2"} rsPodLabels := map[string]string{ "name": "sample-pod-2", "pod": nginxImageName, } rsName := "test-rolling-scale-controller" replicas := int32(1) rsRevision := "3546343826724305832" annotations := make(map[string]string) annotations[deploymentutil.RevisionAnnotation] = rsRevision rs := newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage) rs.Annotations = annotations _, err := c.Extensions().ReplicaSets(ns).Create(rs) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "sample-pod-2", false, 1) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-rolling-scale-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RollingUpdateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 3546343826724305833 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "3546343826724305833", redisImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Verify that the pods were scaled up and down as expected. We use events to verify that. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) framework.WaitForEvents(unversionedClient, ns, deployment, 2) events, err := c.Core().Events(ns).Search(deployment) if err != nil { framework.Logf("error in listing events: %s", err) Expect(err).NotTo(HaveOccurred()) } // There should be 2 events, one to scale up the new ReplicaSet and then to scale down // the old ReplicaSet. Expect(len(events.Items)).Should(Equal(2)) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(newRS).NotTo(Equal(nil)) Expect(events.Items[0].Message).Should(Equal(fmt.Sprintf("Scaled up replica set %s to 1", newRS.Name))) Expect(events.Items[1].Message).Should(Equal(fmt.Sprintf("Scaled down replica set %s to 0", rsName))) } func testRecreateDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "sample-pod-3"} rsPodLabels := map[string]string{ "name": "sample-pod-3", "pod": nginxImageName, } rsName := "test-recreate-controller" replicas := int32(3) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "sample-pod-3", false, 3) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-recreate-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RecreateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", redisImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Verify that the pods were scaled up and down as expected. We use events to verify that. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) framework.WaitForEvents(unversionedClient, ns, deployment, 2) events, err := c.Core().Events(ns).Search(deployment) if err != nil { framework.Logf("error in listing events: %s", err) Expect(err).NotTo(HaveOccurred()) } // There should be 2 events, one to scale up the new ReplicaSet and then to scale down the old ReplicaSet. Expect(len(events.Items)).Should(Equal(2)) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(newRS).NotTo(Equal(nil)) Expect(events.Items[0].Message).Should(Equal(fmt.Sprintf("Scaled down replica set %s to 0", rsName))) Expect(events.Items[1].Message).Should(Equal(fmt.Sprintf("Scaled up replica set %s to 3", newRS.Name))) } // testDeploymentCleanUpPolicy tests that deployment supports cleanup policy func testDeploymentCleanUpPolicy(f *framework.Framework) { ns := f.Namespace.Name unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "cleanup-pod"} rsPodLabels := map[string]string{ "name": "cleanup-pod", "pod": nginxImageName, } rsName := "test-cleanup-controller" replicas := int32(1) revisionHistoryLimit := util.Int32Ptr(0) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "cleanup-pod", false, 1) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-cleanup-deployment" framework.Logf("Creating deployment %s", deploymentName) pods, err := c.Pods(ns).List(api.ListOptions{LabelSelector: labels.Everything()}) if err != nil { Expect(err).NotTo(HaveOccurred(), "Failed to query for pods: %v", err) } options := api.ListOptions{ ResourceVersion: pods.ListMeta.ResourceVersion, } stopCh := make(chan struct{}) w, err := c.Pods(ns).Watch(options) go func() { // There should be only one pod being created, which is the pod with the redis image. // The old RS shouldn't create new pod when deployment controller adding pod template hash label to its selector. numPodCreation := 1 for { select { case event, _ := <-w.ResultChan(): if event.Type != watch.Added { continue } numPodCreation-- if numPodCreation < 0 { framework.Failf("Expect only one pod creation, the second creation event: %#v\n", event) } pod, ok := event.Object.(*api.Pod) if !ok { Fail("Expect event Object to be a pod") } if pod.Spec.Containers[0].Name != redisImageName { framework.Failf("Expect the created pod to have container name %s, got pod %#v\n", redisImageName, pod) } case <-stopCh: return } } }() _, err = c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RollingUpdateDeploymentStrategyType, revisionHistoryLimit)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) err = framework.WaitForDeploymentOldRSsNum(c, ns, deploymentName, int(*revisionHistoryLimit)) Expect(err).NotTo(HaveOccurred()) close(stopCh) } // testRolloverDeployment tests that deployment supports rollover. // i.e. we can change desired state and kick off rolling update, then change desired state again before it finishes. func testRolloverDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) podName := "rollover-pod" deploymentPodLabels := map[string]string{"name": podName} rsPodLabels := map[string]string{ "name": podName, "pod": nginxImageName, } rsName := "test-rollover-controller" rsReplicas := int32(4) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, rsReplicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, podName, false, rsReplicas) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Wait for the required pods to be ready for at least minReadySeconds (be available) deploymentMinReadySeconds := int32(5) err = framework.WaitForPodsReady(c, ns, podName, int(deploymentMinReadySeconds)) Expect(err).NotTo(HaveOccurred()) // Create a deployment to delete nginx pods and instead bring up redis-slave pods. deploymentName, deploymentImageName := "test-rollover-deployment", "redis-slave" deploymentReplicas := int32(4) deploymentImage := "gcr.io/google_samples/gb-redisslave:v1" deploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType framework.Logf("Creating deployment %s", deploymentName) newDeployment := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil) newDeployment.Spec.MinReadySeconds = deploymentMinReadySeconds newDeployment.Spec.Strategy.RollingUpdate = &extensions.RollingUpdateDeployment{ MaxUnavailable: intstr.FromInt(1), MaxSurge: intstr.FromInt(1), } _, err = c.Extensions().Deployments(ns).Create(newDeployment) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Verify that the pods were scaled up and down as expected. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) // Make sure the deployment starts to scale up and down replica sets by checking if its updated replicas >= 1 err = framework.WaitForDeploymentUpdatedReplicasLTE(c, ns, deploymentName, 1, deployment.Generation) // Check if it's updated to revision 1 correctly _, newRS := checkDeploymentRevision(c, ns, deploymentName, "1", deploymentImageName, deploymentImage) // Before the deployment finishes, update the deployment to rollover the above 2 ReplicaSets and bring up redis pods. // If the deployment already finished here, the test would fail. When this happens, increase its minReadySeconds or replicas to prevent it. Expect(newRS.Spec.Replicas).Should(BeNumerically("<", deploymentReplicas)) updatedDeploymentImageName, updatedDeploymentImage := redisImageName, redisImage deployment, err = framework.UpdateDeploymentWithRetries(c, ns, newDeployment.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName update.Spec.Template.Spec.Containers[0].Image = updatedDeploymentImage }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pod template update. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 2 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "2", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) } func testPausedDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) deploymentName := "test-paused-deployment" podLabels := map[string]string{"name": nginxImageName} d := newDeployment(deploymentName, 1, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) d.Spec.Paused = true tgps := int64(20) d.Spec.Template.Spec.TerminationGracePeriodSeconds = &tgps framework.Logf("Creating paused deployment %s", deploymentName) _, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Check that deployment is created fine. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) // Verify that there is no latest state realized for the new deployment. rs, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) if rs != nil { err = fmt.Errorf("unexpected new rs/%s for deployment/%s", rs.Name, deployment.Name) Expect(err).NotTo(HaveOccurred()) } // Update the deployment to run deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Paused = false }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the resume. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) if err != nil { Expect(err).NotTo(HaveOccurred()) } opts := api.ListOptions{LabelSelector: selector} w, err := c.Extensions().ReplicaSets(ns).Watch(opts) Expect(err).NotTo(HaveOccurred()) select { case <-w.ResultChan(): // this is it case <-time.After(time.Minute): err = fmt.Errorf("expected a new replica set to be created") Expect(err).NotTo(HaveOccurred()) } // Pause the deployment and delete the replica set. // The paused deployment shouldn't recreate a new one. deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Paused = true }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pause. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Update the deployment template - the new replicaset should stay the same framework.Logf("Updating paused deployment %q", deploymentName) newTGPS := int64(40) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.TerminationGracePeriodSeconds = &newTGPS }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) framework.Logf("Looking for new replicaset for paused deployment %q (there should be none)", deploymentName) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) if newRS != nil { err = fmt.Errorf("No replica set should match the deployment template but there is %q", newRS.Name) Expect(err).NotTo(HaveOccurred()) } _, allOldRs, err := deploymentutil.GetOldReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) if len(allOldRs) != 1 { err = fmt.Errorf("expected an old replica set") Expect(err).NotTo(HaveOccurred()) } framework.Logf("Comparing deployment diff with old replica set %q", allOldRs[0].Name) if *allOldRs[0].Spec.Template.Spec.TerminationGracePeriodSeconds == newTGPS { err = fmt.Errorf("TerminationGracePeriodSeconds on the replica set should be %d but is %d", tgps, newTGPS) Expect(err).NotTo(HaveOccurred()) } } // testRollbackDeployment tests that a deployment is created (revision 1) and updated (revision 2), and // then rollback to revision 1 (should update template to revision 1, and then update revision 1 to 3), // and then rollback to last revision. func testRollbackDeployment(f *framework.Framework) { ns := f.Namespace.Name unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) podName := "nginx" deploymentPodLabels := map[string]string{"name": podName} // 1. Create a deployment to create nginx pods. deploymentName, deploymentImageName := "test-rollback-deployment", nginxImageName deploymentReplicas := int32(1) deploymentImage := nginxImage deploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType framework.Logf("Creating deployment %s", deploymentName) d := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil) createAnnotation := map[string]string{"action": "create", "author": "minion"} d.Annotations = createAnnotation deploy, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "create" err = framework.CheckNewRSAnnotations(c, ns, deploymentName, createAnnotation) Expect(err).NotTo(HaveOccurred()) // 2. Update the deployment to create redis pods. updatedDeploymentImage := redisImage updatedDeploymentImageName := redisImageName updateAnnotation := map[string]string{"action": "update", "log": "I need to update it"} deployment, err := framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName update.Spec.Template.Spec.Containers[0].Image = updatedDeploymentImage update.Annotations = updateAnnotation }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pod template update. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 2 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "2", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "update" err = framework.CheckNewRSAnnotations(c, ns, deploymentName, updateAnnotation) Expect(err).NotTo(HaveOccurred()) // 3. Update the deploymentRollback to rollback to revision 1 revision := int64(1) framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback := newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackDone in deployment status and check it here // Wait for it to be updated to revision 3 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "3", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "create", after the rollback err = framework.CheckNewRSAnnotations(c, ns, deploymentName, createAnnotation) Expect(err).NotTo(HaveOccurred()) // 4. Update the deploymentRollback to rollback to last revision revision = 0 framework.Logf("rolling back deployment %s to last revision", deploymentName) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 4 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "4", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "update", after the rollback err = framework.CheckNewRSAnnotations(c, ns, deploymentName, updateAnnotation) Expect(err).NotTo(HaveOccurred()) } // testRollbackDeploymentRSNoRevision tests that deployment supports rollback even when there's old replica set without revision. // An old replica set without revision is created, and then a deployment is created (v1). The deployment shouldn't add revision // annotation to the old replica set. Then rollback the deployment to last revision, and it should fail. // Then update the deployment to v2 and rollback it to v1 should succeed, now the deployment // becomes v3. Then rollback the deployment to v10 (doesn't exist in history) should fail. // Finally, rollback the deployment (v3) to v3 should be no-op. // TODO: When we finished reporting rollback status in deployment status, check the rollback status here in each case. func testRollbackDeploymentRSNoRevision(f *framework.Framework) { ns := f.Namespace.Name c := adapter.FromUnversionedClient(f.Client) podName := "nginx" deploymentPodLabels := map[string]string{"name": podName} rsPodLabels := map[string]string{ "name": podName, "pod": nginxImageName, } // Create an old RS without revision rsName := "test-rollback-no-revision-controller" rsReplicas := int32(0) rs := newRS(rsName, rsReplicas, rsPodLabels, nginxImageName, nginxImage) rs.Annotations = make(map[string]string) rs.Annotations["make"] = "difference" _, err := c.Extensions().ReplicaSets(ns).Create(rs) Expect(err).NotTo(HaveOccurred()) // 1. Create a deployment to create nginx pods, which have different template than the replica set created above. deploymentName, deploymentImageName := "test-rollback-no-revision-deployment", nginxImageName deploymentReplicas := int32(1) deploymentImage := nginxImage deploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType framework.Logf("Creating deployment %s", deploymentName) d := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil) deploy, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Check that the replica set we created still doesn't contain revision information rs, err = c.Extensions().ReplicaSets(ns).Get(rsName) Expect(err).NotTo(HaveOccurred()) Expect(rs.Annotations[deploymentutil.RevisionAnnotation]).Should(Equal("")) // 2. Update the deploymentRollback to rollback to last revision // Since there's only 1 revision in history, it should stay as revision 1 revision := int64(0) framework.Logf("rolling back deployment %s to last revision", deploymentName) rollback := newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackRevisionNotFound in deployment status and check it here // The pod template shouldn't change since there's no last revision // Check if the deployment is still revision 1 and still has the old pod template checkDeploymentRevision(c, ns, deploymentName, "1", deploymentImageName, deploymentImage) // 3. Update the deployment to create redis pods. updatedDeploymentImage := redisImage updatedDeploymentImageName := redisImageName deployment, err := framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName update.Spec.Template.Spec.Containers[0].Image = updatedDeploymentImage }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pod template update. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 2 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "2", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // 4. Update the deploymentRollback to rollback to revision 1 revision = 1 framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackDone in deployment status and check it here // The pod template should be updated to the one in revision 1 // Wait for it to be updated to revision 3 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "3", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // 5. Update the deploymentRollback to rollback to revision 10 // Since there's no revision 10 in history, it should stay as revision 3 revision = 10 framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackRevisionNotFound in deployment status and check it here // The pod template shouldn't change since there's no revision 10 // Check if it's still revision 3 and still has the old pod template checkDeploymentRevision(c, ns, deploymentName, "3", deploymentImageName, deploymentImage) // 6. Update the deploymentRollback to rollback to revision 3 // Since it's already revision 3, it should be no-op revision = 3 framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackTemplateUnchanged in deployment status and check it here // The pod template shouldn't change since it's already revision 3 // Check if it's still revision 3 and still has the old pod template checkDeploymentRevision(c, ns, deploymentName, "3", deploymentImageName, deploymentImage) } func testDeploymentLabelAdopted(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. podName := "nginx" podLabels := map[string]string{"name": podName} rsName := "test-adopted-controller" replicas := int32(3) image := nginxImage _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, podLabels, podName, image)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, podName, false, 3) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a nginx deployment to adopt the old rs. deploymentName := "test-adopted-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, podLabels, podName, image, extensions.RollingUpdateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", image) Expect(err).NotTo(HaveOccurred()) // The RS and pods should be relabeled before the status is updated by syncRollingUpdateDeployment err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // There should be no old RSs (overlapping RS) deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) oldRSs, allOldRSs, newRS, err := deploymentutil.GetAllReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(len(oldRSs)).Should(Equal(0)) Expect(len(allOldRSs)).Should(Equal(0)) // New RS should contain pod-template-hash in its selector, label, and template label err = framework.CheckRSHashLabel(newRS) Expect(err).NotTo(HaveOccurred()) // All pods targeted by the deployment should contain pod-template-hash in their labels, and there should be only 3 pods selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) Expect(err).NotTo(HaveOccurred()) options := api.ListOptions{LabelSelector: selector} pods, err := c.Core().Pods(ns).List(options) Expect(err).NotTo(HaveOccurred()) err = framework.CheckPodHashLabel(pods) Expect(err).NotTo(HaveOccurred()) Expect(int32(len(pods.Items))).Should(Equal(replicas)) } func testScalePausedDeployment(f *framework.Framework) { ns := f.Namespace.Name c := adapter.FromUnversionedClient(f.Client) podLabels := map[string]string{"name": nginxImageName} replicas := int32(3) // Create a nginx deployment. deploymentName := "nginx-deployment" d := newDeployment(deploymentName, replicas, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) framework.Logf("Creating deployment %q", deploymentName) _, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Check that deployment is created fine. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) rs, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) // Pause the deployment and try to scale it. deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Paused = true }) Expect(err).NotTo(HaveOccurred()) // Scale the paused deployment. framework.Logf("Scaling up the paused deployment %q", deploymentName) newReplicas := int32(5) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { update.Spec.Replicas = newReplicas }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) rs, err = deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) if rs.Spec.Replicas != newReplicas { err = fmt.Errorf("Expected %d replicas for the new replica set, got %d", newReplicas, rs.Spec.Replicas) Expect(err).NotTo(HaveOccurred()) } } func testScaledRolloutDeployment(f *framework.Framework) { ns := f.Namespace.Name c := adapter.FromUnversionedClient(f.Client) podLabels := map[string]string{"name": nginxImageName} replicas := int32(10) // Create a nginx deployment. deploymentName := "nginx" d := newDeployment(deploymentName, replicas, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) d.Spec.Strategy.RollingUpdate = new(extensions.RollingUpdateDeployment) d.Spec.Strategy.RollingUpdate.MaxSurge = intstr.FromInt(3) d.Spec.Strategy.RollingUpdate.MaxUnavailable = intstr.FromInt(2) By(fmt.Sprintf("Creating deployment %q", deploymentName)) _, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Check that deployment is created fine. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for observed generation %d", deployment.Generation)) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) deployment, err = c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) first, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) // Update the deployment with a non-existent image so that the new replica set will be blocked. By(fmt.Sprintf("Updating deployment %q with a non-existent image", deploymentName)) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Image = "nginx:404" }) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for observed generation %d", deployment.Generation)) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) deployment, err = c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, false) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Checking that the replica sets for %q are synced", deploymentName)) second, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) first, err = c.Extensions().ReplicaSets(first.Namespace).Get(first.Name) Expect(err).NotTo(HaveOccurred()) firstCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), first) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, firstCond) secondCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), second) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, secondCond) By(fmt.Sprintf("Updating the size (up) and template at the same time for deployment %q", deploymentName)) newReplicas := int32(20) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { update.Spec.Replicas = newReplicas update.Spec.Template.Spec.Containers[0].Image = nautilusImage }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) oldRSs, _, rs, err := deploymentutil.GetAllReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) for _, rs := range append(oldRSs, rs) { By(fmt.Sprintf("Ensuring replica set %q has the correct desiredReplicas annotation", rs.Name)) desired, ok := deploymentutil.GetDesiredReplicasAnnotation(rs) if !ok || desired == deployment.Spec.Replicas { continue } err = fmt.Errorf("unexpected desiredReplicas annotation %d for replica set %q", desired, rs.Name) Expect(err).NotTo(HaveOccurred()) } By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Update the deployment with a non-existent image so that the new replica set will be blocked. By(fmt.Sprintf("Updating deployment %q with a non-existent image", deploymentName)) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Image = "nginx:404" }) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for observed generation %d", deployment.Generation)) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) deployment, err = c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, false) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Checking that the replica sets for %q are synced", deploymentName)) oldRs, err := c.Extensions().ReplicaSets(rs.Namespace).Get(rs.Name) Expect(err).NotTo(HaveOccurred()) newRs, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) oldCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), oldRs) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, oldCond) newCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), newRs) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, newCond) By(fmt.Sprintf("Updating the size (down) and template at the same time for deployment %q", deploymentName)) newReplicas = int32(5) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { update.Spec.Replicas = newReplicas update.Spec.Template.Spec.Containers[0].Image = kittenImage }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) oldRSs, _, rs, err = deploymentutil.GetAllReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) for _, rs := range append(oldRSs, rs) { By(fmt.Sprintf("Ensuring replica set %q has the correct desiredReplicas annotation", rs.Name)) desired, ok := deploymentutil.GetDesiredReplicasAnnotation(rs) if !ok || desired == deployment.Spec.Replicas { continue } err = fmt.Errorf("unexpected desiredReplicas annotation %d for replica set %q", desired, rs.Name) Expect(err).NotTo(HaveOccurred()) } By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) }
test/e2e/deployment.go
1
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.9991852641105652, 0.18888628482818604, 0.00016474639414809644, 0.0010562229435890913, 0.38273799419403076 ]
{ "id": 1, "code_window": [ "\t\ttestScalePausedDeployment(f)\n", "\t})\n", "\tIt(\"scaled rollout should not block on annotation check\", func() {\n", "\t\ttestScaledRolloutDeployment(f)\n", "\t})\n", "})\n", "\n", "func newRS(rsName string, replicas int32, rsPodLabels map[string]string, imageName string, image string) *extensions.ReplicaSet {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t// TODO: add tests that cover deployment.Spec.MinReadySeconds once we solved clock-skew issues\n" ], "file_path": "test/e2e/deployment.go", "type": "add", "edit_start_line_idx": 88 }
language: go go: - 1.4 - 1.5 - 1.6 - tip install: - go get -v -t ./... - go get golang.org/x/tools/cmd/cover - go get github.com/onsi/gomega - go install github.com/onsi/ginkgo/ginkgo - export PATH=$PATH:$HOME/gopath/bin script: $HOME/gopath/bin/ginkgo -r --randomizeAllSpecs --randomizeSuites --race --trace
vendor/github.com/onsi/ginkgo/.travis.yml
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.00017933633353095502, 0.0001774434931576252, 0.00017555063823238015, 0.0001774434931576252, 0.0000018928476492874324 ]
{ "id": 1, "code_window": [ "\t\ttestScalePausedDeployment(f)\n", "\t})\n", "\tIt(\"scaled rollout should not block on annotation check\", func() {\n", "\t\ttestScaledRolloutDeployment(f)\n", "\t})\n", "})\n", "\n", "func newRS(rsName string, replicas int32, rsPodLabels map[string]string, imageName string, image string) *extensions.ReplicaSet {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t// TODO: add tests that cover deployment.Spec.MinReadySeconds once we solved clock-skew issues\n" ], "file_path": "test/e2e/deployment.go", "type": "add", "edit_start_line_idx": 88 }
/* 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 deployment import ( "fmt" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/rest" "k8s.io/kubernetes/pkg/apis/extensions" ) // Registry is an interface for things that know how to store Deployments. type Registry interface { ListDeployments(ctx api.Context, options *api.ListOptions) (*extensions.DeploymentList, error) GetDeployment(ctx api.Context, deploymentID string) (*extensions.Deployment, error) CreateDeployment(ctx api.Context, deployment *extensions.Deployment) (*extensions.Deployment, error) UpdateDeployment(ctx api.Context, deployment *extensions.Deployment) (*extensions.Deployment, error) DeleteDeployment(ctx api.Context, deploymentID string) error } // storage puts strong typing around storage calls type storage struct { rest.StandardStorage } // NewRegistry returns a new Registry interface for the given Storage. Any mismatched types will panic. func NewRegistry(s rest.StandardStorage) Registry { return &storage{s} } func (s *storage) ListDeployments(ctx api.Context, options *api.ListOptions) (*extensions.DeploymentList, error) { if options != nil && options.FieldSelector != nil && !options.FieldSelector.Empty() { return nil, fmt.Errorf("field selector not supported yet") } obj, err := s.List(ctx, options) if err != nil { return nil, err } return obj.(*extensions.DeploymentList), err } func (s *storage) GetDeployment(ctx api.Context, deploymentID string) (*extensions.Deployment, error) { obj, err := s.Get(ctx, deploymentID) if err != nil { return nil, err } return obj.(*extensions.Deployment), nil } func (s *storage) CreateDeployment(ctx api.Context, deployment *extensions.Deployment) (*extensions.Deployment, error) { obj, err := s.Create(ctx, deployment) if err != nil { return nil, err } return obj.(*extensions.Deployment), nil } func (s *storage) UpdateDeployment(ctx api.Context, deployment *extensions.Deployment) (*extensions.Deployment, error) { obj, _, err := s.Update(ctx, deployment.Name, rest.DefaultUpdatedObjectInfo(deployment, api.Scheme)) if err != nil { return nil, err } return obj.(*extensions.Deployment), nil } func (s *storage) DeleteDeployment(ctx api.Context, deploymentID string) error { _, err := s.Delete(ctx, deploymentID, nil) return err }
pkg/registry/deployment/registry.go
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.0004521656082943082, 0.00024264937383122742, 0.0001659475965425372, 0.0002037929225480184, 0.00009272352326661348 ]
{ "id": 1, "code_window": [ "\t\ttestScalePausedDeployment(f)\n", "\t})\n", "\tIt(\"scaled rollout should not block on annotation check\", func() {\n", "\t\ttestScaledRolloutDeployment(f)\n", "\t})\n", "})\n", "\n", "func newRS(rsName string, replicas int32, rsPodLabels map[string]string, imageName string, image string) *extensions.ReplicaSet {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t// TODO: add tests that cover deployment.Spec.MinReadySeconds once we solved clock-skew issues\n" ], "file_path": "test/e2e/deployment.go", "type": "add", "edit_start_line_idx": 88 }
<!-- BEGIN MUNGE: UNVERSIONED_WARNING --> <!-- BEGIN STRIP_FOR_RELEASE --> <img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/kubernetes/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.3/docs/devel/kubemark-guide.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 --> # Kubemark User Guide ## Introduction Kubemark is a performance testing tool which allows users to run experiments on simulated clusters. The primary use case is scalability testing, as simulated clusters can be much bigger than the real ones. The objective is to expose problems with the master components (API server, controller manager or scheduler) that appear only on bigger clusters (e.g. small memory leaks). This document serves as a primer to understand what Kubemark is, what it is not, and how to use it. ## Architecture On a very high level Kubemark cluster consists of two parts: real master components and a set of “Hollow” Nodes. The prefix “Hollow” means an implementation/instantiation of a component with all “moving” parts mocked out. The best example is HollowKubelet, which pretends to be an ordinary Kubelet, but does not start anything, nor mount any volumes - it just lies it does. More detailed design and implementation details are at the end of this document. Currently master components run on a dedicated machine(s), and HollowNodes run on an ‘external’ Kubernetes cluster. This design has a slight advantage, over running master components on external cluster, of completely isolating master resources from everything else. ## Requirements To run Kubemark you need a Kubernetes cluster for running all your HollowNodes and a dedicated machine for a master. Master machine has to be directly routable from HollowNodes. You also need an access to some Docker repository. Currently scripts are written to be easily usable by GCE, but it should be relatively straightforward to port them to different providers or bare metal. ## Common use cases and helper scripts Common workflow for Kubemark is: - starting a Kubemark cluster (on GCE) - running e2e tests on Kubemark cluster - monitoring test execution and debugging problems - turning down Kubemark cluster Included in descriptions there will be comments helpful for anyone who’ll want to port Kubemark to different providers. ### Starting a Kubemark cluster To start a Kubemark cluster on GCE you need to create an external cluster (it can be GCE, GKE or any other cluster) by yourself, build a kubernetes release (e.g. by running `make quick-release`) and run `test/kubemark/start-kubemark.sh` script. This script will create a VM for master components, Pods for HollowNodes and do all the setup necessary to let them talk to each other. It will use the configuration stored in `cluster/kubemark/config-default.sh` - you can tweak it however you want, but note that some features may not be implemented yet, as implementation of Hollow components/mocks will probably be lagging behind ‘real’ one. For performance tests interesting variables are `NUM_NODES` and `MASTER_SIZE`. After start-kubemark script is finished you’ll have a ready Kubemark cluster, a kubeconfig file for talking to the Kubemark cluster is stored in `test/kubemark/kubeconfig.loc`. Currently we're running HollowNode with limit of 0.05 a CPU core and ~60MB or memory, which taking into account default cluster addons and fluentD running on an 'external' cluster, allows running ~17.5 HollowNodes per core. #### Behind the scene details: Start-kubemark script does quite a lot of things: - Creates a master machine called hollow-cluster-master and PD for it (*uses gcloud, should be easy to do outside of GCE*) - Creates a firewall rule which opens port 443\* on the master machine (*uses gcloud, should be easy to do outside of GCE*) - Builds a Docker image for HollowNode from the current repository and pushes it to the Docker repository (*GCR for us, using scripts from `cluster/gce/util.sh` - it may get tricky outside of GCE*) - Generates certificates and kubeconfig files, writes a kubeconfig locally to `test/kubemark/kubeconfig.loc` and creates a Secret which stores kubeconfig for HollowKubelet/HollowProxy use (*used gcloud to transfer files to Master, should be easy to do outside of GCE*). - Creates a ReplicationController for HollowNodes and starts them up. (*will work exactly the same everywhere as long as MASTER_IP will be populated correctly, but you’ll need to update docker image address if you’re not using GCR and default image name*) - Waits until all HollowNodes are in the Running phase (*will work exactly the same everywhere*) <sub>\* Port 443 is a secured port on the master machine which is used for all external communication with the API server. In the last sentence *external* means all traffic coming from other machines, including all the Nodes, not only from outside of the cluster. Currently local components, i.e. ControllerManager and Scheduler talk with API server using insecure port 8080.</sub> ### Running e2e tests on Kubemark cluster To run standard e2e test on your Kubemark cluster created in the previous step you execute `test/kubemark/run-e2e-tests.sh` script. It will configure ginkgo to use Kubemark cluster instead of something else and start an e2e test. This script should not need any changes to work on other cloud providers. By default (if nothing will be passed to it) the script will run a Density '30 test. If you want to run a different e2e test you just need to provide flags you want to be passed to `hack/ginkgo-e2e.sh` script, e.g. `--ginkgo.focus="Load"` to run the Load test. By default, at the end of each test, it will delete namespaces and everything under it (e.g. events, replication controllers) on Kubemark master, which takes a lot of time. Such work aren't needed in most cases: if you delete your Kubemark cluster after running `run-e2e-tests.sh`; you don't care about namespace deletion performance, specifically related to etcd; etc. There is a flag that enables you to avoid namespace deletion: `--delete-namespace=false`. Adding the flag should let you see in logs: `Found DeleteNamespace=false, skipping namespace deletion!` ### Monitoring test execution and debugging problems Run-e2e-tests prints the same output on Kubemark as on ordinary e2e cluster, but if you need to dig deeper you need to learn how to debug HollowNodes and how Master machine (currently) differs from the ordinary one. If you need to debug master machine you can do similar things as you do on your ordinary master. The difference between Kubemark setup and ordinary setup is that in Kubemark etcd is run as a plain docker container, and all master components are run as normal processes. There’s no Kubelet overseeing them. Logs are stored in exactly the same place, i.e. `/var/logs/` directory. Because binaries are not supervised by anything they won't be restarted in the case of a crash. To help you with debugging from inside the cluster startup script puts a `~/configure-kubectl.sh` script on the master. It downloads `gcloud` and `kubectl` tool and configures kubectl to work on unsecured master port (useful if there are problems with security). After the script is run you can use kubectl command from the master machine to play with the cluster. Debugging HollowNodes is a bit more tricky, as if you experience a problem on one of them you need to learn which hollow-node pod corresponds to a given HollowNode known by the Master. During self-registeration HollowNodes provide their cluster IPs as Names, which means that if you need to find a HollowNode named `10.2.4.5` you just need to find a Pod in external cluster with this cluster IP. There’s a helper script `test/kubemark/get-real-pod-for-hollow-node.sh` that does this for you. When you have a Pod name you can use `kubectl logs` on external cluster to get logs, or use a `kubectl describe pod` call to find an external Node on which this particular HollowNode is running so you can ssh to it. E.g. you want to see the logs of HollowKubelet on which pod `my-pod` is running. To do so you can execute: ``` $ kubectl kubernetes/test/kubemark/kubeconfig.loc describe pod my-pod ``` Which outputs pod description and among it a line: ``` Node: 1.2.3.4/1.2.3.4 ``` To learn the `hollow-node` pod corresponding to node `1.2.3.4` you use aforementioned script: ``` $ kubernetes/test/kubemark/get-real-pod-for-hollow-node.sh 1.2.3.4 ``` which will output the line: ``` hollow-node-1234 ``` Now you just use ordinary kubectl command to get the logs: ``` kubectl --namespace=kubemark logs hollow-node-1234 ``` All those things should work exactly the same on all cloud providers. ### Turning down Kubemark cluster On GCE you just need to execute `test/kubemark/stop-kubemark.sh` script, which will delete HollowNode ReplicationController and all the resources for you. On other providers you’ll need to delete all this stuff by yourself. ## Some current implementation details Kubemark master uses exactly the same binaries as ordinary Kubernetes does. This means that it will never be out of date. On the other hand HollowNodes use existing fake for Kubelet (called SimpleKubelet), which mocks its runtime manager with `pkg/kubelet/dockertools/fake_manager.go`, where most logic sits. Because there’s no easy way of mocking other managers (e.g. VolumeManager), they are not supported in Kubemark (e.g. we can’t schedule Pods with volumes in them yet). As the time passes more fakes will probably be plugged into HollowNodes, but it’s crucial to make it as simple as possible to allow running a big number of Hollows on a single core. <!-- BEGIN MUNGE: GENERATED_ANALYTICS --> [![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/devel/kubemark-guide.md?pixel)]() <!-- END MUNGE: GENERATED_ANALYTICS -->
docs/devel/kubemark-guide.md
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.00017584649322088808, 0.00016940869682002813, 0.00016148727445397526, 0.00016898450849112123, 0.0000036596682093659183 ]
{ "id": 2, "code_window": [ "\tif err != nil {\n", "\t\tframework.Logf(\"error in waiting for pods to come up: %s\", err)\n", "\t\tExpect(err).NotTo(HaveOccurred())\n", "\t}\n", "\t// Wait for the required pods to be ready for at least minReadySeconds (be available)\n", "\tdeploymentMinReadySeconds := int32(5)\n", "\terr = framework.WaitForPodsReady(c, ns, podName, int(deploymentMinReadySeconds))\n", "\tExpect(err).NotTo(HaveOccurred())\n", "\n", "\t// Create a deployment to delete nginx pods and instead bring up redis-slave pods.\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "test/e2e/deployment.go", "type": "replace", "edit_start_line_idx": 516 }
/* 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 e2e import ( "fmt" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/annotations" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apis/extensions" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" client "k8s.io/kubernetes/pkg/client/unversioned" adapter "k8s.io/kubernetes/pkg/client/unversioned/adapters/internalclientset" deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util" "k8s.io/kubernetes/pkg/kubectl" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/watch" "k8s.io/kubernetes/test/e2e/framework" ) const ( // nginxImage defined in kubectl.go nginxImageName = "nginx" redisImage = "gcr.io/google_containers/redis:e2e" redisImageName = "redis" ) var _ = framework.KubeDescribe("Deployment", func() { f := framework.NewDefaultFramework("deployment") It("deployment should create new pods", func() { testNewDeployment(f) }) It("RollingUpdateDeployment should delete old pods and create new ones", func() { testRollingUpdateDeployment(f) }) It("RollingUpdateDeployment should scale up and down in the right order", func() { testRollingUpdateDeploymentEvents(f) }) It("RecreateDeployment should delete old pods and create new ones", func() { testRecreateDeployment(f) }) It("deployment should delete old replica sets", func() { testDeploymentCleanUpPolicy(f) }) It("deployment should support rollover", func() { testRolloverDeployment(f) }) It("paused deployment should be ignored by the controller", func() { testPausedDeployment(f) }) It("deployment should support rollback", func() { testRollbackDeployment(f) }) It("deployment should support rollback when there's replica set with no revision", func() { testRollbackDeploymentRSNoRevision(f) }) It("deployment should label adopted RSs and pods", func() { testDeploymentLabelAdopted(f) }) It("paused deployment should be able to scale", func() { testScalePausedDeployment(f) }) It("scaled rollout should not block on annotation check", func() { testScaledRolloutDeployment(f) }) }) func newRS(rsName string, replicas int32, rsPodLabels map[string]string, imageName string, image string) *extensions.ReplicaSet { zero := int64(0) return &extensions.ReplicaSet{ ObjectMeta: api.ObjectMeta{ Name: rsName, }, Spec: extensions.ReplicaSetSpec{ Replicas: replicas, Selector: &unversioned.LabelSelector{MatchLabels: rsPodLabels}, Template: api.PodTemplateSpec{ ObjectMeta: api.ObjectMeta{ Labels: rsPodLabels, }, Spec: api.PodSpec{ TerminationGracePeriodSeconds: &zero, Containers: []api.Container{ { Name: imageName, Image: image, }, }, }, }, }, } } func newDeployment(deploymentName string, replicas int32, podLabels map[string]string, imageName string, image string, strategyType extensions.DeploymentStrategyType, revisionHistoryLimit *int32) *extensions.Deployment { zero := int64(0) return &extensions.Deployment{ ObjectMeta: api.ObjectMeta{ Name: deploymentName, }, Spec: extensions.DeploymentSpec{ Replicas: replicas, Selector: &unversioned.LabelSelector{MatchLabels: podLabels}, Strategy: extensions.DeploymentStrategy{ Type: strategyType, }, RevisionHistoryLimit: revisionHistoryLimit, Template: api.PodTemplateSpec{ ObjectMeta: api.ObjectMeta{ Labels: podLabels, }, Spec: api.PodSpec{ TerminationGracePeriodSeconds: &zero, Containers: []api.Container{ { Name: imageName, Image: image, }, }, }, }, }, } } func newDeploymentRollback(name string, annotations map[string]string, revision int64) *extensions.DeploymentRollback { return &extensions.DeploymentRollback{ Name: name, UpdatedAnnotations: annotations, RollbackTo: extensions.RollbackConfig{Revision: revision}, } } // checkDeploymentRevision checks if the input deployment's and its new replica set's revision and images are as expected. func checkDeploymentRevision(c *clientset.Clientset, ns, deploymentName, revision, imageName, image string) (*extensions.Deployment, *extensions.ReplicaSet) { deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) // Check revision of the new replica set of this deployment newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(newRS.Annotations).NotTo(Equal(nil)) Expect(newRS.Annotations[deploymentutil.RevisionAnnotation]).Should(Equal(revision)) // Check revision of This deployment Expect(deployment.Annotations).NotTo(Equal(nil)) Expect(deployment.Annotations[deploymentutil.RevisionAnnotation]).Should(Equal(revision)) if len(imageName) > 0 { // Check the image the new replica set creates Expect(newRS.Spec.Template.Spec.Containers[0].Name).Should(Equal(imageName)) Expect(newRS.Spec.Template.Spec.Containers[0].Image).Should(Equal(image)) // Check the image the deployment creates Expect(deployment.Spec.Template.Spec.Containers[0].Name).Should(Equal(imageName)) Expect(deployment.Spec.Template.Spec.Containers[0].Image).Should(Equal(image)) } return deployment, newRS } func stopDeployment(c *clientset.Clientset, oldC client.Interface, ns, deploymentName string) { deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) framework.Logf("Deleting deployment %s", deploymentName) reaper, err := kubectl.ReaperFor(extensions.Kind("Deployment"), oldC) Expect(err).NotTo(HaveOccurred()) timeout := 1 * time.Minute err = reaper.Stop(ns, deployment.Name, timeout, api.NewDeleteOptions(0)) Expect(err).NotTo(HaveOccurred()) framework.Logf("Ensuring deployment %s was deleted", deploymentName) _, err = c.Extensions().Deployments(ns).Get(deployment.Name) Expect(err).To(HaveOccurred()) Expect(errors.IsNotFound(err)).To(BeTrue()) framework.Logf("Ensuring deployment %s's RSes were deleted", deploymentName) selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) Expect(err).NotTo(HaveOccurred()) options := api.ListOptions{LabelSelector: selector} rss, err := c.Extensions().ReplicaSets(ns).List(options) Expect(err).NotTo(HaveOccurred()) Expect(rss.Items).Should(HaveLen(0)) framework.Logf("Ensuring deployment %s's Pods were deleted", deploymentName) var pods *api.PodList if err := wait.PollImmediate(time.Second, timeout, func() (bool, error) { pods, err = c.Core().Pods(ns).List(api.ListOptions{}) if err != nil { return false, err } if len(pods.Items) == 0 { return true, nil } return false, nil }); err != nil { framework.Failf("Err : %s\n. Failed to remove deployment %s pods : %+v", err, deploymentName, pods) } } func testNewDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. c := adapter.FromUnversionedClient(f.Client) deploymentName := "test-new-deployment" podLabels := map[string]string{"name": nginxImageName} replicas := int32(1) framework.Logf("Creating simple deployment %s", deploymentName) d := newDeployment(deploymentName, replicas, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) d.Annotations = map[string]string{"test": "should-copy-to-replica-set", annotations.LastAppliedConfigAnnotation: "should-not-copy-to-replica-set"} deploy, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", nginxImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) // Check new RS annotations Expect(newRS.Annotations["test"]).Should(Equal("should-copy-to-replica-set")) Expect(newRS.Annotations[annotations.LastAppliedConfigAnnotation]).Should(Equal("")) Expect(deployment.Annotations["test"]).Should(Equal("should-copy-to-replica-set")) Expect(deployment.Annotations[annotations.LastAppliedConfigAnnotation]).Should(Equal("should-not-copy-to-replica-set")) } func testRollingUpdateDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "sample-pod"} rsPodLabels := map[string]string{ "name": "sample-pod", "pod": nginxImageName, } rsName := "test-rolling-update-controller" replicas := int32(3) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "sample-pod", false, 3) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-rolling-update-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RollingUpdateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", redisImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // There should be 1 old RS (nginx-controller, which is adopted) deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) _, allOldRSs, err := deploymentutil.GetOldReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(len(allOldRSs)).Should(Equal(1)) // The old RS should contain pod-template-hash in its selector, label, and template label Expect(len(allOldRSs[0].Labels[extensions.DefaultDeploymentUniqueLabelKey])).Should(BeNumerically(">", 0)) Expect(len(allOldRSs[0].Spec.Selector.MatchLabels[extensions.DefaultDeploymentUniqueLabelKey])).Should(BeNumerically(">", 0)) Expect(len(allOldRSs[0].Spec.Template.Labels[extensions.DefaultDeploymentUniqueLabelKey])).Should(BeNumerically(">", 0)) } func testRollingUpdateDeploymentEvents(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "sample-pod-2"} rsPodLabels := map[string]string{ "name": "sample-pod-2", "pod": nginxImageName, } rsName := "test-rolling-scale-controller" replicas := int32(1) rsRevision := "3546343826724305832" annotations := make(map[string]string) annotations[deploymentutil.RevisionAnnotation] = rsRevision rs := newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage) rs.Annotations = annotations _, err := c.Extensions().ReplicaSets(ns).Create(rs) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "sample-pod-2", false, 1) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-rolling-scale-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RollingUpdateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 3546343826724305833 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "3546343826724305833", redisImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Verify that the pods were scaled up and down as expected. We use events to verify that. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) framework.WaitForEvents(unversionedClient, ns, deployment, 2) events, err := c.Core().Events(ns).Search(deployment) if err != nil { framework.Logf("error in listing events: %s", err) Expect(err).NotTo(HaveOccurred()) } // There should be 2 events, one to scale up the new ReplicaSet and then to scale down // the old ReplicaSet. Expect(len(events.Items)).Should(Equal(2)) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(newRS).NotTo(Equal(nil)) Expect(events.Items[0].Message).Should(Equal(fmt.Sprintf("Scaled up replica set %s to 1", newRS.Name))) Expect(events.Items[1].Message).Should(Equal(fmt.Sprintf("Scaled down replica set %s to 0", rsName))) } func testRecreateDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "sample-pod-3"} rsPodLabels := map[string]string{ "name": "sample-pod-3", "pod": nginxImageName, } rsName := "test-recreate-controller" replicas := int32(3) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "sample-pod-3", false, 3) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-recreate-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RecreateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", redisImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Verify that the pods were scaled up and down as expected. We use events to verify that. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) framework.WaitForEvents(unversionedClient, ns, deployment, 2) events, err := c.Core().Events(ns).Search(deployment) if err != nil { framework.Logf("error in listing events: %s", err) Expect(err).NotTo(HaveOccurred()) } // There should be 2 events, one to scale up the new ReplicaSet and then to scale down the old ReplicaSet. Expect(len(events.Items)).Should(Equal(2)) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(newRS).NotTo(Equal(nil)) Expect(events.Items[0].Message).Should(Equal(fmt.Sprintf("Scaled down replica set %s to 0", rsName))) Expect(events.Items[1].Message).Should(Equal(fmt.Sprintf("Scaled up replica set %s to 3", newRS.Name))) } // testDeploymentCleanUpPolicy tests that deployment supports cleanup policy func testDeploymentCleanUpPolicy(f *framework.Framework) { ns := f.Namespace.Name unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "cleanup-pod"} rsPodLabels := map[string]string{ "name": "cleanup-pod", "pod": nginxImageName, } rsName := "test-cleanup-controller" replicas := int32(1) revisionHistoryLimit := util.Int32Ptr(0) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "cleanup-pod", false, 1) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-cleanup-deployment" framework.Logf("Creating deployment %s", deploymentName) pods, err := c.Pods(ns).List(api.ListOptions{LabelSelector: labels.Everything()}) if err != nil { Expect(err).NotTo(HaveOccurred(), "Failed to query for pods: %v", err) } options := api.ListOptions{ ResourceVersion: pods.ListMeta.ResourceVersion, } stopCh := make(chan struct{}) w, err := c.Pods(ns).Watch(options) go func() { // There should be only one pod being created, which is the pod with the redis image. // The old RS shouldn't create new pod when deployment controller adding pod template hash label to its selector. numPodCreation := 1 for { select { case event, _ := <-w.ResultChan(): if event.Type != watch.Added { continue } numPodCreation-- if numPodCreation < 0 { framework.Failf("Expect only one pod creation, the second creation event: %#v\n", event) } pod, ok := event.Object.(*api.Pod) if !ok { Fail("Expect event Object to be a pod") } if pod.Spec.Containers[0].Name != redisImageName { framework.Failf("Expect the created pod to have container name %s, got pod %#v\n", redisImageName, pod) } case <-stopCh: return } } }() _, err = c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RollingUpdateDeploymentStrategyType, revisionHistoryLimit)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) err = framework.WaitForDeploymentOldRSsNum(c, ns, deploymentName, int(*revisionHistoryLimit)) Expect(err).NotTo(HaveOccurred()) close(stopCh) } // testRolloverDeployment tests that deployment supports rollover. // i.e. we can change desired state and kick off rolling update, then change desired state again before it finishes. func testRolloverDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) podName := "rollover-pod" deploymentPodLabels := map[string]string{"name": podName} rsPodLabels := map[string]string{ "name": podName, "pod": nginxImageName, } rsName := "test-rollover-controller" rsReplicas := int32(4) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, rsReplicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, podName, false, rsReplicas) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Wait for the required pods to be ready for at least minReadySeconds (be available) deploymentMinReadySeconds := int32(5) err = framework.WaitForPodsReady(c, ns, podName, int(deploymentMinReadySeconds)) Expect(err).NotTo(HaveOccurred()) // Create a deployment to delete nginx pods and instead bring up redis-slave pods. deploymentName, deploymentImageName := "test-rollover-deployment", "redis-slave" deploymentReplicas := int32(4) deploymentImage := "gcr.io/google_samples/gb-redisslave:v1" deploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType framework.Logf("Creating deployment %s", deploymentName) newDeployment := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil) newDeployment.Spec.MinReadySeconds = deploymentMinReadySeconds newDeployment.Spec.Strategy.RollingUpdate = &extensions.RollingUpdateDeployment{ MaxUnavailable: intstr.FromInt(1), MaxSurge: intstr.FromInt(1), } _, err = c.Extensions().Deployments(ns).Create(newDeployment) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Verify that the pods were scaled up and down as expected. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) // Make sure the deployment starts to scale up and down replica sets by checking if its updated replicas >= 1 err = framework.WaitForDeploymentUpdatedReplicasLTE(c, ns, deploymentName, 1, deployment.Generation) // Check if it's updated to revision 1 correctly _, newRS := checkDeploymentRevision(c, ns, deploymentName, "1", deploymentImageName, deploymentImage) // Before the deployment finishes, update the deployment to rollover the above 2 ReplicaSets and bring up redis pods. // If the deployment already finished here, the test would fail. When this happens, increase its minReadySeconds or replicas to prevent it. Expect(newRS.Spec.Replicas).Should(BeNumerically("<", deploymentReplicas)) updatedDeploymentImageName, updatedDeploymentImage := redisImageName, redisImage deployment, err = framework.UpdateDeploymentWithRetries(c, ns, newDeployment.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName update.Spec.Template.Spec.Containers[0].Image = updatedDeploymentImage }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pod template update. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 2 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "2", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) } func testPausedDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) deploymentName := "test-paused-deployment" podLabels := map[string]string{"name": nginxImageName} d := newDeployment(deploymentName, 1, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) d.Spec.Paused = true tgps := int64(20) d.Spec.Template.Spec.TerminationGracePeriodSeconds = &tgps framework.Logf("Creating paused deployment %s", deploymentName) _, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Check that deployment is created fine. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) // Verify that there is no latest state realized for the new deployment. rs, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) if rs != nil { err = fmt.Errorf("unexpected new rs/%s for deployment/%s", rs.Name, deployment.Name) Expect(err).NotTo(HaveOccurred()) } // Update the deployment to run deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Paused = false }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the resume. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) if err != nil { Expect(err).NotTo(HaveOccurred()) } opts := api.ListOptions{LabelSelector: selector} w, err := c.Extensions().ReplicaSets(ns).Watch(opts) Expect(err).NotTo(HaveOccurred()) select { case <-w.ResultChan(): // this is it case <-time.After(time.Minute): err = fmt.Errorf("expected a new replica set to be created") Expect(err).NotTo(HaveOccurred()) } // Pause the deployment and delete the replica set. // The paused deployment shouldn't recreate a new one. deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Paused = true }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pause. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Update the deployment template - the new replicaset should stay the same framework.Logf("Updating paused deployment %q", deploymentName) newTGPS := int64(40) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.TerminationGracePeriodSeconds = &newTGPS }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) framework.Logf("Looking for new replicaset for paused deployment %q (there should be none)", deploymentName) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) if newRS != nil { err = fmt.Errorf("No replica set should match the deployment template but there is %q", newRS.Name) Expect(err).NotTo(HaveOccurred()) } _, allOldRs, err := deploymentutil.GetOldReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) if len(allOldRs) != 1 { err = fmt.Errorf("expected an old replica set") Expect(err).NotTo(HaveOccurred()) } framework.Logf("Comparing deployment diff with old replica set %q", allOldRs[0].Name) if *allOldRs[0].Spec.Template.Spec.TerminationGracePeriodSeconds == newTGPS { err = fmt.Errorf("TerminationGracePeriodSeconds on the replica set should be %d but is %d", tgps, newTGPS) Expect(err).NotTo(HaveOccurred()) } } // testRollbackDeployment tests that a deployment is created (revision 1) and updated (revision 2), and // then rollback to revision 1 (should update template to revision 1, and then update revision 1 to 3), // and then rollback to last revision. func testRollbackDeployment(f *framework.Framework) { ns := f.Namespace.Name unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) podName := "nginx" deploymentPodLabels := map[string]string{"name": podName} // 1. Create a deployment to create nginx pods. deploymentName, deploymentImageName := "test-rollback-deployment", nginxImageName deploymentReplicas := int32(1) deploymentImage := nginxImage deploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType framework.Logf("Creating deployment %s", deploymentName) d := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil) createAnnotation := map[string]string{"action": "create", "author": "minion"} d.Annotations = createAnnotation deploy, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "create" err = framework.CheckNewRSAnnotations(c, ns, deploymentName, createAnnotation) Expect(err).NotTo(HaveOccurred()) // 2. Update the deployment to create redis pods. updatedDeploymentImage := redisImage updatedDeploymentImageName := redisImageName updateAnnotation := map[string]string{"action": "update", "log": "I need to update it"} deployment, err := framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName update.Spec.Template.Spec.Containers[0].Image = updatedDeploymentImage update.Annotations = updateAnnotation }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pod template update. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 2 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "2", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "update" err = framework.CheckNewRSAnnotations(c, ns, deploymentName, updateAnnotation) Expect(err).NotTo(HaveOccurred()) // 3. Update the deploymentRollback to rollback to revision 1 revision := int64(1) framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback := newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackDone in deployment status and check it here // Wait for it to be updated to revision 3 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "3", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "create", after the rollback err = framework.CheckNewRSAnnotations(c, ns, deploymentName, createAnnotation) Expect(err).NotTo(HaveOccurred()) // 4. Update the deploymentRollback to rollback to last revision revision = 0 framework.Logf("rolling back deployment %s to last revision", deploymentName) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 4 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "4", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "update", after the rollback err = framework.CheckNewRSAnnotations(c, ns, deploymentName, updateAnnotation) Expect(err).NotTo(HaveOccurred()) } // testRollbackDeploymentRSNoRevision tests that deployment supports rollback even when there's old replica set without revision. // An old replica set without revision is created, and then a deployment is created (v1). The deployment shouldn't add revision // annotation to the old replica set. Then rollback the deployment to last revision, and it should fail. // Then update the deployment to v2 and rollback it to v1 should succeed, now the deployment // becomes v3. Then rollback the deployment to v10 (doesn't exist in history) should fail. // Finally, rollback the deployment (v3) to v3 should be no-op. // TODO: When we finished reporting rollback status in deployment status, check the rollback status here in each case. func testRollbackDeploymentRSNoRevision(f *framework.Framework) { ns := f.Namespace.Name c := adapter.FromUnversionedClient(f.Client) podName := "nginx" deploymentPodLabels := map[string]string{"name": podName} rsPodLabels := map[string]string{ "name": podName, "pod": nginxImageName, } // Create an old RS without revision rsName := "test-rollback-no-revision-controller" rsReplicas := int32(0) rs := newRS(rsName, rsReplicas, rsPodLabels, nginxImageName, nginxImage) rs.Annotations = make(map[string]string) rs.Annotations["make"] = "difference" _, err := c.Extensions().ReplicaSets(ns).Create(rs) Expect(err).NotTo(HaveOccurred()) // 1. Create a deployment to create nginx pods, which have different template than the replica set created above. deploymentName, deploymentImageName := "test-rollback-no-revision-deployment", nginxImageName deploymentReplicas := int32(1) deploymentImage := nginxImage deploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType framework.Logf("Creating deployment %s", deploymentName) d := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil) deploy, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Check that the replica set we created still doesn't contain revision information rs, err = c.Extensions().ReplicaSets(ns).Get(rsName) Expect(err).NotTo(HaveOccurred()) Expect(rs.Annotations[deploymentutil.RevisionAnnotation]).Should(Equal("")) // 2. Update the deploymentRollback to rollback to last revision // Since there's only 1 revision in history, it should stay as revision 1 revision := int64(0) framework.Logf("rolling back deployment %s to last revision", deploymentName) rollback := newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackRevisionNotFound in deployment status and check it here // The pod template shouldn't change since there's no last revision // Check if the deployment is still revision 1 and still has the old pod template checkDeploymentRevision(c, ns, deploymentName, "1", deploymentImageName, deploymentImage) // 3. Update the deployment to create redis pods. updatedDeploymentImage := redisImage updatedDeploymentImageName := redisImageName deployment, err := framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName update.Spec.Template.Spec.Containers[0].Image = updatedDeploymentImage }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pod template update. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 2 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "2", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // 4. Update the deploymentRollback to rollback to revision 1 revision = 1 framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackDone in deployment status and check it here // The pod template should be updated to the one in revision 1 // Wait for it to be updated to revision 3 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "3", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // 5. Update the deploymentRollback to rollback to revision 10 // Since there's no revision 10 in history, it should stay as revision 3 revision = 10 framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackRevisionNotFound in deployment status and check it here // The pod template shouldn't change since there's no revision 10 // Check if it's still revision 3 and still has the old pod template checkDeploymentRevision(c, ns, deploymentName, "3", deploymentImageName, deploymentImage) // 6. Update the deploymentRollback to rollback to revision 3 // Since it's already revision 3, it should be no-op revision = 3 framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackTemplateUnchanged in deployment status and check it here // The pod template shouldn't change since it's already revision 3 // Check if it's still revision 3 and still has the old pod template checkDeploymentRevision(c, ns, deploymentName, "3", deploymentImageName, deploymentImage) } func testDeploymentLabelAdopted(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. podName := "nginx" podLabels := map[string]string{"name": podName} rsName := "test-adopted-controller" replicas := int32(3) image := nginxImage _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, podLabels, podName, image)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, podName, false, 3) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a nginx deployment to adopt the old rs. deploymentName := "test-adopted-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, podLabels, podName, image, extensions.RollingUpdateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", image) Expect(err).NotTo(HaveOccurred()) // The RS and pods should be relabeled before the status is updated by syncRollingUpdateDeployment err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // There should be no old RSs (overlapping RS) deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) oldRSs, allOldRSs, newRS, err := deploymentutil.GetAllReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(len(oldRSs)).Should(Equal(0)) Expect(len(allOldRSs)).Should(Equal(0)) // New RS should contain pod-template-hash in its selector, label, and template label err = framework.CheckRSHashLabel(newRS) Expect(err).NotTo(HaveOccurred()) // All pods targeted by the deployment should contain pod-template-hash in their labels, and there should be only 3 pods selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) Expect(err).NotTo(HaveOccurred()) options := api.ListOptions{LabelSelector: selector} pods, err := c.Core().Pods(ns).List(options) Expect(err).NotTo(HaveOccurred()) err = framework.CheckPodHashLabel(pods) Expect(err).NotTo(HaveOccurred()) Expect(int32(len(pods.Items))).Should(Equal(replicas)) } func testScalePausedDeployment(f *framework.Framework) { ns := f.Namespace.Name c := adapter.FromUnversionedClient(f.Client) podLabels := map[string]string{"name": nginxImageName} replicas := int32(3) // Create a nginx deployment. deploymentName := "nginx-deployment" d := newDeployment(deploymentName, replicas, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) framework.Logf("Creating deployment %q", deploymentName) _, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Check that deployment is created fine. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) rs, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) // Pause the deployment and try to scale it. deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Paused = true }) Expect(err).NotTo(HaveOccurred()) // Scale the paused deployment. framework.Logf("Scaling up the paused deployment %q", deploymentName) newReplicas := int32(5) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { update.Spec.Replicas = newReplicas }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) rs, err = deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) if rs.Spec.Replicas != newReplicas { err = fmt.Errorf("Expected %d replicas for the new replica set, got %d", newReplicas, rs.Spec.Replicas) Expect(err).NotTo(HaveOccurred()) } } func testScaledRolloutDeployment(f *framework.Framework) { ns := f.Namespace.Name c := adapter.FromUnversionedClient(f.Client) podLabels := map[string]string{"name": nginxImageName} replicas := int32(10) // Create a nginx deployment. deploymentName := "nginx" d := newDeployment(deploymentName, replicas, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) d.Spec.Strategy.RollingUpdate = new(extensions.RollingUpdateDeployment) d.Spec.Strategy.RollingUpdate.MaxSurge = intstr.FromInt(3) d.Spec.Strategy.RollingUpdate.MaxUnavailable = intstr.FromInt(2) By(fmt.Sprintf("Creating deployment %q", deploymentName)) _, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Check that deployment is created fine. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for observed generation %d", deployment.Generation)) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) deployment, err = c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) first, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) // Update the deployment with a non-existent image so that the new replica set will be blocked. By(fmt.Sprintf("Updating deployment %q with a non-existent image", deploymentName)) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Image = "nginx:404" }) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for observed generation %d", deployment.Generation)) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) deployment, err = c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, false) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Checking that the replica sets for %q are synced", deploymentName)) second, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) first, err = c.Extensions().ReplicaSets(first.Namespace).Get(first.Name) Expect(err).NotTo(HaveOccurred()) firstCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), first) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, firstCond) secondCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), second) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, secondCond) By(fmt.Sprintf("Updating the size (up) and template at the same time for deployment %q", deploymentName)) newReplicas := int32(20) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { update.Spec.Replicas = newReplicas update.Spec.Template.Spec.Containers[0].Image = nautilusImage }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) oldRSs, _, rs, err := deploymentutil.GetAllReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) for _, rs := range append(oldRSs, rs) { By(fmt.Sprintf("Ensuring replica set %q has the correct desiredReplicas annotation", rs.Name)) desired, ok := deploymentutil.GetDesiredReplicasAnnotation(rs) if !ok || desired == deployment.Spec.Replicas { continue } err = fmt.Errorf("unexpected desiredReplicas annotation %d for replica set %q", desired, rs.Name) Expect(err).NotTo(HaveOccurred()) } By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Update the deployment with a non-existent image so that the new replica set will be blocked. By(fmt.Sprintf("Updating deployment %q with a non-existent image", deploymentName)) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Image = "nginx:404" }) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for observed generation %d", deployment.Generation)) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) deployment, err = c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, false) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Checking that the replica sets for %q are synced", deploymentName)) oldRs, err := c.Extensions().ReplicaSets(rs.Namespace).Get(rs.Name) Expect(err).NotTo(HaveOccurred()) newRs, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) oldCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), oldRs) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, oldCond) newCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), newRs) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, newCond) By(fmt.Sprintf("Updating the size (down) and template at the same time for deployment %q", deploymentName)) newReplicas = int32(5) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { update.Spec.Replicas = newReplicas update.Spec.Template.Spec.Containers[0].Image = kittenImage }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) oldRSs, _, rs, err = deploymentutil.GetAllReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) for _, rs := range append(oldRSs, rs) { By(fmt.Sprintf("Ensuring replica set %q has the correct desiredReplicas annotation", rs.Name)) desired, ok := deploymentutil.GetDesiredReplicasAnnotation(rs) if !ok || desired == deployment.Spec.Replicas { continue } err = fmt.Errorf("unexpected desiredReplicas annotation %d for replica set %q", desired, rs.Name) Expect(err).NotTo(HaveOccurred()) } By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) }
test/e2e/deployment.go
1
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.9989620447158813, 0.05029904469847679, 0.00016559893265366554, 0.00324069382622838, 0.181295707821846 ]
{ "id": 2, "code_window": [ "\tif err != nil {\n", "\t\tframework.Logf(\"error in waiting for pods to come up: %s\", err)\n", "\t\tExpect(err).NotTo(HaveOccurred())\n", "\t}\n", "\t// Wait for the required pods to be ready for at least minReadySeconds (be available)\n", "\tdeploymentMinReadySeconds := int32(5)\n", "\terr = framework.WaitForPodsReady(c, ns, podName, int(deploymentMinReadySeconds))\n", "\tExpect(err).NotTo(HaveOccurred())\n", "\n", "\t// Create a deployment to delete nginx pods and instead bring up redis-slave pods.\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "test/e2e/deployment.go", "type": "replace", "edit_start_line_idx": 516 }
/* 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 cache import ( "errors" "fmt" "math/rand" "strconv" "testing" "time" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/watch" ) var nevererrc chan error type testLW struct { ListFunc func() (runtime.Object, error) WatchFunc func(options api.ListOptions) (watch.Interface, error) } func (t *testLW) List(options api.ListOptions) (runtime.Object, error) { return t.ListFunc() } func (t *testLW) Watch(options api.ListOptions) (watch.Interface, error) { return t.WatchFunc(options) } func TestCloseWatchChannelOnError(t *testing.T) { r := NewReflector(&testLW{}, &api.Pod{}, NewStore(MetaNamespaceKeyFunc), 0) pod := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "bar"}} fw := watch.NewFake() r.listerWatcher = &testLW{ WatchFunc: func(options api.ListOptions) (watch.Interface, error) { return fw, nil }, ListFunc: func() (runtime.Object, error) { return &api.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: "1"}}, nil }, } go r.ListAndWatch(wait.NeverStop) fw.Error(pod) select { case _, ok := <-fw.ResultChan(): if ok { t.Errorf("Watch channel left open after cancellation") } case <-time.After(wait.ForeverTestTimeout): t.Errorf("the cancellation is at least %s late", wait.ForeverTestTimeout.String()) break } } func TestRunUntil(t *testing.T) { stopCh := make(chan struct{}) store := NewStore(MetaNamespaceKeyFunc) r := NewReflector(&testLW{}, &api.Pod{}, store, 0) fw := watch.NewFake() r.listerWatcher = &testLW{ WatchFunc: func(options api.ListOptions) (watch.Interface, error) { return fw, nil }, ListFunc: func() (runtime.Object, error) { return &api.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: "1"}}, nil }, } r.RunUntil(stopCh) // Synchronously add a dummy pod into the watch channel so we // know the RunUntil go routine is in the watch handler. fw.Add(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "bar"}}) close(stopCh) select { case _, ok := <-fw.ResultChan(): if ok { t.Errorf("Watch channel left open after stopping the watch") } case <-time.After(wait.ForeverTestTimeout): t.Errorf("the cancellation is at least %s late", wait.ForeverTestTimeout.String()) break } } func TestReflectorResyncChan(t *testing.T) { s := NewStore(MetaNamespaceKeyFunc) g := NewReflector(&testLW{}, &api.Pod{}, s, time.Millisecond) a, _ := g.resyncChan() b := time.After(wait.ForeverTestTimeout) select { case <-a: t.Logf("got timeout as expected") case <-b: t.Errorf("resyncChan() is at least 99 milliseconds late??") } } func BenchmarkReflectorResyncChanMany(b *testing.B) { s := NewStore(MetaNamespaceKeyFunc) g := NewReflector(&testLW{}, &api.Pod{}, s, 25*time.Millisecond) // The improvement to this (calling the timer's Stop() method) makes // this benchmark about 40% faster. for i := 0; i < b.N; i++ { g.resyncPeriod = time.Duration(rand.Float64() * float64(time.Millisecond) * 25) _, stop := g.resyncChan() stop() } } func TestReflectorWatchHandlerError(t *testing.T) { s := NewStore(MetaNamespaceKeyFunc) g := NewReflector(&testLW{}, &api.Pod{}, s, 0) fw := watch.NewFake() go func() { fw.Stop() }() var resumeRV string err := g.watchHandler(fw, &resumeRV, nevererrc, wait.NeverStop) if err == nil { t.Errorf("unexpected non-error") } } func TestReflectorWatchHandler(t *testing.T) { s := NewStore(MetaNamespaceKeyFunc) g := NewReflector(&testLW{}, &api.Pod{}, s, 0) fw := watch.NewFake() s.Add(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}) s.Add(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "bar"}}) go func() { fw.Add(&api.Service{ObjectMeta: api.ObjectMeta{Name: "rejected"}}) fw.Delete(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}) fw.Modify(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "bar", ResourceVersion: "55"}}) fw.Add(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "baz", ResourceVersion: "32"}}) fw.Stop() }() var resumeRV string err := g.watchHandler(fw, &resumeRV, nevererrc, wait.NeverStop) if err != nil { t.Errorf("unexpected error %v", err) } mkPod := func(id string, rv string) *api.Pod { return &api.Pod{ObjectMeta: api.ObjectMeta{Name: id, ResourceVersion: rv}} } table := []struct { Pod *api.Pod exists bool }{ {mkPod("foo", ""), false}, {mkPod("rejected", ""), false}, {mkPod("bar", "55"), true}, {mkPod("baz", "32"), true}, } for _, item := range table { obj, exists, _ := s.Get(item.Pod) if e, a := item.exists, exists; e != a { t.Errorf("%v: expected %v, got %v", item.Pod, e, a) } if !exists { continue } if e, a := item.Pod.ResourceVersion, obj.(*api.Pod).ResourceVersion; e != a { t.Errorf("%v: expected %v, got %v", item.Pod, e, a) } } // RV should send the last version we see. if e, a := "32", resumeRV; e != a { t.Errorf("expected %v, got %v", e, a) } // last sync resource version should be the last version synced with store if e, a := "32", g.LastSyncResourceVersion(); e != a { t.Errorf("expected %v, got %v", e, a) } } func TestReflectorStopWatch(t *testing.T) { s := NewStore(MetaNamespaceKeyFunc) g := NewReflector(&testLW{}, &api.Pod{}, s, 0) fw := watch.NewFake() var resumeRV string stopWatch := make(chan struct{}, 1) stopWatch <- struct{}{} err := g.watchHandler(fw, &resumeRV, nevererrc, stopWatch) if err != errorStopRequested { t.Errorf("expected stop error, got %q", err) } } func TestReflectorListAndWatch(t *testing.T) { createdFakes := make(chan *watch.FakeWatcher) // The ListFunc says that it's at revision 1. Therefore, we expect our WatchFunc // to get called at the beginning of the watch with 1, and again with 3 when we // inject an error. expectedRVs := []string{"1", "3"} lw := &testLW{ WatchFunc: func(options api.ListOptions) (watch.Interface, error) { rv := options.ResourceVersion fw := watch.NewFake() if e, a := expectedRVs[0], rv; e != a { t.Errorf("Expected rv %v, but got %v", e, a) } expectedRVs = expectedRVs[1:] // channel is not buffered because the for loop below needs to block. But // we don't want to block here, so report the new fake via a go routine. go func() { createdFakes <- fw }() return fw, nil }, ListFunc: func() (runtime.Object, error) { return &api.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: "1"}}, nil }, } s := NewFIFO(MetaNamespaceKeyFunc) r := NewReflector(lw, &api.Pod{}, s, 0) go r.ListAndWatch(wait.NeverStop) ids := []string{"foo", "bar", "baz", "qux", "zoo"} var fw *watch.FakeWatcher for i, id := range ids { if fw == nil { fw = <-createdFakes } sendingRV := strconv.FormatUint(uint64(i+2), 10) fw.Add(&api.Pod{ObjectMeta: api.ObjectMeta{Name: id, ResourceVersion: sendingRV}}) if sendingRV == "3" { // Inject a failure. fw.Stop() fw = nil } } // Verify we received the right ids with the right resource versions. for i, id := range ids { pod := Pop(s).(*api.Pod) if e, a := id, pod.Name; e != a { t.Errorf("%v: Expected %v, got %v", i, e, a) } if e, a := strconv.FormatUint(uint64(i+2), 10), pod.ResourceVersion; e != a { t.Errorf("%v: Expected %v, got %v", i, e, a) } } if len(expectedRVs) != 0 { t.Error("called watchStarter an unexpected number of times") } } func TestReflectorListAndWatchWithErrors(t *testing.T) { mkPod := func(id string, rv string) *api.Pod { return &api.Pod{ObjectMeta: api.ObjectMeta{Name: id, ResourceVersion: rv}} } mkList := func(rv string, pods ...*api.Pod) *api.PodList { list := &api.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: rv}} for _, pod := range pods { list.Items = append(list.Items, *pod) } return list } table := []struct { list *api.PodList listErr error events []watch.Event watchErr error }{ { list: mkList("1"), events: []watch.Event{ {watch.Added, mkPod("foo", "2")}, {watch.Added, mkPod("bar", "3")}, }, }, { list: mkList("3", mkPod("foo", "2"), mkPod("bar", "3")), events: []watch.Event{ {watch.Deleted, mkPod("foo", "4")}, {watch.Added, mkPod("qux", "5")}, }, }, { listErr: fmt.Errorf("a list error"), }, { list: mkList("5", mkPod("bar", "3"), mkPod("qux", "5")), watchErr: fmt.Errorf("a watch error"), }, { list: mkList("5", mkPod("bar", "3"), mkPod("qux", "5")), events: []watch.Event{ {watch.Added, mkPod("baz", "6")}, }, }, { list: mkList("6", mkPod("bar", "3"), mkPod("qux", "5"), mkPod("baz", "6")), }, } s := NewFIFO(MetaNamespaceKeyFunc) for line, item := range table { if item.list != nil { // Test that the list is what currently exists in the store. current := s.List() checkMap := map[string]string{} for _, item := range current { pod := item.(*api.Pod) checkMap[pod.Name] = pod.ResourceVersion } for _, pod := range item.list.Items { if e, a := pod.ResourceVersion, checkMap[pod.Name]; e != a { t.Errorf("%v: expected %v, got %v for pod %v", line, e, a, pod.Name) } } if e, a := len(item.list.Items), len(checkMap); e != a { t.Errorf("%v: expected %v, got %v", line, e, a) } } watchRet, watchErr := item.events, item.watchErr lw := &testLW{ WatchFunc: func(options api.ListOptions) (watch.Interface, error) { if watchErr != nil { return nil, watchErr } watchErr = fmt.Errorf("second watch") fw := watch.NewFake() go func() { for _, e := range watchRet { fw.Action(e.Type, e.Object) } fw.Stop() }() return fw, nil }, ListFunc: func() (runtime.Object, error) { return item.list, item.listErr }, } r := NewReflector(lw, &api.Pod{}, s, 0) r.ListAndWatch(wait.NeverStop) } } func TestReflectorResync(t *testing.T) { iteration := 0 stopCh := make(chan struct{}) rerr := errors.New("expected resync reached") s := &FakeCustomStore{ ResyncFunc: func() error { iteration++ if iteration == 2 { return rerr } return nil }, } lw := &testLW{ WatchFunc: func(options api.ListOptions) (watch.Interface, error) { fw := watch.NewFake() return fw, nil }, ListFunc: func() (runtime.Object, error) { return &api.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: "0"}}, nil }, } resyncPeriod := 1 * time.Millisecond r := NewReflector(lw, &api.Pod{}, s, resyncPeriod) if err := r.ListAndWatch(stopCh); err != nil { // error from Resync is not propaged up to here. t.Errorf("expected error %v", err) } if iteration != 2 { t.Errorf("exactly 2 iterations were expected, got: %v", iteration) } }
pkg/client/cache/reflector_test.go
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.00019341813458595425, 0.000171513733221218, 0.00015711023297626525, 0.0001723001041682437, 0.00000595762639932218 ]
{ "id": 2, "code_window": [ "\tif err != nil {\n", "\t\tframework.Logf(\"error in waiting for pods to come up: %s\", err)\n", "\t\tExpect(err).NotTo(HaveOccurred())\n", "\t}\n", "\t// Wait for the required pods to be ready for at least minReadySeconds (be available)\n", "\tdeploymentMinReadySeconds := int32(5)\n", "\terr = framework.WaitForPodsReady(c, ns, podName, int(deploymentMinReadySeconds))\n", "\tExpect(err).NotTo(HaveOccurred())\n", "\n", "\t// Create a deployment to delete nginx pods and instead bring up redis-slave pods.\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "test/e2e/deployment.go", "type": "replace", "edit_start_line_idx": 516 }
kind: PersistentVolumeClaim apiVersion: v1 metadata: name: nfs spec: accessModes: - ReadWriteMany resources: requests: storage: 1Mi
examples/volumes/nfs/nfs-pvc.yaml
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.00017372956790495664, 0.00017244800983462483, 0.00017116645176429302, 0.00017244800983462483, 0.000001281558070331812 ]
{ "id": 2, "code_window": [ "\tif err != nil {\n", "\t\tframework.Logf(\"error in waiting for pods to come up: %s\", err)\n", "\t\tExpect(err).NotTo(HaveOccurred())\n", "\t}\n", "\t// Wait for the required pods to be ready for at least minReadySeconds (be available)\n", "\tdeploymentMinReadySeconds := int32(5)\n", "\terr = framework.WaitForPodsReady(c, ns, podName, int(deploymentMinReadySeconds))\n", "\tExpect(err).NotTo(HaveOccurred())\n", "\n", "\t// Create a deployment to delete nginx pods and instead bring up redis-slave pods.\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "test/e2e/deployment.go", "type": "replace", "edit_start_line_idx": 516 }
/* 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 fc import ( "fmt" "os" "testing" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/mount" utiltesting "k8s.io/kubernetes/pkg/util/testing" "k8s.io/kubernetes/pkg/volume" volumetest "k8s.io/kubernetes/pkg/volume/testing" ) func TestCanSupport(t *testing.T) { tmpDir, err := utiltesting.MkTmpdir("fc_test") if err != nil { t.Fatalf("error creating temp dir: %v", err) } defer os.RemoveAll(tmpDir) plugMgr := volume.VolumePluginMgr{} plugMgr.InitPlugins(ProbeVolumePlugins(), volumetest.NewFakeVolumeHost(tmpDir, nil, nil, "" /* rootContext */)) plug, err := plugMgr.FindPluginByName("kubernetes.io/fc") if err != nil { t.Errorf("Can't find the plugin by name") } if plug.GetPluginName() != "kubernetes.io/fc" { t.Errorf("Wrong name: %s", plug.GetPluginName()) } if plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{}}}) { t.Errorf("Expected false") } } func TestGetAccessModes(t *testing.T) { tmpDir, err := utiltesting.MkTmpdir("fc_test") if err != nil { t.Fatalf("error creating temp dir: %v", err) } defer os.RemoveAll(tmpDir) plugMgr := volume.VolumePluginMgr{} plugMgr.InitPlugins(ProbeVolumePlugins(), volumetest.NewFakeVolumeHost(tmpDir, nil, nil, "" /* rootContext */)) plug, err := plugMgr.FindPersistentPluginByName("kubernetes.io/fc") if err != nil { t.Errorf("Can't find the plugin by name") } if !contains(plug.GetAccessModes(), api.ReadWriteOnce) || !contains(plug.GetAccessModes(), api.ReadOnlyMany) { t.Errorf("Expected two AccessModeTypes: %s and %s", api.ReadWriteOnce, api.ReadOnlyMany) } } func contains(modes []api.PersistentVolumeAccessMode, mode api.PersistentVolumeAccessMode) bool { for _, m := range modes { if m == mode { return true } } return false } type fakeDiskManager struct { tmpDir string attachCalled bool detachCalled bool } func NewFakeDiskManager() *fakeDiskManager { return &fakeDiskManager{ tmpDir: utiltesting.MkTmpdirOrDie("fc_test"), } } func (fake *fakeDiskManager) Cleanup() { os.RemoveAll(fake.tmpDir) } func (fake *fakeDiskManager) MakeGlobalPDName(disk fcDisk) string { return fake.tmpDir } func (fake *fakeDiskManager) AttachDisk(b fcDiskMounter) error { globalPath := b.manager.MakeGlobalPDName(*b.fcDisk) err := os.MkdirAll(globalPath, 0750) if err != nil { return err } // Simulate the global mount so that the fakeMounter returns the // expected number of mounts for the attached disk. b.mounter.Mount(globalPath, globalPath, b.fsType, nil) fake.attachCalled = true return nil } func (fake *fakeDiskManager) DetachDisk(c fcDiskUnmounter, mntPath string) error { globalPath := c.manager.MakeGlobalPDName(*c.fcDisk) err := os.RemoveAll(globalPath) if err != nil { return err } fake.detachCalled = true return nil } func doTestPlugin(t *testing.T, spec *volume.Spec) { tmpDir, err := utiltesting.MkTmpdir("fc_test") if err != nil { t.Fatalf("error creating temp dir: %v", err) } defer os.RemoveAll(tmpDir) plugMgr := volume.VolumePluginMgr{} plugMgr.InitPlugins(ProbeVolumePlugins(), volumetest.NewFakeVolumeHost(tmpDir, nil, nil, "" /* rootContext */)) plug, err := plugMgr.FindPluginByName("kubernetes.io/fc") if err != nil { t.Errorf("Can't find the plugin by name") } fakeManager := NewFakeDiskManager() defer fakeManager.Cleanup() fakeMounter := &mount.FakeMounter{} mounter, err := plug.(*fcPlugin).newMounterInternal(spec, types.UID("poduid"), fakeManager, fakeMounter) if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) } if mounter == nil { t.Errorf("Got a nil Mounter: %v", err) } path := mounter.GetPath() expectedPath := fmt.Sprintf("%s/pods/poduid/volumes/kubernetes.io~fc/vol1", tmpDir) if path != expectedPath { t.Errorf("Unexpected path, expected %q, got: %q", expectedPath, path) } if err := mounter.SetUp(nil); err != nil { t.Errorf("Expected success, got: %v", err) } if _, err := os.Stat(path); err != nil { if os.IsNotExist(err) { t.Errorf("SetUp() failed, volume path not created: %s", path) } else { t.Errorf("SetUp() failed: %v", err) } } if _, err := os.Stat(path); err != nil { if os.IsNotExist(err) { t.Errorf("SetUp() failed, volume path not created: %s", path) } else { t.Errorf("SetUp() failed: %v", err) } } if !fakeManager.attachCalled { t.Errorf("Attach was not called") } fakeManager2 := NewFakeDiskManager() defer fakeManager2.Cleanup() unmounter, err := plug.(*fcPlugin).newUnmounterInternal("vol1", types.UID("poduid"), fakeManager2, fakeMounter) if err != nil { t.Errorf("Failed to make a new Unmounter: %v", err) } if unmounter == nil { t.Errorf("Got a nil Unmounter: %v", err) } if err := unmounter.TearDown(); err != nil { t.Errorf("Expected success, got: %v", err) } if _, err := os.Stat(path); err == nil { t.Errorf("TearDown() failed, volume path still exists: %s", path) } else if !os.IsNotExist(err) { t.Errorf("SetUp() failed: %v", err) } if !fakeManager2.detachCalled { t.Errorf("Detach was not called") } } func TestPluginVolume(t *testing.T) { lun := int32(0) vol := &api.Volume{ Name: "vol1", VolumeSource: api.VolumeSource{ FC: &api.FCVolumeSource{ TargetWWNs: []string{"some_wwn"}, FSType: "ext4", Lun: &lun, }, }, } doTestPlugin(t, volume.NewSpecFromVolume(vol)) } func TestPluginPersistentVolume(t *testing.T) { lun := int32(0) vol := &api.PersistentVolume{ ObjectMeta: api.ObjectMeta{ Name: "vol1", }, Spec: api.PersistentVolumeSpec{ PersistentVolumeSource: api.PersistentVolumeSource{ FC: &api.FCVolumeSource{ TargetWWNs: []string{"some_wwn"}, FSType: "ext4", Lun: &lun, }, }, }, } doTestPlugin(t, volume.NewSpecFromPersistentVolume(vol, false)) } func TestPersistentClaimReadOnlyFlag(t *testing.T) { tmpDir, err := utiltesting.MkTmpdir("fc_test") if err != nil { t.Fatalf("error creating temp dir: %v", err) } defer os.RemoveAll(tmpDir) lun := int32(0) pv := &api.PersistentVolume{ ObjectMeta: api.ObjectMeta{ Name: "pvA", }, Spec: api.PersistentVolumeSpec{ PersistentVolumeSource: api.PersistentVolumeSource{ FC: &api.FCVolumeSource{ TargetWWNs: []string{"some_wwn"}, FSType: "ext4", Lun: &lun, }, }, ClaimRef: &api.ObjectReference{ Name: "claimA", }, }, } claim := &api.PersistentVolumeClaim{ ObjectMeta: api.ObjectMeta{ Name: "claimA", Namespace: "nsA", }, Spec: api.PersistentVolumeClaimSpec{ VolumeName: "pvA", }, Status: api.PersistentVolumeClaimStatus{ Phase: api.ClaimBound, }, } client := fake.NewSimpleClientset(pv, claim) plugMgr := volume.VolumePluginMgr{} plugMgr.InitPlugins(ProbeVolumePlugins(), volumetest.NewFakeVolumeHost(tmpDir, client, nil, "" /* rootContext */)) plug, _ := plugMgr.FindPluginByName(fcPluginName) // readOnly bool is supplied by persistent-claim volume source when its mounter creates other volumes spec := volume.NewSpecFromPersistentVolume(pv, true) pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} mounter, _ := plug.NewMounter(spec, pod, volume.VolumeOptions{}) if !mounter.GetAttributes().ReadOnly { t.Errorf("Expected true for mounter.IsReadOnly") } }
pkg/volume/fc/fc_test.go
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.00020631207735277712, 0.00017202756134793162, 0.0001594467757968232, 0.0001712975645205006, 0.00001058667476172559 ]
{ "id": 3, "code_window": [ "\n", "\t// Create a deployment to delete nginx pods and instead bring up redis-slave pods.\n", "\tdeploymentName, deploymentImageName := \"test-rollover-deployment\", \"redis-slave\"\n", "\tdeploymentReplicas := int32(4)\n" ], "labels": [ "keep", "add", "keep", "keep" ], "after_edit": [ "\t// We use a nonexistent image here, so that we make sure it won't finish\n" ], "file_path": "test/e2e/deployment.go", "type": "add", "edit_start_line_idx": 522 }
/* 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 e2e import ( "fmt" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/annotations" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apis/extensions" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" client "k8s.io/kubernetes/pkg/client/unversioned" adapter "k8s.io/kubernetes/pkg/client/unversioned/adapters/internalclientset" deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util" "k8s.io/kubernetes/pkg/kubectl" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/watch" "k8s.io/kubernetes/test/e2e/framework" ) const ( // nginxImage defined in kubectl.go nginxImageName = "nginx" redisImage = "gcr.io/google_containers/redis:e2e" redisImageName = "redis" ) var _ = framework.KubeDescribe("Deployment", func() { f := framework.NewDefaultFramework("deployment") It("deployment should create new pods", func() { testNewDeployment(f) }) It("RollingUpdateDeployment should delete old pods and create new ones", func() { testRollingUpdateDeployment(f) }) It("RollingUpdateDeployment should scale up and down in the right order", func() { testRollingUpdateDeploymentEvents(f) }) It("RecreateDeployment should delete old pods and create new ones", func() { testRecreateDeployment(f) }) It("deployment should delete old replica sets", func() { testDeploymentCleanUpPolicy(f) }) It("deployment should support rollover", func() { testRolloverDeployment(f) }) It("paused deployment should be ignored by the controller", func() { testPausedDeployment(f) }) It("deployment should support rollback", func() { testRollbackDeployment(f) }) It("deployment should support rollback when there's replica set with no revision", func() { testRollbackDeploymentRSNoRevision(f) }) It("deployment should label adopted RSs and pods", func() { testDeploymentLabelAdopted(f) }) It("paused deployment should be able to scale", func() { testScalePausedDeployment(f) }) It("scaled rollout should not block on annotation check", func() { testScaledRolloutDeployment(f) }) }) func newRS(rsName string, replicas int32, rsPodLabels map[string]string, imageName string, image string) *extensions.ReplicaSet { zero := int64(0) return &extensions.ReplicaSet{ ObjectMeta: api.ObjectMeta{ Name: rsName, }, Spec: extensions.ReplicaSetSpec{ Replicas: replicas, Selector: &unversioned.LabelSelector{MatchLabels: rsPodLabels}, Template: api.PodTemplateSpec{ ObjectMeta: api.ObjectMeta{ Labels: rsPodLabels, }, Spec: api.PodSpec{ TerminationGracePeriodSeconds: &zero, Containers: []api.Container{ { Name: imageName, Image: image, }, }, }, }, }, } } func newDeployment(deploymentName string, replicas int32, podLabels map[string]string, imageName string, image string, strategyType extensions.DeploymentStrategyType, revisionHistoryLimit *int32) *extensions.Deployment { zero := int64(0) return &extensions.Deployment{ ObjectMeta: api.ObjectMeta{ Name: deploymentName, }, Spec: extensions.DeploymentSpec{ Replicas: replicas, Selector: &unversioned.LabelSelector{MatchLabels: podLabels}, Strategy: extensions.DeploymentStrategy{ Type: strategyType, }, RevisionHistoryLimit: revisionHistoryLimit, Template: api.PodTemplateSpec{ ObjectMeta: api.ObjectMeta{ Labels: podLabels, }, Spec: api.PodSpec{ TerminationGracePeriodSeconds: &zero, Containers: []api.Container{ { Name: imageName, Image: image, }, }, }, }, }, } } func newDeploymentRollback(name string, annotations map[string]string, revision int64) *extensions.DeploymentRollback { return &extensions.DeploymentRollback{ Name: name, UpdatedAnnotations: annotations, RollbackTo: extensions.RollbackConfig{Revision: revision}, } } // checkDeploymentRevision checks if the input deployment's and its new replica set's revision and images are as expected. func checkDeploymentRevision(c *clientset.Clientset, ns, deploymentName, revision, imageName, image string) (*extensions.Deployment, *extensions.ReplicaSet) { deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) // Check revision of the new replica set of this deployment newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(newRS.Annotations).NotTo(Equal(nil)) Expect(newRS.Annotations[deploymentutil.RevisionAnnotation]).Should(Equal(revision)) // Check revision of This deployment Expect(deployment.Annotations).NotTo(Equal(nil)) Expect(deployment.Annotations[deploymentutil.RevisionAnnotation]).Should(Equal(revision)) if len(imageName) > 0 { // Check the image the new replica set creates Expect(newRS.Spec.Template.Spec.Containers[0].Name).Should(Equal(imageName)) Expect(newRS.Spec.Template.Spec.Containers[0].Image).Should(Equal(image)) // Check the image the deployment creates Expect(deployment.Spec.Template.Spec.Containers[0].Name).Should(Equal(imageName)) Expect(deployment.Spec.Template.Spec.Containers[0].Image).Should(Equal(image)) } return deployment, newRS } func stopDeployment(c *clientset.Clientset, oldC client.Interface, ns, deploymentName string) { deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) framework.Logf("Deleting deployment %s", deploymentName) reaper, err := kubectl.ReaperFor(extensions.Kind("Deployment"), oldC) Expect(err).NotTo(HaveOccurred()) timeout := 1 * time.Minute err = reaper.Stop(ns, deployment.Name, timeout, api.NewDeleteOptions(0)) Expect(err).NotTo(HaveOccurred()) framework.Logf("Ensuring deployment %s was deleted", deploymentName) _, err = c.Extensions().Deployments(ns).Get(deployment.Name) Expect(err).To(HaveOccurred()) Expect(errors.IsNotFound(err)).To(BeTrue()) framework.Logf("Ensuring deployment %s's RSes were deleted", deploymentName) selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) Expect(err).NotTo(HaveOccurred()) options := api.ListOptions{LabelSelector: selector} rss, err := c.Extensions().ReplicaSets(ns).List(options) Expect(err).NotTo(HaveOccurred()) Expect(rss.Items).Should(HaveLen(0)) framework.Logf("Ensuring deployment %s's Pods were deleted", deploymentName) var pods *api.PodList if err := wait.PollImmediate(time.Second, timeout, func() (bool, error) { pods, err = c.Core().Pods(ns).List(api.ListOptions{}) if err != nil { return false, err } if len(pods.Items) == 0 { return true, nil } return false, nil }); err != nil { framework.Failf("Err : %s\n. Failed to remove deployment %s pods : %+v", err, deploymentName, pods) } } func testNewDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. c := adapter.FromUnversionedClient(f.Client) deploymentName := "test-new-deployment" podLabels := map[string]string{"name": nginxImageName} replicas := int32(1) framework.Logf("Creating simple deployment %s", deploymentName) d := newDeployment(deploymentName, replicas, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) d.Annotations = map[string]string{"test": "should-copy-to-replica-set", annotations.LastAppliedConfigAnnotation: "should-not-copy-to-replica-set"} deploy, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", nginxImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) // Check new RS annotations Expect(newRS.Annotations["test"]).Should(Equal("should-copy-to-replica-set")) Expect(newRS.Annotations[annotations.LastAppliedConfigAnnotation]).Should(Equal("")) Expect(deployment.Annotations["test"]).Should(Equal("should-copy-to-replica-set")) Expect(deployment.Annotations[annotations.LastAppliedConfigAnnotation]).Should(Equal("should-not-copy-to-replica-set")) } func testRollingUpdateDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "sample-pod"} rsPodLabels := map[string]string{ "name": "sample-pod", "pod": nginxImageName, } rsName := "test-rolling-update-controller" replicas := int32(3) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "sample-pod", false, 3) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-rolling-update-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RollingUpdateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", redisImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // There should be 1 old RS (nginx-controller, which is adopted) deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) _, allOldRSs, err := deploymentutil.GetOldReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(len(allOldRSs)).Should(Equal(1)) // The old RS should contain pod-template-hash in its selector, label, and template label Expect(len(allOldRSs[0].Labels[extensions.DefaultDeploymentUniqueLabelKey])).Should(BeNumerically(">", 0)) Expect(len(allOldRSs[0].Spec.Selector.MatchLabels[extensions.DefaultDeploymentUniqueLabelKey])).Should(BeNumerically(">", 0)) Expect(len(allOldRSs[0].Spec.Template.Labels[extensions.DefaultDeploymentUniqueLabelKey])).Should(BeNumerically(">", 0)) } func testRollingUpdateDeploymentEvents(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "sample-pod-2"} rsPodLabels := map[string]string{ "name": "sample-pod-2", "pod": nginxImageName, } rsName := "test-rolling-scale-controller" replicas := int32(1) rsRevision := "3546343826724305832" annotations := make(map[string]string) annotations[deploymentutil.RevisionAnnotation] = rsRevision rs := newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage) rs.Annotations = annotations _, err := c.Extensions().ReplicaSets(ns).Create(rs) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "sample-pod-2", false, 1) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-rolling-scale-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RollingUpdateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 3546343826724305833 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "3546343826724305833", redisImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Verify that the pods were scaled up and down as expected. We use events to verify that. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) framework.WaitForEvents(unversionedClient, ns, deployment, 2) events, err := c.Core().Events(ns).Search(deployment) if err != nil { framework.Logf("error in listing events: %s", err) Expect(err).NotTo(HaveOccurred()) } // There should be 2 events, one to scale up the new ReplicaSet and then to scale down // the old ReplicaSet. Expect(len(events.Items)).Should(Equal(2)) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(newRS).NotTo(Equal(nil)) Expect(events.Items[0].Message).Should(Equal(fmt.Sprintf("Scaled up replica set %s to 1", newRS.Name))) Expect(events.Items[1].Message).Should(Equal(fmt.Sprintf("Scaled down replica set %s to 0", rsName))) } func testRecreateDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "sample-pod-3"} rsPodLabels := map[string]string{ "name": "sample-pod-3", "pod": nginxImageName, } rsName := "test-recreate-controller" replicas := int32(3) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "sample-pod-3", false, 3) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-recreate-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RecreateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", redisImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Verify that the pods were scaled up and down as expected. We use events to verify that. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) framework.WaitForEvents(unversionedClient, ns, deployment, 2) events, err := c.Core().Events(ns).Search(deployment) if err != nil { framework.Logf("error in listing events: %s", err) Expect(err).NotTo(HaveOccurred()) } // There should be 2 events, one to scale up the new ReplicaSet and then to scale down the old ReplicaSet. Expect(len(events.Items)).Should(Equal(2)) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(newRS).NotTo(Equal(nil)) Expect(events.Items[0].Message).Should(Equal(fmt.Sprintf("Scaled down replica set %s to 0", rsName))) Expect(events.Items[1].Message).Should(Equal(fmt.Sprintf("Scaled up replica set %s to 3", newRS.Name))) } // testDeploymentCleanUpPolicy tests that deployment supports cleanup policy func testDeploymentCleanUpPolicy(f *framework.Framework) { ns := f.Namespace.Name unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "cleanup-pod"} rsPodLabels := map[string]string{ "name": "cleanup-pod", "pod": nginxImageName, } rsName := "test-cleanup-controller" replicas := int32(1) revisionHistoryLimit := util.Int32Ptr(0) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "cleanup-pod", false, 1) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-cleanup-deployment" framework.Logf("Creating deployment %s", deploymentName) pods, err := c.Pods(ns).List(api.ListOptions{LabelSelector: labels.Everything()}) if err != nil { Expect(err).NotTo(HaveOccurred(), "Failed to query for pods: %v", err) } options := api.ListOptions{ ResourceVersion: pods.ListMeta.ResourceVersion, } stopCh := make(chan struct{}) w, err := c.Pods(ns).Watch(options) go func() { // There should be only one pod being created, which is the pod with the redis image. // The old RS shouldn't create new pod when deployment controller adding pod template hash label to its selector. numPodCreation := 1 for { select { case event, _ := <-w.ResultChan(): if event.Type != watch.Added { continue } numPodCreation-- if numPodCreation < 0 { framework.Failf("Expect only one pod creation, the second creation event: %#v\n", event) } pod, ok := event.Object.(*api.Pod) if !ok { Fail("Expect event Object to be a pod") } if pod.Spec.Containers[0].Name != redisImageName { framework.Failf("Expect the created pod to have container name %s, got pod %#v\n", redisImageName, pod) } case <-stopCh: return } } }() _, err = c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RollingUpdateDeploymentStrategyType, revisionHistoryLimit)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) err = framework.WaitForDeploymentOldRSsNum(c, ns, deploymentName, int(*revisionHistoryLimit)) Expect(err).NotTo(HaveOccurred()) close(stopCh) } // testRolloverDeployment tests that deployment supports rollover. // i.e. we can change desired state and kick off rolling update, then change desired state again before it finishes. func testRolloverDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) podName := "rollover-pod" deploymentPodLabels := map[string]string{"name": podName} rsPodLabels := map[string]string{ "name": podName, "pod": nginxImageName, } rsName := "test-rollover-controller" rsReplicas := int32(4) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, rsReplicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, podName, false, rsReplicas) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Wait for the required pods to be ready for at least minReadySeconds (be available) deploymentMinReadySeconds := int32(5) err = framework.WaitForPodsReady(c, ns, podName, int(deploymentMinReadySeconds)) Expect(err).NotTo(HaveOccurred()) // Create a deployment to delete nginx pods and instead bring up redis-slave pods. deploymentName, deploymentImageName := "test-rollover-deployment", "redis-slave" deploymentReplicas := int32(4) deploymentImage := "gcr.io/google_samples/gb-redisslave:v1" deploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType framework.Logf("Creating deployment %s", deploymentName) newDeployment := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil) newDeployment.Spec.MinReadySeconds = deploymentMinReadySeconds newDeployment.Spec.Strategy.RollingUpdate = &extensions.RollingUpdateDeployment{ MaxUnavailable: intstr.FromInt(1), MaxSurge: intstr.FromInt(1), } _, err = c.Extensions().Deployments(ns).Create(newDeployment) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Verify that the pods were scaled up and down as expected. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) // Make sure the deployment starts to scale up and down replica sets by checking if its updated replicas >= 1 err = framework.WaitForDeploymentUpdatedReplicasLTE(c, ns, deploymentName, 1, deployment.Generation) // Check if it's updated to revision 1 correctly _, newRS := checkDeploymentRevision(c, ns, deploymentName, "1", deploymentImageName, deploymentImage) // Before the deployment finishes, update the deployment to rollover the above 2 ReplicaSets and bring up redis pods. // If the deployment already finished here, the test would fail. When this happens, increase its minReadySeconds or replicas to prevent it. Expect(newRS.Spec.Replicas).Should(BeNumerically("<", deploymentReplicas)) updatedDeploymentImageName, updatedDeploymentImage := redisImageName, redisImage deployment, err = framework.UpdateDeploymentWithRetries(c, ns, newDeployment.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName update.Spec.Template.Spec.Containers[0].Image = updatedDeploymentImage }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pod template update. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 2 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "2", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) } func testPausedDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) deploymentName := "test-paused-deployment" podLabels := map[string]string{"name": nginxImageName} d := newDeployment(deploymentName, 1, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) d.Spec.Paused = true tgps := int64(20) d.Spec.Template.Spec.TerminationGracePeriodSeconds = &tgps framework.Logf("Creating paused deployment %s", deploymentName) _, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Check that deployment is created fine. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) // Verify that there is no latest state realized for the new deployment. rs, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) if rs != nil { err = fmt.Errorf("unexpected new rs/%s for deployment/%s", rs.Name, deployment.Name) Expect(err).NotTo(HaveOccurred()) } // Update the deployment to run deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Paused = false }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the resume. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) if err != nil { Expect(err).NotTo(HaveOccurred()) } opts := api.ListOptions{LabelSelector: selector} w, err := c.Extensions().ReplicaSets(ns).Watch(opts) Expect(err).NotTo(HaveOccurred()) select { case <-w.ResultChan(): // this is it case <-time.After(time.Minute): err = fmt.Errorf("expected a new replica set to be created") Expect(err).NotTo(HaveOccurred()) } // Pause the deployment and delete the replica set. // The paused deployment shouldn't recreate a new one. deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Paused = true }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pause. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Update the deployment template - the new replicaset should stay the same framework.Logf("Updating paused deployment %q", deploymentName) newTGPS := int64(40) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.TerminationGracePeriodSeconds = &newTGPS }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) framework.Logf("Looking for new replicaset for paused deployment %q (there should be none)", deploymentName) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) if newRS != nil { err = fmt.Errorf("No replica set should match the deployment template but there is %q", newRS.Name) Expect(err).NotTo(HaveOccurred()) } _, allOldRs, err := deploymentutil.GetOldReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) if len(allOldRs) != 1 { err = fmt.Errorf("expected an old replica set") Expect(err).NotTo(HaveOccurred()) } framework.Logf("Comparing deployment diff with old replica set %q", allOldRs[0].Name) if *allOldRs[0].Spec.Template.Spec.TerminationGracePeriodSeconds == newTGPS { err = fmt.Errorf("TerminationGracePeriodSeconds on the replica set should be %d but is %d", tgps, newTGPS) Expect(err).NotTo(HaveOccurred()) } } // testRollbackDeployment tests that a deployment is created (revision 1) and updated (revision 2), and // then rollback to revision 1 (should update template to revision 1, and then update revision 1 to 3), // and then rollback to last revision. func testRollbackDeployment(f *framework.Framework) { ns := f.Namespace.Name unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) podName := "nginx" deploymentPodLabels := map[string]string{"name": podName} // 1. Create a deployment to create nginx pods. deploymentName, deploymentImageName := "test-rollback-deployment", nginxImageName deploymentReplicas := int32(1) deploymentImage := nginxImage deploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType framework.Logf("Creating deployment %s", deploymentName) d := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil) createAnnotation := map[string]string{"action": "create", "author": "minion"} d.Annotations = createAnnotation deploy, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "create" err = framework.CheckNewRSAnnotations(c, ns, deploymentName, createAnnotation) Expect(err).NotTo(HaveOccurred()) // 2. Update the deployment to create redis pods. updatedDeploymentImage := redisImage updatedDeploymentImageName := redisImageName updateAnnotation := map[string]string{"action": "update", "log": "I need to update it"} deployment, err := framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName update.Spec.Template.Spec.Containers[0].Image = updatedDeploymentImage update.Annotations = updateAnnotation }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pod template update. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 2 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "2", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "update" err = framework.CheckNewRSAnnotations(c, ns, deploymentName, updateAnnotation) Expect(err).NotTo(HaveOccurred()) // 3. Update the deploymentRollback to rollback to revision 1 revision := int64(1) framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback := newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackDone in deployment status and check it here // Wait for it to be updated to revision 3 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "3", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "create", after the rollback err = framework.CheckNewRSAnnotations(c, ns, deploymentName, createAnnotation) Expect(err).NotTo(HaveOccurred()) // 4. Update the deploymentRollback to rollback to last revision revision = 0 framework.Logf("rolling back deployment %s to last revision", deploymentName) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 4 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "4", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "update", after the rollback err = framework.CheckNewRSAnnotations(c, ns, deploymentName, updateAnnotation) Expect(err).NotTo(HaveOccurred()) } // testRollbackDeploymentRSNoRevision tests that deployment supports rollback even when there's old replica set without revision. // An old replica set without revision is created, and then a deployment is created (v1). The deployment shouldn't add revision // annotation to the old replica set. Then rollback the deployment to last revision, and it should fail. // Then update the deployment to v2 and rollback it to v1 should succeed, now the deployment // becomes v3. Then rollback the deployment to v10 (doesn't exist in history) should fail. // Finally, rollback the deployment (v3) to v3 should be no-op. // TODO: When we finished reporting rollback status in deployment status, check the rollback status here in each case. func testRollbackDeploymentRSNoRevision(f *framework.Framework) { ns := f.Namespace.Name c := adapter.FromUnversionedClient(f.Client) podName := "nginx" deploymentPodLabels := map[string]string{"name": podName} rsPodLabels := map[string]string{ "name": podName, "pod": nginxImageName, } // Create an old RS without revision rsName := "test-rollback-no-revision-controller" rsReplicas := int32(0) rs := newRS(rsName, rsReplicas, rsPodLabels, nginxImageName, nginxImage) rs.Annotations = make(map[string]string) rs.Annotations["make"] = "difference" _, err := c.Extensions().ReplicaSets(ns).Create(rs) Expect(err).NotTo(HaveOccurred()) // 1. Create a deployment to create nginx pods, which have different template than the replica set created above. deploymentName, deploymentImageName := "test-rollback-no-revision-deployment", nginxImageName deploymentReplicas := int32(1) deploymentImage := nginxImage deploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType framework.Logf("Creating deployment %s", deploymentName) d := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil) deploy, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Check that the replica set we created still doesn't contain revision information rs, err = c.Extensions().ReplicaSets(ns).Get(rsName) Expect(err).NotTo(HaveOccurred()) Expect(rs.Annotations[deploymentutil.RevisionAnnotation]).Should(Equal("")) // 2. Update the deploymentRollback to rollback to last revision // Since there's only 1 revision in history, it should stay as revision 1 revision := int64(0) framework.Logf("rolling back deployment %s to last revision", deploymentName) rollback := newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackRevisionNotFound in deployment status and check it here // The pod template shouldn't change since there's no last revision // Check if the deployment is still revision 1 and still has the old pod template checkDeploymentRevision(c, ns, deploymentName, "1", deploymentImageName, deploymentImage) // 3. Update the deployment to create redis pods. updatedDeploymentImage := redisImage updatedDeploymentImageName := redisImageName deployment, err := framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName update.Spec.Template.Spec.Containers[0].Image = updatedDeploymentImage }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pod template update. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 2 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "2", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // 4. Update the deploymentRollback to rollback to revision 1 revision = 1 framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackDone in deployment status and check it here // The pod template should be updated to the one in revision 1 // Wait for it to be updated to revision 3 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "3", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // 5. Update the deploymentRollback to rollback to revision 10 // Since there's no revision 10 in history, it should stay as revision 3 revision = 10 framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackRevisionNotFound in deployment status and check it here // The pod template shouldn't change since there's no revision 10 // Check if it's still revision 3 and still has the old pod template checkDeploymentRevision(c, ns, deploymentName, "3", deploymentImageName, deploymentImage) // 6. Update the deploymentRollback to rollback to revision 3 // Since it's already revision 3, it should be no-op revision = 3 framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackTemplateUnchanged in deployment status and check it here // The pod template shouldn't change since it's already revision 3 // Check if it's still revision 3 and still has the old pod template checkDeploymentRevision(c, ns, deploymentName, "3", deploymentImageName, deploymentImage) } func testDeploymentLabelAdopted(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. podName := "nginx" podLabels := map[string]string{"name": podName} rsName := "test-adopted-controller" replicas := int32(3) image := nginxImage _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, podLabels, podName, image)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, podName, false, 3) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a nginx deployment to adopt the old rs. deploymentName := "test-adopted-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, podLabels, podName, image, extensions.RollingUpdateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", image) Expect(err).NotTo(HaveOccurred()) // The RS and pods should be relabeled before the status is updated by syncRollingUpdateDeployment err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // There should be no old RSs (overlapping RS) deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) oldRSs, allOldRSs, newRS, err := deploymentutil.GetAllReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(len(oldRSs)).Should(Equal(0)) Expect(len(allOldRSs)).Should(Equal(0)) // New RS should contain pod-template-hash in its selector, label, and template label err = framework.CheckRSHashLabel(newRS) Expect(err).NotTo(HaveOccurred()) // All pods targeted by the deployment should contain pod-template-hash in their labels, and there should be only 3 pods selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) Expect(err).NotTo(HaveOccurred()) options := api.ListOptions{LabelSelector: selector} pods, err := c.Core().Pods(ns).List(options) Expect(err).NotTo(HaveOccurred()) err = framework.CheckPodHashLabel(pods) Expect(err).NotTo(HaveOccurred()) Expect(int32(len(pods.Items))).Should(Equal(replicas)) } func testScalePausedDeployment(f *framework.Framework) { ns := f.Namespace.Name c := adapter.FromUnversionedClient(f.Client) podLabels := map[string]string{"name": nginxImageName} replicas := int32(3) // Create a nginx deployment. deploymentName := "nginx-deployment" d := newDeployment(deploymentName, replicas, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) framework.Logf("Creating deployment %q", deploymentName) _, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Check that deployment is created fine. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) rs, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) // Pause the deployment and try to scale it. deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Paused = true }) Expect(err).NotTo(HaveOccurred()) // Scale the paused deployment. framework.Logf("Scaling up the paused deployment %q", deploymentName) newReplicas := int32(5) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { update.Spec.Replicas = newReplicas }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) rs, err = deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) if rs.Spec.Replicas != newReplicas { err = fmt.Errorf("Expected %d replicas for the new replica set, got %d", newReplicas, rs.Spec.Replicas) Expect(err).NotTo(HaveOccurred()) } } func testScaledRolloutDeployment(f *framework.Framework) { ns := f.Namespace.Name c := adapter.FromUnversionedClient(f.Client) podLabels := map[string]string{"name": nginxImageName} replicas := int32(10) // Create a nginx deployment. deploymentName := "nginx" d := newDeployment(deploymentName, replicas, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) d.Spec.Strategy.RollingUpdate = new(extensions.RollingUpdateDeployment) d.Spec.Strategy.RollingUpdate.MaxSurge = intstr.FromInt(3) d.Spec.Strategy.RollingUpdate.MaxUnavailable = intstr.FromInt(2) By(fmt.Sprintf("Creating deployment %q", deploymentName)) _, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Check that deployment is created fine. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for observed generation %d", deployment.Generation)) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) deployment, err = c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) first, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) // Update the deployment with a non-existent image so that the new replica set will be blocked. By(fmt.Sprintf("Updating deployment %q with a non-existent image", deploymentName)) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Image = "nginx:404" }) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for observed generation %d", deployment.Generation)) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) deployment, err = c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, false) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Checking that the replica sets for %q are synced", deploymentName)) second, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) first, err = c.Extensions().ReplicaSets(first.Namespace).Get(first.Name) Expect(err).NotTo(HaveOccurred()) firstCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), first) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, firstCond) secondCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), second) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, secondCond) By(fmt.Sprintf("Updating the size (up) and template at the same time for deployment %q", deploymentName)) newReplicas := int32(20) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { update.Spec.Replicas = newReplicas update.Spec.Template.Spec.Containers[0].Image = nautilusImage }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) oldRSs, _, rs, err := deploymentutil.GetAllReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) for _, rs := range append(oldRSs, rs) { By(fmt.Sprintf("Ensuring replica set %q has the correct desiredReplicas annotation", rs.Name)) desired, ok := deploymentutil.GetDesiredReplicasAnnotation(rs) if !ok || desired == deployment.Spec.Replicas { continue } err = fmt.Errorf("unexpected desiredReplicas annotation %d for replica set %q", desired, rs.Name) Expect(err).NotTo(HaveOccurred()) } By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Update the deployment with a non-existent image so that the new replica set will be blocked. By(fmt.Sprintf("Updating deployment %q with a non-existent image", deploymentName)) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Image = "nginx:404" }) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for observed generation %d", deployment.Generation)) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) deployment, err = c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, false) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Checking that the replica sets for %q are synced", deploymentName)) oldRs, err := c.Extensions().ReplicaSets(rs.Namespace).Get(rs.Name) Expect(err).NotTo(HaveOccurred()) newRs, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) oldCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), oldRs) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, oldCond) newCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), newRs) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, newCond) By(fmt.Sprintf("Updating the size (down) and template at the same time for deployment %q", deploymentName)) newReplicas = int32(5) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { update.Spec.Replicas = newReplicas update.Spec.Template.Spec.Containers[0].Image = kittenImage }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) oldRSs, _, rs, err = deploymentutil.GetAllReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) for _, rs := range append(oldRSs, rs) { By(fmt.Sprintf("Ensuring replica set %q has the correct desiredReplicas annotation", rs.Name)) desired, ok := deploymentutil.GetDesiredReplicasAnnotation(rs) if !ok || desired == deployment.Spec.Replicas { continue } err = fmt.Errorf("unexpected desiredReplicas annotation %d for replica set %q", desired, rs.Name) Expect(err).NotTo(HaveOccurred()) } By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) }
test/e2e/deployment.go
1
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.9990600943565369, 0.6812758445739746, 0.00016727461479604244, 0.997321605682373, 0.4524376392364502 ]
{ "id": 3, "code_window": [ "\n", "\t// Create a deployment to delete nginx pods and instead bring up redis-slave pods.\n", "\tdeploymentName, deploymentImageName := \"test-rollover-deployment\", \"redis-slave\"\n", "\tdeploymentReplicas := int32(4)\n" ], "labels": [ "keep", "add", "keep", "keep" ], "after_edit": [ "\t// We use a nonexistent image here, so that we make sure it won't finish\n" ], "file_path": "test/e2e/deployment.go", "type": "add", "edit_start_line_idx": 522 }
// +build linux package libcontainer import ( "fmt" "os" "github.com/opencontainers/runc/libcontainer/system" ) func newRestoredProcess(pid int, fds []string) (*restoredProcess, error) { var ( err error ) proc, err := os.FindProcess(pid) if err != nil { return nil, err } started, err := system.GetProcessStartTime(pid) if err != nil { return nil, err } return &restoredProcess{ proc: proc, processStartTime: started, fds: fds, }, nil } type restoredProcess struct { proc *os.Process processStartTime string fds []string } func (p *restoredProcess) start() error { return newGenericError(fmt.Errorf("restored process cannot be started"), SystemError) } func (p *restoredProcess) pid() int { return p.proc.Pid } func (p *restoredProcess) terminate() error { err := p.proc.Kill() if _, werr := p.wait(); err == nil { err = werr } return err } func (p *restoredProcess) wait() (*os.ProcessState, error) { // TODO: how do we wait on the actual process? // maybe use --exec-cmd in criu st, err := p.proc.Wait() if err != nil { return nil, err } return st, nil } func (p *restoredProcess) startTime() (string, error) { return p.processStartTime, nil } func (p *restoredProcess) signal(s os.Signal) error { return p.proc.Signal(s) } func (p *restoredProcess) externalDescriptors() []string { return p.fds } func (p *restoredProcess) setExternalDescriptors(newFds []string) { p.fds = newFds } // nonChildProcess represents a process where the calling process is not // the parent process. This process is created when a factory loads a container from // a persisted state. type nonChildProcess struct { processPid int processStartTime string fds []string } func (p *nonChildProcess) start() error { return newGenericError(fmt.Errorf("restored process cannot be started"), SystemError) } func (p *nonChildProcess) pid() int { return p.processPid } func (p *nonChildProcess) terminate() error { return newGenericError(fmt.Errorf("restored process cannot be terminated"), SystemError) } func (p *nonChildProcess) wait() (*os.ProcessState, error) { return nil, newGenericError(fmt.Errorf("restored process cannot be waited on"), SystemError) } func (p *nonChildProcess) startTime() (string, error) { return p.processStartTime, nil } func (p *nonChildProcess) signal(s os.Signal) error { proc, err := os.FindProcess(p.processPid) if err != nil { return err } return proc.Signal(s) } func (p *nonChildProcess) externalDescriptors() []string { return p.fds } func (p *nonChildProcess) setExternalDescriptors(newFds []string) { p.fds = newFds }
vendor/github.com/opencontainers/runc/libcontainer/restored_process.go
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.00017778496840037405, 0.00016987680282909423, 0.00016394516569562256, 0.00016977831546682864, 0.0000034878685255534947 ]
{ "id": 3, "code_window": [ "\n", "\t// Create a deployment to delete nginx pods and instead bring up redis-slave pods.\n", "\tdeploymentName, deploymentImageName := \"test-rollover-deployment\", \"redis-slave\"\n", "\tdeploymentReplicas := int32(4)\n" ], "labels": [ "keep", "add", "keep", "keep" ], "after_edit": [ "\t// We use a nonexistent image here, so that we make sure it won't finish\n" ], "file_path": "test/e2e/deployment.go", "type": "add", "edit_start_line_idx": 522 }
/* 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 app import ( "errors" "io/ioutil" "strconv" "github.com/golang/glog" "k8s.io/kubernetes/pkg/util/mount" "k8s.io/kubernetes/pkg/util/sysctl" ) type Conntracker interface { SetMax(max int) error SetTCPEstablishedTimeout(seconds int) error } type realConntracker struct{} var readOnlySysFSError = errors.New("ReadOnlySysFS") func (realConntracker) SetMax(max int) error { glog.Infof("Setting nf_conntrack_max to %d", max) if err := sysctl.SetSysctl("net/netfilter/nf_conntrack_max", max); err != nil { return err } // sysfs is expected to be mounted as 'rw'. However, it may be unexpectedly mounted as // 'ro' by docker because of a known docker issue (https://github.com/docker/docker/issues/24000). // Setting conntrack will fail when sysfs is readonly. When that happens, we don't set conntrack // hashsize and return a special error readOnlySysFSError here. The caller should deal with // readOnlySysFSError differently. writable, err := isSysFSWritable() if err != nil { return err } if !writable { return readOnlySysFSError } // TODO: generify this and sysctl to a new sysfs.WriteInt() glog.Infof("Setting conntrack hashsize to %d", max/4) return ioutil.WriteFile("/sys/module/nf_conntrack/parameters/hashsize", []byte(strconv.Itoa(max/4)), 0640) } func (realConntracker) SetTCPEstablishedTimeout(seconds int) error { glog.Infof("Setting nf_conntrack_tcp_timeout_established to %d", seconds) return sysctl.SetSysctl("net/netfilter/nf_conntrack_tcp_timeout_established", seconds) } // isSysFSWritable checks /proc/mounts to see whether sysfs is 'rw' or not. func isSysFSWritable() (bool, error) { const permWritable = "rw" const sysfsDevice = "sysfs" m := mount.New() mountPoints, err := m.List() if err != nil { glog.Errorf("failed to list mount points: %v", err) return false, err } for _, mountPoint := range mountPoints { if mountPoint.Device != sysfsDevice { continue } // Check whether sysfs is 'rw' if len(mountPoint.Opts) > 0 && mountPoint.Opts[0] == permWritable { return true, nil } glog.Errorf("sysfs is not writable: %+v", mountPoint) break } return false, nil }
cmd/kube-proxy/app/conntrack.go
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.00017790196579881012, 0.0001715383114060387, 0.00016740913270041347, 0.0001709992648102343, 0.000003909867700713221 ]
{ "id": 3, "code_window": [ "\n", "\t// Create a deployment to delete nginx pods and instead bring up redis-slave pods.\n", "\tdeploymentName, deploymentImageName := \"test-rollover-deployment\", \"redis-slave\"\n", "\tdeploymentReplicas := int32(4)\n" ], "labels": [ "keep", "add", "keep", "keep" ], "after_edit": [ "\t// We use a nonexistent image here, so that we make sure it won't finish\n" ], "file_path": "test/e2e/deployment.go", "type": "add", "edit_start_line_idx": 522 }
/* 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 certificates provides Registry interface and its RESTStorage // implementation for storing RoleBinding objects. package rolebinding // import "k8s.io/kubernetes/pkg/registry/rolebinding"
pkg/registry/rolebinding/doc.go
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.00017784313240554184, 0.00017454740009270608, 0.00017125168233178556, 0.00017454740009270608, 0.0000032957250368781388 ]
{ "id": 4, "code_window": [ "\tdeploymentName, deploymentImageName := \"test-rollover-deployment\", \"redis-slave\"\n", "\tdeploymentReplicas := int32(4)\n", "\tdeploymentImage := \"gcr.io/google_samples/gb-redisslave:v1\"\n", "\tdeploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType\n", "\tframework.Logf(\"Creating deployment %s\", deploymentName)\n", "\tnewDeployment := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil)\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tdeploymentImage := \"gcr.io/google_samples/gb-redisslave:nonexistent\"\n" ], "file_path": "test/e2e/deployment.go", "type": "replace", "edit_start_line_idx": 524 }
/* 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 e2e import ( "fmt" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/annotations" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apis/extensions" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" client "k8s.io/kubernetes/pkg/client/unversioned" adapter "k8s.io/kubernetes/pkg/client/unversioned/adapters/internalclientset" deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util" "k8s.io/kubernetes/pkg/kubectl" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/watch" "k8s.io/kubernetes/test/e2e/framework" ) const ( // nginxImage defined in kubectl.go nginxImageName = "nginx" redisImage = "gcr.io/google_containers/redis:e2e" redisImageName = "redis" ) var _ = framework.KubeDescribe("Deployment", func() { f := framework.NewDefaultFramework("deployment") It("deployment should create new pods", func() { testNewDeployment(f) }) It("RollingUpdateDeployment should delete old pods and create new ones", func() { testRollingUpdateDeployment(f) }) It("RollingUpdateDeployment should scale up and down in the right order", func() { testRollingUpdateDeploymentEvents(f) }) It("RecreateDeployment should delete old pods and create new ones", func() { testRecreateDeployment(f) }) It("deployment should delete old replica sets", func() { testDeploymentCleanUpPolicy(f) }) It("deployment should support rollover", func() { testRolloverDeployment(f) }) It("paused deployment should be ignored by the controller", func() { testPausedDeployment(f) }) It("deployment should support rollback", func() { testRollbackDeployment(f) }) It("deployment should support rollback when there's replica set with no revision", func() { testRollbackDeploymentRSNoRevision(f) }) It("deployment should label adopted RSs and pods", func() { testDeploymentLabelAdopted(f) }) It("paused deployment should be able to scale", func() { testScalePausedDeployment(f) }) It("scaled rollout should not block on annotation check", func() { testScaledRolloutDeployment(f) }) }) func newRS(rsName string, replicas int32, rsPodLabels map[string]string, imageName string, image string) *extensions.ReplicaSet { zero := int64(0) return &extensions.ReplicaSet{ ObjectMeta: api.ObjectMeta{ Name: rsName, }, Spec: extensions.ReplicaSetSpec{ Replicas: replicas, Selector: &unversioned.LabelSelector{MatchLabels: rsPodLabels}, Template: api.PodTemplateSpec{ ObjectMeta: api.ObjectMeta{ Labels: rsPodLabels, }, Spec: api.PodSpec{ TerminationGracePeriodSeconds: &zero, Containers: []api.Container{ { Name: imageName, Image: image, }, }, }, }, }, } } func newDeployment(deploymentName string, replicas int32, podLabels map[string]string, imageName string, image string, strategyType extensions.DeploymentStrategyType, revisionHistoryLimit *int32) *extensions.Deployment { zero := int64(0) return &extensions.Deployment{ ObjectMeta: api.ObjectMeta{ Name: deploymentName, }, Spec: extensions.DeploymentSpec{ Replicas: replicas, Selector: &unversioned.LabelSelector{MatchLabels: podLabels}, Strategy: extensions.DeploymentStrategy{ Type: strategyType, }, RevisionHistoryLimit: revisionHistoryLimit, Template: api.PodTemplateSpec{ ObjectMeta: api.ObjectMeta{ Labels: podLabels, }, Spec: api.PodSpec{ TerminationGracePeriodSeconds: &zero, Containers: []api.Container{ { Name: imageName, Image: image, }, }, }, }, }, } } func newDeploymentRollback(name string, annotations map[string]string, revision int64) *extensions.DeploymentRollback { return &extensions.DeploymentRollback{ Name: name, UpdatedAnnotations: annotations, RollbackTo: extensions.RollbackConfig{Revision: revision}, } } // checkDeploymentRevision checks if the input deployment's and its new replica set's revision and images are as expected. func checkDeploymentRevision(c *clientset.Clientset, ns, deploymentName, revision, imageName, image string) (*extensions.Deployment, *extensions.ReplicaSet) { deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) // Check revision of the new replica set of this deployment newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(newRS.Annotations).NotTo(Equal(nil)) Expect(newRS.Annotations[deploymentutil.RevisionAnnotation]).Should(Equal(revision)) // Check revision of This deployment Expect(deployment.Annotations).NotTo(Equal(nil)) Expect(deployment.Annotations[deploymentutil.RevisionAnnotation]).Should(Equal(revision)) if len(imageName) > 0 { // Check the image the new replica set creates Expect(newRS.Spec.Template.Spec.Containers[0].Name).Should(Equal(imageName)) Expect(newRS.Spec.Template.Spec.Containers[0].Image).Should(Equal(image)) // Check the image the deployment creates Expect(deployment.Spec.Template.Spec.Containers[0].Name).Should(Equal(imageName)) Expect(deployment.Spec.Template.Spec.Containers[0].Image).Should(Equal(image)) } return deployment, newRS } func stopDeployment(c *clientset.Clientset, oldC client.Interface, ns, deploymentName string) { deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) framework.Logf("Deleting deployment %s", deploymentName) reaper, err := kubectl.ReaperFor(extensions.Kind("Deployment"), oldC) Expect(err).NotTo(HaveOccurred()) timeout := 1 * time.Minute err = reaper.Stop(ns, deployment.Name, timeout, api.NewDeleteOptions(0)) Expect(err).NotTo(HaveOccurred()) framework.Logf("Ensuring deployment %s was deleted", deploymentName) _, err = c.Extensions().Deployments(ns).Get(deployment.Name) Expect(err).To(HaveOccurred()) Expect(errors.IsNotFound(err)).To(BeTrue()) framework.Logf("Ensuring deployment %s's RSes were deleted", deploymentName) selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) Expect(err).NotTo(HaveOccurred()) options := api.ListOptions{LabelSelector: selector} rss, err := c.Extensions().ReplicaSets(ns).List(options) Expect(err).NotTo(HaveOccurred()) Expect(rss.Items).Should(HaveLen(0)) framework.Logf("Ensuring deployment %s's Pods were deleted", deploymentName) var pods *api.PodList if err := wait.PollImmediate(time.Second, timeout, func() (bool, error) { pods, err = c.Core().Pods(ns).List(api.ListOptions{}) if err != nil { return false, err } if len(pods.Items) == 0 { return true, nil } return false, nil }); err != nil { framework.Failf("Err : %s\n. Failed to remove deployment %s pods : %+v", err, deploymentName, pods) } } func testNewDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. c := adapter.FromUnversionedClient(f.Client) deploymentName := "test-new-deployment" podLabels := map[string]string{"name": nginxImageName} replicas := int32(1) framework.Logf("Creating simple deployment %s", deploymentName) d := newDeployment(deploymentName, replicas, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) d.Annotations = map[string]string{"test": "should-copy-to-replica-set", annotations.LastAppliedConfigAnnotation: "should-not-copy-to-replica-set"} deploy, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", nginxImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) // Check new RS annotations Expect(newRS.Annotations["test"]).Should(Equal("should-copy-to-replica-set")) Expect(newRS.Annotations[annotations.LastAppliedConfigAnnotation]).Should(Equal("")) Expect(deployment.Annotations["test"]).Should(Equal("should-copy-to-replica-set")) Expect(deployment.Annotations[annotations.LastAppliedConfigAnnotation]).Should(Equal("should-not-copy-to-replica-set")) } func testRollingUpdateDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "sample-pod"} rsPodLabels := map[string]string{ "name": "sample-pod", "pod": nginxImageName, } rsName := "test-rolling-update-controller" replicas := int32(3) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "sample-pod", false, 3) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-rolling-update-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RollingUpdateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", redisImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // There should be 1 old RS (nginx-controller, which is adopted) deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) _, allOldRSs, err := deploymentutil.GetOldReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(len(allOldRSs)).Should(Equal(1)) // The old RS should contain pod-template-hash in its selector, label, and template label Expect(len(allOldRSs[0].Labels[extensions.DefaultDeploymentUniqueLabelKey])).Should(BeNumerically(">", 0)) Expect(len(allOldRSs[0].Spec.Selector.MatchLabels[extensions.DefaultDeploymentUniqueLabelKey])).Should(BeNumerically(">", 0)) Expect(len(allOldRSs[0].Spec.Template.Labels[extensions.DefaultDeploymentUniqueLabelKey])).Should(BeNumerically(">", 0)) } func testRollingUpdateDeploymentEvents(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "sample-pod-2"} rsPodLabels := map[string]string{ "name": "sample-pod-2", "pod": nginxImageName, } rsName := "test-rolling-scale-controller" replicas := int32(1) rsRevision := "3546343826724305832" annotations := make(map[string]string) annotations[deploymentutil.RevisionAnnotation] = rsRevision rs := newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage) rs.Annotations = annotations _, err := c.Extensions().ReplicaSets(ns).Create(rs) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "sample-pod-2", false, 1) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-rolling-scale-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RollingUpdateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 3546343826724305833 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "3546343826724305833", redisImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Verify that the pods were scaled up and down as expected. We use events to verify that. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) framework.WaitForEvents(unversionedClient, ns, deployment, 2) events, err := c.Core().Events(ns).Search(deployment) if err != nil { framework.Logf("error in listing events: %s", err) Expect(err).NotTo(HaveOccurred()) } // There should be 2 events, one to scale up the new ReplicaSet and then to scale down // the old ReplicaSet. Expect(len(events.Items)).Should(Equal(2)) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(newRS).NotTo(Equal(nil)) Expect(events.Items[0].Message).Should(Equal(fmt.Sprintf("Scaled up replica set %s to 1", newRS.Name))) Expect(events.Items[1].Message).Should(Equal(fmt.Sprintf("Scaled down replica set %s to 0", rsName))) } func testRecreateDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "sample-pod-3"} rsPodLabels := map[string]string{ "name": "sample-pod-3", "pod": nginxImageName, } rsName := "test-recreate-controller" replicas := int32(3) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "sample-pod-3", false, 3) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-recreate-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RecreateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", redisImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Verify that the pods were scaled up and down as expected. We use events to verify that. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) framework.WaitForEvents(unversionedClient, ns, deployment, 2) events, err := c.Core().Events(ns).Search(deployment) if err != nil { framework.Logf("error in listing events: %s", err) Expect(err).NotTo(HaveOccurred()) } // There should be 2 events, one to scale up the new ReplicaSet and then to scale down the old ReplicaSet. Expect(len(events.Items)).Should(Equal(2)) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(newRS).NotTo(Equal(nil)) Expect(events.Items[0].Message).Should(Equal(fmt.Sprintf("Scaled down replica set %s to 0", rsName))) Expect(events.Items[1].Message).Should(Equal(fmt.Sprintf("Scaled up replica set %s to 3", newRS.Name))) } // testDeploymentCleanUpPolicy tests that deployment supports cleanup policy func testDeploymentCleanUpPolicy(f *framework.Framework) { ns := f.Namespace.Name unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "cleanup-pod"} rsPodLabels := map[string]string{ "name": "cleanup-pod", "pod": nginxImageName, } rsName := "test-cleanup-controller" replicas := int32(1) revisionHistoryLimit := util.Int32Ptr(0) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "cleanup-pod", false, 1) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-cleanup-deployment" framework.Logf("Creating deployment %s", deploymentName) pods, err := c.Pods(ns).List(api.ListOptions{LabelSelector: labels.Everything()}) if err != nil { Expect(err).NotTo(HaveOccurred(), "Failed to query for pods: %v", err) } options := api.ListOptions{ ResourceVersion: pods.ListMeta.ResourceVersion, } stopCh := make(chan struct{}) w, err := c.Pods(ns).Watch(options) go func() { // There should be only one pod being created, which is the pod with the redis image. // The old RS shouldn't create new pod when deployment controller adding pod template hash label to its selector. numPodCreation := 1 for { select { case event, _ := <-w.ResultChan(): if event.Type != watch.Added { continue } numPodCreation-- if numPodCreation < 0 { framework.Failf("Expect only one pod creation, the second creation event: %#v\n", event) } pod, ok := event.Object.(*api.Pod) if !ok { Fail("Expect event Object to be a pod") } if pod.Spec.Containers[0].Name != redisImageName { framework.Failf("Expect the created pod to have container name %s, got pod %#v\n", redisImageName, pod) } case <-stopCh: return } } }() _, err = c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RollingUpdateDeploymentStrategyType, revisionHistoryLimit)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) err = framework.WaitForDeploymentOldRSsNum(c, ns, deploymentName, int(*revisionHistoryLimit)) Expect(err).NotTo(HaveOccurred()) close(stopCh) } // testRolloverDeployment tests that deployment supports rollover. // i.e. we can change desired state and kick off rolling update, then change desired state again before it finishes. func testRolloverDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) podName := "rollover-pod" deploymentPodLabels := map[string]string{"name": podName} rsPodLabels := map[string]string{ "name": podName, "pod": nginxImageName, } rsName := "test-rollover-controller" rsReplicas := int32(4) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, rsReplicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, podName, false, rsReplicas) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Wait for the required pods to be ready for at least minReadySeconds (be available) deploymentMinReadySeconds := int32(5) err = framework.WaitForPodsReady(c, ns, podName, int(deploymentMinReadySeconds)) Expect(err).NotTo(HaveOccurred()) // Create a deployment to delete nginx pods and instead bring up redis-slave pods. deploymentName, deploymentImageName := "test-rollover-deployment", "redis-slave" deploymentReplicas := int32(4) deploymentImage := "gcr.io/google_samples/gb-redisslave:v1" deploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType framework.Logf("Creating deployment %s", deploymentName) newDeployment := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil) newDeployment.Spec.MinReadySeconds = deploymentMinReadySeconds newDeployment.Spec.Strategy.RollingUpdate = &extensions.RollingUpdateDeployment{ MaxUnavailable: intstr.FromInt(1), MaxSurge: intstr.FromInt(1), } _, err = c.Extensions().Deployments(ns).Create(newDeployment) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Verify that the pods were scaled up and down as expected. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) // Make sure the deployment starts to scale up and down replica sets by checking if its updated replicas >= 1 err = framework.WaitForDeploymentUpdatedReplicasLTE(c, ns, deploymentName, 1, deployment.Generation) // Check if it's updated to revision 1 correctly _, newRS := checkDeploymentRevision(c, ns, deploymentName, "1", deploymentImageName, deploymentImage) // Before the deployment finishes, update the deployment to rollover the above 2 ReplicaSets and bring up redis pods. // If the deployment already finished here, the test would fail. When this happens, increase its minReadySeconds or replicas to prevent it. Expect(newRS.Spec.Replicas).Should(BeNumerically("<", deploymentReplicas)) updatedDeploymentImageName, updatedDeploymentImage := redisImageName, redisImage deployment, err = framework.UpdateDeploymentWithRetries(c, ns, newDeployment.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName update.Spec.Template.Spec.Containers[0].Image = updatedDeploymentImage }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pod template update. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 2 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "2", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) } func testPausedDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) deploymentName := "test-paused-deployment" podLabels := map[string]string{"name": nginxImageName} d := newDeployment(deploymentName, 1, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) d.Spec.Paused = true tgps := int64(20) d.Spec.Template.Spec.TerminationGracePeriodSeconds = &tgps framework.Logf("Creating paused deployment %s", deploymentName) _, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Check that deployment is created fine. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) // Verify that there is no latest state realized for the new deployment. rs, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) if rs != nil { err = fmt.Errorf("unexpected new rs/%s for deployment/%s", rs.Name, deployment.Name) Expect(err).NotTo(HaveOccurred()) } // Update the deployment to run deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Paused = false }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the resume. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) if err != nil { Expect(err).NotTo(HaveOccurred()) } opts := api.ListOptions{LabelSelector: selector} w, err := c.Extensions().ReplicaSets(ns).Watch(opts) Expect(err).NotTo(HaveOccurred()) select { case <-w.ResultChan(): // this is it case <-time.After(time.Minute): err = fmt.Errorf("expected a new replica set to be created") Expect(err).NotTo(HaveOccurred()) } // Pause the deployment and delete the replica set. // The paused deployment shouldn't recreate a new one. deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Paused = true }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pause. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Update the deployment template - the new replicaset should stay the same framework.Logf("Updating paused deployment %q", deploymentName) newTGPS := int64(40) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.TerminationGracePeriodSeconds = &newTGPS }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) framework.Logf("Looking for new replicaset for paused deployment %q (there should be none)", deploymentName) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) if newRS != nil { err = fmt.Errorf("No replica set should match the deployment template but there is %q", newRS.Name) Expect(err).NotTo(HaveOccurred()) } _, allOldRs, err := deploymentutil.GetOldReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) if len(allOldRs) != 1 { err = fmt.Errorf("expected an old replica set") Expect(err).NotTo(HaveOccurred()) } framework.Logf("Comparing deployment diff with old replica set %q", allOldRs[0].Name) if *allOldRs[0].Spec.Template.Spec.TerminationGracePeriodSeconds == newTGPS { err = fmt.Errorf("TerminationGracePeriodSeconds on the replica set should be %d but is %d", tgps, newTGPS) Expect(err).NotTo(HaveOccurred()) } } // testRollbackDeployment tests that a deployment is created (revision 1) and updated (revision 2), and // then rollback to revision 1 (should update template to revision 1, and then update revision 1 to 3), // and then rollback to last revision. func testRollbackDeployment(f *framework.Framework) { ns := f.Namespace.Name unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) podName := "nginx" deploymentPodLabels := map[string]string{"name": podName} // 1. Create a deployment to create nginx pods. deploymentName, deploymentImageName := "test-rollback-deployment", nginxImageName deploymentReplicas := int32(1) deploymentImage := nginxImage deploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType framework.Logf("Creating deployment %s", deploymentName) d := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil) createAnnotation := map[string]string{"action": "create", "author": "minion"} d.Annotations = createAnnotation deploy, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "create" err = framework.CheckNewRSAnnotations(c, ns, deploymentName, createAnnotation) Expect(err).NotTo(HaveOccurred()) // 2. Update the deployment to create redis pods. updatedDeploymentImage := redisImage updatedDeploymentImageName := redisImageName updateAnnotation := map[string]string{"action": "update", "log": "I need to update it"} deployment, err := framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName update.Spec.Template.Spec.Containers[0].Image = updatedDeploymentImage update.Annotations = updateAnnotation }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pod template update. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 2 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "2", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "update" err = framework.CheckNewRSAnnotations(c, ns, deploymentName, updateAnnotation) Expect(err).NotTo(HaveOccurred()) // 3. Update the deploymentRollback to rollback to revision 1 revision := int64(1) framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback := newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackDone in deployment status and check it here // Wait for it to be updated to revision 3 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "3", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "create", after the rollback err = framework.CheckNewRSAnnotations(c, ns, deploymentName, createAnnotation) Expect(err).NotTo(HaveOccurred()) // 4. Update the deploymentRollback to rollback to last revision revision = 0 framework.Logf("rolling back deployment %s to last revision", deploymentName) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 4 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "4", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "update", after the rollback err = framework.CheckNewRSAnnotations(c, ns, deploymentName, updateAnnotation) Expect(err).NotTo(HaveOccurred()) } // testRollbackDeploymentRSNoRevision tests that deployment supports rollback even when there's old replica set without revision. // An old replica set without revision is created, and then a deployment is created (v1). The deployment shouldn't add revision // annotation to the old replica set. Then rollback the deployment to last revision, and it should fail. // Then update the deployment to v2 and rollback it to v1 should succeed, now the deployment // becomes v3. Then rollback the deployment to v10 (doesn't exist in history) should fail. // Finally, rollback the deployment (v3) to v3 should be no-op. // TODO: When we finished reporting rollback status in deployment status, check the rollback status here in each case. func testRollbackDeploymentRSNoRevision(f *framework.Framework) { ns := f.Namespace.Name c := adapter.FromUnversionedClient(f.Client) podName := "nginx" deploymentPodLabels := map[string]string{"name": podName} rsPodLabels := map[string]string{ "name": podName, "pod": nginxImageName, } // Create an old RS without revision rsName := "test-rollback-no-revision-controller" rsReplicas := int32(0) rs := newRS(rsName, rsReplicas, rsPodLabels, nginxImageName, nginxImage) rs.Annotations = make(map[string]string) rs.Annotations["make"] = "difference" _, err := c.Extensions().ReplicaSets(ns).Create(rs) Expect(err).NotTo(HaveOccurred()) // 1. Create a deployment to create nginx pods, which have different template than the replica set created above. deploymentName, deploymentImageName := "test-rollback-no-revision-deployment", nginxImageName deploymentReplicas := int32(1) deploymentImage := nginxImage deploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType framework.Logf("Creating deployment %s", deploymentName) d := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil) deploy, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Check that the replica set we created still doesn't contain revision information rs, err = c.Extensions().ReplicaSets(ns).Get(rsName) Expect(err).NotTo(HaveOccurred()) Expect(rs.Annotations[deploymentutil.RevisionAnnotation]).Should(Equal("")) // 2. Update the deploymentRollback to rollback to last revision // Since there's only 1 revision in history, it should stay as revision 1 revision := int64(0) framework.Logf("rolling back deployment %s to last revision", deploymentName) rollback := newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackRevisionNotFound in deployment status and check it here // The pod template shouldn't change since there's no last revision // Check if the deployment is still revision 1 and still has the old pod template checkDeploymentRevision(c, ns, deploymentName, "1", deploymentImageName, deploymentImage) // 3. Update the deployment to create redis pods. updatedDeploymentImage := redisImage updatedDeploymentImageName := redisImageName deployment, err := framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName update.Spec.Template.Spec.Containers[0].Image = updatedDeploymentImage }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pod template update. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 2 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "2", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // 4. Update the deploymentRollback to rollback to revision 1 revision = 1 framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackDone in deployment status and check it here // The pod template should be updated to the one in revision 1 // Wait for it to be updated to revision 3 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "3", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // 5. Update the deploymentRollback to rollback to revision 10 // Since there's no revision 10 in history, it should stay as revision 3 revision = 10 framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackRevisionNotFound in deployment status and check it here // The pod template shouldn't change since there's no revision 10 // Check if it's still revision 3 and still has the old pod template checkDeploymentRevision(c, ns, deploymentName, "3", deploymentImageName, deploymentImage) // 6. Update the deploymentRollback to rollback to revision 3 // Since it's already revision 3, it should be no-op revision = 3 framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackTemplateUnchanged in deployment status and check it here // The pod template shouldn't change since it's already revision 3 // Check if it's still revision 3 and still has the old pod template checkDeploymentRevision(c, ns, deploymentName, "3", deploymentImageName, deploymentImage) } func testDeploymentLabelAdopted(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. podName := "nginx" podLabels := map[string]string{"name": podName} rsName := "test-adopted-controller" replicas := int32(3) image := nginxImage _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, podLabels, podName, image)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, podName, false, 3) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a nginx deployment to adopt the old rs. deploymentName := "test-adopted-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, podLabels, podName, image, extensions.RollingUpdateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", image) Expect(err).NotTo(HaveOccurred()) // The RS and pods should be relabeled before the status is updated by syncRollingUpdateDeployment err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // There should be no old RSs (overlapping RS) deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) oldRSs, allOldRSs, newRS, err := deploymentutil.GetAllReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(len(oldRSs)).Should(Equal(0)) Expect(len(allOldRSs)).Should(Equal(0)) // New RS should contain pod-template-hash in its selector, label, and template label err = framework.CheckRSHashLabel(newRS) Expect(err).NotTo(HaveOccurred()) // All pods targeted by the deployment should contain pod-template-hash in their labels, and there should be only 3 pods selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) Expect(err).NotTo(HaveOccurred()) options := api.ListOptions{LabelSelector: selector} pods, err := c.Core().Pods(ns).List(options) Expect(err).NotTo(HaveOccurred()) err = framework.CheckPodHashLabel(pods) Expect(err).NotTo(HaveOccurred()) Expect(int32(len(pods.Items))).Should(Equal(replicas)) } func testScalePausedDeployment(f *framework.Framework) { ns := f.Namespace.Name c := adapter.FromUnversionedClient(f.Client) podLabels := map[string]string{"name": nginxImageName} replicas := int32(3) // Create a nginx deployment. deploymentName := "nginx-deployment" d := newDeployment(deploymentName, replicas, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) framework.Logf("Creating deployment %q", deploymentName) _, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Check that deployment is created fine. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) rs, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) // Pause the deployment and try to scale it. deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Paused = true }) Expect(err).NotTo(HaveOccurred()) // Scale the paused deployment. framework.Logf("Scaling up the paused deployment %q", deploymentName) newReplicas := int32(5) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { update.Spec.Replicas = newReplicas }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) rs, err = deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) if rs.Spec.Replicas != newReplicas { err = fmt.Errorf("Expected %d replicas for the new replica set, got %d", newReplicas, rs.Spec.Replicas) Expect(err).NotTo(HaveOccurred()) } } func testScaledRolloutDeployment(f *framework.Framework) { ns := f.Namespace.Name c := adapter.FromUnversionedClient(f.Client) podLabels := map[string]string{"name": nginxImageName} replicas := int32(10) // Create a nginx deployment. deploymentName := "nginx" d := newDeployment(deploymentName, replicas, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) d.Spec.Strategy.RollingUpdate = new(extensions.RollingUpdateDeployment) d.Spec.Strategy.RollingUpdate.MaxSurge = intstr.FromInt(3) d.Spec.Strategy.RollingUpdate.MaxUnavailable = intstr.FromInt(2) By(fmt.Sprintf("Creating deployment %q", deploymentName)) _, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Check that deployment is created fine. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for observed generation %d", deployment.Generation)) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) deployment, err = c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) first, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) // Update the deployment with a non-existent image so that the new replica set will be blocked. By(fmt.Sprintf("Updating deployment %q with a non-existent image", deploymentName)) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Image = "nginx:404" }) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for observed generation %d", deployment.Generation)) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) deployment, err = c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, false) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Checking that the replica sets for %q are synced", deploymentName)) second, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) first, err = c.Extensions().ReplicaSets(first.Namespace).Get(first.Name) Expect(err).NotTo(HaveOccurred()) firstCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), first) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, firstCond) secondCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), second) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, secondCond) By(fmt.Sprintf("Updating the size (up) and template at the same time for deployment %q", deploymentName)) newReplicas := int32(20) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { update.Spec.Replicas = newReplicas update.Spec.Template.Spec.Containers[0].Image = nautilusImage }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) oldRSs, _, rs, err := deploymentutil.GetAllReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) for _, rs := range append(oldRSs, rs) { By(fmt.Sprintf("Ensuring replica set %q has the correct desiredReplicas annotation", rs.Name)) desired, ok := deploymentutil.GetDesiredReplicasAnnotation(rs) if !ok || desired == deployment.Spec.Replicas { continue } err = fmt.Errorf("unexpected desiredReplicas annotation %d for replica set %q", desired, rs.Name) Expect(err).NotTo(HaveOccurred()) } By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Update the deployment with a non-existent image so that the new replica set will be blocked. By(fmt.Sprintf("Updating deployment %q with a non-existent image", deploymentName)) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Image = "nginx:404" }) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for observed generation %d", deployment.Generation)) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) deployment, err = c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, false) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Checking that the replica sets for %q are synced", deploymentName)) oldRs, err := c.Extensions().ReplicaSets(rs.Namespace).Get(rs.Name) Expect(err).NotTo(HaveOccurred()) newRs, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) oldCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), oldRs) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, oldCond) newCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), newRs) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, newCond) By(fmt.Sprintf("Updating the size (down) and template at the same time for deployment %q", deploymentName)) newReplicas = int32(5) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { update.Spec.Replicas = newReplicas update.Spec.Template.Spec.Containers[0].Image = kittenImage }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) oldRSs, _, rs, err = deploymentutil.GetAllReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) for _, rs := range append(oldRSs, rs) { By(fmt.Sprintf("Ensuring replica set %q has the correct desiredReplicas annotation", rs.Name)) desired, ok := deploymentutil.GetDesiredReplicasAnnotation(rs) if !ok || desired == deployment.Spec.Replicas { continue } err = fmt.Errorf("unexpected desiredReplicas annotation %d for replica set %q", desired, rs.Name) Expect(err).NotTo(HaveOccurred()) } By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) }
test/e2e/deployment.go
1
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.9984686970710754, 0.25249168276786804, 0.0001644928997848183, 0.006668150424957275, 0.41016557812690735 ]
{ "id": 4, "code_window": [ "\tdeploymentName, deploymentImageName := \"test-rollover-deployment\", \"redis-slave\"\n", "\tdeploymentReplicas := int32(4)\n", "\tdeploymentImage := \"gcr.io/google_samples/gb-redisslave:v1\"\n", "\tdeploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType\n", "\tframework.Logf(\"Creating deployment %s\", deploymentName)\n", "\tnewDeployment := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil)\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tdeploymentImage := \"gcr.io/google_samples/gb-redisslave:nonexistent\"\n" ], "file_path": "test/e2e/deployment.go", "type": "replace", "edit_start_line_idx": 524 }
The MIT License (MIT) Copyright (c) 2013 Phillip Bond 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/bitbucket.org/bertimus9/systemstat/LICENSE
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.00017895355995278805, 0.0001738100399961695, 0.00017051585018634796, 0.00017196068074554205, 0.000003684544935822487 ]
{ "id": 4, "code_window": [ "\tdeploymentName, deploymentImageName := \"test-rollover-deployment\", \"redis-slave\"\n", "\tdeploymentReplicas := int32(4)\n", "\tdeploymentImage := \"gcr.io/google_samples/gb-redisslave:v1\"\n", "\tdeploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType\n", "\tframework.Logf(\"Creating deployment %s\", deploymentName)\n", "\tnewDeployment := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil)\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tdeploymentImage := \"gcr.io/google_samples/gb-redisslave:nonexistent\"\n" ], "file_path": "test/e2e/deployment.go", "type": "replace", "edit_start_line_idx": 524 }
<!-- BEGIN MUNGE: UNVERSIONED_WARNING --> <!-- BEGIN STRIP_FOR_RELEASE --> <img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/kubernetes/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.3/docs/user-guide/config-best-practices.md). Documentation for other releases can be found at [releases.k8s.io](http://releases.k8s.io). </strong> -- <!-- END STRIP_FOR_RELEASE --> <!-- END MUNGE: UNVERSIONED_WARNING --> This file has moved to: http://kubernetes.github.io/docs/user-guide/config-best-practices/ <!-- BEGIN MUNGE: GENERATED_ANALYTICS --> [![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/config-best-practices.md?pixel)]() <!-- END MUNGE: GENERATED_ANALYTICS -->
docs/user-guide/config-best-practices.md
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.00017051585018634796, 0.00016800223966129124, 0.0001640730770304799, 0.00016921330825425684, 0.000002505042175471317 ]
{ "id": 4, "code_window": [ "\tdeploymentName, deploymentImageName := \"test-rollover-deployment\", \"redis-slave\"\n", "\tdeploymentReplicas := int32(4)\n", "\tdeploymentImage := \"gcr.io/google_samples/gb-redisslave:v1\"\n", "\tdeploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType\n", "\tframework.Logf(\"Creating deployment %s\", deploymentName)\n", "\tnewDeployment := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil)\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tdeploymentImage := \"gcr.io/google_samples/gb-redisslave:nonexistent\"\n" ], "file_path": "test/e2e/deployment.go", "type": "replace", "edit_start_line_idx": 524 }
/* 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 persistentvolume import ( "errors" "testing" "k8s.io/kubernetes/pkg/api" ) // Test single call to syncVolume, expecting recycling to happen. // 1. Fill in the controller with initial data // 2. Call the syncVolume *once*. // 3. Compare resulting volumes with expected volumes. func TestDeleteSync(t *testing.T) { tests := []controllerTest{ { // delete volume bound by controller "8-1 - successful delete", newVolumeArray("volume8-1", "1Gi", "uid8-1", "claim8-1", api.VolumeBound, api.PersistentVolumeReclaimDelete, annBoundByController), novolumes, noclaims, noclaims, noevents, noerrors, // Inject deleter into the controller and call syncVolume. The // deleter simulates one delete() call that succeeds. wrapTestWithControllerConfig(operationDelete, []error{nil}, testSyncVolume), }, { // delete volume bound by user "8-2 - successful delete with prebound volume", newVolumeArray("volume8-2", "1Gi", "uid8-2", "claim8-2", api.VolumeBound, api.PersistentVolumeReclaimDelete), novolumes, noclaims, noclaims, noevents, noerrors, // Inject deleter into the controller and call syncVolume. The // deleter simulates one delete() call that succeeds. wrapTestWithControllerConfig(operationDelete, []error{nil}, testSyncVolume), }, { // delete failure - plugin not found "8-3 - plugin not found", newVolumeArray("volume8-3", "1Gi", "uid8-3", "claim8-3", api.VolumeBound, api.PersistentVolumeReclaimDelete), withMessage("Error getting deleter volume plugin for volume \"volume8-3\": no volume plugin matched", newVolumeArray("volume8-3", "1Gi", "uid8-3", "claim8-3", api.VolumeFailed, api.PersistentVolumeReclaimDelete)), noclaims, noclaims, []string{"Warning VolumeFailedDelete"}, noerrors, testSyncVolume, }, { // delete failure - newDeleter returns error "8-4 - newDeleter returns error", newVolumeArray("volume8-4", "1Gi", "uid8-4", "claim8-4", api.VolumeBound, api.PersistentVolumeReclaimDelete), withMessage("Failed to create deleter for volume \"volume8-4\": Mock plugin error: no deleteCalls configured", newVolumeArray("volume8-4", "1Gi", "uid8-4", "claim8-4", api.VolumeFailed, api.PersistentVolumeReclaimDelete)), noclaims, noclaims, []string{"Warning VolumeFailedDelete"}, noerrors, wrapTestWithControllerConfig(operationDelete, []error{}, testSyncVolume), }, { // delete failure - delete() returns error "8-5 - delete returns error", newVolumeArray("volume8-5", "1Gi", "uid8-5", "claim8-5", api.VolumeBound, api.PersistentVolumeReclaimDelete), withMessage("Delete of volume \"volume8-5\" failed: Mock delete error", newVolumeArray("volume8-5", "1Gi", "uid8-5", "claim8-5", api.VolumeFailed, api.PersistentVolumeReclaimDelete)), noclaims, noclaims, []string{"Warning VolumeFailedDelete"}, noerrors, wrapTestWithControllerConfig(operationDelete, []error{errors.New("Mock delete error")}, testSyncVolume), }, { // delete success(?) - volume is deleted before doDelete() starts "8-6 - volume is deleted before deleting", newVolumeArray("volume8-6", "1Gi", "uid8-6", "claim8-6", api.VolumeBound, api.PersistentVolumeReclaimDelete), novolumes, noclaims, noclaims, noevents, noerrors, wrapTestWithInjectedOperation(wrapTestWithControllerConfig(operationDelete, []error{}, testSyncVolume), func(ctrl *PersistentVolumeController, reactor *volumeReactor) { // Delete the volume before delete operation starts reactor.lock.Lock() delete(reactor.volumes, "volume8-6") reactor.lock.Unlock() }), }, { // delete success(?) - volume is bound just at the time doDelete() // starts. This simulates "volume no longer needs recycling, // skipping". "8-7 - volume is bound before deleting", newVolumeArray("volume8-7", "1Gi", "uid8-7", "claim8-7", api.VolumeBound, api.PersistentVolumeReclaimDelete, annBoundByController), newVolumeArray("volume8-7", "1Gi", "uid8-7", "claim8-7", api.VolumeBound, api.PersistentVolumeReclaimDelete, annBoundByController), noclaims, newClaimArray("claim8-7", "uid8-7", "10Gi", "volume8-7", api.ClaimBound), noevents, noerrors, wrapTestWithInjectedOperation(wrapTestWithControllerConfig(operationDelete, []error{}, testSyncVolume), func(ctrl *PersistentVolumeController, reactor *volumeReactor) { reactor.lock.Lock() defer reactor.lock.Unlock() // Bind the volume to resurrected claim (this should never // happen) claim := newClaim("claim8-7", "uid8-7", "10Gi", "volume8-7", api.ClaimBound) reactor.claims[claim.Name] = claim ctrl.claims.Add(claim) volume := reactor.volumes["volume8-7"] volume.Status.Phase = api.VolumeBound }), }, { // delete success - volume bound by user is deleted, while a new // claim is created with another UID. "8-9 - prebound volume is deleted while the claim exists", newVolumeArray("volume8-9", "1Gi", "uid8-9", "claim8-9", api.VolumeBound, api.PersistentVolumeReclaimDelete), novolumes, newClaimArray("claim8-9", "uid8-9-x", "10Gi", "", api.ClaimPending), newClaimArray("claim8-9", "uid8-9-x", "10Gi", "", api.ClaimPending), noevents, noerrors, // Inject deleter into the controller and call syncVolume. The // deleter simulates one delete() call that succeeds. wrapTestWithControllerConfig(operationDelete, []error{nil}, testSyncVolume), }, } runSyncTests(t, tests) } // Test multiple calls to syncClaim/syncVolume and periodic sync of all // volume/claims. The test follows this pattern: // 0. Load the controller with initial data. // 1. Call controllerTest.testCall() once as in TestSync() // 2. For all volumes/claims changed by previous syncVolume/syncClaim calls, // call appropriate syncVolume/syncClaim (simulating "volume/claim changed" // events). Go to 2. if these calls change anything. // 3. When all changes are processed and no new changes were made, call // syncVolume/syncClaim on all volumes/claims (simulating "periodic sync"). // 4. If some changes were done by step 3., go to 2. (simulation of // "volume/claim updated" events, eventually performing step 3. again) // 5. When 3. does not do any changes, finish the tests and compare final set // of volumes/claims with expected claims/volumes and report differences. // Some limit of calls in enforced to prevent endless loops. func TestDeleteMultiSync(t *testing.T) { tests := []controllerTest{ { // delete failure - delete returns error. The controller should // try again. "9-1 - delete returns error", newVolumeArray("volume9-1", "1Gi", "uid9-1", "claim9-1", api.VolumeBound, api.PersistentVolumeReclaimDelete), novolumes, noclaims, noclaims, []string{"Warning VolumeFailedDelete"}, noerrors, wrapTestWithControllerConfig(operationDelete, []error{errors.New("Mock delete error"), nil}, testSyncVolume), }, } runMultisyncTests(t, tests) }
pkg/controller/volume/persistentvolume/delete_test.go
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.0001778824662324041, 0.00017159190610982478, 0.00016427361697424203, 0.00017169116472359747, 0.0000035435905374470167 ]
{ "id": 5, "code_window": [ "\tdeploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType\n", "\tframework.Logf(\"Creating deployment %s\", deploymentName)\n", "\tnewDeployment := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil)\n", "\tnewDeployment.Spec.MinReadySeconds = deploymentMinReadySeconds\n", "\tnewDeployment.Spec.Strategy.RollingUpdate = &extensions.RollingUpdateDeployment{\n", "\t\tMaxUnavailable: intstr.FromInt(1),\n", "\t\tMaxSurge: intstr.FromInt(1),\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "test/e2e/deployment.go", "type": "replace", "edit_start_line_idx": 528 }
/* 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 util import ( "fmt" "sort" "strconv" "time" "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/annotations" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apis/extensions" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/errors" "k8s.io/kubernetes/pkg/util/integer" intstrutil "k8s.io/kubernetes/pkg/util/intstr" labelsutil "k8s.io/kubernetes/pkg/util/labels" podutil "k8s.io/kubernetes/pkg/util/pod" rsutil "k8s.io/kubernetes/pkg/util/replicaset" "k8s.io/kubernetes/pkg/util/wait" ) const ( // RevisionAnnotation is the revision annotation of a deployment's replica sets which records its rollout sequence RevisionAnnotation = "deployment.kubernetes.io/revision" // DesiredReplicasAnnotation is the desired replicas for a deployment recorded as an annotation // in its replica sets. Helps in separating scaling events from the rollout process and for // determining if the new replica set for a deployment is really saturated. DesiredReplicasAnnotation = "deployment.kubernetes.io/desired-replicas" // MaxReplicasAnnotation is the maximum replicas a deployment can have at a given point, which // is deployment.spec.replicas + maxSurge. Used by the underlying replica sets to estimate their // proportions in case the deployment has surge replicas. MaxReplicasAnnotation = "deployment.kubernetes.io/max-replicas" // RollbackRevisionNotFound is not found rollback event reason RollbackRevisionNotFound = "DeploymentRollbackRevisionNotFound" // RollbackTemplateUnchanged is the template unchanged rollback event reason RollbackTemplateUnchanged = "DeploymentRollbackTemplateUnchanged" // RollbackDone is the done rollback event reason RollbackDone = "DeploymentRollback" ) // MaxRevision finds the highest revision in the replica sets func MaxRevision(allRSs []*extensions.ReplicaSet) int64 { max := int64(0) for _, rs := range allRSs { if v, err := Revision(rs); err != nil { // Skip the replica sets when it failed to parse their revision information glog.V(4).Infof("Error: %v. Couldn't parse revision for replica set %#v, deployment controller will skip it when reconciling revisions.", err, rs) } else if v > max { max = v } } return max } // LastRevision finds the second max revision number in all replica sets (the last revision) func LastRevision(allRSs []*extensions.ReplicaSet) int64 { max, secMax := int64(0), int64(0) for _, rs := range allRSs { if v, err := Revision(rs); err != nil { // Skip the replica sets when it failed to parse their revision information glog.V(4).Infof("Error: %v. Couldn't parse revision for replica set %#v, deployment controller will skip it when reconciling revisions.", err, rs) } else if v >= max { secMax = max max = v } else if v > secMax { secMax = v } } return secMax } // SetNewReplicaSetAnnotations sets new replica set's annotations appropriately by updating its revision and // copying required deployment annotations to it; it returns true if replica set's annotation is changed. func SetNewReplicaSetAnnotations(deployment *extensions.Deployment, newRS *extensions.ReplicaSet, newRevision string, exists bool) bool { // First, copy deployment's annotations (except for apply and revision annotations) annotationChanged := copyDeploymentAnnotationsToReplicaSet(deployment, newRS) // Then, update replica set's revision annotation if newRS.Annotations == nil { newRS.Annotations = make(map[string]string) } // The newRS's revision should be the greatest among all RSes. Usually, its revision number is newRevision (the max revision number // of all old RSes + 1). However, it's possible that some of the old RSes are deleted after the newRS revision being updated, and // newRevision becomes smaller than newRS's revision. We should only update newRS revision when it's smaller than newRevision. if newRS.Annotations[RevisionAnnotation] < newRevision { newRS.Annotations[RevisionAnnotation] = newRevision annotationChanged = true glog.V(4).Infof("Updating replica set %q revision to %s", newRS.Name, newRevision) } if !exists && SetReplicasAnnotations(newRS, deployment.Spec.Replicas, deployment.Spec.Replicas+MaxSurge(*deployment)) { annotationChanged = true } return annotationChanged } var annotationsToSkip = map[string]bool{ annotations.LastAppliedConfigAnnotation: true, RevisionAnnotation: true, DesiredReplicasAnnotation: true, MaxReplicasAnnotation: true, } // skipCopyAnnotation returns true if we should skip copying the annotation with the given annotation key // TODO: How to decide which annotations should / should not be copied? // See https://github.com/kubernetes/kubernetes/pull/20035#issuecomment-179558615 func skipCopyAnnotation(key string) bool { return annotationsToSkip[key] } // copyDeploymentAnnotationsToReplicaSet copies deployment's annotations to replica set's annotations, // and returns true if replica set's annotation is changed. // Note that apply and revision annotations are not copied. func copyDeploymentAnnotationsToReplicaSet(deployment *extensions.Deployment, rs *extensions.ReplicaSet) bool { rsAnnotationsChanged := false if rs.Annotations == nil { rs.Annotations = make(map[string]string) } for k, v := range deployment.Annotations { // newRS revision is updated automatically in getNewReplicaSet, and the deployment's revision number is then updated // by copying its newRS revision number. We should not copy deployment's revision to its newRS, since the update of // deployment revision number may fail (revision becomes stale) and the revision number in newRS is more reliable. if skipCopyAnnotation(k) || rs.Annotations[k] == v { continue } rs.Annotations[k] = v rsAnnotationsChanged = true } return rsAnnotationsChanged } // SetDeploymentAnnotationsTo sets deployment's annotations as given RS's annotations. // This action should be done if and only if the deployment is rolling back to this rs. // Note that apply and revision annotations are not changed. func SetDeploymentAnnotationsTo(deployment *extensions.Deployment, rollbackToRS *extensions.ReplicaSet) { deployment.Annotations = getSkippedAnnotations(deployment.Annotations) for k, v := range rollbackToRS.Annotations { if !skipCopyAnnotation(k) { deployment.Annotations[k] = v } } } func getSkippedAnnotations(annotations map[string]string) map[string]string { skippedAnnotations := make(map[string]string) for k, v := range annotations { if skipCopyAnnotation(k) { skippedAnnotations[k] = v } } return skippedAnnotations } // FindActiveOrLatest returns the only active or the latest replica set in case there is at most one active // replica set. If there are more active replica sets, then we should proportionally scale them. func FindActiveOrLatest(newRS *extensions.ReplicaSet, oldRSs []*extensions.ReplicaSet) *extensions.ReplicaSet { if newRS == nil && len(oldRSs) == 0 { return nil } sort.Sort(sort.Reverse(controller.ReplicaSetsByCreationTimestamp(oldRSs))) allRSs := controller.FilterActiveReplicaSets(append(oldRSs, newRS)) switch len(allRSs) { case 0: // If there is no active replica set then we should return the newest. if newRS != nil { return newRS } return oldRSs[0] case 1: return allRSs[0] default: return nil } } // GetDesiredReplicasAnnotation returns the number of desired replicas func GetDesiredReplicasAnnotation(rs *extensions.ReplicaSet) (int32, bool) { return getIntFromAnnotation(rs, DesiredReplicasAnnotation) } func getMaxReplicasAnnotation(rs *extensions.ReplicaSet) (int32, bool) { return getIntFromAnnotation(rs, MaxReplicasAnnotation) } func getIntFromAnnotation(rs *extensions.ReplicaSet, annotationKey string) (int32, bool) { annotationValue, ok := rs.Annotations[annotationKey] if !ok { return int32(0), false } intValue, err := strconv.Atoi(annotationValue) if err != nil { glog.Warningf("Cannot convert the value %q with annotation key %q for the replica set %q", annotationValue, annotationKey, rs.Name) return int32(0), false } return int32(intValue), true } // SetReplicasAnnotations sets the desiredReplicas and maxReplicas into the annotations func SetReplicasAnnotations(rs *extensions.ReplicaSet, desiredReplicas, maxReplicas int32) bool { updated := false if rs.Annotations == nil { rs.Annotations = make(map[string]string) } desiredString := fmt.Sprintf("%d", desiredReplicas) if hasString := rs.Annotations[DesiredReplicasAnnotation]; hasString != desiredString { rs.Annotations[DesiredReplicasAnnotation] = desiredString updated = true } maxString := fmt.Sprintf("%d", maxReplicas) if hasString := rs.Annotations[MaxReplicasAnnotation]; hasString != maxString { rs.Annotations[MaxReplicasAnnotation] = maxString updated = true } return updated } // MaxUnavailable returns the maximum unavailable pods a rolling deployment can take. func MaxUnavailable(deployment extensions.Deployment) int32 { if !IsRollingUpdate(&deployment) { return int32(0) } // Error caught by validation _, maxUnavailable, _ := ResolveFenceposts(&deployment.Spec.Strategy.RollingUpdate.MaxSurge, &deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, deployment.Spec.Replicas) return maxUnavailable } // MaxSurge returns the maximum surge pods a rolling deployment can take. func MaxSurge(deployment extensions.Deployment) int32 { if !IsRollingUpdate(&deployment) { return int32(0) } // Error caught by validation maxSurge, _, _ := ResolveFenceposts(&deployment.Spec.Strategy.RollingUpdate.MaxSurge, &deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, deployment.Spec.Replicas) return maxSurge } // GetProportion will estimate the proportion for the provided replica set using 1. the current size // of the parent deployment, 2. the replica count that needs be added on the replica sets of the // deployment, and 3. the total replicas added in the replica sets of the deployment so far. func GetProportion(rs *extensions.ReplicaSet, d extensions.Deployment, deploymentReplicasToAdd, deploymentReplicasAdded int32) int32 { if rs == nil || rs.Spec.Replicas == 0 || deploymentReplicasToAdd == 0 || deploymentReplicasToAdd == deploymentReplicasAdded { return int32(0) } rsFraction := getReplicaSetFraction(*rs, d) allowed := deploymentReplicasToAdd - deploymentReplicasAdded if deploymentReplicasToAdd > 0 { // Use the minimum between the replica set fraction and the maximum allowed replicas // when scaling up. This way we ensure we will not scale up more than the allowed // replicas we can add. return integer.Int32Min(rsFraction, allowed) } // Use the maximum between the replica set fraction and the maximum allowed replicas // when scaling down. This way we ensure we will not scale down more than the allowed // replicas we can remove. return integer.Int32Max(rsFraction, allowed) } // getReplicaSetFraction estimates the fraction of replicas a replica set can have in // 1. a scaling event during a rollout or 2. when scaling a paused deployment. func getReplicaSetFraction(rs extensions.ReplicaSet, d extensions.Deployment) int32 { // If we are scaling down to zero then the fraction of this replica set is its whole size (negative) if d.Spec.Replicas == int32(0) { return -rs.Spec.Replicas } deploymentReplicas := d.Spec.Replicas + MaxSurge(d) annotatedReplicas, ok := getMaxReplicasAnnotation(&rs) if !ok { // If we cannot find the annotation then fallback to the current deployment size. Note that this // will not be an accurate proportion estimation in case other replica sets have different values // which means that the deployment was scaled at some point but we at least will stay in limits // due to the min-max comparisons in getProportion. annotatedReplicas = d.Status.Replicas } // We should never proportionally scale up from zero which means rs.spec.replicas and annotatedReplicas // will never be zero here. newRSsize := (float64(rs.Spec.Replicas * deploymentReplicas)) / float64(annotatedReplicas) return integer.RoundToInt32(newRSsize) - rs.Spec.Replicas } // GetAllReplicaSets returns the old and new replica sets targeted by the given Deployment. It gets PodList and ReplicaSetList from client interface. // Note that the first set of old replica sets doesn't include the ones with no pods, and the second set of old replica sets include all old replica sets. // The third returned value is the new replica set, and it may be nil if it doesn't exist yet. func GetAllReplicaSets(deployment *extensions.Deployment, c clientset.Interface) ([]*extensions.ReplicaSet, []*extensions.ReplicaSet, *extensions.ReplicaSet, error) { rsList, err := listReplicaSets(deployment, c) if err != nil { return nil, nil, nil, err } podList, err := listPods(deployment, c) if err != nil { return nil, nil, nil, err } oldRSes, allOldRSes, err := FindOldReplicaSets(deployment, rsList, podList) if err != nil { return nil, nil, nil, err } newRS, err := FindNewReplicaSet(deployment, rsList) if err != nil { return nil, nil, nil, err } return oldRSes, allOldRSes, newRS, nil } // GetOldReplicaSets returns the old replica sets targeted by the given Deployment; get PodList and ReplicaSetList from client interface. // Note that the first set of old replica sets doesn't include the ones with no pods, and the second set of old replica sets include all old replica sets. func GetOldReplicaSets(deployment *extensions.Deployment, c clientset.Interface) ([]*extensions.ReplicaSet, []*extensions.ReplicaSet, error) { rsList, err := listReplicaSets(deployment, c) if err != nil { return nil, nil, err } podList, err := listPods(deployment, c) if err != nil { return nil, nil, err } return FindOldReplicaSets(deployment, rsList, podList) } // GetNewReplicaSet returns a replica set that matches the intent of the given deployment; get ReplicaSetList from client interface. // Returns nil if the new replica set doesn't exist yet. func GetNewReplicaSet(deployment *extensions.Deployment, c clientset.Interface) (*extensions.ReplicaSet, error) { rsList, err := listReplicaSets(deployment, c) if err != nil { return nil, err } return FindNewReplicaSet(deployment, rsList) } // listReplicaSets lists all RSes the given deployment targets with the given client interface. func listReplicaSets(deployment *extensions.Deployment, c clientset.Interface) ([]extensions.ReplicaSet, error) { return ListReplicaSets(deployment, func(namespace string, options api.ListOptions) ([]extensions.ReplicaSet, error) { rsList, err := c.Extensions().ReplicaSets(namespace).List(options) return rsList.Items, err }) } // listReplicaSets lists all Pods the given deployment targets with the given client interface. func listPods(deployment *extensions.Deployment, c clientset.Interface) (*api.PodList, error) { return ListPods(deployment, func(namespace string, options api.ListOptions) (*api.PodList, error) { return c.Core().Pods(namespace).List(options) }) } // TODO: switch this to full namespacers type rsListFunc func(string, api.ListOptions) ([]extensions.ReplicaSet, error) type podListFunc func(string, api.ListOptions) (*api.PodList, error) // ListReplicaSets returns a slice of RSes the given deployment targets. func ListReplicaSets(deployment *extensions.Deployment, getRSList rsListFunc) ([]extensions.ReplicaSet, error) { // TODO: Right now we list replica sets by their labels. We should list them by selector, i.e. the replica set's selector // should be a superset of the deployment's selector, see https://github.com/kubernetes/kubernetes/issues/19830; // or use controllerRef, see https://github.com/kubernetes/kubernetes/issues/2210 namespace := deployment.Namespace selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) if err != nil { return nil, err } options := api.ListOptions{LabelSelector: selector} return getRSList(namespace, options) } // ListPods returns a list of pods the given deployment targets. func ListPods(deployment *extensions.Deployment, getPodList podListFunc) (*api.PodList, error) { namespace := deployment.Namespace selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) if err != nil { return nil, err } options := api.ListOptions{LabelSelector: selector} return getPodList(namespace, options) } // equalIgnoreHash returns true if two given podTemplateSpec are equal, ignoring the diff in value of Labels[pod-template-hash] // We ignore pod-template-hash because the hash result would be different upon podTemplateSpec API changes // (e.g. the addition of a new field will cause the hash code to change) // Note that we assume input podTemplateSpecs contain non-empty labels func equalIgnoreHash(template1, template2 api.PodTemplateSpec) (bool, error) { // The podTemplateSpec must have a non-empty label so that label selectors can find them. // This is checked by validation (of resources contain a podTemplateSpec). if len(template1.Labels) == 0 || len(template2.Labels) == 0 { return false, fmt.Errorf("Unexpected empty labels found in given template") } hash1 := template1.Labels[extensions.DefaultDeploymentUniqueLabelKey] hash2 := template2.Labels[extensions.DefaultDeploymentUniqueLabelKey] // compare equality ignoring pod-template-hash template1.Labels[extensions.DefaultDeploymentUniqueLabelKey] = hash2 result := api.Semantic.DeepEqual(template1, template2) template1.Labels[extensions.DefaultDeploymentUniqueLabelKey] = hash1 return result, nil } // FindNewReplicaSet returns the new RS this given deployment targets (the one with the same pod template). func FindNewReplicaSet(deployment *extensions.Deployment, rsList []extensions.ReplicaSet) (*extensions.ReplicaSet, error) { newRSTemplate := GetNewReplicaSetTemplate(deployment) for i := range rsList { equal, err := equalIgnoreHash(rsList[i].Spec.Template, newRSTemplate) if err != nil { return nil, err } if equal { // This is the new ReplicaSet. return &rsList[i], nil } } // new ReplicaSet does not exist. return nil, nil } // FindOldReplicaSets returns the old replica sets targeted by the given Deployment, with the given PodList and slice of RSes. // Note that the first set of old replica sets doesn't include the ones with no pods, and the second set of old replica sets include all old replica sets. func FindOldReplicaSets(deployment *extensions.Deployment, rsList []extensions.ReplicaSet, podList *api.PodList) ([]*extensions.ReplicaSet, []*extensions.ReplicaSet, error) { // Find all pods whose labels match deployment.Spec.Selector, and corresponding replica sets for pods in podList. // All pods and replica sets are labeled with pod-template-hash to prevent overlapping oldRSs := map[string]extensions.ReplicaSet{} allOldRSs := map[string]extensions.ReplicaSet{} newRSTemplate := GetNewReplicaSetTemplate(deployment) for _, pod := range podList.Items { podLabelsSelector := labels.Set(pod.ObjectMeta.Labels) for _, rs := range rsList { rsLabelsSelector, err := unversioned.LabelSelectorAsSelector(rs.Spec.Selector) if err != nil { return nil, nil, fmt.Errorf("invalid label selector: %v", err) } // Filter out replica set that has the same pod template spec as the deployment - that is the new replica set. equal, err := equalIgnoreHash(rs.Spec.Template, newRSTemplate) if err != nil { return nil, nil, err } if equal { continue } allOldRSs[rs.ObjectMeta.Name] = rs if rsLabelsSelector.Matches(podLabelsSelector) { oldRSs[rs.ObjectMeta.Name] = rs } } } requiredRSs := []*extensions.ReplicaSet{} for key := range oldRSs { value := oldRSs[key] requiredRSs = append(requiredRSs, &value) } allRSs := []*extensions.ReplicaSet{} for key := range allOldRSs { value := allOldRSs[key] allRSs = append(allRSs, &value) } return requiredRSs, allRSs, nil } // WaitForReplicaSetUpdated polls the replica set until it is updated. func WaitForReplicaSetUpdated(c clientset.Interface, desiredGeneration int64, namespace, name string) error { return wait.Poll(10*time.Millisecond, 1*time.Minute, func() (bool, error) { rs, err := c.Extensions().ReplicaSets(namespace).Get(name) if err != nil { return false, err } return rs.Status.ObservedGeneration >= desiredGeneration, nil }) } // WaitForPodsHashPopulated polls the replica set until updated and fully labeled. func WaitForPodsHashPopulated(c clientset.Interface, desiredGeneration int64, namespace, name string) error { return wait.Poll(1*time.Second, 1*time.Minute, func() (bool, error) { rs, err := c.Extensions().ReplicaSets(namespace).Get(name) if err != nil { return false, err } return rs.Status.ObservedGeneration >= desiredGeneration && rs.Status.FullyLabeledReplicas == rs.Spec.Replicas, nil }) } // LabelPodsWithHash labels all pods in the given podList with the new hash label. // The returned bool value can be used to tell if all pods are actually labeled. func LabelPodsWithHash(podList *api.PodList, rs *extensions.ReplicaSet, c clientset.Interface, namespace, hash string) (bool, error) { allPodsLabeled := true for _, pod := range podList.Items { // Only label the pod that doesn't already have the new hash if pod.Labels[extensions.DefaultDeploymentUniqueLabelKey] != hash { if _, podUpdated, err := podutil.UpdatePodWithRetries(c.Core().Pods(namespace), &pod, func(podToUpdate *api.Pod) error { // Precondition: the pod doesn't contain the new hash in its label. if podToUpdate.Labels[extensions.DefaultDeploymentUniqueLabelKey] == hash { return errors.ErrPreconditionViolated } podToUpdate.Labels = labelsutil.AddLabel(podToUpdate.Labels, extensions.DefaultDeploymentUniqueLabelKey, hash) return nil }); err != nil { return false, fmt.Errorf("error in adding template hash label %s to pod %+v: %s", hash, pod, err) } else if podUpdated { glog.V(4).Infof("Labeled %s %s/%s of %s %s/%s with hash %s.", pod.Kind, pod.Namespace, pod.Name, rs.Kind, rs.Namespace, rs.Name, hash) } else { // If the pod wasn't updated but didn't return error when we try to update it, we've hit "pod not found" or "precondition violated" error. // Then we can't say all pods are labeled allPodsLabeled = false } } } return allPodsLabeled, nil } // GetNewReplicaSetTemplate returns the desired PodTemplateSpec for the new ReplicaSet corresponding to the given ReplicaSet. func GetNewReplicaSetTemplate(deployment *extensions.Deployment) api.PodTemplateSpec { // newRS will have the same template as in deployment spec, plus a unique label in some cases. newRSTemplate := api.PodTemplateSpec{ ObjectMeta: deployment.Spec.Template.ObjectMeta, Spec: deployment.Spec.Template.Spec, } newRSTemplate.ObjectMeta.Labels = labelsutil.CloneAndAddLabel( deployment.Spec.Template.ObjectMeta.Labels, extensions.DefaultDeploymentUniqueLabelKey, podutil.GetPodTemplateSpecHash(newRSTemplate)) return newRSTemplate } // SetFromReplicaSetTemplate sets the desired PodTemplateSpec from a replica set template to the given deployment. func SetFromReplicaSetTemplate(deployment *extensions.Deployment, template api.PodTemplateSpec) *extensions.Deployment { deployment.Spec.Template.ObjectMeta = template.ObjectMeta deployment.Spec.Template.Spec = template.Spec deployment.Spec.Template.ObjectMeta.Labels = labelsutil.CloneAndRemoveLabel( deployment.Spec.Template.ObjectMeta.Labels, extensions.DefaultDeploymentUniqueLabelKey) return deployment } // GetReplicaCountForReplicaSets returns the sum of Replicas of the given replica sets. func GetReplicaCountForReplicaSets(replicaSets []*extensions.ReplicaSet) int32 { totalReplicaCount := int32(0) for _, rs := range replicaSets { if rs != nil { totalReplicaCount += rs.Spec.Replicas } } return totalReplicaCount } // GetActualReplicaCountForReplicaSets returns the sum of actual replicas of the given replica sets. func GetActualReplicaCountForReplicaSets(replicaSets []*extensions.ReplicaSet) int32 { totalReplicaCount := int32(0) for _, rs := range replicaSets { if rs != nil { totalReplicaCount += rs.Status.Replicas } } return totalReplicaCount } // GetAvailablePodsForReplicaSets returns the number of available pods (listed from clientset) corresponding to the given replica sets. func GetAvailablePodsForReplicaSets(c clientset.Interface, deployment *extensions.Deployment, rss []*extensions.ReplicaSet, minReadySeconds int32) (int32, error) { podList, err := listPods(deployment, c) if err != nil { return 0, err } return CountAvailablePodsForReplicaSets(podList, rss, minReadySeconds) } // CountAvailablePodsForReplicaSets returns the number of available pods corresponding to the given pod list and replica sets. // Note that the input pod list should be the pods targeted by the deployment of input replica sets. func CountAvailablePodsForReplicaSets(podList *api.PodList, rss []*extensions.ReplicaSet, minReadySeconds int32) (int32, error) { rsPods, err := filterPodsMatchingReplicaSets(rss, podList) if err != nil { return 0, err } return countAvailablePods(rsPods, minReadySeconds), nil } // GetAvailablePodsForDeployment returns the number of available pods (listed from clientset) corresponding to the given deployment. func GetAvailablePodsForDeployment(c clientset.Interface, deployment *extensions.Deployment, minReadySeconds int32) (int32, error) { podList, err := listPods(deployment, c) if err != nil { return 0, err } return countAvailablePods(podList.Items, minReadySeconds), nil } func countAvailablePods(pods []api.Pod, minReadySeconds int32) int32 { availablePodCount := int32(0) for _, pod := range pods { // TODO: Make the time.Now() as argument to allow unit test this. if IsPodAvailable(&pod, minReadySeconds, time.Now()) { glog.V(4).Infof("Pod %s/%s is available.", pod.Namespace, pod.Name) availablePodCount++ } } return availablePodCount } // IsPodAvailable return true if the pod is available. func IsPodAvailable(pod *api.Pod, minReadySeconds int32, now time.Time) bool { if !controller.IsPodActive(*pod) { return false } // Check if we've passed minReadySeconds since LastTransitionTime // If so, this pod is ready for _, c := range pod.Status.Conditions { // we only care about pod ready conditions if c.Type == api.PodReady && c.Status == api.ConditionTrue { glog.V(4).Infof("Comparing pod %s/%s ready condition last transition time %s + minReadySeconds %d with now %s.", pod.Namespace, pod.Name, c.LastTransitionTime.String(), minReadySeconds, now.String()) // 2 cases that this ready condition is valid (passed minReadySeconds, i.e. the pod is available): // 1. minReadySeconds == 0, or // 2. LastTransitionTime (is set) + minReadySeconds (>0) < current time minReadySecondsDuration := time.Duration(minReadySeconds) * time.Second if minReadySeconds == 0 || !c.LastTransitionTime.IsZero() && c.LastTransitionTime.Add(minReadySecondsDuration).Before(now) { return true } } } return false } // filterPodsMatchingReplicaSets filters the given pod list and only return the ones targeted by the input replicasets func filterPodsMatchingReplicaSets(replicaSets []*extensions.ReplicaSet, podList *api.PodList) ([]api.Pod, error) { rsPods := []api.Pod{} for _, rs := range replicaSets { matchingFunc, err := rsutil.MatchingPodsFunc(rs) if err != nil { return nil, err } if matchingFunc == nil { continue } rsPods = append(rsPods, podutil.Filter(podList, matchingFunc)...) } return rsPods, nil } // Revision returns the revision number of the input replica set func Revision(rs *extensions.ReplicaSet) (int64, error) { v, ok := rs.Annotations[RevisionAnnotation] if !ok { return 0, nil } return strconv.ParseInt(v, 10, 64) } // IsRollingUpdate returns true if the strategy type is a rolling update. func IsRollingUpdate(deployment *extensions.Deployment) bool { return deployment.Spec.Strategy.Type == extensions.RollingUpdateDeploymentStrategyType } // NewRSNewReplicas calculates the number of replicas a deployment's new RS should have. // When one of the followings is true, we're rolling out the deployment; otherwise, we're scaling it. // 1) The new RS is saturated: newRS's replicas == deployment's replicas // 2) Max number of pods allowed is reached: deployment's replicas + maxSurge == all RSs' replicas func NewRSNewReplicas(deployment *extensions.Deployment, allRSs []*extensions.ReplicaSet, newRS *extensions.ReplicaSet) (int32, error) { switch deployment.Spec.Strategy.Type { case extensions.RollingUpdateDeploymentStrategyType: // Check if we can scale up. maxSurge, err := intstrutil.GetValueFromIntOrPercent(&deployment.Spec.Strategy.RollingUpdate.MaxSurge, int(deployment.Spec.Replicas), true) if err != nil { return 0, err } // Find the total number of pods currentPodCount := GetReplicaCountForReplicaSets(allRSs) maxTotalPods := deployment.Spec.Replicas + int32(maxSurge) if currentPodCount >= maxTotalPods { // Cannot scale up. return newRS.Spec.Replicas, nil } // Scale up. scaleUpCount := maxTotalPods - currentPodCount // Do not exceed the number of desired replicas. scaleUpCount = int32(integer.IntMin(int(scaleUpCount), int(deployment.Spec.Replicas-newRS.Spec.Replicas))) return newRS.Spec.Replicas + scaleUpCount, nil case extensions.RecreateDeploymentStrategyType: return deployment.Spec.Replicas, nil default: return 0, fmt.Errorf("deployment type %v isn't supported", deployment.Spec.Strategy.Type) } } // IsSaturated checks if the new replica set is saturated by comparing its size with its deployment size. // Both the deployment and the replica set have to believe this replica set can own all of the desired // replicas in the deployment and the annotation helps in achieving that. func IsSaturated(deployment *extensions.Deployment, rs *extensions.ReplicaSet) bool { if rs == nil { return false } desiredString := rs.Annotations[DesiredReplicasAnnotation] desired, err := strconv.Atoi(desiredString) if err != nil { return false } return rs.Spec.Replicas == deployment.Spec.Replicas && int32(desired) == deployment.Spec.Replicas } // WaitForObservedDeployment polls for deployment to be updated so that deployment.Status.ObservedGeneration >= desiredGeneration. // Returns error if polling timesout. func WaitForObservedDeployment(getDeploymentFunc func() (*extensions.Deployment, error), desiredGeneration int64, interval, timeout time.Duration) error { // TODO: This should take clientset.Interface when all code is updated to use clientset. Keeping it this way allows the function to be used by callers who have client.Interface. return wait.Poll(interval, timeout, func() (bool, error) { deployment, err := getDeploymentFunc() if err != nil { return false, err } return deployment.Status.ObservedGeneration >= desiredGeneration, nil }) } // ResolveFenceposts resolves both maxSurge and maxUnavailable. This needs to happen in one // step. For example: // // 2 desired, max unavailable 1%, surge 0% - should scale old(-1), then new(+1), then old(-1), then new(+1) // 1 desired, max unavailable 1%, surge 0% - should scale old(-1), then new(+1) // 2 desired, max unavailable 25%, surge 1% - should scale new(+1), then old(-1), then new(+1), then old(-1) // 1 desired, max unavailable 25%, surge 1% - should scale new(+1), then old(-1) // 2 desired, max unavailable 0%, surge 1% - should scale new(+1), then old(-1), then new(+1), then old(-1) // 1 desired, max unavailable 0%, surge 1% - should scale new(+1), then old(-1) func ResolveFenceposts(maxSurge, maxUnavailable *intstrutil.IntOrString, desired int32) (int32, int32, error) { surge, err := intstrutil.GetValueFromIntOrPercent(maxSurge, int(desired), true) if err != nil { return 0, 0, err } unavailable, err := intstrutil.GetValueFromIntOrPercent(maxUnavailable, int(desired), false) if err != nil { return 0, 0, err } if surge == 0 && unavailable == 0 { // Validation should never allow the user to explicitly use zero values for both maxSurge // maxUnavailable. Due to rounding down maxUnavailable though, it may resolve to zero. // If both fenceposts resolve to zero, then we should set maxUnavailable to 1 on the // theory that surge might not work due to quota. unavailable = 1 } return int32(surge), int32(unavailable), nil } func DeploymentDeepCopy(deployment *extensions.Deployment) (*extensions.Deployment, error) { objCopy, err := api.Scheme.DeepCopy(deployment) if err != nil { return nil, err } copied, ok := objCopy.(*extensions.Deployment) if !ok { return nil, fmt.Errorf("expected Deployment, got %#v", objCopy) } return copied, nil }
pkg/controller/deployment/util/deployment_util.go
1
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.8641325235366821, 0.0159646924585104, 0.00016096796025522053, 0.0006501798634417355, 0.0977616235613823 ]
{ "id": 5, "code_window": [ "\tdeploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType\n", "\tframework.Logf(\"Creating deployment %s\", deploymentName)\n", "\tnewDeployment := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil)\n", "\tnewDeployment.Spec.MinReadySeconds = deploymentMinReadySeconds\n", "\tnewDeployment.Spec.Strategy.RollingUpdate = &extensions.RollingUpdateDeployment{\n", "\t\tMaxUnavailable: intstr.FromInt(1),\n", "\t\tMaxSurge: intstr.FromInt(1),\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "test/e2e/deployment.go", "type": "replace", "edit_start_line_idx": 528 }
/* 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 config import ( "fmt" "sort" "strings" ) type ConfigurationMap map[string]string func (m *ConfigurationMap) String() string { pairs := []string{} for k, v := range *m { pairs = append(pairs, fmt.Sprintf("%s=%s", k, v)) } sort.Strings(pairs) return strings.Join(pairs, ",") } func (m *ConfigurationMap) Set(value string) error { for _, s := range strings.Split(value, ",") { if len(s) == 0 { continue } arr := strings.SplitN(s, "=", 2) if len(arr) == 2 { (*m)[strings.TrimSpace(arr[0])] = strings.TrimSpace(arr[1]) } else { (*m)[strings.TrimSpace(arr[0])] = "" } } return nil } func (*ConfigurationMap) Type() string { return "mapStringString" }
pkg/util/config/configuration_map.go
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.00017883653345052153, 0.0001712923840386793, 0.0001608706807019189, 0.00017209822544828057, 0.000006284134997258661 ]
{ "id": 5, "code_window": [ "\tdeploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType\n", "\tframework.Logf(\"Creating deployment %s\", deploymentName)\n", "\tnewDeployment := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil)\n", "\tnewDeployment.Spec.MinReadySeconds = deploymentMinReadySeconds\n", "\tnewDeployment.Spec.Strategy.RollingUpdate = &extensions.RollingUpdateDeployment{\n", "\t\tMaxUnavailable: intstr.FromInt(1),\n", "\t\tMaxSurge: intstr.FromInt(1),\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "test/e2e/deployment.go", "type": "replace", "edit_start_line_idx": 528 }
/* 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 registrytest import ( "fmt" "sync" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/watch" ) // Registry is an interface for things that know how to store endpoints. type EndpointRegistry struct { Endpoints *api.EndpointsList Updates []api.Endpoints Err error lock sync.Mutex } func (e *EndpointRegistry) ListEndpoints(ctx api.Context, options *api.ListOptions) (*api.EndpointsList, error) { // TODO: support namespaces in this mock e.lock.Lock() defer e.lock.Unlock() return e.Endpoints, e.Err } func (e *EndpointRegistry) GetEndpoints(ctx api.Context, name string) (*api.Endpoints, error) { // TODO: support namespaces in this mock e.lock.Lock() defer e.lock.Unlock() if e.Err != nil { return nil, e.Err } if e.Endpoints != nil { for _, endpoint := range e.Endpoints.Items { if endpoint.Name == name { return &endpoint, nil } } } return nil, errors.NewNotFound(api.Resource("endpoints"), name) } func (e *EndpointRegistry) WatchEndpoints(ctx api.Context, options *api.ListOptions) (watch.Interface, error) { return nil, fmt.Errorf("unimplemented!") } func (e *EndpointRegistry) UpdateEndpoints(ctx api.Context, endpoints *api.Endpoints) error { // TODO: support namespaces in this mock e.lock.Lock() defer e.lock.Unlock() e.Updates = append(e.Updates, *endpoints) if e.Err != nil { return e.Err } if e.Endpoints == nil { e.Endpoints = &api.EndpointsList{ Items: []api.Endpoints{ *endpoints, }, } return nil } for ix := range e.Endpoints.Items { if e.Endpoints.Items[ix].Name == endpoints.Name { e.Endpoints.Items[ix] = *endpoints } } e.Endpoints.Items = append(e.Endpoints.Items, *endpoints) return nil } func (e *EndpointRegistry) DeleteEndpoints(ctx api.Context, name string) error { // TODO: support namespaces in this mock e.lock.Lock() defer e.lock.Unlock() if e.Err != nil { return e.Err } if e.Endpoints != nil { var newList []api.Endpoints for _, endpoint := range e.Endpoints.Items { if endpoint.Name != name { newList = append(newList, endpoint) } } e.Endpoints.Items = newList } return nil }
pkg/registry/registrytest/endpoint.go
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.0001991835015360266, 0.00017296035366598517, 0.00016263774887192994, 0.00017205398762598634, 0.000009570127986080479 ]
{ "id": 5, "code_window": [ "\tdeploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType\n", "\tframework.Logf(\"Creating deployment %s\", deploymentName)\n", "\tnewDeployment := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil)\n", "\tnewDeployment.Spec.MinReadySeconds = deploymentMinReadySeconds\n", "\tnewDeployment.Spec.Strategy.RollingUpdate = &extensions.RollingUpdateDeployment{\n", "\t\tMaxUnavailable: intstr.FromInt(1),\n", "\t\tMaxSurge: intstr.FromInt(1),\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "test/e2e/deployment.go", "type": "replace", "edit_start_line_idx": 528 }
// +build linux package configs import "syscall" func (n *Namespace) Syscall() int { return namespaceInfo[n.Type] } var namespaceInfo = map[NamespaceType]int{ NEWNET: syscall.CLONE_NEWNET, NEWNS: syscall.CLONE_NEWNS, NEWUSER: syscall.CLONE_NEWUSER, NEWIPC: syscall.CLONE_NEWIPC, NEWUTS: syscall.CLONE_NEWUTS, NEWPID: syscall.CLONE_NEWPID, } // CloneFlags parses the container's Namespaces options to set the correct // flags on clone, unshare. This function returns flags only for new namespaces. func (n *Namespaces) CloneFlags() uintptr { var flag int for _, v := range *n { if v.Path != "" { continue } flag |= namespaceInfo[v.Type] } return uintptr(flag) }
vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall.go
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.00017365338862873614, 0.00017161639698315412, 0.00016891348059289157, 0.00017194935935549438, 0.0000018272648958372883 ]
{ "id": 6, "code_window": [ "\terr = framework.WaitForDeploymentUpdatedReplicasLTE(c, ns, deploymentName, 1, deployment.Generation)\n", "\t// Check if it's updated to revision 1 correctly\n", "\t_, newRS := checkDeploymentRevision(c, ns, deploymentName, \"1\", deploymentImageName, deploymentImage)\n", "\n", "\t// Before the deployment finishes, update the deployment to rollover the above 2 ReplicaSets and bring up redis pods.\n", "\t// If the deployment already finished here, the test would fail. When this happens, increase its minReadySeconds or replicas to prevent it.\n", "\tExpect(newRS.Spec.Replicas).Should(BeNumerically(\"<\", deploymentReplicas))\n", "\tupdatedDeploymentImageName, updatedDeploymentImage := redisImageName, redisImage\n", "\tdeployment, err = framework.UpdateDeploymentWithRetries(c, ns, newDeployment.Name, func(update *extensions.Deployment) {\n", "\t\tupdate.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "test/e2e/deployment.go", "type": "replace", "edit_start_line_idx": 546 }
/* 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 e2e import ( "fmt" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/annotations" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apis/extensions" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" client "k8s.io/kubernetes/pkg/client/unversioned" adapter "k8s.io/kubernetes/pkg/client/unversioned/adapters/internalclientset" deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util" "k8s.io/kubernetes/pkg/kubectl" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/watch" "k8s.io/kubernetes/test/e2e/framework" ) const ( // nginxImage defined in kubectl.go nginxImageName = "nginx" redisImage = "gcr.io/google_containers/redis:e2e" redisImageName = "redis" ) var _ = framework.KubeDescribe("Deployment", func() { f := framework.NewDefaultFramework("deployment") It("deployment should create new pods", func() { testNewDeployment(f) }) It("RollingUpdateDeployment should delete old pods and create new ones", func() { testRollingUpdateDeployment(f) }) It("RollingUpdateDeployment should scale up and down in the right order", func() { testRollingUpdateDeploymentEvents(f) }) It("RecreateDeployment should delete old pods and create new ones", func() { testRecreateDeployment(f) }) It("deployment should delete old replica sets", func() { testDeploymentCleanUpPolicy(f) }) It("deployment should support rollover", func() { testRolloverDeployment(f) }) It("paused deployment should be ignored by the controller", func() { testPausedDeployment(f) }) It("deployment should support rollback", func() { testRollbackDeployment(f) }) It("deployment should support rollback when there's replica set with no revision", func() { testRollbackDeploymentRSNoRevision(f) }) It("deployment should label adopted RSs and pods", func() { testDeploymentLabelAdopted(f) }) It("paused deployment should be able to scale", func() { testScalePausedDeployment(f) }) It("scaled rollout should not block on annotation check", func() { testScaledRolloutDeployment(f) }) }) func newRS(rsName string, replicas int32, rsPodLabels map[string]string, imageName string, image string) *extensions.ReplicaSet { zero := int64(0) return &extensions.ReplicaSet{ ObjectMeta: api.ObjectMeta{ Name: rsName, }, Spec: extensions.ReplicaSetSpec{ Replicas: replicas, Selector: &unversioned.LabelSelector{MatchLabels: rsPodLabels}, Template: api.PodTemplateSpec{ ObjectMeta: api.ObjectMeta{ Labels: rsPodLabels, }, Spec: api.PodSpec{ TerminationGracePeriodSeconds: &zero, Containers: []api.Container{ { Name: imageName, Image: image, }, }, }, }, }, } } func newDeployment(deploymentName string, replicas int32, podLabels map[string]string, imageName string, image string, strategyType extensions.DeploymentStrategyType, revisionHistoryLimit *int32) *extensions.Deployment { zero := int64(0) return &extensions.Deployment{ ObjectMeta: api.ObjectMeta{ Name: deploymentName, }, Spec: extensions.DeploymentSpec{ Replicas: replicas, Selector: &unversioned.LabelSelector{MatchLabels: podLabels}, Strategy: extensions.DeploymentStrategy{ Type: strategyType, }, RevisionHistoryLimit: revisionHistoryLimit, Template: api.PodTemplateSpec{ ObjectMeta: api.ObjectMeta{ Labels: podLabels, }, Spec: api.PodSpec{ TerminationGracePeriodSeconds: &zero, Containers: []api.Container{ { Name: imageName, Image: image, }, }, }, }, }, } } func newDeploymentRollback(name string, annotations map[string]string, revision int64) *extensions.DeploymentRollback { return &extensions.DeploymentRollback{ Name: name, UpdatedAnnotations: annotations, RollbackTo: extensions.RollbackConfig{Revision: revision}, } } // checkDeploymentRevision checks if the input deployment's and its new replica set's revision and images are as expected. func checkDeploymentRevision(c *clientset.Clientset, ns, deploymentName, revision, imageName, image string) (*extensions.Deployment, *extensions.ReplicaSet) { deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) // Check revision of the new replica set of this deployment newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(newRS.Annotations).NotTo(Equal(nil)) Expect(newRS.Annotations[deploymentutil.RevisionAnnotation]).Should(Equal(revision)) // Check revision of This deployment Expect(deployment.Annotations).NotTo(Equal(nil)) Expect(deployment.Annotations[deploymentutil.RevisionAnnotation]).Should(Equal(revision)) if len(imageName) > 0 { // Check the image the new replica set creates Expect(newRS.Spec.Template.Spec.Containers[0].Name).Should(Equal(imageName)) Expect(newRS.Spec.Template.Spec.Containers[0].Image).Should(Equal(image)) // Check the image the deployment creates Expect(deployment.Spec.Template.Spec.Containers[0].Name).Should(Equal(imageName)) Expect(deployment.Spec.Template.Spec.Containers[0].Image).Should(Equal(image)) } return deployment, newRS } func stopDeployment(c *clientset.Clientset, oldC client.Interface, ns, deploymentName string) { deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) framework.Logf("Deleting deployment %s", deploymentName) reaper, err := kubectl.ReaperFor(extensions.Kind("Deployment"), oldC) Expect(err).NotTo(HaveOccurred()) timeout := 1 * time.Minute err = reaper.Stop(ns, deployment.Name, timeout, api.NewDeleteOptions(0)) Expect(err).NotTo(HaveOccurred()) framework.Logf("Ensuring deployment %s was deleted", deploymentName) _, err = c.Extensions().Deployments(ns).Get(deployment.Name) Expect(err).To(HaveOccurred()) Expect(errors.IsNotFound(err)).To(BeTrue()) framework.Logf("Ensuring deployment %s's RSes were deleted", deploymentName) selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) Expect(err).NotTo(HaveOccurred()) options := api.ListOptions{LabelSelector: selector} rss, err := c.Extensions().ReplicaSets(ns).List(options) Expect(err).NotTo(HaveOccurred()) Expect(rss.Items).Should(HaveLen(0)) framework.Logf("Ensuring deployment %s's Pods were deleted", deploymentName) var pods *api.PodList if err := wait.PollImmediate(time.Second, timeout, func() (bool, error) { pods, err = c.Core().Pods(ns).List(api.ListOptions{}) if err != nil { return false, err } if len(pods.Items) == 0 { return true, nil } return false, nil }); err != nil { framework.Failf("Err : %s\n. Failed to remove deployment %s pods : %+v", err, deploymentName, pods) } } func testNewDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. c := adapter.FromUnversionedClient(f.Client) deploymentName := "test-new-deployment" podLabels := map[string]string{"name": nginxImageName} replicas := int32(1) framework.Logf("Creating simple deployment %s", deploymentName) d := newDeployment(deploymentName, replicas, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) d.Annotations = map[string]string{"test": "should-copy-to-replica-set", annotations.LastAppliedConfigAnnotation: "should-not-copy-to-replica-set"} deploy, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", nginxImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) // Check new RS annotations Expect(newRS.Annotations["test"]).Should(Equal("should-copy-to-replica-set")) Expect(newRS.Annotations[annotations.LastAppliedConfigAnnotation]).Should(Equal("")) Expect(deployment.Annotations["test"]).Should(Equal("should-copy-to-replica-set")) Expect(deployment.Annotations[annotations.LastAppliedConfigAnnotation]).Should(Equal("should-not-copy-to-replica-set")) } func testRollingUpdateDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "sample-pod"} rsPodLabels := map[string]string{ "name": "sample-pod", "pod": nginxImageName, } rsName := "test-rolling-update-controller" replicas := int32(3) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "sample-pod", false, 3) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-rolling-update-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RollingUpdateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", redisImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // There should be 1 old RS (nginx-controller, which is adopted) deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) _, allOldRSs, err := deploymentutil.GetOldReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(len(allOldRSs)).Should(Equal(1)) // The old RS should contain pod-template-hash in its selector, label, and template label Expect(len(allOldRSs[0].Labels[extensions.DefaultDeploymentUniqueLabelKey])).Should(BeNumerically(">", 0)) Expect(len(allOldRSs[0].Spec.Selector.MatchLabels[extensions.DefaultDeploymentUniqueLabelKey])).Should(BeNumerically(">", 0)) Expect(len(allOldRSs[0].Spec.Template.Labels[extensions.DefaultDeploymentUniqueLabelKey])).Should(BeNumerically(">", 0)) } func testRollingUpdateDeploymentEvents(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "sample-pod-2"} rsPodLabels := map[string]string{ "name": "sample-pod-2", "pod": nginxImageName, } rsName := "test-rolling-scale-controller" replicas := int32(1) rsRevision := "3546343826724305832" annotations := make(map[string]string) annotations[deploymentutil.RevisionAnnotation] = rsRevision rs := newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage) rs.Annotations = annotations _, err := c.Extensions().ReplicaSets(ns).Create(rs) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "sample-pod-2", false, 1) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-rolling-scale-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RollingUpdateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 3546343826724305833 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "3546343826724305833", redisImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Verify that the pods were scaled up and down as expected. We use events to verify that. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) framework.WaitForEvents(unversionedClient, ns, deployment, 2) events, err := c.Core().Events(ns).Search(deployment) if err != nil { framework.Logf("error in listing events: %s", err) Expect(err).NotTo(HaveOccurred()) } // There should be 2 events, one to scale up the new ReplicaSet and then to scale down // the old ReplicaSet. Expect(len(events.Items)).Should(Equal(2)) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(newRS).NotTo(Equal(nil)) Expect(events.Items[0].Message).Should(Equal(fmt.Sprintf("Scaled up replica set %s to 1", newRS.Name))) Expect(events.Items[1].Message).Should(Equal(fmt.Sprintf("Scaled down replica set %s to 0", rsName))) } func testRecreateDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "sample-pod-3"} rsPodLabels := map[string]string{ "name": "sample-pod-3", "pod": nginxImageName, } rsName := "test-recreate-controller" replicas := int32(3) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "sample-pod-3", false, 3) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-recreate-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RecreateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", redisImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Verify that the pods were scaled up and down as expected. We use events to verify that. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) framework.WaitForEvents(unversionedClient, ns, deployment, 2) events, err := c.Core().Events(ns).Search(deployment) if err != nil { framework.Logf("error in listing events: %s", err) Expect(err).NotTo(HaveOccurred()) } // There should be 2 events, one to scale up the new ReplicaSet and then to scale down the old ReplicaSet. Expect(len(events.Items)).Should(Equal(2)) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(newRS).NotTo(Equal(nil)) Expect(events.Items[0].Message).Should(Equal(fmt.Sprintf("Scaled down replica set %s to 0", rsName))) Expect(events.Items[1].Message).Should(Equal(fmt.Sprintf("Scaled up replica set %s to 3", newRS.Name))) } // testDeploymentCleanUpPolicy tests that deployment supports cleanup policy func testDeploymentCleanUpPolicy(f *framework.Framework) { ns := f.Namespace.Name unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. deploymentPodLabels := map[string]string{"name": "cleanup-pod"} rsPodLabels := map[string]string{ "name": "cleanup-pod", "pod": nginxImageName, } rsName := "test-cleanup-controller" replicas := int32(1) revisionHistoryLimit := util.Int32Ptr(0) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, "cleanup-pod", false, 1) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a deployment to delete nginx pods and instead bring up redis pods. deploymentName := "test-cleanup-deployment" framework.Logf("Creating deployment %s", deploymentName) pods, err := c.Pods(ns).List(api.ListOptions{LabelSelector: labels.Everything()}) if err != nil { Expect(err).NotTo(HaveOccurred(), "Failed to query for pods: %v", err) } options := api.ListOptions{ ResourceVersion: pods.ListMeta.ResourceVersion, } stopCh := make(chan struct{}) w, err := c.Pods(ns).Watch(options) go func() { // There should be only one pod being created, which is the pod with the redis image. // The old RS shouldn't create new pod when deployment controller adding pod template hash label to its selector. numPodCreation := 1 for { select { case event, _ := <-w.ResultChan(): if event.Type != watch.Added { continue } numPodCreation-- if numPodCreation < 0 { framework.Failf("Expect only one pod creation, the second creation event: %#v\n", event) } pod, ok := event.Object.(*api.Pod) if !ok { Fail("Expect event Object to be a pod") } if pod.Spec.Containers[0].Name != redisImageName { framework.Failf("Expect the created pod to have container name %s, got pod %#v\n", redisImageName, pod) } case <-stopCh: return } } }() _, err = c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, deploymentPodLabels, redisImageName, redisImage, extensions.RollingUpdateDeploymentStrategyType, revisionHistoryLimit)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) err = framework.WaitForDeploymentOldRSsNum(c, ns, deploymentName, int(*revisionHistoryLimit)) Expect(err).NotTo(HaveOccurred()) close(stopCh) } // testRolloverDeployment tests that deployment supports rollover. // i.e. we can change desired state and kick off rolling update, then change desired state again before it finishes. func testRolloverDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) podName := "rollover-pod" deploymentPodLabels := map[string]string{"name": podName} rsPodLabels := map[string]string{ "name": podName, "pod": nginxImageName, } rsName := "test-rollover-controller" rsReplicas := int32(4) _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, rsReplicas, rsPodLabels, nginxImageName, nginxImage)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, podName, false, rsReplicas) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Wait for the required pods to be ready for at least minReadySeconds (be available) deploymentMinReadySeconds := int32(5) err = framework.WaitForPodsReady(c, ns, podName, int(deploymentMinReadySeconds)) Expect(err).NotTo(HaveOccurred()) // Create a deployment to delete nginx pods and instead bring up redis-slave pods. deploymentName, deploymentImageName := "test-rollover-deployment", "redis-slave" deploymentReplicas := int32(4) deploymentImage := "gcr.io/google_samples/gb-redisslave:v1" deploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType framework.Logf("Creating deployment %s", deploymentName) newDeployment := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil) newDeployment.Spec.MinReadySeconds = deploymentMinReadySeconds newDeployment.Spec.Strategy.RollingUpdate = &extensions.RollingUpdateDeployment{ MaxUnavailable: intstr.FromInt(1), MaxSurge: intstr.FromInt(1), } _, err = c.Extensions().Deployments(ns).Create(newDeployment) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Verify that the pods were scaled up and down as expected. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) // Make sure the deployment starts to scale up and down replica sets by checking if its updated replicas >= 1 err = framework.WaitForDeploymentUpdatedReplicasLTE(c, ns, deploymentName, 1, deployment.Generation) // Check if it's updated to revision 1 correctly _, newRS := checkDeploymentRevision(c, ns, deploymentName, "1", deploymentImageName, deploymentImage) // Before the deployment finishes, update the deployment to rollover the above 2 ReplicaSets and bring up redis pods. // If the deployment already finished here, the test would fail. When this happens, increase its minReadySeconds or replicas to prevent it. Expect(newRS.Spec.Replicas).Should(BeNumerically("<", deploymentReplicas)) updatedDeploymentImageName, updatedDeploymentImage := redisImageName, redisImage deployment, err = framework.UpdateDeploymentWithRetries(c, ns, newDeployment.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName update.Spec.Template.Spec.Containers[0].Image = updatedDeploymentImage }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pod template update. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 2 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "2", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) } func testPausedDeployment(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) deploymentName := "test-paused-deployment" podLabels := map[string]string{"name": nginxImageName} d := newDeployment(deploymentName, 1, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) d.Spec.Paused = true tgps := int64(20) d.Spec.Template.Spec.TerminationGracePeriodSeconds = &tgps framework.Logf("Creating paused deployment %s", deploymentName) _, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Check that deployment is created fine. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) // Verify that there is no latest state realized for the new deployment. rs, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) if rs != nil { err = fmt.Errorf("unexpected new rs/%s for deployment/%s", rs.Name, deployment.Name) Expect(err).NotTo(HaveOccurred()) } // Update the deployment to run deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Paused = false }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the resume. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) if err != nil { Expect(err).NotTo(HaveOccurred()) } opts := api.ListOptions{LabelSelector: selector} w, err := c.Extensions().ReplicaSets(ns).Watch(opts) Expect(err).NotTo(HaveOccurred()) select { case <-w.ResultChan(): // this is it case <-time.After(time.Minute): err = fmt.Errorf("expected a new replica set to be created") Expect(err).NotTo(HaveOccurred()) } // Pause the deployment and delete the replica set. // The paused deployment shouldn't recreate a new one. deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Paused = true }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pause. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Update the deployment template - the new replicaset should stay the same framework.Logf("Updating paused deployment %q", deploymentName) newTGPS := int64(40) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.TerminationGracePeriodSeconds = &newTGPS }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) framework.Logf("Looking for new replicaset for paused deployment %q (there should be none)", deploymentName) newRS, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) if newRS != nil { err = fmt.Errorf("No replica set should match the deployment template but there is %q", newRS.Name) Expect(err).NotTo(HaveOccurred()) } _, allOldRs, err := deploymentutil.GetOldReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) if len(allOldRs) != 1 { err = fmt.Errorf("expected an old replica set") Expect(err).NotTo(HaveOccurred()) } framework.Logf("Comparing deployment diff with old replica set %q", allOldRs[0].Name) if *allOldRs[0].Spec.Template.Spec.TerminationGracePeriodSeconds == newTGPS { err = fmt.Errorf("TerminationGracePeriodSeconds on the replica set should be %d but is %d", tgps, newTGPS) Expect(err).NotTo(HaveOccurred()) } } // testRollbackDeployment tests that a deployment is created (revision 1) and updated (revision 2), and // then rollback to revision 1 (should update template to revision 1, and then update revision 1 to 3), // and then rollback to last revision. func testRollbackDeployment(f *framework.Framework) { ns := f.Namespace.Name unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) podName := "nginx" deploymentPodLabels := map[string]string{"name": podName} // 1. Create a deployment to create nginx pods. deploymentName, deploymentImageName := "test-rollback-deployment", nginxImageName deploymentReplicas := int32(1) deploymentImage := nginxImage deploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType framework.Logf("Creating deployment %s", deploymentName) d := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil) createAnnotation := map[string]string{"action": "create", "author": "minion"} d.Annotations = createAnnotation deploy, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "create" err = framework.CheckNewRSAnnotations(c, ns, deploymentName, createAnnotation) Expect(err).NotTo(HaveOccurred()) // 2. Update the deployment to create redis pods. updatedDeploymentImage := redisImage updatedDeploymentImageName := redisImageName updateAnnotation := map[string]string{"action": "update", "log": "I need to update it"} deployment, err := framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName update.Spec.Template.Spec.Containers[0].Image = updatedDeploymentImage update.Annotations = updateAnnotation }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pod template update. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 2 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "2", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "update" err = framework.CheckNewRSAnnotations(c, ns, deploymentName, updateAnnotation) Expect(err).NotTo(HaveOccurred()) // 3. Update the deploymentRollback to rollback to revision 1 revision := int64(1) framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback := newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackDone in deployment status and check it here // Wait for it to be updated to revision 3 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "3", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "create", after the rollback err = framework.CheckNewRSAnnotations(c, ns, deploymentName, createAnnotation) Expect(err).NotTo(HaveOccurred()) // 4. Update the deploymentRollback to rollback to last revision revision = 0 framework.Logf("rolling back deployment %s to last revision", deploymentName) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 4 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "4", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Current newRS annotation should be "update", after the rollback err = framework.CheckNewRSAnnotations(c, ns, deploymentName, updateAnnotation) Expect(err).NotTo(HaveOccurred()) } // testRollbackDeploymentRSNoRevision tests that deployment supports rollback even when there's old replica set without revision. // An old replica set without revision is created, and then a deployment is created (v1). The deployment shouldn't add revision // annotation to the old replica set. Then rollback the deployment to last revision, and it should fail. // Then update the deployment to v2 and rollback it to v1 should succeed, now the deployment // becomes v3. Then rollback the deployment to v10 (doesn't exist in history) should fail. // Finally, rollback the deployment (v3) to v3 should be no-op. // TODO: When we finished reporting rollback status in deployment status, check the rollback status here in each case. func testRollbackDeploymentRSNoRevision(f *framework.Framework) { ns := f.Namespace.Name c := adapter.FromUnversionedClient(f.Client) podName := "nginx" deploymentPodLabels := map[string]string{"name": podName} rsPodLabels := map[string]string{ "name": podName, "pod": nginxImageName, } // Create an old RS without revision rsName := "test-rollback-no-revision-controller" rsReplicas := int32(0) rs := newRS(rsName, rsReplicas, rsPodLabels, nginxImageName, nginxImage) rs.Annotations = make(map[string]string) rs.Annotations["make"] = "difference" _, err := c.Extensions().ReplicaSets(ns).Create(rs) Expect(err).NotTo(HaveOccurred()) // 1. Create a deployment to create nginx pods, which have different template than the replica set created above. deploymentName, deploymentImageName := "test-rollback-no-revision-deployment", nginxImageName deploymentReplicas := int32(1) deploymentImage := nginxImage deploymentStrategyType := extensions.RollingUpdateDeploymentStrategyType framework.Logf("Creating deployment %s", deploymentName) d := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil) deploy, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // Check that the replica set we created still doesn't contain revision information rs, err = c.Extensions().ReplicaSets(ns).Get(rsName) Expect(err).NotTo(HaveOccurred()) Expect(rs.Annotations[deploymentutil.RevisionAnnotation]).Should(Equal("")) // 2. Update the deploymentRollback to rollback to last revision // Since there's only 1 revision in history, it should stay as revision 1 revision := int64(0) framework.Logf("rolling back deployment %s to last revision", deploymentName) rollback := newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackRevisionNotFound in deployment status and check it here // The pod template shouldn't change since there's no last revision // Check if the deployment is still revision 1 and still has the old pod template checkDeploymentRevision(c, ns, deploymentName, "1", deploymentImageName, deploymentImage) // 3. Update the deployment to create redis pods. updatedDeploymentImage := redisImage updatedDeploymentImageName := redisImageName deployment, err := framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName update.Spec.Template.Spec.Containers[0].Image = updatedDeploymentImage }) Expect(err).NotTo(HaveOccurred()) // Use observedGeneration to determine if the controller noticed the pod template update. err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) // Wait for it to be updated to revision 2 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "2", updatedDeploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // 4. Update the deploymentRollback to rollback to revision 1 revision = 1 framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackDone in deployment status and check it here // The pod template should be updated to the one in revision 1 // Wait for it to be updated to revision 3 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "3", deploymentImage) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // 5. Update the deploymentRollback to rollback to revision 10 // Since there's no revision 10 in history, it should stay as revision 3 revision = 10 framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackRevisionNotFound in deployment status and check it here // The pod template shouldn't change since there's no revision 10 // Check if it's still revision 3 and still has the old pod template checkDeploymentRevision(c, ns, deploymentName, "3", deploymentImageName, deploymentImage) // 6. Update the deploymentRollback to rollback to revision 3 // Since it's already revision 3, it should be no-op revision = 3 framework.Logf("rolling back deployment %s to revision %d", deploymentName, revision) rollback = newDeploymentRollback(deploymentName, nil, revision) err = c.Extensions().Deployments(ns).Rollback(rollback) Expect(err).NotTo(HaveOccurred()) // Wait for the deployment to start rolling back err = framework.WaitForDeploymentRollbackCleared(c, ns, deploymentName) Expect(err).NotTo(HaveOccurred()) // TODO: report RollbackTemplateUnchanged in deployment status and check it here // The pod template shouldn't change since it's already revision 3 // Check if it's still revision 3 and still has the old pod template checkDeploymentRevision(c, ns, deploymentName, "3", deploymentImageName, deploymentImage) } func testDeploymentLabelAdopted(f *framework.Framework) { ns := f.Namespace.Name // TODO: remove unversionedClient when the refactoring is done. Currently some // functions like verifyPod still expects a unversioned#Client. unversionedClient := f.Client c := adapter.FromUnversionedClient(unversionedClient) // Create nginx pods. podName := "nginx" podLabels := map[string]string{"name": podName} rsName := "test-adopted-controller" replicas := int32(3) image := nginxImage _, err := c.Extensions().ReplicaSets(ns).Create(newRS(rsName, replicas, podLabels, podName, image)) Expect(err).NotTo(HaveOccurred()) // Verify that the required pods have come up. err = framework.VerifyPods(unversionedClient, ns, podName, false, 3) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) } // Create a nginx deployment to adopt the old rs. deploymentName := "test-adopted-deployment" framework.Logf("Creating deployment %s", deploymentName) deploy, err := c.Extensions().Deployments(ns).Create(newDeployment(deploymentName, replicas, podLabels, podName, image, extensions.RollingUpdateDeploymentStrategyType, nil)) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Wait for it to be updated to revision 1 err = framework.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", image) Expect(err).NotTo(HaveOccurred()) // The RS and pods should be relabeled before the status is updated by syncRollingUpdateDeployment err = framework.WaitForDeploymentStatus(c, deploy, true) Expect(err).NotTo(HaveOccurred()) // There should be no old RSs (overlapping RS) deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) oldRSs, allOldRSs, newRS, err := deploymentutil.GetAllReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) Expect(len(oldRSs)).Should(Equal(0)) Expect(len(allOldRSs)).Should(Equal(0)) // New RS should contain pod-template-hash in its selector, label, and template label err = framework.CheckRSHashLabel(newRS) Expect(err).NotTo(HaveOccurred()) // All pods targeted by the deployment should contain pod-template-hash in their labels, and there should be only 3 pods selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) Expect(err).NotTo(HaveOccurred()) options := api.ListOptions{LabelSelector: selector} pods, err := c.Core().Pods(ns).List(options) Expect(err).NotTo(HaveOccurred()) err = framework.CheckPodHashLabel(pods) Expect(err).NotTo(HaveOccurred()) Expect(int32(len(pods.Items))).Should(Equal(replicas)) } func testScalePausedDeployment(f *framework.Framework) { ns := f.Namespace.Name c := adapter.FromUnversionedClient(f.Client) podLabels := map[string]string{"name": nginxImageName} replicas := int32(3) // Create a nginx deployment. deploymentName := "nginx-deployment" d := newDeployment(deploymentName, replicas, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) framework.Logf("Creating deployment %q", deploymentName) _, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Check that deployment is created fine. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) rs, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) // Pause the deployment and try to scale it. deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Paused = true }) Expect(err).NotTo(HaveOccurred()) // Scale the paused deployment. framework.Logf("Scaling up the paused deployment %q", deploymentName) newReplicas := int32(5) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { update.Spec.Replicas = newReplicas }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) rs, err = deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) if rs.Spec.Replicas != newReplicas { err = fmt.Errorf("Expected %d replicas for the new replica set, got %d", newReplicas, rs.Spec.Replicas) Expect(err).NotTo(HaveOccurred()) } } func testScaledRolloutDeployment(f *framework.Framework) { ns := f.Namespace.Name c := adapter.FromUnversionedClient(f.Client) podLabels := map[string]string{"name": nginxImageName} replicas := int32(10) // Create a nginx deployment. deploymentName := "nginx" d := newDeployment(deploymentName, replicas, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) d.Spec.Strategy.RollingUpdate = new(extensions.RollingUpdateDeployment) d.Spec.Strategy.RollingUpdate.MaxSurge = intstr.FromInt(3) d.Spec.Strategy.RollingUpdate.MaxUnavailable = intstr.FromInt(2) By(fmt.Sprintf("Creating deployment %q", deploymentName)) _, err := c.Extensions().Deployments(ns).Create(d) Expect(err).NotTo(HaveOccurred()) defer stopDeployment(c, f.Client, ns, deploymentName) // Check that deployment is created fine. deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for observed generation %d", deployment.Generation)) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) deployment, err = c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) first, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) // Update the deployment with a non-existent image so that the new replica set will be blocked. By(fmt.Sprintf("Updating deployment %q with a non-existent image", deploymentName)) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Image = "nginx:404" }) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for observed generation %d", deployment.Generation)) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) deployment, err = c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, false) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Checking that the replica sets for %q are synced", deploymentName)) second, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) first, err = c.Extensions().ReplicaSets(first.Namespace).Get(first.Name) Expect(err).NotTo(HaveOccurred()) firstCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), first) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, firstCond) secondCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), second) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, secondCond) By(fmt.Sprintf("Updating the size (up) and template at the same time for deployment %q", deploymentName)) newReplicas := int32(20) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { update.Spec.Replicas = newReplicas update.Spec.Template.Spec.Containers[0].Image = nautilusImage }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) oldRSs, _, rs, err := deploymentutil.GetAllReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) for _, rs := range append(oldRSs, rs) { By(fmt.Sprintf("Ensuring replica set %q has the correct desiredReplicas annotation", rs.Name)) desired, ok := deploymentutil.GetDesiredReplicasAnnotation(rs) if !ok || desired == deployment.Spec.Replicas { continue } err = fmt.Errorf("unexpected desiredReplicas annotation %d for replica set %q", desired, rs.Name) Expect(err).NotTo(HaveOccurred()) } By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) // Update the deployment with a non-existent image so that the new replica set will be blocked. By(fmt.Sprintf("Updating deployment %q with a non-existent image", deploymentName)) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, d.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Image = "nginx:404" }) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for observed generation %d", deployment.Generation)) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) deployment, err = c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, false) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Checking that the replica sets for %q are synced", deploymentName)) oldRs, err := c.Extensions().ReplicaSets(rs.Namespace).Get(rs.Name) Expect(err).NotTo(HaveOccurred()) newRs, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) oldCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), oldRs) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, oldCond) newCond := client.ReplicaSetHasDesiredReplicas(f.Client.Extensions(), newRs) wait.PollImmediate(10*time.Millisecond, 1*time.Minute, newCond) By(fmt.Sprintf("Updating the size (down) and template at the same time for deployment %q", deploymentName)) newReplicas = int32(5) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { update.Spec.Replicas = newReplicas update.Spec.Template.Spec.Containers[0].Image = kittenImage }) Expect(err).NotTo(HaveOccurred()) err = framework.WaitForObservedDeployment(c, ns, deploymentName, deployment.Generation) Expect(err).NotTo(HaveOccurred()) oldRSs, _, rs, err = deploymentutil.GetAllReplicaSets(deployment, c) Expect(err).NotTo(HaveOccurred()) for _, rs := range append(oldRSs, rs) { By(fmt.Sprintf("Ensuring replica set %q has the correct desiredReplicas annotation", rs.Name)) desired, ok := deploymentutil.GetDesiredReplicasAnnotation(rs) if !ok || desired == deployment.Spec.Replicas { continue } err = fmt.Errorf("unexpected desiredReplicas annotation %d for replica set %q", desired, rs.Name) Expect(err).NotTo(HaveOccurred()) } By(fmt.Sprintf("Waiting for deployment status to sync (current available: %d, minimum available: %d)", deployment.Status.AvailableReplicas, d.Spec.Replicas-2)) err = framework.WaitForDeploymentStatus(c, deployment, true) Expect(err).NotTo(HaveOccurred()) }
test/e2e/deployment.go
1
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.9980424642562866, 0.04784594103693962, 0.0001649269979679957, 0.003423864021897316, 0.198272243142128 ]
{ "id": 6, "code_window": [ "\terr = framework.WaitForDeploymentUpdatedReplicasLTE(c, ns, deploymentName, 1, deployment.Generation)\n", "\t// Check if it's updated to revision 1 correctly\n", "\t_, newRS := checkDeploymentRevision(c, ns, deploymentName, \"1\", deploymentImageName, deploymentImage)\n", "\n", "\t// Before the deployment finishes, update the deployment to rollover the above 2 ReplicaSets and bring up redis pods.\n", "\t// If the deployment already finished here, the test would fail. When this happens, increase its minReadySeconds or replicas to prevent it.\n", "\tExpect(newRS.Spec.Replicas).Should(BeNumerically(\"<\", deploymentReplicas))\n", "\tupdatedDeploymentImageName, updatedDeploymentImage := redisImageName, redisImage\n", "\tdeployment, err = framework.UpdateDeploymentWithRetries(c, ns, newDeployment.Name, func(update *extensions.Deployment) {\n", "\t\tupdate.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "test/e2e/deployment.go", "type": "replace", "edit_start_line_idx": 546 }
/* 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. */ // A tiny binary for testing ports. // // Reads env vars; for every var of the form SERVE_PORT_X, where X is a valid // port number, porter starts an HTTP server which serves the env var's value // in response to any query. package main import ( "fmt" "log" "net/http" "os" "strings" ) const prefix = "SERVE_PORT_" const tlsPrefix = "SERVE_TLS_PORT_" func main() { for _, vk := range os.Environ() { // Put everything before the first = sign in parts[0], and // everything else in parts[1] (even if there are multiple = // characters). parts := strings.SplitN(vk, "=", 2) key := parts[0] value := parts[1] if strings.HasPrefix(key, prefix) { port := strings.TrimPrefix(key, prefix) go servePort(port, value) } if strings.HasPrefix(key, tlsPrefix) { port := strings.TrimPrefix(key, tlsPrefix) go serveTLSPort(port, value) } } select {} } func servePort(port, value string) { s := &http.Server{ Addr: "0.0.0.0:" + port, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, value) }), } log.Printf("server on port %q failed: %v", port, s.ListenAndServe()) } func serveTLSPort(port, value string) { s := &http.Server{ Addr: "0.0.0.0:" + port, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, value) }), } certFile := os.Getenv("CERT_FILE") if len(certFile) == 0 { certFile = "localhost.crt" } keyFile := os.Getenv("KEY_FILE") if len(keyFile) == 0 { keyFile = "localhost.key" } log.Printf("tls server on port %q with certFile=%q, keyFile=%q failed: %v", port, certFile, keyFile, s.ListenAndServeTLS(certFile, keyFile)) }
test/images/porter/porter.go
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.00025775146787054837, 0.00018124279449693859, 0.00016854729619808495, 0.00017096681403927505, 0.00002721100281632971 ]
{ "id": 6, "code_window": [ "\terr = framework.WaitForDeploymentUpdatedReplicasLTE(c, ns, deploymentName, 1, deployment.Generation)\n", "\t// Check if it's updated to revision 1 correctly\n", "\t_, newRS := checkDeploymentRevision(c, ns, deploymentName, \"1\", deploymentImageName, deploymentImage)\n", "\n", "\t// Before the deployment finishes, update the deployment to rollover the above 2 ReplicaSets and bring up redis pods.\n", "\t// If the deployment already finished here, the test would fail. When this happens, increase its minReadySeconds or replicas to prevent it.\n", "\tExpect(newRS.Spec.Replicas).Should(BeNumerically(\"<\", deploymentReplicas))\n", "\tupdatedDeploymentImageName, updatedDeploymentImage := redisImageName, redisImage\n", "\tdeployment, err = framework.UpdateDeploymentWithRetries(c, ns, newDeployment.Name, func(update *extensions.Deployment) {\n", "\t\tupdate.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "test/e2e/deployment.go", "type": "replace", "edit_start_line_idx": 546 }
/* 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 v1 import ( api "k8s.io/kubernetes/pkg/api" v1 "k8s.io/kubernetes/pkg/api/v1" watch "k8s.io/kubernetes/pkg/watch" ) // NamespacesGetter has a method to return a NamespaceInterface. // A group's client should implement this interface. type NamespacesGetter interface { Namespaces() NamespaceInterface } // NamespaceInterface has methods to work with Namespace resources. type NamespaceInterface interface { Create(*v1.Namespace) (*v1.Namespace, error) Update(*v1.Namespace) (*v1.Namespace, error) UpdateStatus(*v1.Namespace) (*v1.Namespace, error) Delete(name string, options *api.DeleteOptions) error DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error Get(name string) (*v1.Namespace, error) List(opts api.ListOptions) (*v1.NamespaceList, error) Watch(opts api.ListOptions) (watch.Interface, error) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *v1.Namespace, err error) NamespaceExpansion } // namespaces implements NamespaceInterface type namespaces struct { client *CoreClient } // newNamespaces returns a Namespaces func newNamespaces(c *CoreClient) *namespaces { return &namespaces{ client: c, } } // Create takes the representation of a namespace and creates it. Returns the server's representation of the namespace, and an error, if there is any. func (c *namespaces) Create(namespace *v1.Namespace) (result *v1.Namespace, err error) { result = &v1.Namespace{} err = c.client.Post(). Resource("namespaces"). Body(namespace). Do(). Into(result) return } // Update takes the representation of a namespace and updates it. Returns the server's representation of the namespace, and an error, if there is any. func (c *namespaces) Update(namespace *v1.Namespace) (result *v1.Namespace, err error) { result = &v1.Namespace{} err = c.client.Put(). Resource("namespaces"). Name(namespace.Name). Body(namespace). Do(). Into(result) return } func (c *namespaces) UpdateStatus(namespace *v1.Namespace) (result *v1.Namespace, err error) { result = &v1.Namespace{} err = c.client.Put(). Resource("namespaces"). Name(namespace.Name). SubResource("status"). Body(namespace). Do(). Into(result) return } // Delete takes name of the namespace and deletes it. Returns an error if one occurs. func (c *namespaces) Delete(name string, options *api.DeleteOptions) error { return c.client.Delete(). Resource("namespaces"). Name(name). Body(options). Do(). Error() } // DeleteCollection deletes a collection of objects. func (c *namespaces) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { return c.client.Delete(). Resource("namespaces"). VersionedParams(&listOptions, api.ParameterCodec). Body(options). Do(). Error() } // Get takes name of the namespace, and returns the corresponding namespace object, and an error if there is any. func (c *namespaces) Get(name string) (result *v1.Namespace, err error) { result = &v1.Namespace{} err = c.client.Get(). Resource("namespaces"). Name(name). Do(). Into(result) return } // List takes label and field selectors, and returns the list of Namespaces that match those selectors. func (c *namespaces) List(opts api.ListOptions) (result *v1.NamespaceList, err error) { result = &v1.NamespaceList{} err = c.client.Get(). Resource("namespaces"). VersionedParams(&opts, api.ParameterCodec). Do(). Into(result) return } // Watch returns a watch.Interface that watches the requested namespaces. func (c *namespaces) Watch(opts api.ListOptions) (watch.Interface, error) { return c.client.Get(). Prefix("watch"). Resource("namespaces"). VersionedParams(&opts, api.ParameterCodec). Watch() } // Patch applies the patch and returns the patched namespace. func (c *namespaces) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *v1.Namespace, err error) { result = &v1.Namespace{} err = c.client.Patch(pt). Resource("namespaces"). SubResource(subresources...). Name(name). Body(data). Do(). Into(result) return }
federation/client/clientset_generated/federation_release_1_4/typed/core/v1/namespace.go
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.000642420316580683, 0.00019578772480599582, 0.00015751719183754176, 0.00016606618009973317, 0.00011547682515811175 ]
{ "id": 6, "code_window": [ "\terr = framework.WaitForDeploymentUpdatedReplicasLTE(c, ns, deploymentName, 1, deployment.Generation)\n", "\t// Check if it's updated to revision 1 correctly\n", "\t_, newRS := checkDeploymentRevision(c, ns, deploymentName, \"1\", deploymentImageName, deploymentImage)\n", "\n", "\t// Before the deployment finishes, update the deployment to rollover the above 2 ReplicaSets and bring up redis pods.\n", "\t// If the deployment already finished here, the test would fail. When this happens, increase its minReadySeconds or replicas to prevent it.\n", "\tExpect(newRS.Spec.Replicas).Should(BeNumerically(\"<\", deploymentReplicas))\n", "\tupdatedDeploymentImageName, updatedDeploymentImage := redisImageName, redisImage\n", "\tdeployment, err = framework.UpdateDeploymentWithRetries(c, ns, newDeployment.Name, func(update *extensions.Deployment) {\n", "\t\tupdate.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "test/e2e/deployment.go", "type": "replace", "edit_start_line_idx": 546 }
package members import ( "github.com/rackspace/gophercloud" "github.com/rackspace/gophercloud/pagination" ) // 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 floating IP attributes you want to see returned. SortKey allows you to // sort by a particular network attribute. SortDir sets the direction, and is // either `asc' or `desc'. Marker and Limit are used for pagination. type ListOpts struct { Status string `q:"status"` Weight int `q:"weight"` AdminStateUp *bool `q:"admin_state_up"` TenantID string `q:"tenant_id"` PoolID string `q:"pool_id"` Address string `q:"address"` ProtocolPort int `q:"protocol_port"` ID string `q:"id"` Limit int `q:"limit"` Marker string `q:"marker"` SortKey string `q:"sort_key"` SortDir string `q:"sort_dir"` } // List returns a Pager which allows you to iterate over a collection of // pools. It accepts a ListOpts struct, which allows you to filter and sort // the returned collection for greater efficiency. // // Default policy settings return only those pools that are owned by the // tenant who submits the request, unless an admin user submits the request. func List(c *gophercloud.ServiceClient, opts ListOpts) pagination.Pager { q, err := gophercloud.BuildQueryString(&opts) if err != nil { return pagination.Pager{Err: err} } u := rootURL(c) + q.String() return pagination.NewPager(c, u, func(r pagination.PageResult) pagination.Page { return MemberPage{pagination.LinkedPageBase{PageResult: r}} }) } // CreateOpts contains all the values needed to create a new pool member. type CreateOpts struct { // Only required if the caller has an admin role and wants to create a pool // for another tenant. TenantID string // Required. The IP address of the member. Address string // Required. The port on which the application is hosted. ProtocolPort int // Required. The pool to which this member will belong. PoolID string } // Create accepts a CreateOpts struct and uses the values to create a new // load balancer pool member. func Create(c *gophercloud.ServiceClient, opts CreateOpts) CreateResult { type member struct { TenantID string `json:"tenant_id,omitempty"` ProtocolPort int `json:"protocol_port"` Address string `json:"address"` PoolID string `json:"pool_id"` } type request struct { Member member `json:"member"` } reqBody := request{Member: member{ Address: opts.Address, TenantID: opts.TenantID, ProtocolPort: opts.ProtocolPort, PoolID: opts.PoolID, }} var res CreateResult _, res.Err = c.Post(rootURL(c), reqBody, &res.Body, nil) return res } // Get retrieves a particular pool member based on its unique ID. func Get(c *gophercloud.ServiceClient, id string) GetResult { var res GetResult _, res.Err = c.Get(resourceURL(c, id), &res.Body, nil) return res } // UpdateOpts contains the values used when updating a pool member. type UpdateOpts struct { // The administrative state of the member, which is up (true) or down (false). AdminStateUp bool } // Update allows members to be updated. func Update(c *gophercloud.ServiceClient, id string, opts UpdateOpts) UpdateResult { type member struct { AdminStateUp bool `json:"admin_state_up"` } type request struct { Member member `json:"member"` } reqBody := request{Member: member{AdminStateUp: opts.AdminStateUp}} // Send request to API var res UpdateResult _, res.Err = c.Put(resourceURL(c, id), reqBody, &res.Body, &gophercloud.RequestOpts{ OkCodes: []int{200, 201, 202}, }) return res } // Delete will permanently delete a particular member based on its unique ID. func Delete(c *gophercloud.ServiceClient, id string) DeleteResult { var res DeleteResult _, res.Err = c.Delete(resourceURL(c, id), nil) return res }
vendor/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/members/requests.go
0
https://github.com/kubernetes/kubernetes/commit/b45afc04a2cd3eca6b36911c765213dcb0140975
[ 0.0003393425140529871, 0.00018883107986766845, 0.00016426702495664358, 0.00016801778110675514, 0.00005051785410614684 ]
{ "id": 0, "code_window": [ "\t\"github.com/harness/gitness/types\"\n", ")\n", "\n", "type Controller struct {\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "type registrationCheck func(ctx context.Context) (bool, error)\n", "\n" ], "file_path": "internal/api/controller/system/controller.go", "type": "add", "edit_start_line_idx": 13 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package user import ( "context" "fmt" "github.com/harness/gitness/internal/api/controller/system" "github.com/harness/gitness/internal/api/usererror" "github.com/harness/gitness/internal/token" "github.com/harness/gitness/types" ) // Register creates a new user and returns a new session token on success. // This differs from the Create method as it doesn't require auth, but has limited // functionalities (unable to create admin user for example). func (c *Controller) Register(ctx context.Context, in *CreateInput) (*types.TokenResponse, error) { signUpAllowed, err := system.IsUserRegistrationAllowed(ctx, c.principalStore, c.config) if err != nil { return nil, err } if !signUpAllowed { return nil, usererror.ErrForbidden } user, err := c.CreateNoAuth(ctx, &CreateInput{ UID: in.UID, Email: in.Email, DisplayName: in.DisplayName, Password: in.Password, }, false) if err != nil { return nil, fmt.Errorf("failed to create user: %w", err) } // TODO: how should we name session tokens? token, jwtToken, err := token.CreateUserSession(ctx, c.tokenStore, user, "register") if err != nil { return nil, fmt.Errorf("failed to create token after successful user creation: %w", err) } return &types.TokenResponse{Token: *token, AccessToken: jwtToken}, nil }
internal/api/controller/user/register.go
1
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.9956955909729004, 0.19927534461021423, 0.00016868571401573718, 0.00017032865434885025, 0.3982101082801819 ]
{ "id": 0, "code_window": [ "\t\"github.com/harness/gitness/types\"\n", ")\n", "\n", "type Controller struct {\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "type registrationCheck func(ctx context.Context) (bool, error)\n", "\n" ], "file_path": "internal/api/controller/system/controller.go", "type": "add", "edit_start_line_idx": 13 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package authz import ( "context" "errors" "github.com/harness/gitness/internal/auth" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) var ( // ErrNoPermissionCheckProvided is error that is thrown if no permission checks are provided. ErrNoPermissionCheckProvided = errors.New("no permission checks provided") ) // Authorizer abstraction of an entity responsible for authorizing access to resources. type Authorizer interface { /* * Checks whether the principal of the current session with the provided metadata * has the permission to execute the action on the resource within the scope. * Returns * (true, nil) - the action is permitted * (false, nil) - the action is not permitted * (false, err) - an error occurred while performing the permission check and the action should be denied */ Check(ctx context.Context, session *auth.Session, scope *types.Scope, resource *types.Resource, permission enum.Permission) (bool, error) /* * Checks whether the principal of the current session with the provided metadata * has the permission to execute ALL the action on the resource within the scope. * Returns * (true, nil) - all requested actions are permitted * (false, nil) - at least one requested action is not permitted * (false, err) - an error occurred while performing the permission check and all actions should be denied */ CheckAll(ctx context.Context, session *auth.Session, permissionChecks ...types.PermissionCheck) (bool, error) }
internal/auth/authz/authz.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.005490415263921022, 0.0012392040807753801, 0.00016784931358415633, 0.00016988502466119826, 0.0021256364416331053 ]
{ "id": 0, "code_window": [ "\t\"github.com/harness/gitness/types\"\n", ")\n", "\n", "type Controller struct {\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "type registrationCheck func(ctx context.Context) (bool, error)\n", "\n" ], "file_path": "internal/api/controller/system/controller.go", "type": "add", "edit_start_line_idx": 13 }
# Compiled Form Modules *.fmx # Compiled Menu Modules *.mmx # Compiled Pre-Linked Libraries *.plx
resources/gitignore/OracleForms.gitignore
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00017208945064339787, 0.00017208945064339787, 0.00017208945064339787, 0.00017208945064339787, 0 ]
{ "id": 0, "code_window": [ "\t\"github.com/harness/gitness/types\"\n", ")\n", "\n", "type Controller struct {\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "type registrationCheck func(ctx context.Context) (bool, error)\n", "\n" ], "file_path": "internal/api/controller/system/controller.go", "type": "add", "edit_start_line_idx": 13 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package serviceaccount import ( "context" "github.com/harness/gitness/internal/auth/authz" "github.com/harness/gitness/internal/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/check" ) type Controller struct { principalUIDCheck check.PrincipalUID authorizer authz.Authorizer principalStore store.PrincipalStore spaceStore store.SpaceStore repoStore store.RepoStore tokenStore store.TokenStore } func NewController(principalUIDCheck check.PrincipalUID, authorizer authz.Authorizer, principalStore store.PrincipalStore, spaceStore store.SpaceStore, repoStore store.RepoStore, tokenStore store.TokenStore) *Controller { return &Controller{ principalUIDCheck: principalUIDCheck, authorizer: authorizer, principalStore: principalStore, spaceStore: spaceStore, repoStore: repoStore, tokenStore: tokenStore, } } func findServiceAccountFromUID(ctx context.Context, principalStore store.PrincipalStore, saUID string) (*types.ServiceAccount, error) { return principalStore.FindServiceAccountByUID(ctx, saUID) }
internal/api/controller/serviceaccount/controller.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.9959761500358582, 0.39410680532455444, 0.0001690373755991459, 0.00024163725902326405, 0.48248937726020813 ]
{ "id": 1, "code_window": [ "type Controller struct {\n", "\tprincipalStore store.PrincipalStore\n", "\tconfig *types.Config\n", "}\n", "\n", "func NewController(principalStore store.PrincipalStore, config *types.Config) *Controller {\n", "\treturn &Controller{\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprincipalStore store.PrincipalStore\n", "\tconfig *types.Config\n", "\tIsUserRegistrationAllowed registrationCheck\n" ], "file_path": "internal/api/controller/system/controller.go", "type": "replace", "edit_start_line_idx": 14 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package account import ( "encoding/json" "net/http" "github.com/harness/gitness/internal/api/controller/user" "github.com/harness/gitness/internal/api/render" ) // HandleRegister returns an http.HandlerFunc that processes an http.Request // to register the named user account with the system. func HandleRegister(userCtrl *user.Controller) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() in := new(user.CreateInput) err := json.NewDecoder(r.Body).Decode(in) if err != nil { render.BadRequestf(w, "Invalid request body: %s.", err) return } tokenResponse, err := userCtrl.Register(ctx, in) if err != nil { render.TranslatedUserError(w, err) return } render.JSON(w, http.StatusOK, tokenResponse) } }
internal/api/handler/account/register.go
1
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.6917928457260132, 0.17307813465595245, 0.00016893376596271992, 0.00017538326210342348, 0.2994800806045532 ]
{ "id": 1, "code_window": [ "type Controller struct {\n", "\tprincipalStore store.PrincipalStore\n", "\tconfig *types.Config\n", "}\n", "\n", "func NewController(principalStore store.PrincipalStore, config *types.Config) *Controller {\n", "\treturn &Controller{\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprincipalStore store.PrincipalStore\n", "\tconfig *types.Config\n", "\tIsUserRegistrationAllowed registrationCheck\n" ], "file_path": "internal/api/controller/system/controller.go", "type": "replace", "edit_start_line_idx": 14 }
# Ignore Play! working directory # bin/ /db .eclipse /lib/ /logs/ /modules /project/project /project/target /target tmp/ test-result server.pid *.eml /dist/ .cache
resources/gitignore/PlayFramework.gitignore
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00017491119797341526, 0.0001743751490721479, 0.00017383910017088056, 0.0001743751490721479, 5.360489012673497e-7 ]
{ "id": 1, "code_window": [ "type Controller struct {\n", "\tprincipalStore store.PrincipalStore\n", "\tconfig *types.Config\n", "}\n", "\n", "func NewController(principalStore store.PrincipalStore, config *types.Config) *Controller {\n", "\treturn &Controller{\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprincipalStore store.PrincipalStore\n", "\tconfig *types.Config\n", "\tIsUserRegistrationAllowed registrationCheck\n" ], "file_path": "internal/api/controller/system/controller.go", "type": "replace", "edit_start_line_idx": 14 }
CREATE INDEX webhooks_repo_id ON webhooks(webhook_repo_id);
internal/store/database/migrate/postgres/0008_create_index_webhooks_repo_id.up.sql
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00016560776566620916, 0.00016560776566620916, 0.00016560776566620916, 0.00016560776566620916, 0 ]
{ "id": 1, "code_window": [ "type Controller struct {\n", "\tprincipalStore store.PrincipalStore\n", "\tconfig *types.Config\n", "}\n", "\n", "func NewController(principalStore store.PrincipalStore, config *types.Config) *Controller {\n", "\treturn &Controller{\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprincipalStore store.PrincipalStore\n", "\tconfig *types.Config\n", "\tIsUserRegistrationAllowed registrationCheck\n" ], "file_path": "internal/api/controller/system/controller.go", "type": "replace", "edit_start_line_idx": 14 }
// Copyright 2022 Harness Inc. All rights reserved. // Use of this source code is governed by the Polyform Free Trial License // that can be found in the LICENSE.md file for this repository. package auth import ( "context" "fmt" "github.com/harness/gitness/internal/auth" "github.com/harness/gitness/internal/auth/authz" "github.com/harness/gitness/internal/paths" "github.com/harness/gitness/internal/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/pkg/errors" "github.com/rs/zerolog/log" ) var ( ErrNotAuthenticated = errors.New("not authenticated") ErrNotAuthorized = errors.New("not authorized") ErrParentResourceTypeUnknown = errors.New("Unknown parent resource type") ) /* * Check checks if a resource specific permission is granted for the current auth session in the scope. * Returns nil if the permission is granted, otherwise returns an error. * NotAuthenticated, NotAuthorized, or any unerlaying error. */ func Check(ctx context.Context, authorizer authz.Authorizer, session *auth.Session, scope *types.Scope, resource *types.Resource, permission enum.Permission) error { if session == nil { return ErrNotAuthenticated } authorized, err := authorizer.Check( ctx, session, scope, resource, permission) if err != nil { return err } if !authorized { return ErrNotAuthorized } return nil } /* * CheckChild checks if a resource specific permission is granted for the current auth session * in the scope of a parent. * Returns nil if the permission is granted, otherwise returns an error. * NotAuthenticated, NotAuthorized, or any unerlaying error. */ func CheckChild(ctx context.Context, authorizer authz.Authorizer, session *auth.Session, spaceStore store.SpaceStore, repoStore store.RepoStore, parentType enum.ParentResourceType, parentID int64, resourceType enum.ResourceType, resourceName string, permission enum.Permission) error { scope, err := getScopeForParent(ctx, spaceStore, repoStore, parentType, parentID) if err != nil { return err } resource := &types.Resource{ Type: resourceType, Name: resourceName, } return Check(ctx, authorizer, session, scope, resource, permission) } // getScopeForParent Returns the scope for a given resource parent (space or repo). func getScopeForParent(ctx context.Context, spaceStore store.SpaceStore, repoStore store.RepoStore, parentType enum.ParentResourceType, parentID int64) (*types.Scope, error) { // TODO: Can this be done cleaner? switch parentType { case enum.ParentResourceTypeSpace: space, err := spaceStore.Find(ctx, parentID) if err != nil { return nil, fmt.Errorf("parent space not found: %w", err) } return &types.Scope{SpacePath: space.Path}, nil case enum.ParentResourceTypeRepo: repo, err := repoStore.Find(ctx, parentID) if err != nil { return nil, fmt.Errorf("parent repo not found: %w", err) } spacePath, repoName, err := paths.DisectLeaf(repo.Path) if err != nil { return nil, errors.Wrapf(err, "Failed to disect path '%s'", repo.Path) } return &types.Scope{SpacePath: spacePath, Repo: repoName}, nil default: log.Ctx(ctx).Debug().Msgf("Unsupported parent type encountered: '%s'", parentType) return nil, ErrParentResourceTypeUnknown } }
internal/api/auth/auth.go
0
https://github.com/harness/gitness/commit/f18f142401b4a8dea0e7e0d7339b2de4741a7cbb
[ 0.00018007760809268802, 0.00017149456834886223, 0.0001646057062316686, 0.0001718864223221317, 0.000003878102234011749 ]