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": 3, "code_window": [ "\treqd discovery.PluginRequirements,\n", ") (map[addrs.Provider]providers.Factory, []error) {\n", "\tfactories := make(map[addrs.Provider]providers.Factory, len(reqd))\n", "\tvar errs []error\n", "\n", "\tchosen := choosePlugins(r.Available, r.Internal, reqd)\n", "\tfor name, req := range reqd {\n", "\t\tif factory, isInternal := r.Internal[addrs.NewLegacyProvider(name)]; isInternal {\n", "\t\t\tif !req.Versions.Unconstrained() {\n", "\t\t\t\terrs = append(errs, fmt.Errorf(\"provider.%s: this provider is built in to Terraform and so it does not support version constraints\", name))\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tchosen := chooseProviders(r.Available, r.Internal, reqd)\n" ], "file_path": "command/plugins.go", "type": "replace", "edit_start_line_idx": 65 }
package command import ( "fmt" "log" "os" "sort" "strings" "github.com/hashicorp/hcl/v2" "github.com/hashicorp/terraform-config-inspect/tfconfig" "github.com/posener/complete" "github.com/zclconf/go-cty/cty" "github.com/hashicorp/errwrap" "github.com/hashicorp/terraform/addrs" "github.com/hashicorp/terraform/backend" backendInit "github.com/hashicorp/terraform/backend/init" "github.com/hashicorp/terraform/configs" "github.com/hashicorp/terraform/configs/configschema" "github.com/hashicorp/terraform/configs/configupgrade" "github.com/hashicorp/terraform/internal/earlyconfig" "github.com/hashicorp/terraform/internal/initwd" "github.com/hashicorp/terraform/plugin/discovery" "github.com/hashicorp/terraform/states" "github.com/hashicorp/terraform/terraform" "github.com/hashicorp/terraform/tfdiags" ) // InitCommand is a Command implementation that takes a Terraform // module and clones it to the working directory. type InitCommand struct { Meta // getPlugins is for the -get-plugins flag getPlugins bool // providerInstaller is used to download and install providers that // aren't found locally. This uses a discovery.ProviderInstaller instance // by default, but it can be overridden here as a way to mock fetching // providers for tests. providerInstaller discovery.Installer } func (c *InitCommand) Run(args []string) int { var flagFromModule string var flagBackend, flagGet, flagUpgrade bool var flagPluginPath FlagStringSlice var flagVerifyPlugins bool flagConfigExtra := newRawFlags("-backend-config") args, err := c.Meta.process(args, false) if err != nil { return 1 } cmdFlags := c.Meta.extendedFlagSet("init") cmdFlags.BoolVar(&flagBackend, "backend", true, "") cmdFlags.Var(flagConfigExtra, "backend-config", "") cmdFlags.StringVar(&flagFromModule, "from-module", "", "copy the source of the given module into the directory before init") cmdFlags.BoolVar(&flagGet, "get", true, "") cmdFlags.BoolVar(&c.getPlugins, "get-plugins", true, "") cmdFlags.BoolVar(&c.forceInitCopy, "force-copy", false, "suppress prompts about copying state data") cmdFlags.BoolVar(&c.Meta.stateLock, "lock", true, "lock state") cmdFlags.DurationVar(&c.Meta.stateLockTimeout, "lock-timeout", 0, "lock timeout") cmdFlags.BoolVar(&c.reconfigure, "reconfigure", false, "reconfigure") cmdFlags.BoolVar(&flagUpgrade, "upgrade", false, "") cmdFlags.Var(&flagPluginPath, "plugin-dir", "plugin directory") cmdFlags.BoolVar(&flagVerifyPlugins, "verify-plugins", true, "verify plugins") cmdFlags.Usage = func() { c.Ui.Error(c.Help()) } if err := cmdFlags.Parse(args); err != nil { return 1 } var diags tfdiags.Diagnostics if len(flagPluginPath) > 0 { c.pluginPath = flagPluginPath c.getPlugins = false } // set providerInstaller if we don't have a test version already if c.providerInstaller == nil { c.providerInstaller = &discovery.ProviderInstaller{ Dir: c.pluginDir(), Cache: c.pluginCache(), PluginProtocolVersion: discovery.PluginInstallProtocolVersion, SkipVerify: !flagVerifyPlugins, Ui: c.Ui, Services: c.Services, } } // Validate the arg count args = cmdFlags.Args() if len(args) > 1 { c.Ui.Error("The init command expects at most one argument.\n") cmdFlags.Usage() return 1 } if err := c.storePluginPath(c.pluginPath); err != nil { c.Ui.Error(fmt.Sprintf("Error saving -plugin-path values: %s", err)) return 1 } // Get our pwd. We don't always need it but always getting it is easier // than the logic to determine if it is or isn't needed. pwd, err := os.Getwd() if err != nil { c.Ui.Error(fmt.Sprintf("Error getting pwd: %s", err)) return 1 } // If an argument is provided then it overrides our working directory. path := pwd if len(args) == 1 { path = args[0] } // This will track whether we outputted anything so that we know whether // to output a newline before the success message var header bool if flagFromModule != "" { src := flagFromModule empty, err := configs.IsEmptyDir(path) if err != nil { c.Ui.Error(fmt.Sprintf("Error validating destination directory: %s", err)) return 1 } if !empty { c.Ui.Error(strings.TrimSpace(errInitCopyNotEmpty)) return 1 } c.Ui.Output(c.Colorize().Color(fmt.Sprintf( "[reset][bold]Copying configuration[reset] from %q...", src, ))) header = true hooks := uiModuleInstallHooks{ Ui: c.Ui, ShowLocalPaths: false, // since they are in a weird location for init } initDiags := c.initDirFromModule(path, src, hooks) diags = diags.Append(initDiags) if initDiags.HasErrors() { c.showDiagnostics(diags) return 1 } c.Ui.Output("") } // If our directory is empty, then we're done. We can't get or setup // the backend with an empty directory. empty, err := configs.IsEmptyDir(path) if err != nil { diags = diags.Append(fmt.Errorf("Error checking configuration: %s", err)) return 1 } if empty { c.Ui.Output(c.Colorize().Color(strings.TrimSpace(outputInitEmpty))) return 0 } // Before we do anything else, we'll try loading configuration with both // our "normal" and "early" configuration codepaths. If early succeeds // while normal fails, that strongly suggests that the configuration is // using syntax that worked in 0.11 but no longer in 0.12, which requires // some special behavior here to get the directory initialized just enough // to run "terraform 0.12upgrade". // // FIXME: Once we reach 0.13 and remove 0.12upgrade, we should rework this // so that we first use the early config to do a general compatibility // check with dependencies, producing version-oriented error messages if // dependencies aren't right, and only then use the real loader to deal // with the backend configuration. rootMod, confDiags := c.loadSingleModule(path) rootModEarly, earlyConfDiags := c.loadSingleModuleEarly(path) configUpgradeProbablyNeeded := false if confDiags.HasErrors() { if earlyConfDiags.HasErrors() { // If both parsers produced errors then we'll assume the config // is _truly_ invalid and produce error messages as normal. // Since this may be the user's first ever interaction with Terraform, // we'll provide some additional context in this case. c.Ui.Error(strings.TrimSpace(errInitConfigError)) diags = diags.Append(confDiags) c.showDiagnostics(diags) return 1 } // If _only_ the main loader produced errors then that suggests an // upgrade may help. To give us more certainty here, we'll use the // same heuristic that "terraform 0.12upgrade" uses to guess if a // configuration has already been upgraded, to reduce the risk that // we'll produce a misleading message if the problem is just a regular // syntax error that the early loader just didn't catch. sources, err := configupgrade.LoadModule(path) if err == nil { if already, _ := sources.MaybeAlreadyUpgraded(); already { // Just report the errors as normal, then. c.Ui.Error(strings.TrimSpace(errInitConfigError)) diags = diags.Append(confDiags) c.showDiagnostics(diags) return 1 } } configUpgradeProbablyNeeded = true } if earlyConfDiags.HasErrors() { // If _only_ the early loader encountered errors then that's unusual // (it should generally be a superset of the normal loader) but we'll // return those errors anyway since otherwise we'll probably get // some weird behavior downstream. Errors from the early loader are // generally not as high-quality since it has less context to work with. c.Ui.Error(strings.TrimSpace(errInitConfigError)) diags = diags.Append(earlyConfDiags) c.showDiagnostics(diags) return 1 } if flagGet { modsOutput, modsDiags := c.getModules(path, rootModEarly, flagUpgrade) diags = diags.Append(modsDiags) if modsDiags.HasErrors() { c.showDiagnostics(diags) return 1 } if modsOutput { header = true } } // With all of the modules (hopefully) installed, we can now try to load // the whole configuration tree. // // Just as above, we'll try loading both with the early and normal config // loaders here. Subsequent work will only use the early config, but // loading both gives us an opportunity to prefer the better error messages // from the normal loader if both fail. _, confDiags = c.loadConfig(path) earlyConfig, earlyConfDiags := c.loadConfigEarly(path) if confDiags.HasErrors() && !configUpgradeProbablyNeeded { c.Ui.Error(strings.TrimSpace(errInitConfigError)) diags = diags.Append(confDiags) c.showDiagnostics(diags) return 1 } if earlyConfDiags.HasErrors() { c.Ui.Error(strings.TrimSpace(errInitConfigError)) diags = diags.Append(earlyConfDiags) c.showDiagnostics(diags) return 1 } { // Before we go further, we'll check to make sure none of the modules // in the configuration declare that they don't support this Terraform // version, so we can produce a version-related error message rather // than potentially-confusing downstream errors. versionDiags := initwd.CheckCoreVersionRequirements(earlyConfig) diags = diags.Append(versionDiags) if versionDiags.HasErrors() { c.showDiagnostics(diags) return 1 } } var back backend.Backend if flagBackend { switch { case configUpgradeProbablyNeeded: diags = diags.Append(tfdiags.Sourceless( tfdiags.Warning, "Skipping backend initialization pending configuration upgrade", // The "below" in this message is referring to the special // note about running "terraform 0.12upgrade" that we'll // print out at the end when configUpgradeProbablyNeeded is set. "The root module configuration contains errors that may be fixed by running the configuration upgrade tool, so Terraform is skipping backend initialization. See below for more information.", )) default: be, backendOutput, backendDiags := c.initBackend(rootMod, flagConfigExtra) diags = diags.Append(backendDiags) if backendDiags.HasErrors() { c.showDiagnostics(diags) return 1 } if backendOutput { header = true } back = be } } if back == nil { // If we didn't initialize a backend then we'll try to at least // instantiate one. This might fail if it wasn't already initialized // by a previous run, so we must still expect that "back" may be nil // in code that follows. var backDiags tfdiags.Diagnostics back, backDiags = c.Backend(nil) if backDiags.HasErrors() { // This is fine. We'll proceed with no backend, then. back = nil } } var state *states.State // If we have a functional backend (either just initialized or initialized // on a previous run) we'll use the current state as a potential source // of provider dependencies. if back != nil { sMgr, err := back.StateMgr(c.Workspace()) if err != nil { c.Ui.Error(fmt.Sprintf("Error loading state: %s", err)) return 1 } if err := sMgr.RefreshState(); err != nil { c.Ui.Error(fmt.Sprintf("Error refreshing state: %s", err)) return 1 } state = sMgr.State() } if v := os.Getenv(ProviderSkipVerifyEnvVar); v != "" { c.ignorePluginChecksum = true } // Now that we have loaded all modules, check the module tree for missing providers. providersOutput, providerDiags := c.getProviders(earlyConfig, state, flagUpgrade) diags = diags.Append(providerDiags) if providerDiags.HasErrors() { c.showDiagnostics(diags) return 1 } if providersOutput { header = true } // If we outputted information, then we need to output a newline // so that our success message is nicely spaced out from prior text. if header { c.Ui.Output("") } // If we accumulated any warnings along the way that weren't accompanied // by errors then we'll output them here so that the success message is // still the final thing shown. c.showDiagnostics(diags) if configUpgradeProbablyNeeded { switch { case c.RunningInAutomation: c.Ui.Output(c.Colorize().Color(strings.TrimSpace(outputInitSuccessConfigUpgrade))) default: c.Ui.Output(c.Colorize().Color(strings.TrimSpace(outputInitSuccessConfigUpgradeCLI))) } return 0 } c.Ui.Output(c.Colorize().Color(strings.TrimSpace(outputInitSuccess))) if !c.RunningInAutomation { // If we're not running in an automation wrapper, give the user // some more detailed next steps that are appropriate for interactive // shell usage. c.Ui.Output(c.Colorize().Color(strings.TrimSpace(outputInitSuccessCLI))) } return 0 } func (c *InitCommand) getModules(path string, earlyRoot *tfconfig.Module, upgrade bool) (output bool, diags tfdiags.Diagnostics) { if len(earlyRoot.ModuleCalls) == 0 { // Nothing to do return false, nil } if upgrade { c.Ui.Output(c.Colorize().Color(fmt.Sprintf("[reset][bold]Upgrading modules..."))) } else { c.Ui.Output(c.Colorize().Color(fmt.Sprintf("[reset][bold]Initializing modules..."))) } hooks := uiModuleInstallHooks{ Ui: c.Ui, ShowLocalPaths: true, } instDiags := c.installModules(path, upgrade, hooks) diags = diags.Append(instDiags) // Since module installer has modified the module manifest on disk, we need // to refresh the cache of it in the loader. if c.configLoader != nil { if err := c.configLoader.RefreshModules(); err != nil { // Should never happen diags = diags.Append(tfdiags.Sourceless( tfdiags.Error, "Failed to read module manifest", fmt.Sprintf("After installing modules, Terraform could not re-read the manifest of installed modules. This is a bug in Terraform. %s.", err), )) } } return true, diags } func (c *InitCommand) initBackend(root *configs.Module, extraConfig rawFlags) (be backend.Backend, output bool, diags tfdiags.Diagnostics) { c.Ui.Output(c.Colorize().Color(fmt.Sprintf("\n[reset][bold]Initializing the backend..."))) var backendConfig *configs.Backend var backendConfigOverride hcl.Body if root.Backend != nil { backendType := root.Backend.Type bf := backendInit.Backend(backendType) if bf == nil { diags = diags.Append(&hcl.Diagnostic{ Severity: hcl.DiagError, Summary: "Unsupported backend type", Detail: fmt.Sprintf("There is no backend type named %q.", backendType), Subject: &root.Backend.TypeRange, }) return nil, true, diags } b := bf() backendSchema := b.ConfigSchema() backendConfig = root.Backend var overrideDiags tfdiags.Diagnostics backendConfigOverride, overrideDiags = c.backendConfigOverrideBody(extraConfig, backendSchema) diags = diags.Append(overrideDiags) if overrideDiags.HasErrors() { return nil, true, diags } } else { // If the user supplied a -backend-config on the CLI but no backend // block was found in the configuration, it's likely - but not // necessarily - a mistake. Return a warning. if !extraConfig.Empty() { diags = diags.Append(tfdiags.Sourceless( tfdiags.Warning, "Missing backend configuration", `-backend-config was used without a "backend" block in the configuration. If you intended to override the default local backend configuration, no action is required, but you may add an explicit backend block to your configuration to clear this warning: terraform { backend "local" {} } However, if you intended to override a defined backend, please verify that the backend configuration is present and valid. `, )) } } opts := &BackendOpts{ Config: backendConfig, ConfigOverride: backendConfigOverride, Init: true, } back, backDiags := c.Backend(opts) diags = diags.Append(backDiags) return back, true, diags } // Load the complete module tree, and fetch any missing providers. // This method outputs its own Ui. func (c *InitCommand) getProviders(earlyConfig *earlyconfig.Config, state *states.State, upgrade bool) (output bool, diags tfdiags.Diagnostics) { var available discovery.PluginMetaSet if upgrade { // If we're in upgrade mode, we ignore any auto-installed plugins // in "available", causing us to reinstall and possibly upgrade them. available = c.providerPluginManuallyInstalledSet() } else { available = c.providerPluginSet() } configDeps, depsDiags := earlyConfig.ProviderDependencies() diags = diags.Append(depsDiags) if depsDiags.HasErrors() { return false, diags } configReqs := configDeps.AllPluginRequirements() // FIXME: This is weird because ConfigTreeDependencies was written before // we switched over to using earlyConfig as the main source of dependencies. // In future we should clean this up to be a more reasoable API. stateReqs := terraform.ConfigTreeDependencies(nil, state).AllPluginRequirements() requirements := configReqs.Merge(stateReqs) if len(requirements) == 0 { // nothing to initialize return false, nil } c.Ui.Output(c.Colorize().Color( "\n[reset][bold]Initializing provider plugins...", )) missing := c.missingPlugins(available, requirements) if c.getPlugins { if len(missing) > 0 { c.Ui.Output("- Checking for available provider plugins...") } for provider, reqd := range missing { pty := addrs.Provider{Type: provider} _, providerDiags, err := c.providerInstaller.Get(pty, reqd.Versions) diags = diags.Append(providerDiags) if err != nil { constraint := reqd.Versions.String() if constraint == "" { constraint = "(any version)" } switch { case err == discovery.ErrorServiceUnreachable, err == discovery.ErrorPublicRegistryUnreachable: c.Ui.Error(errDiscoveryServiceUnreachable) case err == discovery.ErrorNoSuchProvider: c.Ui.Error(fmt.Sprintf(errProviderNotFound, provider, DefaultPluginVendorDir)) case err == discovery.ErrorNoSuitableVersion: if reqd.Versions.Unconstrained() { // This should never happen, but might crop up if we catch // the releases server in a weird state where the provider's // directory is present but does not yet contain any // versions. We'll treat it like ErrorNoSuchProvider, then. c.Ui.Error(fmt.Sprintf(errProviderNotFound, provider, DefaultPluginVendorDir)) } else { c.Ui.Error(fmt.Sprintf(errProviderVersionsUnsuitable, provider, reqd.Versions)) } case errwrap.Contains(err, discovery.ErrorVersionIncompatible.Error()): // Attempt to fetch nested error to display to the user which versions // we considered and which versions might be compatible. Otherwise, // we'll just display a generic version incompatible msg incompatErr := errwrap.GetType(err, fmt.Errorf("")) if incompatErr != nil { c.Ui.Error(incompatErr.Error()) } else { // Generic version incompatible msg c.Ui.Error(fmt.Sprintf(errProviderIncompatible, provider, constraint)) } // Reset nested errors err = discovery.ErrorVersionIncompatible case err == discovery.ErrorNoVersionCompatible: // Generic version incompatible msg c.Ui.Error(fmt.Sprintf(errProviderIncompatible, provider, constraint)) case err == discovery.ErrorSignatureVerification: c.Ui.Error(fmt.Sprintf(errSignatureVerification, provider)) case err == discovery.ErrorChecksumVerification, err == discovery.ErrorMissingChecksumVerification: c.Ui.Error(fmt.Sprintf(errChecksumVerification, provider)) default: c.Ui.Error(fmt.Sprintf(errProviderInstallError, provider, err.Error(), DefaultPluginVendorDir)) } diags = diags.Append(err) } } if diags.HasErrors() { return true, diags } } else if len(missing) > 0 { // we have missing providers, but aren't going to try and download them var lines []string for provider, reqd := range missing { if reqd.Versions.Unconstrained() { lines = append(lines, fmt.Sprintf("* %s (any version)\n", provider)) } else { lines = append(lines, fmt.Sprintf("* %s (%s)\n", provider, reqd.Versions)) } diags = diags.Append(fmt.Errorf("missing provider %q", provider)) } sort.Strings(lines) c.Ui.Error(fmt.Sprintf(errMissingProvidersNoInstall, strings.Join(lines, ""), DefaultPluginVendorDir)) return true, diags } // With all the providers downloaded, we'll generate our lock file // that ensures the provider binaries remain unchanged until we init // again. If anything changes, other commands that use providers will // fail with an error instructing the user to re-run this command. available = c.providerPluginSet() // re-discover to see newly-installed plugins // internal providers were already filtered out, since we don't need to get them. chosen := choosePlugins(available, nil, requirements) digests := map[string][]byte{} for name, meta := range chosen { digest, err := meta.SHA256() if err != nil { diags = diags.Append(fmt.Errorf("Failed to read provider plugin %s: %s", meta.Path, err)) return true, diags } digests[name] = digest if c.ignorePluginChecksum { digests[name] = nil } } err := c.providerPluginsLock().Write(digests) if err != nil { diags = diags.Append(fmt.Errorf("failed to save provider manifest: %s", err)) return true, diags } { // Purge any auto-installed plugins that aren't being used. purged, err := c.providerInstaller.PurgeUnused(chosen) if err != nil { // Failure to purge old plugins is not a fatal error c.Ui.Warn(fmt.Sprintf("failed to purge unused plugins: %s", err)) } if purged != nil { for meta := range purged { log.Printf("[DEBUG] Purged unused %s plugin %s", meta.Name, meta.Path) } } } // If any providers have "floating" versions (completely unconstrained) // we'll suggest the user constrain with a pessimistic constraint to // avoid implicitly adopting a later major release. constraintSuggestions := make(map[string]discovery.ConstraintStr) for name, meta := range chosen { req := requirements[name] if req == nil { // should never happen, but we don't want to crash here, so we'll // be cautious. continue } if req.Versions.Unconstrained() && meta.Version != discovery.VersionZero { // meta.Version.MustParse is safe here because our "chosen" metas // were already filtered for validity of versions. constraintSuggestions[name] = meta.Version.MustParse().MinorUpgradeConstraintStr() } } if len(constraintSuggestions) != 0 { names := make([]string, 0, len(constraintSuggestions)) for name := range constraintSuggestions { names = append(names, name) } sort.Strings(names) c.Ui.Output(outputInitProvidersUnconstrained) for _, name := range names { c.Ui.Output(fmt.Sprintf("* provider.%s: version = %q", name, constraintSuggestions[name])) } } return true, diags } // backendConfigOverrideBody interprets the raw values of -backend-config // arguments into a hcl Body that should override the backend settings given // in the configuration. // // If the result is nil then no override needs to be provided. // // If the returned diagnostics contains errors then the returned body may be // incomplete or invalid. func (c *InitCommand) backendConfigOverrideBody(flags rawFlags, schema *configschema.Block) (hcl.Body, tfdiags.Diagnostics) { items := flags.AllItems() if len(items) == 0 { return nil, nil } var ret hcl.Body var diags tfdiags.Diagnostics synthVals := make(map[string]cty.Value) mergeBody := func(newBody hcl.Body) { if ret == nil { ret = newBody } else { ret = configs.MergeBodies(ret, newBody) } } flushVals := func() { if len(synthVals) == 0 { return } newBody := configs.SynthBody("-backend-config=...", synthVals) mergeBody(newBody) synthVals = make(map[string]cty.Value) } if len(items) == 1 && items[0].Value == "" { // Explicitly remove all -backend-config options. // We do this by setting an empty but non-nil ConfigOverrides. return configs.SynthBody("-backend-config=''", synthVals), diags } for _, item := range items { eq := strings.Index(item.Value, "=") if eq == -1 { // The value is interpreted as a filename. newBody, fileDiags := c.loadHCLFile(item.Value) diags = diags.Append(fileDiags) flushVals() // deal with any accumulated individual values first mergeBody(newBody) } else { name := item.Value[:eq] rawValue := item.Value[eq+1:] attrS := schema.Attributes[name] if attrS == nil { diags = diags.Append(tfdiags.Sourceless( tfdiags.Error, "Invalid backend configuration argument", fmt.Sprintf("The backend configuration argument %q given on the command line is not expected for the selected backend type.", name), )) continue } value, valueDiags := configValueFromCLI(item.String(), rawValue, attrS.Type) diags = diags.Append(valueDiags) if valueDiags.HasErrors() { continue } synthVals[name] = value } } flushVals() return ret, diags } func (c *InitCommand) AutocompleteArgs() complete.Predictor { return complete.PredictDirs("") } func (c *InitCommand) AutocompleteFlags() complete.Flags { return complete.Flags{ "-backend": completePredictBoolean, "-backend-config": complete.PredictFiles("*.tfvars"), // can also be key=value, but we can't "predict" that "-force-copy": complete.PredictNothing, "-from-module": completePredictModuleSource, "-get": completePredictBoolean, "-get-plugins": completePredictBoolean, "-input": completePredictBoolean, "-lock": completePredictBoolean, "-lock-timeout": complete.PredictAnything, "-no-color": complete.PredictNothing, "-plugin-dir": complete.PredictDirs(""), "-reconfigure": complete.PredictNothing, "-upgrade": completePredictBoolean, "-verify-plugins": completePredictBoolean, } } func (c *InitCommand) Help() string { helpText := ` Usage: terraform init [options] [DIR] Initialize a new or existing Terraform working directory by creating initial files, loading any remote state, downloading modules, etc. This is the first command that should be run for any new or existing Terraform configuration per machine. This sets up all the local data necessary to run Terraform that is typically not committed to version control. This command is always safe to run multiple times. Though subsequent runs may give errors, this command will never delete your configuration or state. Even so, if you have important information, please back it up prior to running this command, just in case. If no arguments are given, the configuration in this working directory is initialized. Options: -backend=true Configure the backend for this configuration. -backend-config=path This can be either a path to an HCL file with key/value assignments (same format as terraform.tfvars) or a 'key=value' format. This is merged with what is in the configuration file. This can be specified multiple times. The backend type must be in the configuration itself. -force-copy Suppress prompts about copying state data. This is equivalent to providing a "yes" to all confirmation prompts. -from-module=SOURCE Copy the contents of the given module into the target directory before initialization. -get=true Download any modules for this configuration. -get-plugins=true Download any missing plugins for this configuration. -input=true Ask for input if necessary. If false, will error if input was required. -lock=true Lock the state file when locking is supported. -lock-timeout=0s Duration to retry a state lock. -no-color If specified, output won't contain any color. -plugin-dir Directory containing plugin binaries. This overrides all default search paths for plugins, and prevents the automatic installation of plugins. This flag can be used multiple times. -reconfigure Reconfigure the backend, ignoring any saved configuration. -upgrade=false If installing modules (-get) or plugins (-get-plugins), ignore previously-downloaded objects and install the latest version allowed within configured constraints. -verify-plugins=true Verify the authenticity and integrity of automatically downloaded plugins. ` return strings.TrimSpace(helpText) } func (c *InitCommand) Synopsis() string { return "Initialize a Terraform working directory" } const errInitConfigError = ` There are some problems with the configuration, described below. The Terraform configuration must be valid before initialization so that Terraform can determine which modules and providers need to be installed. ` const errInitCopyNotEmpty = ` The working directory already contains files. The -from-module option requires an empty directory into which a copy of the referenced module will be placed. To initialize the configuration already in this working directory, omit the -from-module option. ` const outputInitEmpty = ` [reset][bold]Terraform initialized in an empty directory![reset] The directory has no Terraform configuration files. You may begin working with Terraform immediately by creating Terraform configuration files. ` const outputInitSuccess = ` [reset][bold][green]Terraform has been successfully initialized![reset][green] ` const outputInitSuccessCLI = `[reset][green] You may now begin working with Terraform. Try running "terraform plan" to see any changes that are required for your infrastructure. All Terraform commands should now work. If you ever set or change modules or backend configuration for Terraform, rerun this command to reinitialize your working directory. If you forget, other commands will detect it and remind you to do so if necessary. ` const outputInitSuccessConfigUpgrade = ` [reset][bold]Terraform has initialized, but configuration upgrades may be needed.[reset] Terraform found syntax errors in the configuration that prevented full initialization. If you've recently upgraded to Terraform v0.12, this may be because your configuration uses syntax constructs that are no longer valid, and so must be updated before full initialization is possible. Run terraform init for this configuration at a shell prompt for more information on how to update it for Terraform v0.12 compatibility. ` const outputInitSuccessConfigUpgradeCLI = `[reset][green] [reset][bold]Terraform has initialized, but configuration upgrades may be needed.[reset] Terraform found syntax errors in the configuration that prevented full initialization. If you've recently upgraded to Terraform v0.12, this may be because your configuration uses syntax constructs that are no longer valid, and so must be updated before full initialization is possible. Terraform has installed the required providers to support the configuration upgrade process. To begin upgrading your configuration, run the following: terraform 0.12upgrade To see the full set of errors that led to this message, run: terraform validate ` const outputInitProvidersUnconstrained = ` The following providers do not have any version constraints in configuration, so the latest version was installed. To prevent automatic upgrades to new major versions that may contain breaking changes, it is recommended to add version = "..." constraints to the corresponding provider blocks in configuration, with the constraint strings suggested below. ` const errDiscoveryServiceUnreachable = ` [reset][bold][red]Registry service unreachable.[reset][red] This may indicate a network issue, or an issue with the requested Terraform Registry. ` const errProviderNotFound = ` [reset][bold][red]Provider %[1]q not available for installation.[reset][red] A provider named %[1]q could not be found in the Terraform Registry. This may result from mistyping the provider name, or the given provider may be a third-party provider that cannot be installed automatically. In the latter case, the plugin must be installed manually by locating and downloading a suitable distribution package and placing the plugin's executable file in the following directory: %[2]s Terraform detects necessary plugins by inspecting the configuration and state. To view the provider versions requested by each module, run "terraform providers". ` const errProviderVersionsUnsuitable = ` [reset][bold][red]No provider %[1]q plugins meet the constraint %[2]q.[reset][red] The version constraint is derived from the "version" argument within the provider %[1]q block in configuration. Child modules may also apply provider version constraints. To view the provider versions requested by each module in the current configuration, run "terraform providers". To proceed, the version constraints for this provider must be relaxed by either adjusting or removing the "version" argument in the provider blocks throughout the configuration. ` const errProviderIncompatible = ` [reset][bold][red]No available provider %[1]q plugins are compatible with this Terraform version.[reset][red] From time to time, new Terraform major releases can change the requirements for plugins such that older plugins become incompatible. Terraform checked all of the plugin versions matching the given constraint: %[2]s Unfortunately, none of the suitable versions are compatible with this version of Terraform. If you have recently upgraded Terraform, it may be necessary to move to a newer major release of this provider. Alternatively, if you are attempting to upgrade the provider to a new major version you may need to also upgrade Terraform to support the new version. Consult the documentation for this provider for more information on compatibility between provider versions and Terraform versions. ` const errProviderInstallError = ` [reset][bold][red]Error installing provider %[1]q: %[2]s.[reset][red] Terraform analyses the configuration and state and automatically downloads plugins for the providers used. However, when attempting to download this plugin an unexpected error occurred. This may be caused if for some reason Terraform is unable to reach the plugin repository. The repository may be unreachable if access is blocked by a firewall. If automatic installation is not possible or desirable in your environment, you may alternatively manually install plugins by downloading a suitable distribution package and placing the plugin's executable file in the following directory: %[3]s ` const errMissingProvidersNoInstall = ` [reset][bold][red]Missing required providers.[reset][red] The following provider constraints are not met by the currently-installed provider plugins: %[1]s Terraform can automatically download and install plugins to meet the given constraints, but this step was skipped due to the use of -get-plugins=false and/or -plugin-dir on the command line. If automatic installation is not possible or desirable in your environment, you may manually install plugins by downloading a suitable distribution package and placing the plugin's executable file in one of the directories given in by -plugin-dir on the command line, or in the following directory if custom plugin directories are not set: %[2]s ` const errChecksumVerification = ` [reset][bold][red]Error verifying checksum for provider %[1]q[reset][red] The checksum for provider distribution from the Terraform Registry did not match the source. This may mean that the distributed files were changed after this version was released to the Registry. ` const errSignatureVerification = ` [reset][bold][red]Error verifying GPG signature for provider %[1]q[reset][red] Terraform was unable to verify the GPG signature of the downloaded provider files using the keys downloaded from the Terraform Registry. This may mean that the publisher of the provider removed the key it was signed with, or that the distributed files were changed after this version was released. `
command/init.go
1
https://github.com/hashicorp/terraform/commit/efafadbe5edbfd8faa250aa1eaed46fbb2d52ee2
[ 0.9975467324256897, 0.04730893298983574, 0.00016107650299090892, 0.0001715507823973894, 0.20726631581783295 ]
{ "id": 3, "code_window": [ "\treqd discovery.PluginRequirements,\n", ") (map[addrs.Provider]providers.Factory, []error) {\n", "\tfactories := make(map[addrs.Provider]providers.Factory, len(reqd))\n", "\tvar errs []error\n", "\n", "\tchosen := choosePlugins(r.Available, r.Internal, reqd)\n", "\tfor name, req := range reqd {\n", "\t\tif factory, isInternal := r.Internal[addrs.NewLegacyProvider(name)]; isInternal {\n", "\t\t\tif !req.Versions.Unconstrained() {\n", "\t\t\t\terrs = append(errs, fmt.Errorf(\"provider.%s: this provider is built in to Terraform and so it does not support version constraints\", name))\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tchosen := chooseProviders(r.Available, r.Internal, reqd)\n" ], "file_path": "command/plugins.go", "type": "replace", "edit_start_line_idx": 65 }
// Package complete provides a tool for bash writing bash completion in go. // // Writing bash completion scripts is a hard work. This package provides an easy way // to create bash completion scripts for any command, and also an easy way to install/uninstall // the completion of the command. package complete import ( "flag" "fmt" "io" "os" "strconv" "github.com/posener/complete/cmd" "github.com/posener/complete/match" ) const ( envLine = "COMP_LINE" envPoint = "COMP_POINT" envDebug = "COMP_DEBUG" ) // Complete structs define completion for a command with CLI options type Complete struct { Command Command cmd.CLI Out io.Writer } // New creates a new complete command. // name is the name of command we want to auto complete. // IMPORTANT: it must be the same name - if the auto complete // completes the 'go' command, name must be equal to "go". // command is the struct of the command completion. func New(name string, command Command) *Complete { return &Complete{ Command: command, CLI: cmd.CLI{Name: name}, Out: os.Stdout, } } // Run runs the completion and add installation flags beforehand. // The flags are added to the main flag CommandLine variable. func (c *Complete) Run() bool { c.AddFlags(nil) flag.Parse() return c.Complete() } // Complete a command from completion line in environment variable, // and print out the complete options. // returns success if the completion ran or if the cli matched // any of the given flags, false otherwise // For installation: it assumes that flags were added and parsed before // it was called. func (c *Complete) Complete() bool { line, point, ok := getEnv() if !ok { // make sure flags parsed, // in case they were not added in the main program return c.CLI.Run() } if point >= 0 && point < len(line) { line = line[:point] } Log("Completing phrase: %s", line) a := newArgs(line) Log("Completing last field: %s", a.Last) options := c.Command.Predict(a) Log("Options: %s", options) // filter only options that match the last argument matches := []string{} for _, option := range options { if match.Prefix(option, a.Last) { matches = append(matches, option) } } Log("Matches: %s", matches) c.output(matches) return true } func getEnv() (line string, point int, ok bool) { line = os.Getenv(envLine) if line == "" { return } point, err := strconv.Atoi(os.Getenv(envPoint)) if err != nil { // If failed parsing point for some reason, set it to point // on the end of the line. Log("Failed parsing point %s: %v", os.Getenv(envPoint), err) point = len(line) } return line, point, true } func (c *Complete) output(options []string) { // stdout of program defines the complete options for _, option := range options { fmt.Fprintln(c.Out, option) } }
vendor/github.com/posener/complete/complete.go
0
https://github.com/hashicorp/terraform/commit/efafadbe5edbfd8faa250aa1eaed46fbb2d52ee2
[ 0.00017422110249754041, 0.00017011539603117853, 0.00016527915431652218, 0.00016925025556702167, 0.000003042855951207457 ]
{ "id": 3, "code_window": [ "\treqd discovery.PluginRequirements,\n", ") (map[addrs.Provider]providers.Factory, []error) {\n", "\tfactories := make(map[addrs.Provider]providers.Factory, len(reqd))\n", "\tvar errs []error\n", "\n", "\tchosen := choosePlugins(r.Available, r.Internal, reqd)\n", "\tfor name, req := range reqd {\n", "\t\tif factory, isInternal := r.Internal[addrs.NewLegacyProvider(name)]; isInternal {\n", "\t\t\tif !req.Versions.Unconstrained() {\n", "\t\t\t\terrs = append(errs, fmt.Errorf(\"provider.%s: this provider is built in to Terraform and so it does not support version constraints\", name))\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tchosen := chooseProviders(r.Available, r.Internal, reqd)\n" ], "file_path": "command/plugins.go", "type": "replace", "edit_start_line_idx": 65 }
The following files were ported to Go from C files of libyaml, and thus are still covered by their original copyright and license: apic.go emitterc.go parserc.go readerc.go scannerc.go writerc.go yamlh.go yamlprivateh.go Copyright (c) 2006 Kirill Simonov 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/gopkg.in/yaml.v2/LICENSE.libyaml
0
https://github.com/hashicorp/terraform/commit/efafadbe5edbfd8faa250aa1eaed46fbb2d52ee2
[ 0.00017574807861819863, 0.0001705550093902275, 0.0001646630116738379, 0.00017090447363443673, 0.000004008731593785342 ]
{ "id": 3, "code_window": [ "\treqd discovery.PluginRequirements,\n", ") (map[addrs.Provider]providers.Factory, []error) {\n", "\tfactories := make(map[addrs.Provider]providers.Factory, len(reqd))\n", "\tvar errs []error\n", "\n", "\tchosen := choosePlugins(r.Available, r.Internal, reqd)\n", "\tfor name, req := range reqd {\n", "\t\tif factory, isInternal := r.Internal[addrs.NewLegacyProvider(name)]; isInternal {\n", "\t\t\tif !req.Versions.Unconstrained() {\n", "\t\t\t\terrs = append(errs, fmt.Errorf(\"provider.%s: this provider is built in to Terraform and so it does not support version constraints\", name))\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tchosen := chooseProviders(r.Available, r.Internal, reqd)\n" ], "file_path": "command/plugins.go", "type": "replace", "edit_start_line_idx": 65 }
/* * * Copyright 2016 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // This file is the implementation of a gRPC server using HTTP/2 which // uses the standard Go http2 Server implementation (via the // http.Handler interface), rather than speaking low-level HTTP/2 // frames itself. It is the implementation of *grpc.Server.ServeHTTP. package transport import ( "context" "errors" "fmt" "io" "net" "net/http" "strings" "sync" "time" "github.com/golang/protobuf/proto" "golang.org/x/net/http2" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" ) // NewServerHandlerTransport returns a ServerTransport handling gRPC // from inside an http.Handler. It requires that the http Server // supports HTTP/2. func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request, stats stats.Handler) (ServerTransport, error) { if r.ProtoMajor != 2 { return nil, errors.New("gRPC requires HTTP/2") } if r.Method != "POST" { return nil, errors.New("invalid gRPC request method") } contentType := r.Header.Get("Content-Type") // TODO: do we assume contentType is lowercase? we did before contentSubtype, validContentType := contentSubtype(contentType) if !validContentType { return nil, errors.New("invalid gRPC request content-type") } if _, ok := w.(http.Flusher); !ok { return nil, errors.New("gRPC requires a ResponseWriter supporting http.Flusher") } st := &serverHandlerTransport{ rw: w, req: r, closedCh: make(chan struct{}), writes: make(chan func()), contentType: contentType, contentSubtype: contentSubtype, stats: stats, } if v := r.Header.Get("grpc-timeout"); v != "" { to, err := decodeTimeout(v) if err != nil { return nil, status.Errorf(codes.Internal, "malformed time-out: %v", err) } st.timeoutSet = true st.timeout = to } metakv := []string{"content-type", contentType} if r.Host != "" { metakv = append(metakv, ":authority", r.Host) } for k, vv := range r.Header { k = strings.ToLower(k) if isReservedHeader(k) && !isWhitelistedHeader(k) { continue } for _, v := range vv { v, err := decodeMetadataHeader(k, v) if err != nil { return nil, status.Errorf(codes.Internal, "malformed binary metadata: %v", err) } metakv = append(metakv, k, v) } } st.headerMD = metadata.Pairs(metakv...) return st, nil } // serverHandlerTransport is an implementation of ServerTransport // which replies to exactly one gRPC request (exactly one HTTP request), // using the net/http.Handler interface. This http.Handler is guaranteed // at this point to be speaking over HTTP/2, so it's able to speak valid // gRPC. type serverHandlerTransport struct { rw http.ResponseWriter req *http.Request timeoutSet bool timeout time.Duration didCommonHeaders bool headerMD metadata.MD closeOnce sync.Once closedCh chan struct{} // closed on Close // writes is a channel of code to run serialized in the // ServeHTTP (HandleStreams) goroutine. The channel is closed // when WriteStatus is called. writes chan func() // block concurrent WriteStatus calls // e.g. grpc/(*serverStream).SendMsg/RecvMsg writeStatusMu sync.Mutex // we just mirror the request content-type contentType string // we store both contentType and contentSubtype so we don't keep recreating them // TODO make sure this is consistent across handler_server and http2_server contentSubtype string stats stats.Handler } func (ht *serverHandlerTransport) Close() error { ht.closeOnce.Do(ht.closeCloseChanOnce) return nil } func (ht *serverHandlerTransport) closeCloseChanOnce() { close(ht.closedCh) } func (ht *serverHandlerTransport) RemoteAddr() net.Addr { return strAddr(ht.req.RemoteAddr) } // strAddr is a net.Addr backed by either a TCP "ip:port" string, or // the empty string if unknown. type strAddr string func (a strAddr) Network() string { if a != "" { // Per the documentation on net/http.Request.RemoteAddr, if this is // set, it's set to the IP:port of the peer (hence, TCP): // https://golang.org/pkg/net/http/#Request // // If we want to support Unix sockets later, we can // add our own grpc-specific convention within the // grpc codebase to set RemoteAddr to a different // format, or probably better: we can attach it to the // context and use that from serverHandlerTransport.RemoteAddr. return "tcp" } return "" } func (a strAddr) String() string { return string(a) } // do runs fn in the ServeHTTP goroutine. func (ht *serverHandlerTransport) do(fn func()) error { select { case <-ht.closedCh: return ErrConnClosing case ht.writes <- fn: return nil } } func (ht *serverHandlerTransport) WriteStatus(s *Stream, st *status.Status) error { ht.writeStatusMu.Lock() defer ht.writeStatusMu.Unlock() err := ht.do(func() { ht.writeCommonHeaders(s) // And flush, in case no header or body has been sent yet. // This forces a separation of headers and trailers if this is the // first call (for example, in end2end tests's TestNoService). ht.rw.(http.Flusher).Flush() h := ht.rw.Header() h.Set("Grpc-Status", fmt.Sprintf("%d", st.Code())) if m := st.Message(); m != "" { h.Set("Grpc-Message", encodeGrpcMessage(m)) } if p := st.Proto(); p != nil && len(p.Details) > 0 { stBytes, err := proto.Marshal(p) if err != nil { // TODO: return error instead, when callers are able to handle it. panic(err) } h.Set("Grpc-Status-Details-Bin", encodeBinHeader(stBytes)) } if md := s.Trailer(); len(md) > 0 { for k, vv := range md { // Clients don't tolerate reading restricted headers after some non restricted ones were sent. if isReservedHeader(k) { continue } for _, v := range vv { // http2 ResponseWriter mechanism to send undeclared Trailers after // the headers have possibly been written. h.Add(http2.TrailerPrefix+k, encodeMetadataHeader(k, v)) } } } }) if err == nil { // transport has not been closed if ht.stats != nil { ht.stats.HandleRPC(s.Context(), &stats.OutTrailer{}) } } ht.Close() return err } // writeCommonHeaders sets common headers on the first write // call (Write, WriteHeader, or WriteStatus). func (ht *serverHandlerTransport) writeCommonHeaders(s *Stream) { if ht.didCommonHeaders { return } ht.didCommonHeaders = true h := ht.rw.Header() h["Date"] = nil // suppress Date to make tests happy; TODO: restore h.Set("Content-Type", ht.contentType) // Predeclare trailers we'll set later in WriteStatus (after the body). // This is a SHOULD in the HTTP RFC, and the way you add (known) // Trailers per the net/http.ResponseWriter contract. // See https://golang.org/pkg/net/http/#ResponseWriter // and https://golang.org/pkg/net/http/#example_ResponseWriter_trailers h.Add("Trailer", "Grpc-Status") h.Add("Trailer", "Grpc-Message") h.Add("Trailer", "Grpc-Status-Details-Bin") if s.sendCompress != "" { h.Set("Grpc-Encoding", s.sendCompress) } } func (ht *serverHandlerTransport) Write(s *Stream, hdr []byte, data []byte, opts *Options) error { return ht.do(func() { ht.writeCommonHeaders(s) ht.rw.Write(hdr) ht.rw.Write(data) ht.rw.(http.Flusher).Flush() }) } func (ht *serverHandlerTransport) WriteHeader(s *Stream, md metadata.MD) error { err := ht.do(func() { ht.writeCommonHeaders(s) h := ht.rw.Header() for k, vv := range md { // Clients don't tolerate reading restricted headers after some non restricted ones were sent. if isReservedHeader(k) { continue } for _, v := range vv { v = encodeMetadataHeader(k, v) h.Add(k, v) } } ht.rw.WriteHeader(200) ht.rw.(http.Flusher).Flush() }) if err == nil { if ht.stats != nil { ht.stats.HandleRPC(s.Context(), &stats.OutHeader{}) } } return err } func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream), traceCtx func(context.Context, string) context.Context) { // With this transport type there will be exactly 1 stream: this HTTP request. ctx := ht.req.Context() var cancel context.CancelFunc if ht.timeoutSet { ctx, cancel = context.WithTimeout(ctx, ht.timeout) } else { ctx, cancel = context.WithCancel(ctx) } // requestOver is closed when the status has been written via WriteStatus. requestOver := make(chan struct{}) go func() { select { case <-requestOver: case <-ht.closedCh: case <-ht.req.Context().Done(): } cancel() ht.Close() }() req := ht.req s := &Stream{ id: 0, // irrelevant requestRead: func(int) {}, cancel: cancel, buf: newRecvBuffer(), st: ht, method: req.URL.Path, recvCompress: req.Header.Get("grpc-encoding"), contentSubtype: ht.contentSubtype, } pr := &peer.Peer{ Addr: ht.RemoteAddr(), } if req.TLS != nil { pr.AuthInfo = credentials.TLSInfo{State: *req.TLS} } ctx = metadata.NewIncomingContext(ctx, ht.headerMD) s.ctx = peer.NewContext(ctx, pr) if ht.stats != nil { s.ctx = ht.stats.TagRPC(s.ctx, &stats.RPCTagInfo{FullMethodName: s.method}) inHeader := &stats.InHeader{ FullMethod: s.method, RemoteAddr: ht.RemoteAddr(), Compression: s.recvCompress, } ht.stats.HandleRPC(s.ctx, inHeader) } s.trReader = &transportReader{ reader: &recvBufferReader{ctx: s.ctx, ctxDone: s.ctx.Done(), recv: s.buf}, windowHandler: func(int) {}, } // readerDone is closed when the Body.Read-ing goroutine exits. readerDone := make(chan struct{}) go func() { defer close(readerDone) // TODO: minimize garbage, optimize recvBuffer code/ownership const readSize = 8196 for buf := make([]byte, readSize); ; { n, err := req.Body.Read(buf) if n > 0 { s.buf.put(recvMsg{data: buf[:n:n]}) buf = buf[n:] } if err != nil { s.buf.put(recvMsg{err: mapRecvMsgError(err)}) return } if len(buf) == 0 { buf = make([]byte, readSize) } } }() // startStream is provided by the *grpc.Server's serveStreams. // It starts a goroutine serving s and exits immediately. // The goroutine that is started is the one that then calls // into ht, calling WriteHeader, Write, WriteStatus, Close, etc. startStream(s) ht.runStream() close(requestOver) // Wait for reading goroutine to finish. req.Body.Close() <-readerDone } func (ht *serverHandlerTransport) runStream() { for { select { case fn := <-ht.writes: fn() case <-ht.closedCh: return } } } func (ht *serverHandlerTransport) IncrMsgSent() {} func (ht *serverHandlerTransport) IncrMsgRecv() {} func (ht *serverHandlerTransport) Drain() { panic("Drain() is not implemented") } // mapRecvMsgError returns the non-nil err into the appropriate // error value as expected by callers of *grpc.parser.recvMsg. // In particular, in can only be: // * io.EOF // * io.ErrUnexpectedEOF // * of type transport.ConnectionError // * an error from the status package func mapRecvMsgError(err error) error { if err == io.EOF || err == io.ErrUnexpectedEOF { return err } if se, ok := err.(http2.StreamError); ok { if code, ok := http2ErrConvTab[se.Code]; ok { return status.Error(code, se.Error()) } } if strings.Contains(err.Error(), "body closed by handler") { return status.Error(codes.Canceled, err.Error()) } return connectionErrorf(true, err, err.Error()) }
vendor/google.golang.org/grpc/internal/transport/handler_server.go
0
https://github.com/hashicorp/terraform/commit/efafadbe5edbfd8faa250aa1eaed46fbb2d52ee2
[ 0.004709617234766483, 0.0002762384829111397, 0.00016044924268499017, 0.00016926511307246983, 0.0006763486308045685 ]
{ "id": 0, "code_window": [ "// guessIsRPCReq - returns true if the request is for an RPC endpoint.\n", "func guessIsRPCReq(req *http.Request) bool {\n", "\tif req == nil {\n", "\t\treturn false\n", "\t}\n", "\treturn req.Method == http.MethodPost\n", "}\n", "\n", "func (h redirectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n", "\taType := getRequestAuthType(r)\n", "\t// Re-direct only for JWT and anonymous requests from browser.\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\treturn req.Method == http.MethodPost &&\n", "\t\tstrings.HasPrefix(req.URL.Path, minioReservedBucketPath+\"/\")\n" ], "file_path": "cmd/generic-handlers.go", "type": "replace", "edit_start_line_idx": 230 }
/* * Minio Cloud Storage, (C) 2016 Minio, 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 cmd import ( "net/http" "net/http/httptest" "net/url" "strconv" "testing" "github.com/minio/minio/cmd/crypto" ) // Tests getRedirectLocation function for all its criteria. func TestRedirectLocation(t *testing.T) { testCases := []struct { urlPath string location string }{ { // 1. When urlPath is '/minio' urlPath: minioReservedBucketPath, location: minioReservedBucketPath + "/", }, { // 2. When urlPath is '/' urlPath: "/", location: minioReservedBucketPath + "/", }, { // 3. When urlPath is '/webrpc' urlPath: "/webrpc", location: minioReservedBucketPath + "/webrpc", }, { // 4. When urlPath is '/login' urlPath: "/login", location: minioReservedBucketPath + "/login", }, { // 5. When urlPath is '/favicon.ico' urlPath: "/favicon.ico", location: minioReservedBucketPath + "/favicon.ico", }, { // 6. When urlPath is '/unknown' urlPath: "/unknown", location: "", }, } // Validate all conditions. for i, testCase := range testCases { loc := getRedirectLocation(testCase.urlPath) if testCase.location != loc { t.Errorf("Test %d: Unexpected location expected %s, got %s", i+1, testCase.location, loc) } } } // Tests request guess function for net/rpc requests. func TestGuessIsRPC(t *testing.T) { if guessIsRPCReq(nil) { t.Fatal("Unexpected return for nil request") } r := &http.Request{ Proto: "HTTP/1.0", Method: http.MethodPost, } if !guessIsRPCReq(r) { t.Fatal("Test shouldn't fail for a possible net/rpc request.") } r = &http.Request{ Proto: "HTTP/1.1", Method: http.MethodGet, } if guessIsRPCReq(r) { t.Fatal("Test shouldn't report as net/rpc for a non net/rpc request.") } } // Tests browser request guess function. func TestGuessIsBrowser(t *testing.T) { if guessIsBrowserReq(nil) { t.Fatal("Unexpected return for nil request") } r := &http.Request{ Header: http.Header{}, } r.Header.Set("User-Agent", "Mozilla") if !guessIsBrowserReq(r) { t.Fatal("Test shouldn't fail for a possible browser request.") } r = &http.Request{ Header: http.Header{}, } r.Header.Set("User-Agent", "mc") if guessIsBrowserReq(r) { t.Fatal("Test shouldn't report as browser for a non browser request.") } } var isHTTPHeaderSizeTooLargeTests = []struct { header http.Header shouldFail bool }{ {header: generateHeader(0, 0), shouldFail: false}, {header: generateHeader(1024, 0), shouldFail: false}, {header: generateHeader(2048, 0), shouldFail: false}, {header: generateHeader(8*1024+1, 0), shouldFail: true}, {header: generateHeader(0, 1024), shouldFail: false}, {header: generateHeader(0, 2048), shouldFail: true}, {header: generateHeader(0, 2048+1), shouldFail: true}, } func generateHeader(size, usersize int) http.Header { header := http.Header{} for i := 0; i < size; i++ { header.Add(strconv.Itoa(i), "") } userlength := 0 for i := 0; userlength < usersize; i++ { userlength += len(userMetadataKeyPrefixes[0] + strconv.Itoa(i)) header.Add(userMetadataKeyPrefixes[0]+strconv.Itoa(i), "") } return header } func TestIsHTTPHeaderSizeTooLarge(t *testing.T) { for i, test := range isHTTPHeaderSizeTooLargeTests { if res := isHTTPHeaderSizeTooLarge(test.header); res != test.shouldFail { t.Errorf("Test %d: Expected %v got %v", i, res, test.shouldFail) } } } var containsReservedMetadataTests = []struct { header http.Header shouldFail bool }{ { header: http.Header{"X-Minio-Key": []string{"value"}}, }, { header: http.Header{crypto.SSEIV: []string{"iv"}}, shouldFail: true, }, { header: http.Header{crypto.SSESealAlgorithm: []string{SSESealAlgorithmDareSha256}}, shouldFail: true, }, { header: http.Header{crypto.SSECSealedKey: []string{"mac"}}, shouldFail: true, }, { header: http.Header{ReservedMetadataPrefix + "Key": []string{"value"}}, shouldFail: true, }, } func TestContainsReservedMetadata(t *testing.T) { for i, test := range containsReservedMetadataTests { if contains := containsReservedMetadata(test.header); contains && !test.shouldFail { t.Errorf("Test %d: contains reserved header but should not fail", i) } else if !contains && test.shouldFail { t.Errorf("Test %d: does not contain reserved header but failed", i) } } } var sseTLSHandlerTests = []struct { URL *url.URL Header http.Header IsTLS, ShouldFail bool }{ {URL: &url.URL{}, Header: http.Header{}, IsTLS: false, ShouldFail: false}, // 0 {URL: &url.URL{}, Header: http.Header{crypto.SSECAlgorithm: []string{"AES256"}}, IsTLS: false, ShouldFail: true}, // 1 {URL: &url.URL{}, Header: http.Header{crypto.SSECAlgorithm: []string{"AES256"}}, IsTLS: true, ShouldFail: false}, // 2 {URL: &url.URL{}, Header: http.Header{crypto.SSECKey: []string{""}}, IsTLS: true, ShouldFail: false}, // 3 {URL: &url.URL{}, Header: http.Header{crypto.SSECopyAlgorithm: []string{""}}, IsTLS: false, ShouldFail: true}, // 4 } func TestSSETLSHandler(t *testing.T) { defer func(isSSL bool) { globalIsSSL = isSSL }(globalIsSSL) // reset globalIsSSL after test var okHandler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } for i, test := range sseTLSHandlerTests { globalIsSSL = test.IsTLS w := httptest.NewRecorder() r := new(http.Request) r.Header = test.Header r.URL = test.URL h := setSSETLSHandler(okHandler) h.ServeHTTP(w, r) switch { case test.ShouldFail && w.Code == http.StatusOK: t.Errorf("Test %d: should fail but status code is HTTP %d", i, w.Code) case !test.ShouldFail && w.Code != http.StatusOK: t.Errorf("Test %d: should not fail but status code is HTTP %d and not 200 OK", i, w.Code) } } }
cmd/generic-handlers_test.go
1
https://github.com/minio/minio/commit/40852801ea63d0e10f220c0d7d2a8d6a8efa5688
[ 0.9990590214729309, 0.2605735659599304, 0.0001682329166214913, 0.00028654708876274526, 0.43651798367500305 ]
{ "id": 0, "code_window": [ "// guessIsRPCReq - returns true if the request is for an RPC endpoint.\n", "func guessIsRPCReq(req *http.Request) bool {\n", "\tif req == nil {\n", "\t\treturn false\n", "\t}\n", "\treturn req.Method == http.MethodPost\n", "}\n", "\n", "func (h redirectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n", "\taType := getRequestAuthType(r)\n", "\t// Re-direct only for JWT and anonymous requests from browser.\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\treturn req.Method == http.MethodPost &&\n", "\t\tstrings.HasPrefix(req.URL.Path, minioReservedBucketPath+\"/\")\n" ], "file_path": "cmd/generic-handlers.go", "type": "replace", "edit_start_line_idx": 230 }
// 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. // Package jws provides a partial implementation // of JSON Web Signature encoding and decoding. // It exists to support the golang.org/x/oauth2 package. // // See RFC 7515. // // Deprecated: this package is not intended for public use and might be // removed in the future. It exists for internal use only. // Please switch to another JWS package or copy this package into your own // source tree. package jws // import "golang.org/x/oauth2/jws" import ( "bytes" "crypto" "crypto/rand" "crypto/rsa" "crypto/sha256" "encoding/base64" "encoding/json" "errors" "fmt" "strings" "time" ) // ClaimSet contains information about the JWT signature including the // permissions being requested (scopes), the target of the token, the issuer, // the time the token was issued, and the lifetime of the token. type ClaimSet struct { Iss string `json:"iss"` // email address of the client_id of the application making the access token request Scope string `json:"scope,omitempty"` // space-delimited list of the permissions the application requests Aud string `json:"aud"` // descriptor of the intended target of the assertion (Optional). Exp int64 `json:"exp"` // the expiration time of the assertion (seconds since Unix epoch) Iat int64 `json:"iat"` // the time the assertion was issued (seconds since Unix epoch) Typ string `json:"typ,omitempty"` // token type (Optional). // Email for which the application is requesting delegated access (Optional). Sub string `json:"sub,omitempty"` // The old name of Sub. Client keeps setting Prn to be // complaint with legacy OAuth 2.0 providers. (Optional) Prn string `json:"prn,omitempty"` // See http://tools.ietf.org/html/draft-jones-json-web-token-10#section-4.3 // This array is marshalled using custom code (see (c *ClaimSet) encode()). PrivateClaims map[string]interface{} `json:"-"` } func (c *ClaimSet) encode() (string, error) { // Reverting time back for machines whose time is not perfectly in sync. // If client machine's time is in the future according // to Google servers, an access token will not be issued. now := time.Now().Add(-10 * time.Second) if c.Iat == 0 { c.Iat = now.Unix() } if c.Exp == 0 { c.Exp = now.Add(time.Hour).Unix() } if c.Exp < c.Iat { return "", fmt.Errorf("jws: invalid Exp = %v; must be later than Iat = %v", c.Exp, c.Iat) } b, err := json.Marshal(c) if err != nil { return "", err } if len(c.PrivateClaims) == 0 { return base64.RawURLEncoding.EncodeToString(b), nil } // Marshal private claim set and then append it to b. prv, err := json.Marshal(c.PrivateClaims) if err != nil { return "", fmt.Errorf("jws: invalid map of private claims %v", c.PrivateClaims) } // Concatenate public and private claim JSON objects. if !bytes.HasSuffix(b, []byte{'}'}) { return "", fmt.Errorf("jws: invalid JSON %s", b) } if !bytes.HasPrefix(prv, []byte{'{'}) { return "", fmt.Errorf("jws: invalid JSON %s", prv) } b[len(b)-1] = ',' // Replace closing curly brace with a comma. b = append(b, prv[1:]...) // Append private claims. return base64.RawURLEncoding.EncodeToString(b), nil } // Header represents the header for the signed JWS payloads. type Header struct { // The algorithm used for signature. Algorithm string `json:"alg"` // Represents the token type. Typ string `json:"typ"` // The optional hint of which key is being used. KeyID string `json:"kid,omitempty"` } func (h *Header) encode() (string, error) { b, err := json.Marshal(h) if err != nil { return "", err } return base64.RawURLEncoding.EncodeToString(b), nil } // Decode decodes a claim set from a JWS payload. func Decode(payload string) (*ClaimSet, error) { // decode returned id token to get expiry s := strings.Split(payload, ".") if len(s) < 2 { // TODO(jbd): Provide more context about the error. return nil, errors.New("jws: invalid token received") } decoded, err := base64.RawURLEncoding.DecodeString(s[1]) if err != nil { return nil, err } c := &ClaimSet{} err = json.NewDecoder(bytes.NewBuffer(decoded)).Decode(c) return c, err } // Signer returns a signature for the given data. type Signer func(data []byte) (sig []byte, err error) // EncodeWithSigner encodes a header and claim set with the provided signer. func EncodeWithSigner(header *Header, c *ClaimSet, sg Signer) (string, error) { head, err := header.encode() if err != nil { return "", err } cs, err := c.encode() if err != nil { return "", err } ss := fmt.Sprintf("%s.%s", head, cs) sig, err := sg([]byte(ss)) if err != nil { return "", err } return fmt.Sprintf("%s.%s", ss, base64.RawURLEncoding.EncodeToString(sig)), nil } // Encode encodes a signed JWS with provided header and claim set. // This invokes EncodeWithSigner using crypto/rsa.SignPKCS1v15 with the given RSA private key. func Encode(header *Header, c *ClaimSet, key *rsa.PrivateKey) (string, error) { sg := func(data []byte) (sig []byte, err error) { h := sha256.New() h.Write(data) return rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, h.Sum(nil)) } return EncodeWithSigner(header, c, sg) } // Verify tests whether the provided JWT token's signature was produced by the private key // associated with the supplied public key. func Verify(token string, key *rsa.PublicKey) error { parts := strings.Split(token, ".") if len(parts) != 3 { return errors.New("jws: invalid token received, token must have 3 parts") } signedContent := parts[0] + "." + parts[1] signatureString, err := base64.RawURLEncoding.DecodeString(parts[2]) if err != nil { return err } h := sha256.New() h.Write([]byte(signedContent)) return rsa.VerifyPKCS1v15(key, crypto.SHA256, h.Sum(nil), []byte(signatureString)) }
vendor/golang.org/x/oauth2/jws/jws.go
0
https://github.com/minio/minio/commit/40852801ea63d0e10f220c0d7d2a8d6a8efa5688
[ 0.0023669558577239513, 0.00043486221693456173, 0.0001636189263081178, 0.0001766745263012126, 0.0005225481581874192 ]
{ "id": 0, "code_window": [ "// guessIsRPCReq - returns true if the request is for an RPC endpoint.\n", "func guessIsRPCReq(req *http.Request) bool {\n", "\tif req == nil {\n", "\t\treturn false\n", "\t}\n", "\treturn req.Method == http.MethodPost\n", "}\n", "\n", "func (h redirectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n", "\taType := getRequestAuthType(r)\n", "\t// Re-direct only for JWT and anonymous requests from browser.\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\treturn req.Method == http.MethodPost &&\n", "\t\tstrings.HasPrefix(req.URL.Path, minioReservedBucketPath+\"/\")\n" ], "file_path": "cmd/generic-handlers.go", "type": "replace", "edit_start_line_idx": 230 }
/* * * Copyright 2017 gRPC 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 codes import "strconv" func (c Code) String() string { switch c { case OK: return "OK" case Canceled: return "Canceled" case Unknown: return "Unknown" case InvalidArgument: return "InvalidArgument" case DeadlineExceeded: return "DeadlineExceeded" case NotFound: return "NotFound" case AlreadyExists: return "AlreadyExists" case PermissionDenied: return "PermissionDenied" case ResourceExhausted: return "ResourceExhausted" case FailedPrecondition: return "FailedPrecondition" case Aborted: return "Aborted" case OutOfRange: return "OutOfRange" case Unimplemented: return "Unimplemented" case Internal: return "Internal" case Unavailable: return "Unavailable" case DataLoss: return "DataLoss" case Unauthenticated: return "Unauthenticated" default: return "Code(" + strconv.FormatInt(int64(c), 10) + ")" } }
vendor/google.golang.org/grpc/codes/code_string.go
0
https://github.com/minio/minio/commit/40852801ea63d0e10f220c0d7d2a8d6a8efa5688
[ 0.00019796400738414377, 0.00017568274051882327, 0.00016846985090523958, 0.00017247910727746785, 0.000009422447874385398 ]
{ "id": 0, "code_window": [ "// guessIsRPCReq - returns true if the request is for an RPC endpoint.\n", "func guessIsRPCReq(req *http.Request) bool {\n", "\tif req == nil {\n", "\t\treturn false\n", "\t}\n", "\treturn req.Method == http.MethodPost\n", "}\n", "\n", "func (h redirectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n", "\taType := getRequestAuthType(r)\n", "\t// Re-direct only for JWT and anonymous requests from browser.\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\treturn req.Method == http.MethodPost &&\n", "\t\tstrings.HasPrefix(req.URL.Path, minioReservedBucketPath+\"/\")\n" ], "file_path": "cmd/generic-handlers.go", "type": "replace", "edit_start_line_idx": 230 }
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.7 package context import ( "errors" "fmt" "sync" "time" ) // An emptyCtx is never canceled, has no values, and has no deadline. It is not // struct{}, since vars of this type must have distinct addresses. type emptyCtx int func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { return } func (*emptyCtx) Done() <-chan struct{} { return nil } func (*emptyCtx) Err() error { return nil } func (*emptyCtx) Value(key interface{}) interface{} { return nil } func (e *emptyCtx) String() string { switch e { case background: return "context.Background" case todo: return "context.TODO" } return "unknown empty Context" } var ( background = new(emptyCtx) todo = new(emptyCtx) ) // Canceled is the error returned by Context.Err when the context is canceled. var Canceled = errors.New("context canceled") // DeadlineExceeded is the error returned by Context.Err when the context's // deadline passes. var DeadlineExceeded = errors.New("context deadline exceeded") // WithCancel returns a copy of parent with a new Done channel. The returned // context's Done channel is closed when the returned cancel function is called // or when the parent context's Done channel is closed, whichever happens first. // // Canceling this context releases resources associated with it, so code should // call cancel as soon as the operations running in this Context complete. func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { c := newCancelCtx(parent) propagateCancel(parent, c) return c, func() { c.cancel(true, Canceled) } } // newCancelCtx returns an initialized cancelCtx. func newCancelCtx(parent Context) *cancelCtx { return &cancelCtx{ Context: parent, done: make(chan struct{}), } } // propagateCancel arranges for child to be canceled when parent is. func propagateCancel(parent Context, child canceler) { if parent.Done() == nil { return // parent is never canceled } if p, ok := parentCancelCtx(parent); ok { p.mu.Lock() if p.err != nil { // parent has already been canceled child.cancel(false, p.err) } else { if p.children == nil { p.children = make(map[canceler]bool) } p.children[child] = true } p.mu.Unlock() } else { go func() { select { case <-parent.Done(): child.cancel(false, parent.Err()) case <-child.Done(): } }() } } // parentCancelCtx follows a chain of parent references until it finds a // *cancelCtx. This function understands how each of the concrete types in this // package represents its parent. func parentCancelCtx(parent Context) (*cancelCtx, bool) { for { switch c := parent.(type) { case *cancelCtx: return c, true case *timerCtx: return c.cancelCtx, true case *valueCtx: parent = c.Context default: return nil, false } } } // removeChild removes a context from its parent. func removeChild(parent Context, child canceler) { p, ok := parentCancelCtx(parent) if !ok { return } p.mu.Lock() if p.children != nil { delete(p.children, child) } p.mu.Unlock() } // A canceler is a context type that can be canceled directly. The // implementations are *cancelCtx and *timerCtx. type canceler interface { cancel(removeFromParent bool, err error) Done() <-chan struct{} } // A cancelCtx can be canceled. When canceled, it also cancels any children // that implement canceler. type cancelCtx struct { Context done chan struct{} // closed by the first cancel call. mu sync.Mutex children map[canceler]bool // set to nil by the first cancel call err error // set to non-nil by the first cancel call } func (c *cancelCtx) Done() <-chan struct{} { return c.done } func (c *cancelCtx) Err() error { c.mu.Lock() defer c.mu.Unlock() return c.err } func (c *cancelCtx) String() string { return fmt.Sprintf("%v.WithCancel", c.Context) } // cancel closes c.done, cancels each of c's children, and, if // removeFromParent is true, removes c from its parent's children. func (c *cancelCtx) cancel(removeFromParent bool, err error) { if err == nil { panic("context: internal error: missing cancel error") } c.mu.Lock() if c.err != nil { c.mu.Unlock() return // already canceled } c.err = err close(c.done) for child := range c.children { // NOTE: acquiring the child's lock while holding parent's lock. child.cancel(false, err) } c.children = nil c.mu.Unlock() if removeFromParent { removeChild(c.Context, c) } } // WithDeadline returns a copy of the parent context with the deadline adjusted // to be no later than d. If the parent's deadline is already earlier than d, // WithDeadline(parent, d) is semantically equivalent to parent. The returned // context's Done channel is closed when the deadline expires, when the returned // cancel function is called, or when the parent context's Done channel is // closed, whichever happens first. // // Canceling this context releases resources associated with it, so code should // call cancel as soon as the operations running in this Context complete. func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { if cur, ok := parent.Deadline(); ok && cur.Before(deadline) { // The current deadline is already sooner than the new one. return WithCancel(parent) } c := &timerCtx{ cancelCtx: newCancelCtx(parent), deadline: deadline, } propagateCancel(parent, c) d := deadline.Sub(time.Now()) if d <= 0 { c.cancel(true, DeadlineExceeded) // deadline has already passed return c, func() { c.cancel(true, Canceled) } } c.mu.Lock() defer c.mu.Unlock() if c.err == nil { c.timer = time.AfterFunc(d, func() { c.cancel(true, DeadlineExceeded) }) } return c, func() { c.cancel(true, Canceled) } } // A timerCtx carries a timer and a deadline. It embeds a cancelCtx to // implement Done and Err. It implements cancel by stopping its timer then // delegating to cancelCtx.cancel. type timerCtx struct { *cancelCtx timer *time.Timer // Under cancelCtx.mu. deadline time.Time } func (c *timerCtx) Deadline() (deadline time.Time, ok bool) { return c.deadline, true } func (c *timerCtx) String() string { return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now())) } func (c *timerCtx) cancel(removeFromParent bool, err error) { c.cancelCtx.cancel(false, err) if removeFromParent { // Remove this timerCtx from its parent cancelCtx's children. removeChild(c.cancelCtx.Context, c) } c.mu.Lock() if c.timer != nil { c.timer.Stop() c.timer = nil } c.mu.Unlock() } // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). // // Canceling this context releases resources associated with it, so code should // call cancel as soon as the operations running in this Context complete: // // func slowOperationWithTimeout(ctx context.Context) (Result, error) { // ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) // defer cancel() // releases resources if slowOperation completes before timeout elapses // return slowOperation(ctx) // } func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { return WithDeadline(parent, time.Now().Add(timeout)) } // WithValue returns a copy of parent in which the value associated with key is // val. // // Use context Values only for request-scoped data that transits processes and // APIs, not for passing optional parameters to functions. func WithValue(parent Context, key interface{}, val interface{}) Context { return &valueCtx{parent, key, val} } // A valueCtx carries a key-value pair. It implements Value for that key and // delegates all other calls to the embedded Context. type valueCtx struct { Context key, val interface{} } func (c *valueCtx) String() string { return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val) } func (c *valueCtx) Value(key interface{}) interface{} { if c.key == key { return c.val } return c.Context.Value(key) }
vendor/golang.org/x/net/context/pre_go17.go
0
https://github.com/minio/minio/commit/40852801ea63d0e10f220c0d7d2a8d6a8efa5688
[ 0.000640275829937309, 0.00020066714205313474, 0.00016415728896390647, 0.00016913360741455108, 0.00009201706416206434 ]
{ "id": 1, "code_window": [ "func TestGuessIsRPC(t *testing.T) {\n", "\tif guessIsRPCReq(nil) {\n", "\t\tt.Fatal(\"Unexpected return for nil request\")\n", "\t}\n", "\tr := &http.Request{\n", "\t\tProto: \"HTTP/1.0\",\n", "\t\tMethod: http.MethodPost,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tu, err := url.Parse(\"http://localhost:9000/minio/lock\")\n", "\tif err != nil {\n", "\t\tt.Fatal(err)\n", "\t}\n", "\n" ], "file_path": "cmd/generic-handlers_test.go", "type": "add", "edit_start_line_idx": 80 }
/* * Minio Cloud Storage, (C) 2016 Minio, 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 cmd import ( "net/http" "net/http/httptest" "net/url" "strconv" "testing" "github.com/minio/minio/cmd/crypto" ) // Tests getRedirectLocation function for all its criteria. func TestRedirectLocation(t *testing.T) { testCases := []struct { urlPath string location string }{ { // 1. When urlPath is '/minio' urlPath: minioReservedBucketPath, location: minioReservedBucketPath + "/", }, { // 2. When urlPath is '/' urlPath: "/", location: minioReservedBucketPath + "/", }, { // 3. When urlPath is '/webrpc' urlPath: "/webrpc", location: minioReservedBucketPath + "/webrpc", }, { // 4. When urlPath is '/login' urlPath: "/login", location: minioReservedBucketPath + "/login", }, { // 5. When urlPath is '/favicon.ico' urlPath: "/favicon.ico", location: minioReservedBucketPath + "/favicon.ico", }, { // 6. When urlPath is '/unknown' urlPath: "/unknown", location: "", }, } // Validate all conditions. for i, testCase := range testCases { loc := getRedirectLocation(testCase.urlPath) if testCase.location != loc { t.Errorf("Test %d: Unexpected location expected %s, got %s", i+1, testCase.location, loc) } } } // Tests request guess function for net/rpc requests. func TestGuessIsRPC(t *testing.T) { if guessIsRPCReq(nil) { t.Fatal("Unexpected return for nil request") } r := &http.Request{ Proto: "HTTP/1.0", Method: http.MethodPost, } if !guessIsRPCReq(r) { t.Fatal("Test shouldn't fail for a possible net/rpc request.") } r = &http.Request{ Proto: "HTTP/1.1", Method: http.MethodGet, } if guessIsRPCReq(r) { t.Fatal("Test shouldn't report as net/rpc for a non net/rpc request.") } } // Tests browser request guess function. func TestGuessIsBrowser(t *testing.T) { if guessIsBrowserReq(nil) { t.Fatal("Unexpected return for nil request") } r := &http.Request{ Header: http.Header{}, } r.Header.Set("User-Agent", "Mozilla") if !guessIsBrowserReq(r) { t.Fatal("Test shouldn't fail for a possible browser request.") } r = &http.Request{ Header: http.Header{}, } r.Header.Set("User-Agent", "mc") if guessIsBrowserReq(r) { t.Fatal("Test shouldn't report as browser for a non browser request.") } } var isHTTPHeaderSizeTooLargeTests = []struct { header http.Header shouldFail bool }{ {header: generateHeader(0, 0), shouldFail: false}, {header: generateHeader(1024, 0), shouldFail: false}, {header: generateHeader(2048, 0), shouldFail: false}, {header: generateHeader(8*1024+1, 0), shouldFail: true}, {header: generateHeader(0, 1024), shouldFail: false}, {header: generateHeader(0, 2048), shouldFail: true}, {header: generateHeader(0, 2048+1), shouldFail: true}, } func generateHeader(size, usersize int) http.Header { header := http.Header{} for i := 0; i < size; i++ { header.Add(strconv.Itoa(i), "") } userlength := 0 for i := 0; userlength < usersize; i++ { userlength += len(userMetadataKeyPrefixes[0] + strconv.Itoa(i)) header.Add(userMetadataKeyPrefixes[0]+strconv.Itoa(i), "") } return header } func TestIsHTTPHeaderSizeTooLarge(t *testing.T) { for i, test := range isHTTPHeaderSizeTooLargeTests { if res := isHTTPHeaderSizeTooLarge(test.header); res != test.shouldFail { t.Errorf("Test %d: Expected %v got %v", i, res, test.shouldFail) } } } var containsReservedMetadataTests = []struct { header http.Header shouldFail bool }{ { header: http.Header{"X-Minio-Key": []string{"value"}}, }, { header: http.Header{crypto.SSEIV: []string{"iv"}}, shouldFail: true, }, { header: http.Header{crypto.SSESealAlgorithm: []string{SSESealAlgorithmDareSha256}}, shouldFail: true, }, { header: http.Header{crypto.SSECSealedKey: []string{"mac"}}, shouldFail: true, }, { header: http.Header{ReservedMetadataPrefix + "Key": []string{"value"}}, shouldFail: true, }, } func TestContainsReservedMetadata(t *testing.T) { for i, test := range containsReservedMetadataTests { if contains := containsReservedMetadata(test.header); contains && !test.shouldFail { t.Errorf("Test %d: contains reserved header but should not fail", i) } else if !contains && test.shouldFail { t.Errorf("Test %d: does not contain reserved header but failed", i) } } } var sseTLSHandlerTests = []struct { URL *url.URL Header http.Header IsTLS, ShouldFail bool }{ {URL: &url.URL{}, Header: http.Header{}, IsTLS: false, ShouldFail: false}, // 0 {URL: &url.URL{}, Header: http.Header{crypto.SSECAlgorithm: []string{"AES256"}}, IsTLS: false, ShouldFail: true}, // 1 {URL: &url.URL{}, Header: http.Header{crypto.SSECAlgorithm: []string{"AES256"}}, IsTLS: true, ShouldFail: false}, // 2 {URL: &url.URL{}, Header: http.Header{crypto.SSECKey: []string{""}}, IsTLS: true, ShouldFail: false}, // 3 {URL: &url.URL{}, Header: http.Header{crypto.SSECopyAlgorithm: []string{""}}, IsTLS: false, ShouldFail: true}, // 4 } func TestSSETLSHandler(t *testing.T) { defer func(isSSL bool) { globalIsSSL = isSSL }(globalIsSSL) // reset globalIsSSL after test var okHandler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } for i, test := range sseTLSHandlerTests { globalIsSSL = test.IsTLS w := httptest.NewRecorder() r := new(http.Request) r.Header = test.Header r.URL = test.URL h := setSSETLSHandler(okHandler) h.ServeHTTP(w, r) switch { case test.ShouldFail && w.Code == http.StatusOK: t.Errorf("Test %d: should fail but status code is HTTP %d", i, w.Code) case !test.ShouldFail && w.Code != http.StatusOK: t.Errorf("Test %d: should not fail but status code is HTTP %d and not 200 OK", i, w.Code) } } }
cmd/generic-handlers_test.go
1
https://github.com/minio/minio/commit/40852801ea63d0e10f220c0d7d2a8d6a8efa5688
[ 0.9984796643257141, 0.23619234561920166, 0.0001652901992201805, 0.0003217664489056915, 0.4068933129310608 ]
{ "id": 1, "code_window": [ "func TestGuessIsRPC(t *testing.T) {\n", "\tif guessIsRPCReq(nil) {\n", "\t\tt.Fatal(\"Unexpected return for nil request\")\n", "\t}\n", "\tr := &http.Request{\n", "\t\tProto: \"HTTP/1.0\",\n", "\t\tMethod: http.MethodPost,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tu, err := url.Parse(\"http://localhost:9000/minio/lock\")\n", "\tif err != nil {\n", "\t\tt.Fatal(err)\n", "\t}\n", "\n" ], "file_path": "cmd/generic-handlers_test.go", "type": "add", "edit_start_line_idx": 80 }
/* * Minio Cloud Storage, (C) 2016 Minio, 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 cmd import ( "context" "sort" "strings" ) // Tree walk result carries results of tree walking. type treeWalkResult struct { entry string err error end bool } // posix.ListDir returns entries with trailing "/" for directories. At the object layer // we need to remove this trailing "/" for objects and retain "/" for prefixes before // sorting because the trailing "/" can affect the sorting results for certain cases. // Ex. lets say entries = ["a-b/", "a/"] and both are objects. // sorting with out trailing "/" = ["a", "a-b"] // sorting with trailing "/" = ["a-b/", "a/"] // Hence if entries[] does not have a case like the above example then isLeaf() check // can be delayed till the entry is pushed into the treeWalkResult channel. // delayIsLeafCheck() returns true if isLeaf can be delayed or false if // isLeaf should be done in listDir() func delayIsLeafCheck(entries []string) bool { for i, entry := range entries { if i == len(entries)-1 { break } // If any byte in the "entry" string is less than '/' then the // next "entry" should not contain '/' at the same same byte position. for j := 0; j < len(entry); j++ { if entry[j] < '/' { if len(entries[i+1]) > j { if entries[i+1][j] == '/' { return false } } } } } return true } // Return entries that have prefix prefixEntry. // Note: input entries are expected to be sorted. func filterMatchingPrefix(entries []string, prefixEntry string) []string { start := 0 end := len(entries) for { if start == end { break } if hasPrefix(entries[start], prefixEntry) { break } start++ } for { if start == end { break } if hasPrefix(entries[end-1], prefixEntry) { break } end-- } return entries[start:end] } // "listDir" function of type listDirFunc returned by listDirFactory() - explained below. type listDirFunc func(bucket, prefixDir, prefixEntry string) (entries []string, delayIsLeaf bool) // A function isLeaf of type isLeafFunc is used to detect if an entry is a leaf entry. There are four scenarios // where isLeaf should behave differently: // 1. FS backend object listing - isLeaf is true if the entry has a trailing "/" // 2. FS backend multipart listing - isLeaf is true if the entry is a directory and contains uploads.json // 3. XL backend object listing - isLeaf is true if the entry is a directory and contains xl.json // 4. XL backend multipart listing - isLeaf is true if the entry is a directory and contains uploads.json type isLeafFunc func(string, string) bool // A function isLeafDir of type isLeafDirFunc is used to detect if an entry represents an empty directory. type isLeafDirFunc func(string, string) bool func filterListEntries(bucket, prefixDir string, entries []string, prefixEntry string, isLeaf isLeafFunc) ([]string, bool) { // Listing needs to be sorted. sort.Strings(entries) // Filter entries that have the prefix prefixEntry. entries = filterMatchingPrefix(entries, prefixEntry) // Can isLeaf() check be delayed till when it has to be sent down the // treeWalkResult channel? delayIsLeaf := delayIsLeafCheck(entries) if delayIsLeaf { return entries, true } // isLeaf() check has to happen here so that trailing "/" for objects can be removed. for i, entry := range entries { if isLeaf(bucket, pathJoin(prefixDir, entry)) { entries[i] = strings.TrimSuffix(entry, slashSeparator) } } // Sort again after removing trailing "/" for objects as the previous sort // does not hold good anymore. sort.Strings(entries) return entries, false } // treeWalk walks directory tree recursively pushing treeWalkResult into the channel as and when it encounters files. func doTreeWalk(ctx context.Context, bucket, prefixDir, entryPrefixMatch, marker string, recursive bool, listDir listDirFunc, isLeaf isLeafFunc, isLeafDir isLeafDirFunc, resultCh chan treeWalkResult, endWalkCh chan struct{}, isEnd bool) error { // Example: // if prefixDir="one/two/three/" and marker="four/five.txt" treeWalk is recursively // called with prefixDir="one/two/three/four/" and marker="five.txt" var markerBase, markerDir string if marker != "" { // Ex: if marker="four/five.txt", markerDir="four/" markerBase="five.txt" markerSplit := strings.SplitN(marker, slashSeparator, 2) markerDir = markerSplit[0] if len(markerSplit) == 2 { markerDir += slashSeparator markerBase = markerSplit[1] } } entries, delayIsLeaf := listDir(bucket, prefixDir, entryPrefixMatch) // When isleaf check is delayed, make sure that it is set correctly here. if delayIsLeaf && isLeaf == nil { return errInvalidArgument } // For an empty list return right here. if len(entries) == 0 { return nil } // example: // If markerDir="four/" Search() returns the index of "four/" in the sorted // entries list so we skip all the entries till "four/" idx := sort.Search(len(entries), func(i int) bool { return entries[i] >= markerDir }) entries = entries[idx:] // For an empty list after search through the entries, return right here. if len(entries) == 0 { return nil } for i, entry := range entries { var leaf, leafDir bool // Decision to do isLeaf check was pushed from listDir() to here. if delayIsLeaf { leaf = isLeaf(bucket, pathJoin(prefixDir, entry)) if leaf { entry = strings.TrimSuffix(entry, slashSeparator) } } else { leaf = !strings.HasSuffix(entry, slashSeparator) } if strings.HasSuffix(entry, slashSeparator) { leafDir = isLeafDir(bucket, pathJoin(prefixDir, entry)) } isDir := !leafDir && !leaf if i == 0 && markerDir == entry { if !recursive { // Skip as the marker would already be listed in the previous listing. continue } if recursive && !isDir { // We should not skip for recursive listing and if markerDir is a directory // for ex. if marker is "four/five.txt" markerDir will be "four/" which // should not be skipped, instead it will need to be treeWalk()'ed into. // Skip if it is a file though as it would be listed in previous listing. continue } } if recursive && isDir { // If the entry is a directory, we will need recurse into it. markerArg := "" if entry == markerDir { // We need to pass "five.txt" as marker only if we are // recursing into "four/" markerArg = markerBase } prefixMatch := "" // Valid only for first level treeWalk and empty for subdirectories. // markIsEnd is passed to this entry's treeWalk() so that treeWalker.end can be marked // true at the end of the treeWalk stream. markIsEnd := i == len(entries)-1 && isEnd if tErr := doTreeWalk(ctx, bucket, pathJoin(prefixDir, entry), prefixMatch, markerArg, recursive, listDir, isLeaf, isLeafDir, resultCh, endWalkCh, markIsEnd); tErr != nil { return tErr } continue } // EOF is set if we are at last entry and the caller indicated we at the end. isEOF := ((i == len(entries)-1) && isEnd) select { case <-endWalkCh: return errWalkAbort case resultCh <- treeWalkResult{entry: pathJoin(prefixDir, entry), end: isEOF}: } } // Everything is listed. return nil } // Initiate a new treeWalk in a goroutine. func startTreeWalk(ctx context.Context, bucket, prefix, marker string, recursive bool, listDir listDirFunc, isLeaf isLeafFunc, isLeafDir isLeafDirFunc, endWalkCh chan struct{}) chan treeWalkResult { // Example 1 // If prefix is "one/two/three/" and marker is "one/two/three/four/five.txt" // treeWalk is called with prefixDir="one/two/three/" and marker="four/five.txt" // and entryPrefixMatch="" // Example 2 // if prefix is "one/two/th" and marker is "one/two/three/four/five.txt" // treeWalk is called with prefixDir="one/two/" and marker="three/four/five.txt" // and entryPrefixMatch="th" resultCh := make(chan treeWalkResult, maxObjectList) entryPrefixMatch := prefix prefixDir := "" lastIndex := strings.LastIndex(prefix, slashSeparator) if lastIndex != -1 { entryPrefixMatch = prefix[lastIndex+1:] prefixDir = prefix[:lastIndex+1] } marker = strings.TrimPrefix(marker, prefixDir) go func() { isEnd := true // Indication to start walking the tree with end as true. doTreeWalk(ctx, bucket, prefixDir, entryPrefixMatch, marker, recursive, listDir, isLeaf, isLeafDir, resultCh, endWalkCh, isEnd) close(resultCh) }() return resultCh }
cmd/tree-walk.go
0
https://github.com/minio/minio/commit/40852801ea63d0e10f220c0d7d2a8d6a8efa5688
[ 0.00017857804778032005, 0.00017048415611498058, 0.00016308452177327126, 0.00017059530364349484, 0.0000034388281164865475 ]
{ "id": 1, "code_window": [ "func TestGuessIsRPC(t *testing.T) {\n", "\tif guessIsRPCReq(nil) {\n", "\t\tt.Fatal(\"Unexpected return for nil request\")\n", "\t}\n", "\tr := &http.Request{\n", "\t\tProto: \"HTTP/1.0\",\n", "\t\tMethod: http.MethodPost,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tu, err := url.Parse(\"http://localhost:9000/minio/lock\")\n", "\tif err != nil {\n", "\t\tt.Fatal(err)\n", "\t}\n", "\n" ], "file_path": "cmd/generic-handlers_test.go", "type": "add", "edit_start_line_idx": 80 }
The MIT License (MIT) Copyright (c) 2016 Apcera Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
vendor/github.com/nats-io/go-nats-streaming/LICENSE
0
https://github.com/minio/minio/commit/40852801ea63d0e10f220c0d7d2a8d6a8efa5688
[ 0.00017838674830272794, 0.00017458002548664808, 0.00017066810687538236, 0.0001746851921780035, 0.000003151999635520042 ]
{ "id": 1, "code_window": [ "func TestGuessIsRPC(t *testing.T) {\n", "\tif guessIsRPCReq(nil) {\n", "\t\tt.Fatal(\"Unexpected return for nil request\")\n", "\t}\n", "\tr := &http.Request{\n", "\t\tProto: \"HTTP/1.0\",\n", "\t\tMethod: http.MethodPost,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "\tu, err := url.Parse(\"http://localhost:9000/minio/lock\")\n", "\tif err != nil {\n", "\t\tt.Fatal(err)\n", "\t}\n", "\n" ], "file_path": "cmd/generic-handlers_test.go", "type": "add", "edit_start_line_idx": 80 }
// Copyright 2015 The etcd Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package logutil import ( "fmt" "sync" "time" "github.com/coreos/pkg/capnslog" ) var ( defaultMergePeriod = time.Second defaultTimeOutputScale = 10 * time.Millisecond outputInterval = time.Second ) // line represents a log line that can be printed out // through capnslog.PackageLogger. type line struct { level capnslog.LogLevel str string } func (l line) append(s string) line { return line{ level: l.level, str: l.str + " " + s, } } // status represents the merge status of a line. type status struct { period time.Duration start time.Time // start time of latest merge period count int // number of merged lines from starting } func (s *status) isInMergePeriod(now time.Time) bool { return s.period == 0 || s.start.Add(s.period).After(now) } func (s *status) isEmpty() bool { return s.count == 0 } func (s *status) summary(now time.Time) string { ts := s.start.Round(defaultTimeOutputScale) took := now.Round(defaultTimeOutputScale).Sub(ts) return fmt.Sprintf("[merged %d repeated lines in %s]", s.count, took) } func (s *status) reset(now time.Time) { s.start = now s.count = 0 } // MergeLogger supports merge logging, which merges repeated log lines // and prints summary log lines instead. // // For merge logging, MergeLogger prints out the line when the line appears // at the first time. MergeLogger holds the same log line printed within // defaultMergePeriod, and prints out summary log line at the end of defaultMergePeriod. // It stops merging when the line doesn't appear within the // defaultMergePeriod. type MergeLogger struct { *capnslog.PackageLogger mu sync.Mutex // protect statusm statusm map[line]*status } func NewMergeLogger(logger *capnslog.PackageLogger) *MergeLogger { l := &MergeLogger{ PackageLogger: logger, statusm: make(map[line]*status), } go l.outputLoop() return l } func (l *MergeLogger) MergeInfo(entries ...interface{}) { l.merge(line{ level: capnslog.INFO, str: fmt.Sprint(entries...), }) } func (l *MergeLogger) MergeInfof(format string, args ...interface{}) { l.merge(line{ level: capnslog.INFO, str: fmt.Sprintf(format, args...), }) } func (l *MergeLogger) MergeNotice(entries ...interface{}) { l.merge(line{ level: capnslog.NOTICE, str: fmt.Sprint(entries...), }) } func (l *MergeLogger) MergeNoticef(format string, args ...interface{}) { l.merge(line{ level: capnslog.NOTICE, str: fmt.Sprintf(format, args...), }) } func (l *MergeLogger) MergeWarning(entries ...interface{}) { l.merge(line{ level: capnslog.WARNING, str: fmt.Sprint(entries...), }) } func (l *MergeLogger) MergeWarningf(format string, args ...interface{}) { l.merge(line{ level: capnslog.WARNING, str: fmt.Sprintf(format, args...), }) } func (l *MergeLogger) MergeError(entries ...interface{}) { l.merge(line{ level: capnslog.ERROR, str: fmt.Sprint(entries...), }) } func (l *MergeLogger) MergeErrorf(format string, args ...interface{}) { l.merge(line{ level: capnslog.ERROR, str: fmt.Sprintf(format, args...), }) } func (l *MergeLogger) merge(ln line) { l.mu.Lock() // increase count if the logger is merging the line if status, ok := l.statusm[ln]; ok { status.count++ l.mu.Unlock() return } // initialize status of the line l.statusm[ln] = &status{ period: defaultMergePeriod, start: time.Now(), } // release the lock before IO operation l.mu.Unlock() // print out the line at its first time l.PackageLogger.Logf(ln.level, ln.str) } func (l *MergeLogger) outputLoop() { for now := range time.Tick(outputInterval) { var outputs []line l.mu.Lock() for ln, status := range l.statusm { if status.isInMergePeriod(now) { continue } if status.isEmpty() { delete(l.statusm, ln) continue } outputs = append(outputs, ln.append(status.summary(now))) status.reset(now) } l.mu.Unlock() for _, o := range outputs { l.PackageLogger.Logf(o.level, o.str) } } }
vendor/github.com/coreos/etcd/pkg/logutil/merge_logger.go
0
https://github.com/minio/minio/commit/40852801ea63d0e10f220c0d7d2a8d6a8efa5688
[ 0.00018221713253296912, 0.00017338038014713675, 0.00016629497986286879, 0.00017347416724078357, 0.0000037852009882044513 ]
{ "id": 2, "code_window": [ "\tr := &http.Request{\n", "\t\tProto: \"HTTP/1.0\",\n", "\t\tMethod: http.MethodPost,\n", "\t}\n", "\tif !guessIsRPCReq(r) {\n", "\t\tt.Fatal(\"Test shouldn't fail for a possible net/rpc request.\")\n", "\t}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tURL: u,\n" ], "file_path": "cmd/generic-handlers_test.go", "type": "add", "edit_start_line_idx": 83 }
/* * Minio Cloud Storage, (C) 2016 Minio, 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 cmd import ( "net/http" "net/http/httptest" "net/url" "strconv" "testing" "github.com/minio/minio/cmd/crypto" ) // Tests getRedirectLocation function for all its criteria. func TestRedirectLocation(t *testing.T) { testCases := []struct { urlPath string location string }{ { // 1. When urlPath is '/minio' urlPath: minioReservedBucketPath, location: minioReservedBucketPath + "/", }, { // 2. When urlPath is '/' urlPath: "/", location: minioReservedBucketPath + "/", }, { // 3. When urlPath is '/webrpc' urlPath: "/webrpc", location: minioReservedBucketPath + "/webrpc", }, { // 4. When urlPath is '/login' urlPath: "/login", location: minioReservedBucketPath + "/login", }, { // 5. When urlPath is '/favicon.ico' urlPath: "/favicon.ico", location: minioReservedBucketPath + "/favicon.ico", }, { // 6. When urlPath is '/unknown' urlPath: "/unknown", location: "", }, } // Validate all conditions. for i, testCase := range testCases { loc := getRedirectLocation(testCase.urlPath) if testCase.location != loc { t.Errorf("Test %d: Unexpected location expected %s, got %s", i+1, testCase.location, loc) } } } // Tests request guess function for net/rpc requests. func TestGuessIsRPC(t *testing.T) { if guessIsRPCReq(nil) { t.Fatal("Unexpected return for nil request") } r := &http.Request{ Proto: "HTTP/1.0", Method: http.MethodPost, } if !guessIsRPCReq(r) { t.Fatal("Test shouldn't fail for a possible net/rpc request.") } r = &http.Request{ Proto: "HTTP/1.1", Method: http.MethodGet, } if guessIsRPCReq(r) { t.Fatal("Test shouldn't report as net/rpc for a non net/rpc request.") } } // Tests browser request guess function. func TestGuessIsBrowser(t *testing.T) { if guessIsBrowserReq(nil) { t.Fatal("Unexpected return for nil request") } r := &http.Request{ Header: http.Header{}, } r.Header.Set("User-Agent", "Mozilla") if !guessIsBrowserReq(r) { t.Fatal("Test shouldn't fail for a possible browser request.") } r = &http.Request{ Header: http.Header{}, } r.Header.Set("User-Agent", "mc") if guessIsBrowserReq(r) { t.Fatal("Test shouldn't report as browser for a non browser request.") } } var isHTTPHeaderSizeTooLargeTests = []struct { header http.Header shouldFail bool }{ {header: generateHeader(0, 0), shouldFail: false}, {header: generateHeader(1024, 0), shouldFail: false}, {header: generateHeader(2048, 0), shouldFail: false}, {header: generateHeader(8*1024+1, 0), shouldFail: true}, {header: generateHeader(0, 1024), shouldFail: false}, {header: generateHeader(0, 2048), shouldFail: true}, {header: generateHeader(0, 2048+1), shouldFail: true}, } func generateHeader(size, usersize int) http.Header { header := http.Header{} for i := 0; i < size; i++ { header.Add(strconv.Itoa(i), "") } userlength := 0 for i := 0; userlength < usersize; i++ { userlength += len(userMetadataKeyPrefixes[0] + strconv.Itoa(i)) header.Add(userMetadataKeyPrefixes[0]+strconv.Itoa(i), "") } return header } func TestIsHTTPHeaderSizeTooLarge(t *testing.T) { for i, test := range isHTTPHeaderSizeTooLargeTests { if res := isHTTPHeaderSizeTooLarge(test.header); res != test.shouldFail { t.Errorf("Test %d: Expected %v got %v", i, res, test.shouldFail) } } } var containsReservedMetadataTests = []struct { header http.Header shouldFail bool }{ { header: http.Header{"X-Minio-Key": []string{"value"}}, }, { header: http.Header{crypto.SSEIV: []string{"iv"}}, shouldFail: true, }, { header: http.Header{crypto.SSESealAlgorithm: []string{SSESealAlgorithmDareSha256}}, shouldFail: true, }, { header: http.Header{crypto.SSECSealedKey: []string{"mac"}}, shouldFail: true, }, { header: http.Header{ReservedMetadataPrefix + "Key": []string{"value"}}, shouldFail: true, }, } func TestContainsReservedMetadata(t *testing.T) { for i, test := range containsReservedMetadataTests { if contains := containsReservedMetadata(test.header); contains && !test.shouldFail { t.Errorf("Test %d: contains reserved header but should not fail", i) } else if !contains && test.shouldFail { t.Errorf("Test %d: does not contain reserved header but failed", i) } } } var sseTLSHandlerTests = []struct { URL *url.URL Header http.Header IsTLS, ShouldFail bool }{ {URL: &url.URL{}, Header: http.Header{}, IsTLS: false, ShouldFail: false}, // 0 {URL: &url.URL{}, Header: http.Header{crypto.SSECAlgorithm: []string{"AES256"}}, IsTLS: false, ShouldFail: true}, // 1 {URL: &url.URL{}, Header: http.Header{crypto.SSECAlgorithm: []string{"AES256"}}, IsTLS: true, ShouldFail: false}, // 2 {URL: &url.URL{}, Header: http.Header{crypto.SSECKey: []string{""}}, IsTLS: true, ShouldFail: false}, // 3 {URL: &url.URL{}, Header: http.Header{crypto.SSECopyAlgorithm: []string{""}}, IsTLS: false, ShouldFail: true}, // 4 } func TestSSETLSHandler(t *testing.T) { defer func(isSSL bool) { globalIsSSL = isSSL }(globalIsSSL) // reset globalIsSSL after test var okHandler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } for i, test := range sseTLSHandlerTests { globalIsSSL = test.IsTLS w := httptest.NewRecorder() r := new(http.Request) r.Header = test.Header r.URL = test.URL h := setSSETLSHandler(okHandler) h.ServeHTTP(w, r) switch { case test.ShouldFail && w.Code == http.StatusOK: t.Errorf("Test %d: should fail but status code is HTTP %d", i, w.Code) case !test.ShouldFail && w.Code != http.StatusOK: t.Errorf("Test %d: should not fail but status code is HTTP %d and not 200 OK", i, w.Code) } } }
cmd/generic-handlers_test.go
1
https://github.com/minio/minio/commit/40852801ea63d0e10f220c0d7d2a8d6a8efa5688
[ 0.9981392621994019, 0.18822278082370758, 0.00016490199777763337, 0.00030458628316409886, 0.3657934367656708 ]
{ "id": 2, "code_window": [ "\tr := &http.Request{\n", "\t\tProto: \"HTTP/1.0\",\n", "\t\tMethod: http.MethodPost,\n", "\t}\n", "\tif !guessIsRPCReq(r) {\n", "\t\tt.Fatal(\"Test shouldn't fail for a possible net/rpc request.\")\n", "\t}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tURL: u,\n" ], "file_path": "cmd/generic-handlers_test.go", "type": "add", "edit_start_line_idx": 83 }
// Copyright (c) 2016 Uber Technologies, Inc. // // 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. package atomic import "sync/atomic" // String is an atomic type-safe wrapper around atomic.Value for strings. type String struct{ v atomic.Value } // NewString creates a String. func NewString(str string) *String { s := &String{} if str != "" { s.Store(str) } return s } // Load atomically loads the wrapped string. func (s *String) Load() string { v := s.v.Load() if v == nil { return "" } return v.(string) } // Store atomically stores the passed string. // Note: Converting the string to an interface{} to store in the atomic.Value // requires an allocation. func (s *String) Store(str string) { s.v.Store(str) }
vendor/go.uber.org/atomic/string.go
0
https://github.com/minio/minio/commit/40852801ea63d0e10f220c0d7d2a8d6a8efa5688
[ 0.00018264677783008665, 0.00017416475748177618, 0.0001660745620029047, 0.00017531821504235268, 0.000005719477940147044 ]
{ "id": 2, "code_window": [ "\tr := &http.Request{\n", "\t\tProto: \"HTTP/1.0\",\n", "\t\tMethod: http.MethodPost,\n", "\t}\n", "\tif !guessIsRPCReq(r) {\n", "\t\tt.Fatal(\"Test shouldn't fail for a possible net/rpc request.\")\n", "\t}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tURL: u,\n" ], "file_path": "cmd/generic-handlers_test.go", "type": "add", "edit_start_line_idx": 83 }
// Copyright 2012-present Oliver Eilhard. All rights reserved. // Use of this source code is governed by a MIT-license. // See http://olivere.mit-license.org/license.txt for details. package elastic import ( "time" ) // RangeAggregation is a multi-bucket value source based aggregation that // enables the user to define a set of ranges - each representing a bucket. // During the aggregation process, the values extracted from each document // will be checked against each bucket range and "bucket" the // relevant/matching document. Note that this aggregration includes the // from value and excludes the to value for each range. // See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-range-aggregation.html type RangeAggregation struct { field string script *Script missing interface{} subAggregations map[string]Aggregation meta map[string]interface{} keyed *bool unmapped *bool entries []rangeAggregationEntry } type rangeAggregationEntry struct { Key string From interface{} To interface{} } func NewRangeAggregation() *RangeAggregation { return &RangeAggregation{ subAggregations: make(map[string]Aggregation), entries: make([]rangeAggregationEntry, 0), } } func (a *RangeAggregation) Field(field string) *RangeAggregation { a.field = field return a } func (a *RangeAggregation) Script(script *Script) *RangeAggregation { a.script = script return a } // Missing configures the value to use when documents miss a value. func (a *RangeAggregation) Missing(missing interface{}) *RangeAggregation { a.missing = missing return a } func (a *RangeAggregation) SubAggregation(name string, subAggregation Aggregation) *RangeAggregation { a.subAggregations[name] = subAggregation return a } // Meta sets the meta data to be included in the aggregation response. func (a *RangeAggregation) Meta(metaData map[string]interface{}) *RangeAggregation { a.meta = metaData return a } func (a *RangeAggregation) Keyed(keyed bool) *RangeAggregation { a.keyed = &keyed return a } func (a *RangeAggregation) Unmapped(unmapped bool) *RangeAggregation { a.unmapped = &unmapped return a } func (a *RangeAggregation) AddRange(from, to interface{}) *RangeAggregation { a.entries = append(a.entries, rangeAggregationEntry{From: from, To: to}) return a } func (a *RangeAggregation) AddRangeWithKey(key string, from, to interface{}) *RangeAggregation { a.entries = append(a.entries, rangeAggregationEntry{Key: key, From: from, To: to}) return a } func (a *RangeAggregation) AddUnboundedTo(from interface{}) *RangeAggregation { a.entries = append(a.entries, rangeAggregationEntry{From: from, To: nil}) return a } func (a *RangeAggregation) AddUnboundedToWithKey(key string, from interface{}) *RangeAggregation { a.entries = append(a.entries, rangeAggregationEntry{Key: key, From: from, To: nil}) return a } func (a *RangeAggregation) AddUnboundedFrom(to interface{}) *RangeAggregation { a.entries = append(a.entries, rangeAggregationEntry{From: nil, To: to}) return a } func (a *RangeAggregation) AddUnboundedFromWithKey(key string, to interface{}) *RangeAggregation { a.entries = append(a.entries, rangeAggregationEntry{Key: key, From: nil, To: to}) return a } func (a *RangeAggregation) Lt(to interface{}) *RangeAggregation { a.entries = append(a.entries, rangeAggregationEntry{From: nil, To: to}) return a } func (a *RangeAggregation) LtWithKey(key string, to interface{}) *RangeAggregation { a.entries = append(a.entries, rangeAggregationEntry{Key: key, From: nil, To: to}) return a } func (a *RangeAggregation) Between(from, to interface{}) *RangeAggregation { a.entries = append(a.entries, rangeAggregationEntry{From: from, To: to}) return a } func (a *RangeAggregation) BetweenWithKey(key string, from, to interface{}) *RangeAggregation { a.entries = append(a.entries, rangeAggregationEntry{Key: key, From: from, To: to}) return a } func (a *RangeAggregation) Gt(from interface{}) *RangeAggregation { a.entries = append(a.entries, rangeAggregationEntry{From: from, To: nil}) return a } func (a *RangeAggregation) GtWithKey(key string, from interface{}) *RangeAggregation { a.entries = append(a.entries, rangeAggregationEntry{Key: key, From: from, To: nil}) return a } func (a *RangeAggregation) Source() (interface{}, error) { // Example: // { // "aggs" : { // "price_ranges" : { // "range" : { // "field" : "price", // "ranges" : [ // { "to" : 50 }, // { "from" : 50, "to" : 100 }, // { "from" : 100 } // ] // } // } // } // } // // This method returns only the { "range" : { ... } } part. source := make(map[string]interface{}) opts := make(map[string]interface{}) source["range"] = opts // ValuesSourceAggregationBuilder if a.field != "" { opts["field"] = a.field } if a.script != nil { src, err := a.script.Source() if err != nil { return nil, err } opts["script"] = src } if a.missing != nil { opts["missing"] = a.missing } if a.keyed != nil { opts["keyed"] = *a.keyed } if a.unmapped != nil { opts["unmapped"] = *a.unmapped } var ranges []interface{} for _, ent := range a.entries { r := make(map[string]interface{}) if ent.Key != "" { r["key"] = ent.Key } if ent.From != nil { switch from := ent.From.(type) { case int, int16, int32, int64, float32, float64: r["from"] = from case time.Time: r["from"] = from.Format(time.RFC3339) case string: r["from"] = from } } if ent.To != nil { switch to := ent.To.(type) { case int, int16, int32, int64, float32, float64: r["to"] = to case time.Time: r["to"] = to.Format(time.RFC3339) case string: r["to"] = to } } ranges = append(ranges, r) } opts["ranges"] = ranges // AggregationBuilder (SubAggregations) if len(a.subAggregations) > 0 { aggsMap := make(map[string]interface{}) source["aggregations"] = aggsMap for name, aggregate := range a.subAggregations { src, err := aggregate.Source() if err != nil { return nil, err } aggsMap[name] = src } } // Add Meta data if available if len(a.meta) > 0 { source["meta"] = a.meta } return source, nil }
vendor/gopkg.in/olivere/elastic.v5/search_aggs_bucket_range.go
0
https://github.com/minio/minio/commit/40852801ea63d0e10f220c0d7d2a8d6a8efa5688
[ 0.003730162512511015, 0.0005032432381995022, 0.0001658160035731271, 0.00017166425823234022, 0.0009333865600638092 ]
{ "id": 2, "code_window": [ "\tr := &http.Request{\n", "\t\tProto: \"HTTP/1.0\",\n", "\t\tMethod: http.MethodPost,\n", "\t}\n", "\tif !guessIsRPCReq(r) {\n", "\t\tt.Fatal(\"Test shouldn't fail for a possible net/rpc request.\")\n", "\t}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tURL: u,\n" ], "file_path": "cmd/generic-handlers_test.go", "type": "add", "edit_start_line_idx": 83 }
/* * Minio Cloud Storage (C) 2018 Minio, 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. */ import React from "react" import { shallow } from "enzyme" import { ObjectsList } from "../ObjectsList" describe("ObjectsList", () => { it("should render without crashing", () => { shallow(<ObjectsList objects={[]} />) }) it("should render ObjectContainer for every object", () => { const wrapper = shallow( <ObjectsList objects={[{ name: "test1.jpg" }, { name: "test2.jpg" }]} /> ) expect(wrapper.find("Connect(ObjectContainer)").length).toBe(2) }) it("should render PrefixContainer for every prefix", () => { const wrapper = shallow( <ObjectsList objects={[{ name: "abc/" }, { name: "xyz/" }]} /> ) expect(wrapper.find("Connect(PrefixContainer)").length).toBe(2) }) })
browser/app/js/objects/__tests__/ObjectsList.test.js
0
https://github.com/minio/minio/commit/40852801ea63d0e10f220c0d7d2a8d6a8efa5688
[ 0.0001775571145117283, 0.00017322039639111608, 0.00016738071280997247, 0.00017397185729350895, 0.000003677780796351726 ]
{ "id": 0, "code_window": [ "func (container *Container) Mount() error {\n", "\timage, err := container.GetImage()\n", "\tif err != nil {\n", "\t\treturn err\n", "\t}\n", "\treturn image.Mount(container.RootfsPath(), container.rwPath())\n", "}\n", "\n", "func (container *Container) Changes() ([]Change, error) {\n", "\timage, err := container.GetImage()\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\treturn image.Mount(container.runtime, container.RootfsPath(), container.rwPath(), container.ID)\n" ], "file_path": "container.go", "type": "replace", "edit_start_line_idx": 1000 }
package docker import ( "crypto/rand" "encoding/hex" "encoding/json" "fmt" "github.com/dotcloud/docker/utils" "io" "io/ioutil" "log" "os" "os/exec" "path" "path/filepath" "strconv" "strings" "time" ) type Image struct { ID string `json:"id"` Parent string `json:"parent,omitempty"` Comment string `json:"comment,omitempty"` Created time.Time `json:"created"` Container string `json:"container,omitempty"` ContainerConfig Config `json:"container_config,omitempty"` DockerVersion string `json:"docker_version,omitempty"` Author string `json:"author,omitempty"` Config *Config `json:"config,omitempty"` Architecture string `json:"architecture,omitempty"` graph *Graph Size int64 } func LoadImage(root string) (*Image, error) { // Load the json data jsonData, err := ioutil.ReadFile(jsonPath(root)) if err != nil { return nil, err } img := &Image{} if err := json.Unmarshal(jsonData, img); err != nil { return nil, err } if err := ValidateID(img.ID); err != nil { return nil, err } if buf, err := ioutil.ReadFile(path.Join(root, "layersize")); err != nil { if !os.IsNotExist(err) { return nil, err } } else { if size, err := strconv.Atoi(string(buf)); err != nil { return nil, err } else { img.Size = int64(size) } } // Check that the filesystem layer exists if stat, err := os.Stat(layerPath(root)); err != nil { if os.IsNotExist(err) { return nil, fmt.Errorf("Couldn't load image %s: no filesystem layer", img.ID) } return nil, err } else if !stat.IsDir() { return nil, fmt.Errorf("Couldn't load image %s: %s is not a directory", img.ID, layerPath(root)) } return img, nil } func StoreImage(img *Image, jsonData []byte, layerData Archive, root string) error { // Check that root doesn't already exist if _, err := os.Stat(root); err == nil { return fmt.Errorf("Image %s already exists", img.ID) } else if !os.IsNotExist(err) { return err } // Store the layer layer := layerPath(root) if err := os.MkdirAll(layer, 0755); err != nil { return err } // If layerData is not nil, unpack it into the new layer if layerData != nil { start := time.Now() utils.Debugf("Start untar layer") if err := Untar(layerData, layer); err != nil { return err } utils.Debugf("Untar time: %vs\n", time.Now().Sub(start).Seconds()) } // If raw json is provided, then use it if jsonData != nil { return ioutil.WriteFile(jsonPath(root), jsonData, 0600) } else { // Otherwise, unmarshal the image jsonData, err := json.Marshal(img) if err != nil { return err } if err := ioutil.WriteFile(jsonPath(root), jsonData, 0600); err != nil { return err } } return StoreSize(img, root) } func StoreSize(img *Image, root string) error { layer := layerPath(root) var totalSize int64 = 0 filepath.Walk(layer, func(path string, fileInfo os.FileInfo, err error) error { totalSize += fileInfo.Size() return nil }) img.Size = totalSize if err := ioutil.WriteFile(path.Join(root, "layersize"), []byte(strconv.Itoa(int(totalSize))), 0600); err != nil { return nil } return nil } func layerPath(root string) string { return path.Join(root, "layer") } func jsonPath(root string) string { return path.Join(root, "json") } func MountAUFS(ro []string, rw string, target string) error { // FIXME: Now mount the layers rwBranch := fmt.Sprintf("%v=rw", rw) roBranches := "" for _, layer := range ro { roBranches += fmt.Sprintf("%v=ro+wh:", layer) } branches := fmt.Sprintf("br:%v:%v", rwBranch, roBranches) branches += ",xino=/dev/shm/aufs.xino" //if error, try to load aufs kernel module if err := mount("none", target, "aufs", 0, branches); err != nil { log.Printf("Kernel does not support AUFS, trying to load the AUFS module with modprobe...") if err := exec.Command("modprobe", "aufs").Run(); err != nil { return fmt.Errorf("Unable to load the AUFS module") } log.Printf("...module loaded.") if err := mount("none", target, "aufs", 0, branches); err != nil { return fmt.Errorf("Unable to mount using aufs") } } return nil } // TarLayer returns a tar archive of the image's filesystem layer. func (image *Image) TarLayer(compression Compression) (Archive, error) { layerPath, err := image.layer() if err != nil { return nil, err } return Tar(layerPath, compression) } func (image *Image) Mount(root, rw string) error { if mounted, err := Mounted(root); err != nil { return err } else if mounted { return fmt.Errorf("%s is already mounted", root) } layers, err := image.layers() if err != nil { return err } // Create the target directories if they don't exist if err := os.Mkdir(root, 0755); err != nil && !os.IsExist(err) { return err } if err := os.Mkdir(rw, 0755); err != nil && !os.IsExist(err) { return err } if err := MountAUFS(layers, rw, root); err != nil { return err } return nil } func (image *Image) Changes(rw string) ([]Change, error) { layers, err := image.layers() if err != nil { return nil, err } return Changes(layers, rw) } func (image *Image) ShortID() string { return utils.TruncateID(image.ID) } func ValidateID(id string) error { if id == "" { return fmt.Errorf("Image id can't be empty") } if strings.Contains(id, ":") { return fmt.Errorf("Invalid character in image id: ':'") } return nil } func GenerateID() string { id := make([]byte, 32) _, err := io.ReadFull(rand.Reader, id) if err != nil { panic(err) // This shouldn't happen } return hex.EncodeToString(id) } // Image includes convenience proxy functions to its graph // These functions will return an error if the image is not registered // (ie. if image.graph == nil) func (img *Image) History() ([]*Image, error) { var parents []*Image if err := img.WalkHistory( func(img *Image) error { parents = append(parents, img) return nil }, ); err != nil { return nil, err } return parents, nil } // layers returns all the filesystem layers needed to mount an image // FIXME: @shykes refactor this function with the new error handling // (I'll do it if I have time tonight, I focus on the rest) func (img *Image) layers() ([]string, error) { var list []string var e error if err := img.WalkHistory( func(img *Image) (err error) { if layer, err := img.layer(); err != nil { e = err } else if layer != "" { list = append(list, layer) } return err }, ); err != nil { return nil, err } else if e != nil { // Did an error occur inside the handler? return nil, e } if len(list) == 0 { return nil, fmt.Errorf("No layer found for image %s\n", img.ID) } // Inject the dockerinit layer (empty place-holder for mount-binding dockerinit) if dockerinitLayer, err := img.getDockerInitLayer(); err != nil { return nil, err } else { list = append([]string{dockerinitLayer}, list...) } return list, nil } func (img *Image) WalkHistory(handler func(*Image) error) (err error) { currentImg := img for currentImg != nil { if handler != nil { if err := handler(currentImg); err != nil { return err } } currentImg, err = currentImg.GetParent() if err != nil { return fmt.Errorf("Error while getting parent image: %v", err) } } return nil } func (img *Image) GetParent() (*Image, error) { if img.Parent == "" { return nil, nil } if img.graph == nil { return nil, fmt.Errorf("Can't lookup parent of unregistered image") } return img.graph.Get(img.Parent) } func (img *Image) getDockerInitLayer() (string, error) { if img.graph == nil { return "", fmt.Errorf("Can't lookup dockerinit layer of unregistered image") } return img.graph.getDockerInitLayer() } func (img *Image) root() (string, error) { if img.graph == nil { return "", fmt.Errorf("Can't lookup root of unregistered image") } return img.graph.imageRoot(img.ID), nil } // Return the path of an image's layer func (img *Image) layer() (string, error) { root, err := img.root() if err != nil { return "", err } return layerPath(root), nil } func (img *Image) getParentsSize(size int64) int64 { parentImage, err := img.GetParent() if err != nil || parentImage == nil { return size } size += parentImage.Size return parentImage.getParentsSize(size) } // Build an Image object from raw json data func NewImgJSON(src []byte) (*Image, error) { ret := &Image{} utils.Debugf("Json string: {%s}\n", src) // FIXME: Is there a cleaner way to "purify" the input json? if err := json.Unmarshal(src, ret); err != nil { return nil, err } return ret, nil }
image.go
1
https://github.com/moby/moby/commit/e368c8bb01b3c52c8e4c334c3a7f32556af9d632
[ 0.9947356581687927, 0.05348462983965874, 0.00016550846339669079, 0.00017057699733413756, 0.21534688770771027 ]
{ "id": 0, "code_window": [ "func (container *Container) Mount() error {\n", "\timage, err := container.GetImage()\n", "\tif err != nil {\n", "\t\treturn err\n", "\t}\n", "\treturn image.Mount(container.RootfsPath(), container.rwPath())\n", "}\n", "\n", "func (container *Container) Changes() ([]Change, error) {\n", "\timage, err := container.GetImage()\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\treturn image.Mount(container.runtime, container.RootfsPath(), container.rwPath(), container.ID)\n" ], "file_path": "container.go", "type": "replace", "edit_start_line_idx": 1000 }
// 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 ipv6_test import ( "code.google.com/p/go.net/ipv6" "net" "os" "runtime" "testing" ) var packetConnMulticastSocketOptionTests = []struct { net, proto, addr string gaddr net.Addr }{ {"udp6", "", "[ff02::]:0", &net.UDPAddr{IP: net.ParseIP("ff02::114")}}, // see RFC 4727 {"ip6", ":ipv6-icmp", "::", &net.IPAddr{IP: net.ParseIP("ff02::114")}}, // see RFC 4727 } func TestPacketConnMulticastSocketOptions(t *testing.T) { switch runtime.GOOS { case "plan9", "windows": t.Skipf("not supported on %q", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } ifi := loopbackInterface() if ifi == nil { t.Skipf("not available on %q", runtime.GOOS) } for _, tt := range packetConnMulticastSocketOptionTests { if tt.net == "ip6" && os.Getuid() != 0 { t.Skip("must be root") } c, err := net.ListenPacket(tt.net+tt.proto, tt.addr) if err != nil { t.Fatalf("net.ListenPacket failed: %v", err) } defer c.Close() p := ipv6.NewPacketConn(c) hoplim := 255 if err := p.SetMulticastHopLimit(hoplim); err != nil { t.Fatalf("ipv6.PacketConn.SetMulticastHopLimit failed: %v", err) } if v, err := p.MulticastHopLimit(); err != nil { t.Fatalf("ipv6.PacketConn.MulticastHopLimit failed: %v", err) } else if v != hoplim { t.Fatalf("got unexpected multicast hop limit %v; expected %v", v, hoplim) } for _, toggle := range []bool{true, false} { if err := p.SetMulticastLoopback(toggle); err != nil { t.Fatalf("ipv6.PacketConn.SetMulticastLoopback failed: %v", err) } if v, err := p.MulticastLoopback(); err != nil { t.Fatalf("ipv6.PacketConn.MulticastLoopback failed: %v", err) } else if v != toggle { t.Fatalf("got unexpected multicast loopback %v; expected %v", v, toggle) } } if err := p.JoinGroup(ifi, tt.gaddr); err != nil { t.Fatalf("ipv6.PacketConn.JoinGroup(%v, %v) failed: %v", ifi, tt.gaddr, err) } if err := p.LeaveGroup(ifi, tt.gaddr); err != nil { t.Fatalf("ipv6.PacketConn.LeaveGroup(%v, %v) failed: %v", ifi, tt.gaddr, err) } } }
vendor/src/code.google.com/p/go.net/ipv6/multicastsockopt_test.go
0
https://github.com/moby/moby/commit/e368c8bb01b3c52c8e4c334c3a7f32556af9d632
[ 0.0001905660901684314, 0.00017359419143758714, 0.00016675848746672273, 0.00017156990361399949, 0.000006923960427229758 ]
{ "id": 0, "code_window": [ "func (container *Container) Mount() error {\n", "\timage, err := container.GetImage()\n", "\tif err != nil {\n", "\t\treturn err\n", "\t}\n", "\treturn image.Mount(container.RootfsPath(), container.rwPath())\n", "}\n", "\n", "func (container *Container) Changes() ([]Change, error) {\n", "\timage, err := container.GetImage()\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\treturn image.Mount(container.runtime, container.RootfsPath(), container.rwPath(), container.ID)\n" ], "file_path": "container.go", "type": "replace", "edit_start_line_idx": 1000 }
package pty import ( "errors" "os" "syscall" "unsafe" ) // see ioccom.h const sys_IOCPARM_MASK = 0x1fff func open() (pty, tty *os.File, err error) { p, err := os.OpenFile("/dev/ptmx", os.O_RDWR, 0) if err != nil { return nil, nil, err } sname, err := ptsname(p) if err != nil { return nil, nil, err } err = grantpt(p) if err != nil { return nil, nil, err } err = unlockpt(p) if err != nil { return nil, nil, err } t, err := os.OpenFile(sname, os.O_RDWR, 0) if err != nil { return nil, nil, err } return p, t, nil } func ptsname(f *os.File) (string, error) { var n [(syscall.TIOCPTYGNAME >> 16) & sys_IOCPARM_MASK]byte ioctl(f.Fd(), syscall.TIOCPTYGNAME, uintptr(unsafe.Pointer(&n))) for i, c := range n { if c == 0 { return string(n[:i]), nil } } return "", errors.New("TIOCPTYGNAME string not NUL-terminated") } func grantpt(f *os.File) error { var u int return ioctl(f.Fd(), syscall.TIOCPTYGRANT, uintptr(unsafe.Pointer(&u))) } func unlockpt(f *os.File) error { var u int return ioctl(f.Fd(), syscall.TIOCPTYUNLK, uintptr(unsafe.Pointer(&u))) } func ioctl(fd, cmd, ptr uintptr) error { _, _, e := syscall.Syscall(syscall.SYS_IOCTL, fd, cmd, ptr) if e != 0 { return syscall.ENOTTY } return nil }
vendor/src/github.com/kr/pty/pty_darwin.go
0
https://github.com/moby/moby/commit/e368c8bb01b3c52c8e4c334c3a7f32556af9d632
[ 0.00019318278646096587, 0.00017106952145695686, 0.00016326858894899487, 0.00016798269643913954, 0.000009519344530417584 ]
{ "id": 0, "code_window": [ "func (container *Container) Mount() error {\n", "\timage, err := container.GetImage()\n", "\tif err != nil {\n", "\t\treturn err\n", "\t}\n", "\treturn image.Mount(container.RootfsPath(), container.rwPath())\n", "}\n", "\n", "func (container *Container) Changes() ([]Change, error) {\n", "\timage, err := container.GetImage()\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\treturn image.Mount(container.runtime, container.RootfsPath(), container.rwPath(), container.ID)\n" ], "file_path": "container.go", "type": "replace", "edit_start_line_idx": 1000 }
# Docker: what's next? This document is a high-level overview of where we want to take Docker next. It is a curated selection of planned improvements which are either important, difficult, or both. For a more complete view of planned and requested improvements, see [the Github issues](https://github.com/dotcloud/docker/issues). Tu suggest changes to the roadmap, including additions, please write the change as if it were already in effect, and make a pull request. ## Container wiring and service discovery In its current version, docker doesn’t make it very easy to manipulate multiple containers as a cohesive group (ie. orchestration), and it doesn’t make it seamless for containers to connect to each other as network services (ie. wiring). To achieve wiring and orchestration with docker today, you need to write glue scripts yourself, or use one several companion tools available, like Orchestra, Shipper, Deis, Pipeworks, etc. We want the Docker API to support orchestration and wiring natively, so that these tools can cleanly and seamlessly integrate into the Docker user experience, and remain interoperable with each other. ## Better integration with process supervisors For docker to be fully usable in production, it needs to cleanly integrate with the host machine’s process supervisor of choice. Whether it’s sysV-init, upstart, systemd, runit or supervisord, we want to make sure docker plays nice with your existing system. This will be a major focus of the 0.7 release. ## Plugin API We want Docker to run everywhere, and to integrate with every devops tool. Those are ambitious goals, and the only way to reach them is with the Docker community. For the community to participate fully, we need an API which allows Docker to be deeply and easily customized. We are working on a plugin API which will make Docker very, very customization-friendly. We believe it will facilitate the integrations listed above – and many more we didn’t even think about. ## Broader kernel support Our goal is to make Docker run everywhere, but currently Docker requires Linux version 3.8 or higher with lxc and aufs support. If you’re deploying new machines for the purpose of running Docker, this is a fairly easy requirement to meet. However, if you’re adding Docker to an existing deployment, you may not have the flexibility to update and patch the kernel. Expanding Docker’s kernel support is a priority. This includes running on older kernel versions, but also on kernels with no AUFS support, or with incomplete lxc capabilities. ## Cross-architecture support Our goal is to make Docker run everywhere. However currently Docker only runs on x86_64 systems. We plan on expanding architecture support, so that Docker containers can be created and used on more architectures. ## Production-ready Docker is still beta software, and not suited for production. We are working hard to get there, and we are confident that it will be possible within a few months. Stay tuned for a more detailed roadmap soon.
hack/ROADMAP.md
0
https://github.com/moby/moby/commit/e368c8bb01b3c52c8e4c334c3a7f32556af9d632
[ 0.0001902621443150565, 0.0001717723935144022, 0.00016300212882924825, 0.0001663022703723982, 0.000010137748176930472 ]
{ "id": 1, "code_window": [ "\t\t}\n", "\t}\n", "}\n", "\n", "func TestMount(t *testing.T) {\n", "\tgraph := tempGraph(t)\n", "\tdefer os.RemoveAll(graph.Root)\n", "\tarchive, err := fakeTar()\n", "\tif err != nil {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\truntime := mkRuntime(t)\n", "\tdefer nuke(runtime)\n", "\n" ], "file_path": "graph_test.go", "type": "add", "edit_start_line_idx": 123 }
package docker import ( "archive/tar" "bytes" "errors" "github.com/dotcloud/docker/utils" "io" "io/ioutil" "os" "path" "testing" "time" ) func TestInit(t *testing.T) { graph := tempGraph(t) defer os.RemoveAll(graph.Root) // Root should exist if _, err := os.Stat(graph.Root); err != nil { t.Fatal(err) } // Map() should be empty if l, err := graph.Map(); err != nil { t.Fatal(err) } else if len(l) != 0 { t.Fatalf("len(Map()) should return %d, not %d", 0, len(l)) } } // Test that Register can be interrupted cleanly without side effects func TestInterruptedRegister(t *testing.T) { graph := tempGraph(t) defer os.RemoveAll(graph.Root) badArchive, w := io.Pipe() // Use a pipe reader as a fake archive which never yields data image := &Image{ ID: GenerateID(), Comment: "testing", Created: time.Now(), } go graph.Register(nil, badArchive, image) time.Sleep(200 * time.Millisecond) w.CloseWithError(errors.New("But I'm not a tarball!")) // (Nobody's perfect, darling) if _, err := graph.Get(image.ID); err == nil { t.Fatal("Image should not exist after Register is interrupted") } // Registering the same image again should succeed if the first register was interrupted goodArchive, err := fakeTar() if err != nil { t.Fatal(err) } if err := graph.Register(nil, goodArchive, image); err != nil { t.Fatal(err) } } // FIXME: Do more extensive tests (ex: create multiple, delete, recreate; // create multiple, check the amount of images and paths, etc..) func TestGraphCreate(t *testing.T) { graph := tempGraph(t) defer os.RemoveAll(graph.Root) archive, err := fakeTar() if err != nil { t.Fatal(err) } image, err := graph.Create(archive, nil, "Testing", "", nil) if err != nil { t.Fatal(err) } if err := ValidateID(image.ID); err != nil { t.Fatal(err) } if image.Comment != "Testing" { t.Fatalf("Wrong comment: should be '%s', not '%s'", "Testing", image.Comment) } if image.DockerVersion != VERSION { t.Fatalf("Wrong docker_version: should be '%s', not '%s'", VERSION, image.DockerVersion) } images, err := graph.Map() if err != nil { t.Fatal(err) } else if l := len(images); l != 1 { t.Fatalf("Wrong number of images. Should be %d, not %d", 1, l) } if images[image.ID] == nil { t.Fatalf("Could not find image with id %s", image.ID) } } func TestRegister(t *testing.T) { graph := tempGraph(t) defer os.RemoveAll(graph.Root) archive, err := fakeTar() if err != nil { t.Fatal(err) } image := &Image{ ID: GenerateID(), Comment: "testing", Created: time.Now(), } err = graph.Register(nil, archive, image) if err != nil { t.Fatal(err) } if images, err := graph.Map(); err != nil { t.Fatal(err) } else if l := len(images); l != 1 { t.Fatalf("Wrong number of images. Should be %d, not %d", 1, l) } if resultImg, err := graph.Get(image.ID); err != nil { t.Fatal(err) } else { if resultImg.ID != image.ID { t.Fatalf("Wrong image ID. Should be '%s', not '%s'", image.ID, resultImg.ID) } if resultImg.Comment != image.Comment { t.Fatalf("Wrong image comment. Should be '%s', not '%s'", image.Comment, resultImg.Comment) } } } func TestMount(t *testing.T) { graph := tempGraph(t) defer os.RemoveAll(graph.Root) archive, err := fakeTar() if err != nil { t.Fatal(err) } image, err := graph.Create(archive, nil, "Testing", "", nil) if err != nil { t.Fatal(err) } tmp, err := ioutil.TempDir("", "docker-test-graph-mount-") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) rootfs := path.Join(tmp, "rootfs") if err := os.MkdirAll(rootfs, 0700); err != nil { t.Fatal(err) } rw := path.Join(tmp, "rw") if err := os.MkdirAll(rw, 0700); err != nil { t.Fatal(err) } if err := image.Mount(rootfs, rw); err != nil { t.Fatal(err) } // FIXME: test for mount contents defer func() { if err := Unmount(rootfs); err != nil { t.Error(err) } }() } // Test that an image can be deleted by its shorthand prefix func TestDeletePrefix(t *testing.T) { graph := tempGraph(t) defer os.RemoveAll(graph.Root) img := createTestImage(graph, t) if err := graph.Delete(utils.TruncateID(img.ID)); err != nil { t.Fatal(err) } assertNImages(graph, t, 0) } func createTestImage(graph *Graph, t *testing.T) *Image { archive, err := fakeTar() if err != nil { t.Fatal(err) } img, err := graph.Create(archive, nil, "Test image", "", nil) if err != nil { t.Fatal(err) } return img } func TestDelete(t *testing.T) { graph := tempGraph(t) defer os.RemoveAll(graph.Root) archive, err := fakeTar() if err != nil { t.Fatal(err) } assertNImages(graph, t, 0) img, err := graph.Create(archive, nil, "Bla bla", "", nil) if err != nil { t.Fatal(err) } assertNImages(graph, t, 1) if err := graph.Delete(img.ID); err != nil { t.Fatal(err) } assertNImages(graph, t, 0) archive, err = fakeTar() if err != nil { t.Fatal(err) } // Test 2 create (same name) / 1 delete img1, err := graph.Create(archive, nil, "Testing", "", nil) if err != nil { t.Fatal(err) } archive, err = fakeTar() if err != nil { t.Fatal(err) } if _, err = graph.Create(archive, nil, "Testing", "", nil); err != nil { t.Fatal(err) } assertNImages(graph, t, 2) if err := graph.Delete(img1.ID); err != nil { t.Fatal(err) } assertNImages(graph, t, 1) // Test delete wrong name if err := graph.Delete("Not_foo"); err == nil { t.Fatalf("Deleting wrong ID should return an error") } assertNImages(graph, t, 1) archive, err = fakeTar() if err != nil { t.Fatal(err) } // Test delete twice (pull -> rm -> pull -> rm) if err := graph.Register(nil, archive, img1); err != nil { t.Fatal(err) } if err := graph.Delete(img1.ID); err != nil { t.Fatal(err) } assertNImages(graph, t, 1) } func TestByParent(t *testing.T) { archive1, _ := fakeTar() archive2, _ := fakeTar() archive3, _ := fakeTar() graph := tempGraph(t) defer os.RemoveAll(graph.Root) parentImage := &Image{ ID: GenerateID(), Comment: "parent", Created: time.Now(), Parent: "", } childImage1 := &Image{ ID: GenerateID(), Comment: "child1", Created: time.Now(), Parent: parentImage.ID, } childImage2 := &Image{ ID: GenerateID(), Comment: "child2", Created: time.Now(), Parent: parentImage.ID, } _ = graph.Register(nil, archive1, parentImage) _ = graph.Register(nil, archive2, childImage1) _ = graph.Register(nil, archive3, childImage2) byParent, err := graph.ByParent() if err != nil { t.Fatal(err) } numChildren := len(byParent[parentImage.ID]) if numChildren != 2 { t.Fatalf("Expected 2 children, found %d", numChildren) } } func assertNImages(graph *Graph, t *testing.T, n int) { if images, err := graph.Map(); err != nil { t.Fatal(err) } else if actualN := len(images); actualN != n { t.Fatalf("Expected %d images, found %d", n, actualN) } } /* * HELPER FUNCTIONS */ func tempGraph(t *testing.T) *Graph { tmp, err := ioutil.TempDir("", "docker-graph-") if err != nil { t.Fatal(err) } graph, err := NewGraph(tmp) if err != nil { t.Fatal(err) } return graph } func testArchive(t *testing.T) Archive { archive, err := fakeTar() if err != nil { t.Fatal(err) } return archive } func fakeTar() (io.Reader, error) { content := []byte("Hello world!\n") buf := new(bytes.Buffer) tw := tar.NewWriter(buf) for _, name := range []string{"/etc/postgres/postgres.conf", "/etc/passwd", "/var/log/postgres/postgres.conf"} { hdr := new(tar.Header) hdr.Size = int64(len(content)) hdr.Name = name if err := tw.WriteHeader(hdr); err != nil { return nil, err } tw.Write([]byte(content)) } tw.Close() return buf, nil }
graph_test.go
1
https://github.com/moby/moby/commit/e368c8bb01b3c52c8e4c334c3a7f32556af9d632
[ 0.9980251789093018, 0.680218517780304, 0.00016662639973219484, 0.9375990629196167, 0.41370993852615356 ]
{ "id": 1, "code_window": [ "\t\t}\n", "\t}\n", "}\n", "\n", "func TestMount(t *testing.T) {\n", "\tgraph := tempGraph(t)\n", "\tdefer os.RemoveAll(graph.Root)\n", "\tarchive, err := fakeTar()\n", "\tif err != nil {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\truntime := mkRuntime(t)\n", "\tdefer nuke(runtime)\n", "\n" ], "file_path": "graph_test.go", "type": "add", "edit_start_line_idx": 123 }
/*! * Bootstrap v2.3.0 * * Copyright 2012 Twitter, Inc * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Designed and built with all the love in the world @twitter by @mdo and @fat. */.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;line-height:0;content:""}.clearfix:after{clear:both}.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}audio,canvas,video{display:inline-block;*display:inline;*zoom:1}audio:not([controls]){display:none}html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}a:hover,a:active{outline:0}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{width:auto\9;height:auto;max-width:100%;vertical-align:middle;border:0;-ms-interpolation-mode:bicubic}#map_canvas img,.google-maps img{max-width:none}button,input,select,textarea{margin:0;font-size:100%;vertical-align:middle}button,input{*overflow:visible;line-height:normal}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}button,html input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button}label,select,button,input[type="button"],input[type="reset"],input[type="submit"],input[type="radio"],input[type="checkbox"]{cursor:pointer}input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type="search"]::-webkit-search-decoration,input[type="search"]::-webkit-search-cancel-button{-webkit-appearance:none}textarea{overflow:auto;vertical-align:top}@media print{*{color:#000!important;text-shadow:none!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}@page{margin:.5cm}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}}body{margin:0;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:20px;color:#333;background-color:#fff}a{color:#08c;text-decoration:none}a:hover,a:focus{color:#005580;text-decoration:underline}.img-rounded{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.img-polaroid{padding:4px;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);-webkit-box-shadow:0 1px 3px rgba(0,0,0,0.1);-moz-box-shadow:0 1px 3px rgba(0,0,0,0.1);box-shadow:0 1px 3px rgba(0,0,0,0.1)}.img-circle{-webkit-border-radius:500px;-moz-border-radius:500px;border-radius:500px}.row{margin-left:-20px;*zoom:1}.row:before,.row:after{display:table;line-height:0;content:""}.row:after{clear:both}[class*="span"]{float:left;min-height:1px;margin-left:20px}.container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px}.span12{width:940px}.span11{width:860px}.span10{width:780px}.span9{width:700px}.span8{width:620px}.span7{width:540px}.span6{width:460px}.span5{width:380px}.span4{width:300px}.span3{width:220px}.span2{width:140px}.span1{width:60px}.offset12{margin-left:980px}.offset11{margin-left:900px}.offset10{margin-left:820px}.offset9{margin-left:740px}.offset8{margin-left:660px}.offset7{margin-left:580px}.offset6{margin-left:500px}.offset5{margin-left:420px}.offset4{margin-left:340px}.offset3{margin-left:260px}.offset2{margin-left:180px}.offset1{margin-left:100px}.row-fluid{width:100%;*zoom:1}.row-fluid:before,.row-fluid:after{display:table;line-height:0;content:""}.row-fluid:after{clear:both}.row-fluid [class*="span"]{display:block;float:left;width:100%;min-height:30px;margin-left:2.127659574468085%;*margin-left:2.074468085106383%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.row-fluid [class*="span"]:first-child{margin-left:0}.row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.127659574468085%}.row-fluid .span12{width:100%;*width:99.94680851063829%}.row-fluid .span11{width:91.48936170212765%;*width:91.43617021276594%}.row-fluid .span10{width:82.97872340425532%;*width:82.92553191489361%}.row-fluid .span9{width:74.46808510638297%;*width:74.41489361702126%}.row-fluid .span8{width:65.95744680851064%;*width:65.90425531914893%}.row-fluid .span7{width:57.44680851063829%;*width:57.39361702127659%}.row-fluid .span6{width:48.93617021276595%;*width:48.88297872340425%}.row-fluid .span5{width:40.42553191489362%;*width:40.37234042553192%}.row-fluid .span4{width:31.914893617021278%;*width:31.861702127659576%}.row-fluid .span3{width:23.404255319148934%;*width:23.351063829787233%}.row-fluid .span2{width:14.893617021276595%;*width:14.840425531914894%}.row-fluid .span1{width:6.382978723404255%;*width:6.329787234042553%}.row-fluid .offset12{margin-left:104.25531914893617%;*margin-left:104.14893617021275%}.row-fluid .offset12:first-child{margin-left:102.12765957446808%;*margin-left:102.02127659574467%}.row-fluid .offset11{margin-left:95.74468085106382%;*margin-left:95.6382978723404%}.row-fluid .offset11:first-child{margin-left:93.61702127659574%;*margin-left:93.51063829787232%}.row-fluid .offset10{margin-left:87.23404255319149%;*margin-left:87.12765957446807%}.row-fluid .offset10:first-child{margin-left:85.1063829787234%;*margin-left:84.99999999999999%}.row-fluid .offset9{margin-left:78.72340425531914%;*margin-left:78.61702127659572%}.row-fluid .offset9:first-child{margin-left:76.59574468085106%;*margin-left:76.48936170212764%}.row-fluid .offset8{margin-left:70.2127659574468%;*margin-left:70.10638297872339%}.row-fluid .offset8:first-child{margin-left:68.08510638297872%;*margin-left:67.9787234042553%}.row-fluid .offset7{margin-left:61.70212765957446%;*margin-left:61.59574468085106%}.row-fluid .offset7:first-child{margin-left:59.574468085106375%;*margin-left:59.46808510638297%}.row-fluid .offset6{margin-left:53.191489361702125%;*margin-left:53.085106382978715%}.row-fluid .offset6:first-child{margin-left:51.063829787234035%;*margin-left:50.95744680851063%}.row-fluid .offset5{margin-left:44.68085106382979%;*margin-left:44.57446808510638%}.row-fluid .offset5:first-child{margin-left:42.5531914893617%;*margin-left:42.4468085106383%}.row-fluid .offset4{margin-left:36.170212765957444%;*margin-left:36.06382978723405%}.row-fluid .offset4:first-child{margin-left:34.04255319148936%;*margin-left:33.93617021276596%}.row-fluid .offset3{margin-left:27.659574468085104%;*margin-left:27.5531914893617%}.row-fluid .offset3:first-child{margin-left:25.53191489361702%;*margin-left:25.425531914893618%}.row-fluid .offset2{margin-left:19.148936170212764%;*margin-left:19.04255319148936%}.row-fluid .offset2:first-child{margin-left:17.02127659574468%;*margin-left:16.914893617021278%}.row-fluid .offset1{margin-left:10.638297872340425%;*margin-left:10.53191489361702%}.row-fluid .offset1:first-child{margin-left:8.51063829787234%;*margin-left:8.404255319148938%}[class*="span"].hide,.row-fluid [class*="span"].hide{display:none}[class*="span"].pull-right,.row-fluid [class*="span"].pull-right{float:right}.container{margin-right:auto;margin-left:auto;*zoom:1}.container:before,.container:after{display:table;line-height:0;content:""}.container:after{clear:both}.container-fluid{padding-right:20px;padding-left:20px;*zoom:1}.container-fluid:before,.container-fluid:after{display:table;line-height:0;content:""}.container-fluid:after{clear:both}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:21px;font-weight:200;line-height:30px}small{font-size:85%}strong{font-weight:bold}em{font-style:italic}cite{font-style:normal}.muted{color:#999}a.muted:hover,a.muted:focus{color:#808080}.text-warning{color:#c09853}a.text-warning:hover,a.text-warning:focus{color:#a47e3c}.text-error{color:#b94a48}a.text-error:hover,a.text-error:focus{color:#953b39}.text-info{color:#3a87ad}a.text-info:hover,a.text-info:focus{color:#2d6987}.text-success{color:#468847}a.text-success:hover,a.text-success:focus{color:#356635}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}h1,h2,h3,h4,h5,h6{margin:10px 0;font-family:inherit;font-weight:bold;line-height:20px;color:inherit;text-rendering:optimizelegibility}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small{font-weight:normal;line-height:1;color:#999}h1,h2,h3{line-height:40px}h1{font-size:38.5px}h2{font-size:31.5px}h3{font-size:24.5px}h4{font-size:17.5px}h5{font-size:14px}h6{font-size:11.9px}h1 small{font-size:24.5px}h2 small{font-size:17.5px}h3 small{font-size:14px}h4 small{font-size:14px}.page-header{padding-bottom:9px;margin:20px 0 30px;border-bottom:1px solid #eee}ul,ol{padding:0;margin:0 0 10px 25px}ul ul,ul ol,ol ol,ol ul{margin-bottom:0}li{line-height:20px}ul.unstyled,ol.unstyled{margin-left:0;list-style:none}ul.inline,ol.inline{margin-left:0;list-style:none}ul.inline>li,ol.inline>li{display:inline-block;*display:inline;padding-right:5px;padding-left:5px;*zoom:1}dl{margin-bottom:20px}dt,dd{line-height:20px}dt{font-weight:bold}dd{margin-left:10px}.dl-horizontal{*zoom:1}.dl-horizontal:before,.dl-horizontal:after{display:table;line-height:0;content:""}.dl-horizontal:after{clear:both}.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}hr{margin:20px 0;border:0;border-top:1px solid #eee;border-bottom:1px solid #fff}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999}abbr.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:0 0 0 15px;margin:0 0 20px;border-left:5px solid #eee}blockquote p{margin-bottom:0;font-size:17.5px;font-weight:300;line-height:1.25}blockquote small{display:block;line-height:20px;color:#999}blockquote small:before{content:'\2014 \00A0'}blockquote.pull-right{float:right;padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0}blockquote.pull-right p,blockquote.pull-right small{text-align:right}blockquote.pull-right small:before{content:''}blockquote.pull-right small:after{content:'\00A0 \2014'}q:before,q:after,blockquote:before,blockquote:after{content:""}address{display:block;margin-bottom:20px;font-style:normal;line-height:20px}code,pre{padding:0 3px 2px;font-family:Monaco,Menlo,Consolas,"Courier New",monospace;font-size:12px;color:#333;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}code{padding:2px 4px;color:#d14;white-space:nowrap;background-color:#f7f7f9;border:1px solid #e1e1e8}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:20px;word-break:break-all;word-wrap:break-word;white-space:pre;white-space:pre-wrap;background-color:#f5f5f5;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.15);-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}pre.prettyprint{margin-bottom:20px}pre code{padding:0;color:inherit;white-space:pre;white-space:pre-wrap;background-color:transparent;border:0}.pre-scrollable{max-height:340px;overflow-y:scroll}form{margin:0 0 20px}fieldset{padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:40px;color:#333;border:0;border-bottom:1px solid #e5e5e5}legend small{font-size:15px;color:#999}label,input,button,select,textarea{font-size:14px;font-weight:normal;line-height:20px}input,button,select,textarea{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif}label{display:block;margin-bottom:5px}select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px 6px;margin-bottom:10px;font-size:14px;line-height:20px;color:#555;vertical-align:middle;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}input,textarea,.uneditable-input{width:206px}textarea{height:auto}textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#fff;border:1px solid #ccc;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-webkit-transition:border linear .2s,box-shadow linear .2s;-moz-transition:border linear .2s,box-shadow linear .2s;-o-transition:border linear .2s,box-shadow linear .2s;transition:border linear .2s,box-shadow linear .2s}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82,168,236,0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}input[type="radio"],input[type="checkbox"]{margin:4px 0 0;margin-top:1px \9;*margin-top:0;line-height:normal}input[type="file"],input[type="image"],input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto}select,input[type="file"]{height:30px;*margin-top:4px;line-height:30px}select{width:220px;background-color:#fff;border:1px solid #ccc}select[multiple],select[size]{height:auto}select:focus,input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.uneditable-input,.uneditable-textarea{color:#999;cursor:not-allowed;background-color:#fcfcfc;border-color:#ccc;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.025);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.025);box-shadow:inset 0 1px 2px rgba(0,0,0,0.025)}.uneditable-input{overflow:hidden;white-space:nowrap}.uneditable-textarea{width:auto;height:auto}input:-moz-placeholder,textarea:-moz-placeholder{color:#999}input:-ms-input-placeholder,textarea:-ms-input-placeholder{color:#999}input::-webkit-input-placeholder,textarea::-webkit-input-placeholder{color:#999}.radio,.checkbox{min-height:20px;padding-left:20px}.radio input[type="radio"],.checkbox input[type="checkbox"]{float:left;margin-left:-20px}.controls>.radio:first-child,.controls>.checkbox:first-child{padding-top:5px}.radio.inline,.checkbox.inline{display:inline-block;padding-top:5px;margin-bottom:0;vertical-align:middle}.radio.inline+.radio.inline,.checkbox.inline+.checkbox.inline{margin-left:10px}.input-mini{width:60px}.input-small{width:90px}.input-medium{width:150px}.input-large{width:210px}.input-xlarge{width:270px}.input-xxlarge{width:530px}input[class*="span"],select[class*="span"],textarea[class*="span"],.uneditable-input[class*="span"],.row-fluid input[class*="span"],.row-fluid select[class*="span"],.row-fluid textarea[class*="span"],.row-fluid .uneditable-input[class*="span"]{float:none;margin-left:0}.input-append input[class*="span"],.input-append .uneditable-input[class*="span"],.input-prepend input[class*="span"],.input-prepend .uneditable-input[class*="span"],.row-fluid input[class*="span"],.row-fluid select[class*="span"],.row-fluid textarea[class*="span"],.row-fluid .uneditable-input[class*="span"],.row-fluid .input-prepend [class*="span"],.row-fluid .input-append [class*="span"]{display:inline-block}input,textarea,.uneditable-input{margin-left:0}.controls-row [class*="span"]+[class*="span"]{margin-left:20px}input.span12,textarea.span12,.uneditable-input.span12{width:926px}input.span11,textarea.span11,.uneditable-input.span11{width:846px}input.span10,textarea.span10,.uneditable-input.span10{width:766px}input.span9,textarea.span9,.uneditable-input.span9{width:686px}input.span8,textarea.span8,.uneditable-input.span8{width:606px}input.span7,textarea.span7,.uneditable-input.span7{width:526px}input.span6,textarea.span6,.uneditable-input.span6{width:446px}input.span5,textarea.span5,.uneditable-input.span5{width:366px}input.span4,textarea.span4,.uneditable-input.span4{width:286px}input.span3,textarea.span3,.uneditable-input.span3{width:206px}input.span2,textarea.span2,.uneditable-input.span2{width:126px}input.span1,textarea.span1,.uneditable-input.span1{width:46px}.controls-row{*zoom:1}.controls-row:before,.controls-row:after{display:table;line-height:0;content:""}.controls-row:after{clear:both}.controls-row [class*="span"],.row-fluid .controls-row [class*="span"]{float:left}.controls-row .checkbox[class*="span"],.controls-row .radio[class*="span"]{padding-top:5px}input[disabled],select[disabled],textarea[disabled],input[readonly],select[readonly],textarea[readonly]{cursor:not-allowed;background-color:#eee}input[type="radio"][disabled],input[type="checkbox"][disabled],input[type="radio"][readonly],input[type="checkbox"][readonly]{background-color:transparent}.control-group.warning .control-label,.control-group.warning .help-block,.control-group.warning .help-inline{color:#c09853}.control-group.warning .checkbox,.control-group.warning .radio,.control-group.warning input,.control-group.warning select,.control-group.warning textarea{color:#c09853}.control-group.warning input,.control-group.warning select,.control-group.warning textarea{border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.warning input:focus,.control-group.warning select:focus,.control-group.warning textarea:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e}.control-group.warning .input-prepend .add-on,.control-group.warning .input-append .add-on{color:#c09853;background-color:#fcf8e3;border-color:#c09853}.control-group.error .control-label,.control-group.error .help-block,.control-group.error .help-inline{color:#b94a48}.control-group.error .checkbox,.control-group.error .radio,.control-group.error input,.control-group.error select,.control-group.error textarea{color:#b94a48}.control-group.error input,.control-group.error select,.control-group.error textarea{border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.error input:focus,.control-group.error select:focus,.control-group.error textarea:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392}.control-group.error .input-prepend .add-on,.control-group.error .input-append .add-on{color:#b94a48;background-color:#f2dede;border-color:#b94a48}.control-group.success .control-label,.control-group.success .help-block,.control-group.success .help-inline{color:#468847}.control-group.success .checkbox,.control-group.success .radio,.control-group.success input,.control-group.success select,.control-group.success textarea{color:#468847}.control-group.success input,.control-group.success select,.control-group.success textarea{border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.success input:focus,.control-group.success select:focus,.control-group.success textarea:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b}.control-group.success .input-prepend .add-on,.control-group.success .input-append .add-on{color:#468847;background-color:#dff0d8;border-color:#468847}.control-group.info .control-label,.control-group.info .help-block,.control-group.info .help-inline{color:#3a87ad}.control-group.info .checkbox,.control-group.info .radio,.control-group.info input,.control-group.info select,.control-group.info textarea{color:#3a87ad}.control-group.info input,.control-group.info select,.control-group.info textarea{border-color:#3a87ad;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.info input:focus,.control-group.info select:focus,.control-group.info textarea:focus{border-color:#2d6987;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3}.control-group.info .input-prepend .add-on,.control-group.info .input-append .add-on{color:#3a87ad;background-color:#d9edf7;border-color:#3a87ad}input:focus:invalid,textarea:focus:invalid,select:focus:invalid{color:#b94a48;border-color:#ee5f5b}input:focus:invalid:focus,textarea:focus:invalid:focus,select:focus:invalid:focus{border-color:#e9322d;-webkit-box-shadow:0 0 6px #f8b9b7;-moz-box-shadow:0 0 6px #f8b9b7;box-shadow:0 0 6px #f8b9b7}.form-actions{padding:19px 20px 20px;margin-top:20px;margin-bottom:20px;background-color:#f5f5f5;border-top:1px solid #e5e5e5;*zoom:1}.form-actions:before,.form-actions:after{display:table;line-height:0;content:""}.form-actions:after{clear:both}.help-block,.help-inline{color:#595959}.help-block{display:block;margin-bottom:10px}.help-inline{display:inline-block;*display:inline;padding-left:5px;vertical-align:middle;*zoom:1}.input-append,.input-prepend{display:inline-block;margin-bottom:10px;font-size:0;white-space:nowrap;vertical-align:middle}.input-append input,.input-prepend input,.input-append select,.input-prepend select,.input-append .uneditable-input,.input-prepend .uneditable-input,.input-append .dropdown-menu,.input-prepend .dropdown-menu,.input-append .popover,.input-prepend .popover{font-size:14px}.input-append input,.input-prepend input,.input-append select,.input-prepend select,.input-append .uneditable-input,.input-prepend .uneditable-input{position:relative;margin-bottom:0;*margin-left:0;vertical-align:top;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-append input:focus,.input-prepend input:focus,.input-append select:focus,.input-prepend select:focus,.input-append .uneditable-input:focus,.input-prepend .uneditable-input:focus{z-index:2}.input-append .add-on,.input-prepend .add-on{display:inline-block;width:auto;height:20px;min-width:16px;padding:4px 5px;font-size:14px;font-weight:normal;line-height:20px;text-align:center;text-shadow:0 1px 0 #fff;background-color:#eee;border:1px solid #ccc}.input-append .add-on,.input-prepend .add-on,.input-append .btn,.input-prepend .btn,.input-append .btn-group>.dropdown-toggle,.input-prepend .btn-group>.dropdown-toggle{vertical-align:top;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.input-append .active,.input-prepend .active{background-color:#a9dba9;border-color:#46a546}.input-prepend .add-on,.input-prepend .btn{margin-right:-1px}.input-prepend .add-on:first-child,.input-prepend .btn:first-child{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.input-append input,.input-append select,.input-append .uneditable-input{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.input-append input+.btn-group .btn:last-child,.input-append select+.btn-group .btn:last-child,.input-append .uneditable-input+.btn-group .btn:last-child{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-append .add-on,.input-append .btn,.input-append .btn-group{margin-left:-1px}.input-append .add-on:last-child,.input-append .btn:last-child,.input-append .btn-group:last-child>.dropdown-toggle{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-prepend.input-append input,.input-prepend.input-append select,.input-prepend.input-append .uneditable-input{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.input-prepend.input-append input+.btn-group .btn,.input-prepend.input-append select+.btn-group .btn,.input-prepend.input-append .uneditable-input+.btn-group .btn{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-prepend.input-append .add-on:first-child,.input-prepend.input-append .btn:first-child{margin-right:-1px;-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.input-prepend.input-append .add-on:last-child,.input-prepend.input-append .btn:last-child{margin-left:-1px;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-prepend.input-append .btn-group:first-child{margin-left:0}input.search-query{padding-right:14px;padding-right:4px \9;padding-left:14px;padding-left:4px \9;margin-bottom:0;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.form-search .input-append .search-query,.form-search .input-prepend .search-query{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.form-search .input-append .search-query{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px}.form-search .input-append .btn{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0}.form-search .input-prepend .search-query{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0}.form-search .input-prepend .btn{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px}.form-search input,.form-inline input,.form-horizontal input,.form-search textarea,.form-inline textarea,.form-horizontal textarea,.form-search select,.form-inline select,.form-horizontal select,.form-search .help-inline,.form-inline .help-inline,.form-horizontal .help-inline,.form-search .uneditable-input,.form-inline .uneditable-input,.form-horizontal .uneditable-input,.form-search .input-prepend,.form-inline .input-prepend,.form-horizontal .input-prepend,.form-search .input-append,.form-inline .input-append,.form-horizontal .input-append{display:inline-block;*display:inline;margin-bottom:0;vertical-align:middle;*zoom:1}.form-search .hide,.form-inline .hide,.form-horizontal .hide{display:none}.form-search label,.form-inline label,.form-search .btn-group,.form-inline .btn-group{display:inline-block}.form-search .input-append,.form-inline .input-append,.form-search .input-prepend,.form-inline .input-prepend{margin-bottom:0}.form-search .radio,.form-search .checkbox,.form-inline .radio,.form-inline .checkbox{padding-left:0;margin-bottom:0;vertical-align:middle}.form-search .radio input[type="radio"],.form-search .checkbox input[type="checkbox"],.form-inline .radio input[type="radio"],.form-inline .checkbox input[type="checkbox"]{float:left;margin-right:3px;margin-left:0}.control-group{margin-bottom:10px}legend+.control-group{margin-top:20px;-webkit-margin-top-collapse:separate}.form-horizontal .control-group{margin-bottom:20px;*zoom:1}.form-horizontal .control-group:before,.form-horizontal .control-group:after{display:table;line-height:0;content:""}.form-horizontal .control-group:after{clear:both}.form-horizontal .control-label{float:left;width:160px;padding-top:5px;text-align:right}.form-horizontal .controls{*display:inline-block;*padding-left:20px;margin-left:180px;*margin-left:0}.form-horizontal .controls:first-child{*padding-left:180px}.form-horizontal .help-block{margin-bottom:0}.form-horizontal input+.help-block,.form-horizontal select+.help-block,.form-horizontal textarea+.help-block,.form-horizontal .uneditable-input+.help-block,.form-horizontal .input-prepend+.help-block,.form-horizontal .input-append+.help-block{margin-top:10px}.form-horizontal .form-actions{padding-left:180px}table{max-width:100%;background-color:transparent;border-collapse:collapse;border-spacing:0}.table{width:100%;margin-bottom:20px}.table th,.table td{padding:8px;line-height:20px;text-align:left;vertical-align:top;border-top:1px solid #ddd}.table th{font-weight:bold}.table thead th{vertical-align:bottom}.table caption+thead tr:first-child th,.table caption+thead tr:first-child td,.table colgroup+thead tr:first-child th,.table colgroup+thead tr:first-child td,.table thead:first-child tr:first-child th,.table thead:first-child tr:first-child td{border-top:0}.table tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed th,.table-condensed td{padding:4px 5px}.table-bordered{border:1px solid #ddd;border-collapse:separate;*border-collapse:collapse;border-left:0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.table-bordered th,.table-bordered td{border-left:1px solid #ddd}.table-bordered caption+thead tr:first-child th,.table-bordered caption+tbody tr:first-child th,.table-bordered caption+tbody tr:first-child td,.table-bordered colgroup+thead tr:first-child th,.table-bordered colgroup+tbody tr:first-child th,.table-bordered colgroup+tbody tr:first-child td,.table-bordered thead:first-child tr:first-child th,.table-bordered tbody:first-child tr:first-child th,.table-bordered tbody:first-child tr:first-child td{border-top:0}.table-bordered thead:first-child tr:first-child>th:first-child,.table-bordered tbody:first-child tr:first-child>td:first-child,.table-bordered tbody:first-child tr:first-child>th:first-child{-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topleft:4px}.table-bordered thead:first-child tr:first-child>th:last-child,.table-bordered tbody:first-child tr:first-child>td:last-child,.table-bordered tbody:first-child tr:first-child>th:last-child{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-moz-border-radius-topright:4px}.table-bordered thead:last-child tr:last-child>th:first-child,.table-bordered tbody:last-child tr:last-child>td:first-child,.table-bordered tbody:last-child tr:last-child>th:first-child,.table-bordered tfoot:last-child tr:last-child>td:first-child,.table-bordered tfoot:last-child tr:last-child>th:first-child{-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px}.table-bordered thead:last-child tr:last-child>th:last-child,.table-bordered tbody:last-child tr:last-child>td:last-child,.table-bordered tbody:last-child tr:last-child>th:last-child,.table-bordered tfoot:last-child tr:last-child>td:last-child,.table-bordered tfoot:last-child tr:last-child>th:last-child{-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px}.table-bordered tfoot+tbody:last-child tr:last-child td:first-child{-webkit-border-bottom-left-radius:0;border-bottom-left-radius:0;-moz-border-radius-bottomleft:0}.table-bordered tfoot+tbody:last-child tr:last-child td:last-child{-webkit-border-bottom-right-radius:0;border-bottom-right-radius:0;-moz-border-radius-bottomright:0}.table-bordered caption+thead tr:first-child th:first-child,.table-bordered caption+tbody tr:first-child td:first-child,.table-bordered colgroup+thead tr:first-child th:first-child,.table-bordered colgroup+tbody tr:first-child td:first-child{-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topleft:4px}.table-bordered caption+thead tr:first-child th:last-child,.table-bordered caption+tbody tr:first-child td:last-child,.table-bordered colgroup+thead tr:first-child th:last-child,.table-bordered colgroup+tbody tr:first-child td:last-child{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-moz-border-radius-topright:4px}.table-striped tbody>tr:nth-child(odd)>td,.table-striped tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.table-hover tbody tr:hover>td,.table-hover tbody tr:hover>th{background-color:#f5f5f5}table td[class*="span"],table th[class*="span"],.row-fluid table td[class*="span"],.row-fluid table th[class*="span"]{display:table-cell;float:none;margin-left:0}.table td.span1,.table th.span1{float:none;width:44px;margin-left:0}.table td.span2,.table th.span2{float:none;width:124px;margin-left:0}.table td.span3,.table th.span3{float:none;width:204px;margin-left:0}.table td.span4,.table th.span4{float:none;width:284px;margin-left:0}.table td.span5,.table th.span5{float:none;width:364px;margin-left:0}.table td.span6,.table th.span6{float:none;width:444px;margin-left:0}.table td.span7,.table th.span7{float:none;width:524px;margin-left:0}.table td.span8,.table th.span8{float:none;width:604px;margin-left:0}.table td.span9,.table th.span9{float:none;width:684px;margin-left:0}.table td.span10,.table th.span10{float:none;width:764px;margin-left:0}.table td.span11,.table th.span11{float:none;width:844px;margin-left:0}.table td.span12,.table th.span12{float:none;width:924px;margin-left:0}.table tbody tr.success>td{background-color:#dff0d8}.table tbody tr.error>td{background-color:#f2dede}.table tbody tr.warning>td{background-color:#fcf8e3}.table tbody tr.info>td{background-color:#d9edf7}.table-hover tbody tr.success:hover>td{background-color:#d0e9c6}.table-hover tbody tr.error:hover>td{background-color:#ebcccc}.table-hover tbody tr.warning:hover>td{background-color:#faf2cc}.table-hover tbody tr.info:hover>td{background-color:#c4e3f3}[class^="icon-"],[class*=" icon-"]{display:inline-block;width:14px;height:14px;margin-top:1px;*margin-right:.3em;line-height:14px;vertical-align:text-top;background-image:url("../img/glyphicons-halflings.png");background-position:14px 14px;background-repeat:no-repeat}.icon-white,.nav-pills>.active>a>[class^="icon-"],.nav-pills>.active>a>[class*=" icon-"],.nav-list>.active>a>[class^="icon-"],.nav-list>.active>a>[class*=" icon-"],.navbar-inverse .nav>.active>a>[class^="icon-"],.navbar-inverse .nav>.active>a>[class*=" icon-"],.dropdown-menu>li>a:hover>[class^="icon-"],.dropdown-menu>li>a:focus>[class^="icon-"],.dropdown-menu>li>a:hover>[class*=" icon-"],.dropdown-menu>li>a:focus>[class*=" icon-"],.dropdown-menu>.active>a>[class^="icon-"],.dropdown-menu>.active>a>[class*=" icon-"],.dropdown-submenu:hover>a>[class^="icon-"],.dropdown-submenu:focus>a>[class^="icon-"],.dropdown-submenu:hover>a>[class*=" icon-"],.dropdown-submenu:focus>a>[class*=" icon-"]{background-image:url("../img/glyphicons-halflings-white.png")}.icon-glass{background-position:0 0}.icon-music{background-position:-24px 0}.icon-search{background-position:-48px 0}.icon-envelope{background-position:-72px 0}.icon-heart{background-position:-96px 0}.icon-star{background-position:-120px 0}.icon-star-empty{background-position:-144px 0}.icon-user{background-position:-168px 0}.icon-film{background-position:-192px 0}.icon-th-large{background-position:-216px 0}.icon-th{background-position:-240px 0}.icon-th-list{background-position:-264px 0}.icon-ok{background-position:-288px 0}.icon-remove{background-position:-312px 0}.icon-zoom-in{background-position:-336px 0}.icon-zoom-out{background-position:-360px 0}.icon-off{background-position:-384px 0}.icon-signal{background-position:-408px 0}.icon-cog{background-position:-432px 0}.icon-trash{background-position:-456px 0}.icon-home{background-position:0 -24px}.icon-file{background-position:-24px -24px}.icon-time{background-position:-48px -24px}.icon-road{background-position:-72px -24px}.icon-download-alt{background-position:-96px -24px}.icon-download{background-position:-120px -24px}.icon-upload{background-position:-144px -24px}.icon-inbox{background-position:-168px -24px}.icon-play-circle{background-position:-192px -24px}.icon-repeat{background-position:-216px -24px}.icon-refresh{background-position:-240px -24px}.icon-list-alt{background-position:-264px -24px}.icon-lock{background-position:-287px -24px}.icon-flag{background-position:-312px -24px}.icon-headphones{background-position:-336px -24px}.icon-volume-off{background-position:-360px -24px}.icon-volume-down{background-position:-384px -24px}.icon-volume-up{background-position:-408px -24px}.icon-qrcode{background-position:-432px -24px}.icon-barcode{background-position:-456px -24px}.icon-tag{background-position:0 -48px}.icon-tags{background-position:-25px -48px}.icon-book{background-position:-48px -48px}.icon-bookmark{background-position:-72px -48px}.icon-print{background-position:-96px -48px}.icon-camera{background-position:-120px -48px}.icon-font{background-position:-144px -48px}.icon-bold{background-position:-167px -48px}.icon-italic{background-position:-192px -48px}.icon-text-height{background-position:-216px -48px}.icon-text-width{background-position:-240px -48px}.icon-align-left{background-position:-264px -48px}.icon-align-center{background-position:-288px -48px}.icon-align-right{background-position:-312px -48px}.icon-align-justify{background-position:-336px -48px}.icon-list{background-position:-360px -48px}.icon-indent-left{background-position:-384px -48px}.icon-indent-right{background-position:-408px -48px}.icon-facetime-video{background-position:-432px -48px}.icon-picture{background-position:-456px -48px}.icon-pencil{background-position:0 -72px}.icon-map-marker{background-position:-24px -72px}.icon-adjust{background-position:-48px -72px}.icon-tint{background-position:-72px -72px}.icon-edit{background-position:-96px -72px}.icon-share{background-position:-120px -72px}.icon-check{background-position:-144px -72px}.icon-move{background-position:-168px -72px}.icon-step-backward{background-position:-192px -72px}.icon-fast-backward{background-position:-216px -72px}.icon-backward{background-position:-240px -72px}.icon-play{background-position:-264px -72px}.icon-pause{background-position:-288px -72px}.icon-stop{background-position:-312px -72px}.icon-forward{background-position:-336px -72px}.icon-fast-forward{background-position:-360px -72px}.icon-step-forward{background-position:-384px -72px}.icon-eject{background-position:-408px -72px}.icon-chevron-left{background-position:-432px -72px}.icon-chevron-right{background-position:-456px -72px}.icon-plus-sign{background-position:0 -96px}.icon-minus-sign{background-position:-24px -96px}.icon-remove-sign{background-position:-48px -96px}.icon-ok-sign{background-position:-72px -96px}.icon-question-sign{background-position:-96px -96px}.icon-info-sign{background-position:-120px -96px}.icon-screenshot{background-position:-144px -96px}.icon-remove-circle{background-position:-168px -96px}.icon-ok-circle{background-position:-192px -96px}.icon-ban-circle{background-position:-216px -96px}.icon-arrow-left{background-position:-240px -96px}.icon-arrow-right{background-position:-264px -96px}.icon-arrow-up{background-position:-289px -96px}.icon-arrow-down{background-position:-312px -96px}.icon-share-alt{background-position:-336px -96px}.icon-resize-full{background-position:-360px -96px}.icon-resize-small{background-position:-384px -96px}.icon-plus{background-position:-408px -96px}.icon-minus{background-position:-433px -96px}.icon-asterisk{background-position:-456px -96px}.icon-exclamation-sign{background-position:0 -120px}.icon-gift{background-position:-24px -120px}.icon-leaf{background-position:-48px -120px}.icon-fire{background-position:-72px -120px}.icon-eye-open{background-position:-96px -120px}.icon-eye-close{background-position:-120px -120px}.icon-warning-sign{background-position:-144px -120px}.icon-plane{background-position:-168px -120px}.icon-calendar{background-position:-192px -120px}.icon-random{width:16px;background-position:-216px -120px}.icon-comment{background-position:-240px -120px}.icon-magnet{background-position:-264px -120px}.icon-chevron-up{background-position:-288px -120px}.icon-chevron-down{background-position:-313px -119px}.icon-retweet{background-position:-336px -120px}.icon-shopping-cart{background-position:-360px -120px}.icon-folder-close{width:16px;background-position:-384px -120px}.icon-folder-open{width:16px;background-position:-408px -120px}.icon-resize-vertical{background-position:-432px -119px}.icon-resize-horizontal{background-position:-456px -118px}.icon-hdd{background-position:0 -144px}.icon-bullhorn{background-position:-24px -144px}.icon-bell{background-position:-48px -144px}.icon-certificate{background-position:-72px -144px}.icon-thumbs-up{background-position:-96px -144px}.icon-thumbs-down{background-position:-120px -144px}.icon-hand-right{background-position:-144px -144px}.icon-hand-left{background-position:-168px -144px}.icon-hand-up{background-position:-192px -144px}.icon-hand-down{background-position:-216px -144px}.icon-circle-arrow-right{background-position:-240px -144px}.icon-circle-arrow-left{background-position:-264px -144px}.icon-circle-arrow-up{background-position:-288px -144px}.icon-circle-arrow-down{background-position:-312px -144px}.icon-globe{background-position:-336px -144px}.icon-wrench{background-position:-360px -144px}.icon-tasks{background-position:-384px -144px}.icon-filter{background-position:-408px -144px}.icon-briefcase{background-position:-432px -144px}.icon-fullscreen{background-position:-456px -144px}.dropup,.dropdown{position:relative}.dropdown-toggle{*margin-bottom:-3px}.dropdown-toggle:active,.open .dropdown-toggle{outline:0}.caret{display:inline-block;width:0;height:0;vertical-align:top;border-top:4px solid #000;border-right:4px solid transparent;border-left:4px solid transparent;content:""}.dropdown .caret{margin-top:8px;margin-left:2px}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);*border-right-width:2px;*border-bottom-width:2px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #fff}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:20px;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus,.dropdown-submenu:hover>a,.dropdown-submenu:focus>a{color:#fff;text-decoration:none;background-color:#0081c2;background-image:-moz-linear-gradient(top,#08c,#0077b3);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#0077b3));background-image:-webkit-linear-gradient(top,#08c,#0077b3);background-image:-o-linear-gradient(top,#08c,#0077b3);background-image:linear-gradient(to bottom,#08c,#0077b3);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0077b3',GradientType=0)}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;background-color:#0081c2;background-image:-moz-linear-gradient(top,#08c,#0077b3);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#0077b3));background-image:-webkit-linear-gradient(top,#08c,#0077b3);background-image:-o-linear-gradient(top,#08c,#0077b3);background-image:linear-gradient(to bottom,#08c,#0077b3);background-repeat:repeat-x;outline:0;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0077b3',GradientType=0)}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#999}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;cursor:default;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open{*z-index:1000}.open>.dropdown-menu{display:block}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid #000;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}.dropdown-submenu{position:relative}.dropdown-submenu>.dropdown-menu{top:0;left:100%;margin-top:-6px;margin-left:-1px;-webkit-border-radius:0 6px 6px 6px;-moz-border-radius:0 6px 6px 6px;border-radius:0 6px 6px 6px}.dropdown-submenu:hover>.dropdown-menu{display:block}.dropup .dropdown-submenu>.dropdown-menu{top:auto;bottom:0;margin-top:0;margin-bottom:-2px;-webkit-border-radius:5px 5px 5px 0;-moz-border-radius:5px 5px 5px 0;border-radius:5px 5px 5px 0}.dropdown-submenu>a:after{display:block;float:right;width:0;height:0;margin-top:5px;margin-right:-10px;border-color:transparent;border-left-color:#ccc;border-style:solid;border-width:5px 0 5px 5px;content:" "}.dropdown-submenu:hover>a:after{border-left-color:#fff}.dropdown-submenu.pull-left{float:none}.dropdown-submenu.pull-left>.dropdown-menu{left:-100%;margin-left:10px;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px}.dropdown .dropdown-menu .nav-header{padding-right:20px;padding-left:20px}.typeahead{z-index:1051;margin-top:2px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,0.15)}.well-large{padding:24px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.well-small{padding:9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.fade{opacity:0;-webkit-transition:opacity .15s linear;-moz-transition:opacity .15s linear;-o-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;-moz-transition:height .35s ease;-o-transition:height .35s ease;transition:height .35s ease}.collapse.in{height:auto}.close{float:right;font-size:20px;font-weight:bold;line-height:20px;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.4;filter:alpha(opacity=40)}button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}.btn{display:inline-block;*display:inline;padding:4px 12px;margin-bottom:0;*margin-left:.3em;font-size:14px;line-height:20px;color:#333;text-align:center;text-shadow:0 1px 1px rgba(255,255,255,0.75);vertical-align:middle;cursor:pointer;background-color:#f5f5f5;*background-color:#e6e6e6;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;border:1px solid #ccc;*border:0;border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);*zoom:1;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-right:0;padding-left:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;*background-color:#04c;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;*background-color:#f89406;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.btn-warning.disabled,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning:active,.btn-warning.active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#da4f49;*background-color:#bd362f;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeat:repeat-x;border-color:#bd362f #bd362f #802420;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b',endColorstr='#ffbd362f',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.btn-danger.disabled,.btn-danger[disabled]{color:#fff;background-color:#bd362f;*background-color:#a9302a}.btn-danger:active,.btn-danger.active{background-color:#942a25 \9}.btn-success{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#5bb75b;*background-color:#51a351;background-image:-moz-linear-gradient(top,#62c462,#51a351);background-image:-webkit-gradient(linear,0 0,0 100%,from(#62c462),to(#51a351));background-image:-webkit-linear-gradient(top,#62c462,#51a351);background-image:-o-linear-gradient(top,#62c462,#51a351);background-image:linear-gradient(to bottom,#62c462,#51a351);background-repeat:repeat-x;border-color:#51a351 #51a351 #387038;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462',endColorstr='#ff51a351',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.btn-success.disabled,.btn-success[disabled]{color:#fff;background-color:#51a351;*background-color:#499249}.btn-success:active,.btn-success.active{background-color:#408140 \9}.btn-info{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#49afcd;*background-color:#2f96b4;background-image:-moz-linear-gradient(top,#5bc0de,#2f96b4);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5bc0de),to(#2f96b4));background-image:-webkit-linear-gradient(top,#5bc0de,#2f96b4);background-image:-o-linear-gradient(top,#5bc0de,#2f96b4);background-image:linear-gradient(to bottom,#5bc0de,#2f96b4);background-repeat:repeat-x;border-color:#2f96b4 #2f96b4 #1f6377;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff2f96b4',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.btn-info.disabled,.btn-info[disabled]{color:#fff;background-color:#2f96b4;*background-color:#2a85a0}.btn-info:active,.btn-info.active{background-color:#24748c \9}.btn-inverse{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#363636;*background-color:#222;background-image:-moz-linear-gradient(top,#444,#222);background-image:-webkit-gradient(linear,0 0,0 100%,from(#444),to(#222));background-image:-webkit-linear-gradient(top,#444,#222);background-image:-o-linear-gradient(top,#444,#222);background-image:linear-gradient(to bottom,#444,#222);background-repeat:repeat-x;border-color:#222 #222 #000;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444',endColorstr='#ff222222',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-inverse:hover,.btn-inverse:focus,.btn-inverse:active,.btn-inverse.active,.btn-inverse.disabled,.btn-inverse[disabled]{color:#fff;background-color:#222;*background-color:#151515}.btn-inverse:active,.btn-inverse.active{background-color:#080808 \9}button.btn,input[type="submit"].btn{*padding-top:3px;*padding-bottom:3px}button.btn::-moz-focus-inner,input[type="submit"].btn::-moz-focus-inner{padding:0;border:0}button.btn.btn-large,input[type="submit"].btn.btn-large{*padding-top:7px;*padding-bottom:7px}button.btn.btn-small,input[type="submit"].btn.btn-small{*padding-top:3px;*padding-bottom:3px}button.btn.btn-mini,input[type="submit"].btn.btn-mini{*padding-top:1px;*padding-bottom:1px}.btn-link,.btn-link:active,.btn-link[disabled]{background-color:transparent;background-image:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-link{color:#08c;cursor:pointer;border-color:transparent;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-link:hover,.btn-link:focus{color:#005580;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,.btn-link[disabled]:focus{color:#333;text-decoration:none}.btn-group{position:relative;display:inline-block;*display:inline;*margin-left:.3em;font-size:0;white-space:nowrap;vertical-align:middle;*zoom:1}.btn-group:first-child{*margin-left:0}.btn-group+.btn-group{margin-left:5px}.btn-toolbar{margin-top:10px;margin-bottom:10px;font-size:0}.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group{margin-left:5px}.btn-group>.btn{position:relative;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-group>.btn+.btn{margin-left:-1px}.btn-group>.btn,.btn-group>.dropdown-menu,.btn-group>.popover{font-size:14px}.btn-group>.btn-mini{font-size:10.5px}.btn-group>.btn-small{font-size:11.9px}.btn-group>.btn-large{font-size:17.5px}.btn-group>.btn:first-child{margin-left:0;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-bottomleft:4px;-moz-border-radius-topleft:4px}.btn-group>.btn:last-child,.btn-group>.dropdown-toggle{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-bottomright:4px}.btn-group>.btn.large:first-child{margin-left:0;-webkit-border-bottom-left-radius:6px;border-bottom-left-radius:6px;-webkit-border-top-left-radius:6px;border-top-left-radius:6px;-moz-border-radius-bottomleft:6px;-moz-border-radius-topleft:6px}.btn-group>.btn.large:last-child,.btn-group>.large.dropdown-toggle{-webkit-border-top-right-radius:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;border-bottom-right-radius:6px;-moz-border-radius-topright:6px;-moz-border-radius-bottomright:6px}.btn-group>.btn:hover,.btn-group>.btn:focus,.btn-group>.btn:active,.btn-group>.btn.active{z-index:2}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{*padding-top:5px;padding-right:8px;*padding-bottom:5px;padding-left:8px;-webkit-box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)}.btn-group>.btn-mini+.dropdown-toggle{*padding-top:2px;padding-right:5px;*padding-bottom:2px;padding-left:5px}.btn-group>.btn-small+.dropdown-toggle{*padding-top:5px;*padding-bottom:4px}.btn-group>.btn-large+.dropdown-toggle{*padding-top:7px;padding-right:12px;*padding-bottom:7px;padding-left:12px}.btn-group.open .dropdown-toggle{background-image:none;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.btn-group.open .btn.dropdown-toggle{background-color:#e6e6e6}.btn-group.open .btn-primary.dropdown-toggle{background-color:#04c}.btn-group.open .btn-warning.dropdown-toggle{background-color:#f89406}.btn-group.open .btn-danger.dropdown-toggle{background-color:#bd362f}.btn-group.open .btn-success.dropdown-toggle{background-color:#51a351}.btn-group.open .btn-info.dropdown-toggle{background-color:#2f96b4}.btn-group.open .btn-inverse.dropdown-toggle{background-color:#222}.btn .caret{margin-top:8px;margin-left:0}.btn-large .caret{margin-top:6px}.btn-large .caret{border-top-width:5px;border-right-width:5px;border-left-width:5px}.btn-mini .caret,.btn-small .caret{margin-top:8px}.dropup .btn-large .caret{border-bottom-width:5px}.btn-primary .caret,.btn-warning .caret,.btn-danger .caret,.btn-info .caret,.btn-success .caret,.btn-inverse .caret{border-top-color:#fff;border-bottom-color:#fff}.btn-group-vertical{display:inline-block;*display:inline;*zoom:1}.btn-group-vertical>.btn{display:block;float:none;max-width:100%;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-group-vertical>.btn+.btn{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:first-child{-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0}.btn-group-vertical>.btn:last-child{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px}.btn-group-vertical>.btn-large:first-child{-webkit-border-radius:6px 6px 0 0;-moz-border-radius:6px 6px 0 0;border-radius:6px 6px 0 0}.btn-group-vertical>.btn-large:last-child{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px}.alert{padding:8px 35px 8px 14px;margin-bottom:20px;text-shadow:0 1px 0 rgba(255,255,255,0.5);background-color:#fcf8e3;border:1px solid #fbeed5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.alert,.alert h4{color:#c09853}.alert h4{margin:0}.alert .close{position:relative;top:-2px;right:-21px;line-height:20px}.alert-success{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.alert-success h4{color:#468847}.alert-danger,.alert-error{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.alert-danger h4,.alert-error h4{color:#b94a48}.alert-info{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.alert-info h4{color:#3a87ad}.alert-block{padding-top:14px;padding-bottom:14px}.alert-block>p,.alert-block>ul{margin-bottom:0}.alert-block p+p{margin-top:5px}.nav{margin-bottom:20px;margin-left:0;list-style:none}.nav>li>a{display:block}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li>a>img{max-width:none}.nav>.pull-right{float:right}.nav-header{display:block;padding:3px 15px;font-size:11px;font-weight:bold;line-height:20px;color:#999;text-shadow:0 1px 0 rgba(255,255,255,0.5);text-transform:uppercase}.nav li+.nav-header{margin-top:9px}.nav-list{padding-right:15px;padding-left:15px;margin-bottom:0}.nav-list>li>a,.nav-list .nav-header{margin-right:-15px;margin-left:-15px;text-shadow:0 1px 0 rgba(255,255,255,0.5)}.nav-list>li>a{padding:3px 15px}.nav-list>.active>a,.nav-list>.active>a:hover,.nav-list>.active>a:focus{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.2);background-color:#08c}.nav-list [class^="icon-"],.nav-list [class*=" icon-"]{margin-right:2px}.nav-list .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #fff}.nav-tabs,.nav-pills{*zoom:1}.nav-tabs:before,.nav-pills:before,.nav-tabs:after,.nav-pills:after{display:table;line-height:0;content:""}.nav-tabs:after,.nav-pills:after{clear:both}.nav-tabs>li,.nav-pills>li{float:left}.nav-tabs>li>a,.nav-pills>li>a{padding-right:12px;padding-left:12px;margin-right:2px;line-height:14px}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{margin-bottom:-1px}.nav-tabs>li>a{padding-top:8px;padding-bottom:8px;line-height:20px;border:1px solid transparent;-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover,.nav-tabs>li>a:focus{border-color:#eee #eee #ddd}.nav-tabs>.active>a,.nav-tabs>.active>a:hover,.nav-tabs>.active>a:focus{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-pills>li>a{padding-top:8px;padding-bottom:8px;margin-top:2px;margin-bottom:2px;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px}.nav-pills>.active>a,.nav-pills>.active>a:hover,.nav-pills>.active>a:focus{color:#fff;background-color:#08c}.nav-stacked>li{float:none}.nav-stacked>li>a{margin-right:0}.nav-tabs.nav-stacked{border-bottom:0}.nav-tabs.nav-stacked>li>a{border:1px solid #ddd;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.nav-tabs.nav-stacked>li:first-child>a{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-topleft:4px}.nav-tabs.nav-stacked>li:last-child>a{-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-moz-border-radius-bottomright:4px;-moz-border-radius-bottomleft:4px}.nav-tabs.nav-stacked>li>a:hover,.nav-tabs.nav-stacked>li>a:focus{z-index:2;border-color:#ddd}.nav-pills.nav-stacked>li>a{margin-bottom:3px}.nav-pills.nav-stacked>li:last-child>a{margin-bottom:1px}.nav-tabs .dropdown-menu{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px}.nav-pills .dropdown-menu{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.nav .dropdown-toggle .caret{margin-top:6px;border-top-color:#08c;border-bottom-color:#08c}.nav .dropdown-toggle:hover .caret,.nav .dropdown-toggle:focus .caret{border-top-color:#005580;border-bottom-color:#005580}.nav-tabs .dropdown-toggle .caret{margin-top:8px}.nav .active .dropdown-toggle .caret{border-top-color:#fff;border-bottom-color:#fff}.nav-tabs .active .dropdown-toggle .caret{border-top-color:#555;border-bottom-color:#555}.nav>.dropdown.active>a:hover,.nav>.dropdown.active>a:focus{cursor:pointer}.nav-tabs .open .dropdown-toggle,.nav-pills .open .dropdown-toggle,.nav>li.dropdown.open.active>a:hover,.nav>li.dropdown.open.active>a:focus{color:#fff;background-color:#999;border-color:#999}.nav li.dropdown.open .caret,.nav li.dropdown.open.active .caret,.nav li.dropdown.open a:hover .caret,.nav li.dropdown.open a:focus .caret{border-top-color:#fff;border-bottom-color:#fff;opacity:1;filter:alpha(opacity=100)}.tabs-stacked .open>a:hover,.tabs-stacked .open>a:focus{border-color:#999}.tabbable{*zoom:1}.tabbable:before,.tabbable:after{display:table;line-height:0;content:""}.tabbable:after{clear:both}.tab-content{overflow:auto}.tabs-below>.nav-tabs,.tabs-right>.nav-tabs,.tabs-left>.nav-tabs{border-bottom:0}.tab-content>.tab-pane,.pill-content>.pill-pane{display:none}.tab-content>.active,.pill-content>.active{display:block}.tabs-below>.nav-tabs{border-top:1px solid #ddd}.tabs-below>.nav-tabs>li{margin-top:-1px;margin-bottom:0}.tabs-below>.nav-tabs>li>a{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px}.tabs-below>.nav-tabs>li>a:hover,.tabs-below>.nav-tabs>li>a:focus{border-top-color:#ddd;border-bottom-color:transparent}.tabs-below>.nav-tabs>.active>a,.tabs-below>.nav-tabs>.active>a:hover,.tabs-below>.nav-tabs>.active>a:focus{border-color:transparent #ddd #ddd #ddd}.tabs-left>.nav-tabs>li,.tabs-right>.nav-tabs>li{float:none}.tabs-left>.nav-tabs>li>a,.tabs-right>.nav-tabs>li>a{min-width:74px;margin-right:0;margin-bottom:3px}.tabs-left>.nav-tabs{float:left;margin-right:19px;border-right:1px solid #ddd}.tabs-left>.nav-tabs>li>a{margin-right:-1px;-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.tabs-left>.nav-tabs>li>a:hover,.tabs-left>.nav-tabs>li>a:focus{border-color:#eee #ddd #eee #eee}.tabs-left>.nav-tabs .active>a,.tabs-left>.nav-tabs .active>a:hover,.tabs-left>.nav-tabs .active>a:focus{border-color:#ddd transparent #ddd #ddd;*border-right-color:#fff}.tabs-right>.nav-tabs{float:right;margin-left:19px;border-left:1px solid #ddd}.tabs-right>.nav-tabs>li>a{margin-left:-1px;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.tabs-right>.nav-tabs>li>a:hover,.tabs-right>.nav-tabs>li>a:focus{border-color:#eee #eee #eee #ddd}.tabs-right>.nav-tabs .active>a,.tabs-right>.nav-tabs .active>a:hover,.tabs-right>.nav-tabs .active>a:focus{border-color:#ddd #ddd #ddd transparent;*border-left-color:#fff}.nav>.disabled>a{color:#999}.nav>.disabled>a:hover,.nav>.disabled>a:focus{text-decoration:none;cursor:default;background-color:transparent}.navbar{*position:relative;*z-index:2;margin-bottom:20px;overflow:visible}.navbar-inner{min-height:40px;padding-right:20px;padding-left:20px;background-color:#fafafa;background-image:-moz-linear-gradient(top,#fff,#f2f2f2);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#f2f2f2));background-image:-webkit-linear-gradient(top,#fff,#f2f2f2);background-image:-o-linear-gradient(top,#fff,#f2f2f2);background-image:linear-gradient(to bottom,#fff,#f2f2f2);background-repeat:repeat-x;border:1px solid #d4d4d4;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#fff2f2f2',GradientType=0);*zoom:1;-webkit-box-shadow:0 1px 4px rgba(0,0,0,0.065);-moz-box-shadow:0 1px 4px rgba(0,0,0,0.065);box-shadow:0 1px 4px rgba(0,0,0,0.065)}.navbar-inner:before,.navbar-inner:after{display:table;line-height:0;content:""}.navbar-inner:after{clear:both}.navbar .container{width:auto}.nav-collapse.collapse{height:auto;overflow:visible}.navbar .brand{display:block;float:left;padding:10px 20px 10px;margin-left:-20px;font-size:20px;font-weight:200;color:#777;text-shadow:0 1px 0 #fff}.navbar .brand:hover,.navbar .brand:focus{text-decoration:none}.navbar-text{margin-bottom:0;line-height:40px;color:#777}.navbar-link{color:#777}.navbar-link:hover,.navbar-link:focus{color:#333}.navbar .divider-vertical{height:40px;margin:0 9px;border-right:1px solid #fff;border-left:1px solid #f2f2f2}.navbar .btn,.navbar .btn-group{margin-top:5px}.navbar .btn-group .btn,.navbar .input-prepend .btn,.navbar .input-append .btn,.navbar .input-prepend .btn-group,.navbar .input-append .btn-group{margin-top:0}.navbar-form{margin-bottom:0;*zoom:1}.navbar-form:before,.navbar-form:after{display:table;line-height:0;content:""}.navbar-form:after{clear:both}.navbar-form input,.navbar-form select,.navbar-form .radio,.navbar-form .checkbox{margin-top:5px}.navbar-form input,.navbar-form select,.navbar-form .btn{display:inline-block;margin-bottom:0}.navbar-form input[type="image"],.navbar-form input[type="checkbox"],.navbar-form input[type="radio"]{margin-top:3px}.navbar-form .input-append,.navbar-form .input-prepend{margin-top:5px;white-space:nowrap}.navbar-form .input-append input,.navbar-form .input-prepend input{margin-top:0}.navbar-search{position:relative;float:left;margin-top:5px;margin-bottom:0}.navbar-search .search-query{padding:4px 14px;margin-bottom:0;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:13px;font-weight:normal;line-height:1;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.navbar-static-top{position:static;margin-bottom:0}.navbar-static-top .navbar-inner{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030;margin-bottom:0}.navbar-fixed-top .navbar-inner,.navbar-static-top .navbar-inner{border-width:0 0 1px}.navbar-fixed-bottom .navbar-inner{border-width:1px 0 0}.navbar-fixed-top .navbar-inner,.navbar-fixed-bottom .navbar-inner{padding-right:0;padding-left:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px}.navbar-fixed-top{top:0}.navbar-fixed-top .navbar-inner,.navbar-static-top .navbar-inner{-webkit-box-shadow:0 1px 10px rgba(0,0,0,0.1);-moz-box-shadow:0 1px 10px rgba(0,0,0,0.1);box-shadow:0 1px 10px rgba(0,0,0,0.1)}.navbar-fixed-bottom{bottom:0}.navbar-fixed-bottom .navbar-inner{-webkit-box-shadow:0 -1px 10px rgba(0,0,0,0.1);-moz-box-shadow:0 -1px 10px rgba(0,0,0,0.1);box-shadow:0 -1px 10px rgba(0,0,0,0.1)}.navbar .nav{position:relative;left:0;display:block;float:left;margin:0 10px 0 0}.navbar .nav.pull-right{float:right;margin-right:0}.navbar .nav>li{float:left}.navbar .nav>li>a{float:none;padding:10px 15px 10px;color:#777;text-decoration:none;text-shadow:0 1px 0 #fff}.navbar .nav .dropdown-toggle .caret{margin-top:8px}.navbar .nav>li>a:focus,.navbar .nav>li>a:hover{color:#333;text-decoration:none;background-color:transparent}.navbar .nav>.active>a,.navbar .nav>.active>a:hover,.navbar .nav>.active>a:focus{color:#555;text-decoration:none;background-color:#e5e5e5;-webkit-box-shadow:inset 0 3px 8px rgba(0,0,0,0.125);-moz-box-shadow:inset 0 3px 8px rgba(0,0,0,0.125);box-shadow:inset 0 3px 8px rgba(0,0,0,0.125)}.navbar .btn-navbar{display:none;float:right;padding:7px 10px;margin-right:5px;margin-left:5px;color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#ededed;*background-color:#e5e5e5;background-image:-moz-linear-gradient(top,#f2f2f2,#e5e5e5);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f2f2f2),to(#e5e5e5));background-image:-webkit-linear-gradient(top,#f2f2f2,#e5e5e5);background-image:-o-linear-gradient(top,#f2f2f2,#e5e5e5);background-image:linear-gradient(to bottom,#f2f2f2,#e5e5e5);background-repeat:repeat-x;border-color:#e5e5e5 #e5e5e5 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2',endColorstr='#ffe5e5e5',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075);box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075)}.navbar .btn-navbar:hover,.navbar .btn-navbar:focus,.navbar .btn-navbar:active,.navbar .btn-navbar.active,.navbar .btn-navbar.disabled,.navbar .btn-navbar[disabled]{color:#fff;background-color:#e5e5e5;*background-color:#d9d9d9}.navbar .btn-navbar:active,.navbar .btn-navbar.active{background-color:#ccc \9}.navbar .btn-navbar .icon-bar{display:block;width:18px;height:2px;background-color:#f5f5f5;-webkit-border-radius:1px;-moz-border-radius:1px;border-radius:1px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,0.25);-moz-box-shadow:0 1px 0 rgba(0,0,0,0.25);box-shadow:0 1px 0 rgba(0,0,0,0.25)}.btn-navbar .icon-bar+.icon-bar{margin-top:3px}.navbar .nav>li>.dropdown-menu:before{position:absolute;top:-7px;left:9px;display:inline-block;border-right:7px solid transparent;border-bottom:7px solid #ccc;border-left:7px solid transparent;border-bottom-color:rgba(0,0,0,0.2);content:''}.navbar .nav>li>.dropdown-menu:after{position:absolute;top:-6px;left:10px;display:inline-block;border-right:6px solid transparent;border-bottom:6px solid #fff;border-left:6px solid transparent;content:''}.navbar-fixed-bottom .nav>li>.dropdown-menu:before{top:auto;bottom:-7px;border-top:7px solid #ccc;border-bottom:0;border-top-color:rgba(0,0,0,0.2)}.navbar-fixed-bottom .nav>li>.dropdown-menu:after{top:auto;bottom:-6px;border-top:6px solid #fff;border-bottom:0}.navbar .nav li.dropdown>a:hover .caret,.navbar .nav li.dropdown>a:focus .caret{border-top-color:#333;border-bottom-color:#333}.navbar .nav li.dropdown.open>.dropdown-toggle,.navbar .nav li.dropdown.active>.dropdown-toggle,.navbar .nav li.dropdown.open.active>.dropdown-toggle{color:#555;background-color:#e5e5e5}.navbar .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#777;border-bottom-color:#777}.navbar .nav li.dropdown.open>.dropdown-toggle .caret,.navbar .nav li.dropdown.active>.dropdown-toggle .caret,.navbar .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#555;border-bottom-color:#555}.navbar .pull-right>li>.dropdown-menu,.navbar .nav>li>.dropdown-menu.pull-right{right:0;left:auto}.navbar .pull-right>li>.dropdown-menu:before,.navbar .nav>li>.dropdown-menu.pull-right:before{right:12px;left:auto}.navbar .pull-right>li>.dropdown-menu:after,.navbar .nav>li>.dropdown-menu.pull-right:after{right:13px;left:auto}.navbar .pull-right>li>.dropdown-menu .dropdown-menu,.navbar .nav>li>.dropdown-menu.pull-right .dropdown-menu{right:100%;left:auto;margin-right:-1px;margin-left:0;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px}.navbar-inverse .navbar-inner{background-color:#1b1b1b;background-image:-moz-linear-gradient(top,#222,#111);background-image:-webkit-gradient(linear,0 0,0 100%,from(#222),to(#111));background-image:-webkit-linear-gradient(top,#222,#111);background-image:-o-linear-gradient(top,#222,#111);background-image:linear-gradient(to bottom,#222,#111);background-repeat:repeat-x;border-color:#252525;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222',endColorstr='#ff111111',GradientType=0)}.navbar-inverse .brand,.navbar-inverse .nav>li>a{color:#999;text-shadow:0 -1px 0 rgba(0,0,0,0.25)}.navbar-inverse .brand:hover,.navbar-inverse .nav>li>a:hover,.navbar-inverse .brand:focus,.navbar-inverse .nav>li>a:focus{color:#fff}.navbar-inverse .brand{color:#999}.navbar-inverse .navbar-text{color:#999}.navbar-inverse .nav>li>a:focus,.navbar-inverse .nav>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .nav .active>a,.navbar-inverse .nav .active>a:hover,.navbar-inverse .nav .active>a:focus{color:#fff;background-color:#111}.navbar-inverse .navbar-link{color:#999}.navbar-inverse .navbar-link:hover,.navbar-inverse .navbar-link:focus{color:#fff}.navbar-inverse .divider-vertical{border-right-color:#222;border-left-color:#111}.navbar-inverse .nav li.dropdown.open>.dropdown-toggle,.navbar-inverse .nav li.dropdown.active>.dropdown-toggle,.navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle{color:#fff;background-color:#111}.navbar-inverse .nav li.dropdown>a:hover .caret,.navbar-inverse .nav li.dropdown>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#999;border-bottom-color:#999}.navbar-inverse .nav li.dropdown.open>.dropdown-toggle .caret,.navbar-inverse .nav li.dropdown.active>.dropdown-toggle .caret,.navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .navbar-search .search-query{color:#fff;background-color:#515151;border-color:#111;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);-webkit-transition:none;-moz-transition:none;-o-transition:none;transition:none}.navbar-inverse .navbar-search .search-query:-moz-placeholder{color:#ccc}.navbar-inverse .navbar-search .search-query:-ms-input-placeholder{color:#ccc}.navbar-inverse .navbar-search .search-query::-webkit-input-placeholder{color:#ccc}.navbar-inverse .navbar-search .search-query:focus,.navbar-inverse .navbar-search .search-query.focused{padding:5px 15px;color:#333;text-shadow:0 1px 0 #fff;background-color:#fff;border:0;outline:0;-webkit-box-shadow:0 0 3px rgba(0,0,0,0.15);-moz-box-shadow:0 0 3px rgba(0,0,0,0.15);box-shadow:0 0 3px rgba(0,0,0,0.15)}.navbar-inverse .btn-navbar{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#0e0e0e;*background-color:#040404;background-image:-moz-linear-gradient(top,#151515,#040404);background-image:-webkit-gradient(linear,0 0,0 100%,from(#151515),to(#040404));background-image:-webkit-linear-gradient(top,#151515,#040404);background-image:-o-linear-gradient(top,#151515,#040404);background-image:linear-gradient(to bottom,#151515,#040404);background-repeat:repeat-x;border-color:#040404 #040404 #000;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff151515',endColorstr='#ff040404',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.navbar-inverse .btn-navbar:hover,.navbar-inverse .btn-navbar:focus,.navbar-inverse .btn-navbar:active,.navbar-inverse .btn-navbar.active,.navbar-inverse .btn-navbar.disabled,.navbar-inverse .btn-navbar[disabled]{color:#fff;background-color:#040404;*background-color:#000}.navbar-inverse .btn-navbar:active,.navbar-inverse .btn-navbar.active{background-color:#000 \9}.breadcrumb{padding:8px 15px;margin:0 0 20px;list-style:none;background-color:#f5f5f5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.breadcrumb>li{display:inline-block;*display:inline;text-shadow:0 1px 0 #fff;*zoom:1}.breadcrumb>li>.divider{padding:0 5px;color:#ccc}.breadcrumb>.active{color:#999}.pagination{margin:20px 0}.pagination ul{display:inline-block;*display:inline;margin-bottom:0;margin-left:0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*zoom:1;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,0.05);box-shadow:0 1px 2px rgba(0,0,0,0.05)}.pagination ul>li{display:inline}.pagination ul>li>a,.pagination ul>li>span{float:left;padding:4px 12px;line-height:20px;text-decoration:none;background-color:#fff;border:1px solid #ddd;border-left-width:0}.pagination ul>li>a:hover,.pagination ul>li>a:focus,.pagination ul>.active>a,.pagination ul>.active>span{background-color:#f5f5f5}.pagination ul>.active>a,.pagination ul>.active>span{color:#999;cursor:default}.pagination ul>.disabled>span,.pagination ul>.disabled>a,.pagination ul>.disabled>a:hover,.pagination ul>.disabled>a:focus{color:#999;cursor:default;background-color:transparent}.pagination ul>li:first-child>a,.pagination ul>li:first-child>span{border-left-width:1px;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-bottomleft:4px;-moz-border-radius-topleft:4px}.pagination ul>li:last-child>a,.pagination ul>li:last-child>span{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-bottomright:4px}.pagination-centered{text-align:center}.pagination-right{text-align:right}.pagination-large ul>li>a,.pagination-large ul>li>span{padding:11px 19px;font-size:17.5px}.pagination-large ul>li:first-child>a,.pagination-large ul>li:first-child>span{-webkit-border-bottom-left-radius:6px;border-bottom-left-radius:6px;-webkit-border-top-left-radius:6px;border-top-left-radius:6px;-moz-border-radius-bottomleft:6px;-moz-border-radius-topleft:6px}.pagination-large ul>li:last-child>a,.pagination-large ul>li:last-child>span{-webkit-border-top-right-radius:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;border-bottom-right-radius:6px;-moz-border-radius-topright:6px;-moz-border-radius-bottomright:6px}.pagination-mini ul>li:first-child>a,.pagination-small ul>li:first-child>a,.pagination-mini ul>li:first-child>span,.pagination-small ul>li:first-child>span{-webkit-border-bottom-left-radius:3px;border-bottom-left-radius:3px;-webkit-border-top-left-radius:3px;border-top-left-radius:3px;-moz-border-radius-bottomleft:3px;-moz-border-radius-topleft:3px}.pagination-mini ul>li:last-child>a,.pagination-small ul>li:last-child>a,.pagination-mini ul>li:last-child>span,.pagination-small ul>li:last-child>span{-webkit-border-top-right-radius:3px;border-top-right-radius:3px;-webkit-border-bottom-right-radius:3px;border-bottom-right-radius:3px;-moz-border-radius-topright:3px;-moz-border-radius-bottomright:3px}.pagination-small ul>li>a,.pagination-small ul>li>span{padding:2px 10px;font-size:11.9px}.pagination-mini ul>li>a,.pagination-mini ul>li>span{padding:0 6px;font-size:10.5px}.pager{margin:20px 0;text-align:center;list-style:none;*zoom:1}.pager:before,.pager:after{display:table;line-height:0;content:""}.pager:after{clear:both}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#f5f5f5}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#999;cursor:default;background-color:#fff}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{opacity:0}.modal-backdrop,.modal-backdrop.fade.in{opacity:.8;filter:alpha(opacity=80)}.modal{position:fixed;top:10%;left:50%;z-index:1050;width:560px;margin-left:-280px;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,0.3);*border:1px solid #999;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;outline:0;-webkit-box-shadow:0 3px 7px rgba(0,0,0,0.3);-moz-box-shadow:0 3px 7px rgba(0,0,0,0.3);box-shadow:0 3px 7px rgba(0,0,0,0.3);-webkit-background-clip:padding-box;-moz-background-clip:padding-box;background-clip:padding-box}.modal.fade{top:-25%;-webkit-transition:opacity .3s linear,top .3s ease-out;-moz-transition:opacity .3s linear,top .3s ease-out;-o-transition:opacity .3s linear,top .3s ease-out;transition:opacity .3s linear,top .3s ease-out}.modal.fade.in{top:10%}.modal-header{padding:9px 15px;border-bottom:1px solid #eee}.modal-header .close{margin-top:2px}.modal-header h3{margin:0;line-height:30px}.modal-body{position:relative;max-height:400px;padding:15px;overflow-y:auto}.modal-form{margin-bottom:0}.modal-footer{padding:14px 15px 15px;margin-bottom:0;text-align:right;background-color:#f5f5f5;border-top:1px solid #ddd;-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;*zoom:1;-webkit-box-shadow:inset 0 1px 0 #fff;-moz-box-shadow:inset 0 1px 0 #fff;box-shadow:inset 0 1px 0 #fff}.modal-footer:before,.modal-footer:after{display:table;line-height:0;content:""}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.tooltip{position:absolute;z-index:1030;display:block;font-size:11px;line-height:1.4;opacity:0;filter:alpha(opacity=0);visibility:visible}.tooltip.in{opacity:.8;filter:alpha(opacity=80)}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:8px;color:#fff;text-align:center;text-decoration:none;background-color:#000;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-top-color:#000;border-width:5px 5px 0}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-right-color:#000;border-width:5px 5px 5px 0}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-left-color:#000;border-width:5px 0 5px 5px}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-bottom-color:#000;border-width:0 5px 5px}.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;white-space:normal;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;-webkit-border-radius:5px 5px 0 0;-moz-border-radius:5px 5px 0 0;border-radius:5px 5px 0 0}.popover-title:empty{display:none}.popover-content{padding:9px 14px}.popover .arrow,.popover .arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover .arrow{border-width:11px}.popover .arrow:after{border-width:10px;content:""}.popover.top .arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,0.25);border-bottom-width:0}.popover.top .arrow:after{bottom:1px;margin-left:-10px;border-top-color:#fff;border-bottom-width:0}.popover.right .arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,0.25);border-left-width:0}.popover.right .arrow:after{bottom:-10px;left:1px;border-right-color:#fff;border-left-width:0}.popover.bottom .arrow{top:-11px;left:50%;margin-left:-11px;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,0.25);border-top-width:0}.popover.bottom .arrow:after{top:1px;margin-left:-10px;border-bottom-color:#fff;border-top-width:0}.popover.left .arrow{top:50%;right:-11px;margin-top:-11px;border-left-color:#999;border-left-color:rgba(0,0,0,0.25);border-right-width:0}.popover.left .arrow:after{right:1px;bottom:-10px;border-left-color:#fff;border-right-width:0}.thumbnails{margin-left:-20px;list-style:none;*zoom:1}.thumbnails:before,.thumbnails:after{display:table;line-height:0;content:""}.thumbnails:after{clear:both}.row-fluid .thumbnails{margin-left:0}.thumbnails>li{float:left;margin-bottom:20px;margin-left:20px}.thumbnail{display:block;padding:4px;line-height:20px;border:1px solid #ddd;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 1px 3px rgba(0,0,0,0.055);-moz-box-shadow:0 1px 3px rgba(0,0,0,0.055);box-shadow:0 1px 3px rgba(0,0,0,0.055);-webkit-transition:all .2s ease-in-out;-moz-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}a.thumbnail:hover,a.thumbnail:focus{border-color:#08c;-webkit-box-shadow:0 1px 4px rgba(0,105,214,0.25);-moz-box-shadow:0 1px 4px rgba(0,105,214,0.25);box-shadow:0 1px 4px rgba(0,105,214,0.25)}.thumbnail>img{display:block;max-width:100%;margin-right:auto;margin-left:auto}.thumbnail .caption{padding:9px;color:#555}.media,.media-body{overflow:hidden;*overflow:visible;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{margin-left:0;list-style:none}.label,.badge{display:inline-block;padding:2px 4px;font-size:11.844px;font-weight:bold;line-height:14px;color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);white-space:nowrap;vertical-align:baseline;background-color:#999}.label{-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.badge{padding-right:9px;padding-left:9px;-webkit-border-radius:9px;-moz-border-radius:9px;border-radius:9px}.label:empty,.badge:empty{display:none}a.label:hover,a.label:focus,a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}.label-important,.badge-important{background-color:#b94a48}.label-important[href],.badge-important[href]{background-color:#953b39}.label-warning,.badge-warning{background-color:#f89406}.label-warning[href],.badge-warning[href]{background-color:#c67605}.label-success,.badge-success{background-color:#468847}.label-success[href],.badge-success[href]{background-color:#356635}.label-info,.badge-info{background-color:#3a87ad}.label-info[href],.badge-info[href]{background-color:#2d6987}.label-inverse,.badge-inverse{background-color:#333}.label-inverse[href],.badge-inverse[href]{background-color:#1a1a1a}.btn .label,.btn .badge{position:relative;top:-1px}.btn-mini .label,.btn-mini .badge{top:0}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-moz-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-ms-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:0 0}to{background-position:40px 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f7f7f7;background-image:-moz-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f5f5f5),to(#f9f9f9));background-image:-webkit-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:-o-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:linear-gradient(to bottom,#f5f5f5,#f9f9f9);background-repeat:repeat-x;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5',endColorstr='#fff9f9f9',GradientType=0);-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1)}.progress .bar{float:left;width:0;height:100%;font-size:12px;color:#fff;text-align:center;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#0e90d2;background-image:-moz-linear-gradient(top,#149bdf,#0480be);background-image:-webkit-gradient(linear,0 0,0 100%,from(#149bdf),to(#0480be));background-image:-webkit-linear-gradient(top,#149bdf,#0480be);background-image:-o-linear-gradient(top,#149bdf,#0480be);background-image:linear-gradient(to bottom,#149bdf,#0480be);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff149bdf',endColorstr='#ff0480be',GradientType=0);-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-moz-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;-webkit-transition:width .6s ease;-moz-transition:width .6s ease;-o-transition:width .6s ease;transition:width .6s ease}.progress .bar+.bar{-webkit-box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15);-moz-box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15)}.progress-striped .bar{background-color:#149bdf;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);-webkit-background-size:40px 40px;-moz-background-size:40px 40px;-o-background-size:40px 40px;background-size:40px 40px}.progress.active .bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-moz-animation:progress-bar-stripes 2s linear infinite;-ms-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-danger .bar,.progress .bar-danger{background-color:#dd514c;background-image:-moz-linear-gradient(top,#ee5f5b,#c43c35);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#c43c35));background-image:-webkit-linear-gradient(top,#ee5f5b,#c43c35);background-image:-o-linear-gradient(top,#ee5f5b,#c43c35);background-image:linear-gradient(to bottom,#ee5f5b,#c43c35);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b',endColorstr='#ffc43c35',GradientType=0)}.progress-danger.progress-striped .bar,.progress-striped .bar-danger{background-color:#ee5f5b;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-success .bar,.progress .bar-success{background-color:#5eb95e;background-image:-moz-linear-gradient(top,#62c462,#57a957);background-image:-webkit-gradient(linear,0 0,0 100%,from(#62c462),to(#57a957));background-image:-webkit-linear-gradient(top,#62c462,#57a957);background-image:-o-linear-gradient(top,#62c462,#57a957);background-image:linear-gradient(to bottom,#62c462,#57a957);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462',endColorstr='#ff57a957',GradientType=0)}.progress-success.progress-striped .bar,.progress-striped .bar-success{background-color:#62c462;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-info .bar,.progress .bar-info{background-color:#4bb1cf;background-image:-moz-linear-gradient(top,#5bc0de,#339bb9);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5bc0de),to(#339bb9));background-image:-webkit-linear-gradient(top,#5bc0de,#339bb9);background-image:-o-linear-gradient(top,#5bc0de,#339bb9);background-image:linear-gradient(to bottom,#5bc0de,#339bb9);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff339bb9',GradientType=0)}.progress-info.progress-striped .bar,.progress-striped .bar-info{background-color:#5bc0de;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-warning .bar,.progress .bar-warning{background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0)}.progress-warning.progress-striped .bar,.progress-striped .bar-warning{background-color:#fbb450;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.accordion{margin-bottom:20px}.accordion-group{margin-bottom:2px;border:1px solid #e5e5e5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.accordion-heading{border-bottom:0}.accordion-heading .accordion-toggle{display:block;padding:8px 15px}.accordion-toggle{cursor:pointer}.accordion-inner{padding:9px 15px;border-top:1px solid #e5e5e5}.carousel{position:relative;margin-bottom:20px;line-height:1}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;-moz-transition:.6s ease-in-out left;-o-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:block;line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:40%;left:15px;width:40px;height:40px;margin-top:-20px;font-size:60px;font-weight:100;line-height:30px;color:#fff;text-align:center;background:#222;border:3px solid #fff;-webkit-border-radius:23px;-moz-border-radius:23px;border-radius:23px;opacity:.5;filter:alpha(opacity=50)}.carousel-control.right{right:15px;left:auto}.carousel-control:hover,.carousel-control:focus{color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.carousel-indicators{position:absolute;top:15px;right:15px;z-index:5;margin:0;list-style:none}.carousel-indicators li{display:block;float:left;width:10px;height:10px;margin-left:5px;text-indent:-999px;background-color:#ccc;background-color:rgba(255,255,255,0.25);border-radius:5px}.carousel-indicators .active{background-color:#fff}.carousel-caption{position:absolute;right:0;bottom:0;left:0;padding:15px;background:#333;background:rgba(0,0,0,0.75)}.carousel-caption h4,.carousel-caption p{line-height:20px;color:#fff}.carousel-caption h4{margin:0 0 5px}.carousel-caption p{margin-bottom:0}.hero-unit{padding:60px;margin-bottom:30px;font-size:18px;font-weight:200;line-height:30px;color:inherit;background-color:#eee;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.hero-unit h1{margin-bottom:0;font-size:60px;line-height:1;letter-spacing:-1px;color:inherit}.hero-unit li{line-height:30px}.pull-right{float:right}.pull-left{float:left}.hide{display:none}.show{display:block}.invisible{visibility:hidden}.affix{position:fixed}
docs/theme/docker/static/css/bootstrap.min.css
0
https://github.com/moby/moby/commit/e368c8bb01b3c52c8e4c334c3a7f32556af9d632
[ 0.0001705698377918452, 0.0001705698377918452, 0.0001705698377918452, 0.0001705698377918452, 0 ]
{ "id": 1, "code_window": [ "\t\t}\n", "\t}\n", "}\n", "\n", "func TestMount(t *testing.T) {\n", "\tgraph := tempGraph(t)\n", "\tdefer os.RemoveAll(graph.Root)\n", "\tarchive, err := fakeTar()\n", "\tif err != nil {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\truntime := mkRuntime(t)\n", "\tdefer nuke(runtime)\n", "\n" ], "file_path": "graph_test.go", "type": "add", "edit_start_line_idx": 123 }
// 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 ipv6 import "syscall" func ipv6PathMTU(fd int) (int, error) { // TODO(mikio): Implement this return 0, syscall.EPLAN9 }
vendor/src/code.google.com/p/go.net/ipv6/sockopt_rfc3542_plan9.go
0
https://github.com/moby/moby/commit/e368c8bb01b3c52c8e4c334c3a7f32556af9d632
[ 0.0001756335113896057, 0.00017347378889098763, 0.0001713140809442848, 0.00017347378889098763, 0.000002159715222660452 ]
{ "id": 1, "code_window": [ "\t\t}\n", "\t}\n", "}\n", "\n", "func TestMount(t *testing.T) {\n", "\tgraph := tempGraph(t)\n", "\tdefer os.RemoveAll(graph.Root)\n", "\tarchive, err := fakeTar()\n", "\tif err != nil {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\truntime := mkRuntime(t)\n", "\tdefer nuke(runtime)\n", "\n" ], "file_path": "graph_test.go", "type": "add", "edit_start_line_idx": 123 }
Docker on Arch ============== The AUR lxc-docker and lxc-docker-git packages handle building docker on Arch linux. The PKGBUILD specifies all dependencies, build, and packaging steps. Dependencies ============ The only buildtime dependencies are git and go which are available via pacman. The -s flag can be used on makepkg commands below to automatically install these dependencies. Building Package ================ Download the tarball for either AUR packaged to a local directory. In that directory makepkg can be run to build the package. # Build the binary package makepkg # Build an updated source tarball makepkg --source
packaging/archlinux/README.archlinux
0
https://github.com/moby/moby/commit/e368c8bb01b3c52c8e4c334c3a7f32556af9d632
[ 0.00017378144548274577, 0.0001683299196884036, 0.00016410171519964933, 0.0001671065838309005, 0.0000040453014662489295 ]
{ "id": 2, "code_window": [ "\trw := path.Join(tmp, \"rw\")\n", "\tif err := os.MkdirAll(rw, 0700); err != nil {\n", "\t\tt.Fatal(err)\n", "\t}\n", "\tif err := image.Mount(rootfs, rw); err != nil {\n", "\t\tt.Fatal(err)\n", "\t}\n", "\t// FIXME: test for mount contents\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tif err := image.Mount(runtime, rootfs, rw, \"testing\"); err != nil {\n" ], "file_path": "graph_test.go", "type": "replace", "edit_start_line_idx": 146 }
package docker import ( "archive/tar" "bytes" "errors" "github.com/dotcloud/docker/utils" "io" "io/ioutil" "os" "path" "testing" "time" ) func TestInit(t *testing.T) { graph := tempGraph(t) defer os.RemoveAll(graph.Root) // Root should exist if _, err := os.Stat(graph.Root); err != nil { t.Fatal(err) } // Map() should be empty if l, err := graph.Map(); err != nil { t.Fatal(err) } else if len(l) != 0 { t.Fatalf("len(Map()) should return %d, not %d", 0, len(l)) } } // Test that Register can be interrupted cleanly without side effects func TestInterruptedRegister(t *testing.T) { graph := tempGraph(t) defer os.RemoveAll(graph.Root) badArchive, w := io.Pipe() // Use a pipe reader as a fake archive which never yields data image := &Image{ ID: GenerateID(), Comment: "testing", Created: time.Now(), } go graph.Register(nil, badArchive, image) time.Sleep(200 * time.Millisecond) w.CloseWithError(errors.New("But I'm not a tarball!")) // (Nobody's perfect, darling) if _, err := graph.Get(image.ID); err == nil { t.Fatal("Image should not exist after Register is interrupted") } // Registering the same image again should succeed if the first register was interrupted goodArchive, err := fakeTar() if err != nil { t.Fatal(err) } if err := graph.Register(nil, goodArchive, image); err != nil { t.Fatal(err) } } // FIXME: Do more extensive tests (ex: create multiple, delete, recreate; // create multiple, check the amount of images and paths, etc..) func TestGraphCreate(t *testing.T) { graph := tempGraph(t) defer os.RemoveAll(graph.Root) archive, err := fakeTar() if err != nil { t.Fatal(err) } image, err := graph.Create(archive, nil, "Testing", "", nil) if err != nil { t.Fatal(err) } if err := ValidateID(image.ID); err != nil { t.Fatal(err) } if image.Comment != "Testing" { t.Fatalf("Wrong comment: should be '%s', not '%s'", "Testing", image.Comment) } if image.DockerVersion != VERSION { t.Fatalf("Wrong docker_version: should be '%s', not '%s'", VERSION, image.DockerVersion) } images, err := graph.Map() if err != nil { t.Fatal(err) } else if l := len(images); l != 1 { t.Fatalf("Wrong number of images. Should be %d, not %d", 1, l) } if images[image.ID] == nil { t.Fatalf("Could not find image with id %s", image.ID) } } func TestRegister(t *testing.T) { graph := tempGraph(t) defer os.RemoveAll(graph.Root) archive, err := fakeTar() if err != nil { t.Fatal(err) } image := &Image{ ID: GenerateID(), Comment: "testing", Created: time.Now(), } err = graph.Register(nil, archive, image) if err != nil { t.Fatal(err) } if images, err := graph.Map(); err != nil { t.Fatal(err) } else if l := len(images); l != 1 { t.Fatalf("Wrong number of images. Should be %d, not %d", 1, l) } if resultImg, err := graph.Get(image.ID); err != nil { t.Fatal(err) } else { if resultImg.ID != image.ID { t.Fatalf("Wrong image ID. Should be '%s', not '%s'", image.ID, resultImg.ID) } if resultImg.Comment != image.Comment { t.Fatalf("Wrong image comment. Should be '%s', not '%s'", image.Comment, resultImg.Comment) } } } func TestMount(t *testing.T) { graph := tempGraph(t) defer os.RemoveAll(graph.Root) archive, err := fakeTar() if err != nil { t.Fatal(err) } image, err := graph.Create(archive, nil, "Testing", "", nil) if err != nil { t.Fatal(err) } tmp, err := ioutil.TempDir("", "docker-test-graph-mount-") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) rootfs := path.Join(tmp, "rootfs") if err := os.MkdirAll(rootfs, 0700); err != nil { t.Fatal(err) } rw := path.Join(tmp, "rw") if err := os.MkdirAll(rw, 0700); err != nil { t.Fatal(err) } if err := image.Mount(rootfs, rw); err != nil { t.Fatal(err) } // FIXME: test for mount contents defer func() { if err := Unmount(rootfs); err != nil { t.Error(err) } }() } // Test that an image can be deleted by its shorthand prefix func TestDeletePrefix(t *testing.T) { graph := tempGraph(t) defer os.RemoveAll(graph.Root) img := createTestImage(graph, t) if err := graph.Delete(utils.TruncateID(img.ID)); err != nil { t.Fatal(err) } assertNImages(graph, t, 0) } func createTestImage(graph *Graph, t *testing.T) *Image { archive, err := fakeTar() if err != nil { t.Fatal(err) } img, err := graph.Create(archive, nil, "Test image", "", nil) if err != nil { t.Fatal(err) } return img } func TestDelete(t *testing.T) { graph := tempGraph(t) defer os.RemoveAll(graph.Root) archive, err := fakeTar() if err != nil { t.Fatal(err) } assertNImages(graph, t, 0) img, err := graph.Create(archive, nil, "Bla bla", "", nil) if err != nil { t.Fatal(err) } assertNImages(graph, t, 1) if err := graph.Delete(img.ID); err != nil { t.Fatal(err) } assertNImages(graph, t, 0) archive, err = fakeTar() if err != nil { t.Fatal(err) } // Test 2 create (same name) / 1 delete img1, err := graph.Create(archive, nil, "Testing", "", nil) if err != nil { t.Fatal(err) } archive, err = fakeTar() if err != nil { t.Fatal(err) } if _, err = graph.Create(archive, nil, "Testing", "", nil); err != nil { t.Fatal(err) } assertNImages(graph, t, 2) if err := graph.Delete(img1.ID); err != nil { t.Fatal(err) } assertNImages(graph, t, 1) // Test delete wrong name if err := graph.Delete("Not_foo"); err == nil { t.Fatalf("Deleting wrong ID should return an error") } assertNImages(graph, t, 1) archive, err = fakeTar() if err != nil { t.Fatal(err) } // Test delete twice (pull -> rm -> pull -> rm) if err := graph.Register(nil, archive, img1); err != nil { t.Fatal(err) } if err := graph.Delete(img1.ID); err != nil { t.Fatal(err) } assertNImages(graph, t, 1) } func TestByParent(t *testing.T) { archive1, _ := fakeTar() archive2, _ := fakeTar() archive3, _ := fakeTar() graph := tempGraph(t) defer os.RemoveAll(graph.Root) parentImage := &Image{ ID: GenerateID(), Comment: "parent", Created: time.Now(), Parent: "", } childImage1 := &Image{ ID: GenerateID(), Comment: "child1", Created: time.Now(), Parent: parentImage.ID, } childImage2 := &Image{ ID: GenerateID(), Comment: "child2", Created: time.Now(), Parent: parentImage.ID, } _ = graph.Register(nil, archive1, parentImage) _ = graph.Register(nil, archive2, childImage1) _ = graph.Register(nil, archive3, childImage2) byParent, err := graph.ByParent() if err != nil { t.Fatal(err) } numChildren := len(byParent[parentImage.ID]) if numChildren != 2 { t.Fatalf("Expected 2 children, found %d", numChildren) } } func assertNImages(graph *Graph, t *testing.T, n int) { if images, err := graph.Map(); err != nil { t.Fatal(err) } else if actualN := len(images); actualN != n { t.Fatalf("Expected %d images, found %d", n, actualN) } } /* * HELPER FUNCTIONS */ func tempGraph(t *testing.T) *Graph { tmp, err := ioutil.TempDir("", "docker-graph-") if err != nil { t.Fatal(err) } graph, err := NewGraph(tmp) if err != nil { t.Fatal(err) } return graph } func testArchive(t *testing.T) Archive { archive, err := fakeTar() if err != nil { t.Fatal(err) } return archive } func fakeTar() (io.Reader, error) { content := []byte("Hello world!\n") buf := new(bytes.Buffer) tw := tar.NewWriter(buf) for _, name := range []string{"/etc/postgres/postgres.conf", "/etc/passwd", "/var/log/postgres/postgres.conf"} { hdr := new(tar.Header) hdr.Size = int64(len(content)) hdr.Name = name if err := tw.WriteHeader(hdr); err != nil { return nil, err } tw.Write([]byte(content)) } tw.Close() return buf, nil }
graph_test.go
1
https://github.com/moby/moby/commit/e368c8bb01b3c52c8e4c334c3a7f32556af9d632
[ 0.9985253214836121, 0.042113419622182846, 0.00016298596165142953, 0.00030991656240075827, 0.17969562113285065 ]
{ "id": 2, "code_window": [ "\trw := path.Join(tmp, \"rw\")\n", "\tif err := os.MkdirAll(rw, 0700); err != nil {\n", "\t\tt.Fatal(err)\n", "\t}\n", "\tif err := image.Mount(rootfs, rw); err != nil {\n", "\t\tt.Fatal(err)\n", "\t}\n", "\t// FIXME: test for mount contents\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tif err := image.Mount(runtime, rootfs, rw, \"testing\"); err != nil {\n" ], "file_path": "graph_test.go", "type": "replace", "edit_start_line_idx": 146 }
# Hacking on Docker The hack/ directory holds information and tools for everyone involved in the process of creating and distributing Docker, specifically: ## Guides If you're a *contributor* or aspiring contributor, you should read CONTRIBUTORS.md. If you're a *maintainer* or aspiring maintainer, you should read MAINTAINERS.md. If you're a *packager* or aspiring packager, you should read PACKAGERS.md. If you're a maintainer in charge of a *release*, you should read RELEASE-CHECKLIST.md. ## Roadmap A high-level roadmap is available at ROADMAP.md. ## Build tools make.sh is the primary build tool for docker. It is used for compiling the official binary, running the test suite, and pushing releases.
hack/README.md
0
https://github.com/moby/moby/commit/e368c8bb01b3c52c8e4c334c3a7f32556af9d632
[ 0.00017065134306903929, 0.00016731633513700217, 0.00016386123024858534, 0.00016743643209338188, 0.0000027733522074413486 ]
{ "id": 2, "code_window": [ "\trw := path.Join(tmp, \"rw\")\n", "\tif err := os.MkdirAll(rw, 0700); err != nil {\n", "\t\tt.Fatal(err)\n", "\t}\n", "\tif err := image.Mount(rootfs, rw); err != nil {\n", "\t\tt.Fatal(err)\n", "\t}\n", "\t// FIXME: test for mount contents\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tif err := image.Mount(runtime, rootfs, rw, \"testing\"); err != nil {\n" ], "file_path": "graph_test.go", "type": "replace", "edit_start_line_idx": 146 }
:title: Registry API :description: API Documentation for Docker Registry :keywords: API, Docker, index, registry, REST, documentation =================== Docker Registry API =================== 1. Brief introduction ===================== - This is the REST API for the Docker Registry - It stores the images and the graph for a set of repositories - It does not have user accounts data - It has no notion of user accounts or authorization - It delegates authentication and authorization to the Index Auth service using tokens - It supports different storage backends (S3, cloud files, local FS) - It doesn’t have a local database - It will be open-sourced at some point We expect that there will be multiple registries out there. To help to grasp the context, here are some examples of registries: - **sponsor registry**: such a registry is provided by a third-party hosting infrastructure as a convenience for their customers and the docker community as a whole. Its costs are supported by the third party, but the management and operation of the registry are supported by dotCloud. It features read/write access, and delegates authentication and authorization to the Index. - **mirror registry**: such a registry is provided by a third-party hosting infrastructure but is targeted at their customers only. Some mechanism (unspecified to date) ensures that public images are pulled from a sponsor registry to the mirror registry, to make sure that the customers of the third-party provider can “docker pull” those images locally. - **vendor registry**: such a registry is provided by a software vendor, who wants to distribute docker images. It would be operated and managed by the vendor. Only users authorized by the vendor would be able to get write access. Some images would be public (accessible for anyone), others private (accessible only for authorized users). Authentication and authorization would be delegated to the Index. The goal of vendor registries is to let someone do “docker pull basho/riak1.3” and automatically push from the vendor registry (instead of a sponsor registry); i.e. get all the convenience of a sponsor registry, while retaining control on the asset distribution. - **private registry**: such a registry is located behind a firewall, or protected by an additional security layer (HTTP authorization, SSL client-side certificates, IP address authorization...). The registry is operated by a private entity, outside of dotCloud’s control. It can optionally delegate additional authorization to the Index, but it is not mandatory. .. note:: Mirror registries and private registries which do not use the Index don’t even need to run the registry code. They can be implemented by any kind of transport implementing HTTP GET and PUT. Read-only registries can be powered by a simple static HTTP server. .. note:: The latter implies that while HTTP is the protocol of choice for a registry, multiple schemes are possible (and in some cases, trivial): - HTTP with GET (and PUT for read-write registries); - local mount point; - remote docker addressed through SSH. The latter would only require two new commands in docker, e.g. “registryget” and “registryput”, wrapping access to the local filesystem (and optionally doing consistency checks). Authentication and authorization are then delegated to SSH (e.g. with public keys). 2. Endpoints ============ 2.1 Images ---------- Layer ***** .. http:get:: /v1/images/(image_id)/layer get image layer for a given ``image_id`` **Example Request**: .. sourcecode:: http GET /v1/images/088b4505aa3adc3d35e79c031fa126b403200f02f51920fbd9b7c503e87c7a2c/layer HTTP/1.1 Host: registry-1.docker.io Accept: application/json Content-Type: application/json Authorization: Token signature=123abc,repository="foo/bar",access=read :parameter image_id: the id for the layer you want to get **Example Response**: .. sourcecode:: http HTTP/1.1 200 Vary: Accept X-Docker-Registry-Version: 0.6.0 Cookie: (Cookie provided by the Registry) {layer binary data stream} :statuscode 200: OK :statuscode 401: Requires authorization :statuscode 404: Image not found .. http:put:: /v1/images/(image_id)/layer put image layer for a given ``image_id`` **Example Request**: .. sourcecode:: http PUT /v1/images/088b4505aa3adc3d35e79c031fa126b403200f02f51920fbd9b7c503e87c7a2c/layer HTTP/1.1 Host: registry-1.docker.io Transfer-Encoding: chunked Authorization: Token signature=123abc,repository="foo/bar",access=write {layer binary data stream} :parameter image_id: the id for the layer you want to get **Example Response**: .. sourcecode:: http HTTP/1.1 200 Vary: Accept Content-Type: application/json X-Docker-Registry-Version: 0.6.0 "" :statuscode 200: OK :statuscode 401: Requires authorization :statuscode 404: Image not found Image ***** .. http:put:: /v1/images/(image_id)/json put image for a given ``image_id`` **Example Request**: .. sourcecode:: http PUT /v1/images/088b4505aa3adc3d35e79c031fa126b403200f02f51920fbd9b7c503e87c7a2c/json HTTP/1.1 Host: registry-1.docker.io Accept: application/json Content-Type: application/json Cookie: (Cookie provided by the Registry) { id: "088b4505aa3adc3d35e79c031fa126b403200f02f51920fbd9b7c503e87c7a2c", parent: "aeee6396d62273d180a49c96c62e45438d87c7da4a5cf5d2be6bee4e21bc226f", created: "2013-04-30T17:46:10.843673+03:00", container: "8305672a76cc5e3d168f97221106ced35a76ec7ddbb03209b0f0d96bf74f6ef7", container_config: { Hostname: "host-test", User: "", Memory: 0, MemorySwap: 0, AttachStdin: false, AttachStdout: false, AttachStderr: false, PortSpecs: null, Tty: false, OpenStdin: false, StdinOnce: false, Env: null, Cmd: [ "/bin/bash", "-c", "apt-get -q -yy -f install libevent-dev" ], Dns: null, Image: "imagename/blah", Volumes: { }, VolumesFrom: "" }, docker_version: "0.1.7" } :parameter image_id: the id for the layer you want to get **Example Response**: .. sourcecode:: http HTTP/1.1 200 Vary: Accept Content-Type: application/json X-Docker-Registry-Version: 0.6.0 "" :statuscode 200: OK :statuscode 401: Requires authorization .. http:get:: /v1/images/(image_id)/json get image for a given ``image_id`` **Example Request**: .. sourcecode:: http GET /v1/images/088b4505aa3adc3d35e79c031fa126b403200f02f51920fbd9b7c503e87c7a2c/json HTTP/1.1 Host: registry-1.docker.io Accept: application/json Content-Type: application/json Cookie: (Cookie provided by the Registry) :parameter image_id: the id for the layer you want to get **Example Response**: .. sourcecode:: http HTTP/1.1 200 Vary: Accept Content-Type: application/json X-Docker-Registry-Version: 0.6.0 X-Docker-Size: 456789 X-Docker-Checksum: b486531f9a779a0c17e3ed29dae8f12c4f9e89cc6f0bc3c38722009fe6857087 { id: "088b4505aa3adc3d35e79c031fa126b403200f02f51920fbd9b7c503e87c7a2c", parent: "aeee6396d62273d180a49c96c62e45438d87c7da4a5cf5d2be6bee4e21bc226f", created: "2013-04-30T17:46:10.843673+03:00", container: "8305672a76cc5e3d168f97221106ced35a76ec7ddbb03209b0f0d96bf74f6ef7", container_config: { Hostname: "host-test", User: "", Memory: 0, MemorySwap: 0, AttachStdin: false, AttachStdout: false, AttachStderr: false, PortSpecs: null, Tty: false, OpenStdin: false, StdinOnce: false, Env: null, Cmd: [ "/bin/bash", "-c", "apt-get -q -yy -f install libevent-dev" ], Dns: null, Image: "imagename/blah", Volumes: { }, VolumesFrom: "" }, docker_version: "0.1.7" } :statuscode 200: OK :statuscode 401: Requires authorization :statuscode 404: Image not found Ancestry ******** .. http:get:: /v1/images/(image_id)/ancestry get ancestry for an image given an ``image_id`` **Example Request**: .. sourcecode:: http GET /v1/images/088b4505aa3adc3d35e79c031fa126b403200f02f51920fbd9b7c503e87c7a2c/ancestry HTTP/1.1 Host: registry-1.docker.io Accept: application/json Content-Type: application/json Cookie: (Cookie provided by the Registry) :parameter image_id: the id for the layer you want to get **Example Response**: .. sourcecode:: http HTTP/1.1 200 Vary: Accept Content-Type: application/json X-Docker-Registry-Version: 0.6.0 ["088b4502f51920fbd9b7c503e87c7a2c05aa3adc3d35e79c031fa126b403200f", "aeee63968d87c7da4a5cf5d2be6bee4e21bc226fd62273d180a49c96c62e4543", "bfa4c5326bc764280b0863b46a4b20d940bc1897ef9c1dfec060604bdc383280", "6ab5893c6927c15a15665191f2c6cf751f5056d8b95ceee32e43c5e8a3648544"] :statuscode 200: OK :statuscode 401: Requires authorization :statuscode 404: Image not found 2.2 Tags -------- .. http:get:: /v1/repositories/(namespace)/(repository)/tags get all of the tags for the given repo. **Example Request**: .. sourcecode:: http GET /v1/repositories/foo/bar/tags HTTP/1.1 Host: registry-1.docker.io Accept: application/json Content-Type: application/json X-Docker-Registry-Version: 0.6.0 Cookie: (Cookie provided by the Registry) :parameter namespace: namespace for the repo :parameter repository: name for the repo **Example Response**: .. sourcecode:: http HTTP/1.1 200 Vary: Accept Content-Type: application/json X-Docker-Registry-Version: 0.6.0 { "latest": "9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f", "0.1.1": "b486531f9a779a0c17e3ed29dae8f12c4f9e89cc6f0bc3c38722009fe6857087" } :statuscode 200: OK :statuscode 401: Requires authorization :statuscode 404: Repository not found .. http:get:: /v1/repositories/(namespace)/(repository)/tags/(tag) get a tag for the given repo. **Example Request**: .. sourcecode:: http GET /v1/repositories/foo/bar/tags/latest HTTP/1.1 Host: registry-1.docker.io Accept: application/json Content-Type: application/json X-Docker-Registry-Version: 0.6.0 Cookie: (Cookie provided by the Registry) :parameter namespace: namespace for the repo :parameter repository: name for the repo :parameter tag: name of tag you want to get **Example Response**: .. sourcecode:: http HTTP/1.1 200 Vary: Accept Content-Type: application/json X-Docker-Registry-Version: 0.6.0 "9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f" :statuscode 200: OK :statuscode 401: Requires authorization :statuscode 404: Tag not found .. http:delete:: /v1/repositories/(namespace)/(repository)/tags/(tag) delete the tag for the repo **Example Request**: .. sourcecode:: http DELETE /v1/repositories/foo/bar/tags/latest HTTP/1.1 Host: registry-1.docker.io Accept: application/json Content-Type: application/json Cookie: (Cookie provided by the Registry) :parameter namespace: namespace for the repo :parameter repository: name for the repo :parameter tag: name of tag you want to delete **Example Response**: .. sourcecode:: http HTTP/1.1 200 Vary: Accept Content-Type: application/json X-Docker-Registry-Version: 0.6.0 "" :statuscode 200: OK :statuscode 401: Requires authorization :statuscode 404: Tag not found .. http:put:: /v1/repositories/(namespace)/(repository)/tags/(tag) put a tag for the given repo. **Example Request**: .. sourcecode:: http PUT /v1/repositories/foo/bar/tags/latest HTTP/1.1 Host: registry-1.docker.io Accept: application/json Content-Type: application/json Cookie: (Cookie provided by the Registry) "9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f" :parameter namespace: namespace for the repo :parameter repository: name for the repo :parameter tag: name of tag you want to add **Example Response**: .. sourcecode:: http HTTP/1.1 200 Vary: Accept Content-Type: application/json X-Docker-Registry-Version: 0.6.0 "" :statuscode 200: OK :statuscode 400: Invalid data :statuscode 401: Requires authorization :statuscode 404: Image not found 2.3 Repositories ---------------- .. http:delete:: /v1/repositories/(namespace)/(repository)/ delete a repository **Example Request**: .. sourcecode:: http DELETE /v1/repositories/foo/bar/ HTTP/1.1 Host: registry-1.docker.io Accept: application/json Content-Type: application/json Cookie: (Cookie provided by the Registry) "" :parameter namespace: namespace for the repo :parameter repository: name for the repo **Example Response**: .. sourcecode:: http HTTP/1.1 200 Vary: Accept Content-Type: application/json X-Docker-Registry-Version: 0.6.0 "" :statuscode 200: OK :statuscode 401: Requires authorization :statuscode 404: Repository not found 2.4 Status ---------- .. http:get /v1/_ping Check status of the registry. This endpoint is also used to determine if the registry supports SSL. **Example Request**: .. sourcecode:: http GET /v1/_ping HTTP/1.1 Host: registry-1.docker.io Accept: application/json Content-Type: application/json "" :parameter namespace: namespace for the repo :parameter repository: name for the repo **Example Response**: .. sourcecode:: http HTTP/1.1 200 Vary: Accept Content-Type: application/json X-Docker-Registry-Version: 0.6.0 "" :statuscode 200: OK 3 Authorization =============== This is where we describe the authorization process, including the tokens and cookies. TODO: add more info.
docs/sources/api/registry_api.rst
0
https://github.com/moby/moby/commit/e368c8bb01b3c52c8e4c334c3a7f32556af9d632
[ 0.00018918848945759237, 0.00017077999655157328, 0.00016037476598285139, 0.00017091807967517525, 0.000004581183020491153 ]
{ "id": 2, "code_window": [ "\trw := path.Join(tmp, \"rw\")\n", "\tif err := os.MkdirAll(rw, 0700); err != nil {\n", "\t\tt.Fatal(err)\n", "\t}\n", "\tif err := image.Mount(rootfs, rw); err != nil {\n", "\t\tt.Fatal(err)\n", "\t}\n", "\t// FIXME: test for mount contents\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tif err := image.Mount(runtime, rootfs, rw, \"testing\"); err != nil {\n" ], "file_path": "graph_test.go", "type": "replace", "edit_start_line_idx": 146 }
:title: Registry Documentation :description: Documentation for docker Registry and Registry API :keywords: docker, registry, api, index .. _registryindexspec: ===================== Registry & Index Spec ===================== 1. The 3 roles =============== 1.1 Index --------- The Index is responsible for centralizing information about: - User accounts - Checksums of the images - Public namespaces The Index has different components: - Web UI - Meta-data store (comments, stars, list public repositories) - Authentication service - Tokenization The index is authoritative for those information. We expect that there will be only one instance of the index, run and managed by dotCloud. 1.2 Registry ------------ - It stores the images and the graph for a set of repositories - It does not have user accounts data - It has no notion of user accounts or authorization - It delegates authentication and authorization to the Index Auth service using tokens - It supports different storage backends (S3, cloud files, local FS) - It doesn’t have a local database - It will be open-sourced at some point We expect that there will be multiple registries out there. To help to grasp the context, here are some examples of registries: - **sponsor registry**: such a registry is provided by a third-party hosting infrastructure as a convenience for their customers and the docker community as a whole. Its costs are supported by the third party, but the management and operation of the registry are supported by dotCloud. It features read/write access, and delegates authentication and authorization to the Index. - **mirror registry**: such a registry is provided by a third-party hosting infrastructure but is targeted at their customers only. Some mechanism (unspecified to date) ensures that public images are pulled from a sponsor registry to the mirror registry, to make sure that the customers of the third-party provider can “docker pull” those images locally. - **vendor registry**: such a registry is provided by a software vendor, who wants to distribute docker images. It would be operated and managed by the vendor. Only users authorized by the vendor would be able to get write access. Some images would be public (accessible for anyone), others private (accessible only for authorized users). Authentication and authorization would be delegated to the Index. The goal of vendor registries is to let someone do “docker pull basho/riak1.3” and automatically push from the vendor registry (instead of a sponsor registry); i.e. get all the convenience of a sponsor registry, while retaining control on the asset distribution. - **private registry**: such a registry is located behind a firewall, or protected by an additional security layer (HTTP authorization, SSL client-side certificates, IP address authorization...). The registry is operated by a private entity, outside of dotCloud’s control. It can optionally delegate additional authorization to the Index, but it is not mandatory. .. note:: Mirror registries and private registries which do not use the Index don’t even need to run the registry code. They can be implemented by any kind of transport implementing HTTP GET and PUT. Read-only registries can be powered by a simple static HTTP server. .. note:: The latter implies that while HTTP is the protocol of choice for a registry, multiple schemes are possible (and in some cases, trivial): - HTTP with GET (and PUT for read-write registries); - local mount point; - remote docker addressed through SSH. The latter would only require two new commands in docker, e.g. “registryget” and “registryput”, wrapping access to the local filesystem (and optionally doing consistency checks). Authentication and authorization are then delegated to SSH (e.g. with public keys). 1.3 Docker ---------- On top of being a runtime for LXC, Docker is the Registry client. It supports: - Push / Pull on the registry - Client authentication on the Index 2. Workflow =========== 2.1 Pull -------- .. image:: /static_files/docker_pull_chart.png 1. Contact the Index to know where I should download “samalba/busybox” 2. Index replies: a. “samalba/busybox” is on Registry A b. here are the checksums for “samalba/busybox” (for all layers) c. token 3. Contact Registry A to receive the layers for “samalba/busybox” (all of them to the base image). Registry A is authoritative for “samalba/busybox” but keeps a copy of all inherited layers and serve them all from the same location. 4. registry contacts index to verify if token/user is allowed to download images 5. Index returns true/false lettings registry know if it should proceed or error out 6. Get the payload for all layers It’s possible to run docker pull \https://<registry>/repositories/samalba/busybox. In this case, docker bypasses the Index. However the security is not guaranteed (in case Registry A is corrupted) because there won’t be any checksum checks. Currently registry redirects to s3 urls for downloads, going forward all downloads need to be streamed through the registry. The Registry will then abstract the calls to S3 by a top-level class which implements sub-classes for S3 and local storage. Token is only returned when the 'X-Docker-Token' header is sent with request. Basic Auth is required to pull private repos. Basic auth isn't required for pulling public repos, but if one is provided, it needs to be valid and for an active account. API (pulling repository foo/bar): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1. (Docker -> Index) GET /v1/repositories/foo/bar/images **Headers**: Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== X-Docker-Token: true **Action**: (looking up the foo/bar in db and gets images and checksums for that repo (all if no tag is specified, if tag, only checksums for those tags) see part 4.4.1) 2. (Index -> Docker) HTTP 200 OK **Headers**: - Authorization: Token signature=123abc,repository=”foo/bar”,access=write - X-Docker-Endpoints: registry.docker.io [, registry2.docker.io] **Body**: Jsonified checksums (see part 4.4.1) 3. (Docker -> Registry) GET /v1/repositories/foo/bar/tags/latest **Headers**: Authorization: Token signature=123abc,repository=”foo/bar”,access=write 4. (Registry -> Index) GET /v1/repositories/foo/bar/images **Headers**: Authorization: Token signature=123abc,repository=”foo/bar”,access=read **Body**: <ids and checksums in payload> **Action**: ( Lookup token see if they have access to pull.) If good: HTTP 200 OK Index will invalidate the token If bad: HTTP 401 Unauthorized 5. (Docker -> Registry) GET /v1/images/928374982374/ancestry **Action**: (for each image id returned in the registry, fetch /json + /layer) .. note:: If someone makes a second request, then we will always give a new token, never reuse tokens. 2.2 Push -------- .. image:: /static_files/docker_push_chart.png 1. Contact the index to allocate the repository name “samalba/busybox” (authentication required with user credentials) 2. If authentication works and namespace available, “samalba/busybox” is allocated and a temporary token is returned (namespace is marked as initialized in index) 3. Push the image on the registry (along with the token) 4. Registry A contacts the Index to verify the token (token must corresponds to the repository name) 5. Index validates the token. Registry A starts reading the stream pushed by docker and store the repository (with its images) 6. docker contacts the index to give checksums for upload images .. note:: **It’s possible not to use the Index at all!** In this case, a deployed version of the Registry is deployed to store and serve images. Those images are not authenticated and the security is not guaranteed. .. note:: **Index can be replaced!** For a private Registry deployed, a custom Index can be used to serve and validate token according to different policies. Docker computes the checksums and submit them to the Index at the end of the push. When a repository name does not have checksums on the Index, it means that the push is in progress (since checksums are submitted at the end). API (pushing repos foo/bar): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1. (Docker -> Index) PUT /v1/repositories/foo/bar/ **Headers**: Authorization: Basic sdkjfskdjfhsdkjfh== X-Docker-Token: true **Action**:: - in index, we allocated a new repository, and set to initialized **Body**:: (The body contains the list of images that are going to be pushed, with empty checksums. The checksums will be set at the end of the push):: [{“id”: “9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f”}] 2. (Index -> Docker) 200 Created **Headers**: - WWW-Authenticate: Token signature=123abc,repository=”foo/bar”,access=write - X-Docker-Endpoints: registry.docker.io [, registry2.docker.io] 3. (Docker -> Registry) PUT /v1/images/98765432_parent/json **Headers**: Authorization: Token signature=123abc,repository=”foo/bar”,access=write 4. (Registry->Index) GET /v1/repositories/foo/bar/images **Headers**: Authorization: Token signature=123abc,repository=”foo/bar”,access=write **Action**:: - Index: will invalidate the token. - Registry: grants a session (if token is approved) and fetches the images id 5. (Docker -> Registry) PUT /v1/images/98765432_parent/json **Headers**:: - Authorization: Token signature=123abc,repository=”foo/bar”,access=write - Cookie: (Cookie provided by the Registry) 6. (Docker -> Registry) PUT /v1/images/98765432/json **Headers**: Cookie: (Cookie provided by the Registry) 7. (Docker -> Registry) PUT /v1/images/98765432_parent/layer **Headers**: Cookie: (Cookie provided by the Registry) 8. (Docker -> Registry) PUT /v1/images/98765432/layer **Headers**: X-Docker-Checksum: sha256:436745873465fdjkhdfjkgh 9. (Docker -> Registry) PUT /v1/repositories/foo/bar/tags/latest **Headers**: Cookie: (Cookie provided by the Registry) **Body**: “98765432” 10. (Docker -> Index) PUT /v1/repositories/foo/bar/images **Headers**: Authorization: Basic 123oislifjsldfj== X-Docker-Endpoints: registry1.docker.io (no validation on this right now) **Body**: (The image, id’s, tags and checksums) [{“id”: “9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f”, “checksum”: “b486531f9a779a0c17e3ed29dae8f12c4f9e89cc6f0bc3c38722009fe6857087”}] **Return** HTTP 204 .. note:: If push fails and they need to start again, what happens in the index, there will already be a record for the namespace/name, but it will be initialized. Should we allow it, or mark as name already used? One edge case could be if someone pushes the same thing at the same time with two different shells. If it's a retry on the Registry, Docker has a cookie (provided by the registry after token validation). So the Index won’t have to provide a new token. 2.3 Delete ---------- If you need to delete something from the index or registry, we need a nice clean way to do that. Here is the workflow. 1. Docker contacts the index to request a delete of a repository “samalba/busybox” (authentication required with user credentials) 2. If authentication works and repository is valid, “samalba/busybox” is marked as deleted and a temporary token is returned 3. Send a delete request to the registry for the repository (along with the token) 4. Registry A contacts the Index to verify the token (token must corresponds to the repository name) 5. Index validates the token. Registry A deletes the repository and everything associated to it. 6. docker contacts the index to let it know it was removed from the registry, the index removes all records from the database. .. note:: The Docker client should present an "Are you sure?" prompt to confirm the deletion before starting the process. Once it starts it can't be undone. API (deleting repository foo/bar): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1. (Docker -> Index) DELETE /v1/repositories/foo/bar/ **Headers**: Authorization: Basic sdkjfskdjfhsdkjfh== X-Docker-Token: true **Action**:: - in index, we make sure it is a valid repository, and set to deleted (logically) **Body**:: Empty 2. (Index -> Docker) 202 Accepted **Headers**: - WWW-Authenticate: Token signature=123abc,repository=”foo/bar”,access=delete - X-Docker-Endpoints: registry.docker.io [, registry2.docker.io] # list of endpoints where this repo lives. 3. (Docker -> Registry) DELETE /v1/repositories/foo/bar/ **Headers**: Authorization: Token signature=123abc,repository=”foo/bar”,access=delete 4. (Registry->Index) PUT /v1/repositories/foo/bar/auth **Headers**: Authorization: Token signature=123abc,repository=”foo/bar”,access=delete **Action**:: - Index: will invalidate the token. - Registry: deletes the repository (if token is approved) 5. (Registry -> Docker) 200 OK 200 If success 403 if forbidden 400 if bad request 404 if repository isn't found 6. (Docker -> Index) DELETE /v1/repositories/foo/bar/ **Headers**: Authorization: Basic 123oislifjsldfj== X-Docker-Endpoints: registry-1.docker.io (no validation on this right now) **Body**: Empty **Return** HTTP 200 3. How to use the Registry in standalone mode ============================================= The Index has two main purposes (along with its fancy social features): - Resolve short names (to avoid passing absolute URLs all the time) - username/projectname -> \https://registry.docker.io/users/<username>/repositories/<projectname>/ - team/projectname -> \https://registry.docker.io/team/<team>/repositories/<projectname>/ - Authenticate a user as a repos owner (for a central referenced repository) 3.1 Without an Index -------------------- Using the Registry without the Index can be useful to store the images on a private network without having to rely on an external entity controlled by dotCloud. In this case, the registry will be launched in a special mode (--standalone? --no-index?). In this mode, the only thing which changes is that Registry will never contact the Index to verify a token. It will be the Registry owner responsibility to authenticate the user who pushes (or even pulls) an image using any mechanism (HTTP auth, IP based, etc...). In this scenario, the Registry is responsible for the security in case of data corruption since the checksums are not delivered by a trusted entity. As hinted previously, a standalone registry can also be implemented by any HTTP server handling GET/PUT requests (or even only GET requests if no write access is necessary). 3.2 With an Index ----------------- The Index data needed by the Registry are simple: - Serve the checksums - Provide and authorize a Token In the scenario of a Registry running on a private network with the need of centralizing and authorizing, it’s easy to use a custom Index. The only challenge will be to tell Docker to contact (and trust) this custom Index. Docker will be configurable at some point to use a specific Index, it’ll be the private entity responsibility (basically the organization who uses Docker in a private environment) to maintain the Index and the Docker’s configuration among its consumers. 4. The API ========== The first version of the api is available here: https://github.com/jpetazzo/docker/blob/acd51ecea8f5d3c02b00a08176171c59442df8b3/docs/images-repositories-push-pull.md 4.1 Images ---------- The format returned in the images is not defined here (for layer and json), basically because Registry stores exactly the same kind of information as Docker uses to manage them. The format of ancestry is a line-separated list of image ids, in age order. I.e. the image’s parent is on the last line, the parent of the parent on the next-to-last line, etc.; if the image has no parent, the file is empty. GET /v1/images/<image_id>/layer PUT /v1/images/<image_id>/layer GET /v1/images/<image_id>/json PUT /v1/images/<image_id>/json GET /v1/images/<image_id>/ancestry PUT /v1/images/<image_id>/ancestry 4.2 Users --------- 4.2.1 Create a user (Index) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ POST /v1/users **Body**: {"email": "[email protected]", "password": "toto42", "username": "foobar"'} **Validation**: - **username**: min 4 character, max 30 characters, must match the regular expression [a-z0-9\_]. - **password**: min 5 characters **Valid**: return HTTP 200 Errors: HTTP 400 (we should create error codes for possible errors) - invalid json - missing field - wrong format (username, password, email, etc) - forbidden name - name already exists .. note:: A user account will be valid only if the email has been validated (a validation link is sent to the email address). 4.2.2 Update a user (Index) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ PUT /v1/users/<username> **Body**: {"password": "toto"} .. note:: We can also update email address, if they do, they will need to reverify their new email address. 4.2.3 Login (Index) ^^^^^^^^^^^^^^^^^^^ Does nothing else but asking for a user authentication. Can be used to validate credentials. HTTP Basic Auth for now, maybe change in future. GET /v1/users **Return**: - Valid: HTTP 200 - Invalid login: HTTP 401 - Account inactive: HTTP 403 Account is not Active 4.3 Tags (Registry) ------------------- The Registry does not know anything about users. Even though repositories are under usernames, it’s just a namespace for the registry. Allowing us to implement organizations or different namespaces per user later, without modifying the Registry’s API. The following naming restrictions apply: - Namespaces must match the same regular expression as usernames (See 4.2.1.) - Repository names must match the regular expression [a-zA-Z0-9-_.] 4.3.1 Get all tags ^^^^^^^^^^^^^^^^^^ GET /v1/repositories/<namespace>/<repository_name>/tags **Return**: HTTP 200 { "latest": "9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f", “0.1.1”: “b486531f9a779a0c17e3ed29dae8f12c4f9e89cc6f0bc3c38722009fe6857087” } 4.3.2 Read the content of a tag (resolve the image id) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ GET /v1/repositories/<namespace>/<repo_name>/tags/<tag> **Return**: "9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f" 4.3.3 Delete a tag (registry) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ DELETE /v1/repositories/<namespace>/<repo_name>/tags/<tag> 4.4 Images (Index) ------------------ For the Index to “resolve” the repository name to a Registry location, it uses the X-Docker-Endpoints header. In other terms, this requests always add a “X-Docker-Endpoints” to indicate the location of the registry which hosts this repository. 4.4.1 Get the images ^^^^^^^^^^^^^^^^^^^^^ GET /v1/repositories/<namespace>/<repo_name>/images **Return**: HTTP 200 [{“id”: “9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f”, “checksum”: “md5:b486531f9a779a0c17e3ed29dae8f12c4f9e89cc6f0bc3c38722009fe6857087”}] 4.4.2 Add/update the images ^^^^^^^^^^^^^^^^^^^^^^^^^^^ You always add images, you never remove them. PUT /v1/repositories/<namespace>/<repo_name>/images **Body**: [ {“id”: “9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f”, “checksum”: “sha256:b486531f9a779a0c17e3ed29dae8f12c4f9e89cc6f0bc3c38722009fe6857087”} ] **Return** 204 4.5 Repositories ---------------- 4.5.1 Remove a Repository (Registry) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ DELETE /v1/repositories/<namespace>/<repo_name> Return 200 OK 4.5.2 Remove a Repository (Index) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This starts the delete process. see 2.3 for more details. DELETE /v1/repositories/<namespace>/<repo_name> Return 202 OK 5. Chaining Registries ====================== It’s possible to chain Registries server for several reasons: - Load balancing - Delegate the next request to another server When a Registry is a reference for a repository, it should host the entire images chain in order to avoid breaking the chain during the download. The Index and Registry use this mechanism to redirect on one or the other. Example with an image download: On every request, a special header can be returned: X-Docker-Endpoints: server1,server2 On the next request, the client will always pick a server from this list. 6. Authentication & Authorization ================================= 6.1 On the Index ----------------- The Index supports both “Basic” and “Token” challenges. Usually when there is a “401 Unauthorized”, the Index replies this:: 401 Unauthorized WWW-Authenticate: Basic realm="auth required",Token You have 3 options: 1. Provide user credentials and ask for a token **Header**: - Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== - X-Docker-Token: true In this case, along with the 200 response, you’ll get a new token (if user auth is ok): If authorization isn't correct you get a 401 response. If account isn't active you will get a 403 response. **Response**: - 200 OK - X-Docker-Token: Token signature=123abc,repository=”foo/bar”,access=read 2. Provide user credentials only **Header**: Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== 3. Provide Token **Header**: Authorization: Token signature=123abc,repository=”foo/bar”,access=read 6.2 On the Registry ------------------- The Registry only supports the Token challenge:: 401 Unauthorized WWW-Authenticate: Token The only way is to provide a token on “401 Unauthorized” responses:: Authorization: Token signature=123abc,repository=”foo/bar”,access=read Usually, the Registry provides a Cookie when a Token verification succeeded. Every time the Registry passes a Cookie, you have to pass it back the same cookie.:: 200 OK Set-Cookie: session="wD/J7LqL5ctqw8haL10vgfhrb2Q=?foo=UydiYXInCnAxCi4=&timestamp=RjEzNjYzMTQ5NDcuNDc0NjQzCi4="; Path=/; HttpOnly Next request:: GET /(...) Cookie: session="wD/J7LqL5ctqw8haL10vgfhrb2Q=?foo=UydiYXInCnAxCi4=&timestamp=RjEzNjYzMTQ5NDcuNDc0NjQzCi4=" 7 Document Version ==================== - 1.0 : May 6th 2013 : initial release - 1.1 : June 1st 2013 : Added Delete Repository and way to handle new source namespace.
docs/sources/api/registry_index_spec.rst
0
https://github.com/moby/moby/commit/e368c8bb01b3c52c8e4c334c3a7f32556af9d632
[ 0.00022081827046349645, 0.00017013699107337743, 0.00016037476598285139, 0.00017020769882947206, 0.0000077476388469222 ]
{ "id": 3, "code_window": [ "\t}\n", "\treturn Tar(layerPath, compression)\n", "}\n", "\n", "func (image *Image) Mount(root, rw string) error {\n", "\tif mounted, err := Mounted(root); err != nil {\n", "\t\treturn err\n", "\t} else if mounted {\n", "\t\treturn fmt.Errorf(\"%s is already mounted\", root)\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "func (image *Image) Mount(runtime *Runtime, root, rw string, id string) error {\n" ], "file_path": "image.go", "type": "replace", "edit_start_line_idx": 172 }
package docker import ( "encoding/json" "errors" "flag" "fmt" "github.com/dotcloud/docker/term" "github.com/dotcloud/docker/utils" "github.com/kr/pty" "io" "io/ioutil" "log" "net" "os" "os/exec" "path" "path/filepath" "strconv" "strings" "syscall" "time" ) type Container struct { root string ID string Created time.Time Path string Args []string Config *Config State State Image string network *NetworkInterface NetworkSettings *NetworkSettings SysInitPath string ResolvConfPath string HostnamePath string HostsPath string cmd *exec.Cmd stdout *utils.WriteBroadcaster stderr *utils.WriteBroadcaster stdin io.ReadCloser stdinPipe io.WriteCloser ptyMaster io.Closer runtime *Runtime waitLock chan struct{} Volumes map[string]string // Store rw/ro in a separate structure to preserve reverse-compatibility on-disk. // Easier than migrating older container configs :) VolumesRW map[string]bool } type Config struct { Hostname string Domainname string User string Memory int64 // Memory limit (in bytes) MemorySwap int64 // Total memory usage (memory + swap); set `-1' to disable swap CpuShares int64 // CPU shares (relative weight vs. other containers) AttachStdin bool AttachStdout bool AttachStderr bool PortSpecs []string Tty bool // Attach standard streams to a tty, including stdin if it is not closed. OpenStdin bool // Open stdin StdinOnce bool // If true, close stdin after the 1 attached client disconnects. Env []string Cmd []string Dns []string Image string // Name of the image as it was passed by the operator (eg. could be symbolic) Volumes map[string]struct{} VolumesFrom string WorkingDir string Entrypoint []string NetworkDisabled bool Privileged bool } type HostConfig struct { Binds []string ContainerIDFile string LxcConf []KeyValuePair } type BindMap struct { SrcPath string DstPath string Mode string } var ( ErrInvaidWorikingDirectory = errors.New("The working directory is invalid. It needs to be an absolute path.") ) type KeyValuePair struct { Key string Value string } func ParseRun(args []string, capabilities *Capabilities) (*Config, *HostConfig, *flag.FlagSet, error) { cmd := Subcmd("run", "[OPTIONS] IMAGE [COMMAND] [ARG...]", "Run a command in a new container") if os.Getenv("TEST") != "" { cmd.SetOutput(ioutil.Discard) cmd.Usage = nil } flHostname := cmd.String("h", "", "Container host name") flWorkingDir := cmd.String("w", "", "Working directory inside the container") flUser := cmd.String("u", "", "Username or UID") flDetach := cmd.Bool("d", false, "Detached mode: Run container in the background, print new container id") flAttach := NewAttachOpts() cmd.Var(flAttach, "a", "Attach to stdin, stdout or stderr.") flStdin := cmd.Bool("i", false, "Keep stdin open even if not attached") flTty := cmd.Bool("t", false, "Allocate a pseudo-tty") flMemory := cmd.Int64("m", 0, "Memory limit (in bytes)") flContainerIDFile := cmd.String("cidfile", "", "Write the container ID to the file") flNetwork := cmd.Bool("n", true, "Enable networking for this container") flPrivileged := cmd.Bool("privileged", false, "Give extended privileges to this container") flAutoRemove := cmd.Bool("rm", false, "Automatically remove the container when it exits (incompatible with -d)") if capabilities != nil && *flMemory > 0 && !capabilities.MemoryLimit { //fmt.Fprintf(stdout, "WARNING: Your kernel does not support memory limit capabilities. Limitation discarded.\n") *flMemory = 0 } flCpuShares := cmd.Int64("c", 0, "CPU shares (relative weight)") var flPorts ListOpts cmd.Var(&flPorts, "p", "Expose a container's port to the host (use 'docker port' to see the actual mapping)") var flEnv ListOpts cmd.Var(&flEnv, "e", "Set environment variables") var flDns ListOpts cmd.Var(&flDns, "dns", "Set custom dns servers") flVolumes := NewPathOpts() cmd.Var(flVolumes, "v", "Bind mount a volume (e.g. from the host: -v /host:/container, from docker: -v /container)") var flVolumesFrom ListOpts cmd.Var(&flVolumesFrom, "volumes-from", "Mount volumes from the specified container") flEntrypoint := cmd.String("entrypoint", "", "Overwrite the default entrypoint of the image") var flLxcOpts ListOpts cmd.Var(&flLxcOpts, "lxc-conf", "Add custom lxc options -lxc-conf=\"lxc.cgroup.cpuset.cpus = 0,1\"") if err := cmd.Parse(args); err != nil { return nil, nil, cmd, err } if *flDetach && len(flAttach) > 0 { return nil, nil, cmd, fmt.Errorf("Conflicting options: -a and -d") } if *flWorkingDir != "" && !path.IsAbs(*flWorkingDir) { return nil, nil, cmd, ErrInvaidWorikingDirectory } // If neither -d or -a are set, attach to everything by default if len(flAttach) == 0 && !*flDetach { if !*flDetach { flAttach.Set("stdout") flAttach.Set("stderr") if *flStdin { flAttach.Set("stdin") } } } if *flDetach && *flAutoRemove { return nil, nil, cmd, fmt.Errorf("Conflicting options: -rm and -d") } var binds []string // add any bind targets to the list of container volumes for bind := range flVolumes { arr := strings.Split(bind, ":") if len(arr) > 1 { dstDir := arr[1] flVolumes[dstDir] = struct{}{} binds = append(binds, bind) delete(flVolumes, bind) } } parsedArgs := cmd.Args() runCmd := []string{} entrypoint := []string{} image := "" if len(parsedArgs) >= 1 { image = cmd.Arg(0) } if len(parsedArgs) > 1 { runCmd = parsedArgs[1:] } if *flEntrypoint != "" { entrypoint = []string{*flEntrypoint} } var lxcConf []KeyValuePair lxcConf, err := parseLxcConfOpts(flLxcOpts) if err != nil { return nil, nil, cmd, err } hostname := *flHostname domainname := "" parts := strings.SplitN(hostname, ".", 2) if len(parts) > 1 { hostname = parts[0] domainname = parts[1] } config := &Config{ Hostname: hostname, Domainname: domainname, PortSpecs: flPorts, User: *flUser, Tty: *flTty, NetworkDisabled: !*flNetwork, OpenStdin: *flStdin, Memory: *flMemory, CpuShares: *flCpuShares, AttachStdin: flAttach.Get("stdin"), AttachStdout: flAttach.Get("stdout"), AttachStderr: flAttach.Get("stderr"), Env: flEnv, Cmd: runCmd, Dns: flDns, Image: image, Volumes: flVolumes, VolumesFrom: strings.Join(flVolumesFrom, ","), Entrypoint: entrypoint, Privileged: *flPrivileged, WorkingDir: *flWorkingDir, } hostConfig := &HostConfig{ Binds: binds, ContainerIDFile: *flContainerIDFile, LxcConf: lxcConf, } if capabilities != nil && *flMemory > 0 && !capabilities.SwapLimit { //fmt.Fprintf(stdout, "WARNING: Your kernel does not support swap limit capabilities. Limitation discarded.\n") config.MemorySwap = -1 } // When allocating stdin in attached mode, close stdin at client disconnect if config.OpenStdin && config.AttachStdin { config.StdinOnce = true } return config, hostConfig, cmd, nil } type PortMapping map[string]string type NetworkSettings struct { IPAddress string IPPrefixLen int Gateway string Bridge string PortMapping map[string]PortMapping } // returns a more easy to process description of the port mapping defined in the settings func (settings *NetworkSettings) PortMappingAPI() []APIPort { var mapping []APIPort for private, public := range settings.PortMapping["Tcp"] { pubint, _ := strconv.ParseInt(public, 0, 0) privint, _ := strconv.ParseInt(private, 0, 0) mapping = append(mapping, APIPort{ PrivatePort: privint, PublicPort: pubint, Type: "tcp", }) } for private, public := range settings.PortMapping["Udp"] { pubint, _ := strconv.ParseInt(public, 0, 0) privint, _ := strconv.ParseInt(private, 0, 0) mapping = append(mapping, APIPort{ PrivatePort: privint, PublicPort: pubint, Type: "udp", }) } return mapping } // Inject the io.Reader at the given path. Note: do not close the reader func (container *Container) Inject(file io.Reader, pth string) error { // Make sure the directory exists if err := os.MkdirAll(path.Join(container.rwPath(), path.Dir(pth)), 0755); err != nil { return err } // FIXME: Handle permissions/already existing dest dest, err := os.Create(path.Join(container.rwPath(), pth)) if err != nil { return err } if _, err := io.Copy(dest, file); err != nil { return err } return nil } func (container *Container) Cmd() *exec.Cmd { return container.cmd } func (container *Container) When() time.Time { return container.Created } func (container *Container) FromDisk() error { data, err := ioutil.ReadFile(container.jsonPath()) if err != nil { return err } // Load container settings // udp broke compat of docker.PortMapping, but it's not used when loading a container, we can skip it if err := json.Unmarshal(data, container); err != nil && !strings.Contains(err.Error(), "docker.PortMapping") { return err } return nil } func (container *Container) ToDisk() (err error) { data, err := json.Marshal(container) if err != nil { return } return ioutil.WriteFile(container.jsonPath(), data, 0666) } func (container *Container) ReadHostConfig() (*HostConfig, error) { data, err := ioutil.ReadFile(container.hostConfigPath()) if err != nil { return &HostConfig{}, err } hostConfig := &HostConfig{} if err := json.Unmarshal(data, hostConfig); err != nil { return &HostConfig{}, err } return hostConfig, nil } func (container *Container) SaveHostConfig(hostConfig *HostConfig) (err error) { data, err := json.Marshal(hostConfig) if err != nil { return } return ioutil.WriteFile(container.hostConfigPath(), data, 0666) } func (container *Container) generateLXCConfig(hostConfig *HostConfig) error { fo, err := os.Create(container.lxcConfigPath()) if err != nil { return err } defer fo.Close() if err := LxcTemplateCompiled.Execute(fo, container); err != nil { return err } if hostConfig != nil { if err := LxcHostConfigTemplateCompiled.Execute(fo, hostConfig); err != nil { return err } } return nil } func (container *Container) startPty() error { ptyMaster, ptySlave, err := pty.Open() if err != nil { return err } container.ptyMaster = ptyMaster container.cmd.Stdout = ptySlave container.cmd.Stderr = ptySlave // Copy the PTYs to our broadcasters go func() { defer container.stdout.CloseWriters() utils.Debugf("[startPty] Begin of stdout pipe") io.Copy(container.stdout, ptyMaster) utils.Debugf("[startPty] End of stdout pipe") }() // stdin if container.Config.OpenStdin { container.cmd.Stdin = ptySlave container.cmd.SysProcAttr.Setctty = true go func() { defer container.stdin.Close() utils.Debugf("[startPty] Begin of stdin pipe") io.Copy(ptyMaster, container.stdin) utils.Debugf("[startPty] End of stdin pipe") }() } if err := container.cmd.Start(); err != nil { return err } ptySlave.Close() return nil } func (container *Container) start() error { container.cmd.Stdout = container.stdout container.cmd.Stderr = container.stderr if container.Config.OpenStdin { stdin, err := container.cmd.StdinPipe() if err != nil { return err } go func() { defer stdin.Close() utils.Debugf("Begin of stdin pipe [start]") io.Copy(stdin, container.stdin) utils.Debugf("End of stdin pipe [start]") }() } return container.cmd.Start() } func (container *Container) Attach(stdin io.ReadCloser, stdinCloser io.Closer, stdout io.Writer, stderr io.Writer) chan error { var cStdout, cStderr io.ReadCloser var nJobs int errors := make(chan error, 3) if stdin != nil && container.Config.OpenStdin { nJobs += 1 if cStdin, err := container.StdinPipe(); err != nil { errors <- err } else { go func() { utils.Debugf("[start] attach stdin\n") defer utils.Debugf("[end] attach stdin\n") // No matter what, when stdin is closed (io.Copy unblock), close stdout and stderr if container.Config.StdinOnce && !container.Config.Tty { defer cStdin.Close() } else { if cStdout != nil { defer cStdout.Close() } if cStderr != nil { defer cStderr.Close() } } if container.Config.Tty { _, err = utils.CopyEscapable(cStdin, stdin) } else { _, err = io.Copy(cStdin, stdin) } if err != nil { utils.Debugf("[error] attach stdin: %s\n", err) } // Discard error, expecting pipe error errors <- nil }() } } if stdout != nil { nJobs += 1 if p, err := container.StdoutPipe(); err != nil { errors <- err } else { cStdout = p go func() { utils.Debugf("[start] attach stdout\n") defer utils.Debugf("[end] attach stdout\n") // If we are in StdinOnce mode, then close stdin if container.Config.StdinOnce && stdin != nil { defer stdin.Close() } if stdinCloser != nil { defer stdinCloser.Close() } _, err := io.Copy(stdout, cStdout) if err != nil { utils.Debugf("[error] attach stdout: %s\n", err) } errors <- err }() } } else { go func() { if stdinCloser != nil { defer stdinCloser.Close() } if cStdout, err := container.StdoutPipe(); err != nil { utils.Debugf("Error stdout pipe") } else { io.Copy(&utils.NopWriter{}, cStdout) } }() } if stderr != nil { nJobs += 1 if p, err := container.StderrPipe(); err != nil { errors <- err } else { cStderr = p go func() { utils.Debugf("[start] attach stderr\n") defer utils.Debugf("[end] attach stderr\n") // If we are in StdinOnce mode, then close stdin if container.Config.StdinOnce && stdin != nil { defer stdin.Close() } if stdinCloser != nil { defer stdinCloser.Close() } _, err := io.Copy(stderr, cStderr) if err != nil { utils.Debugf("[error] attach stderr: %s\n", err) } errors <- err }() } } else { go func() { if stdinCloser != nil { defer stdinCloser.Close() } if cStderr, err := container.StderrPipe(); err != nil { utils.Debugf("Error stdout pipe") } else { io.Copy(&utils.NopWriter{}, cStderr) } }() } return utils.Go(func() error { if cStdout != nil { defer cStdout.Close() } if cStderr != nil { defer cStderr.Close() } // FIXME: how do clean up the stdin goroutine without the unwanted side effect // of closing the passed stdin? Add an intermediary io.Pipe? for i := 0; i < nJobs; i += 1 { utils.Debugf("Waiting for job %d/%d\n", i+1, nJobs) if err := <-errors; err != nil { utils.Debugf("Job %d returned error %s. Aborting all jobs\n", i+1, err) return err } utils.Debugf("Job %d completed successfully\n", i+1) } utils.Debugf("All jobs completed successfully\n") return nil }) } func (container *Container) Start(hostConfig *HostConfig) error { container.State.Lock() defer container.State.Unlock() if hostConfig == nil { // in docker start of docker restart we want to reuse previous HostConfigFile hostConfig, _ = container.ReadHostConfig() } if container.State.Running { return fmt.Errorf("The container %s is already running.", container.ID) } if err := container.EnsureMounted(); err != nil { return err } if container.runtime.networkManager.disabled { container.Config.NetworkDisabled = true } else { if err := container.allocateNetwork(); err != nil { return err } } // Make sure the config is compatible with the current kernel if container.Config.Memory > 0 && !container.runtime.capabilities.MemoryLimit { log.Printf("WARNING: Your kernel does not support memory limit capabilities. Limitation discarded.\n") container.Config.Memory = 0 } if container.Config.Memory > 0 && !container.runtime.capabilities.SwapLimit { log.Printf("WARNING: Your kernel does not support swap limit capabilities. Limitation discarded.\n") container.Config.MemorySwap = -1 } if container.runtime.capabilities.IPv4ForwardingDisabled { log.Printf("WARNING: IPv4 forwarding is disabled. Networking will not work") } // Create the requested bind mounts binds := make(map[string]BindMap) // Define illegal container destinations illegalDsts := []string{"/", "."} for _, bind := range hostConfig.Binds { // FIXME: factorize bind parsing in parseBind var src, dst, mode string arr := strings.Split(bind, ":") if len(arr) == 2 { src = arr[0] dst = arr[1] mode = "rw" } else if len(arr) == 3 { src = arr[0] dst = arr[1] mode = arr[2] } else { return fmt.Errorf("Invalid bind specification: %s", bind) } // Bail if trying to mount to an illegal destination for _, illegal := range illegalDsts { if dst == illegal { return fmt.Errorf("Illegal bind destination: %s", dst) } } bindMap := BindMap{ SrcPath: src, DstPath: dst, Mode: mode, } binds[path.Clean(dst)] = bindMap } if container.Volumes == nil || len(container.Volumes) == 0 { container.Volumes = make(map[string]string) container.VolumesRW = make(map[string]bool) } // Apply volumes from another container if requested if container.Config.VolumesFrom != "" { volumes := strings.Split(container.Config.VolumesFrom, ",") for _, v := range volumes { c := container.runtime.Get(v) if c == nil { return fmt.Errorf("Container %s not found. Impossible to mount its volumes", container.ID) } for volPath, id := range c.Volumes { if _, exists := container.Volumes[volPath]; exists { continue } if err := os.MkdirAll(path.Join(container.RootfsPath(), volPath), 0755); err != nil { return err } container.Volumes[volPath] = id if isRW, exists := c.VolumesRW[volPath]; exists { container.VolumesRW[volPath] = isRW } } } } // Create the requested volumes if they don't exist for volPath := range container.Config.Volumes { volPath = path.Clean(volPath) // Skip existing volumes if _, exists := container.Volumes[volPath]; exists { continue } var srcPath string var isBindMount bool srcRW := false // If an external bind is defined for this volume, use that as a source if bindMap, exists := binds[volPath]; exists { isBindMount = true srcPath = bindMap.SrcPath if strings.ToLower(bindMap.Mode) == "rw" { srcRW = true } // Otherwise create an directory in $ROOT/volumes/ and use that } else { c, err := container.runtime.volumes.Create(nil, container, "", "", nil) if err != nil { return err } srcPath, err = c.layer() if err != nil { return err } srcRW = true // RW by default } container.Volumes[volPath] = srcPath container.VolumesRW[volPath] = srcRW // Create the mountpoint rootVolPath := path.Join(container.RootfsPath(), volPath) if err := os.MkdirAll(rootVolPath, 0755); err != nil { return nil } // Do not copy or change permissions if we are mounting from the host if srcRW && !isBindMount { volList, err := ioutil.ReadDir(rootVolPath) if err != nil { return err } if len(volList) > 0 { srcList, err := ioutil.ReadDir(srcPath) if err != nil { return err } if len(srcList) == 0 { // If the source volume is empty copy files from the root into the volume if err := CopyWithTar(rootVolPath, srcPath); err != nil { return err } var stat syscall.Stat_t if err := syscall.Stat(rootVolPath, &stat); err != nil { return err } var srcStat syscall.Stat_t if err := syscall.Stat(srcPath, &srcStat); err != nil { return err } // Change the source volume's ownership if it differs from the root // files that where just copied if stat.Uid != srcStat.Uid || stat.Gid != srcStat.Gid { if err := os.Chown(srcPath, int(stat.Uid), int(stat.Gid)); err != nil { return err } } } } } } if err := container.generateLXCConfig(hostConfig); err != nil { return err } params := []string{ "-n", container.ID, "-f", container.lxcConfigPath(), "--", "/.dockerinit", } // Networking if !container.Config.NetworkDisabled { params = append(params, "-g", container.network.Gateway.String()) } // User if container.Config.User != "" { params = append(params, "-u", container.Config.User) } if container.Config.Tty { params = append(params, "-e", "TERM=xterm") } // Setup environment params = append(params, "-e", "HOME=/", "-e", "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "-e", "container=lxc", "-e", "HOSTNAME="+container.Config.Hostname, ) if container.Config.WorkingDir != "" { workingDir := path.Clean(container.Config.WorkingDir) utils.Debugf("[working dir] working dir is %s", workingDir) if err := os.MkdirAll(path.Join(container.RootfsPath(), workingDir), 0755); err != nil { return nil } params = append(params, "-w", workingDir, ) } for _, elem := range container.Config.Env { params = append(params, "-e", elem) } // Program params = append(params, "--", container.Path) params = append(params, container.Args...) container.cmd = exec.Command("lxc-start", params...) // Setup logging of stdout and stderr to disk if err := container.runtime.LogToDisk(container.stdout, container.logPath("json"), "stdout"); err != nil { return err } if err := container.runtime.LogToDisk(container.stderr, container.logPath("json"), "stderr"); err != nil { return err } container.cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} var err error if container.Config.Tty { err = container.startPty() } else { err = container.start() } if err != nil { return err } // FIXME: save state on disk *first*, then converge // this way disk state is used as a journal, eg. we can restore after crash etc. container.State.setRunning(container.cmd.Process.Pid) // Init the lock container.waitLock = make(chan struct{}) container.ToDisk() container.SaveHostConfig(hostConfig) go container.monitor(hostConfig) return nil } func (container *Container) Run() error { hostConfig := &HostConfig{} if err := container.Start(hostConfig); err != nil { return err } container.Wait() return nil } func (container *Container) Output() (output []byte, err error) { pipe, err := container.StdoutPipe() if err != nil { return nil, err } defer pipe.Close() hostConfig := &HostConfig{} if err := container.Start(hostConfig); err != nil { return nil, err } output, err = ioutil.ReadAll(pipe) container.Wait() return output, err } // StdinPipe() returns a pipe connected to the standard input of the container's // active process. // func (container *Container) StdinPipe() (io.WriteCloser, error) { return container.stdinPipe, nil } func (container *Container) StdoutPipe() (io.ReadCloser, error) { reader, writer := io.Pipe() container.stdout.AddWriter(writer, "") return utils.NewBufReader(reader), nil } func (container *Container) StderrPipe() (io.ReadCloser, error) { reader, writer := io.Pipe() container.stderr.AddWriter(writer, "") return utils.NewBufReader(reader), nil } func (container *Container) allocateNetwork() error { if container.Config.NetworkDisabled { return nil } var iface *NetworkInterface var err error if !container.State.Ghost { iface, err = container.runtime.networkManager.Allocate() if err != nil { return err } } else { manager := container.runtime.networkManager if manager.disabled { iface = &NetworkInterface{disabled: true} } else { iface = &NetworkInterface{ IPNet: net.IPNet{IP: net.ParseIP(container.NetworkSettings.IPAddress), Mask: manager.bridgeNetwork.Mask}, Gateway: manager.bridgeNetwork.IP, manager: manager, } ipNum := ipToInt(iface.IPNet.IP) manager.ipAllocator.inUse[ipNum] = struct{}{} } } var portSpecs []string if !container.State.Ghost { portSpecs = container.Config.PortSpecs } else { for backend, frontend := range container.NetworkSettings.PortMapping["Tcp"] { portSpecs = append(portSpecs, fmt.Sprintf("%s:%s/tcp", frontend, backend)) } for backend, frontend := range container.NetworkSettings.PortMapping["Udp"] { portSpecs = append(portSpecs, fmt.Sprintf("%s:%s/udp", frontend, backend)) } } container.NetworkSettings.PortMapping = make(map[string]PortMapping) container.NetworkSettings.PortMapping["Tcp"] = make(PortMapping) container.NetworkSettings.PortMapping["Udp"] = make(PortMapping) for _, spec := range portSpecs { nat, err := iface.AllocatePort(spec) if err != nil { iface.Release() return err } proto := strings.Title(nat.Proto) backend, frontend := strconv.Itoa(nat.Backend), strconv.Itoa(nat.Frontend) container.NetworkSettings.PortMapping[proto][backend] = frontend } container.network = iface container.NetworkSettings.Bridge = container.runtime.networkManager.bridgeIface container.NetworkSettings.IPAddress = iface.IPNet.IP.String() container.NetworkSettings.IPPrefixLen, _ = iface.IPNet.Mask.Size() container.NetworkSettings.Gateway = iface.Gateway.String() return nil } func (container *Container) releaseNetwork() { if container.Config.NetworkDisabled { return } container.network.Release() container.network = nil container.NetworkSettings = &NetworkSettings{} } // FIXME: replace this with a control socket within docker-init func (container *Container) waitLxc() error { for { output, err := exec.Command("lxc-info", "-n", container.ID).CombinedOutput() if err != nil { return err } if !strings.Contains(string(output), "RUNNING") { return nil } time.Sleep(500 * time.Millisecond) } } func (container *Container) monitor(hostConfig *HostConfig) { // Wait for the program to exit utils.Debugf("Waiting for process") // If the command does not exists, try to wait via lxc if container.cmd == nil { if err := container.waitLxc(); err != nil { utils.Debugf("%s: Process: %s", container.ID, err) } } else { if err := container.cmd.Wait(); err != nil { // Discard the error as any signals or non 0 returns will generate an error utils.Debugf("%s: Process: %s", container.ID, err) } } utils.Debugf("Process finished") exitCode := -1 if container.cmd != nil { exitCode = container.cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus() } // Report status back container.State.setStopped(exitCode) if container.runtime != nil && container.runtime.srv != nil { container.runtime.srv.LogEvent("die", container.ShortID(), container.runtime.repositories.ImageName(container.Image)) } // Cleanup container.releaseNetwork() if container.Config.OpenStdin { if err := container.stdin.Close(); err != nil { utils.Debugf("%s: Error close stdin: %s", container.ID, err) } } if err := container.stdout.CloseWriters(); err != nil { utils.Debugf("%s: Error close stdout: %s", container.ID, err) } if err := container.stderr.CloseWriters(); err != nil { utils.Debugf("%s: Error close stderr: %s", container.ID, err) } if container.ptyMaster != nil { if err := container.ptyMaster.Close(); err != nil { utils.Debugf("%s: Error closing Pty master: %s", container.ID, err) } } if err := container.Unmount(); err != nil { log.Printf("%v: Failed to umount filesystem: %v", container.ID, err) } // Re-create a brand new stdin pipe once the container exited if container.Config.OpenStdin { container.stdin, container.stdinPipe = io.Pipe() } // Release the lock close(container.waitLock) if err := container.ToDisk(); err != nil { // FIXME: there is a race condition here which causes this to fail during the unit tests. // If another goroutine was waiting for Wait() to return before removing the container's root // from the filesystem... At this point it may already have done so. // This is because State.setStopped() has already been called, and has caused Wait() // to return. // FIXME: why are we serializing running state to disk in the first place? //log.Printf("%s: Failed to dump configuration to the disk: %s", container.ID, err) } } func (container *Container) kill() error { if !container.State.Running { return nil } // Sending SIGKILL to the process via lxc output, err := exec.Command("lxc-kill", "-n", container.ID, "9").CombinedOutput() if err != nil { log.Printf("error killing container %s (%s, %s)", container.ID, output, err) } // 2. Wait for the process to die, in last resort, try to kill the process directly if err := container.WaitTimeout(10 * time.Second); err != nil { if container.cmd == nil { return fmt.Errorf("lxc-kill failed, impossible to kill the container %s", container.ID) } log.Printf("Container %s failed to exit within 10 seconds of lxc SIGKILL - trying direct SIGKILL", container.ID) if err := container.cmd.Process.Kill(); err != nil { return err } } // Wait for the container to be actually stopped container.Wait() return nil } func (container *Container) Kill() error { container.State.Lock() defer container.State.Unlock() if !container.State.Running { return nil } return container.kill() } func (container *Container) Stop(seconds int) error { container.State.Lock() defer container.State.Unlock() if !container.State.Running { return nil } // 1. Send a SIGTERM if output, err := exec.Command("lxc-kill", "-n", container.ID, "15").CombinedOutput(); err != nil { log.Print(string(output)) log.Print("Failed to send SIGTERM to the process, force killing") if err := container.kill(); err != nil { return err } } // 2. Wait for the process to exit on its own if err := container.WaitTimeout(time.Duration(seconds) * time.Second); err != nil { log.Printf("Container %v failed to exit within %d seconds of SIGTERM - using the force", container.ID, seconds) if err := container.kill(); err != nil { return err } } return nil } func (container *Container) Restart(seconds int) error { if err := container.Stop(seconds); err != nil { return err } hostConfig := &HostConfig{} if err := container.Start(hostConfig); err != nil { return err } return nil } // Wait blocks until the container stops running, then returns its exit code. func (container *Container) Wait() int { <-container.waitLock return container.State.ExitCode } func (container *Container) Resize(h, w int) error { pty, ok := container.ptyMaster.(*os.File) if !ok { return fmt.Errorf("ptyMaster does not have Fd() method") } return term.SetWinsize(pty.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)}) } func (container *Container) ExportRw() (Archive, error) { return Tar(container.rwPath(), Uncompressed) } func (container *Container) RwChecksum() (string, error) { rwData, err := Tar(container.rwPath(), Xz) if err != nil { return "", err } return utils.HashData(rwData) } func (container *Container) Export() (Archive, error) { if err := container.EnsureMounted(); err != nil { return nil, err } return Tar(container.RootfsPath(), Uncompressed) } func (container *Container) WaitTimeout(timeout time.Duration) error { done := make(chan bool) go func() { container.Wait() done <- true }() select { case <-time.After(timeout): return fmt.Errorf("Timed Out") case <-done: return nil } } func (container *Container) EnsureMounted() error { if mounted, err := container.Mounted(); err != nil { return err } else if mounted { return nil } return container.Mount() } func (container *Container) Mount() error { image, err := container.GetImage() if err != nil { return err } return image.Mount(container.RootfsPath(), container.rwPath()) } func (container *Container) Changes() ([]Change, error) { image, err := container.GetImage() if err != nil { return nil, err } return image.Changes(container.rwPath()) } func (container *Container) GetImage() (*Image, error) { if container.runtime == nil { return nil, fmt.Errorf("Can't get image of unregistered container") } return container.runtime.graph.Get(container.Image) } func (container *Container) Mounted() (bool, error) { return Mounted(container.RootfsPath()) } func (container *Container) Unmount() error { return Unmount(container.RootfsPath()) } // ShortID returns a shorthand version of the container's id for convenience. // A collision with other container shorthands is very unlikely, but possible. // In case of a collision a lookup with Runtime.Get() will fail, and the caller // will need to use a langer prefix, or the full-length container Id. func (container *Container) ShortID() string { return utils.TruncateID(container.ID) } func (container *Container) logPath(name string) string { return path.Join(container.root, fmt.Sprintf("%s-%s.log", container.ID, name)) } func (container *Container) ReadLog(name string) (io.Reader, error) { return os.Open(container.logPath(name)) } func (container *Container) hostConfigPath() string { return path.Join(container.root, "hostconfig.json") } func (container *Container) jsonPath() string { return path.Join(container.root, "config.json") } func (container *Container) lxcConfigPath() string { return path.Join(container.root, "config.lxc") } // This method must be exported to be used from the lxc template func (container *Container) RootfsPath() string { return path.Join(container.root, "rootfs") } func (container *Container) rwPath() string { return path.Join(container.root, "rw") } func validateID(id string) error { if id == "" { return fmt.Errorf("Invalid empty id") } return nil } // GetSize, return real size, virtual size func (container *Container) GetSize() (int64, int64) { var sizeRw, sizeRootfs int64 filepath.Walk(container.rwPath(), func(path string, fileInfo os.FileInfo, err error) error { if fileInfo != nil { sizeRw += fileInfo.Size() } return nil }) _, err := os.Stat(container.RootfsPath()) if err == nil { filepath.Walk(container.RootfsPath(), func(path string, fileInfo os.FileInfo, err error) error { if fileInfo != nil { sizeRootfs += fileInfo.Size() } return nil }) } return sizeRw, sizeRootfs } func (container *Container) Copy(resource string) (Archive, error) { if err := container.EnsureMounted(); err != nil { return nil, err } var filter []string basePath := path.Join(container.RootfsPath(), resource) stat, err := os.Stat(basePath) if err != nil { return nil, err } if !stat.IsDir() { d, f := path.Split(basePath) basePath = d filter = []string{f} } else { filter = []string{path.Base(basePath)} basePath = path.Dir(basePath) } return TarFilter(basePath, Uncompressed, filter) }
container.go
1
https://github.com/moby/moby/commit/e368c8bb01b3c52c8e4c334c3a7f32556af9d632
[ 0.9976339340209961, 0.048469215631484985, 0.00016336746921297163, 0.00017027735884767026, 0.19831009209156036 ]
{ "id": 3, "code_window": [ "\t}\n", "\treturn Tar(layerPath, compression)\n", "}\n", "\n", "func (image *Image) Mount(root, rw string) error {\n", "\tif mounted, err := Mounted(root); err != nil {\n", "\t\treturn err\n", "\t} else if mounted {\n", "\t\treturn fmt.Errorf(\"%s is already mounted\", root)\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "func (image *Image) Mount(runtime *Runtime, root, rw string, id string) error {\n" ], "file_path": "image.go", "type": "replace", "edit_start_line_idx": 172 }
#data <!DOCTYPE html><p><b><i><u></p> <p>X #errors Line: 1 Col: 31 Unexpected end tag (p). Ignored. Line: 1 Col: 36 Expected closing tag. Unexpected end of file. #document | <!DOCTYPE html> | <html> | <head> | <body> | <p> | <b> | <i> | <u> | <b> | <i> | <u> | " " | <p> | "X" #data <p><b><i><u></p> <p>X #errors Line: 1 Col: 3 Unexpected start tag (p). Expected DOCTYPE. Line: 1 Col: 16 Unexpected end tag (p). Ignored. Line: 2 Col: 4 Expected closing tag. Unexpected end of file. #document | <html> | <head> | <body> | <p> | <b> | <i> | <u> | <b> | <i> | <u> | " " | <p> | "X" #data <!doctype html></html> <head> #errors Line: 1 Col: 22 Unexpected end tag (html) after the (implied) root element. #document | <!DOCTYPE html> | <html> | <head> | <body> | " " #data <!doctype html></body><meta> #errors Line: 1 Col: 22 Unexpected end tag (body) after the (implied) root element. #document | <!DOCTYPE html> | <html> | <head> | <body> | <meta> #data <html></html><!-- foo --> #errors Line: 1 Col: 6 Unexpected start tag (html). Expected DOCTYPE. Line: 1 Col: 13 Unexpected end tag (html) after the (implied) root element. #document | <html> | <head> | <body> | <!-- foo --> #data <!doctype html></body><title>X</title> #errors Line: 1 Col: 22 Unexpected end tag (body) after the (implied) root element. #document | <!DOCTYPE html> | <html> | <head> | <body> | <title> | "X" #data <!doctype html><table> X<meta></table> #errors Line: 1 Col: 24 Unexpected non-space characters in table context caused voodoo mode. Line: 1 Col: 30 Unexpected start tag (meta) in table context caused voodoo mode. #document | <!DOCTYPE html> | <html> | <head> | <body> | " X" | <meta> | <table> #data <!doctype html><table> x</table> #errors Line: 1 Col: 24 Unexpected non-space characters in table context caused voodoo mode. #document | <!DOCTYPE html> | <html> | <head> | <body> | " x" | <table> #data <!doctype html><table> x </table> #errors Line: 1 Col: 25 Unexpected non-space characters in table context caused voodoo mode. #document | <!DOCTYPE html> | <html> | <head> | <body> | " x " | <table> #data <!doctype html><table><tr> x</table> #errors Line: 1 Col: 28 Unexpected non-space characters in table context caused voodoo mode. #document | <!DOCTYPE html> | <html> | <head> | <body> | " x" | <table> | <tbody> | <tr> #data <!doctype html><table>X<style> <tr>x </style> </table> #errors Line: 1 Col: 23 Unexpected non-space characters in table context caused voodoo mode. #document | <!DOCTYPE html> | <html> | <head> | <body> | "X" | <table> | <style> | " <tr>x " | " " #data <!doctype html><div><table><a>foo</a> <tr><td>bar</td> </tr></table></div> #errors Line: 1 Col: 30 Unexpected start tag (a) in table context caused voodoo mode. Line: 1 Col: 37 Unexpected end tag (a) in table context caused voodoo mode. #document | <!DOCTYPE html> | <html> | <head> | <body> | <div> | <a> | "foo" | <table> | " " | <tbody> | <tr> | <td> | "bar" | " " #data <frame></frame></frame><frameset><frame><frameset><frame></frameset><noframes></frameset><noframes> #errors 6: Start tag seen without seeing a doctype first. Expected “<!DOCTYPE html>”. 13: Stray start tag “frame”. 21: Stray end tag “frame”. 29: Stray end tag “frame”. 39: “frameset” start tag after “body” already open. 105: End of file seen inside an [R]CDATA element. 105: End of file seen and there were open elements. XXX: These errors are wrong, please fix me! #document | <html> | <head> | <frameset> | <frame> | <frameset> | <frame> | <noframes> | "</frameset><noframes>" #data <!DOCTYPE html><object></html> #errors 1: Expected closing tag. Unexpected end of file #document | <!DOCTYPE html> | <html> | <head> | <body> | <object>
vendor/src/code.google.com/p/go.net/html/testdata/webkit/tests15.dat
0
https://github.com/moby/moby/commit/e368c8bb01b3c52c8e4c334c3a7f32556af9d632
[ 0.0001779620215529576, 0.00017236989515367895, 0.00016673973004799336, 0.00017306524387095124, 0.000003384068122613826 ]
{ "id": 3, "code_window": [ "\t}\n", "\treturn Tar(layerPath, compression)\n", "}\n", "\n", "func (image *Image) Mount(root, rw string) error {\n", "\tif mounted, err := Mounted(root); err != nil {\n", "\t\treturn err\n", "\t} else if mounted {\n", "\t\treturn fmt.Errorf(\"%s is already mounted\", root)\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "func (image *Image) Mount(runtime *Runtime, root, rw string, id string) error {\n" ], "file_path": "image.go", "type": "replace", "edit_start_line_idx": 172 }
// 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 darwin freebsd linux netbsd openbsd windows package ipv4_test import ( "code.google.com/p/go.net/ipv4" "net" "os" "runtime" "testing" ) type testMulticastConn interface { testUnicastConn MulticastTTL() (int, error) SetMulticastTTL(ttl int) error MulticastLoopback() (bool, error) SetMulticastLoopback(bool) error JoinGroup(*net.Interface, net.Addr) error LeaveGroup(*net.Interface, net.Addr) error } type multicastSockoptTest struct { tos int ttl int mcttl int mcloop bool gaddr net.IP } var multicastSockoptTests = []multicastSockoptTest{ {DiffServCS0 | NotECNTransport, 127, 128, false, net.IPv4(224, 0, 0, 249)}, // see RFC 4727 {DiffServAF11 | NotECNTransport, 255, 254, true, net.IPv4(224, 0, 0, 250)}, // see RFC 4727 } func TestUDPMulticastSockopt(t *testing.T) { if testing.Short() || !*testExternal { t.Skip("to avoid external network") } for _, tt := range multicastSockoptTests { c, err := net.ListenPacket("udp4", "0.0.0.0:0") if err != nil { t.Fatalf("net.ListenPacket failed: %v", err) } defer c.Close() p := ipv4.NewPacketConn(c) testMulticastSockopt(t, tt, p, &net.UDPAddr{IP: tt.gaddr}) } } func TestIPMulticastSockopt(t *testing.T) { if testing.Short() || !*testExternal { t.Skip("to avoid external network") } if os.Getuid() != 0 { t.Skip("must be root") } for _, tt := range multicastSockoptTests { c, err := net.ListenPacket("ip4:icmp", "0.0.0.0") if err != nil { t.Fatalf("net.ListenPacket failed: %v", err) } defer c.Close() r, _ := ipv4.NewRawConn(c) testMulticastSockopt(t, tt, r, &net.IPAddr{IP: tt.gaddr}) } } func testMulticastSockopt(t *testing.T, tt multicastSockoptTest, c testMulticastConn, gaddr net.Addr) { switch runtime.GOOS { case "windows": // IP_TOS option is supported on Windows 8 and beyond. t.Logf("skipping IP_TOS test on %q", runtime.GOOS) default: if err := c.SetTOS(tt.tos); err != nil { t.Fatalf("ipv4.PacketConn.SetTOS failed: %v", err) } if v, err := c.TOS(); err != nil { t.Fatalf("ipv4.PacketConn.TOS failed: %v", err) } else if v != tt.tos { t.Fatalf("Got unexpected TOS value %v; expected %v", v, tt.tos) } } if err := c.SetTTL(tt.ttl); err != nil { t.Fatalf("ipv4.PacketConn.SetTTL failed: %v", err) } if v, err := c.TTL(); err != nil { t.Fatalf("ipv4.PacketConn.TTL failed: %v", err) } else if v != tt.ttl { t.Fatalf("Got unexpected TTL value %v; expected %v", v, tt.ttl) } if err := c.SetMulticastTTL(tt.mcttl); err != nil { t.Fatalf("ipv4.PacketConn.SetMulticastTTL failed: %v", err) } if v, err := c.MulticastTTL(); err != nil { t.Fatalf("ipv4.PacketConn.MulticastTTL failed: %v", err) } else if v != tt.mcttl { t.Fatalf("Got unexpected MulticastTTL value %v; expected %v", v, tt.mcttl) } if err := c.SetMulticastLoopback(tt.mcloop); err != nil { t.Fatalf("ipv4.PacketConn.SetMulticastLoopback failed: %v", err) } if v, err := c.MulticastLoopback(); err != nil { t.Fatalf("ipv4.PacketConn.MulticastLoopback failed: %v", err) } else if v != tt.mcloop { t.Fatalf("Got unexpected MulticastLoopback value %v; expected %v", v, tt.mcloop) } if err := c.JoinGroup(nil, gaddr); err != nil { t.Fatalf("ipv4.PacketConn.JoinGroup(%v) failed: %v", gaddr, err) } if err := c.LeaveGroup(nil, gaddr); err != nil { t.Fatalf("ipv4.PacketConn.LeaveGroup(%v) failed: %v", gaddr, err) } }
vendor/src/code.google.com/p/go.net/ipv4/multicastsockopt_test.go
0
https://github.com/moby/moby/commit/e368c8bb01b3c52c8e4c334c3a7f32556af9d632
[ 0.0002604246838018298, 0.0001834716968005523, 0.0001688886695774272, 0.00017046609718818218, 0.000027219706680625677 ]
{ "id": 3, "code_window": [ "\t}\n", "\treturn Tar(layerPath, compression)\n", "}\n", "\n", "func (image *Image) Mount(root, rw string) error {\n", "\tif mounted, err := Mounted(root); err != nil {\n", "\t\treturn err\n", "\t} else if mounted {\n", "\t\treturn fmt.Errorf(\"%s is already mounted\", root)\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "func (image *Image) Mount(runtime *Runtime, root, rw string, id string) error {\n" ], "file_path": "image.go", "type": "replace", "edit_start_line_idx": 172 }
.. note:: Docker is still under heavy development! We don't recommend using it in production yet, but we're getting closer with each release. Please see our blog post, `"Getting to Docker 1.0" <http://blog.docker.io/2013/08/getting-to-docker-1-0/>`_
docs/sources/installation/install_header.inc
0
https://github.com/moby/moby/commit/e368c8bb01b3c52c8e4c334c3a7f32556af9d632
[ 0.00017332271090708673, 0.00017332271090708673, 0.00017332271090708673, 0.00017332271090708673, 0 ]
{ "id": 0, "code_window": [ "// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.\n", "\n", "package trie\n", "\n", "import (\n", "\t\"fmt\"\n", "\t\"sync\"\n", "\n", "\t\"github.com/ethereum/go-ethereum/common\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\"errors\"\n" ], "file_path": "trie/stacktrie.go", "type": "add", "edit_start_line_idx": 19 }
// Copyright 2020 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 trie import ( "fmt" "sync" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/rlp" ) var stPool = sync.Pool{ New: func() interface{} { return NewStackTrie(nil) }, } func stackTrieFromPool(db ethdb.KeyValueStore) *StackTrie { st := stPool.Get().(*StackTrie) st.db = db return st } func returnToPool(st *StackTrie) { st.Reset() stPool.Put(st) } // StackTrie is a trie implementation that expects keys to be inserted // in order. Once it determines that a subtree will no longer be inserted // into, it will hash it and free up the memory it uses. type StackTrie struct { nodeType uint8 // node type (as in branch, ext, leaf) val []byte // value contained by this node if it's a leaf key []byte // key chunk covered by this (full|ext) node keyOffset int // offset of the key chunk inside a full key children [16]*StackTrie // list of children (for fullnodes and exts) db ethdb.KeyValueStore // Pointer to the commit db, can be nil } // NewStackTrie allocates and initializes an empty trie. func NewStackTrie(db ethdb.KeyValueStore) *StackTrie { return &StackTrie{ nodeType: emptyNode, db: db, } } func newLeaf(ko int, key, val []byte, db ethdb.KeyValueStore) *StackTrie { st := stackTrieFromPool(db) st.nodeType = leafNode st.keyOffset = ko st.key = append(st.key, key[ko:]...) st.val = val return st } func newExt(ko int, key []byte, child *StackTrie, db ethdb.KeyValueStore) *StackTrie { st := stackTrieFromPool(db) st.nodeType = extNode st.keyOffset = ko st.key = append(st.key, key[ko:]...) st.children[0] = child return st } // List all values that StackTrie#nodeType can hold const ( emptyNode = iota branchNode extNode leafNode hashedNode ) // TryUpdate inserts a (key, value) pair into the stack trie func (st *StackTrie) TryUpdate(key, value []byte) error { k := keybytesToHex(key) if len(value) == 0 { panic("deletion not supported") } st.insert(k[:len(k)-1], value) return nil } func (st *StackTrie) Update(key, value []byte) { if err := st.TryUpdate(key, value); err != nil { log.Error(fmt.Sprintf("Unhandled trie error: %v", err)) } } func (st *StackTrie) Reset() { st.db = nil st.key = st.key[:0] st.val = st.val[:0] for i := range st.children { st.children[i] = nil } st.nodeType = emptyNode st.keyOffset = 0 } // Helper function that, given a full key, determines the index // at which the chunk pointed by st.keyOffset is different from // the same chunk in the full key. func (st *StackTrie) getDiffIndex(key []byte) int { diffindex := 0 for ; diffindex < len(st.key) && st.key[diffindex] == key[st.keyOffset+diffindex]; diffindex++ { } return diffindex } // Helper function to that inserts a (key, value) pair into // the trie. func (st *StackTrie) insert(key, value []byte) { switch st.nodeType { case branchNode: /* Branch */ idx := int(key[st.keyOffset]) // Unresolve elder siblings for i := idx - 1; i >= 0; i-- { if st.children[i] != nil { if st.children[i].nodeType != hashedNode { st.children[i].hash() } break } } // Add new child if st.children[idx] == nil { st.children[idx] = stackTrieFromPool(st.db) st.children[idx].keyOffset = st.keyOffset + 1 } st.children[idx].insert(key, value) case extNode: /* Ext */ // Compare both key chunks and see where they differ diffidx := st.getDiffIndex(key) // Check if chunks are identical. If so, recurse into // the child node. Otherwise, the key has to be split // into 1) an optional common prefix, 2) the fullnode // representing the two differing path, and 3) a leaf // for each of the differentiated subtrees. if diffidx == len(st.key) { // Ext key and key segment are identical, recurse into // the child node. st.children[0].insert(key, value) return } // Save the original part. Depending if the break is // at the extension's last byte or not, create an // intermediate extension or use the extension's child // node directly. var n *StackTrie if diffidx < len(st.key)-1 { n = newExt(diffidx+1, st.key, st.children[0], st.db) } else { // Break on the last byte, no need to insert // an extension node: reuse the current node n = st.children[0] } // Convert to hash n.hash() var p *StackTrie if diffidx == 0 { // the break is on the first byte, so // the current node is converted into // a branch node. st.children[0] = nil p = st st.nodeType = branchNode } else { // the common prefix is at least one byte // long, insert a new intermediate branch // node. st.children[0] = stackTrieFromPool(st.db) st.children[0].nodeType = branchNode st.children[0].keyOffset = st.keyOffset + diffidx p = st.children[0] } // Create a leaf for the inserted part o := newLeaf(st.keyOffset+diffidx+1, key, value, st.db) // Insert both child leaves where they belong: origIdx := st.key[diffidx] newIdx := key[diffidx+st.keyOffset] p.children[origIdx] = n p.children[newIdx] = o st.key = st.key[:diffidx] case leafNode: /* Leaf */ // Compare both key chunks and see where they differ diffidx := st.getDiffIndex(key) // Overwriting a key isn't supported, which means that // the current leaf is expected to be split into 1) an // optional extension for the common prefix of these 2 // keys, 2) a fullnode selecting the path on which the // keys differ, and 3) one leaf for the differentiated // component of each key. if diffidx >= len(st.key) { panic("Trying to insert into existing key") } // Check if the split occurs at the first nibble of the // chunk. In that case, no prefix extnode is necessary. // Otherwise, create that var p *StackTrie if diffidx == 0 { // Convert current leaf into a branch st.nodeType = branchNode p = st st.children[0] = nil } else { // Convert current node into an ext, // and insert a child branch node. st.nodeType = extNode st.children[0] = NewStackTrie(st.db) st.children[0].nodeType = branchNode st.children[0].keyOffset = st.keyOffset + diffidx p = st.children[0] } // Create the two child leaves: the one containing the // original value and the one containing the new value // The child leave will be hashed directly in order to // free up some memory. origIdx := st.key[diffidx] p.children[origIdx] = newLeaf(diffidx+1, st.key, st.val, st.db) p.children[origIdx].hash() newIdx := key[diffidx+st.keyOffset] p.children[newIdx] = newLeaf(p.keyOffset+1, key, value, st.db) // Finally, cut off the key part that has been passed // over to the children. st.key = st.key[:diffidx] st.val = nil case emptyNode: /* Empty */ st.nodeType = leafNode st.key = key[st.keyOffset:] st.val = value case hashedNode: panic("trying to insert into hash") default: panic("invalid type") } } // hash() hashes the node 'st' and converts it into 'hashedNode', if possible. // Possible outcomes: // 1. The rlp-encoded value was >= 32 bytes: // - Then the 32-byte `hash` will be accessible in `st.val`. // - And the 'st.type' will be 'hashedNode' // 2. The rlp-encoded value was < 32 bytes // - Then the <32 byte rlp-encoded value will be accessible in 'st.val'. // - And the 'st.type' will be 'hashedNode' AGAIN // // This method will also: // set 'st.type' to hashedNode // clear 'st.key' func (st *StackTrie) hash() { /* Shortcut if node is already hashed */ if st.nodeType == hashedNode { return } // The 'hasher' is taken from a pool, but we don't actually // claim an instance until all children are done with their hashing, // and we actually need one var h *hasher switch st.nodeType { case branchNode: var nodes [17]node for i, child := range st.children { if child == nil { nodes[i] = nilValueNode continue } child.hash() if len(child.val) < 32 { nodes[i] = rawNode(child.val) } else { nodes[i] = hashNode(child.val) } st.children[i] = nil // Reclaim mem from subtree returnToPool(child) } nodes[16] = nilValueNode h = newHasher(false) defer returnHasherToPool(h) h.tmp.Reset() if err := rlp.Encode(&h.tmp, nodes); err != nil { panic(err) } case extNode: h = newHasher(false) defer returnHasherToPool(h) h.tmp.Reset() st.children[0].hash() // This is also possible: //sz := hexToCompactInPlace(st.key) //n := [][]byte{ // st.key[:sz], // st.children[0].val, //} n := [][]byte{ hexToCompact(st.key), st.children[0].val, } if err := rlp.Encode(&h.tmp, n); err != nil { panic(err) } returnToPool(st.children[0]) st.children[0] = nil // Reclaim mem from subtree case leafNode: h = newHasher(false) defer returnHasherToPool(h) h.tmp.Reset() st.key = append(st.key, byte(16)) sz := hexToCompactInPlace(st.key) n := [][]byte{st.key[:sz], st.val} if err := rlp.Encode(&h.tmp, n); err != nil { panic(err) } case emptyNode: st.val = st.val[:0] st.val = append(st.val, emptyRoot[:]...) st.key = st.key[:0] st.nodeType = hashedNode return default: panic("Invalid node type") } st.key = st.key[:0] st.nodeType = hashedNode if len(h.tmp) < 32 { st.val = st.val[:0] st.val = append(st.val, h.tmp...) return } // Going to write the hash to the 'val'. Need to ensure it's properly sized first // Typically, 'branchNode's will have no 'val', and require this allocation if required := 32 - len(st.val); required > 0 { buf := make([]byte, required) st.val = append(st.val, buf...) } st.val = st.val[:32] h.sha.Reset() h.sha.Write(h.tmp) h.sha.Read(st.val) if st.db != nil { // TODO! Is it safe to Put the slice here? // Do all db implementations copy the value provided? st.db.Put(st.val, h.tmp) } } // Hash returns the hash of the current node func (st *StackTrie) Hash() (h common.Hash) { st.hash() if len(st.val) != 32 { // If the node's RLP isn't 32 bytes long, the node will not // be hashed, and instead contain the rlp-encoding of the // node. For the top level node, we need to force the hashing. ret := make([]byte, 32) h := newHasher(false) defer returnHasherToPool(h) h.sha.Reset() h.sha.Write(st.val) h.sha.Read(ret) return common.BytesToHash(ret) } return common.BytesToHash(st.val) } // Commit will commit the current node to database db func (st *StackTrie) Commit(db ethdb.KeyValueStore) common.Hash { oldDb := st.db st.db = db defer func() { st.db = oldDb }() st.hash() h := common.BytesToHash(st.val) return h }
trie/stacktrie.go
1
https://github.com/ethereum/go-ethereum/commit/86dd005544179818edd78ef6c9396b9574e8a614
[ 0.0249385554343462, 0.000842181034386158, 0.00016345785115845501, 0.00017017035861499608, 0.003828583052381873 ]
{ "id": 0, "code_window": [ "// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.\n", "\n", "package trie\n", "\n", "import (\n", "\t\"fmt\"\n", "\t\"sync\"\n", "\n", "\t\"github.com/ethereum/go-ethereum/common\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\"errors\"\n" ], "file_path": "trie/stacktrie.go", "type": "add", "edit_start_line_idx": 19 }
# Prover implementation for Weierstrass curves of the form # y^2 = x^3 + A * x + B, specifically with a = 0 and b = 7, with group laws # operating on affine and Jacobian coordinates, including the point at infinity # represented by a 4th variable in coordinates. load("group_prover.sage") class affinepoint: def __init__(self, x, y, infinity=0): self.x = x self.y = y self.infinity = infinity def __str__(self): return "affinepoint(x=%s,y=%s,inf=%s)" % (self.x, self.y, self.infinity) class jacobianpoint: def __init__(self, x, y, z, infinity=0): self.X = x self.Y = y self.Z = z self.Infinity = infinity def __str__(self): return "jacobianpoint(X=%s,Y=%s,Z=%s,inf=%s)" % (self.X, self.Y, self.Z, self.Infinity) def point_at_infinity(): return jacobianpoint(1, 1, 1, 1) def negate(p): if p.__class__ == affinepoint: return affinepoint(p.x, -p.y) if p.__class__ == jacobianpoint: return jacobianpoint(p.X, -p.Y, p.Z) assert(False) def on_weierstrass_curve(A, B, p): """Return a set of zero-expressions for an affine point to be on the curve""" return constraints(zero={p.x^3 + A*p.x + B - p.y^2: 'on_curve'}) def tangential_to_weierstrass_curve(A, B, p12, p3): """Return a set of zero-expressions for ((x12,y12),(x3,y3)) to be a line that is tangential to the curve at (x12,y12)""" return constraints(zero={ (p12.y - p3.y) * (p12.y * 2) - (p12.x^2 * 3 + A) * (p12.x - p3.x): 'tangential_to_curve' }) def colinear(p1, p2, p3): """Return a set of zero-expressions for ((x1,y1),(x2,y2),(x3,y3)) to be collinear""" return constraints(zero={ (p1.y - p2.y) * (p1.x - p3.x) - (p1.y - p3.y) * (p1.x - p2.x): 'colinear_1', (p2.y - p3.y) * (p2.x - p1.x) - (p2.y - p1.y) * (p2.x - p3.x): 'colinear_2', (p3.y - p1.y) * (p3.x - p2.x) - (p3.y - p2.y) * (p3.x - p1.x): 'colinear_3' }) def good_affine_point(p): return constraints(nonzero={p.x : 'nonzero_x', p.y : 'nonzero_y'}) def good_jacobian_point(p): return constraints(nonzero={p.X : 'nonzero_X', p.Y : 'nonzero_Y', p.Z^6 : 'nonzero_Z'}) def good_point(p): return constraints(nonzero={p.Z^6 : 'nonzero_X'}) def finite(p, *affine_fns): con = good_point(p) + constraints(zero={p.Infinity : 'finite_point'}) if p.Z != 0: return con + reduce(lambda a, b: a + b, (f(affinepoint(p.X / p.Z^2, p.Y / p.Z^3)) for f in affine_fns), con) else: return con def infinite(p): return constraints(nonzero={p.Infinity : 'infinite_point'}) def law_jacobian_weierstrass_add(A, B, pa, pb, pA, pB, pC): """Check whether the passed set of coordinates is a valid Jacobian add, given assumptions""" assumeLaw = (good_affine_point(pa) + good_affine_point(pb) + good_jacobian_point(pA) + good_jacobian_point(pB) + on_weierstrass_curve(A, B, pa) + on_weierstrass_curve(A, B, pb) + finite(pA) + finite(pB) + constraints(nonzero={pa.x - pb.x : 'different_x'})) require = (finite(pC, lambda pc: on_weierstrass_curve(A, B, pc) + colinear(pa, pb, negate(pc)))) return (assumeLaw, require) def law_jacobian_weierstrass_double(A, B, pa, pb, pA, pB, pC): """Check whether the passed set of coordinates is a valid Jacobian doubling, given assumptions""" assumeLaw = (good_affine_point(pa) + good_affine_point(pb) + good_jacobian_point(pA) + good_jacobian_point(pB) + on_weierstrass_curve(A, B, pa) + on_weierstrass_curve(A, B, pb) + finite(pA) + finite(pB) + constraints(zero={pa.x - pb.x : 'equal_x', pa.y - pb.y : 'equal_y'})) require = (finite(pC, lambda pc: on_weierstrass_curve(A, B, pc) + tangential_to_weierstrass_curve(A, B, pa, negate(pc)))) return (assumeLaw, require) def law_jacobian_weierstrass_add_opposites(A, B, pa, pb, pA, pB, pC): assumeLaw = (good_affine_point(pa) + good_affine_point(pb) + good_jacobian_point(pA) + good_jacobian_point(pB) + on_weierstrass_curve(A, B, pa) + on_weierstrass_curve(A, B, pb) + finite(pA) + finite(pB) + constraints(zero={pa.x - pb.x : 'equal_x', pa.y + pb.y : 'opposite_y'})) require = infinite(pC) return (assumeLaw, require) def law_jacobian_weierstrass_add_infinite_a(A, B, pa, pb, pA, pB, pC): assumeLaw = (good_affine_point(pa) + good_affine_point(pb) + good_jacobian_point(pA) + good_jacobian_point(pB) + on_weierstrass_curve(A, B, pb) + infinite(pA) + finite(pB)) require = finite(pC, lambda pc: constraints(zero={pc.x - pb.x : 'c.x=b.x', pc.y - pb.y : 'c.y=b.y'})) return (assumeLaw, require) def law_jacobian_weierstrass_add_infinite_b(A, B, pa, pb, pA, pB, pC): assumeLaw = (good_affine_point(pa) + good_affine_point(pb) + good_jacobian_point(pA) + good_jacobian_point(pB) + on_weierstrass_curve(A, B, pa) + infinite(pB) + finite(pA)) require = finite(pC, lambda pc: constraints(zero={pc.x - pa.x : 'c.x=a.x', pc.y - pa.y : 'c.y=a.y'})) return (assumeLaw, require) def law_jacobian_weierstrass_add_infinite_ab(A, B, pa, pb, pA, pB, pC): assumeLaw = (good_affine_point(pa) + good_affine_point(pb) + good_jacobian_point(pA) + good_jacobian_point(pB) + infinite(pA) + infinite(pB)) require = infinite(pC) return (assumeLaw, require) laws_jacobian_weierstrass = { 'add': law_jacobian_weierstrass_add, 'double': law_jacobian_weierstrass_double, 'add_opposite': law_jacobian_weierstrass_add_opposites, 'add_infinite_a': law_jacobian_weierstrass_add_infinite_a, 'add_infinite_b': law_jacobian_weierstrass_add_infinite_b, 'add_infinite_ab': law_jacobian_weierstrass_add_infinite_ab } def check_exhaustive_jacobian_weierstrass(name, A, B, branches, formula, p): """Verify an implementation of addition of Jacobian points on a Weierstrass curve, by executing and validating the result for every possible addition in a prime field""" F = Integers(p) print "Formula %s on Z%i:" % (name, p) points = [] for x in xrange(0, p): for y in xrange(0, p): point = affinepoint(F(x), F(y)) r, e = concrete_verify(on_weierstrass_curve(A, B, point)) if r: points.append(point) for za in xrange(1, p): for zb in xrange(1, p): for pa in points: for pb in points: for ia in xrange(2): for ib in xrange(2): pA = jacobianpoint(pa.x * F(za)^2, pa.y * F(za)^3, F(za), ia) pB = jacobianpoint(pb.x * F(zb)^2, pb.y * F(zb)^3, F(zb), ib) for branch in xrange(0, branches): assumeAssert, assumeBranch, pC = formula(branch, pA, pB) pC.X = F(pC.X) pC.Y = F(pC.Y) pC.Z = F(pC.Z) pC.Infinity = F(pC.Infinity) r, e = concrete_verify(assumeAssert + assumeBranch) if r: match = False for key in laws_jacobian_weierstrass: assumeLaw, require = laws_jacobian_weierstrass[key](A, B, pa, pb, pA, pB, pC) r, e = concrete_verify(assumeLaw) if r: if match: print " multiple branches for (%s,%s,%s,%s) + (%s,%s,%s,%s)" % (pA.X, pA.Y, pA.Z, pA.Infinity, pB.X, pB.Y, pB.Z, pB.Infinity) else: match = True r, e = concrete_verify(require) if not r: print " failure in branch %i for (%s,%s,%s,%s) + (%s,%s,%s,%s) = (%s,%s,%s,%s): %s" % (branch, pA.X, pA.Y, pA.Z, pA.Infinity, pB.X, pB.Y, pB.Z, pB.Infinity, pC.X, pC.Y, pC.Z, pC.Infinity, e) print def check_symbolic_function(R, assumeAssert, assumeBranch, f, A, B, pa, pb, pA, pB, pC): assumeLaw, require = f(A, B, pa, pb, pA, pB, pC) return check_symbolic(R, assumeLaw, assumeAssert, assumeBranch, require) def check_symbolic_jacobian_weierstrass(name, A, B, branches, formula): """Verify an implementation of addition of Jacobian points on a Weierstrass curve symbolically""" R.<ax,bx,ay,by,Az,Bz,Ai,Bi> = PolynomialRing(QQ,8,order='invlex') lift = lambda x: fastfrac(R,x) ax = lift(ax) ay = lift(ay) Az = lift(Az) bx = lift(bx) by = lift(by) Bz = lift(Bz) Ai = lift(Ai) Bi = lift(Bi) pa = affinepoint(ax, ay, Ai) pb = affinepoint(bx, by, Bi) pA = jacobianpoint(ax * Az^2, ay * Az^3, Az, Ai) pB = jacobianpoint(bx * Bz^2, by * Bz^3, Bz, Bi) res = {} for key in laws_jacobian_weierstrass: res[key] = [] print ("Formula " + name + ":") count = 0 for branch in xrange(branches): assumeFormula, assumeBranch, pC = formula(branch, pA, pB) pC.X = lift(pC.X) pC.Y = lift(pC.Y) pC.Z = lift(pC.Z) pC.Infinity = lift(pC.Infinity) for key in laws_jacobian_weierstrass: res[key].append((check_symbolic_function(R, assumeFormula, assumeBranch, laws_jacobian_weierstrass[key], A, B, pa, pb, pA, pB, pC), branch)) for key in res: print " %s:" % key val = res[key] for x in val: if x[0] is not None: print " branch %i: %s" % (x[1], x[0]) print
crypto/secp256k1/libsecp256k1/sage/weierstrass_prover.sage
0
https://github.com/ethereum/go-ethereum/commit/86dd005544179818edd78ef6c9396b9574e8a614
[ 0.00017610019131097943, 0.00017019937513396144, 0.00016246414452325553, 0.00017042318359017372, 0.000003065612645514193 ]
{ "id": 0, "code_window": [ "// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.\n", "\n", "package trie\n", "\n", "import (\n", "\t\"fmt\"\n", "\t\"sync\"\n", "\n", "\t\"github.com/ethereum/go-ethereum/common\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\"errors\"\n" ], "file_path": "trie/stacktrie.go", "type": "add", "edit_start_line_idx": 19 }
[{"X":"0000000000000000000000000000000000000000000000000000000000000000","Y":"0000000000000000000000000000000000000000000000000000000000000000","Expected":"0000000000000000000000000000000000000000000000000000000000000000"},{"X":"0000000000000000000000000000000000000000000000000000000000000000","Y":"0000000000000000000000000000000000000000000000000000000000000001","Expected":"0000000000000000000000000000000000000000000000000000000000000001"},{"X":"0000000000000000000000000000000000000000000000000000000000000000","Y":"0000000000000000000000000000000000000000000000000000000000000005","Expected":"0000000000000000000000000000000000000000000000000000000000000005"},{"X":"0000000000000000000000000000000000000000000000000000000000000000","Y":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe","Expected":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe"},{"X":"0000000000000000000000000000000000000000000000000000000000000000","Y":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Expected":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},{"X":"0000000000000000000000000000000000000000000000000000000000000000","Y":"8000000000000000000000000000000000000000000000000000000000000000","Expected":"8000000000000000000000000000000000000000000000000000000000000000"},{"X":"0000000000000000000000000000000000000000000000000000000000000000","Y":"8000000000000000000000000000000000000000000000000000000000000001","Expected":"8000000000000000000000000000000000000000000000000000000000000001"},{"X":"0000000000000000000000000000000000000000000000000000000000000000","Y":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb","Expected":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb"},{"X":"0000000000000000000000000000000000000000000000000000000000000000","Y":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Expected":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},{"X":"0000000000000000000000000000000000000000000000000000000000000001","Y":"0000000000000000000000000000000000000000000000000000000000000000","Expected":"0000000000000000000000000000000000000000000000000000000000000001"},{"X":"0000000000000000000000000000000000000000000000000000000000000001","Y":"0000000000000000000000000000000000000000000000000000000000000001","Expected":"0000000000000000000000000000000000000000000000000000000000000002"},{"X":"0000000000000000000000000000000000000000000000000000000000000001","Y":"0000000000000000000000000000000000000000000000000000000000000005","Expected":"0000000000000000000000000000000000000000000000000000000000000006"},{"X":"0000000000000000000000000000000000000000000000000000000000000001","Y":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe","Expected":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},{"X":"0000000000000000000000000000000000000000000000000000000000000001","Y":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Expected":"8000000000000000000000000000000000000000000000000000000000000000"},{"X":"0000000000000000000000000000000000000000000000000000000000000001","Y":"8000000000000000000000000000000000000000000000000000000000000000","Expected":"8000000000000000000000000000000000000000000000000000000000000001"},{"X":"0000000000000000000000000000000000000000000000000000000000000001","Y":"8000000000000000000000000000000000000000000000000000000000000001","Expected":"8000000000000000000000000000000000000000000000000000000000000002"},{"X":"0000000000000000000000000000000000000000000000000000000000000001","Y":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb","Expected":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"},{"X":"0000000000000000000000000000000000000000000000000000000000000001","Y":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Expected":"0000000000000000000000000000000000000000000000000000000000000000"},{"X":"0000000000000000000000000000000000000000000000000000000000000005","Y":"0000000000000000000000000000000000000000000000000000000000000000","Expected":"0000000000000000000000000000000000000000000000000000000000000005"},{"X":"0000000000000000000000000000000000000000000000000000000000000005","Y":"0000000000000000000000000000000000000000000000000000000000000001","Expected":"0000000000000000000000000000000000000000000000000000000000000006"},{"X":"0000000000000000000000000000000000000000000000000000000000000005","Y":"0000000000000000000000000000000000000000000000000000000000000005","Expected":"000000000000000000000000000000000000000000000000000000000000000a"},{"X":"0000000000000000000000000000000000000000000000000000000000000005","Y":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe","Expected":"8000000000000000000000000000000000000000000000000000000000000003"},{"X":"0000000000000000000000000000000000000000000000000000000000000005","Y":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Expected":"8000000000000000000000000000000000000000000000000000000000000004"},{"X":"0000000000000000000000000000000000000000000000000000000000000005","Y":"8000000000000000000000000000000000000000000000000000000000000000","Expected":"8000000000000000000000000000000000000000000000000000000000000005"},{"X":"0000000000000000000000000000000000000000000000000000000000000005","Y":"8000000000000000000000000000000000000000000000000000000000000001","Expected":"8000000000000000000000000000000000000000000000000000000000000006"},{"X":"0000000000000000000000000000000000000000000000000000000000000005","Y":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb","Expected":"0000000000000000000000000000000000000000000000000000000000000000"},{"X":"0000000000000000000000000000000000000000000000000000000000000005","Y":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Expected":"0000000000000000000000000000000000000000000000000000000000000004"},{"X":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe","Y":"0000000000000000000000000000000000000000000000000000000000000000","Expected":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe"},{"X":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe","Y":"0000000000000000000000000000000000000000000000000000000000000001","Expected":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},{"X":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe","Y":"0000000000000000000000000000000000000000000000000000000000000005","Expected":"8000000000000000000000000000000000000000000000000000000000000003"},{"X":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe","Y":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe","Expected":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"},{"X":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe","Y":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Expected":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd"},{"X":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe","Y":"8000000000000000000000000000000000000000000000000000000000000000","Expected":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe"},{"X":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe","Y":"8000000000000000000000000000000000000000000000000000000000000001","Expected":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},{"X":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe","Y":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb","Expected":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9"},{"X":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe","Y":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Expected":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd"},{"X":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Y":"0000000000000000000000000000000000000000000000000000000000000000","Expected":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},{"X":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Y":"0000000000000000000000000000000000000000000000000000000000000001","Expected":"8000000000000000000000000000000000000000000000000000000000000000"},{"X":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Y":"0000000000000000000000000000000000000000000000000000000000000005","Expected":"8000000000000000000000000000000000000000000000000000000000000004"},{"X":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Y":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe","Expected":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd"},{"X":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Y":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Expected":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe"},{"X":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Y":"8000000000000000000000000000000000000000000000000000000000000000","Expected":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},{"X":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Y":"8000000000000000000000000000000000000000000000000000000000000001","Expected":"0000000000000000000000000000000000000000000000000000000000000000"},{"X":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Y":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb","Expected":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa"},{"X":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Y":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Expected":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe"},{"X":"8000000000000000000000000000000000000000000000000000000000000000","Y":"0000000000000000000000000000000000000000000000000000000000000000","Expected":"8000000000000000000000000000000000000000000000000000000000000000"},{"X":"8000000000000000000000000000000000000000000000000000000000000000","Y":"0000000000000000000000000000000000000000000000000000000000000001","Expected":"8000000000000000000000000000000000000000000000000000000000000001"},{"X":"8000000000000000000000000000000000000000000000000000000000000000","Y":"0000000000000000000000000000000000000000000000000000000000000005","Expected":"8000000000000000000000000000000000000000000000000000000000000005"},{"X":"8000000000000000000000000000000000000000000000000000000000000000","Y":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe","Expected":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe"},{"X":"8000000000000000000000000000000000000000000000000000000000000000","Y":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Expected":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},{"X":"8000000000000000000000000000000000000000000000000000000000000000","Y":"8000000000000000000000000000000000000000000000000000000000000000","Expected":"0000000000000000000000000000000000000000000000000000000000000000"},{"X":"8000000000000000000000000000000000000000000000000000000000000000","Y":"8000000000000000000000000000000000000000000000000000000000000001","Expected":"0000000000000000000000000000000000000000000000000000000000000001"},{"X":"8000000000000000000000000000000000000000000000000000000000000000","Y":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb","Expected":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb"},{"X":"8000000000000000000000000000000000000000000000000000000000000000","Y":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Expected":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},{"X":"8000000000000000000000000000000000000000000000000000000000000001","Y":"0000000000000000000000000000000000000000000000000000000000000000","Expected":"8000000000000000000000000000000000000000000000000000000000000001"},{"X":"8000000000000000000000000000000000000000000000000000000000000001","Y":"0000000000000000000000000000000000000000000000000000000000000001","Expected":"8000000000000000000000000000000000000000000000000000000000000002"},{"X":"8000000000000000000000000000000000000000000000000000000000000001","Y":"0000000000000000000000000000000000000000000000000000000000000005","Expected":"8000000000000000000000000000000000000000000000000000000000000006"},{"X":"8000000000000000000000000000000000000000000000000000000000000001","Y":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe","Expected":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},{"X":"8000000000000000000000000000000000000000000000000000000000000001","Y":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Expected":"0000000000000000000000000000000000000000000000000000000000000000"},{"X":"8000000000000000000000000000000000000000000000000000000000000001","Y":"8000000000000000000000000000000000000000000000000000000000000000","Expected":"0000000000000000000000000000000000000000000000000000000000000001"},{"X":"8000000000000000000000000000000000000000000000000000000000000001","Y":"8000000000000000000000000000000000000000000000000000000000000001","Expected":"0000000000000000000000000000000000000000000000000000000000000002"},{"X":"8000000000000000000000000000000000000000000000000000000000000001","Y":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb","Expected":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"},{"X":"8000000000000000000000000000000000000000000000000000000000000001","Y":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Expected":"8000000000000000000000000000000000000000000000000000000000000000"},{"X":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb","Y":"0000000000000000000000000000000000000000000000000000000000000000","Expected":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb"},{"X":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb","Y":"0000000000000000000000000000000000000000000000000000000000000001","Expected":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"},{"X":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb","Y":"0000000000000000000000000000000000000000000000000000000000000005","Expected":"0000000000000000000000000000000000000000000000000000000000000000"},{"X":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb","Y":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe","Expected":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9"},{"X":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb","Y":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Expected":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa"},{"X":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb","Y":"8000000000000000000000000000000000000000000000000000000000000000","Expected":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb"},{"X":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb","Y":"8000000000000000000000000000000000000000000000000000000000000001","Expected":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"},{"X":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb","Y":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb","Expected":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6"},{"X":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb","Y":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Expected":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa"},{"X":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Y":"0000000000000000000000000000000000000000000000000000000000000000","Expected":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},{"X":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Y":"0000000000000000000000000000000000000000000000000000000000000001","Expected":"0000000000000000000000000000000000000000000000000000000000000000"},{"X":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Y":"0000000000000000000000000000000000000000000000000000000000000005","Expected":"0000000000000000000000000000000000000000000000000000000000000004"},{"X":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Y":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe","Expected":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd"},{"X":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Y":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Expected":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe"},{"X":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Y":"8000000000000000000000000000000000000000000000000000000000000000","Expected":"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},{"X":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Y":"8000000000000000000000000000000000000000000000000000000000000001","Expected":"8000000000000000000000000000000000000000000000000000000000000000"},{"X":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Y":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb","Expected":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa"},{"X":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Y":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","Expected":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe"}]
core/vm/testdata/testcases_add.json
0
https://github.com/ethereum/go-ethereum/commit/86dd005544179818edd78ef6c9396b9574e8a614
[ 0.0038521396927535534, 0.0038521396927535534, 0.0038521396927535534, 0.0038521396927535534, 0 ]
{ "id": 0, "code_window": [ "// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.\n", "\n", "package trie\n", "\n", "import (\n", "\t\"fmt\"\n", "\t\"sync\"\n", "\n", "\t\"github.com/ethereum/go-ethereum/common\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\"errors\"\n" ], "file_path": "trie/stacktrie.go", "type": "add", "edit_start_line_idx": 19 }
// +build !go1.4 package log import ( "sync/atomic" "unsafe" ) // swapHandler wraps another handler that may be swapped out // dynamically at runtime in a thread-safe fashion. type swapHandler struct { handler unsafe.Pointer } func (h *swapHandler) Log(r *Record) error { return h.Get().Log(r) } func (h *swapHandler) Get() Handler { return *(*Handler)(atomic.LoadPointer(&h.handler)) } func (h *swapHandler) Swap(newHandler Handler) { atomic.StorePointer(&h.handler, unsafe.Pointer(&newHandler)) }
log/handler_go13.go
0
https://github.com/ethereum/go-ethereum/commit/86dd005544179818edd78ef6c9396b9574e8a614
[ 0.0003386034513823688, 0.0002234099229099229, 0.00016511046851519495, 0.00016651586338412017, 0.00008145614265231416 ]
{ "id": 1, "code_window": [ "\t\"github.com/ethereum/go-ethereum/log\"\n", "\t\"github.com/ethereum/go-ethereum/rlp\"\n", ")\n", "\n", "var stPool = sync.Pool{\n", "\tNew: func() interface{} {\n", "\t\treturn NewStackTrie(nil)\n", "\t},\n", "}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "var ErrCommitDisabled = errors.New(\"no database for committing\")\n", "\n" ], "file_path": "trie/stacktrie.go", "type": "add", "edit_start_line_idx": 28 }
// Copyright 2020 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 trie import ( "fmt" "sync" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/rlp" ) var stPool = sync.Pool{ New: func() interface{} { return NewStackTrie(nil) }, } func stackTrieFromPool(db ethdb.KeyValueStore) *StackTrie { st := stPool.Get().(*StackTrie) st.db = db return st } func returnToPool(st *StackTrie) { st.Reset() stPool.Put(st) } // StackTrie is a trie implementation that expects keys to be inserted // in order. Once it determines that a subtree will no longer be inserted // into, it will hash it and free up the memory it uses. type StackTrie struct { nodeType uint8 // node type (as in branch, ext, leaf) val []byte // value contained by this node if it's a leaf key []byte // key chunk covered by this (full|ext) node keyOffset int // offset of the key chunk inside a full key children [16]*StackTrie // list of children (for fullnodes and exts) db ethdb.KeyValueStore // Pointer to the commit db, can be nil } // NewStackTrie allocates and initializes an empty trie. func NewStackTrie(db ethdb.KeyValueStore) *StackTrie { return &StackTrie{ nodeType: emptyNode, db: db, } } func newLeaf(ko int, key, val []byte, db ethdb.KeyValueStore) *StackTrie { st := stackTrieFromPool(db) st.nodeType = leafNode st.keyOffset = ko st.key = append(st.key, key[ko:]...) st.val = val return st } func newExt(ko int, key []byte, child *StackTrie, db ethdb.KeyValueStore) *StackTrie { st := stackTrieFromPool(db) st.nodeType = extNode st.keyOffset = ko st.key = append(st.key, key[ko:]...) st.children[0] = child return st } // List all values that StackTrie#nodeType can hold const ( emptyNode = iota branchNode extNode leafNode hashedNode ) // TryUpdate inserts a (key, value) pair into the stack trie func (st *StackTrie) TryUpdate(key, value []byte) error { k := keybytesToHex(key) if len(value) == 0 { panic("deletion not supported") } st.insert(k[:len(k)-1], value) return nil } func (st *StackTrie) Update(key, value []byte) { if err := st.TryUpdate(key, value); err != nil { log.Error(fmt.Sprintf("Unhandled trie error: %v", err)) } } func (st *StackTrie) Reset() { st.db = nil st.key = st.key[:0] st.val = st.val[:0] for i := range st.children { st.children[i] = nil } st.nodeType = emptyNode st.keyOffset = 0 } // Helper function that, given a full key, determines the index // at which the chunk pointed by st.keyOffset is different from // the same chunk in the full key. func (st *StackTrie) getDiffIndex(key []byte) int { diffindex := 0 for ; diffindex < len(st.key) && st.key[diffindex] == key[st.keyOffset+diffindex]; diffindex++ { } return diffindex } // Helper function to that inserts a (key, value) pair into // the trie. func (st *StackTrie) insert(key, value []byte) { switch st.nodeType { case branchNode: /* Branch */ idx := int(key[st.keyOffset]) // Unresolve elder siblings for i := idx - 1; i >= 0; i-- { if st.children[i] != nil { if st.children[i].nodeType != hashedNode { st.children[i].hash() } break } } // Add new child if st.children[idx] == nil { st.children[idx] = stackTrieFromPool(st.db) st.children[idx].keyOffset = st.keyOffset + 1 } st.children[idx].insert(key, value) case extNode: /* Ext */ // Compare both key chunks and see where they differ diffidx := st.getDiffIndex(key) // Check if chunks are identical. If so, recurse into // the child node. Otherwise, the key has to be split // into 1) an optional common prefix, 2) the fullnode // representing the two differing path, and 3) a leaf // for each of the differentiated subtrees. if diffidx == len(st.key) { // Ext key and key segment are identical, recurse into // the child node. st.children[0].insert(key, value) return } // Save the original part. Depending if the break is // at the extension's last byte or not, create an // intermediate extension or use the extension's child // node directly. var n *StackTrie if diffidx < len(st.key)-1 { n = newExt(diffidx+1, st.key, st.children[0], st.db) } else { // Break on the last byte, no need to insert // an extension node: reuse the current node n = st.children[0] } // Convert to hash n.hash() var p *StackTrie if diffidx == 0 { // the break is on the first byte, so // the current node is converted into // a branch node. st.children[0] = nil p = st st.nodeType = branchNode } else { // the common prefix is at least one byte // long, insert a new intermediate branch // node. st.children[0] = stackTrieFromPool(st.db) st.children[0].nodeType = branchNode st.children[0].keyOffset = st.keyOffset + diffidx p = st.children[0] } // Create a leaf for the inserted part o := newLeaf(st.keyOffset+diffidx+1, key, value, st.db) // Insert both child leaves where they belong: origIdx := st.key[diffidx] newIdx := key[diffidx+st.keyOffset] p.children[origIdx] = n p.children[newIdx] = o st.key = st.key[:diffidx] case leafNode: /* Leaf */ // Compare both key chunks and see where they differ diffidx := st.getDiffIndex(key) // Overwriting a key isn't supported, which means that // the current leaf is expected to be split into 1) an // optional extension for the common prefix of these 2 // keys, 2) a fullnode selecting the path on which the // keys differ, and 3) one leaf for the differentiated // component of each key. if diffidx >= len(st.key) { panic("Trying to insert into existing key") } // Check if the split occurs at the first nibble of the // chunk. In that case, no prefix extnode is necessary. // Otherwise, create that var p *StackTrie if diffidx == 0 { // Convert current leaf into a branch st.nodeType = branchNode p = st st.children[0] = nil } else { // Convert current node into an ext, // and insert a child branch node. st.nodeType = extNode st.children[0] = NewStackTrie(st.db) st.children[0].nodeType = branchNode st.children[0].keyOffset = st.keyOffset + diffidx p = st.children[0] } // Create the two child leaves: the one containing the // original value and the one containing the new value // The child leave will be hashed directly in order to // free up some memory. origIdx := st.key[diffidx] p.children[origIdx] = newLeaf(diffidx+1, st.key, st.val, st.db) p.children[origIdx].hash() newIdx := key[diffidx+st.keyOffset] p.children[newIdx] = newLeaf(p.keyOffset+1, key, value, st.db) // Finally, cut off the key part that has been passed // over to the children. st.key = st.key[:diffidx] st.val = nil case emptyNode: /* Empty */ st.nodeType = leafNode st.key = key[st.keyOffset:] st.val = value case hashedNode: panic("trying to insert into hash") default: panic("invalid type") } } // hash() hashes the node 'st' and converts it into 'hashedNode', if possible. // Possible outcomes: // 1. The rlp-encoded value was >= 32 bytes: // - Then the 32-byte `hash` will be accessible in `st.val`. // - And the 'st.type' will be 'hashedNode' // 2. The rlp-encoded value was < 32 bytes // - Then the <32 byte rlp-encoded value will be accessible in 'st.val'. // - And the 'st.type' will be 'hashedNode' AGAIN // // This method will also: // set 'st.type' to hashedNode // clear 'st.key' func (st *StackTrie) hash() { /* Shortcut if node is already hashed */ if st.nodeType == hashedNode { return } // The 'hasher' is taken from a pool, but we don't actually // claim an instance until all children are done with their hashing, // and we actually need one var h *hasher switch st.nodeType { case branchNode: var nodes [17]node for i, child := range st.children { if child == nil { nodes[i] = nilValueNode continue } child.hash() if len(child.val) < 32 { nodes[i] = rawNode(child.val) } else { nodes[i] = hashNode(child.val) } st.children[i] = nil // Reclaim mem from subtree returnToPool(child) } nodes[16] = nilValueNode h = newHasher(false) defer returnHasherToPool(h) h.tmp.Reset() if err := rlp.Encode(&h.tmp, nodes); err != nil { panic(err) } case extNode: h = newHasher(false) defer returnHasherToPool(h) h.tmp.Reset() st.children[0].hash() // This is also possible: //sz := hexToCompactInPlace(st.key) //n := [][]byte{ // st.key[:sz], // st.children[0].val, //} n := [][]byte{ hexToCompact(st.key), st.children[0].val, } if err := rlp.Encode(&h.tmp, n); err != nil { panic(err) } returnToPool(st.children[0]) st.children[0] = nil // Reclaim mem from subtree case leafNode: h = newHasher(false) defer returnHasherToPool(h) h.tmp.Reset() st.key = append(st.key, byte(16)) sz := hexToCompactInPlace(st.key) n := [][]byte{st.key[:sz], st.val} if err := rlp.Encode(&h.tmp, n); err != nil { panic(err) } case emptyNode: st.val = st.val[:0] st.val = append(st.val, emptyRoot[:]...) st.key = st.key[:0] st.nodeType = hashedNode return default: panic("Invalid node type") } st.key = st.key[:0] st.nodeType = hashedNode if len(h.tmp) < 32 { st.val = st.val[:0] st.val = append(st.val, h.tmp...) return } // Going to write the hash to the 'val'. Need to ensure it's properly sized first // Typically, 'branchNode's will have no 'val', and require this allocation if required := 32 - len(st.val); required > 0 { buf := make([]byte, required) st.val = append(st.val, buf...) } st.val = st.val[:32] h.sha.Reset() h.sha.Write(h.tmp) h.sha.Read(st.val) if st.db != nil { // TODO! Is it safe to Put the slice here? // Do all db implementations copy the value provided? st.db.Put(st.val, h.tmp) } } // Hash returns the hash of the current node func (st *StackTrie) Hash() (h common.Hash) { st.hash() if len(st.val) != 32 { // If the node's RLP isn't 32 bytes long, the node will not // be hashed, and instead contain the rlp-encoding of the // node. For the top level node, we need to force the hashing. ret := make([]byte, 32) h := newHasher(false) defer returnHasherToPool(h) h.sha.Reset() h.sha.Write(st.val) h.sha.Read(ret) return common.BytesToHash(ret) } return common.BytesToHash(st.val) } // Commit will commit the current node to database db func (st *StackTrie) Commit(db ethdb.KeyValueStore) common.Hash { oldDb := st.db st.db = db defer func() { st.db = oldDb }() st.hash() h := common.BytesToHash(st.val) return h }
trie/stacktrie.go
1
https://github.com/ethereum/go-ethereum/commit/86dd005544179818edd78ef6c9396b9574e8a614
[ 0.9986255168914795, 0.11243975907564163, 0.0001617150119272992, 0.0003507300280034542, 0.29800695180892944 ]
{ "id": 1, "code_window": [ "\t\"github.com/ethereum/go-ethereum/log\"\n", "\t\"github.com/ethereum/go-ethereum/rlp\"\n", ")\n", "\n", "var stPool = sync.Pool{\n", "\tNew: func() interface{} {\n", "\t\treturn NewStackTrie(nil)\n", "\t},\n", "}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "var ErrCommitDisabled = errors.New(\"no database for committing\")\n", "\n" ], "file_path": "trie/stacktrie.go", "type": "add", "edit_start_line_idx": 28 }
package bn256 // For details of the algorithms used, see "Multiplication and Squaring on // Pairing-Friendly Fields, Devegili et al. // http://eprint.iacr.org/2006/471.pdf. import ( "math/big" ) // gfP12 implements the field of size p¹² as a quadratic extension of gfP6 // where ω²=τ. type gfP12 struct { x, y gfP6 // value is xω + y } func (e *gfP12) String() string { return "(" + e.x.String() + "," + e.y.String() + ")" } func (e *gfP12) Set(a *gfP12) *gfP12 { e.x.Set(&a.x) e.y.Set(&a.y) return e } func (e *gfP12) SetZero() *gfP12 { e.x.SetZero() e.y.SetZero() return e } func (e *gfP12) SetOne() *gfP12 { e.x.SetZero() e.y.SetOne() return e } func (e *gfP12) IsZero() bool { return e.x.IsZero() && e.y.IsZero() } func (e *gfP12) IsOne() bool { return e.x.IsZero() && e.y.IsOne() } func (e *gfP12) Conjugate(a *gfP12) *gfP12 { e.x.Neg(&a.x) e.y.Set(&a.y) return e } func (e *gfP12) Neg(a *gfP12) *gfP12 { e.x.Neg(&a.x) e.y.Neg(&a.y) return e } // Frobenius computes (xω+y)^p = x^p ω·ξ^((p-1)/6) + y^p func (e *gfP12) Frobenius(a *gfP12) *gfP12 { e.x.Frobenius(&a.x) e.y.Frobenius(&a.y) e.x.MulScalar(&e.x, xiToPMinus1Over6) return e } // FrobeniusP2 computes (xω+y)^p² = x^p² ω·ξ^((p²-1)/6) + y^p² func (e *gfP12) FrobeniusP2(a *gfP12) *gfP12 { e.x.FrobeniusP2(&a.x) e.x.MulGFP(&e.x, xiToPSquaredMinus1Over6) e.y.FrobeniusP2(&a.y) return e } func (e *gfP12) FrobeniusP4(a *gfP12) *gfP12 { e.x.FrobeniusP4(&a.x) e.x.MulGFP(&e.x, xiToPSquaredMinus1Over3) e.y.FrobeniusP4(&a.y) return e } func (e *gfP12) Add(a, b *gfP12) *gfP12 { e.x.Add(&a.x, &b.x) e.y.Add(&a.y, &b.y) return e } func (e *gfP12) Sub(a, b *gfP12) *gfP12 { e.x.Sub(&a.x, &b.x) e.y.Sub(&a.y, &b.y) return e } func (e *gfP12) Mul(a, b *gfP12) *gfP12 { tx := (&gfP6{}).Mul(&a.x, &b.y) t := (&gfP6{}).Mul(&b.x, &a.y) tx.Add(tx, t) ty := (&gfP6{}).Mul(&a.y, &b.y) t.Mul(&a.x, &b.x).MulTau(t) e.x.Set(tx) e.y.Add(ty, t) return e } func (e *gfP12) MulScalar(a *gfP12, b *gfP6) *gfP12 { e.x.Mul(&e.x, b) e.y.Mul(&e.y, b) return e } func (c *gfP12) Exp(a *gfP12, power *big.Int) *gfP12 { sum := (&gfP12{}).SetOne() t := &gfP12{} for i := power.BitLen() - 1; i >= 0; i-- { t.Square(sum) if power.Bit(i) != 0 { sum.Mul(t, a) } else { sum.Set(t) } } c.Set(sum) return c } func (e *gfP12) Square(a *gfP12) *gfP12 { // Complex squaring algorithm v0 := (&gfP6{}).Mul(&a.x, &a.y) t := (&gfP6{}).MulTau(&a.x) t.Add(&a.y, t) ty := (&gfP6{}).Add(&a.x, &a.y) ty.Mul(ty, t).Sub(ty, v0) t.MulTau(v0) ty.Sub(ty, t) e.x.Add(v0, v0) e.y.Set(ty) return e } func (e *gfP12) Invert(a *gfP12) *gfP12 { // See "Implementing cryptographic pairings", M. Scott, section 3.2. // ftp://136.206.11.249/pub/crypto/pairings.pdf t1, t2 := &gfP6{}, &gfP6{} t1.Square(&a.x) t2.Square(&a.y) t1.MulTau(t1).Sub(t2, t1) t2.Invert(t1) e.x.Neg(&a.x) e.y.Set(&a.y) e.MulScalar(e, t2) return e }
crypto/bn256/cloudflare/gfp12.go
0
https://github.com/ethereum/go-ethereum/commit/86dd005544179818edd78ef6c9396b9574e8a614
[ 0.00018069869838654995, 0.00017163058510050178, 0.00016005546785891056, 0.0001714245299808681, 0.000004401892965688603 ]
{ "id": 1, "code_window": [ "\t\"github.com/ethereum/go-ethereum/log\"\n", "\t\"github.com/ethereum/go-ethereum/rlp\"\n", ")\n", "\n", "var stPool = sync.Pool{\n", "\tNew: func() interface{} {\n", "\t\treturn NewStackTrie(nil)\n", "\t},\n", "}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "var ErrCommitDisabled = errors.New(\"no database for committing\")\n", "\n" ], "file_path": "trie/stacktrie.go", "type": "add", "edit_start_line_idx": 28 }
// Copyright 2020 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 utesting import ( "strings" "testing" ) func TestTest(t *testing.T) { tests := []Test{ { Name: "successful test", Fn: func(t *T) {}, }, { Name: "failing test", Fn: func(t *T) { t.Log("output") t.Error("failed") }, }, { Name: "panicking test", Fn: func(t *T) { panic("oh no") }, }, } results := RunTests(tests, nil) if results[0].Failed || results[0].Output != "" { t.Fatalf("wrong result for successful test: %#v", results[0]) } if !results[1].Failed || results[1].Output != "output\nfailed\n" { t.Fatalf("wrong result for failing test: %#v", results[1]) } if !results[2].Failed || !strings.HasPrefix(results[2].Output, "panic: oh no\n") { t.Fatalf("wrong result for panicking test: %#v", results[2]) } }
internal/utesting/utesting_test.go
0
https://github.com/ethereum/go-ethereum/commit/86dd005544179818edd78ef6c9396b9574e8a614
[ 0.00017769854457583278, 0.00016975983453448862, 0.00016171486640814692, 0.00017082462727557868, 0.00000535710978510906 ]
{ "id": 1, "code_window": [ "\t\"github.com/ethereum/go-ethereum/log\"\n", "\t\"github.com/ethereum/go-ethereum/rlp\"\n", ")\n", "\n", "var stPool = sync.Pool{\n", "\tNew: func() interface{} {\n", "\t\treturn NewStackTrie(nil)\n", "\t},\n", "}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "var ErrCommitDisabled = errors.New(\"no database for committing\")\n", "\n" ], "file_path": "trie/stacktrie.go", "type": "add", "edit_start_line_idx": 28 }
[ { "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e10000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1", "Expected": "000000000000000000000000000000000572cbea904d67468808c8eb50a9450c9721db309128012543902d0ac358a62ae28f75bb8f1c7c42c39a8c5529bf0f4e00000000000000000000000000000000166a9d8cabc673a322fda673779d8e3822ba3ecb8670e461f73bb9021d5fd76a4c56d9d4cd16bd1bba86881979749d28", "Name": "bls_g1add_(g1+g1=2*g1)", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000572cbea904d67468808c8eb50a9450c9721db309128012543902d0ac358a62ae28f75bb8f1c7c42c39a8c5529bf0f4e00000000000000000000000000000000166a9d8cabc673a322fda673779d8e3822ba3ecb8670e461f73bb9021d5fd76a4c56d9d4cd16bd1bba86881979749d280000000000000000000000000000000009ece308f9d1f0131765212deca99697b112d61f9be9a5f1f3780a51335b3ff981747a0b2ca2179b96d2c0c9024e522400000000000000000000000000000000032b80d3a6f5b09f8a84623389c5f80ca69a0cddabc3097f9d9c27310fd43be6e745256c634af45ca3473b0590ae30d1", "Expected": "0000000000000000000000000000000010e7791fb972fe014159aa33a98622da3cdc98ff707965e536d8636b5fcc5ac7a91a8c46e59a00dca575af0f18fb13dc0000000000000000000000000000000016ba437edcc6551e30c10512367494bfb6b01cc6681e8a4c3cd2501832ab5c4abc40b4578b85cbaffbf0bcd70d67c6e2", "Name": "bls_g1add_(2*g1+3*g1=5*g1)", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "Expected": "0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1", "Name": "bls_g1add_(inf+g1=g1)", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "Expected": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "Name": "bls_g1add_(inf+inf=inf)", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000012196c5a43d69224d8713389285f26b98f86ee910ab3dd668e413738282003cc5b7357af9a7af54bb713d62255e80f560000000000000000000000000000000006ba8102bfbeea4416b710c73e8cce3032c31c6269c44906f8ac4f7874ce99fb17559992486528963884ce429a992fee000000000000000000000000000000000001101098f5c39893765766af4512a0c74e1bb89bc7e6fdf14e3e7337d257cc0f94658179d83320b99f31ff94cd2bac0000000000000000000000000000000003e1a9f9f44ca2cdab4f43a1a3ee3470fdf90b2fc228eb3b709fcd72f014838ac82a6d797aeefed9a0804b22ed1ce8f7", "Expected": "000000000000000000000000000000001466e1373ae4a7e7ba885c5f0c3ccfa48cdb50661646ac6b779952f466ac9fc92730dcaed9be831cd1f8c4fefffd5209000000000000000000000000000000000c1fb750d2285d4ca0378e1e8cdbf6044151867c34a711b73ae818aee6dbe9e886f53d7928cc6ed9c851e0422f609b11", "Name": "matter_g1_add_0", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000117dbe419018f67844f6a5e1b78a1e597283ad7b8ee7ac5e58846f5a5fd68d0da99ce235a91db3ec1cf340fe6b7afcdb0000000000000000000000000000000013316f23de032d25e912ae8dc9b54c8dba1be7cecdbb9d2228d7e8f652011d46be79089dd0a6080a73c82256ce5e4ed2000000000000000000000000000000000441e7f7f96198e4c23bd5eb16f1a7f045dbc8c53219ab2bcea91d3a027e2dfe659feac64905f8b9add7e4bfc91bec2b0000000000000000000000000000000005fc51bb1b40c87cd4292d4b66f8ca5ce4ef9abd2b69d4464b4879064203bda7c9fc3f896a3844ebc713f7bb20951d95", "Expected": "0000000000000000000000000000000016b8ab56b45a9294466809b8e858c1ad15ad0d52cfcb62f8f5753dc94cee1de6efaaebce10701e3ec2ecaa9551024ea600000000000000000000000000000000124571eec37c0b1361023188d66ec17c1ec230d31b515e0e81e599ec19e40c8a7c8cdea9735bc3d8b4e37ca7e5dd71f6", "Name": "matter_g1_add_1", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000008ab7b556c672db7883ec47efa6d98bb08cec7902ebb421aac1c31506b177ac444ffa2d9b400a6f1cbdc6240c607ee110000000000000000000000000000000016b7fa9adf4addc2192271ce7ad3c8d8f902d061c43b7d2e8e26922009b777855bffabe7ed1a09155819eabfa87f276f00000000000000000000000000000000114c3f11ba0b47551fa28f09f148936d6b290dc9f2d0534a83c32b0b849ab921ce6bcaa4ff3c917707798d9c74f2084f00000000000000000000000000000000149dc028207fb04a7795d94ea65e21f9952e445000eb954531ee519efde6901675d3d2446614d243efb77a9cfe0ca3ae", "Expected": "0000000000000000000000000000000002ce7a08719448494857102da464bc65a47c95c77819af325055a23ac50b626df4732daf63feb9a663d71b7c9b8f2c510000000000000000000000000000000016117e87e9b55bd4bd5763d69d5240d30745e014b9aef87c498f9a9e3286ec4d5927df7cd5a2e54ac4179e78645acf27", "Name": "matter_g1_add_2", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000015ff9a232d9b5a8020a85d5fe08a1dcfb73ece434258fe0e2fddf10ddef0906c42dcb5f5d62fc97f934ba900f17beb330000000000000000000000000000000009cfe4ee2241d9413c616462d7bac035a6766aeaab69c81e094d75b840df45d7e0dfac0265608b93efefb9a8728b98e4000000000000000000000000000000000c3d564ac1fe12f18f528c3750583ab6af8973bff3eded7bb4778c32805d9b17846cc7c687af0f46bc87de7748ab72980000000000000000000000000000000002f164c131cbd5afc85692c246157d38dc4bbb2959d2edfa6daf0a8b17c7a898aad53b400e8bdc2b29bf6688ee863db7", "Expected": "0000000000000000000000000000000015510826f50b88fa369caf062ecdf8b03a67e660a35b219b44437a5583b5a9adf76991dce7bff9afc50257f847299504000000000000000000000000000000000a83e879895a1b47dbd6cd25ce8b719e7490cfe021614f7539e841fc2f9c09f071e386676de60b6579aa4bf6d37b13dd", "Name": "matter_g1_add_3", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000017a17b82e3bfadf3250210d8ef572c02c3610d65ab4d7366e0b748768a28ee6a1b51f77ed686a64f087f36f641e7dca900000000000000000000000000000000077ea73d233ccea51dc4d5acecf6d9332bf17ae51598f4b394a5f62fb387e9c9aa1d6823b64a074f5873422ca57545d30000000000000000000000000000000019fe3a64361fea14936ff0b3e630471494d0c0b9423e6a004184a2965221c18849b5ed0eb2708a587323d8d6c6735a90000000000000000000000000000000000340823d314703e5efeb0a65c23069199d7dfff8793aaacb98cdcd6177fc8e61ab3294c57bf13b4406266715752ef3e6", "Expected": "00000000000000000000000000000000010b1c96d3910f56b0bf54da5ae8c7ab674a07f8143b61fed660e7309e626dc73eaa2b11886cdb82e2b6735e7802cc860000000000000000000000000000000002dabbbedd72872c2c012e7e893d2f3df1834c43873315488d814ddd6bfcca6758a18aa6bd02a0f3aed962cb51f0a222", "Name": "matter_g1_add_4", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000c1243478f4fbdc21ea9b241655947a28accd058d0cdb4f9f0576d32f09dddaf0850464550ff07cab5927b3e4c863ce90000000000000000000000000000000015fb54db10ffac0b6cd374eb7168a8cb3df0a7d5f872d8e98c1f623deb66df5dd08ff4c3658f2905ec8bd02598bd4f90000000000000000000000000000000001461565b03a86df363d1854b4af74879115dffabeddfa879e2c8db9aa414fb291a076c3bdf0beee82d9c094ea8dc381a000000000000000000000000000000000e19d51ab619ee2daf25ea5bfa51eb217eabcfe0b5cb0358fd2fa105fd7cb0f5203816b990df6fda4e0e8d541be9bcf6", "Expected": "000000000000000000000000000000000cb40d0bf86a627d3973f1e7846484ffd0bc4943b42a54ff9527c285fed3c056b947a9b6115824cabafe13cd1af8181c00000000000000000000000000000000076255fc12f1a9dbd232025815238baaa6a3977fd87594e8d1606caec0d37b916e1e43ee2d2953d75a40a7ba416df237", "Name": "matter_g1_add_5", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000328f09584b6d6c98a709fc22e184123994613aca95a28ac53df8523b92273eb6f4e2d9b2a7dcebb474604d54a210719000000000000000000000000000000001220ebde579911fe2e707446aaad8d3789fae96ae2e23670a4fd856ed82daaab704779eb4224027c1ed9460f39951a1b0000000000000000000000000000000019cabba3e09ad34cc3d125e0eb41b527aa48a4562c2b7637467b2dbc71c373897d50eed1bc75b2bde8904ece5626d6e400000000000000000000000000000000056b0746f820cff527358c86479dc924a10b9f7cae24cd495625a4159c8b71a8c3ad1a15ebf22d3561cd4b74e8a6e48b", "Expected": "000000000000000000000000000000000e115e0b61c1f1b25cc10a7b3bd21cf696b1433a0c366c2e1bca3c26b09482c6eced8c8ecfa69ce6b9b3b4419779262e00000000000000000000000000000000077b85daf61b9f947e81633e3bc64e697bc6c1d873f2c21e5c4c3a11302d4d5ef4c3ff5519564729aaf2a50a3c9f1196", "Name": "matter_g1_add_6", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000002ebfa98aa92c32a29ebe17fcb1819ba82e686abd9371fcee8ea793b4c72b6464085044f818f1f5902396df0122830cb00000000000000000000000000000000001184715b8432ed190b459113977289a890f68f6085ea111466af15103c9c02467da33e01d6bff87fd57db6ccba442a0000000000000000000000000000000011f649ee35ff8114060fc5e4df9ac828293f6212a9857ca31cb3e9ce49aa1212154a9808f1e763bc989b6d5ba7cf09390000000000000000000000000000000019af81eca7452f58c1a6e99fab50dc0d5eeebc7712153e717a14a31cffdfd0a923dbd585e652704a174905605a2e8b9d", "Expected": "000000000000000000000000000000000013e37a8950a659265b285c6fb56930fb77759d9d40298acac2714b97b83ec7692a7d1c4ccb83f074384db9eedd809c0000000000000000000000000000000003215d524d6419214568ba42a31502f2a58a97d0139c66908e9d71755f5a7666567aafe30ea84d89308f06768f28a648", "Name": "matter_g1_add_7", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000009d6424e002439998e91cd509f85751ad25e574830c564e7568347d19e3f38add0cab067c0b4b0801785a78bcbeaf246000000000000000000000000000000000ef6d7db03ee654503b46ff0dbc3297536a422e963bda9871a8da8f4eeb98dedebd6071c4880b4636198f4c2375dc795000000000000000000000000000000000d713e148769fac2efd380886f8566c6d4662dd38317bb7e68744c4339efaedbab88435ce3dc289afaa7ecb37df37a5300000000000000000000000000000000129d9cd031b31c77a4e68093dcdbb585feba786207aa115d9cf120fe4f19ca31a0dca9c692bd0f53721d60a55c333129", "Expected": "00000000000000000000000000000000029405b9615e14bdac8b5666bbc5f3843d4bca17c97bed66d164f1b58d2a148f0f506d645d665a40e60d53fe29375ed400000000000000000000000000000000162761f1712814e474beb2289cc50519253d680699b530c2a6477f727ccc75a19681b82e490f441f91a3c611eeb0e9e2", "Name": "matter_g1_add_8", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000002d1cdb93191d1f9f0308c2c55d0208a071f5520faca7c52ab0311dbc9ba563bd33b5dd6baa77bf45ac2c3269e945f4800000000000000000000000000000000072a52106e6d7b92c594c4dacd20ef5fab7141e45c231457cd7e71463b2254ee6e72689e516fa6a8f29f2a173ce0a1900000000000000000000000000000000006d92bcb599edca426ff4ceeb154ebf133c2dea210c7db0441f74bd37c8d239149c8b5056ace0bfefb1db04b42664f530000000000000000000000000000000008522fc155eef6d5746283808091f91b427f2a96ac248850f9e3d7aadd14848101c965663fd4a63aea1153d71918435a", "Expected": "000000000000000000000000000000000cfaa8df9437c0b6f344a0c8dcbc7529a07aec0d7632ace89af6796b6b960b014f78dd10e987a993fb8a95cc909822ec0000000000000000000000000000000007475f115f6eb35f78ba9a2b71a44ccb6bbc1e980b8cd369c5c469565f3fb798bc907353cf47f524ba715deaedf379cb", "Name": "matter_g1_add_9", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000000641642f6801d39a09a536f506056f72a619c50d043673d6d39aa4af11d8e3ded38b9c3bbc970dbc1bd55d68f94b50d0000000000000000000000000000000009ab050de356a24aea90007c6b319614ba2f2ed67223b972767117769e3c8e31ee4056494628fb2892d3d37afb6ac9430000000000000000000000000000000016380d03b7c5cc3301ffcb2cf7c28c9bde54fc22ba2b36ec293739d8eb674678c8e6461e34c1704747817c8f8341499a000000000000000000000000000000000ec6667aa5c6a769a64c180d277a341926376c39376480dc69fcad9a8d3b540238eb39d05aaa8e3ca15fc2c3ab696047", "Expected": "0000000000000000000000000000000011541d798b4b5069e2541fa5410dad03fd02784332e72658c7b0fa96c586142a967addc11a7a82bfcee33bd5d07066b900000000000000000000000000000000195b3fcb94ab7beb908208283b4e5d19c0af90fca4c76268f3c703859dea7d038aca976927f48839ebc7310869c724aa", "Name": "matter_g1_add_10", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000fd4893addbd58fb1bf30b8e62bef068da386edbab9541d198e8719b2de5beb9223d87387af82e8b55bd521ff3e47e2d000000000000000000000000000000000f3a923b76473d5b5a53501790cb02597bb778bdacb3805a9002b152d22241ad131d0f0d6a260739cbab2c2fe602870e00000000000000000000000000000000065eb0770ab40199658bf87db6c6b52cd8c6c843a3e40dd60433d4d79971ff31296c9e00a5d553df7c81ade533379f4b0000000000000000000000000000000017a6f6137ddd90c15cf5e415f040260e15287d8d2254c6bfee88938caec9e5a048ff34f10607d1345ba1f09f30441ef4", "Expected": "0000000000000000000000000000000006b0853b3d41fc2d7b27da0bb2d6eb76be32530b59f8f537d227a6eb78364c7c0760447494a8bba69ef4b256dbef750200000000000000000000000000000000166e55ba2d20d94da474d4a085c14245147705e252e2a76ae696c7e37d75cde6a77fea738cef045182d5e628924dc0bb", "Name": "matter_g1_add_11", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000002cb4b24c8aa799fd7cb1e4ab1aab1372113200343d8526ea7bc64dfaf926baf5d90756a40e35617854a2079cd07fba40000000000000000000000000000000003327ca22bd64ebd673cc6d5b02b2a8804d5353c9d251637c4273ad08d581cc0d58da9bea27c37a0b3f4961dbafd276b0000000000000000000000000000000006a3f7eb0e42567210cc1ba5e6f8c42d02f1eef325b6483fef49ba186f59ab69ca2284715b736086d2a0a1f0ea224b40000000000000000000000000000000000bc08427fda31a6cfbe657a8c71c73894a33700e93e411d42f1471160c403b939b535070b68d60a4dc50e47493da63dc", "Expected": "000000000000000000000000000000000c35d4cd5d43e9cf52c15d46fef521666a1e1ab9f0b4a77b8e78882e9fab40f3f988597f202c5bd176c011a56a1887d4000000000000000000000000000000000ae2b5c24928a00c02daddf03fade45344f250dcf4c12eda06c39645b4d56147cb239d95b06fd719d4dc20fe332a6fce", "Name": "matter_g1_add_12", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000024ad70f2b2105ca37112858e84c6f5e3ffd4a8b064522faae1ecba38fabd52a6274cb46b00075deb87472f11f2e67d90000000000000000000000000000000010a502c8b2a68aa30d2cb719273550b9a3c283c35b2e18a01b0b765344ffaaa5cb30a1e3e6ecd3a53ab67658a578768100000000000000000000000000000000068e79aea45b7199ec4b6f26e01e88ec76533743639ce76df66937fff9e7de3edf6700d227f10f43e073afcc63e2eddc00000000000000000000000000000000039c0b6d9e9681401aeb57a94cedc0709a0eff423ace9253eb00ae75e21cabeb626b52ef4368e6a4592aed9689c6fca4", "Expected": "0000000000000000000000000000000013bad27dafa20f03863454c30bd5ae6b202c9c7310875da302d4693fc1c2b78cca502b1ff851b183c4b2564c5d3eb4dc0000000000000000000000000000000000552b322b3d672704382b5d8b214c225b4f7868f9c5ae0766b7cdb181f97ed90a4892235915ffbc0daf3e14ec98a606", "Name": "matter_g1_add_13", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000000704cc57c8e0944326ddc7c747d9e7347a7f6918977132eea269f161461eb64066f773352f293a3ac458dc3ccd5026a000000000000000000000000000000001099d3c2bb2d082f2fdcbed013f7ac69e8624f4fcf6dfab3ee9dcf7fbbdb8c49ee79de40e887c0b6828d2496e3a6f7680000000000000000000000000000000000adac9bb98bb6f35a8f941dbff39dfd307b6a4d5756ccae103c814564e3d3993a8866ff91581ccdd7686c1dce0b19f700000000000000000000000000000000083d235e0579032ca47f65b6ae007ce8ffd2f1a890ce3bc45ebd0df6673ad530d2f42125d543cb0c51ba0c28345729d8", "Expected": "000000000000000000000000000000000b5513e42f5217490f395a8cb3673a4fc35142575f770af75ecf7a4fcd97eee215c4298fc4feab51915137cbdb814839000000000000000000000000000000000e9d4db04b233b0b12a7ff620faefef906aeb2b15481ce1609dad50eb6a7d0c09a850375599c501296219fb7b288e305", "Name": "matter_g1_add_14", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000130535a29392c77f045ac90e47f2e7b3cffff94494fe605aad345b41043f6663ada8e2e7ecd3d06f3b8854ef92212f42000000000000000000000000000000001699a3cc1f10cd2ed0dc68eb916b4402e4f12bf4746893bf70e26e209e605ea89e3d53e7ac52bd07713d3c8fc671931d000000000000000000000000000000000d5bb4fa8b494c0adf4b695477d4a05f0ce48f7f971ef53952f685e9fb69dc8db1603e4a58292ddab7129bb5911d6cea0000000000000000000000000000000004a568c556641f0e0a2f44124b77ba70e4e560d7e030f1a21eff41eeec0d3c437b43488c535cdabf19a70acc777bacca", "Expected": "000000000000000000000000000000000c27ef4ebf37fd629370508f4cd062b74faa355b305d2ee60c7f4d67dd741363f18a7bbd368cdb17e848f372a5e33a6f0000000000000000000000000000000000ed833df28988944115502f554636e0b436cccf845341e21191e82d5b662482f32c24df492da4c605a0f9e0f8b00604", "Name": "matter_g1_add_15", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000001830f52d9bff64a623c6f5259e2cd2c2a08ea17a8797aaf83174ea1e8c3bd3955c2af1d39bfa474815bfe60714b7cd80000000000000000000000000000000000874389c02d4cf1c61bc54c4c24def11dfbe7880bc998a95e70063009451ee8226fec4b278aade3a7cea55659459f1d500000000000000000000000000000000091ee883cb9ea2c933f6645f0f4c535a826d95b6da6847b4fe2349342bd4bd496e0dd546df7a7a17a4b9fb8349e5064f000000000000000000000000000000000902d7e72242a5e6b068ca82d0cb71dc0f51335dbd302941045319f9a06777518b56a6e0b0b0c9fd8f1edf6b114ad331", "Expected": "00000000000000000000000000000000122cce99f623944dfebffcdf6b0a0a3696162f35053e5952dddc2537421c60da9fe931579d1c4fc2e31082b6c25f96b500000000000000000000000000000000011366ffa91dc0b7da8b7c1839ea84d49299310f5c1ca244012eed0dd363dbcf4ad5813b8e3fb49361ef05ea8cb18ffe", "Name": "matter_g1_add_16", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000043c4ff154778330b4d5457b7811b551dbbf9701b402230411c527282fb5d2ba12cb445709718d5999e79fdd74c0a67000000000000000000000000000000000013a80ede40df002b72f6b33b1f0e3862d505efbe0721dce495d18920d542c98cdd2daf5164dbd1a2fee917ba943debe0000000000000000000000000000000000d3d4f11bc79b8425b77d25698b7e151d360ebb22c3a6afdb227de72fe432dcd6f0276b4fd3f1fcc2da5b59865053930000000000000000000000000000000015ac432071dc23148765f198ed7ea2234662745a96032c215cd9d7cf0ad8dafb8d52f209983fe98aaa2243ecc2073f1b", "Expected": "000000000000000000000000000000000113ccf11264ff04448f8c58b279a6a49acb386750c2051eab2c90fa8b8e03d7c5b9e87eccf36b4b3f79446b80be7b1d0000000000000000000000000000000004358a1fabfe803f4c787a671196b593981a837ee78587225fb21d5a883b98a15b912862763b94d18b971cb7e37dbcf0", "Name": "matter_g1_add_17", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000009f9a78a70b9973c43182ba54bb6e363c6984d5f7920c1d347c5ff82e6093e73f4fb5e3cd985c9ddf9af936b16200e880000000000000000000000000000000008d7489c2d78f17b2b9b1d535f21588d8761b8fb323b08fa9af8a60f39b26e98af76aa883522f21e083c8a14c2e7edb600000000000000000000000000000000034f725766897ed76394145da2f02c92c66794a51fd5ae07bd7cc60c013d7a48ebf1b07faf669dfed74d82d07e48d1150000000000000000000000000000000018f4926a3d0f740988da25379199ecb849250239ad7efcfef7ffaa43bc1373166c0448cc30dcdbd75ceb71f76f883ea7", "Expected": "00000000000000000000000000000000167336aeeb9e447348156936849d518faee314c291c84d732fa3c1bd3951559230d94230e37a08e28e689e9d1fef05770000000000000000000000000000000005366535f7a68996e066ab80c55bb372a15fb0ed6634585b88fe7cafbf818fbfebbf6f6ddd9ca0ff72137594a1e84b35", "Name": "matter_g1_add_18", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000010fcfe8af8403a52400bf79e1bd0058f66b9cab583afe554aa1d82a3e794fffad5f0e19d385263b2dd9ef69d1154f10a000000000000000000000000000000000aba6a0b58b49f7c6c2802afd2a5ed1320bf062c7b93135f3c0ed7a1d7b1ee27b2b986cde732a60fa585ca6ab7cc154b00000000000000000000000000000000079e5a154cf84190b6c735bc8cd968559182166568649b813732e4fb4c5c428c8b38e8265d4ef04990c49aa1381f51c8000000000000000000000000000000000ae08e682ef92b4986a5ac5d4f094ad0919c826a97efe8d8120a96877766eae5828803804a0cae67df9822fd18622aae", "Expected": "000000000000000000000000000000000a3d66cf87b1ce8c5683d71a6de4bf829d094041240f56d9071aa84ff189a06940e8e1935127e23a970c78ca73c28bf6000000000000000000000000000000000b2adda87740873c0c59e3ebde44d33834773f0fe69e2f5e7ede99c4f928978a5caaede7262e45fd22136a394b3f7858", "Name": "matter_g1_add_19", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000013c5ebfb853f0c8741f12057b6b845c4cdbf72aecbeafc8f5b5978f186eead8685f2f3f125e536c465ade1a00f212b0900000000000000000000000000000000082543b58a13354d0cce5dc3fb1d91d1de6d5927290b2ff51e4e48f40cdf2d490730843b53a92865140153888d73d4af0000000000000000000000000000000008cefd0fd289d6964a962051c2c2ad98dab178612663548370dd5f007c5264fece368468d3ca8318a381b443c68c4cc7000000000000000000000000000000000708d118d44c1cb5609667fd51df9e58cacce8b65565ef20ad1649a3e1b9453e4fb37af67c95387de008d4c2114e5b95", "Expected": "0000000000000000000000000000000004b2311897264fe08972d62872d3679225d9880a16f2f3d7dd59412226e5e3f4f2aa8a69d283a2dc5b93e022293f0ee1000000000000000000000000000000000f03e18cef3f9a86e6b842272f2c7ee48d0ad23bfc7f1d5a9a796d88e5d5ac31326db5fe90de8f0690c70ae6e0155039", "Name": "matter_g1_add_20", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000053a12f6a1cb64272c34e042b7922fabe879275b837ba3b116adfe1eb2a6dc1c1fa6df40c779a7cdb8ed8689b8bc5ba800000000000000000000000000000000097ec91c728ae2d290489909bbee1a30048a7fa90bcfd96fe1d9297545867cbfee0939f20f1791329460a4fe1ac719290000000000000000000000000000000008e5afc16d909eb9d8bdaaf229ad291f34f7baf5247bbd4cc938278f1349adb4b0f0aacd14799c01d0ca2ed38c937d600000000000000000000000000000000006cf972c64e20403c82fee901c90eaa5547460d57cce2565fd091ff9bc55e24584595c9182298f148882d6949c36c9d5", "Expected": "000000000000000000000000000000000caf46f480ae2ea8e700f7913c505d5150c4629c9137e917357d2a4ba8a7a1c63b8f6e2978293755952fbed7f0ad8d6d0000000000000000000000000000000002e62e715b72eebbc7c366a2390318f73e69203a9533e72340aab568f65105129ffc9889a8bc00a692494d93688c7ec0", "Name": "matter_g1_add_21", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000001354dd8a230fde7c983dcf06fa9ac075b3ab8f56cdd9f15bf870afce2ae6e7c65ba91a1df6255b6f640bb51d7fed302500000000000000000000000000000000130f139ca118869de846d1d938521647b7d27a95b127bbc53578c7b66d88d541adb525e7028a147bf332607bd760deac0000000000000000000000000000000013a6439e0ec0fabe93f6c772e102b96b1f692971d7181c386f7f8a360daca6e5f99772e1a736f1e72a17148d90b08efe0000000000000000000000000000000010f27477f3171dcf74498e940fc324596ef5ec6792be590028c2963385d84ef8c4bbb12c6eb3f06b1afb6809a2cb0358", "Expected": "000000000000000000000000000000000dea57d1fc19f994e6bdda9478a400b0ada23aed167bfe7a16ef79b6aa020403a04d554303c0b2a9c5a38f85cf6f3800000000000000000000000000000000000b8d76ccd41ba81a835775185bbf1d6bf94b031d94d5c78b3b97beb24cf246b0c25c4c309e2c06ae9896ed800169eeee", "Name": "matter_g1_add_22", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000003f76a6dc6da31a399b93f4431bfabb3e48d86745eaa4b24d6337305006e3c7fc7bfcc85c85e2f3514cd389fec4e70580000000000000000000000000000000010e4280374c532ed0df44ac0bac82572f839afcfb8b696eea617d5bd1261288dfa90a7190200687d470992fb4827ff320000000000000000000000000000000005728a219d128bc0a1f851f228e2bf604a72400c393cfb0d3484456b6b28a2c5061198656f0e106bbe257d849be159040000000000000000000000000000000011f6d08baa91fb2c8b36191d5b2318e355f8964cc8112838394ba1ded84b075de58d90452601dcfc9aa8a275cfec695d", "Expected": "0000000000000000000000000000000012e6d6c518c15cfd3020181ff3f829e29140b3b507b99251cc7f31795128adec817750296bce413bac18b9a80f69ca5000000000000000000000000000000000131ee9b748f6f1eb790adeb9edd0e79d89a9908368f5a6bb82ee0c913061cdfffe75d9ba411a49aa3f9194ee6d4d08a9", "Name": "matter_g1_add_23", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000009439f061c7d5fada6e5431c77fd093222285c98449951f6a6c4c8f225b316144875bc764be5ca51c7895773a9f1a640000000000000000000000000000000000ebdef273e2288c784c061bef6a45cd49b0306ac1e9faab263c6ff73dea4627189c8f10a823253d86a8752769cc4f8f200000000000000000000000000000000171696781ba195f330241584e42fb112adf9b8437b54ad17d410892b45c7d334e8734e25862604d1b679097590b8ab0a000000000000000000000000000000001879328fdf0d1fb79afd920e0b0a386828be5b8e0e6024dfeea800ffcb5c65f9044061af26d639d4dcc27bcb5ba1481a", "Expected": "00000000000000000000000000000000111c416d5bd018a77f3317e3fbf4b03d8e19658f2b810dc9c17863310dfb09e1c4ffdbb7c98951d357f1c3d93c5d0745000000000000000000000000000000000af0a252bff336d5eb3a406778557ef67d91776a9c788be9a76cff7727f519a70fc7809f1a50a58d29185cb9722624fd", "Name": "matter_g1_add_24", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000001478ee0ffebf22708a6ab88855081daba5ee2f279b5a2ee5f5f8aec8f97649c8d5634fec3f8b28ad60981e6f29a091b10000000000000000000000000000000011efaeec0b1a4057b1e0053263afe40158790229c5bfb08062c90a252f59eca36085ab35e4cbc70483d29880c5c2f8c2000000000000000000000000000000000231b0d6189a4faad082ce4a69398c1734fcf35d222b7bce22b14571033a1066b049ae3cd3bd6c8cec5bec743955cdd600000000000000000000000000000000037375237fb71536564ea693ab316ae11722aadd7cab12b17b926c8a31bd13c4565619e8c894bffb960e632896856bbe", "Expected": "000000000000000000000000000000000d2b9c677417f4e9b38af6393718f55a27dbd23c730796c50472bc476ebf52172559b10f6ceb81e644ec2d0a41b3bb01000000000000000000000000000000001697f241ff6eceb05d9ada4be7d7078ecbbffa64dd4fb43ead0692eef270cb7cc31513ee4bf38a1b1154fe008a8b836a", "Name": "matter_g1_add_25", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000150d43c64cb1dbb7b981f455e90b740918e2d63453ca17d8eeecb68e662d2581f8aa1aea5b095cd8fc2a941d6e2728390000000000000000000000000000000006dc2ccb10213d3f6c3f10856888cb2bf6f1c7fcb2a17d6e63596c29281682cafd4c72696ecd6af3cce31c440144ebd10000000000000000000000000000000015653d1c5184736cdc78838be953390d12b307d268b394136b917b0462d5e31b8f1b9d96cce8f7a1203c2cae93db6a4000000000000000000000000000000000060efeece033ac711d500c1156e4b6dce3243156170c94bc948fd7beae7b28a31463a44872ca22ca49dc5d4d4dd27d1c", "Expected": "0000000000000000000000000000000003996050756117eeab27a5e4fa9acdde2a1161d6fbfff2601a1c7329f900e93a29f55a8073f85be8f7c2a4d0323e95cc00000000000000000000000000000000010b195a132c1cba2f1a6a73f2507baa079e9b5cb8894ea78bebc16d4151ee56fe562b16e2741f3ab1e8640cdad83180", "Name": "matter_g1_add_26", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000f46bb86e827aa9c0c570d93f4d7d6986668c0099e4853927571199e1ce9e756d9db951f5b0325acafb2bf6e8fec2a1b0000000000000000000000000000000006d38cc6cc1a950a18e92e16287f201af4c014aba1a17929dd407d0440924ce5f08fad8fe0c50f7f733b285bf282acfc0000000000000000000000000000000018adb42928304cbc310a229306a205e7c21cdb31b9e5daf0ff6bb9437acee80cd8cf02b35dab823155d60f8a83fde5cc0000000000000000000000000000000018b57460c81cab43235be79c8c90dcda40fafcaf69e4e767133aee56308a6df07eac71275597dd8ed6607ffb9151ed9a", "Expected": "0000000000000000000000000000000003c7a7ee3d1b73cf1f0213404363bf3c0de4425ab97d679ed51448e877b7537400f148f14eba588ed241fea34e56d465000000000000000000000000000000000c581b5070e6bb8582b7ee2cd312dfeb5aaf0b0da95cf5a22a505ffba21fc204e26a5e17311d1f47113653ff13349f57", "Name": "matter_g1_add_27", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000010cde0dbf4e18009c94ba648477624bbfb3732481d21663dd13cea914d6c54ec060557010ebe333d5e4b266e1563c631000000000000000000000000000000000fb24d3d4063fd054cd5b7288498f107114ff323226aca58d3336444fc79c010db15094ceda6eb99770c168d459f0da00000000000000000000000000000000001da65df8574a864ab454e5f2fa929405501bb73c3162a600979a1145586079361c89839cc0c5a07f1135c94bf059f9c0000000000000000000000000000000002560df402c0550662a2c4c463ad428ab6e60297fbc42a6484107e397ae016b58494d1c46ac4952027aa8c0896c50be3", "Expected": "000000000000000000000000000000000d7a539b679e5858271a6f9cf20108410eb5d5d2b1a905e09a8aa20318efbe9175450385d78389f08f836f5634f7a2f0000000000000000000000000000000000fb624e5f6c4c814b7d73eb63b70237c5de7d90d19ac81cac776d86171a8d307d3cc8c56da14f444fe8cf329ab7e63dd", "Name": "matter_g1_add_28", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000008c0a4c543b7506e9718658902982b4ab7926cd90d4986eceb17b149d8f5122334903300ad419b90c2cb56dc6d2fe976000000000000000000000000000000000824e1631f054b666893784b1e7edb44b9a53596f718a6e5ba606dc1020cb6e269e9edf828de1768df0dd8ab8440e0530000000000000000000000000000000005311c11f4d0bb8542f3b60247c1441656608e5ac5c363f4d62127cecb88800a771767cf23a0e7c45f698ffa5015061f0000000000000000000000000000000018f7f1d23c8b0566a6a1fcb58d3a5c6fd422573840eb04660c3c6ba65762ed1becc756ac6300e9ce4f5bfb962e963419", "Expected": "0000000000000000000000000000000000849bbc7b0226b18abbcb4c9a9e78dca2f5f75a2cbb983bd95ff3a95b427b1a01fd909ce36384c49eb88ffb8ff77bb000000000000000000000000000000000087d8d28d92305b5313ca533a6b47f454ddce1c2d0fa3574b255128ef0b145fa4158beb07e4f0d50d6b7b90ea8a8ea8a", "Name": "matter_g1_add_29", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000159d94fb0cf6f4e3e26bdeb536d1ee9c511a29d32944da43420e86c3b5818e0f482a7a8af72880d4825a50fee6bc8cd8000000000000000000000000000000000c2ffe6be05eccd9170b6c181966bb8c1c3ed10e763613112238cabb41370e2a5bb5fef967f4f8f2af944dbef09d265e000000000000000000000000000000000c8e293f730253128399e5c39ab18c3f040b6cd9df10d794a28d2a428a9256ea1a71cf53022bd1be11f501805e0ddda40000000000000000000000000000000003e60c2291be46900930f710969f79f27e76cf710efefc243236428db2fed93719edeeb64ada0edf6346a0411f2a4cb8", "Expected": "00000000000000000000000000000000191084201608f706ea1f7c51dd5b593dda87b15d2c594b52829db66ce3beab6b30899d1d285bdb9590335949ceda5f050000000000000000000000000000000000d3460622c7f1d849658a20a7ae7b05e5afae1f01e871cad52ef632cc831b0529a3066f7b81248a7728d231e51fc4ad", "Name": "matter_g1_add_30", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000019c822a4d44ac22f6fbaef356c37ceff93c1d6933e8c8f3b55784cfe62e5705930be48607c3f7a4a2ca146945cad6242000000000000000000000000000000000353d6521a17474856ad69582ce225f27d60f5a8319bea8cefded2c3f6b862d76fe633c77ed8ccdf99d2b10430253fc80000000000000000000000000000000013267db8fdf8f488a2806fead5cffdcbb7b1b4b7681a2b67d322cd7f5985c65d088c70cdc2638e679ed678cae3cc63c80000000000000000000000000000000007757233ad6d38d488c3d9d8252b41e4ab7ee54e4ef4bbf171402df57c14f9977dd3583c6c8f9b5171b368d61f082447", "Expected": "000000000000000000000000000000000c06fef6639ab7dceb44dc648ca6a7d614739e40e6486ee9fc01ecc55af580d98abc026c630a95878da7b6d5701d755c0000000000000000000000000000000007c9a7f2bc7fa1f65c9e3a1e463eb4e3283e47bb5490938edb12abf6c8f5a9b56d8ce7a81a60df67db8c399a9a1df1d4", "Name": "matter_g1_add_31", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000189bf269a72de2872706983835afcbd09f6f4dfcabe0241b4e9fe1965a250d230d6f793ab17ce7cac456af7be4376be6000000000000000000000000000000000d4441801d287ba8de0e2fb6b77f766dbff07b4027098ce463cab80e01eb31d9f5dbd7ac935703d68c7032fa5128ff17000000000000000000000000000000001975bc52669187f27a86096ae6bf2d60178706105d15bce8fe782759f14e449bc97cb1570e87eec5f12214a9ae0e0170000000000000000000000000000000000ca6106d6e6487a3b6f00fc2af769d21cb3b83b5dc03db19e4824fc28fd9b3d9f7a986e79f05c02b3a914ff26c7a78d6", "Expected": "0000000000000000000000000000000002fbf4fba68ae416b42a99f3b26916dea464d662cebce55f4545481e5ab92d3c40f3e189504b54db4c9cd51ecdd60e8d0000000000000000000000000000000008e81e094c6d4ded718ef63c5edfacb2d258f48ccfa37562950c607299bb2dca18e680a620dff8c72dedc89b4e9d4759", "Name": "matter_g1_add_32", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000003299542a0c40efbb55d169a92ad11b4d6d7a6ed949cb0d6477803fbedcf74e4bd74de854c4c8b7f200c85c8129292540000000000000000000000000000000013a3d49e58274c2b4a534b95b7071b6d2f42b17b887bf128627c0f8894c19d3d69c1a419373ca4bd1bb6d4efc78e1d3f00000000000000000000000000000000109f6168a719add6ea1a14f9dc95345e325d6b0e56da2f4ecff8408536446894069fa61e81bdaebfc96b13b402fad865000000000000000000000000000000001806aa27c576f4c4fa8a6db49d577cd8f257a8450e89b061cbc7773c0b5434f06bacf12b479abf6847f537c4cbefcb46", "Expected": "0000000000000000000000000000000014e0bd4397b90a3f96240daf835d5fb05da28a64538f4bf42d9e7925a571f831c6e663910aa37dcc265ddd7938d83045000000000000000000000000000000001695d405d4f8ba385ebf4ad25fb3f34c65977217e90d6e5ed5085b3e5b0b143194f82e6c25766d28ad6c63114ca9dcdf", "Name": "matter_g1_add_33", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000121b540a0465b39f2f093112c20a9822fc82497105778937c9d5cdcfe039d62998d47d4f41c76482c31f39a79352beda0000000000000000000000000000000014a461f829e0a76ba89f42eb57dffb4f5544df2008163bd0ea1af824f7ff910b27418a0e4f86cb8046dc1f3139cab9af0000000000000000000000000000000019d3623a7866933e2d73214ceb2e56097a1b047db5943c3ecb846890aa02250126e90fc76a729a952cef895bd154cc7d000000000000000000000000000000000e87c376bbd695a356ef72226ac7ef6a550d99e9693d8485770a686e568ae28c038ee201d3f2ea38362046236ade91cd", "Expected": "000000000000000000000000000000000ffeab47985bd9b3e10ce27c6636bbda336dcf540cd37eccc3faec2adff2d97dd126633bd83a7d3c8c73c3623bdf0ba2000000000000000000000000000000001992eca4b1e924b360d57ca98b543ab496a8b55bd288d23f03bcc1b22f6bc76d95b12f47c3e305812097253c73b876dd", "Name": "matter_g1_add_34", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000001383bc4d6c748d5c76ab4ba04f8fcd4c0fed9a49ea080c548893440819833ad72a8249f77391d5fbff78329eb319d3830000000000000000000000000000000016404bd07b6c6480af2d23301940e61817ee2e61fc625c100b31e1b324c369a583b61048dd57ab97b80b1fe6cd64c5c300000000000000000000000000000000163aaecf83d6c77a5d7417e73f5cf9d71a6aedfd194b2f3b53c608d06a228190f4f79ac57b029d77504c72744df4ecc0000000000000000000000000000000000416e6f9ca188d16daa2c28acd6a594f8fcb990eaa26e60ca2a34dfcad7ad76c425b241acedf674d48d298d0df0f824d", "Expected": "000000000000000000000000000000001812bcb26fa05e0ab5176e703699ab16f5ef8917a33a9626ae6ff20f2a6f4a9d5e2afe3a11f57061cbaa992e1f30477f000000000000000000000000000000000680acf0b632cb48017cb80baa93753d030aa4b49957178d8a10d1d1a27bbdc89ac6811a91868b2c181c5c0b9b6caf86", "Name": "matter_g1_add_35", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000006bc68c6510c15a5d7bc6eebce04f7c5fce3bb02f9f89ea14ab0dfb43645b6346af7e25a8e044e842b7a3d06fe9b1a0300000000000000000000000000000000053ee41f6a51c49b069f12de32e3e6b0b355cd2c3ba87a149c7de86136a5d9c5b7b59f2d1237964e548d1b62ec36c8db000000000000000000000000000000000aba7362eee717d03ef2d4f0fef2763822115fcc8fb9e2e8243683b6c1cde799ebc78f23812e557de2cc38e2b4a2e56700000000000000000000000000000000170833db69b3f067cf5c4c4690857e6711c9e3fcad91ca7cd045e9d2f38c7b31236960e8718f5dd4c8bfb4de76c6c9b9", "Expected": "00000000000000000000000000000000196ffe76a4b726fa8dd720cc1cd04c040724cb18ec10915e312eaa90d124100b08f0ce3a7fc888f46914319a3d7581f4000000000000000000000000000000000e2612357059ca6dbb64efb98ef19370560c9e83e2aad7ab2d9015e2444fe4d8c796b5577584aac9f63258beb5ae863c", "Name": "matter_g1_add_36", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000024ca57c2dc2a7deec3082f2f2110b6788c57a8cdc43515044d275fe7d6f20540055bde823b7b091134fb811d23468ce0000000000000000000000000000000009cd91a281b96a881b20946fda164a987243c052378fcd8fee3926b75576dfa1d29a0aaca4b653da4e61da8257721808000000000000000000000000000000000a98ae36c690f2e3be8100f43678be5a1064390e210328dd23f61f5a496b87398db2798580edeabc6273fb9537fa12880000000000000000000000000000000009aedf77bb969592c6552ae0121a1c74de78ba222b6cd08623c7a34708a12763b5ff7969cf761ccd25adc1b65da0f02d", "Expected": "00000000000000000000000000000000072334ec8349fc38b99d6dea0b4259c03cd96c1438c90ef0da6321df2495892de031a53c23838ca2b260774fa09b5461000000000000000000000000000000000e4535767c2477c4f87c087540c836eeffcd0c45960841f9c3561a8a5f8e61ab98b183b11192b8e7ea1c9c7717336243", "Name": "matter_g1_add_37", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000001305e1b9706c7fc132aea63f0926146557d4dd081b7a2913dae02bab75b0409a515d0f25ffa3eda81cf4764de15741f60000000000000000000000000000000011bf87b12734a6360d3dda4b452deede34470fba8e62a68f79153cc288a8e7fed98c74af862883b9861d2195a58262e00000000000000000000000000000000015c3c056ec904ce865d073f8f70ef2d4b5adb5b9238deaa5e167d32f45cad4901aa6d87efa2338c633e7853ce4c19185000000000000000000000000000000000a15f1aa6e662f21d7127351a1655821c943c4cf590e3c9e60c9ab968b4a835f87fb8d87eee6331ee4e194e5f1ea91f4", "Expected": "000000000000000000000000000000000140fb6dcf872d0a3bff3e32a0cb4a7fb7e60ee4fb476bb120c4ce068e169d72e1c167d7fda321280d5855983d5a9af800000000000000000000000000000000108f54a4ec3ba26dd614f4d94c5c82652583906986158ad40ffea54c17703fa4b0bd7806633e1c0318d06e8dc7d41cde", "Name": "matter_g1_add_38", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000012662b26f03fc8179f090f29894e86155cff4ec2def43393e054f417bbf375edd79f5032a5333ab4eba4418306ed0153000000000000000000000000000000000f26fdf1af1b8ad442ef4494627c815ca01ae84510944788b87f4aa2c8600ed310b9579318bc617a689b916bb7731dcb000000000000000000000000000000000307841cb33e0f188103a83334a828fa864cea09c264d5f4343246f64ab244add4610c9ccd64c001816e5074fe84013f000000000000000000000000000000000e15bbeb6fff7f1435097828f5d64c448bbc800f31a5b7428436dcffd68abc92682f2b01744d7c60540e0cd1b57ab5d4", "Expected": "000000000000000000000000000000000a1b50660ed9120fff1e5c4abb401e4691a09f41780ca188cea4b1c2d77002f08ce28eb1caa41ee3fe73169e3651bb7f00000000000000000000000000000000125439ac3b45c698a98063ab911364bd3c6dd2a69435d00d6edf89fc5566b33038e960a125e5e52141abb605587942fe", "Name": "matter_g1_add_39", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000001837f0f18bed66841b4ff0b0411da3d5929e59b957a0872bce1c898a4ef0e13350bf4c7c8bcff4e61f24feca1acd5a370000000000000000000000000000000003d2c7fe67cada2213e842ac5ec0dec8ec205b762f2a9c05fa12fa120c80eba30676834f0560d11ce9939fe210ad6c6300000000000000000000000000000000013866438b089d39de5a3ca2a624d72c241a54cbdcf5b2a67ebdd2db8373b112a814e74662bd52e37748ffbfc21782a5000000000000000000000000000000000d55454a22d5c2ef82611ef9cb6533e2f08668577764afc5bb9b7dfe32abd5d333147774fb1001dd24889775de57d305", "Expected": "000000000000000000000000000000000037b4e8846b423335711ac12f91e2419de772216509d6b9deb9c27fd1c1ee5851b3e032bf3bcac3dd8e93f3dce8a91b00000000000000000000000000000000113a1bf4be1103e858c3be282effafd5e2384f4d1073350f7073b0a415ecf9e7a3bfb55c951c0b2c25c6bab35454ecf0", "Name": "matter_g1_add_40", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000181dc6fd3668d036a37d60b214d68f1a6ffe1949ec6b22f923e69fb373b9c70e8bcc5cdace068024c631c27f28d994e5000000000000000000000000000000000b02ca2b0e6e0989ea917719b89caf1aa84b959e45b6238813bf02f40db95fbb3bf43d3017c3f9c57eab1be617f180320000000000000000000000000000000017440fd557df23286da15f9a96bb88cfbc79589b1c157af13baf02c65227dc0a5bdec6f2f300083ff91dae395ed8cb75000000000000000000000000000000000ad09b4290842cc599d346110fdb39ededbb1d651568579564e274465f07b8f77eeaf00fece0c10db69c2125de8ab394", "Expected": "0000000000000000000000000000000007c158b4e21566742f7e4e39a672bd383e27864505acef4ef8c26f8b0a9db418f9c088b555b8e9eb25acf9859b1207b40000000000000000000000000000000016e06a1ace89f992d582af0de7662ef91c0a98f574306f6f6d0d8d5e80166638d2deef70105cce2e9b20faa9d6315510", "Name": "matter_g1_add_41", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000001329a75975b714c861064d743092866d61c4467e0c0316b78142e6db7e74538a376a09487cb09ee89583d547c187229000000000000000000000000000000000096713619bf088bd9e12752cab83e9cdd58296ada8d338c86a749f00ba014087a3836ce10adaaf2e815f431235bff4f0000000000000000000000000000000000d7ccc3a4efdfe1a92a88e453933b8216016091f1b9d575faf18a5b3abf90daf077813167a3f4acce7359472dee544bb00000000000000000000000000000000128008c075ab176100e755cbb8de5b9ff0e9a78114f862d26ed030d9c1d1dea1c21ec8ae4d82a84d3ff5ae4c1cd6f339", "Expected": "000000000000000000000000000000000b84f9de79c748e37797c629cb78b86b4b736b199f161b30147b5dacf6eabe0b54afce40d5dacfe9a8ee8da5ef5b49de0000000000000000000000000000000010277ad094bb9a3b96379b1366dd90125b51a21ebeb4f776a81d9d9c1f37ab58c32a884a26fa32c83783ed0eef42b820", "Name": "matter_g1_add_42", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000001195502bc48c44b37e3f8f4e6f40295c1156f58dbc00b04b3018d237b574a20512599d18af01c50192db37cb8eb2c8a90000000000000000000000000000000002b03f02b45aa15b39e030c4b88c89a285dff5c4bbfe16f643f3f87d91db774f8ab7019285fda0b236ff7eec16496e5e00000000000000000000000000000000008da4a93d5ffcdaa0adc736a59f0c187ae3bf11ecb5e9e6f6aedea976a47757739042200b4c4593c2dd5db555425531000000000000000000000000000000000a6fdb2d4160c6c35223daa6fa10d0b1073de07fe4f2eba28e65ed049ff8d8852ed0538b30759fe7a0d944009ddf9a6f", "Expected": "000000000000000000000000000000000d740bd1effd8674250618af0358ad0b83bbc787f0264af9c2ada72fa5431be909e82155da1de0211f46fb307e9949f0000000000000000000000000000000000ddf62c91d587a14b64feef07da52c081b40fbbf9a0f2eae8b66022e0850fc94de6a467e7e4f580c7f2c806f6c6ed8cf", "Name": "matter_g1_add_43", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000d7e1651f3e172dcca8774a7a0d58ab47178d3e759933289e1d3eb0da414160ff9e890a608bf8ccdf2820c4aea6e11cb00000000000000000000000000000000185e8671e2ddb8e36380e39fe4eafefbac9769935603c28caac7d3f7f0f3e8ad14e925024b55aeb67d68b219875c9d790000000000000000000000000000000003258d7931a1d72ab6344c7e96c0dbd435a7909fe68cc679c08ca9b62f7a6a04863082cbcfdbe9a736625d895e4f3bdb0000000000000000000000000000000009ee3e470e2b2cebc955ba3444b7e478f887138e36c13bd68490689122627269ea5e7ce22dd9c69792394a24187103d6", "Expected": "000000000000000000000000000000000af674691f5d87655f0066188fac5013f31b4169a0181d3feb7ac3beae0d9a3429d4125f099ee344f644a2de8b941f9f00000000000000000000000000000000042a9603b8e4a6c37d59ede3a1398f5f80c5298da66de575a204ee28811d9f7c7c0dd40cef3769bd72a2156b9eb620c8", "Name": "matter_g1_add_44", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000001454d4a82163a155446467164904cefd7e1e3c67ae99bf65c581a75c72716fb011e2fd030eaf3d36977fbb0ff5156e2700000000000000000000000000000000123f973ab6bd3c2e5b0512a0c77ea0ac3003fd891e1262137f9444cd07b927b564e618205ba09220320ea1aa4564e820000000000000000000000000000000001833807f1ced52399305419450355499a63411837ee61ad681559d59561db18511eb1e8ad3161e7fe30016b560d18b8f00000000000000000000000000000000198b11b31586e17964a4a4ccdee85703163d2106481833e71f26327a589bafb43578d08d87f6cb19c7a04b4ca92392bf", "Expected": "000000000000000000000000000000001081c3359a0fadfe7850ce878182859e3dd77028772da7bcac9f6451ac6455739c22627889673db626bbea70aa3648d50000000000000000000000000000000000f4e8766f976fa49a0b05ef3f06f56d92fe6452ff05c3fac455f9c16efadf1b81a44d2921bed73511dda81d6fc7478e", "Name": "matter_g1_add_45", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000178e6828261ee6855b38234ed15c27551bb1648ac6ec9a9e70744643cd1f134b2309dd0c34b1e59ddfe3f831ab814c90000000000000000000000000000000002ec930fb58c898ede931384c5a5f9edd2f5c70b8c3794edb83a12f23be5400949f95e81c96c666c1a72dffb50b811580000000000000000000000000000000007dc719ae9e3f1e11d3ed4747a546a7b973ccb1967adb1b3066645a8bde9632bcfa3530e768f088ddbc022b169e67cbf000000000000000000000000000000000bbf9cf884b19c84045da1cead7dcd9fdbf39d764ff1ad60d83ed1e4fd0ce0554f0fb618203952cf02a7c4ba466c66b8", "Expected": "000000000000000000000000000000000f60d66fd1ed5eb04f9619d6458c522cc49f5ace111aff2b61903b112559972f80ac615591463abf2b944c4f99d4c03e000000000000000000000000000000000001a1abfa869be2cda6bd7e05454a8735e1b638db7e1b3715708539c2d14ade53069c7e68b36d3b08cff80837028b7d", "Name": "matter_g1_add_46", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000001ea88d0f329135df49893406b4f9aee0abfd74b62e7eb5576d3ddb329fc4b1649b7c228ec39c6577a069c0811c952f100000000000000000000000000000000033f481fc62ab0a249561d180da39ff641a540c9c109cde41946a0e85d18c9d60b41dbcdec370c5c9f22a9ee9de00ccd0000000000000000000000000000000014b78c66c4acecdd913ba73cc4ab573c64b404a9494d29d4a2ba02393d9b8fdaba47bb7e76d32586df3a00e03ae2896700000000000000000000000000000000025c371cd8b72592a45dc521336a891202c5f96954812b1095ba2ea6bb11aad7b6941a44d68fe9b44e4e5fd06bd541d4", "Expected": "0000000000000000000000000000000015b164c854a2277658f5d08e04887d896a082c6c20895c8809ed4b349da8492d6fa0333ace6059a1f0d37e92ae9bad30000000000000000000000000000000001510d176ddba09ab60bb452188c2705ef154f449bed26abf0255897673a625637b5761355b17676748f67844a61d4e9f", "Name": "matter_g1_add_47", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000008d8c4a16fb9d8800cce987c0eadbb6b3b005c213d44ecb5adeed713bae79d606041406df26169c35df63cf972c94be10000000000000000000000000000000011bc8afe71676e6730702a46ef817060249cd06cd82e6981085012ff6d013aa4470ba3a2c71e13ef653e1e223d1ccfe900000000000000000000000000000000104ee0990ba4194916f670f44e254200971b67a18ed45b25c17be49df66e4f9b934bac8c1552ecc25bdaa3af55952076000000000000000000000000000000000591094d9d89afe025ca1832d7f3e60444f83e72403a434b42216b6c4213980d29e4ef0c64ae497006de550c1faa9425", "Expected": "0000000000000000000000000000000006db0cc24ffec8aa11aecc43e9b76a418daac51d51f3de437090c1bcaabace19f7f8b5ceb6277d6b32b7f3b239a90c4700000000000000000000000000000000069e01f60ca7468c6b9a247c79d18cf3d88bf5d1d62c76abf9237408edeba05dea744205ac5b501920f519bb847bb711", "Name": "matter_g1_add_48", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000120ddc1cd9e3a7b298673b1036d162c31dbb35d6e83b39b2564b3be16e446a836c96907e8a6af1e677e906bf5ed73159000000000000000000000000000000000fa57c1436615442bbb049d08ac46e501c07736cd239298752bb94d1904bd38cc687759987cadd99bd3c4d45ba07193a0000000000000000000000000000000004840d028d0c0f056aeb37b7a8505325081e9822ef26046f2da72f2155c20987dd51f4b5577c5395e24288b71d2ce5140000000000000000000000000000000015f231a233e997633c1d6492e0df358fb658ae29d0f53928c8a0578484c899a699178ca3223772210063aa08991c3fff", "Expected": "000000000000000000000000000000000fa72bf2d7d564cc4982b9f2cdca743d2ac14f0f1be4218dbafb8b93a9277e55273487a5d2857fd3f731ac4ee469a6a1000000000000000000000000000000000fce44f886453c6ca5ebde9af41d2be92d1126e9897d72978a179dd7eebeed6242b6e9718604ab0c9369529a0426a575", "Name": "matter_g1_add_49", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000e3ccaa4fa358a5a885094cbb0b8baa106fbcca66edbe31511ac2f6f3d14edbd8701979d6e4690853555c625091392b600000000000000000000000000000000175bdd42583cbbf733242510c152380525aff7649273acef1ec20569804ffba7f029ca06878dbafde84540cece1738220000000000000000000000000000000004877b97faa1d05d61ab65001110bf190d442cabcd6d4d1b9c1f0e513309aebd278f84a80354dfdef875769d00ec2c7500000000000000000000000000000000187066cccb5008bc2ffd0bcd1b227a5a0fe0cd4984316ba3cfd5113c4632a04c56cbda8d48993bd0dd50e9b7ce2b7ee9", "Expected": "0000000000000000000000000000000019ecd38afacc6b281b2515270157328e18039d51574bae0f7e0ef16c3f6da89f55ddee9e3bbb450ad51fe11edfd9f18d00000000000000000000000000000000088a5e292761bbf7a914a9f723de099035e91bd3c1fe9cd50728a4ceaa4fd3953683f30aa8e70ba0eb23919092aa9e22", "Name": "matter_g1_add_50", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000001bc359baeac07a93aca770174ea6444aac9f04affdaa77c8a47b30c60ee2b527c061a4344139264e541d4134f42bfd0000000000000000000000000000000000cbf7a31e6fef4f4664bca4bc87ec7c0b12ced7224300aa4e1a6a7cbdedfcef07482b5d20fa607e3f03fdd6dd03fd10c000000000000000000000000000000001881f5aba0603b0a256e03e5dc507598dd63682ce80a29e0fa141b2afdadf6168e98221e4ee45d378cee0416baaadc49000000000000000000000000000000000070d255101319dd3a0f8ca3a0856188428c09de15475d6b70d70a405e45ab379a5b1f2e55f84bd7fe5dd12aeedce670", "Expected": "0000000000000000000000000000000011ccd455d5e3eba94567a17bcd777559b4ff1afa66fd6f05f99c69937404290a2f1c83cfd6c2c25886ebff4934332c0e0000000000000000000000000000000010920aa3d5974df25530610ef466adce3d51fd6a508d4b1111739c586dfd7ba9040836e075fd812fe111d92f25b67f51", "Name": "matter_g1_add_51", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000006b06ae8cb0981bf5167ad51e19d132db77548c4376697f855c8397b835743c42771096ed7b0a4b18af9494e42ee89aa0000000000000000000000000000000005aa892b0a056ff61706430f1daa3f0263dc01337eadabd8a7fd58152affd9aaa329e8c11ea98692134d9718cb4119bf000000000000000000000000000000000b53e5339f25bcd31afd091362874b5042c0b762ed7425341331630addbc4dccc299936e1acdf89823c36867d46c6f28000000000000000000000000000000000fc3c6b522268511dd52826dd1aee707413d925ee51aeb0e5d69c0e3eb697fabbc14783b5007e240cc0c53c299a40ada", "Expected": "00000000000000000000000000000000060773b9b8f3babdba3db27089b7be3e6e287a635dbae19576039d34ae18a0e6413278bfa280570f6329ae05cdb693fd00000000000000000000000000000000075fb9527f99a8c8db41e67baaf1deafffd2c134badb1b3478a26b5501b31dca858fad6f0d52f412d5631ecfa72eece4", "Name": "matter_g1_add_52", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000015dc9f87213e4781863ad43f6bbccd547967d9bcf6a35d95d530cbfbf0d7307981aee5bc4ccd41254841651717393a0300000000000000000000000000000000166ce33c0482b5957c6e746c16908ba579d6402b230bc977d3ff29ac2a4a800748d9c14608f2519e2ac4d1fe4daf29b2000000000000000000000000000000001693f4ebab3fed548784264196fb01cf55311399f47cdad74a9543bda5d1ca682a00ee04bb0b3954d5a0f00ceef97a750000000000000000000000000000000017f4019c23bd68e84d889857c417b17aa96c780fec3c1ed6ca75100cc70c97a8bb8272ad4c6de896d76dc2a1b09c7a61", "Expected": "000000000000000000000000000000000a3ea8afdc83794f18f9a9427bcd60a355196925d38fdf74ab09d4a08279647b2da6f1fbe30948a785497d6c6dddc2a9000000000000000000000000000000001263c88f1ca3e574cafac21641432d45ee01e1b05eba95716565922abe28c7f0fb004c255afcbfa10cf7959bbe6b00d7", "Name": "matter_g1_add_53", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000171fbc9cec717964c4324aa0d7dcf56a59b947c24a9092157f4f8c78ae43b8e4222fd1e8acdbf5989d0d17ea10f6046300000000000000000000000000000000148b5454f9b9868aefd2accc3318ddabfe618c5026e8c04f8a6bce76cd88e350bebcd779f2021fe7ceda3e8b4d438a0b0000000000000000000000000000000005d5602e05499a435effff3812744b582b0cd7c68f1c88faa3c268515c8b14f3c041b8ae322fe526b2406e7c25d84e61000000000000000000000000000000001038eaf49e74e19111e4456ebba01dc4d22c7e23a303d5dec821da832e90a1b07b1a6b8034137f1bfdcddeb58053a170", "Expected": "0000000000000000000000000000000019258ea5023ce73343dcd201ec9be68ec1ee1cb4e5b9964309d801c2bc523343c8ebc4f8393a403c7881e5928f29db14000000000000000000000000000000001423bf52daefb432162ce2bd9ef78b256ff3b24d0a84766b87119489fd56ecf6156b2884c8a7e1220e493469723cd7f8", "Name": "matter_g1_add_54", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000018724e2b9a2f383329207ee85577805f35d5c5bb9f6903e3c962e57ab7eb9d1639d1e9adbde53499863b299f576325a00000000000000000000000000000000016d2c22eabd4a06a5ae67b890a25fbede7d0e96c625b80329b19be6aa861f44b6e85778130d0bdf69f2abd491ee9751a0000000000000000000000000000000002626f28d421d9d1c28f5e1eb5a51ada9610dbdd62cd33c4078d2fdfc18dbd092e2847cf705ba5fcd8c1a60c1cc34a3b0000000000000000000000000000000001f7b8cfdb7e406c920f5fdecae45fb4be736f209480ccb455f972c6b1a1aebdd5ba116903c46ded72ce37cd8836e871", "Expected": "00000000000000000000000000000000081d674f5b9c7c64673c39fe33f4f3d77271e826dcb4dfd2591062e47c931237e8539ef9c886c9e112eccc50da4f63fd00000000000000000000000000000000141b700695839110ed4ced5f8a3f4fd64a8086805358ab4a5abd2705592e616cd95ff01271212ca9014dcb68d8157ba0", "Name": "matter_g1_add_55", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000010fcf5e5e478ac6442b218ce261878d8f61b405c0b9549512e23ead1f26a2240771993f8c039fbce4008a1707aeaaf25000000000000000000000000000000000f1afe9b199362f51cc84edb1d3cf2faf8e5bc0a734a646851ab83e213f73a3734114f255b611ec18db75694dcb0df91000000000000000000000000000000000259e307eacb1bc45a13811b02a7aeaaf4dc2bb405dcd88069bb6ec1c08a78905516169bd3440a36921764df0ef3a85b000000000000000000000000000000001263372b675124f6cc19ca16842ba069c5697dbf57730875fe72c864a81189d7d16fe126b5d24953a0524f96dbac5183", "Expected": "000000000000000000000000000000001908aa3a640817e31a4213156fbd4fd39ab39eb931091670a0e06399def71a689e67286f90d38ce9f97cb85f6488d9c8000000000000000000000000000000000764e46b6b82aa2f8862d28e9d543a751a9de855645377b9633cc098c2110ec6ed4fd30f0044ea5868c93f950f6cfd24", "Name": "matter_g1_add_56", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000f75bc9feb74110697c9f353686910c6246e587dd71d744aab99917f1aea7165b41deb333e6bd14843f28b2232f799830000000000000000000000000000000019275491a51599736722295659dd5589f4e3f558e3d45137a66b4c8066c7514ae66ec35c862cd00bce809db528040c04000000000000000000000000000000000a138203c916cb8425663db3bbff37f239a5745be885784b8e035a4f40c47954c48873f6d5aa06d579e213282fe789fa0000000000000000000000000000000016897b8adbc3a3a0dccd809f7311ba1f84f76e218c58af243c0aa29a1bb150ed719191d1ced802d4372e717c1c97570a", "Expected": "0000000000000000000000000000000004ad79769fd10081ebaaed9e2131de5d8738d9ef143b6d0fa6e106bd82cfd53bbc9fab08c422aa03d03896a0fb2460d0000000000000000000000000000000000bb79356c2d477dfbcb1b0e417df7cb79affbe151c1f03fa60b1372d7d82fd53b2160afdd88be1bf0e9dc99596366055", "Name": "matter_g1_add_57", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000a87d0ccfb9c01148703d48993de04059d22a4cc48c5dabd2571ad4f7e60d6abfbcc5fb3bf363fd311fec675486c2a20000000000000000000000000000000000a896c5a84cbd03e52ae77000eb0285f5704993664a744a89ff6b346efd2efec1a519b67229a3b87e1f80e6aa17e29460000000000000000000000000000000019f60f2cf585bdbc36947f760a15fa16c54cf46435cc5707def410202a3f4fa61b577ab2481e058b0345982d3e3d1666000000000000000000000000000000000a70b7bbc55e1f3e11e9eb7efd79d4e396742de48d911ddff8dd0a7cf10422423d5e68021948e1448e92c2e07c194776", "Expected": "000000000000000000000000000000000a87e7e115ccdf3c2c1a2716491d449c3f8329e73d264088f4af444d43cf05f8be0410da273ce7eeb32969830195b7e70000000000000000000000000000000010a973d6e4bd85105bf311eb0dcfdc0a5d38dba1c099206b60f2e2df4791fd58846bf19d83769506e1561212920b4895", "Name": "matter_g1_add_58", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000d35ffa284655a94c3050213f4f14e927c162818bbfd0480bad2e07000dd3081274056715c96408f243589d83365c9f20000000000000000000000000000000001450bddfa14033ed8cdb94386715013ed9b2c4f9d65944e9d32c0b3545a085113e173e5afcfccb78878414a464d318400000000000000000000000000000000109bd6e0636a7f96ffe2ce8e109171efaacfcd60189c7050259ddedd15dd257e11f2585bbd84e4a3f4d8fc5fbc0289cf0000000000000000000000000000000019b420d778da53aed81b48f2c9b9eb399e771edd5e124a41577452b409ca2503e2798cd25d791f489352fc7b7268ae23", "Expected": "00000000000000000000000000000000162bd29f2de10002c1c446bd9583e89751fb91703ad564e7951d41673e28d214729aa9b4b9875c397989df197c912d5f0000000000000000000000000000000004d393181871c93714afab6c33c16f68ec391fbfcad606ac65cc1d070949c099e21f710e2fe0dd4e4f50f99ea2167a7e", "Name": "matter_g1_add_59", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000344cafaca754db423544657de1b77025164ccc702f8d45697fb73602302a3cb4511c38f0a76a37415d683398f35556500000000000000000000000000000000120935947070451885bf0c328bd83def193831ab9353844a01130074f16a1ff4d20df8459b5ad6a57d5f1959d37aae920000000000000000000000000000000012bb529b45ad7875784b62a7281d025002f15e7f86cc33555e7472df60da2cb15d37c8bf628142818c0711ee9047fb4d000000000000000000000000000000000baa801623312d95e2b51ce86373fea516007e468f265d974c2327c1779830db180bed6dbe8a64f0959aad26eaafb8d9", "Expected": "0000000000000000000000000000000010c4b328d264893099d89ba81b0765d0642bf36b0ac043be090c7b4f7987d21a906228c3c208c4ec5123d577efb0771f0000000000000000000000000000000016d08ce3bf755da7d4bae5f4b06b37845c17a717329c547e941be93325a04e9a5095d3f6e6c6f9ec3b1a740f59d88919", "Name": "matter_g1_add_60", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000008797f704442e133d3b77a5f0020aa304d36ce326ea75ca47e041e4d8a721754e0579ce82b96a69142cb7185998d18ce00000000000000000000000000000000144f438d86d1d808d528ea60c5d343b427124af6e43d4d9652368ddc508daab32fd9c9425cba44fba72e3449e366b1700000000000000000000000000000000002c9e50f37ff0db2676637be8a6275fce7948ae700df1e9e6a0861a8af942b6032cca2c3be8b8d95d4b4b36171b4b0d400000000000000000000000000000000050f1a9b2416bbda35bac9c8fdd4a91c12e7ee8e035973f79bd35e418fd88fa603761e2b36736c13f1d7a582984bd15e", "Expected": "000000000000000000000000000000000f798f8d5c21cbce7e9cfcbb708c3800bf5c22773ec5b44590cdbb6f720ccddf05a9f5d5e6a51f704f7c295c291df29f000000000000000000000000000000001483903fde5a968dba6924dfac3933cd39f757e2f89120f4ca9d03aaaf9e18252bdb5c5d3939471666b8a42aeb31b4ed", "Name": "matter_g1_add_61", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000000707c711f77bb425cddc71ecf96a18b6eb0bed7f012c4f6cc9431003f2e1ac17f7c1f68c4965a4fcc273a3db93451d000000000000000000000000000000001211464c91c7e78b00fe156da874407e4eeb7f422dbd698effb9a83357bf226d3f189f2db541eb17db3ed555084e91ec000000000000000000000000000000000332cdc97c1611c043dac5fd0014cfeaee4879fee3f1ad36cddf43d76162108e2dc71f181407171da0ceec4165bcd9760000000000000000000000000000000015b96a13732a726bad5860446a8f7e3f40458e865229bd924181aa671d16b2df2171669a3faa3977f0ee27920a2c5270", "Expected": "0000000000000000000000000000000001c762175f885a8d7cb0be11866bd370c97fb50d4277ab15b5531dacd08da0145e037d82be3a46a4ee4116305b807de6000000000000000000000000000000000bb6c4065723eaf84d432c9fde8ce05f80de7fe3baed26cf9d1662939baac9320da69c7fe956acdd085f725178fe1b97", "Name": "matter_g1_add_62", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000004b3c0e8b240b79c55f02833c2c20fa158e35c941e9e8e48247b96cb1d4923641b97e766637a3ced9fbef275ca9bd1ea000000000000000000000000000000000b4e7355aea3488234552d3dddfa2d1ad3164056407770e6c54f764193c9dc044cb7f2b157a1c4153b2045867d6f99c50000000000000000000000000000000003ebca978ea429eedad3a2c782816929724fc7529fbf78ea5738f2ca049aab56c1773f625df2698433d55db7f5fc8ca2000000000000000000000000000000000d2477f57b21ed471a40566f99b7c2d84ce6b82eaf83a6c87a7c21f3242959c8423d4113b7fd8449277b363303bb17b0", "Expected": "00000000000000000000000000000000071dc0f985703bd8335093779de651b524c02faca5fc967766abd3f6f59176d2046d7a14d18c0b757b8c9802e44ebcd300000000000000000000000000000000154e5cb66be8979ee276e8e0f240557e3f7dc074c497293af589256652da21d66a6e6b00ca5bfa6f89963fbd5bc6cf48", "Name": "matter_g1_add_63", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000001465358836eb5c6e173e425f675aa231f9c62e9b122584078f2ab9af7440a4ce4ac2cd21ce35a0017b01e4913b40f73d00000000000000000000000000000000170e2da3bca3d0a8659e31df4d8a3a73e681c22beb21577bea6bbc3de1cabff8a1db28b51fdd46ba906767b69db2f679000000000000000000000000000000001461afe277bf0e1754c12a8aabbe60262758941281f23496c2eeb714f8c01fd3793faf15139ae173be6c3ff5d534d2bc00000000000000000000000000000000148ad14901be55baa302fa166e5d81cc741d67a98a7052618d77294c12aea56e2d04b7e497662debc714096c433e844e", "Expected": "0000000000000000000000000000000012c4dd169f55dfb5634bc4866f7cbd110648b5392ace6042b5f64aba3278f24085227521b7834864f00d01ec9998dd6800000000000000000000000000000000102d7a495850195424677853da01d70caeb6c0af5270bcfffbc2d4252c0f3680518cd8d2a0a6dbbbc7b52923a5b26562", "Name": "matter_g1_add_64", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000ab6e2a649ed97be4574603b3b4a210f0748d8cddf132079e0543ec776ceb63902e48598b7698cf79fd5130cebaf0250000000000000000000000000000000000d55b3115d2bfcd1b93c631a71b2356c887b32452aae53ffd01a719121d58834be1e0fa4f22a01bbde0d40f55ad38f2c0000000000000000000000000000000002218b4498c91e0fe66417fe835e03c2896d858a10338e92a461c9d76bcecd66df209771ae02c7dcace119596018f83c000000000000000000000000000000001990233c0bae1c21ba9b0e18e09b03aeb3680539c2b2ef8c9a95a3e94cf6e7c344730bf7a499d0f9f1b77345926fef2d", "Expected": "0000000000000000000000000000000010c50bd0f5169ebd65ee1f9cd2341fa18dd5254b33d2f7da0c644327677fe99b5d655dd5bfdb705b50d4df9cfce33d1400000000000000000000000000000000088e47ffbbc80c69ec3c5f2abe644a483f62df3e7c17aa2ff025553d1aaf3c884a44506eff069f4c41d622df84bbafa1", "Name": "matter_g1_add_65", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000001654e99ebd103ed5709ae412a6df1751add90d4d56025667a4640c1d51435e7cad5464ff2c8b08cca56e34517b05acf10000000000000000000000000000000004d8353f55fdfb2407e80e881a5e57672fbcf7712dcec4cb583dbd93cf3f1052511fdee20f338a387690da7d69f4f6f7000000000000000000000000000000000160e0f540d64a3cedba9cf1e97b727be716bbfa97fbf980686c86e086833dc7a3028758be237de7be488e1c1c368fe100000000000000000000000000000000108250b265bd78f5e52f14ef11515d80af71e4d201389693a5c3ef202cf9d974628421d73666ead30481547582f7abaf", "Expected": "00000000000000000000000000000000168af33c85ae6e650375ed29b91218198edd9135683f6a1428211acdcbf16bdf86f0a95575e47ee0969587a10fa9f3c90000000000000000000000000000000012d9f5d692c870b3da951b6d07797c186a8ddc89b9f08a1c0b8f0f119f10ca0b155e8df5424cf48900ad3bf09ce6872a", "Name": "matter_g1_add_66", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000001bb1e11a1ccc0b70ce46114caca7ac1aba2a607fea8c6a0e01785e17559b271a0e8b5afbfa8705ecb77420473e81c510000000000000000000000000000000018f2289ba50f703f87f0516d517e2f6309fe0dc7aca87cc534554c0e57c4bdc5cde0ca896033b7f3d96995d5cbd563d20000000000000000000000000000000002fa19b32a825608ab46b5c681c16ae23ebefd804bb06079059e3f2c7686fe1a74c9406f8581d29ff78f39221d995bfd000000000000000000000000000000000b41ea8a18c64de43301320eaf52d923a1f1d36812c92c6e8b34420eff031e05a037eed47b9fe701fd6a03eb045f2ca7", "Expected": "000000000000000000000000000000000b99587f721a490b503a973591b2bb76152919269d80347aeba85d2912b864a3f67b868c34aee834ecc8cd82ac1373db0000000000000000000000000000000007767bb0ca3047eee40b83bf14d444e63d98e9fc6c4121bdf04ea7148bcfaf3819b70dcebd9a941134e5c649da8f8d80", "Name": "matter_g1_add_67", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000012ecb4c2f259efb4416025e236108eff7862e54f796605cc7eb12f3e5275c80ef42aadd2acfbf84d5206f6884d8e3eab000000000000000000000000000000001554412fc407e6b6cf3cbcc0c240524d1a0bf9c1335926715ac1c5a5a79ecdf2fdd97c3d828881b3d2f8c0104c85531f0000000000000000000000000000000002a540b681a6113a54249c0bbb47faf7c79e8da746260f71fbf83e60f18c17e5d6c8a7474badafee646fe74217a86ca4000000000000000000000000000000000fe2db7736129b35dc4958ffd0de7115359857fb9480b03a751c4fceb9ae1b2b05855398badffc517ae52c67f6394e2a", "Expected": "000000000000000000000000000000000bc719a8397a035fc3587d32d7ef4b4cfd63d4a5619ab78301d59659208f86df9e247e5d12650acc51a3bca3827063a900000000000000000000000000000000150d5519380a65b1909b0d84da374484675d99b00b254d03e423e634a012b286e3fe074e9b0a7bb24ff52d327249a01b", "Name": "matter_g1_add_68", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000010dac3e5885cc55f3e53b3fdd5d28b2d78ceeea2b669757a187de0ce3f28b586e451b119cdb7dc8b97d603f2bb700e2000000000000000000000000000000000712a9656fa95abf8c8c5d0d18a599c4cae3a0ae4bda12c0759ea60fe9f3b698d3c357edebb9f461d95762b1a24e787900000000000000000000000000000000019d917eb431ce0c066f80742fe7b48f5e008cffa55ee5d02a2a585cc7a105a32bbf47bdff44f8a855ade38184a8279e0000000000000000000000000000000012ee762e29d91a4fc70bc7a2fb296a1dcdd05c90368286cca352b3d5fffc76e3b838e14ea005773c461075beddf414d8", "Expected": "0000000000000000000000000000000008197403ab10f32d873974c937ef4c27fbdb0f505c4df8ac96504705d4851cf951fb0263335e477063884527b21edf160000000000000000000000000000000005396f1affa20ca8530b519a4d5d400969f0c8c8731ecc0944e8086388e89a7ff7c16d9a2a90780972c4762b88a0f0af", "Name": "matter_g1_add_69", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000001889ef0e20d5ddbeeb4380b97ed7d4be97ef0def051d232598b2459a72845d97fa5c1264802ab18d76b15d8fbd25e55900000000000000000000000000000000135519fb1c21b215b1f982009db41b30d7af69a3fada207e0c915d01c8b1a22df3bf0dc0ad10020c3e4b88a41609e12a000000000000000000000000000000000d280fe0b8297311751de20adf5e2d9e97f0c1bfe0cd430514cfddbafd5cdcb8c61bd8af4176cc3394f51f2de64b152400000000000000000000000000000000039f511e890187f28c7a0b2bd695ae665e89b0544c325a44b9109da52cc6908d81e1a27163a353ab275d683860c2e007", "Expected": "0000000000000000000000000000000002baea63055f72646189bdd133153dd83026f95afad5ce2cffbee3f74c8d47d5480094b2b58b0936c78aa33cd9a8f72f0000000000000000000000000000000013e600456a2d76f5a760059e0ba987b881c6bc10d6161f388d7a9d8b2031921054edfec46afbd80b1364d8e8f6a5a7a2", "Name": "matter_g1_add_70", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000008726a32d489a5ea1c1b314dc4d400d995d0eb8b49d47e65a6ac8fd0e6ec0cda1c637ee314c0c5d1ad72cd3588ebf925000000000000000000000000000000001849697df83d625fc5cdd722c76faf542a42506fc3479d8127eee7af57611c7d6f33a7f9dba5d3c420fab33ec19305f50000000000000000000000000000000015bad24d12b5d68558e961a17dbc3e1686e1b918e6192ebe6f3f71c925177e61d0162e018ac81126099effa0cadfa185000000000000000000000000000000000de73182569184b3d79dcfa8c27f46ec7a31fe8a3fd73fe26eec37a088461192bdbcf4d4b37b33b6177d6fde015d1631", "Expected": "000000000000000000000000000000000ced641c930387432d512861eefbf2d6131017154f99a0d3d24da880dfd2aaae91c2d9634053fab8b85fc11a7884d30600000000000000000000000000000000122071c0e87fae5031c850dccc4777c3ec9d8463bbc4ed84364d4261bc9d38f696a4320d53eea926a75ed9fcc9789a07", "Name": "matter_g1_add_71", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000001688c63e325569855bc2e51d668cef112b2479efa33519fe7f45eab89e275e2c4652cf8c2814f179935ccf1d24d8bd0f0000000000000000000000000000000011ebf7d4984237ac0173807f31be64575e7cccb36ce94e666e8149b9c292ebdb68d30ed4ba68f8e00982ee7780b256730000000000000000000000000000000015cdf7dafedce64aba34e1f18c57b28f297629c07ee96b732029b545cf5ea6afdf926daa6a48d1250c67aa2a8b797d370000000000000000000000000000000004867352f86267dbe8e32806e4ed02f1487e036051068f8e06d02e8dea6d3773b422e065d2db27c89ea69246d0185351", "Expected": "000000000000000000000000000000000e2c633351d627a075acd1e373bec96ba41b047f0307201f4b7c9978c1a72243d0b18113604cc421b8f66d76ec9b1360000000000000000000000000000000000844e258d602bf9aaa35ce46c4c91c80dd9337053d8ab22c1163a0571fcd1488a2ef57476e2b66dd9c26963b28284d11", "Name": "matter_g1_add_72", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000bb6f731b345bb1319b9acab09c186449a51dad8b6526251bc58e958cfd933137067e6f778b019f131cc7b23e08a0706000000000000000000000000000000001979a4f3e444c5950d0e2d71f97e99578b3058a6e414dfca313b898c4e02787e6eed89a2d1b05f31cff4af1e12bbedc300000000000000000000000000000000077eb801bcde78e9dd73b58d2429a907ea0f5600a8005093d471be373bba23ea70bf828c766ccced6a46db84b440053f00000000000000000000000000000000101af9df2939089d72e42fe2dc3de3e32be8f4526a2263ebd872d0080ed4a152107bb3d2f56176bf72d5ae8bd0c30a3f", "Expected": "0000000000000000000000000000000010205c6be10a5fc5390b0e5ae47a8a822c8e9a7a96f113d081cde477ec0de7bf0e8385e61780b2335e4297edb35bcc6d000000000000000000000000000000001796af180463ed70cf330791c8201ee3f0fe52993f64819291bda33017285fcc3a515669b3d48a411276c849fa021f6f", "Name": "matter_g1_add_73", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000078cca0bfd6957f9aff9731b45fdbdbeca6691f6fe6bf0b7847859c77478037e14864b202b235953ac7da231367324c200000000000000000000000000000000096ddc8631aff282d14d1878ef6bc537159abe9dda5732d0b2fe3668e184049cc19e05fec4666a0df204182edb9b0b8a0000000000000000000000000000000019b09bb7dddd11c5d0e304dac120b920601dd3a3505e478c88850cc701c17eb02aa7bfb20e4017a62fc4fb544d4f9e8f00000000000000000000000000000000048ad536cf89576d4cce83ef065bc16c47f1a28ae27bd71d30d8f2177a9c6f8b2ed0cdf872ead71bc5a1252bccb4a7e0", "Expected": "000000000000000000000000000000000fb047098a1996a625cd19021f81ea79895e038756878d8772aaee9b6bbb66930e474dcc04579ad58f4877b742a890900000000000000000000000000000000017da74a4caefc55794a36eda7938371f42265cc1f2d87d41883152db82873daeb59642e8e663afddd4f24536a1f52b3f", "Name": "matter_g1_add_74", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000b3a1dfe2d1b62538ed49648cb2a8a1d66bdc4f7a492eee59942ab810a306876a7d49e5ac4c6bb1613866c158ded993e000000000000000000000000000000001300956110f47ca8e2aacb30c948dfd046bf33f69bf54007d76373c5a66019454da45e3cf14ce2b9d53a50c9b4366aa30000000000000000000000000000000005f84f9afa2a4a80ea1be03770cb26ac94bec65cf9cb3412a07683df41bb267c2b561b744b34779635218527484633e30000000000000000000000000000000013ce1d1764961d1b0dff236c1f64eabec2ce5a8526edf6b0bccb9ea412e5a91880db24510435cf297fcc1b774b318b65", "Expected": "000000000000000000000000000000000f4ca788dc52b7c8c0cb3419ab62c26db9fb434321fc6830837333c2bb53b9f31138eecccc3c33461297f99a810e24ad0000000000000000000000000000000006785d4f9cdf42264c00fdc4452883b9050eb56e2f6e46c7b8fc8d937dfe4d3ad5072d969a47c4811b36d3887256d0b9", "Name": "matter_g1_add_75", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000007c00b3e7e50a860e99cdc92235f45a555c343304a067a71b6aaade016ef99bc50e3b2c5e3335d4bdacb816d3c765630000000000000000000000000000000000f8a45100cd8afcbb7c05c2d62bfedbf250d68d0fde0a1593cd2ed2f5f4278e1baa9e24625c263764e4347ed78cce6c8000000000000000000000000000000000f0dd7a15dfc39dc2df47cf09761498b0b363157d8443356e768567f5a6d5913c2a67f12d93df2dcf50756bb686836b100000000000000000000000000000000055914dbda5b115222e738d94fbd430440c99bcc6d2c6cf7225c77756ffadf765b2d83447d395e876b5f6134563ed914", "Expected": "000000000000000000000000000000000ac0f0f62202d09cede55ca77b7344b46fd831b41015eb357cac07f0fa49c2564c2e9d5c591630226677446a9100757c000000000000000000000000000000000ca21d0128ef933fc1a48c1b4967f56912513e63a416d86ad40c0a4590b2edf88e4e8a286338b8b176d8b341ea480277", "Name": "matter_g1_add_76", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000001517dd04b165c50d2b1ef2f470c821c080f604fe1a23f2fa5481f3a63e0f56e05c89c7403d4067a5f6e59d4a338d0b5c0000000000000000000000000000000007b6b1d032aadd51052f228d7e062e336bacda83bbce657678b5f9634174f0c3c4d0374e83b520a192783a8a5f3fb211000000000000000000000000000000000a6ff5f01a97c0f3c89ac0a460861dc9040f00693bfae22d81ea9a46b6c570436f0688ed0deef5cdcc5e2142f195b5c000000000000000000000000000000000193a17880edffe5b2ebedf0dc25e479cac3b136db9b6b24009ea0a9ca526d6dd9714d10d64c999d4334baa081b9f2fbe", "Expected": "000000000000000000000000000000000b728d4ae4b45fae9a9e242524e95e44f175356726da50f46236f690eec17fdd5edce5df1253383378dc8f9c1fee98ae00000000000000000000000000000000131d28a5eab968c45ddc86b82f220dcdeab7c009c7c61986ee4e55045c024e1bcbe76a4e35000b5699ccec5858ba427e", "Name": "matter_g1_add_77", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000475e66c9e4e434c4872b8537e0ab930165b39f41e04b208d74d3033e1d69dfb4b134ae3a9dc46347d30a6805508c0420000000000000000000000000000000019e585e1d9adf34a98a7cd38de35aa243d7853c19bc21747213c11240d5fa41ff3b21ae033dd664aaac8fa45354a470a000000000000000000000000000000000b35fcf625cde78fba1b70904acb97d7eb449d968e8013855d44292e9c3b0df3cfbcace6f292ec3c7717e25490bb4c67000000000000000000000000000000000af57abd87df55034c32dbe68bd1c0b47139fc2c3a8887b7c151e57b57c9002070337c8dcb2ce2687f9f007d48dd68c1", "Expected": "00000000000000000000000000000000178a19966b5b0fa70c138be7f5ea51d5399c7b8dcc5171cbef82ecb1451aeccbd1ed29170a27f404ebf6daa2ec99bd69000000000000000000000000000000000b1b748494806175030f6b5e2977c58982bd6ec6662d69237f0521351653c772a40035f2504ac8949fb448a901379fd6", "Name": "matter_g1_add_78", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000002291ff240598e2c129ea12292e4a2fc86e03da9bd9fbbb8bddd6f25797003a4688ba2ed3bafd8dfcf0ddd44c3288c1e000000000000000000000000000000000d7541c9c54a95f3789ca7637348378f8956fd451c3266c8f1a34906bf1cf8e7499fcf8ad1f1a73dafcf71b86833ff3b00000000000000000000000000000000177a51fcc81580ccb7a8873fa93eaf860ca8fedde13cdf3eb53f11e66a1c1e934b82ee9251f711c5c479f33a22770c47000000000000000000000000000000000a0edc9a58f4bb414aa0aeec7bfa6076fb62bdbaee987192c18855adf4e813e7103b943e1dddc24754acfa90600a5750", "Expected": "0000000000000000000000000000000019195049a2d457709e284c84c72a211224efc4d7d46d25c9a537eea94149b06506df02a2a4e0a6428263e9605eaaacb500000000000000000000000000000000061139f9a70ce7cd87ed3a701163bde247382295f557b47a3a0a880d2780f015e8ac753eb3243f9ad138f92c3a2257c5", "Name": "matter_g1_add_79", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000018d31bd5a7e94ceb18d803969a2001c6eb3bfbcf82c27e88ca60d4c46807d12f116ca71c67d27270c2332205a4ea11bb0000000000000000000000000000000010b6db11d4fc3a2b449b8fd189d2e4ed4591bf4258d7b92b3eb152048cb3a3eecb87782691e9b954377fd1f34b38cb0d000000000000000000000000000000001552982822e0b64a6204b27da0e192873bb5bd2997784ff0b6ed53801b402501a665c17f0a379fd946ab1adfae43c6af000000000000000000000000000000000938359655fe135dd2a390f83e27273feb68387ba94f2b6f7c15389f8272d64231ebe9c8271de90ff2358d935359ba85", "Expected": "00000000000000000000000000000000168f958a40e85341d90012e134976d1a5839e807948410cc0c81a50961552c052bb784c50da4c734f6aa583777c22b28000000000000000000000000000000000d26998bac6ec11bc5fcf6fe7262c984d6500cd5b21af979048b940e20054f8d759f8a011f3e09d01d10f9cf8ab150e1", "Name": "matter_g1_add_80", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000190f4dc14439eccc46d46c5c9b15eeba0bbf2dbca11af4183408afdb15c7bfa26f107cf5fda0c1e0236aab95728eac2e000000000000000000000000000000000c47feeb1a1d2891d986b1660810859c1bba427d43a69b4e5ddeaf77116418138bfc2b7b4aa4c0cc6df10bd116721d50000000000000000000000000000000000d94885dcc21b0b98821b6861a4d094e9eb5d5adcf7ca4275c5b759abbf9a9910f3b38073183d54a0569ecbbc1e9826400000000000000000000000000000000034a54b4bbb3f128608a866f5f5c554cf6ad7899f6650ca663a5bd5f1a3e4471e35a2440644c0e4e0a56080936b46d12", "Expected": "000000000000000000000000000000000d4734ab1bbcf9e30cf142a7aa9e8cde1b3c88d92397b8d7d48c7a7402561feee58a810abf67776e1890489efe7f8ec20000000000000000000000000000000005be9e4af0c0c183c43601339f162345f7c013f5941167cd925057e91c4641e19091a20123a36f2e803142833c0bc1ef", "Name": "matter_g1_add_81", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000021203675e0ae188ec782160e21492a6ee39fa97d922c1ef9bbfd79b82b3fad54fab11ba633fb8f02cf92249d85d9d8000000000000000000000000000000000062783335b87300c97b38e03e5b1318d15a499b29a473c187f930bf34bc1214b4d822725678cbde978c7b5ae6d4bad5100000000000000000000000000000000014f16cbb17e7f63284d8a75968a4c8fc8ee7f37233ed656d696477c507c23e7c7eaf54001f44c93deb14c298aa6f94c00000000000000000000000000000000169bde83e861889c50b2138c76531a5866235d515a6fee4da7aaf8e8b903f2848a9fe7bbd55eac7f1c58ce3a88e7249d", "Expected": "000000000000000000000000000000001400f774b2d932c6b990da6e1b3493685e8f51d429e0c53e9af1b4a2d3876781b790bca4a1bc28ce0240ea21be24a2350000000000000000000000000000000004993fcf5723b7e02095d4ba73ff3194bbe36027bc9099b57084c91c7e7d50b76331bfb06d3c678d3e401bc3f7fcc577", "Name": "matter_g1_add_82", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000e4979375cd880e26d00461de629bac880c12e24ede4a7c702f151c34a728a69a021e37b6a1af520a5f47d3a33f8c8a80000000000000000000000000000000013b5317e3ff7540048b19ceebd47c15538d7eb3bf402823b9c348c464afb1000ce0f7ea4c1cb668af5c8cbf77e6a92510000000000000000000000000000000009acc4b4678b4b645fde47d1b75a5dda8caf6696ad2bf312dd5c12d7f3ab50b95152f5fe59842650c8a1a785f345c3ab000000000000000000000000000000000b672989004fe54f4d645e40cd29a21418151134fd2b90a68185040ceff141ced7f7ece1fdd9137c32589fa04b105a0e", "Expected": "000000000000000000000000000000000fcb0ab180a69b0a230d9dba98099fdce4969f82fc7e7ad93352a7c8dd448bb0ba9c7d62f53d5dc80506bc36190d9bc700000000000000000000000000000000047b7306f4a53c21d42993c50f2365486d02dac495f2dee4f8971a4af308396fce6c90f3cfde857bf7a2c6bf5d0d8aa7", "Name": "matter_g1_add_83", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000017f16cffb737dadd52b3c5be258733dc47301474b7351c8dcb8ddb4c519018be08b64efea3336f2b6cfa78e0669dccf9000000000000000000000000000000000ae10eb4f791aa31e5bd7b6c4d68b04c6744262d8f5e9469b3987b101ff5a3066794e05694a9167b7050c3944b6d84f6000000000000000000000000000000000198e12ade128447a240e03e024183c401d605cab1ed81f0f5bb7bc4c7cc9c889a2a01f59c0e37a0767a927719e5a95d000000000000000000000000000000001946e39fee9b76ce552108b339b9b24d11e43d3275ac19d2d4bc745c409bdc3f7c473a60c4d3a4d2cc3b598ae0d66880", "Expected": "00000000000000000000000000000000050b45f896fa40099cda8b1f20ab88644915c16f926589cd709e00149b12922347fa7122175424cd44e8875f217b9ad7000000000000000000000000000000001122b7e9b1509efe5616368b14085bdd36fb7adb85cd5a7f23e327548986f5298c045a602b6ee1265d53a4432a4a3c0e", "Name": "matter_g1_add_84", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000062168f0bfd29c44074430158708a1e3b6808bae633ce9506b32eb9124db1a0668d83f2076adffb568ccf289a61685420000000000000000000000000000000016aead8bd8c4d5ddc444e15bc83e8f14d377d5e8d756a0255f1387506b9a9add69592241dbd9cab95474d55ac47388620000000000000000000000000000000009c48aa2681b3005b24075bb3a122ac100cbaca872f761f4398edaba9dd9da6d04d4a4925028297dfe5f77c2b0b5c821000000000000000000000000000000000ea95c646fb68aa458e69c267a6ca640a6a24d40bdca0161246e4521d13c46facfc1ac86dfc0a804cfa6665cebeec822", "Expected": "0000000000000000000000000000000005325a499aec678ada9eb673d366fe0475e885d5188e2fb687a96949e8f782852fba962197976b868ec083c512bfb66b000000000000000000000000000000000c4d6fcacc8d82401882bee355b37930d83e3cea2e4a7bc133e65a3e0af919b25fc3f30c333873da9406845ce42dbb87", "Name": "matter_g1_add_85", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000c60b948942652a8214d8776b77a6c559ca77eb3a537b0a9abadc3058eac8c1d7840f091acd6c0056d5a71468a2b1ceb0000000000000000000000000000000019049c394e547b9b714b5969adcf068b381def6af2b27d1d361d06e9576273a8febb5bf94b5061ccec7afdb5642c0ae80000000000000000000000000000000008e8799a6cc0339e94e861692c81eee53e8a7b326523d5344b416bfbce04290585ef56018834cfd93d234bfa2943369f000000000000000000000000000000000fa1b01aab0878adad693ec769fb68640931c355b3802c51d4a3772300be5b16ceecdc8328a229b3b9f3639170db96f8", "Expected": "000000000000000000000000000000000685ec14da61c48bcb697966aca9e27601db43f0fb1f32e026fb33738eecfbb7012aa1ca3acf36a21fa846730245add70000000000000000000000000000000003fc52a1c3342b12271bbc178545bb20e96e8f1fde673e51f3d27ab5cb42e60aca49c6077e0f687be59b2d25cda9718e", "Name": "matter_g1_add_86", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000013fe38343072af8ef1d8247c3d46b4fd190086ceddfeb767787031368da6a6a6ae849cfc26a24ead499338e37fa337e30000000000000000000000000000000009f7d7b21882455e9f1f24ea120f3eb69f739c1320c37eb2b17e0a271cb03ac6e2b0c55d3518548a005f28b5748b7f59000000000000000000000000000000000bb3a76287fb98fe668cb0a5de603c768340ee6b7f9f686a22da3a86926d8734d2c565c41f94f08fa3ef0e665f4ccb520000000000000000000000000000000016c02dbfb307c96d5b9c144672fe62f3e9cd78991844f246945ee484cbdef2a4c1b001a017cafb3acc57b35f7c08dc44", "Expected": "00000000000000000000000000000000021796fd6ef624eed7049b8a5c50415cc86104b2367f2966eb3a9f5b7c4833b9470ef558457426f87756d526d94d8dfe000000000000000000000000000000000f492dca3f0a89102b503d7a7d5b197946348e195954d23b8ab9ab7704b3bccecaa2123b8386662f95cd4cfdbbb7a64d", "Name": "matter_g1_add_87", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000018c6df81d810deaac0b143edf79956c92af7941f7b279db345f838bd583177912fc2eb367616ae165e261014a4d7b1b900000000000000000000000000000000146696840e8e988d0eab90ea935dd8b5f1272bbb81eb524e523c57d34ad7c5f0f3b721566f51dac4774826b84cc1c82f00000000000000000000000000000000127420ff97df415e336cf3e24c39c161fad630c45c7ccef80f1831c4f5ed54da12f2c49a161e72bc70285fa0498e46d00000000000000000000000000000000013e605c21014f72364f8bff392ce64a10078ea537237fa282d5dd252ba1677b84b8c15d7925e54a4ab36f1feb13d3064", "Expected": "000000000000000000000000000000000ae916770455b0a63717e81802f5a7fcfbcc3e260b7adeca02a61a520c338d495eea29c4f070fd6efc1b8d23eb285e4c00000000000000000000000000000000134784e092744df573ba78f7d6f3cf1ed19491a0fc7ddfa02d3ca043bcf102fd40c33ac44b03a947308e3cc7af41c2df", "Name": "matter_g1_add_88", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000c6b634d90c2664b9fa4ccbca35913d23696825350e21f0a6dd5e9abb17497a0a499e1b7b928a57ba8c730158f63b75d0000000000000000000000000000000009d569f05e69a38231d0f636e1ef040af059a00db4ff09bd2ad82b7e04cc041a33603c2eb9b148e3b1412bdef9740ab40000000000000000000000000000000016f41e8b098839944adc12481e5f965657a4faedd4f4cdea51a9597a6a0356989e791a686d3d2ee6232ab93683259c6b000000000000000000000000000000000d27b4a56b2cc2216e61eb41061f9a586a704652704906f7fe0eab869ba00d34205ea66f7a02d337d08b916598494e52", "Expected": "0000000000000000000000000000000012842c9d7f4309f6e40124a071d317f5597de419db0d5a8e5324a517f7b61dfdeea2fb4503ad7cdd8deb8aaa5c412554000000000000000000000000000000000ace4d9f98ee6e8a4416ef14d64f26dc49e102e69eced46ef829a352e58e8c1a7e1f083e3f4fc07f24ccd1685dedf215", "Name": "matter_g1_add_89", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000018129b2f00be24717c906d215beaaa136758aa1730bd0bbe9c0de9b3cbb3c0ea47911817fa322b907cc6fc720cabde05000000000000000000000000000000000e8b0f968ccb230517ef8980be559f410a2c4035a1101e6796d4f7a5ee5c93a19c111d38930bd5bca69405fc35fea7c20000000000000000000000000000000019e7c8d182e3b674dfa21539613f7de5d4872d4f4732307a5c6d95ada7e81a01bc25bda34e0b46634e0b0b32cd47e8ec0000000000000000000000000000000008149237de73ab46d5c20dfd85b07f593c0caf2e2e364335450e3ebb478a9f6b9ac0af89174dffd92eda2783a5271f01", "Expected": "000000000000000000000000000000000875289fdaead079a283aafe4de7035c88662642b6bba389b17583f8e3b5801dada6e46bd897af961997665e6ed4a55700000000000000000000000000000000050a6b9c1db35865df0a042d27a042ff4b8d3bec2fba6a3a28a71c5a574620dc05cda0e70932ce9b8966e4592220c147", "Name": "matter_g1_add_90", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000001667fdc9b89d12fb0704fdec910cab1b51ac04219ef6e50f996688b2ceb26dca0e9e8594c5b81fca2e8fc2c8d8fa9a4700000000000000000000000000000000193118d1f237c68a8a0961fb220c0fd6a08853908a039dd57f8ed334063e5316bf83e8c3c3f44420734abbd7ddda31a6000000000000000000000000000000000c0f33f2d76366af661d6fa58a8b5aab207d35ce03899e495f7ddccedf201d9816f270468b207413a2ca70380c798fc60000000000000000000000000000000002a7dc7e2b163e65cadf93b5d682982288c8f36d08b1db8e0b1cb40cd3c7231f3f1672da42b4679f35db2076a8de5b42", "Expected": "0000000000000000000000000000000019ea92820dcd442358db359146797aa82beff6154946b1ea14dccae05e8252b776b817dc044a20764e3514cd22799c0b000000000000000000000000000000000ed929fef2cb11e8b6b9b5d52bfde82080eda747f0c82f33b9cb87019476f0c128e6b918a4486172dee2884ba538ae5d", "Name": "matter_g1_add_91", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000217a4c563d730ef545e452038813301933ccc6638321ee5e217dad0be2e3ddc855a14054d0d72b6bcc692a5fb1ac7300000000000000000000000000000000007025f1c4a5f85a9c1587d4d4a2e620d83d60568343940ffd85e6b1e4fb0f0f53bb08c4f48bf6f45a7dbc3722ecc951e00000000000000000000000000000000118fb45274a6b0ca9fe2654821e3b30caa46444f7c64b1921cf16dfd56a43916947d4fb6968d718a59a30ed38d65ce3000000000000000000000000000000000110e8e73e640bbea6927cd770baaf887c8e0e0c58260bca489c39b6dd7a24ab8c0c0a2495133d8ff8c7afb9790b37faa", "Expected": "0000000000000000000000000000000009452bd0a167683e30c673ffd4e750c66a81edf309a8d2d6dd915c358b30b0ffc001c4165b1b17bf157a0f966bfd91d00000000000000000000000000000000015df0b1ee359dd3e35a7b2c33edbb8e92b18804ae3359a369c6a529f5561298e6be9a3498c9477f33353124af7e91968", "Name": "matter_g1_add_92", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000009ec00ea2da59d937d3154d86dbed2957667253401bce9de80e0ffe6df32f36b06404b9e3af08e912a0b4ef091f93efb000000000000000000000000000000000dd8d1bd66f4accbc9d0c7dabef7af72f51c67a0d61384647533ad92bba44a312f0be0fa52163176f1aff4e64c00aefb0000000000000000000000000000000005dcb54cdf9635db275540c16307fc9f07b4ca5cd91e3977e4b95b58e8103e40ed9fa74752b2a43d95b6acb6f5fcbf440000000000000000000000000000000007ef8457752a47864ef2698176a53990e4822421ecf83b2716251e3ce69151ab2767d4a6611a0a6e0e40a57164ffb94e", "Expected": "0000000000000000000000000000000011f1ac702a06699dd64b63ebdd8b5381578f63b603c63c3a47413fe764af239ab7024712320f3ea3daefa6bd3cd3dfe9000000000000000000000000000000000918bb83a22b4fc66247e007c17155c4c2ec6326131c10fe04a5f9b82ddeca3d21c7c397a70a3949fda4d766540c85ff", "Name": "matter_g1_add_93", "Gas": 600, "NoBenchmark": false }, { "Input": "0000000000000000000000000000000014153e01c9e495c5c01c82b3cad9eaf20cf78369ccbabf57fb160ded309cbd1caea3d3df38a7ea5490c67f168e9acec0000000000000000000000000000000001648030be79658c134e016a211d311841988065957b35e9bc1580fb6e05e291e747b7a960a50e26a2a3c0cd1634c35850000000000000000000000000000000006d3335e092616363e94436bb68be89667c706564ba687f4a3494fcf7da62fd9ad8ae68cb76524926c261983711a14ad000000000000000000000000000000000f085a3d013592c402a380e2e8d9019864a775e7b8e8b94603c8cc1eb1def1e91075fd5675f76534397e2a7d76c2331e", "Expected": "000000000000000000000000000000000344951ccb5e60d1838f7793fcf8b765f5f252b69e1cfdb4bd3c20692c8ffa01afbda6950974a65f6ac74afb9da5942e0000000000000000000000000000000014f5f0e6b99a04d1c5c2adf96c53dd41f8c01aab8db4f0e6d7fc5eab27f6c03c429632db4e1c21467c09d8a54066a4d3", "Name": "matter_g1_add_94", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000001555535228eb9a24f460df9894d59aa06fc848a8bf8d6c3b51653b1d85734b3c5a2bece161309bd478d356fa198d579500000000000000000000000000000000144401f7eb69f6321eae8dad39dbe2cf4ae58e455474701dd9f1b62c85c7536813e84eb4f9def511eb62e5194288728b0000000000000000000000000000000019e2ed6e9757e2339d013078fac91c966045f7a1416a56135d75e603c2021a8bebf4acbf6c0d5ba911f66510e9a7ad1a0000000000000000000000000000000008b8585444ffb3bd4fb6ee23e8128142aa72fd574a506151a0eea8979cbd694e03897caba63771b0490d46063bc5bb57", "Expected": "000000000000000000000000000000000a449fb0da911c544887b24860bc5fcaaf054041cc80f16bbb44c796520bee454d0d06f84fd5aa179a44fd4fac9f144a000000000000000000000000000000000fca81401349089caaef9156a86c64271c77235c9efd136dcfad9894450b076cb3dd1a05bfa1e62ef904435eee5d2250", "Name": "matter_g1_add_95", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000b767f399e4ebea34fd6b6b7f32a77f4a36841a12fc79e68910a963175d28cb634eeb8dc6e0533c662223c36b728cce2000000000000000000000000000000000cb3827fd6ac2c84f24f64789adac53439b4eba89409e12fbca0917faa6b7109aa831d16ca03191a124738228095ed65000000000000000000000000000000000f4a256b4288386545957a3ba28278c0ce69a8a412febfed1f952ca13e673822bacb6b7751ea75893b680ea363aab66400000000000000000000000000000000152379d006e74798199f83b0c6c22a98440ef653d7f0a8c5e3026bcdabec8be59a3cc291ba05860bd0639c5c5f5bee26", "Expected": "000000000000000000000000000000000c427721953e139d4f12ad2a3f8f91a4caa49875a87001b619c8a6e909a7da8ddd9dd026bf56d5f85d49fd17527106a800000000000000000000000000000000018add2816914ef51a289e707ba0224fcf0b7bcfa4001487e90dbdce53f1b596e1f5872de32fcee6f63bce4484ccbef7", "Name": "matter_g1_add_96", "Gas": 600, "NoBenchmark": false }, { "Input": "00000000000000000000000000000000150b75e9e9c03ada40b607f3d648bd6c40269aba3a1a992986dc005c9fde80bb1605266add0819641a0ca702d67bceed00000000000000000000000000000000083b43df032654f2dce90c8049ae4872a39f9cd860f08512930f43898e0f1e5625a5620818788797f3ca68134bc27d220000000000000000000000000000000012dae9aee13ed6ad52fe664bf7d2d0a1f134f0951d0d7ce5184e223bde164f6860967f9aaaa44fa6654d77d026c52d2a000000000000000000000000000000000f71889d64ec2f7da7319994883eb8bd1c753e6cdd3495036b630c35f07118a1bc10568c411ecbdf468a9cdaa9b4811b", "Expected": "000000000000000000000000000000000275b8efb3a3e43e2a24d0cda238154520f0a2b265f168bfc502b9cd4a07b930756961ae7e4fe3f01a5473d36ce3356200000000000000000000000000000000113403d5a968f01ba127dd8ef6c8d7b783a10d039a6b69c617032eba7122e9297f3ce2360c829ae64fdc9794695bf173", "Name": "matter_g1_add_97", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000cba419694214e95a3605a9b748854d16c8e6e1ee151c907487d8189acfac1361b790a5e78f43593152027295adf8df400000000000000000000000000000000110813ff6e0ddf3427e2a514d3f0bfbadcaf9dbf039e0f93fb9643d1e62bc2469fe84cd9ff0d585bdd1037255bbe54850000000000000000000000000000000004e9dd69012ab596b5d3f1f8e4593b448685fcec4ab3394008178b137b762ddf9150cbb8dbb74c8af45bd8baab9a6c4f000000000000000000000000000000001132b66a2127885774062732127951f051c9c3c9b5aba02406e3f3cd4ecfe2dbf6614ebaca3bfe9efbe4f6e5b15ba0f5", "Expected": "000000000000000000000000000000000594c808954bb930bd038806500c9e3fd6460a83554e945baeeec2354a3805f046c76aea62c249080f16ae8e70f8fa6b00000000000000000000000000000000046924a32fb3f2df9a52615e45eeea2fa3ac0e2ccd38458194ada6b4d993ecdc0f441e41d0ea37599254a06aef68b9ae", "Name": "matter_g1_add_98", "Gas": 600, "NoBenchmark": false }, { "Input": "000000000000000000000000000000000106df8eba767e90cce0eabdaacc24d8e226c6865012ef8cb1460de5a319d443fdc6b4f4e58fb668943e0528b1809da10000000000000000000000000000000019789f464c95c179af18704c0b67b881991880f75ee7b03b9feafa3eafcd0f7d30a17fdd9cf439ff7fe683adca2083b50000000000000000000000000000000017a81b957a12adf474a2913e8636f169ea9cd10be62c16b88f95f5caf661f158a032a9f7d249fdf2765caa1564bed0570000000000000000000000000000000017fbf2abc62dc2678b65d509e19c9c9c5d961c72565649a078da8dff98be6236ef314e9ff8022f639ff565353345c230", "Expected": "00000000000000000000000000000000002c8bc5f39b2c9fea01372429e92a9c945fad152da67174f4e478fdead734d50f6e2da867c235f1f2f11bdfee67d2a7000000000000000000000000000000000c1dd27aad9f5d48c4824da3071daedf0c7a0e2a0b0ed39c50c9d25e61334a9c96765e049542ccaa00e0eccb316eec08", "Name": "matter_g1_add_99", "Gas": 600, "NoBenchmark": false } ]
core/vm/testdata/precompiles/blsG1Add.json
0
https://github.com/ethereum/go-ethereum/commit/86dd005544179818edd78ef6c9396b9574e8a614
[ 0.009971192106604576, 0.0017075450159609318, 0.0001727529743220657, 0.0006690306472592056, 0.0021978437434881926 ]
{ "id": 2, "code_window": [ "\t\treturn common.BytesToHash(ret)\n", "\t}\n", "\treturn common.BytesToHash(st.val)\n", "}\n", "\n", "// Commit will commit the current node to database db\n", "func (st *StackTrie) Commit(db ethdb.KeyValueStore) common.Hash {\n", "\toldDb := st.db\n", "\tst.db = db\n", "\tdefer func() {\n", "\t\tst.db = oldDb\n", "\t}()\n", "\tst.hash()\n", "\th := common.BytesToHash(st.val)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "// Commit will firstly hash the entrie trie if it's still not hashed\n", "// and then commit all nodes to the associated database. Actually most\n", "// of the trie nodes MAY have been committed already. The main purpose\n", "// here is to commit the root node.\n", "//\n", "// The associated database is expected, otherwise the whole commit\n", "// functionality should be disabled.\n", "func (st *StackTrie) Commit() (common.Hash, error) {\n", "\tif st.db == nil {\n", "\t\treturn common.Hash{}, ErrCommitDisabled\n", "\t}\n" ], "file_path": "trie/stacktrie.go", "type": "replace", "edit_start_line_idx": 393 }
// Copyright 2020 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 trie import ( "fmt" "sync" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/rlp" ) var stPool = sync.Pool{ New: func() interface{} { return NewStackTrie(nil) }, } func stackTrieFromPool(db ethdb.KeyValueStore) *StackTrie { st := stPool.Get().(*StackTrie) st.db = db return st } func returnToPool(st *StackTrie) { st.Reset() stPool.Put(st) } // StackTrie is a trie implementation that expects keys to be inserted // in order. Once it determines that a subtree will no longer be inserted // into, it will hash it and free up the memory it uses. type StackTrie struct { nodeType uint8 // node type (as in branch, ext, leaf) val []byte // value contained by this node if it's a leaf key []byte // key chunk covered by this (full|ext) node keyOffset int // offset of the key chunk inside a full key children [16]*StackTrie // list of children (for fullnodes and exts) db ethdb.KeyValueStore // Pointer to the commit db, can be nil } // NewStackTrie allocates and initializes an empty trie. func NewStackTrie(db ethdb.KeyValueStore) *StackTrie { return &StackTrie{ nodeType: emptyNode, db: db, } } func newLeaf(ko int, key, val []byte, db ethdb.KeyValueStore) *StackTrie { st := stackTrieFromPool(db) st.nodeType = leafNode st.keyOffset = ko st.key = append(st.key, key[ko:]...) st.val = val return st } func newExt(ko int, key []byte, child *StackTrie, db ethdb.KeyValueStore) *StackTrie { st := stackTrieFromPool(db) st.nodeType = extNode st.keyOffset = ko st.key = append(st.key, key[ko:]...) st.children[0] = child return st } // List all values that StackTrie#nodeType can hold const ( emptyNode = iota branchNode extNode leafNode hashedNode ) // TryUpdate inserts a (key, value) pair into the stack trie func (st *StackTrie) TryUpdate(key, value []byte) error { k := keybytesToHex(key) if len(value) == 0 { panic("deletion not supported") } st.insert(k[:len(k)-1], value) return nil } func (st *StackTrie) Update(key, value []byte) { if err := st.TryUpdate(key, value); err != nil { log.Error(fmt.Sprintf("Unhandled trie error: %v", err)) } } func (st *StackTrie) Reset() { st.db = nil st.key = st.key[:0] st.val = st.val[:0] for i := range st.children { st.children[i] = nil } st.nodeType = emptyNode st.keyOffset = 0 } // Helper function that, given a full key, determines the index // at which the chunk pointed by st.keyOffset is different from // the same chunk in the full key. func (st *StackTrie) getDiffIndex(key []byte) int { diffindex := 0 for ; diffindex < len(st.key) && st.key[diffindex] == key[st.keyOffset+diffindex]; diffindex++ { } return diffindex } // Helper function to that inserts a (key, value) pair into // the trie. func (st *StackTrie) insert(key, value []byte) { switch st.nodeType { case branchNode: /* Branch */ idx := int(key[st.keyOffset]) // Unresolve elder siblings for i := idx - 1; i >= 0; i-- { if st.children[i] != nil { if st.children[i].nodeType != hashedNode { st.children[i].hash() } break } } // Add new child if st.children[idx] == nil { st.children[idx] = stackTrieFromPool(st.db) st.children[idx].keyOffset = st.keyOffset + 1 } st.children[idx].insert(key, value) case extNode: /* Ext */ // Compare both key chunks and see where they differ diffidx := st.getDiffIndex(key) // Check if chunks are identical. If so, recurse into // the child node. Otherwise, the key has to be split // into 1) an optional common prefix, 2) the fullnode // representing the two differing path, and 3) a leaf // for each of the differentiated subtrees. if diffidx == len(st.key) { // Ext key and key segment are identical, recurse into // the child node. st.children[0].insert(key, value) return } // Save the original part. Depending if the break is // at the extension's last byte or not, create an // intermediate extension or use the extension's child // node directly. var n *StackTrie if diffidx < len(st.key)-1 { n = newExt(diffidx+1, st.key, st.children[0], st.db) } else { // Break on the last byte, no need to insert // an extension node: reuse the current node n = st.children[0] } // Convert to hash n.hash() var p *StackTrie if diffidx == 0 { // the break is on the first byte, so // the current node is converted into // a branch node. st.children[0] = nil p = st st.nodeType = branchNode } else { // the common prefix is at least one byte // long, insert a new intermediate branch // node. st.children[0] = stackTrieFromPool(st.db) st.children[0].nodeType = branchNode st.children[0].keyOffset = st.keyOffset + diffidx p = st.children[0] } // Create a leaf for the inserted part o := newLeaf(st.keyOffset+diffidx+1, key, value, st.db) // Insert both child leaves where they belong: origIdx := st.key[diffidx] newIdx := key[diffidx+st.keyOffset] p.children[origIdx] = n p.children[newIdx] = o st.key = st.key[:diffidx] case leafNode: /* Leaf */ // Compare both key chunks and see where they differ diffidx := st.getDiffIndex(key) // Overwriting a key isn't supported, which means that // the current leaf is expected to be split into 1) an // optional extension for the common prefix of these 2 // keys, 2) a fullnode selecting the path on which the // keys differ, and 3) one leaf for the differentiated // component of each key. if diffidx >= len(st.key) { panic("Trying to insert into existing key") } // Check if the split occurs at the first nibble of the // chunk. In that case, no prefix extnode is necessary. // Otherwise, create that var p *StackTrie if diffidx == 0 { // Convert current leaf into a branch st.nodeType = branchNode p = st st.children[0] = nil } else { // Convert current node into an ext, // and insert a child branch node. st.nodeType = extNode st.children[0] = NewStackTrie(st.db) st.children[0].nodeType = branchNode st.children[0].keyOffset = st.keyOffset + diffidx p = st.children[0] } // Create the two child leaves: the one containing the // original value and the one containing the new value // The child leave will be hashed directly in order to // free up some memory. origIdx := st.key[diffidx] p.children[origIdx] = newLeaf(diffidx+1, st.key, st.val, st.db) p.children[origIdx].hash() newIdx := key[diffidx+st.keyOffset] p.children[newIdx] = newLeaf(p.keyOffset+1, key, value, st.db) // Finally, cut off the key part that has been passed // over to the children. st.key = st.key[:diffidx] st.val = nil case emptyNode: /* Empty */ st.nodeType = leafNode st.key = key[st.keyOffset:] st.val = value case hashedNode: panic("trying to insert into hash") default: panic("invalid type") } } // hash() hashes the node 'st' and converts it into 'hashedNode', if possible. // Possible outcomes: // 1. The rlp-encoded value was >= 32 bytes: // - Then the 32-byte `hash` will be accessible in `st.val`. // - And the 'st.type' will be 'hashedNode' // 2. The rlp-encoded value was < 32 bytes // - Then the <32 byte rlp-encoded value will be accessible in 'st.val'. // - And the 'st.type' will be 'hashedNode' AGAIN // // This method will also: // set 'st.type' to hashedNode // clear 'st.key' func (st *StackTrie) hash() { /* Shortcut if node is already hashed */ if st.nodeType == hashedNode { return } // The 'hasher' is taken from a pool, but we don't actually // claim an instance until all children are done with their hashing, // and we actually need one var h *hasher switch st.nodeType { case branchNode: var nodes [17]node for i, child := range st.children { if child == nil { nodes[i] = nilValueNode continue } child.hash() if len(child.val) < 32 { nodes[i] = rawNode(child.val) } else { nodes[i] = hashNode(child.val) } st.children[i] = nil // Reclaim mem from subtree returnToPool(child) } nodes[16] = nilValueNode h = newHasher(false) defer returnHasherToPool(h) h.tmp.Reset() if err := rlp.Encode(&h.tmp, nodes); err != nil { panic(err) } case extNode: h = newHasher(false) defer returnHasherToPool(h) h.tmp.Reset() st.children[0].hash() // This is also possible: //sz := hexToCompactInPlace(st.key) //n := [][]byte{ // st.key[:sz], // st.children[0].val, //} n := [][]byte{ hexToCompact(st.key), st.children[0].val, } if err := rlp.Encode(&h.tmp, n); err != nil { panic(err) } returnToPool(st.children[0]) st.children[0] = nil // Reclaim mem from subtree case leafNode: h = newHasher(false) defer returnHasherToPool(h) h.tmp.Reset() st.key = append(st.key, byte(16)) sz := hexToCompactInPlace(st.key) n := [][]byte{st.key[:sz], st.val} if err := rlp.Encode(&h.tmp, n); err != nil { panic(err) } case emptyNode: st.val = st.val[:0] st.val = append(st.val, emptyRoot[:]...) st.key = st.key[:0] st.nodeType = hashedNode return default: panic("Invalid node type") } st.key = st.key[:0] st.nodeType = hashedNode if len(h.tmp) < 32 { st.val = st.val[:0] st.val = append(st.val, h.tmp...) return } // Going to write the hash to the 'val'. Need to ensure it's properly sized first // Typically, 'branchNode's will have no 'val', and require this allocation if required := 32 - len(st.val); required > 0 { buf := make([]byte, required) st.val = append(st.val, buf...) } st.val = st.val[:32] h.sha.Reset() h.sha.Write(h.tmp) h.sha.Read(st.val) if st.db != nil { // TODO! Is it safe to Put the slice here? // Do all db implementations copy the value provided? st.db.Put(st.val, h.tmp) } } // Hash returns the hash of the current node func (st *StackTrie) Hash() (h common.Hash) { st.hash() if len(st.val) != 32 { // If the node's RLP isn't 32 bytes long, the node will not // be hashed, and instead contain the rlp-encoding of the // node. For the top level node, we need to force the hashing. ret := make([]byte, 32) h := newHasher(false) defer returnHasherToPool(h) h.sha.Reset() h.sha.Write(st.val) h.sha.Read(ret) return common.BytesToHash(ret) } return common.BytesToHash(st.val) } // Commit will commit the current node to database db func (st *StackTrie) Commit(db ethdb.KeyValueStore) common.Hash { oldDb := st.db st.db = db defer func() { st.db = oldDb }() st.hash() h := common.BytesToHash(st.val) return h }
trie/stacktrie.go
1
https://github.com/ethereum/go-ethereum/commit/86dd005544179818edd78ef6c9396b9574e8a614
[ 0.9978173971176147, 0.1172669306397438, 0.00016884019714780152, 0.0035013933666050434, 0.2786172032356262 ]
{ "id": 2, "code_window": [ "\t\treturn common.BytesToHash(ret)\n", "\t}\n", "\treturn common.BytesToHash(st.val)\n", "}\n", "\n", "// Commit will commit the current node to database db\n", "func (st *StackTrie) Commit(db ethdb.KeyValueStore) common.Hash {\n", "\toldDb := st.db\n", "\tst.db = db\n", "\tdefer func() {\n", "\t\tst.db = oldDb\n", "\t}()\n", "\tst.hash()\n", "\th := common.BytesToHash(st.val)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "// Commit will firstly hash the entrie trie if it's still not hashed\n", "// and then commit all nodes to the associated database. Actually most\n", "// of the trie nodes MAY have been committed already. The main purpose\n", "// here is to commit the root node.\n", "//\n", "// The associated database is expected, otherwise the whole commit\n", "// functionality should be disabled.\n", "func (st *StackTrie) Commit() (common.Hash, error) {\n", "\tif st.db == nil {\n", "\t\treturn common.Hash{}, ErrCommitDisabled\n", "\t}\n" ], "file_path": "trie/stacktrie.go", "type": "replace", "edit_start_line_idx": 393 }
{"address":"289d485d9771714cce91d3393d764e1311907acc","crypto":{"cipher":"aes-128-ctr","ciphertext":"faf32ca89d286b107f5e6d842802e05263c49b78d46eac74e6109e9a963378ab","cipherparams":{"iv":"558833eec4a665a8c55608d7d503407d"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":8,"p":16,"r":8,"salt":"d571fff447ffb24314f9513f5160246f09997b857ac71348b73e785aab40dc04"},"mac":"21edb85ff7d0dab1767b9bf498f2c3cb7be7609490756bd32300bb213b59effe"},"id":"3279afcf-55ba-43ff-8997-02dcc46a6525","version":3}
accounts/keystore/testdata/keystore/zzz
0
https://github.com/ethereum/go-ethereum/commit/86dd005544179818edd78ef6c9396b9574e8a614
[ 0.00016813926049508154, 0.00016813926049508154, 0.00016813926049508154, 0.00016813926049508154, 0 ]
{ "id": 2, "code_window": [ "\t\treturn common.BytesToHash(ret)\n", "\t}\n", "\treturn common.BytesToHash(st.val)\n", "}\n", "\n", "// Commit will commit the current node to database db\n", "func (st *StackTrie) Commit(db ethdb.KeyValueStore) common.Hash {\n", "\toldDb := st.db\n", "\tst.db = db\n", "\tdefer func() {\n", "\t\tst.db = oldDb\n", "\t}()\n", "\tst.hash()\n", "\th := common.BytesToHash(st.val)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "// Commit will firstly hash the entrie trie if it's still not hashed\n", "// and then commit all nodes to the associated database. Actually most\n", "// of the trie nodes MAY have been committed already. The main purpose\n", "// here is to commit the root node.\n", "//\n", "// The associated database is expected, otherwise the whole commit\n", "// functionality should be disabled.\n", "func (st *StackTrie) Commit() (common.Hash, error) {\n", "\tif st.db == nil {\n", "\t\treturn common.Hash{}, ErrCommitDisabled\n", "\t}\n" ], "file_path": "trie/stacktrie.go", "type": "replace", "edit_start_line_idx": 393 }
// Copyright 2017 The go-ethereum Authors // This file is part of go-ethereum. // // go-ethereum is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // go-ethereum 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>. package main import ( "encoding/json" "errors" "fmt" "net" "strconv" "strings" "time" "github.com/ethereum/go-ethereum/log" ) var ( // ErrServiceUnknown is returned when a service container doesn't exist. ErrServiceUnknown = errors.New("service unknown") // ErrServiceOffline is returned when a service container exists, but it is not // running. ErrServiceOffline = errors.New("service offline") // ErrServiceUnreachable is returned when a service container is running, but // seems to not respond to communication attempts. ErrServiceUnreachable = errors.New("service unreachable") // ErrNotExposed is returned if a web-service doesn't have an exposed port, nor // a reverse-proxy in front of it to forward requests. ErrNotExposed = errors.New("service not exposed, nor proxied") ) // containerInfos is a heavily reduced version of the huge inspection dataset // returned from docker inspect, parsed into a form easily usable by puppeth. type containerInfos struct { running bool // Flag whether the container is running currently envvars map[string]string // Collection of environmental variables set on the container portmap map[string]int // Port mapping from internal port/proto combos to host binds volumes map[string]string // Volume mount points from container to host directories } // inspectContainer runs docker inspect against a running container func inspectContainer(client *sshClient, container string) (*containerInfos, error) { // Check whether there's a container running for the service out, err := client.Run(fmt.Sprintf("docker inspect %s", container)) if err != nil { return nil, ErrServiceUnknown } // If yes, extract various configuration options type inspection struct { State struct { Running bool } Mounts []struct { Source string Destination string } Config struct { Env []string } HostConfig struct { PortBindings map[string][]map[string]string } } var inspects []inspection if err = json.Unmarshal(out, &inspects); err != nil { return nil, err } inspect := inspects[0] // Infos retrieved, parse the above into something meaningful infos := &containerInfos{ running: inspect.State.Running, envvars: make(map[string]string), portmap: make(map[string]int), volumes: make(map[string]string), } for _, envvar := range inspect.Config.Env { if parts := strings.Split(envvar, "="); len(parts) == 2 { infos.envvars[parts[0]] = parts[1] } } for portname, details := range inspect.HostConfig.PortBindings { if len(details) > 0 { port, _ := strconv.Atoi(details[0]["HostPort"]) infos.portmap[portname] = port } } for _, mount := range inspect.Mounts { infos.volumes[mount.Destination] = mount.Source } return infos, err } // tearDown connects to a remote machine via SSH and terminates docker containers // running with the specified name in the specified network. func tearDown(client *sshClient, network string, service string, purge bool) ([]byte, error) { // Tear down the running (or paused) container out, err := client.Run(fmt.Sprintf("docker rm -f %s_%s_1", network, service)) if err != nil { return out, err } // If requested, purge the associated docker image too if purge { return client.Run(fmt.Sprintf("docker rmi %s/%s", network, service)) } return nil, nil } // resolve retrieves the hostname a service is running on either by returning the // actual server name and port, or preferably an nginx virtual host if available. func resolve(client *sshClient, network string, service string, port int) (string, error) { // Inspect the service to get various configurations from it infos, err := inspectContainer(client, fmt.Sprintf("%s_%s_1", network, service)) if err != nil { return "", err } if !infos.running { return "", ErrServiceOffline } // Container online, extract any environmental variables if vhost := infos.envvars["VIRTUAL_HOST"]; vhost != "" { return vhost, nil } return fmt.Sprintf("%s:%d", client.server, port), nil } // checkPort tries to connect to a remote host on a given func checkPort(host string, port int) error { log.Trace("Verifying remote TCP connectivity", "server", host, "port", port) conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", host, port), time.Second) if err != nil { return err } conn.Close() return nil }
cmd/puppeth/module.go
0
https://github.com/ethereum/go-ethereum/commit/86dd005544179818edd78ef6c9396b9574e8a614
[ 0.00031655366183258593, 0.00018439910490997136, 0.00016640093235764652, 0.00016954075545072556, 0.000038205784221645445 ]
{ "id": 2, "code_window": [ "\t\treturn common.BytesToHash(ret)\n", "\t}\n", "\treturn common.BytesToHash(st.val)\n", "}\n", "\n", "// Commit will commit the current node to database db\n", "func (st *StackTrie) Commit(db ethdb.KeyValueStore) common.Hash {\n", "\toldDb := st.db\n", "\tst.db = db\n", "\tdefer func() {\n", "\t\tst.db = oldDb\n", "\t}()\n", "\tst.hash()\n", "\th := common.BytesToHash(st.val)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "// Commit will firstly hash the entrie trie if it's still not hashed\n", "// and then commit all nodes to the associated database. Actually most\n", "// of the trie nodes MAY have been committed already. The main purpose\n", "// here is to commit the root node.\n", "//\n", "// The associated database is expected, otherwise the whole commit\n", "// functionality should be disabled.\n", "func (st *StackTrie) Commit() (common.Hash, error) {\n", "\tif st.db == nil {\n", "\t\treturn common.Hash{}, ErrCommitDisabled\n", "\t}\n" ], "file_path": "trie/stacktrie.go", "type": "replace", "edit_start_line_idx": 393 }
{ "context": { "difficulty": "3755480783", "gasLimit": "5401723", "miner": "0xd049bfd667cb46aa3ef5df0da3e57db3be39e511", "number": "2294702", "timestamp": "1513676146" }, "genesis": { "alloc": { "0x13e4acefe6a6700604929946e70e6443e4e73447": { "balance": "0xcf3e0938579f000", "code": "0x", "nonce": "9", "storage": {} }, "0x7dc9c9730689ff0b0fd506c67db815f12d90a448": { "balance": "0x0", "code": "0x", "nonce": "0", "storage": {} } }, "config": { "byzantiumBlock": 1700000, "chainId": 3, "daoForkSupport": true, "eip150Block": 0, "eip150Hash": "0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d", "eip155Block": 10, "eip158Block": 10, "ethash": {}, "homesteadBlock": 0 }, "difficulty": "3757315409", "extraData": "0x566961425443", "gasLimit": "5406414", "hash": "0xae107f592eebdd9ff8d6ba00363676096e6afb0e1007a7d3d0af88173077378d", "miner": "0xd049bfd667cb46aa3ef5df0da3e57db3be39e511", "mixHash": "0xc927aa05a38bc3de864e95c33b3ae559d3f39c4ccd51cef6f113f9c50ba0caf1", "nonce": "0x93363bbd2c95f410", "number": "2294701", "stateRoot": "0x6b6737d5bde8058990483e915866bd1578014baeff57bd5e4ed228a2bfad635c", "timestamp": "1513676127", "totalDifficulty": "7160808139332585" }, "input": "0xf907ef098504e3b29200830897be8080b9079c606060405260405160208061077c83398101604052808051906020019091905050600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415151561007d57600080fd5b336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555080600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506001600460006101000a81548160ff02191690831515021790555050610653806101296000396000f300606060405260043610610083576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806305e4382a146100855780631c02708d146100ae5780632e1a7d4d146100c35780635114cb52146100e6578063a37dda2c146100fe578063ae200e7914610153578063b5769f70146101a8575b005b341561009057600080fd5b6100986101d1565b6040518082815260200191505060405180910390f35b34156100b957600080fd5b6100c16101d7565b005b34156100ce57600080fd5b6100e460048080359060200190919050506102eb565b005b6100fc6004808035906020019091905050610513565b005b341561010957600080fd5b6101116105d6565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b341561015e57600080fd5b6101666105fc565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156101b357600080fd5b6101bb610621565b6040518082815260200191505060405180910390f35b60025481565b60011515600460009054906101000a900460ff1615151415156101f957600080fd5b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102a15750600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16145b15156102ac57600080fd5b6000600460006101000a81548160ff0219169083151502179055506003543073ffffffffffffffffffffffffffffffffffffffff163103600281905550565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806103935750600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16145b151561039e57600080fd5b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561048357600060025411801561040757506002548111155b151561041257600080fd5b80600254036002819055506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166108fc829081150290604051600060405180830381858888f19350505050151561047e57600080fd5b610510565b600060035411801561049757506003548111155b15156104a257600080fd5b8060035403600381905550600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166108fc829081150290604051600060405180830381858888f19350505050151561050f57600080fd5b5b50565b60011515600460009054906101000a900460ff16151514151561053557600080fd5b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614801561059657506003548160035401115b80156105bd575080600354013073ffffffffffffffffffffffffffffffffffffffff163110155b15156105c857600080fd5b806003540160038190555050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600354815600a165627a7a72305820c3b849e8440987ce43eae3097b77672a69234d516351368b03fe5b7de03807910029000000000000000000000000c65e620a3a55451316168d57e268f5702ef56a1129a01060f46676a5dff6f407f0f51eb6f37f5c8c54e238c70221e18e65fc29d3ea65a0557b01c50ff4ffaac8ed6e5d31237a4ecbac843ab1bfe8bb0165a0060df7c54f", "result": { "from": "0x13e4acefe6a6700604929946e70e6443e4e73447", "gas": "0x5e106", "gasUsed": "0x5e106", "input": "0x606060405260405160208061077c83398101604052808051906020019091905050600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415151561007d57600080fd5b336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555080600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506001600460006101000a81548160ff02191690831515021790555050610653806101296000396000f300606060405260043610610083576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806305e4382a146100855780631c02708d146100ae5780632e1a7d4d146100c35780635114cb52146100e6578063a37dda2c146100fe578063ae200e7914610153578063b5769f70146101a8575b005b341561009057600080fd5b6100986101d1565b6040518082815260200191505060405180910390f35b34156100b957600080fd5b6100c16101d7565b005b34156100ce57600080fd5b6100e460048080359060200190919050506102eb565b005b6100fc6004808035906020019091905050610513565b005b341561010957600080fd5b6101116105d6565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b341561015e57600080fd5b6101666105fc565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156101b357600080fd5b6101bb610621565b6040518082815260200191505060405180910390f35b60025481565b60011515600460009054906101000a900460ff1615151415156101f957600080fd5b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102a15750600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16145b15156102ac57600080fd5b6000600460006101000a81548160ff0219169083151502179055506003543073ffffffffffffffffffffffffffffffffffffffff163103600281905550565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806103935750600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16145b151561039e57600080fd5b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561048357600060025411801561040757506002548111155b151561041257600080fd5b80600254036002819055506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166108fc829081150290604051600060405180830381858888f19350505050151561047e57600080fd5b610510565b600060035411801561049757506003548111155b15156104a257600080fd5b8060035403600381905550600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166108fc829081150290604051600060405180830381858888f19350505050151561050f57600080fd5b5b50565b60011515600460009054906101000a900460ff16151514151561053557600080fd5b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614801561059657506003548160035401115b80156105bd575080600354013073ffffffffffffffffffffffffffffffffffffffff163110155b15156105c857600080fd5b806003540160038190555050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600354815600a165627a7a72305820c3b849e8440987ce43eae3097b77672a69234d516351368b03fe5b7de03807910029000000000000000000000000c65e620a3a55451316168d57e268f5702ef56a11", "output": "0x606060405260043610610083576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806305e4382a146100855780631c02708d146100ae5780632e1a7d4d146100c35780635114cb52146100e6578063a37dda2c146100fe578063ae200e7914610153578063b5769f70146101a8575b005b341561009057600080fd5b6100986101d1565b6040518082815260200191505060405180910390f35b34156100b957600080fd5b6100c16101d7565b005b34156100ce57600080fd5b6100e460048080359060200190919050506102eb565b005b6100fc6004808035906020019091905050610513565b005b341561010957600080fd5b6101116105d6565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b341561015e57600080fd5b6101666105fc565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156101b357600080fd5b6101bb610621565b6040518082815260200191505060405180910390f35b60025481565b60011515600460009054906101000a900460ff1615151415156101f957600080fd5b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102a15750600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16145b15156102ac57600080fd5b6000600460006101000a81548160ff0219169083151502179055506003543073ffffffffffffffffffffffffffffffffffffffff163103600281905550565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806103935750600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16145b151561039e57600080fd5b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561048357600060025411801561040757506002548111155b151561041257600080fd5b80600254036002819055506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166108fc829081150290604051600060405180830381858888f19350505050151561047e57600080fd5b610510565b600060035411801561049757506003548111155b15156104a257600080fd5b8060035403600381905550600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166108fc829081150290604051600060405180830381858888f19350505050151561050f57600080fd5b5b50565b60011515600460009054906101000a900460ff16151514151561053557600080fd5b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614801561059657506003548160035401115b80156105bd575080600354013073ffffffffffffffffffffffffffffffffffffffff163110155b15156105c857600080fd5b806003540160038190555050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600354815600a165627a7a72305820c3b849e8440987ce43eae3097b77672a69234d516351368b03fe5b7de03807910029", "to": "0x7dc9c9730689ff0b0fd506c67db815f12d90a448", "type": "CREATE", "value": "0x0" } }
eth/tracers/testdata/call_tracer_create.json
0
https://github.com/ethereum/go-ethereum/commit/86dd005544179818edd78ef6c9396b9574e8a614
[ 0.012357435189187527, 0.0033941336441785097, 0.00016715170932002366, 0.00020009871514048427, 0.004771409556269646 ]
{ "id": 3, "code_window": [ "\tst.hash()\n", "\th := common.BytesToHash(st.val)\n", "\treturn h\n", "}" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [ "\treturn h, nil\n" ], "file_path": "trie/stacktrie.go", "type": "replace", "edit_start_line_idx": 402 }
// Copyright 2020 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 trie import ( "fmt" "sync" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/rlp" ) var stPool = sync.Pool{ New: func() interface{} { return NewStackTrie(nil) }, } func stackTrieFromPool(db ethdb.KeyValueStore) *StackTrie { st := stPool.Get().(*StackTrie) st.db = db return st } func returnToPool(st *StackTrie) { st.Reset() stPool.Put(st) } // StackTrie is a trie implementation that expects keys to be inserted // in order. Once it determines that a subtree will no longer be inserted // into, it will hash it and free up the memory it uses. type StackTrie struct { nodeType uint8 // node type (as in branch, ext, leaf) val []byte // value contained by this node if it's a leaf key []byte // key chunk covered by this (full|ext) node keyOffset int // offset of the key chunk inside a full key children [16]*StackTrie // list of children (for fullnodes and exts) db ethdb.KeyValueStore // Pointer to the commit db, can be nil } // NewStackTrie allocates and initializes an empty trie. func NewStackTrie(db ethdb.KeyValueStore) *StackTrie { return &StackTrie{ nodeType: emptyNode, db: db, } } func newLeaf(ko int, key, val []byte, db ethdb.KeyValueStore) *StackTrie { st := stackTrieFromPool(db) st.nodeType = leafNode st.keyOffset = ko st.key = append(st.key, key[ko:]...) st.val = val return st } func newExt(ko int, key []byte, child *StackTrie, db ethdb.KeyValueStore) *StackTrie { st := stackTrieFromPool(db) st.nodeType = extNode st.keyOffset = ko st.key = append(st.key, key[ko:]...) st.children[0] = child return st } // List all values that StackTrie#nodeType can hold const ( emptyNode = iota branchNode extNode leafNode hashedNode ) // TryUpdate inserts a (key, value) pair into the stack trie func (st *StackTrie) TryUpdate(key, value []byte) error { k := keybytesToHex(key) if len(value) == 0 { panic("deletion not supported") } st.insert(k[:len(k)-1], value) return nil } func (st *StackTrie) Update(key, value []byte) { if err := st.TryUpdate(key, value); err != nil { log.Error(fmt.Sprintf("Unhandled trie error: %v", err)) } } func (st *StackTrie) Reset() { st.db = nil st.key = st.key[:0] st.val = st.val[:0] for i := range st.children { st.children[i] = nil } st.nodeType = emptyNode st.keyOffset = 0 } // Helper function that, given a full key, determines the index // at which the chunk pointed by st.keyOffset is different from // the same chunk in the full key. func (st *StackTrie) getDiffIndex(key []byte) int { diffindex := 0 for ; diffindex < len(st.key) && st.key[diffindex] == key[st.keyOffset+diffindex]; diffindex++ { } return diffindex } // Helper function to that inserts a (key, value) pair into // the trie. func (st *StackTrie) insert(key, value []byte) { switch st.nodeType { case branchNode: /* Branch */ idx := int(key[st.keyOffset]) // Unresolve elder siblings for i := idx - 1; i >= 0; i-- { if st.children[i] != nil { if st.children[i].nodeType != hashedNode { st.children[i].hash() } break } } // Add new child if st.children[idx] == nil { st.children[idx] = stackTrieFromPool(st.db) st.children[idx].keyOffset = st.keyOffset + 1 } st.children[idx].insert(key, value) case extNode: /* Ext */ // Compare both key chunks and see where they differ diffidx := st.getDiffIndex(key) // Check if chunks are identical. If so, recurse into // the child node. Otherwise, the key has to be split // into 1) an optional common prefix, 2) the fullnode // representing the two differing path, and 3) a leaf // for each of the differentiated subtrees. if diffidx == len(st.key) { // Ext key and key segment are identical, recurse into // the child node. st.children[0].insert(key, value) return } // Save the original part. Depending if the break is // at the extension's last byte or not, create an // intermediate extension or use the extension's child // node directly. var n *StackTrie if diffidx < len(st.key)-1 { n = newExt(diffidx+1, st.key, st.children[0], st.db) } else { // Break on the last byte, no need to insert // an extension node: reuse the current node n = st.children[0] } // Convert to hash n.hash() var p *StackTrie if diffidx == 0 { // the break is on the first byte, so // the current node is converted into // a branch node. st.children[0] = nil p = st st.nodeType = branchNode } else { // the common prefix is at least one byte // long, insert a new intermediate branch // node. st.children[0] = stackTrieFromPool(st.db) st.children[0].nodeType = branchNode st.children[0].keyOffset = st.keyOffset + diffidx p = st.children[0] } // Create a leaf for the inserted part o := newLeaf(st.keyOffset+diffidx+1, key, value, st.db) // Insert both child leaves where they belong: origIdx := st.key[diffidx] newIdx := key[diffidx+st.keyOffset] p.children[origIdx] = n p.children[newIdx] = o st.key = st.key[:diffidx] case leafNode: /* Leaf */ // Compare both key chunks and see where they differ diffidx := st.getDiffIndex(key) // Overwriting a key isn't supported, which means that // the current leaf is expected to be split into 1) an // optional extension for the common prefix of these 2 // keys, 2) a fullnode selecting the path on which the // keys differ, and 3) one leaf for the differentiated // component of each key. if diffidx >= len(st.key) { panic("Trying to insert into existing key") } // Check if the split occurs at the first nibble of the // chunk. In that case, no prefix extnode is necessary. // Otherwise, create that var p *StackTrie if diffidx == 0 { // Convert current leaf into a branch st.nodeType = branchNode p = st st.children[0] = nil } else { // Convert current node into an ext, // and insert a child branch node. st.nodeType = extNode st.children[0] = NewStackTrie(st.db) st.children[0].nodeType = branchNode st.children[0].keyOffset = st.keyOffset + diffidx p = st.children[0] } // Create the two child leaves: the one containing the // original value and the one containing the new value // The child leave will be hashed directly in order to // free up some memory. origIdx := st.key[diffidx] p.children[origIdx] = newLeaf(diffidx+1, st.key, st.val, st.db) p.children[origIdx].hash() newIdx := key[diffidx+st.keyOffset] p.children[newIdx] = newLeaf(p.keyOffset+1, key, value, st.db) // Finally, cut off the key part that has been passed // over to the children. st.key = st.key[:diffidx] st.val = nil case emptyNode: /* Empty */ st.nodeType = leafNode st.key = key[st.keyOffset:] st.val = value case hashedNode: panic("trying to insert into hash") default: panic("invalid type") } } // hash() hashes the node 'st' and converts it into 'hashedNode', if possible. // Possible outcomes: // 1. The rlp-encoded value was >= 32 bytes: // - Then the 32-byte `hash` will be accessible in `st.val`. // - And the 'st.type' will be 'hashedNode' // 2. The rlp-encoded value was < 32 bytes // - Then the <32 byte rlp-encoded value will be accessible in 'st.val'. // - And the 'st.type' will be 'hashedNode' AGAIN // // This method will also: // set 'st.type' to hashedNode // clear 'st.key' func (st *StackTrie) hash() { /* Shortcut if node is already hashed */ if st.nodeType == hashedNode { return } // The 'hasher' is taken from a pool, but we don't actually // claim an instance until all children are done with their hashing, // and we actually need one var h *hasher switch st.nodeType { case branchNode: var nodes [17]node for i, child := range st.children { if child == nil { nodes[i] = nilValueNode continue } child.hash() if len(child.val) < 32 { nodes[i] = rawNode(child.val) } else { nodes[i] = hashNode(child.val) } st.children[i] = nil // Reclaim mem from subtree returnToPool(child) } nodes[16] = nilValueNode h = newHasher(false) defer returnHasherToPool(h) h.tmp.Reset() if err := rlp.Encode(&h.tmp, nodes); err != nil { panic(err) } case extNode: h = newHasher(false) defer returnHasherToPool(h) h.tmp.Reset() st.children[0].hash() // This is also possible: //sz := hexToCompactInPlace(st.key) //n := [][]byte{ // st.key[:sz], // st.children[0].val, //} n := [][]byte{ hexToCompact(st.key), st.children[0].val, } if err := rlp.Encode(&h.tmp, n); err != nil { panic(err) } returnToPool(st.children[0]) st.children[0] = nil // Reclaim mem from subtree case leafNode: h = newHasher(false) defer returnHasherToPool(h) h.tmp.Reset() st.key = append(st.key, byte(16)) sz := hexToCompactInPlace(st.key) n := [][]byte{st.key[:sz], st.val} if err := rlp.Encode(&h.tmp, n); err != nil { panic(err) } case emptyNode: st.val = st.val[:0] st.val = append(st.val, emptyRoot[:]...) st.key = st.key[:0] st.nodeType = hashedNode return default: panic("Invalid node type") } st.key = st.key[:0] st.nodeType = hashedNode if len(h.tmp) < 32 { st.val = st.val[:0] st.val = append(st.val, h.tmp...) return } // Going to write the hash to the 'val'. Need to ensure it's properly sized first // Typically, 'branchNode's will have no 'val', and require this allocation if required := 32 - len(st.val); required > 0 { buf := make([]byte, required) st.val = append(st.val, buf...) } st.val = st.val[:32] h.sha.Reset() h.sha.Write(h.tmp) h.sha.Read(st.val) if st.db != nil { // TODO! Is it safe to Put the slice here? // Do all db implementations copy the value provided? st.db.Put(st.val, h.tmp) } } // Hash returns the hash of the current node func (st *StackTrie) Hash() (h common.Hash) { st.hash() if len(st.val) != 32 { // If the node's RLP isn't 32 bytes long, the node will not // be hashed, and instead contain the rlp-encoding of the // node. For the top level node, we need to force the hashing. ret := make([]byte, 32) h := newHasher(false) defer returnHasherToPool(h) h.sha.Reset() h.sha.Write(st.val) h.sha.Read(ret) return common.BytesToHash(ret) } return common.BytesToHash(st.val) } // Commit will commit the current node to database db func (st *StackTrie) Commit(db ethdb.KeyValueStore) common.Hash { oldDb := st.db st.db = db defer func() { st.db = oldDb }() st.hash() h := common.BytesToHash(st.val) return h }
trie/stacktrie.go
1
https://github.com/ethereum/go-ethereum/commit/86dd005544179818edd78ef6c9396b9574e8a614
[ 0.9980947375297546, 0.21404887735843658, 0.00016555123147554696, 0.00029963775887154043, 0.39744433760643005 ]
{ "id": 3, "code_window": [ "\tst.hash()\n", "\th := common.BytesToHash(st.val)\n", "\treturn h\n", "}" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [ "\treturn h, nil\n" ], "file_path": "trie/stacktrie.go", "type": "replace", "edit_start_line_idx": 402 }
// Copyright 2019 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 dbtest import ( "bytes" "reflect" "sort" "testing" "github.com/ethereum/go-ethereum/ethdb" ) // TestDatabaseSuite runs a suite of tests against a KeyValueStore database // implementation. func TestDatabaseSuite(t *testing.T, New func() ethdb.KeyValueStore) { t.Run("Iterator", func(t *testing.T) { tests := []struct { content map[string]string prefix string start string order []string }{ // Empty databases should be iterable {map[string]string{}, "", "", nil}, {map[string]string{}, "non-existent-prefix", "", nil}, // Single-item databases should be iterable {map[string]string{"key": "val"}, "", "", []string{"key"}}, {map[string]string{"key": "val"}, "k", "", []string{"key"}}, {map[string]string{"key": "val"}, "l", "", nil}, // Multi-item databases should be fully iterable { map[string]string{"k1": "v1", "k5": "v5", "k2": "v2", "k4": "v4", "k3": "v3"}, "", "", []string{"k1", "k2", "k3", "k4", "k5"}, }, { map[string]string{"k1": "v1", "k5": "v5", "k2": "v2", "k4": "v4", "k3": "v3"}, "k", "", []string{"k1", "k2", "k3", "k4", "k5"}, }, { map[string]string{"k1": "v1", "k5": "v5", "k2": "v2", "k4": "v4", "k3": "v3"}, "l", "", nil, }, // Multi-item databases should be prefix-iterable { map[string]string{ "ka1": "va1", "ka5": "va5", "ka2": "va2", "ka4": "va4", "ka3": "va3", "kb1": "vb1", "kb5": "vb5", "kb2": "vb2", "kb4": "vb4", "kb3": "vb3", }, "ka", "", []string{"ka1", "ka2", "ka3", "ka4", "ka5"}, }, { map[string]string{ "ka1": "va1", "ka5": "va5", "ka2": "va2", "ka4": "va4", "ka3": "va3", "kb1": "vb1", "kb5": "vb5", "kb2": "vb2", "kb4": "vb4", "kb3": "vb3", }, "kc", "", nil, }, // Multi-item databases should be prefix-iterable with start position { map[string]string{ "ka1": "va1", "ka5": "va5", "ka2": "va2", "ka4": "va4", "ka3": "va3", "kb1": "vb1", "kb5": "vb5", "kb2": "vb2", "kb4": "vb4", "kb3": "vb3", }, "ka", "3", []string{"ka3", "ka4", "ka5"}, }, { map[string]string{ "ka1": "va1", "ka5": "va5", "ka2": "va2", "ka4": "va4", "ka3": "va3", "kb1": "vb1", "kb5": "vb5", "kb2": "vb2", "kb4": "vb4", "kb3": "vb3", }, "ka", "8", nil, }, } for i, tt := range tests { // Create the key-value data store db := New() for key, val := range tt.content { if err := db.Put([]byte(key), []byte(val)); err != nil { t.Fatalf("test %d: failed to insert item %s:%s into database: %v", i, key, val, err) } } // Iterate over the database with the given configs and verify the results it, idx := db.NewIterator([]byte(tt.prefix), []byte(tt.start)), 0 for it.Next() { if len(tt.order) <= idx { t.Errorf("test %d: prefix=%q more items than expected: checking idx=%d (key %q), expecting len=%d", i, tt.prefix, idx, it.Key(), len(tt.order)) break } if !bytes.Equal(it.Key(), []byte(tt.order[idx])) { t.Errorf("test %d: item %d: key mismatch: have %s, want %s", i, idx, string(it.Key()), tt.order[idx]) } if !bytes.Equal(it.Value(), []byte(tt.content[tt.order[idx]])) { t.Errorf("test %d: item %d: value mismatch: have %s, want %s", i, idx, string(it.Value()), tt.content[tt.order[idx]]) } idx++ } if err := it.Error(); err != nil { t.Errorf("test %d: iteration failed: %v", i, err) } if idx != len(tt.order) { t.Errorf("test %d: iteration terminated prematurely: have %d, want %d", i, idx, len(tt.order)) } db.Close() } }) t.Run("IteratorWith", func(t *testing.T) { db := New() defer db.Close() keys := []string{"1", "2", "3", "4", "6", "10", "11", "12", "20", "21", "22"} sort.Strings(keys) // 1, 10, 11, etc for _, k := range keys { if err := db.Put([]byte(k), nil); err != nil { t.Fatal(err) } } { it := db.NewIterator(nil, nil) got, want := iterateKeys(it), keys if err := it.Error(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(got, want) { t.Errorf("Iterator: got: %s; want: %s", got, want) } } { it := db.NewIterator([]byte("1"), nil) got, want := iterateKeys(it), []string{"1", "10", "11", "12"} if err := it.Error(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(got, want) { t.Errorf("IteratorWith(1,nil): got: %s; want: %s", got, want) } } { it := db.NewIterator([]byte("5"), nil) got, want := iterateKeys(it), []string{} if err := it.Error(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(got, want) { t.Errorf("IteratorWith(5,nil): got: %s; want: %s", got, want) } } { it := db.NewIterator(nil, []byte("2")) got, want := iterateKeys(it), []string{"2", "20", "21", "22", "3", "4", "6"} if err := it.Error(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(got, want) { t.Errorf("IteratorWith(nil,2): got: %s; want: %s", got, want) } } { it := db.NewIterator(nil, []byte("5")) got, want := iterateKeys(it), []string{"6"} if err := it.Error(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(got, want) { t.Errorf("IteratorWith(nil,5): got: %s; want: %s", got, want) } } }) t.Run("KeyValueOperations", func(t *testing.T) { db := New() defer db.Close() key := []byte("foo") if got, err := db.Has(key); err != nil { t.Error(err) } else if got { t.Errorf("wrong value: %t", got) } value := []byte("hello world") if err := db.Put(key, value); err != nil { t.Error(err) } if got, err := db.Has(key); err != nil { t.Error(err) } else if !got { t.Errorf("wrong value: %t", got) } if got, err := db.Get(key); err != nil { t.Error(err) } else if !bytes.Equal(got, value) { t.Errorf("wrong value: %q", got) } if err := db.Delete(key); err != nil { t.Error(err) } if got, err := db.Has(key); err != nil { t.Error(err) } else if got { t.Errorf("wrong value: %t", got) } }) t.Run("Batch", func(t *testing.T) { db := New() defer db.Close() b := db.NewBatch() for _, k := range []string{"1", "2", "3", "4"} { if err := b.Put([]byte(k), nil); err != nil { t.Fatal(err) } } if has, err := db.Has([]byte("1")); err != nil { t.Fatal(err) } else if has { t.Error("db contains element before batch write") } if err := b.Write(); err != nil { t.Fatal(err) } { it := db.NewIterator(nil, nil) if got, want := iterateKeys(it), []string{"1", "2", "3", "4"}; !reflect.DeepEqual(got, want) { t.Errorf("got: %s; want: %s", got, want) } } b.Reset() // Mix writes and deletes in batch b.Put([]byte("5"), nil) b.Delete([]byte("1")) b.Put([]byte("6"), nil) b.Delete([]byte("3")) b.Put([]byte("3"), nil) if err := b.Write(); err != nil { t.Fatal(err) } { it := db.NewIterator(nil, nil) if got, want := iterateKeys(it), []string{"2", "3", "4", "5", "6"}; !reflect.DeepEqual(got, want) { t.Errorf("got: %s; want: %s", got, want) } } }) t.Run("BatchReplay", func(t *testing.T) { db := New() defer db.Close() want := []string{"1", "2", "3", "4"} b := db.NewBatch() for _, k := range want { if err := b.Put([]byte(k), nil); err != nil { t.Fatal(err) } } b2 := db.NewBatch() if err := b.Replay(b2); err != nil { t.Fatal(err) } if err := b2.Replay(db); err != nil { t.Fatal(err) } it := db.NewIterator(nil, nil) if got := iterateKeys(it); !reflect.DeepEqual(got, want) { t.Errorf("got: %s; want: %s", got, want) } }) } func iterateKeys(it ethdb.Iterator) []string { keys := []string{} for it.Next() { keys = append(keys, string(it.Key())) } sort.Strings(keys) it.Release() return keys }
ethdb/dbtest/testsuite.go
0
https://github.com/ethereum/go-ethereum/commit/86dd005544179818edd78ef6c9396b9574e8a614
[ 0.00017606945766601712, 0.00017021165695041418, 0.00016342308663297445, 0.0001707252231426537, 0.0000030730254820809932 ]
{ "id": 3, "code_window": [ "\tst.hash()\n", "\th := common.BytesToHash(st.val)\n", "\treturn h\n", "}" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [ "\treturn h, nil\n" ], "file_path": "trie/stacktrie.go", "type": "replace", "edit_start_line_idx": 402 }
## Fuzzers To run a fuzzer locally, you need [go-fuzz](https://github.com/dvyukov/go-fuzz) installed. First build a fuzzing-binary out of the selected package: ``` (cd ./rlp && CGO_ENABLED=0 go-fuzz-build .) ``` That command should generate a `rlp-fuzz.zip` in the `rlp/` directory. If you are already in that directory, you can do ``` [user@work rlp]$ go-fuzz 2019/11/26 13:36:54 workers: 6, corpus: 3 (3s ago), crashers: 0, restarts: 1/0, execs: 0 (0/sec), cover: 0, uptime: 3s 2019/11/26 13:36:57 workers: 6, corpus: 3 (6s ago), crashers: 0, restarts: 1/0, execs: 0 (0/sec), cover: 1054, uptime: 6s 2019/11/26 13:37:00 workers: 6, corpus: 3 (9s ago), crashers: 0, restarts: 1/8358, execs: 25074 (2786/sec), cover: 1054, uptime: 9s 2019/11/26 13:37:03 workers: 6, corpus: 3 (12s ago), crashers: 0, restarts: 1/8497, execs: 50986 (4249/sec), cover: 1054, uptime: 12s 2019/11/26 13:37:06 workers: 6, corpus: 3 (15s ago), crashers: 0, restarts: 1/9330, execs: 74640 (4976/sec), cover: 1054, uptime: 15s 2019/11/26 13:37:09 workers: 6, corpus: 3 (18s ago), crashers: 0, restarts: 1/9948, execs: 99482 (5527/sec), cover: 1054, uptime: 18s 2019/11/26 13:37:12 workers: 6, corpus: 3 (21s ago), crashers: 0, restarts: 1/9428, execs: 122568 (5836/sec), cover: 1054, uptime: 21s 2019/11/26 13:37:15 workers: 6, corpus: 3 (24s ago), crashers: 0, restarts: 1/9676, execs: 145152 (6048/sec), cover: 1054, uptime: 24s 2019/11/26 13:37:18 workers: 6, corpus: 3 (27s ago), crashers: 0, restarts: 1/9855, execs: 167538 (6205/sec), cover: 1054, uptime: 27s 2019/11/26 13:37:21 workers: 6, corpus: 3 (30s ago), crashers: 0, restarts: 1/9645, execs: 192901 (6430/sec), cover: 1054, uptime: 30s 2019/11/26 13:37:24 workers: 6, corpus: 3 (33s ago), crashers: 0, restarts: 1/9967, execs: 219294 (6645/sec), cover: 1054, uptime: 33s ``` Otherwise: ``` go-fuzz -bin ./rlp/rlp-fuzz.zip ``` ### Notes Once a 'crasher' is found, the fuzzer tries to avoid reporting the same vector twice, so stores the fault in the `suppressions` folder. Thus, if you e.g. make changes to fix a bug, you should _remove_ all data from the `suppressions`-folder, to verify that the issue is indeed resolved. Also, if you have only one and the same exit-point for multiple different types of test, the suppression can make the fuzzer hide different types of errors. So make sure that each type of failure is unique (for an example, see the rlp fuzzer, where a counter `i` is used to differentiate between failures: ```golang if !bytes.Equal(input, output) { panic(fmt.Sprintf("case %d: encode-decode is not equal, \ninput : %x\noutput: %x", i, input, output)) } ```
tests/fuzzers/README.md
0
https://github.com/ethereum/go-ethereum/commit/86dd005544179818edd78ef6c9396b9574e8a614
[ 0.0001729016366880387, 0.00016968019190244377, 0.00016744903405196965, 0.0001694474194664508, 0.0000018379537323198747 ]
{ "id": 3, "code_window": [ "\tst.hash()\n", "\th := common.BytesToHash(st.val)\n", "\treturn h\n", "}" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [ "\treturn h, nil\n" ], "file_path": "trie/stacktrie.go", "type": "replace", "edit_start_line_idx": 402 }
// Copyright 2019 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 asm import ( "testing" ) func TestCompiler(t *testing.T) { tests := []struct { input, output string }{ { input: ` GAS label: PUSH @label `, output: "5a5b6300000001", }, { input: ` PUSH @label label: `, output: "63000000055b", }, { input: ` PUSH @label JUMP label: `, output: "6300000006565b", }, { input: ` JUMP @label label: `, output: "6300000006565b", }, } for _, test := range tests { ch := Lex([]byte(test.input), false) c := NewCompiler(false) c.Feed(ch) output, err := c.Compile() if len(err) != 0 { t.Errorf("compile error: %v\ninput: %s", err, test.input) continue } if output != test.output { t.Errorf("incorrect output\ninput: %sgot: %s\nwant: %s\n", test.input, output, test.output) } } }
core/asm/compiler_test.go
0
https://github.com/ethereum/go-ethereum/commit/86dd005544179818edd78ef6c9396b9574e8a614
[ 0.00018234869639854878, 0.00017395534086972475, 0.00016997690545395017, 0.00017269534873776138, 0.0000036468097732722526 ]
{ "id": 4, "code_window": [ "\t\troot, _ := trie.Commit(nil)\n", "\t\t// Flush memdb -> disk (sponge)\n", "\t\tdb.Commit(root, false, nil)\n", "\t\t// And flush stacktrie -> disk\n", "\t\tstRoot := stTrie.Commit(stTrie.db)\n", "\t\tif stRoot != root {\n", "\t\t\tt.Fatalf(\"root wrong, got %x exp %x\", stRoot, root)\n", "\t\t}\n", "\t\tif got, exp := stackTrieSponge.sponge.Sum(nil), s.sponge.Sum(nil); !bytes.Equal(got, exp) {\n", "\t\t\t// Show the journal\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tstRoot, err := stTrie.Commit()\n", "\t\tif err != nil {\n", "\t\t\tt.Fatalf(\"Failed to commit stack trie %v\", err)\n", "\t\t}\n" ], "file_path": "trie/trie_test.go", "type": "replace", "edit_start_line_idx": 833 }
// Copyright 2020 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 trie import ( "fmt" "sync" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/rlp" ) var stPool = sync.Pool{ New: func() interface{} { return NewStackTrie(nil) }, } func stackTrieFromPool(db ethdb.KeyValueStore) *StackTrie { st := stPool.Get().(*StackTrie) st.db = db return st } func returnToPool(st *StackTrie) { st.Reset() stPool.Put(st) } // StackTrie is a trie implementation that expects keys to be inserted // in order. Once it determines that a subtree will no longer be inserted // into, it will hash it and free up the memory it uses. type StackTrie struct { nodeType uint8 // node type (as in branch, ext, leaf) val []byte // value contained by this node if it's a leaf key []byte // key chunk covered by this (full|ext) node keyOffset int // offset of the key chunk inside a full key children [16]*StackTrie // list of children (for fullnodes and exts) db ethdb.KeyValueStore // Pointer to the commit db, can be nil } // NewStackTrie allocates and initializes an empty trie. func NewStackTrie(db ethdb.KeyValueStore) *StackTrie { return &StackTrie{ nodeType: emptyNode, db: db, } } func newLeaf(ko int, key, val []byte, db ethdb.KeyValueStore) *StackTrie { st := stackTrieFromPool(db) st.nodeType = leafNode st.keyOffset = ko st.key = append(st.key, key[ko:]...) st.val = val return st } func newExt(ko int, key []byte, child *StackTrie, db ethdb.KeyValueStore) *StackTrie { st := stackTrieFromPool(db) st.nodeType = extNode st.keyOffset = ko st.key = append(st.key, key[ko:]...) st.children[0] = child return st } // List all values that StackTrie#nodeType can hold const ( emptyNode = iota branchNode extNode leafNode hashedNode ) // TryUpdate inserts a (key, value) pair into the stack trie func (st *StackTrie) TryUpdate(key, value []byte) error { k := keybytesToHex(key) if len(value) == 0 { panic("deletion not supported") } st.insert(k[:len(k)-1], value) return nil } func (st *StackTrie) Update(key, value []byte) { if err := st.TryUpdate(key, value); err != nil { log.Error(fmt.Sprintf("Unhandled trie error: %v", err)) } } func (st *StackTrie) Reset() { st.db = nil st.key = st.key[:0] st.val = st.val[:0] for i := range st.children { st.children[i] = nil } st.nodeType = emptyNode st.keyOffset = 0 } // Helper function that, given a full key, determines the index // at which the chunk pointed by st.keyOffset is different from // the same chunk in the full key. func (st *StackTrie) getDiffIndex(key []byte) int { diffindex := 0 for ; diffindex < len(st.key) && st.key[diffindex] == key[st.keyOffset+diffindex]; diffindex++ { } return diffindex } // Helper function to that inserts a (key, value) pair into // the trie. func (st *StackTrie) insert(key, value []byte) { switch st.nodeType { case branchNode: /* Branch */ idx := int(key[st.keyOffset]) // Unresolve elder siblings for i := idx - 1; i >= 0; i-- { if st.children[i] != nil { if st.children[i].nodeType != hashedNode { st.children[i].hash() } break } } // Add new child if st.children[idx] == nil { st.children[idx] = stackTrieFromPool(st.db) st.children[idx].keyOffset = st.keyOffset + 1 } st.children[idx].insert(key, value) case extNode: /* Ext */ // Compare both key chunks and see where they differ diffidx := st.getDiffIndex(key) // Check if chunks are identical. If so, recurse into // the child node. Otherwise, the key has to be split // into 1) an optional common prefix, 2) the fullnode // representing the two differing path, and 3) a leaf // for each of the differentiated subtrees. if diffidx == len(st.key) { // Ext key and key segment are identical, recurse into // the child node. st.children[0].insert(key, value) return } // Save the original part. Depending if the break is // at the extension's last byte or not, create an // intermediate extension or use the extension's child // node directly. var n *StackTrie if diffidx < len(st.key)-1 { n = newExt(diffidx+1, st.key, st.children[0], st.db) } else { // Break on the last byte, no need to insert // an extension node: reuse the current node n = st.children[0] } // Convert to hash n.hash() var p *StackTrie if diffidx == 0 { // the break is on the first byte, so // the current node is converted into // a branch node. st.children[0] = nil p = st st.nodeType = branchNode } else { // the common prefix is at least one byte // long, insert a new intermediate branch // node. st.children[0] = stackTrieFromPool(st.db) st.children[0].nodeType = branchNode st.children[0].keyOffset = st.keyOffset + diffidx p = st.children[0] } // Create a leaf for the inserted part o := newLeaf(st.keyOffset+diffidx+1, key, value, st.db) // Insert both child leaves where they belong: origIdx := st.key[diffidx] newIdx := key[diffidx+st.keyOffset] p.children[origIdx] = n p.children[newIdx] = o st.key = st.key[:diffidx] case leafNode: /* Leaf */ // Compare both key chunks and see where they differ diffidx := st.getDiffIndex(key) // Overwriting a key isn't supported, which means that // the current leaf is expected to be split into 1) an // optional extension for the common prefix of these 2 // keys, 2) a fullnode selecting the path on which the // keys differ, and 3) one leaf for the differentiated // component of each key. if diffidx >= len(st.key) { panic("Trying to insert into existing key") } // Check if the split occurs at the first nibble of the // chunk. In that case, no prefix extnode is necessary. // Otherwise, create that var p *StackTrie if diffidx == 0 { // Convert current leaf into a branch st.nodeType = branchNode p = st st.children[0] = nil } else { // Convert current node into an ext, // and insert a child branch node. st.nodeType = extNode st.children[0] = NewStackTrie(st.db) st.children[0].nodeType = branchNode st.children[0].keyOffset = st.keyOffset + diffidx p = st.children[0] } // Create the two child leaves: the one containing the // original value and the one containing the new value // The child leave will be hashed directly in order to // free up some memory. origIdx := st.key[diffidx] p.children[origIdx] = newLeaf(diffidx+1, st.key, st.val, st.db) p.children[origIdx].hash() newIdx := key[diffidx+st.keyOffset] p.children[newIdx] = newLeaf(p.keyOffset+1, key, value, st.db) // Finally, cut off the key part that has been passed // over to the children. st.key = st.key[:diffidx] st.val = nil case emptyNode: /* Empty */ st.nodeType = leafNode st.key = key[st.keyOffset:] st.val = value case hashedNode: panic("trying to insert into hash") default: panic("invalid type") } } // hash() hashes the node 'st' and converts it into 'hashedNode', if possible. // Possible outcomes: // 1. The rlp-encoded value was >= 32 bytes: // - Then the 32-byte `hash` will be accessible in `st.val`. // - And the 'st.type' will be 'hashedNode' // 2. The rlp-encoded value was < 32 bytes // - Then the <32 byte rlp-encoded value will be accessible in 'st.val'. // - And the 'st.type' will be 'hashedNode' AGAIN // // This method will also: // set 'st.type' to hashedNode // clear 'st.key' func (st *StackTrie) hash() { /* Shortcut if node is already hashed */ if st.nodeType == hashedNode { return } // The 'hasher' is taken from a pool, but we don't actually // claim an instance until all children are done with their hashing, // and we actually need one var h *hasher switch st.nodeType { case branchNode: var nodes [17]node for i, child := range st.children { if child == nil { nodes[i] = nilValueNode continue } child.hash() if len(child.val) < 32 { nodes[i] = rawNode(child.val) } else { nodes[i] = hashNode(child.val) } st.children[i] = nil // Reclaim mem from subtree returnToPool(child) } nodes[16] = nilValueNode h = newHasher(false) defer returnHasherToPool(h) h.tmp.Reset() if err := rlp.Encode(&h.tmp, nodes); err != nil { panic(err) } case extNode: h = newHasher(false) defer returnHasherToPool(h) h.tmp.Reset() st.children[0].hash() // This is also possible: //sz := hexToCompactInPlace(st.key) //n := [][]byte{ // st.key[:sz], // st.children[0].val, //} n := [][]byte{ hexToCompact(st.key), st.children[0].val, } if err := rlp.Encode(&h.tmp, n); err != nil { panic(err) } returnToPool(st.children[0]) st.children[0] = nil // Reclaim mem from subtree case leafNode: h = newHasher(false) defer returnHasherToPool(h) h.tmp.Reset() st.key = append(st.key, byte(16)) sz := hexToCompactInPlace(st.key) n := [][]byte{st.key[:sz], st.val} if err := rlp.Encode(&h.tmp, n); err != nil { panic(err) } case emptyNode: st.val = st.val[:0] st.val = append(st.val, emptyRoot[:]...) st.key = st.key[:0] st.nodeType = hashedNode return default: panic("Invalid node type") } st.key = st.key[:0] st.nodeType = hashedNode if len(h.tmp) < 32 { st.val = st.val[:0] st.val = append(st.val, h.tmp...) return } // Going to write the hash to the 'val'. Need to ensure it's properly sized first // Typically, 'branchNode's will have no 'val', and require this allocation if required := 32 - len(st.val); required > 0 { buf := make([]byte, required) st.val = append(st.val, buf...) } st.val = st.val[:32] h.sha.Reset() h.sha.Write(h.tmp) h.sha.Read(st.val) if st.db != nil { // TODO! Is it safe to Put the slice here? // Do all db implementations copy the value provided? st.db.Put(st.val, h.tmp) } } // Hash returns the hash of the current node func (st *StackTrie) Hash() (h common.Hash) { st.hash() if len(st.val) != 32 { // If the node's RLP isn't 32 bytes long, the node will not // be hashed, and instead contain the rlp-encoding of the // node. For the top level node, we need to force the hashing. ret := make([]byte, 32) h := newHasher(false) defer returnHasherToPool(h) h.sha.Reset() h.sha.Write(st.val) h.sha.Read(ret) return common.BytesToHash(ret) } return common.BytesToHash(st.val) } // Commit will commit the current node to database db func (st *StackTrie) Commit(db ethdb.KeyValueStore) common.Hash { oldDb := st.db st.db = db defer func() { st.db = oldDb }() st.hash() h := common.BytesToHash(st.val) return h }
trie/stacktrie.go
1
https://github.com/ethereum/go-ethereum/commit/86dd005544179818edd78ef6c9396b9574e8a614
[ 0.0071600996889173985, 0.00042786780977621675, 0.00016476384189445525, 0.0001743143075145781, 0.0010984196560457349 ]
{ "id": 4, "code_window": [ "\t\troot, _ := trie.Commit(nil)\n", "\t\t// Flush memdb -> disk (sponge)\n", "\t\tdb.Commit(root, false, nil)\n", "\t\t// And flush stacktrie -> disk\n", "\t\tstRoot := stTrie.Commit(stTrie.db)\n", "\t\tif stRoot != root {\n", "\t\t\tt.Fatalf(\"root wrong, got %x exp %x\", stRoot, root)\n", "\t\t}\n", "\t\tif got, exp := stackTrieSponge.sponge.Sum(nil), s.sponge.Sum(nil); !bytes.Equal(got, exp) {\n", "\t\t\t// Show the journal\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tstRoot, err := stTrie.Commit()\n", "\t\tif err != nil {\n", "\t\t\tt.Fatalf(\"Failed to commit stack trie %v\", err)\n", "\t\t}\n" ], "file_path": "trie/trie_test.go", "type": "replace", "edit_start_line_idx": 833 }
// Copyright 2018 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/>. // +build !windows package metrics import ( "syscall" "github.com/ethereum/go-ethereum/log" ) // getProcessCPUTime retrieves the process' CPU time since program startup. func getProcessCPUTime() int64 { var usage syscall.Rusage if err := syscall.Getrusage(syscall.RUSAGE_SELF, &usage); err != nil { log.Warn("Failed to retrieve CPU time", "err", err) return 0 } return int64(usage.Utime.Sec+usage.Stime.Sec)*100 + int64(usage.Utime.Usec+usage.Stime.Usec)/10000 //nolint:unconvert }
metrics/cpu_syscall.go
0
https://github.com/ethereum/go-ethereum/commit/86dd005544179818edd78ef6c9396b9574e8a614
[ 0.00017836854385677725, 0.0001752369134919718, 0.00017068632587324828, 0.00017594639211893082, 0.0000029491204713849584 ]
{ "id": 4, "code_window": [ "\t\troot, _ := trie.Commit(nil)\n", "\t\t// Flush memdb -> disk (sponge)\n", "\t\tdb.Commit(root, false, nil)\n", "\t\t// And flush stacktrie -> disk\n", "\t\tstRoot := stTrie.Commit(stTrie.db)\n", "\t\tif stRoot != root {\n", "\t\t\tt.Fatalf(\"root wrong, got %x exp %x\", stRoot, root)\n", "\t\t}\n", "\t\tif got, exp := stackTrieSponge.sponge.Sum(nil), s.sponge.Sum(nil); !bytes.Equal(got, exp) {\n", "\t\t\t// Show the journal\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tstRoot, err := stTrie.Commit()\n", "\t\tif err != nil {\n", "\t\t\tt.Fatalf(\"Failed to commit stack trie %v\", err)\n", "\t\t}\n" ], "file_path": "trie/trie_test.go", "type": "replace", "edit_start_line_idx": 833 }
// Copyright 2017 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 accounts implements high level Ethereum account management. package accounts import ( "fmt" "math/big" ethereum "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/event" "golang.org/x/crypto/sha3" ) // Account represents an Ethereum account located at a specific location defined // by the optional URL field. type Account struct { Address common.Address `json:"address"` // Ethereum account address derived from the key URL URL `json:"url"` // Optional resource locator within a backend } const ( MimetypeDataWithValidator = "data/validator" MimetypeTypedData = "data/typed" MimetypeClique = "application/x-clique-header" MimetypeTextPlain = "text/plain" ) // Wallet represents a software or hardware wallet that might contain one or more // accounts (derived from the same seed). type Wallet interface { // URL retrieves the canonical path under which this wallet is reachable. It is // user by upper layers to define a sorting order over all wallets from multiple // backends. URL() URL // Status returns a textual status to aid the user in the current state of the // wallet. It also returns an error indicating any failure the wallet might have // encountered. Status() (string, error) // Open initializes access to a wallet instance. It is not meant to unlock or // decrypt account keys, rather simply to establish a connection to hardware // wallets and/or to access derivation seeds. // // The passphrase parameter may or may not be used by the implementation of a // particular wallet instance. The reason there is no passwordless open method // is to strive towards a uniform wallet handling, oblivious to the different // backend providers. // // Please note, if you open a wallet, you must close it to release any allocated // resources (especially important when working with hardware wallets). Open(passphrase string) error // Close releases any resources held by an open wallet instance. Close() error // Accounts retrieves the list of signing accounts the wallet is currently aware // of. For hierarchical deterministic wallets, the list will not be exhaustive, // rather only contain the accounts explicitly pinned during account derivation. Accounts() []Account // Contains returns whether an account is part of this particular wallet or not. Contains(account Account) bool // Derive attempts to explicitly derive a hierarchical deterministic account at // the specified derivation path. If requested, the derived account will be added // to the wallet's tracked account list. Derive(path DerivationPath, pin bool) (Account, error) // SelfDerive sets a base account derivation path from which the wallet attempts // to discover non zero accounts and automatically add them to list of tracked // accounts. // // Note, self derivaton will increment the last component of the specified path // opposed to decending into a child path to allow discovering accounts starting // from non zero components. // // Some hardware wallets switched derivation paths through their evolution, so // this method supports providing multiple bases to discover old user accounts // too. Only the last base will be used to derive the next empty account. // // You can disable automatic account discovery by calling SelfDerive with a nil // chain state reader. SelfDerive(bases []DerivationPath, chain ethereum.ChainStateReader) // SignData requests the wallet to sign the hash of the given data // It looks up the account specified either solely via its address contained within, // or optionally with the aid of any location metadata from the embedded URL field. // // If the wallet requires additional authentication to sign the request (e.g. // a password to decrypt the account, or a PIN code o verify the transaction), // an AuthNeededError instance will be returned, containing infos for the user // about which fields or actions are needed. The user may retry by providing // the needed details via SignDataWithPassphrase, or by other means (e.g. unlock // the account in a keystore). SignData(account Account, mimeType string, data []byte) ([]byte, error) // SignDataWithPassphrase is identical to SignData, but also takes a password // NOTE: there's an chance that an erroneous call might mistake the two strings, and // supply password in the mimetype field, or vice versa. Thus, an implementation // should never echo the mimetype or return the mimetype in the error-response SignDataWithPassphrase(account Account, passphrase, mimeType string, data []byte) ([]byte, error) // SignText requests the wallet to sign the hash of a given piece of data, prefixed // by the Ethereum prefix scheme // It looks up the account specified either solely via its address contained within, // or optionally with the aid of any location metadata from the embedded URL field. // // If the wallet requires additional authentication to sign the request (e.g. // a password to decrypt the account, or a PIN code o verify the transaction), // an AuthNeededError instance will be returned, containing infos for the user // about which fields or actions are needed. The user may retry by providing // the needed details via SignHashWithPassphrase, or by other means (e.g. unlock // the account in a keystore). // // This method should return the signature in 'canonical' format, with v 0 or 1 SignText(account Account, text []byte) ([]byte, error) // SignTextWithPassphrase is identical to Signtext, but also takes a password SignTextWithPassphrase(account Account, passphrase string, hash []byte) ([]byte, error) // SignTx requests the wallet to sign the given transaction. // // It looks up the account specified either solely via its address contained within, // or optionally with the aid of any location metadata from the embedded URL field. // // If the wallet requires additional authentication to sign the request (e.g. // a password to decrypt the account, or a PIN code to verify the transaction), // an AuthNeededError instance will be returned, containing infos for the user // about which fields or actions are needed. The user may retry by providing // the needed details via SignTxWithPassphrase, or by other means (e.g. unlock // the account in a keystore). SignTx(account Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) // SignTxWithPassphrase is identical to SignTx, but also takes a password SignTxWithPassphrase(account Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) } // Backend is a "wallet provider" that may contain a batch of accounts they can // sign transactions with and upon request, do so. type Backend interface { // Wallets retrieves the list of wallets the backend is currently aware of. // // The returned wallets are not opened by default. For software HD wallets this // means that no base seeds are decrypted, and for hardware wallets that no actual // connection is established. // // The resulting wallet list will be sorted alphabetically based on its internal // URL assigned by the backend. Since wallets (especially hardware) may come and // go, the same wallet might appear at a different positions in the list during // subsequent retrievals. Wallets() []Wallet // Subscribe creates an async subscription to receive notifications when the // backend detects the arrival or departure of a wallet. Subscribe(sink chan<- WalletEvent) event.Subscription } // TextHash is a helper function that calculates a hash for the given message that can be // safely used to calculate a signature from. // // The hash is calulcated as // keccak256("\x19Ethereum Signed Message:\n"${message length}${message}). // // This gives context to the signed message and prevents signing of transactions. func TextHash(data []byte) []byte { hash, _ := TextAndHash(data) return hash } // TextAndHash is a helper function that calculates a hash for the given message that can be // safely used to calculate a signature from. // // The hash is calulcated as // keccak256("\x19Ethereum Signed Message:\n"${message length}${message}). // // This gives context to the signed message and prevents signing of transactions. func TextAndHash(data []byte) ([]byte, string) { msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), string(data)) hasher := sha3.NewLegacyKeccak256() hasher.Write([]byte(msg)) return hasher.Sum(nil), msg } // WalletEventType represents the different event types that can be fired by // the wallet subscription subsystem. type WalletEventType int const ( // WalletArrived is fired when a new wallet is detected either via USB or via // a filesystem event in the keystore. WalletArrived WalletEventType = iota // WalletOpened is fired when a wallet is successfully opened with the purpose // of starting any background processes such as automatic key derivation. WalletOpened // WalletDropped WalletDropped ) // WalletEvent is an event fired by an account backend when a wallet arrival or // departure is detected. type WalletEvent struct { Wallet Wallet // Wallet instance arrived or departed Kind WalletEventType // Event type that happened in the system }
accounts/accounts.go
0
https://github.com/ethereum/go-ethereum/commit/86dd005544179818edd78ef6c9396b9574e8a614
[ 0.0003526221262291074, 0.000178751623025164, 0.00016244572179857641, 0.00017104213475249708, 0.00003729488162207417 ]
{ "id": 4, "code_window": [ "\t\troot, _ := trie.Commit(nil)\n", "\t\t// Flush memdb -> disk (sponge)\n", "\t\tdb.Commit(root, false, nil)\n", "\t\t// And flush stacktrie -> disk\n", "\t\tstRoot := stTrie.Commit(stTrie.db)\n", "\t\tif stRoot != root {\n", "\t\t\tt.Fatalf(\"root wrong, got %x exp %x\", stRoot, root)\n", "\t\t}\n", "\t\tif got, exp := stackTrieSponge.sponge.Sum(nil), s.sponge.Sum(nil); !bytes.Equal(got, exp) {\n", "\t\t\t// Show the journal\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tstRoot, err := stTrie.Commit()\n", "\t\tif err != nil {\n", "\t\t\tt.Fatalf(\"Failed to commit stack trie %v\", err)\n", "\t\t}\n" ], "file_path": "trie/trie_test.go", "type": "replace", "edit_start_line_idx": 833 }
// 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 rlp import ( "io" "reflect" ) // RawValue represents an encoded RLP value and can be used to delay // RLP decoding or to precompute an encoding. Note that the decoder does // not verify whether the content of RawValues is valid RLP. type RawValue []byte var rawValueType = reflect.TypeOf(RawValue{}) // ListSize returns the encoded size of an RLP list with the given // content size. func ListSize(contentSize uint64) uint64 { return uint64(headsize(contentSize)) + contentSize } // Split returns the content of first RLP value and any // bytes after the value as subslices of b. func Split(b []byte) (k Kind, content, rest []byte, err error) { k, ts, cs, err := readKind(b) if err != nil { return 0, nil, b, err } return k, b[ts : ts+cs], b[ts+cs:], nil } // SplitString splits b into the content of an RLP string // and any remaining bytes after the string. func SplitString(b []byte) (content, rest []byte, err error) { k, content, rest, err := Split(b) if err != nil { return nil, b, err } if k == List { return nil, b, ErrExpectedString } return content, rest, nil } // SplitUint64 decodes an integer at the beginning of b. // It also returns the remaining data after the integer in 'rest'. func SplitUint64(b []byte) (x uint64, rest []byte, err error) { content, rest, err := SplitString(b) if err != nil { return 0, b, err } switch { case len(content) == 0: return 0, rest, nil case len(content) == 1: if content[0] == 0 { return 0, b, ErrCanonInt } return uint64(content[0]), rest, nil case len(content) > 8: return 0, b, errUintOverflow default: x, err = readSize(content, byte(len(content))) if err != nil { return 0, b, ErrCanonInt } return x, rest, nil } } // SplitList splits b into the content of a list and any remaining // bytes after the list. func SplitList(b []byte) (content, rest []byte, err error) { k, content, rest, err := Split(b) if err != nil { return nil, b, err } if k != List { return nil, b, ErrExpectedList } return content, rest, nil } // CountValues counts the number of encoded values in b. func CountValues(b []byte) (int, error) { i := 0 for ; len(b) > 0; i++ { _, tagsize, size, err := readKind(b) if err != nil { return 0, err } b = b[tagsize+size:] } return i, nil } func readKind(buf []byte) (k Kind, tagsize, contentsize uint64, err error) { if len(buf) == 0 { return 0, 0, 0, io.ErrUnexpectedEOF } b := buf[0] switch { case b < 0x80: k = Byte tagsize = 0 contentsize = 1 case b < 0xB8: k = String tagsize = 1 contentsize = uint64(b - 0x80) // Reject strings that should've been single bytes. if contentsize == 1 && len(buf) > 1 && buf[1] < 128 { return 0, 0, 0, ErrCanonSize } case b < 0xC0: k = String tagsize = uint64(b-0xB7) + 1 contentsize, err = readSize(buf[1:], b-0xB7) case b < 0xF8: k = List tagsize = 1 contentsize = uint64(b - 0xC0) default: k = List tagsize = uint64(b-0xF7) + 1 contentsize, err = readSize(buf[1:], b-0xF7) } if err != nil { return 0, 0, 0, err } // Reject values larger than the input slice. if contentsize > uint64(len(buf))-tagsize { return 0, 0, 0, ErrValueTooLarge } return k, tagsize, contentsize, err } func readSize(b []byte, slen byte) (uint64, error) { if int(slen) > len(b) { return 0, io.ErrUnexpectedEOF } var s uint64 switch slen { case 1: s = uint64(b[0]) case 2: s = uint64(b[0])<<8 | uint64(b[1]) case 3: s = uint64(b[0])<<16 | uint64(b[1])<<8 | uint64(b[2]) case 4: s = uint64(b[0])<<24 | uint64(b[1])<<16 | uint64(b[2])<<8 | uint64(b[3]) case 5: s = uint64(b[0])<<32 | uint64(b[1])<<24 | uint64(b[2])<<16 | uint64(b[3])<<8 | uint64(b[4]) case 6: s = uint64(b[0])<<40 | uint64(b[1])<<32 | uint64(b[2])<<24 | uint64(b[3])<<16 | uint64(b[4])<<8 | uint64(b[5]) case 7: s = uint64(b[0])<<48 | uint64(b[1])<<40 | uint64(b[2])<<32 | uint64(b[3])<<24 | uint64(b[4])<<16 | uint64(b[5])<<8 | uint64(b[6]) case 8: s = uint64(b[0])<<56 | uint64(b[1])<<48 | uint64(b[2])<<40 | uint64(b[3])<<32 | uint64(b[4])<<24 | uint64(b[5])<<16 | uint64(b[6])<<8 | uint64(b[7]) } // Reject sizes < 56 (shouldn't have separate size) and sizes with // leading zero bytes. if s < 56 || b[0] == 0 { return 0, ErrCanonSize } return s, nil }
rlp/raw.go
0
https://github.com/ethereum/go-ethereum/commit/86dd005544179818edd78ef6c9396b9574e8a614
[ 0.0014264759374782443, 0.0002499202382750809, 0.00016480250633321702, 0.00017548369942232966, 0.0002801776572596282 ]
{ "id": 0, "code_window": [ "\t// State returns a wrapper object that provides safe concurrent access to\n", "\t// the global state.\n", "\tState() *states.SyncState\n", "\n", "\t// InstanceExpander returns a helper object for tracking the expansion of\n", "\t// graph nodes during the plan phase in response to \"count\" and \"for_each\"\n", "\t// arguments.\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t// RefreshState returns a wrapper object that provides safe concurrent\n", "\t// access to the state used to store the most recently refreshed resource\n", "\t// values.\n", "\tRefreshState() *states.SyncState\n", "\n" ], "file_path": "terraform/eval_context.go", "type": "add", "edit_start_line_idx": 154 }
package terraform import ( "github.com/hashicorp/hcl/v2" "github.com/hashicorp/terraform/addrs" "github.com/hashicorp/terraform/configs/configschema" "github.com/hashicorp/terraform/instances" "github.com/hashicorp/terraform/lang" "github.com/hashicorp/terraform/plans" "github.com/hashicorp/terraform/providers" "github.com/hashicorp/terraform/provisioners" "github.com/hashicorp/terraform/states" "github.com/hashicorp/terraform/tfdiags" "github.com/zclconf/go-cty/cty" ) // EvalContext is the interface that is given to eval nodes to execute. type EvalContext interface { // Stopped returns a channel that is closed when evaluation is stopped // via Terraform.Context.Stop() Stopped() <-chan struct{} // Path is the current module path. Path() addrs.ModuleInstance // Hook is used to call hook methods. The callback is called for each // hook and should return the hook action to take and the error. Hook(func(Hook) (HookAction, error)) error // Input is the UIInput object for interacting with the UI. Input() UIInput // InitProvider initializes the provider with the given address, and returns // the implementation of the resource provider or an error. // // It is an error to initialize the same provider more than once. This // method will panic if the module instance address of the given provider // configuration does not match the Path() of the EvalContext. InitProvider(addr addrs.AbsProviderConfig) (providers.Interface, error) // Provider gets the provider instance with the given address (already // initialized) or returns nil if the provider isn't initialized. // // This method expects an _absolute_ provider configuration address, since // resources in one module are able to use providers from other modules. // InitProvider must've been called on the EvalContext of the module // that owns the given provider before calling this method. Provider(addrs.AbsProviderConfig) providers.Interface // ProviderSchema retrieves the schema for a particular provider, which // must have already been initialized with InitProvider. // // This method expects an _absolute_ provider configuration address, since // resources in one module are able to use providers from other modules. ProviderSchema(addrs.AbsProviderConfig) *ProviderSchema // CloseProvider closes provider connections that aren't needed anymore. // // This method will panic if the module instance address of the given // provider configuration does not match the Path() of the EvalContext. CloseProvider(addrs.AbsProviderConfig) error // ConfigureProvider configures the provider with the given // configuration. This is a separate context call because this call // is used to store the provider configuration for inheritance lookups // with ParentProviderConfig(). // // This method will panic if the module instance address of the given // provider configuration does not match the Path() of the EvalContext. ConfigureProvider(addrs.AbsProviderConfig, cty.Value) tfdiags.Diagnostics // ProviderInput and SetProviderInput are used to configure providers // from user input. // // These methods will panic if the module instance address of the given // provider configuration does not match the Path() of the EvalContext. ProviderInput(addrs.AbsProviderConfig) map[string]cty.Value SetProviderInput(addrs.AbsProviderConfig, map[string]cty.Value) // InitProvisioner initializes the provisioner with the given name. // It is an error to initialize the same provisioner more than once. InitProvisioner(string) error // Provisioner gets the provisioner instance with the given name (already // initialized) or returns nil if the provisioner isn't initialized. Provisioner(string) provisioners.Interface // ProvisionerSchema retrieves the main configuration schema for a // particular provisioner, which must have already been initialized with // InitProvisioner. ProvisionerSchema(string) *configschema.Block // CloseProvisioner closes provisioner connections that aren't needed // anymore. CloseProvisioner(string) error // EvaluateBlock takes the given raw configuration block and associated // schema and evaluates it to produce a value of an object type that // conforms to the implied type of the schema. // // The "self" argument is optional. If given, it is the referenceable // address that the name "self" should behave as an alias for when // evaluating. Set this to nil if the "self" object should not be available. // // The "key" argument is also optional. If given, it is the instance key // of the current object within the multi-instance container it belongs // to. For example, on a resource block with "count" set this should be // set to a different addrs.IntKey for each instance created from that // block. Set this to addrs.NoKey if not appropriate. // // The returned body is an expanded version of the given body, with any // "dynamic" blocks replaced with zero or more static blocks. This can be // used to extract correct source location information about attributes of // the returned object value. EvaluateBlock(body hcl.Body, schema *configschema.Block, self addrs.Referenceable, keyData InstanceKeyEvalData) (cty.Value, hcl.Body, tfdiags.Diagnostics) // EvaluateExpr takes the given HCL expression and evaluates it to produce // a value. // // The "self" argument is optional. If given, it is the referenceable // address that the name "self" should behave as an alias for when // evaluating. Set this to nil if the "self" object should not be available. EvaluateExpr(expr hcl.Expression, wantType cty.Type, self addrs.Referenceable) (cty.Value, tfdiags.Diagnostics) // EvaluationScope returns a scope that can be used to evaluate reference // addresses in this context. EvaluationScope(self addrs.Referenceable, keyData InstanceKeyEvalData) *lang.Scope // SetModuleCallArguments defines values for the variables of a particular // child module call. // // Calling this function multiple times has merging behavior, keeping any // previously-set keys that are not present in the new map. SetModuleCallArguments(addrs.ModuleCallInstance, map[string]cty.Value) // GetVariableValue returns the value provided for the input variable with // the given address, or cty.DynamicVal if the variable hasn't been assigned // a value yet. // // Most callers should deal with variable values only indirectly via // EvaluationScope and the other expression evaluation functions, but // this is provided because variables tend to be evaluated outside of // the context of the module they belong to and so we sometimes need to // override the normal expression evaluation behavior. GetVariableValue(addr addrs.AbsInputVariableInstance) cty.Value // Changes returns the writer object that can be used to write new proposed // changes into the global changes set. Changes() *plans.ChangesSync // State returns a wrapper object that provides safe concurrent access to // the global state. State() *states.SyncState // InstanceExpander returns a helper object for tracking the expansion of // graph nodes during the plan phase in response to "count" and "for_each" // arguments. // // The InstanceExpander is a global object that is shared across all of the // EvalContext objects for a given configuration. InstanceExpander() *instances.Expander // WithPath returns a copy of the context with the internal path set to the // path argument. WithPath(path addrs.ModuleInstance) EvalContext }
terraform/eval_context.go
1
https://github.com/hashicorp/terraform/commit/d6a586709cf8eee53b46b56bcf00fa7fa44d6441
[ 0.19656337797641754, 0.016452666372060776, 0.00016635381325613707, 0.0005115379462949932, 0.047253601253032684 ]
{ "id": 0, "code_window": [ "\t// State returns a wrapper object that provides safe concurrent access to\n", "\t// the global state.\n", "\tState() *states.SyncState\n", "\n", "\t// InstanceExpander returns a helper object for tracking the expansion of\n", "\t// graph nodes during the plan phase in response to \"count\" and \"for_each\"\n", "\t// arguments.\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t// RefreshState returns a wrapper object that provides safe concurrent\n", "\t// access to the state used to store the most recently refreshed resource\n", "\t// values.\n", "\tRefreshState() *states.SyncState\n", "\n" ], "file_path": "terraform/eval_context.go", "type": "add", "edit_start_line_idx": 154 }
/* * * Copyright 2018 gRPC 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 grpc // Version is the current grpc version. const Version = "1.27.1"
vendor/google.golang.org/grpc/version.go
0
https://github.com/hashicorp/terraform/commit/d6a586709cf8eee53b46b56bcf00fa7fa44d6441
[ 0.00016951560974121094, 0.00016892807616386563, 0.00016783156024757773, 0.00016943707305472344, 7.760198741380009e-7 ]
{ "id": 0, "code_window": [ "\t// State returns a wrapper object that provides safe concurrent access to\n", "\t// the global state.\n", "\tState() *states.SyncState\n", "\n", "\t// InstanceExpander returns a helper object for tracking the expansion of\n", "\t// graph nodes during the plan phase in response to \"count\" and \"for_each\"\n", "\t// arguments.\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t// RefreshState returns a wrapper object that provides safe concurrent\n", "\t// access to the state used to store the most recently refreshed resource\n", "\t// values.\n", "\tRefreshState() *states.SyncState\n", "\n" ], "file_path": "terraform/eval_context.go", "type": "add", "edit_start_line_idx": 154 }
--- layout: "functions" page_title: "base64gzip - Functions - Configuration Language" sidebar_current: "docs-funcs-encoding-base64gzip" description: |- The base64encode function compresses the given string with gzip and then encodes the result in Base64. --- # `base64gzip` Function -> **Note:** This page is about Terraform 0.12 and later. For Terraform 0.11 and earlier, see [0.11 Configuration Language: Interpolation Syntax](../../configuration-0-11/interpolation.html). `base64gzip` compresses a string with gzip and then encodes the result in Base64 encoding. Terraform uses the "standard" Base64 alphabet as defined in [RFC 4648 section 4](https://tools.ietf.org/html/rfc4648#section-4). Strings in the Terraform language are sequences of unicode characters rather than bytes, so this function will first encode the characters from the string as UTF-8, then apply gzip compression, and then finally apply Base64 encoding. While we do not recommend manipulating large, raw binary data in the Terraform language, this function can be used to compress reasonably sized text strings generated within the Terraform language. For example, the result of this function can be used to create a compressed object in Amazon S3 as part of an S3 website. ## Related Functions * [`base64encode`](./base64encode.html) applies Base64 encoding _without_ gzip compression. * [`filebase64`](./filebase64.html) reads a file from the local filesystem and returns its raw bytes with Base64 encoding.
website/docs/configuration/functions/base64gzip.html.md
0
https://github.com/hashicorp/terraform/commit/d6a586709cf8eee53b46b56bcf00fa7fa44d6441
[ 0.0001689988566795364, 0.00016729356138966978, 0.00016555629554204643, 0.00016730953939259052, 0.0000013271255738800392 ]
{ "id": 0, "code_window": [ "\t// State returns a wrapper object that provides safe concurrent access to\n", "\t// the global state.\n", "\tState() *states.SyncState\n", "\n", "\t// InstanceExpander returns a helper object for tracking the expansion of\n", "\t// graph nodes during the plan phase in response to \"count\" and \"for_each\"\n", "\t// arguments.\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t// RefreshState returns a wrapper object that provides safe concurrent\n", "\t// access to the state used to store the most recently refreshed resource\n", "\t// values.\n", "\tRefreshState() *states.SyncState\n", "\n" ], "file_path": "terraform/eval_context.go", "type": "add", "edit_start_line_idx": 154 }
package api import ( "encoding/json" "fmt" "path" "sync" "time" ) const ( // DefaultSemaphoreSessionName is the Session Name we assign if none is provided DefaultSemaphoreSessionName = "Consul API Semaphore" // DefaultSemaphoreSessionTTL is the default session TTL if no Session is provided // when creating a new Semaphore. This is used because we do not have another // other check to depend upon. DefaultSemaphoreSessionTTL = "15s" // DefaultSemaphoreWaitTime is how long we block for at a time to check if semaphore // acquisition is possible. This affects the minimum time it takes to cancel // a Semaphore acquisition. DefaultSemaphoreWaitTime = 15 * time.Second // DefaultSemaphoreKey is the key used within the prefix to // use for coordination between all the contenders. DefaultSemaphoreKey = ".lock" // SemaphoreFlagValue is a magic flag we set to indicate a key // is being used for a semaphore. It is used to detect a potential // conflict with a lock. SemaphoreFlagValue = 0xe0f69a2baa414de0 ) var ( // ErrSemaphoreHeld is returned if we attempt to double lock ErrSemaphoreHeld = fmt.Errorf("Semaphore already held") // ErrSemaphoreNotHeld is returned if we attempt to unlock a semaphore // that we do not hold. ErrSemaphoreNotHeld = fmt.Errorf("Semaphore not held") // ErrSemaphoreInUse is returned if we attempt to destroy a semaphore // that is in use. ErrSemaphoreInUse = fmt.Errorf("Semaphore in use") // ErrSemaphoreConflict is returned if the flags on a key // used for a semaphore do not match expectation ErrSemaphoreConflict = fmt.Errorf("Existing key does not match semaphore use") ) // Semaphore is used to implement a distributed semaphore // using the Consul KV primitives. type Semaphore struct { c *Client opts *SemaphoreOptions isHeld bool sessionRenew chan struct{} lockSession string l sync.Mutex } // SemaphoreOptions is used to parameterize the Semaphore type SemaphoreOptions struct { Prefix string // Must be set and have write permissions Limit int // Must be set, and be positive Value []byte // Optional, value to associate with the contender entry Session string // Optional, created if not specified SessionName string // Optional, defaults to DefaultLockSessionName SessionTTL string // Optional, defaults to DefaultLockSessionTTL MonitorRetries int // Optional, defaults to 0 which means no retries MonitorRetryTime time.Duration // Optional, defaults to DefaultMonitorRetryTime SemaphoreWaitTime time.Duration // Optional, defaults to DefaultSemaphoreWaitTime SemaphoreTryOnce bool // Optional, defaults to false which means try forever } // semaphoreLock is written under the DefaultSemaphoreKey and // is used to coordinate between all the contenders. type semaphoreLock struct { // Limit is the integer limit of holders. This is used to // verify that all the holders agree on the value. Limit int // Holders is a list of all the semaphore holders. // It maps the session ID to true. It is used as a set effectively. Holders map[string]bool } // SemaphorePrefix is used to created a Semaphore which will operate // at the given KV prefix and uses the given limit for the semaphore. // The prefix must have write privileges, and the limit must be agreed // upon by all contenders. func (c *Client) SemaphorePrefix(prefix string, limit int) (*Semaphore, error) { opts := &SemaphoreOptions{ Prefix: prefix, Limit: limit, } return c.SemaphoreOpts(opts) } // SemaphoreOpts is used to create a Semaphore with the given options. // The prefix must have write privileges, and the limit must be agreed // upon by all contenders. If a Session is not provided, one will be created. func (c *Client) SemaphoreOpts(opts *SemaphoreOptions) (*Semaphore, error) { if opts.Prefix == "" { return nil, fmt.Errorf("missing prefix") } if opts.Limit <= 0 { return nil, fmt.Errorf("semaphore limit must be positive") } if opts.SessionName == "" { opts.SessionName = DefaultSemaphoreSessionName } if opts.SessionTTL == "" { opts.SessionTTL = DefaultSemaphoreSessionTTL } else { if _, err := time.ParseDuration(opts.SessionTTL); err != nil { return nil, fmt.Errorf("invalid SessionTTL: %v", err) } } if opts.MonitorRetryTime == 0 { opts.MonitorRetryTime = DefaultMonitorRetryTime } if opts.SemaphoreWaitTime == 0 { opts.SemaphoreWaitTime = DefaultSemaphoreWaitTime } s := &Semaphore{ c: c, opts: opts, } return s, nil } // Acquire attempts to reserve a slot in the semaphore, blocking until // success, interrupted via the stopCh or an error is encountered. // Providing a non-nil stopCh can be used to abort the attempt. // On success, a channel is returned that represents our slot. // This channel could be closed at any time due to session invalidation, // communication errors, operator intervention, etc. It is NOT safe to // assume that the slot is held until Release() unless the Session is specifically // created without any associated health checks. By default Consul sessions // prefer liveness over safety and an application must be able to handle // the session being lost. func (s *Semaphore) Acquire(stopCh <-chan struct{}) (<-chan struct{}, error) { // Hold the lock as we try to acquire s.l.Lock() defer s.l.Unlock() // Check if we already hold the semaphore if s.isHeld { return nil, ErrSemaphoreHeld } // Check if we need to create a session first s.lockSession = s.opts.Session if s.lockSession == "" { sess, err := s.createSession() if err != nil { return nil, fmt.Errorf("failed to create session: %v", err) } s.sessionRenew = make(chan struct{}) s.lockSession = sess session := s.c.Session() go session.RenewPeriodic(s.opts.SessionTTL, sess, nil, s.sessionRenew) // If we fail to acquire the lock, cleanup the session defer func() { if !s.isHeld { close(s.sessionRenew) s.sessionRenew = nil } }() } // Create the contender entry kv := s.c.KV() made, _, err := kv.Acquire(s.contenderEntry(s.lockSession), nil) if err != nil || !made { return nil, fmt.Errorf("failed to make contender entry: %v", err) } // Setup the query options qOpts := &QueryOptions{ WaitTime: s.opts.SemaphoreWaitTime, } start := time.Now() attempts := 0 WAIT: // Check if we should quit select { case <-stopCh: return nil, nil default: } // Handle the one-shot mode. if s.opts.SemaphoreTryOnce && attempts > 0 { elapsed := time.Since(start) if elapsed > qOpts.WaitTime { return nil, nil } qOpts.WaitTime -= elapsed } attempts++ // Read the prefix pairs, meta, err := kv.List(s.opts.Prefix, qOpts) if err != nil { return nil, fmt.Errorf("failed to read prefix: %v", err) } // Decode the lock lockPair := s.findLock(pairs) if lockPair.Flags != SemaphoreFlagValue { return nil, ErrSemaphoreConflict } lock, err := s.decodeLock(lockPair) if err != nil { return nil, err } // Verify we agree with the limit if lock.Limit != s.opts.Limit { return nil, fmt.Errorf("semaphore limit conflict (lock: %d, local: %d)", lock.Limit, s.opts.Limit) } // Prune the dead holders s.pruneDeadHolders(lock, pairs) // Check if the lock is held if len(lock.Holders) >= lock.Limit { qOpts.WaitIndex = meta.LastIndex goto WAIT } // Create a new lock with us as a holder lock.Holders[s.lockSession] = true newLock, err := s.encodeLock(lock, lockPair.ModifyIndex) if err != nil { return nil, err } // Attempt the acquisition didSet, _, err := kv.CAS(newLock, nil) if err != nil { return nil, fmt.Errorf("failed to update lock: %v", err) } if !didSet { // Update failed, could have been a race with another contender, // retry the operation goto WAIT } // Watch to ensure we maintain ownership of the slot lockCh := make(chan struct{}) go s.monitorLock(s.lockSession, lockCh) // Set that we own the lock s.isHeld = true // Acquired! All done return lockCh, nil } // Release is used to voluntarily give up our semaphore slot. It is // an error to call this if the semaphore has not been acquired. func (s *Semaphore) Release() error { // Hold the lock as we try to release s.l.Lock() defer s.l.Unlock() // Ensure the lock is actually held if !s.isHeld { return ErrSemaphoreNotHeld } // Set that we no longer own the lock s.isHeld = false // Stop the session renew if s.sessionRenew != nil { defer func() { close(s.sessionRenew) s.sessionRenew = nil }() } // Get and clear the lock session lockSession := s.lockSession s.lockSession = "" // Remove ourselves as a lock holder kv := s.c.KV() key := path.Join(s.opts.Prefix, DefaultSemaphoreKey) READ: pair, _, err := kv.Get(key, nil) if err != nil { return err } if pair == nil { pair = &KVPair{} } lock, err := s.decodeLock(pair) if err != nil { return err } // Create a new lock without us as a holder if _, ok := lock.Holders[lockSession]; ok { delete(lock.Holders, lockSession) newLock, err := s.encodeLock(lock, pair.ModifyIndex) if err != nil { return err } // Swap the locks didSet, _, err := kv.CAS(newLock, nil) if err != nil { return fmt.Errorf("failed to update lock: %v", err) } if !didSet { goto READ } } // Destroy the contender entry contenderKey := path.Join(s.opts.Prefix, lockSession) if _, err := kv.Delete(contenderKey, nil); err != nil { return err } return nil } // Destroy is used to cleanup the semaphore entry. It is not necessary // to invoke. It will fail if the semaphore is in use. func (s *Semaphore) Destroy() error { // Hold the lock as we try to acquire s.l.Lock() defer s.l.Unlock() // Check if we already hold the semaphore if s.isHeld { return ErrSemaphoreHeld } // List for the semaphore kv := s.c.KV() pairs, _, err := kv.List(s.opts.Prefix, nil) if err != nil { return fmt.Errorf("failed to read prefix: %v", err) } // Find the lock pair, bail if it doesn't exist lockPair := s.findLock(pairs) if lockPair.ModifyIndex == 0 { return nil } if lockPair.Flags != SemaphoreFlagValue { return ErrSemaphoreConflict } // Decode the lock lock, err := s.decodeLock(lockPair) if err != nil { return err } // Prune the dead holders s.pruneDeadHolders(lock, pairs) // Check if there are any holders if len(lock.Holders) > 0 { return ErrSemaphoreInUse } // Attempt the delete didRemove, _, err := kv.DeleteCAS(lockPair, nil) if err != nil { return fmt.Errorf("failed to remove semaphore: %v", err) } if !didRemove { return ErrSemaphoreInUse } return nil } // createSession is used to create a new managed session func (s *Semaphore) createSession() (string, error) { session := s.c.Session() se := &SessionEntry{ Name: s.opts.SessionName, TTL: s.opts.SessionTTL, Behavior: SessionBehaviorDelete, } id, _, err := session.Create(se, nil) if err != nil { return "", err } return id, nil } // contenderEntry returns a formatted KVPair for the contender func (s *Semaphore) contenderEntry(session string) *KVPair { return &KVPair{ Key: path.Join(s.opts.Prefix, session), Value: s.opts.Value, Session: session, Flags: SemaphoreFlagValue, } } // findLock is used to find the KV Pair which is used for coordination func (s *Semaphore) findLock(pairs KVPairs) *KVPair { key := path.Join(s.opts.Prefix, DefaultSemaphoreKey) for _, pair := range pairs { if pair.Key == key { return pair } } return &KVPair{Flags: SemaphoreFlagValue} } // decodeLock is used to decode a semaphoreLock from an // entry in Consul func (s *Semaphore) decodeLock(pair *KVPair) (*semaphoreLock, error) { // Handle if there is no lock if pair == nil || pair.Value == nil { return &semaphoreLock{ Limit: s.opts.Limit, Holders: make(map[string]bool), }, nil } l := &semaphoreLock{} if err := json.Unmarshal(pair.Value, l); err != nil { return nil, fmt.Errorf("lock decoding failed: %v", err) } return l, nil } // encodeLock is used to encode a semaphoreLock into a KVPair // that can be PUT func (s *Semaphore) encodeLock(l *semaphoreLock, oldIndex uint64) (*KVPair, error) { enc, err := json.Marshal(l) if err != nil { return nil, fmt.Errorf("lock encoding failed: %v", err) } pair := &KVPair{ Key: path.Join(s.opts.Prefix, DefaultSemaphoreKey), Value: enc, Flags: SemaphoreFlagValue, ModifyIndex: oldIndex, } return pair, nil } // pruneDeadHolders is used to remove all the dead lock holders func (s *Semaphore) pruneDeadHolders(lock *semaphoreLock, pairs KVPairs) { // Gather all the live holders alive := make(map[string]struct{}, len(pairs)) for _, pair := range pairs { if pair.Session != "" { alive[pair.Session] = struct{}{} } } // Remove any holders that are dead for holder := range lock.Holders { if _, ok := alive[holder]; !ok { delete(lock.Holders, holder) } } } // monitorLock is a long running routine to monitor a semaphore ownership // It closes the stopCh if we lose our slot. func (s *Semaphore) monitorLock(session string, stopCh chan struct{}) { defer close(stopCh) kv := s.c.KV() opts := &QueryOptions{RequireConsistent: true} WAIT: retries := s.opts.MonitorRetries RETRY: pairs, meta, err := kv.List(s.opts.Prefix, opts) if err != nil { // If configured we can try to ride out a brief Consul unavailability // by doing retries. Note that we have to attempt the retry in a non- // blocking fashion so that we have a clean place to reset the retry // counter if service is restored. if retries > 0 && IsRetryableError(err) { time.Sleep(s.opts.MonitorRetryTime) retries-- opts.WaitIndex = 0 goto RETRY } return } lockPair := s.findLock(pairs) lock, err := s.decodeLock(lockPair) if err != nil { return } s.pruneDeadHolders(lock, pairs) if _, ok := lock.Holders[session]; ok { opts.WaitIndex = meta.LastIndex goto WAIT } }
vendor/github.com/hashicorp/consul/api/semaphore.go
0
https://github.com/hashicorp/terraform/commit/d6a586709cf8eee53b46b56bcf00fa7fa44d6441
[ 0.0013380693271756172, 0.00028799346182495356, 0.0001644627918722108, 0.00020857671916019171, 0.00021632740390487015 ]
{ "id": 1, "code_window": [ "\tProvisionerLock *sync.Mutex\n", "\tChangesValue *plans.ChangesSync\n", "\tStateValue *states.SyncState\n", "\tInstanceExpanderValue *instances.Expander\n", "}\n", "\n", "// BuiltinEvalContext implements EvalContext\n", "var _ EvalContext = (*BuiltinEvalContext)(nil)\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tRefreshStateValue *states.SyncState\n" ], "file_path": "terraform/eval_context_builtin.go", "type": "add", "edit_start_line_idx": 73 }
package terraform import ( "github.com/hashicorp/hcl/v2" "github.com/hashicorp/hcl/v2/hcldec" "github.com/hashicorp/terraform/addrs" "github.com/hashicorp/terraform/configs/configschema" "github.com/hashicorp/terraform/instances" "github.com/hashicorp/terraform/lang" "github.com/hashicorp/terraform/plans" "github.com/hashicorp/terraform/providers" "github.com/hashicorp/terraform/provisioners" "github.com/hashicorp/terraform/states" "github.com/hashicorp/terraform/tfdiags" "github.com/zclconf/go-cty/cty" "github.com/zclconf/go-cty/cty/convert" ) // MockEvalContext is a mock version of EvalContext that can be used // for tests. type MockEvalContext struct { StoppedCalled bool StoppedValue <-chan struct{} HookCalled bool HookHook Hook HookError error InputCalled bool InputInput UIInput InitProviderCalled bool InitProviderType string InitProviderAddr addrs.AbsProviderConfig InitProviderProvider providers.Interface InitProviderError error ProviderCalled bool ProviderAddr addrs.AbsProviderConfig ProviderProvider providers.Interface ProviderSchemaCalled bool ProviderSchemaAddr addrs.AbsProviderConfig ProviderSchemaSchema *ProviderSchema CloseProviderCalled bool CloseProviderAddr addrs.AbsProviderConfig CloseProviderProvider providers.Interface ProviderInputCalled bool ProviderInputAddr addrs.AbsProviderConfig ProviderInputValues map[string]cty.Value SetProviderInputCalled bool SetProviderInputAddr addrs.AbsProviderConfig SetProviderInputValues map[string]cty.Value ConfigureProviderCalled bool ConfigureProviderAddr addrs.AbsProviderConfig ConfigureProviderConfig cty.Value ConfigureProviderDiags tfdiags.Diagnostics InitProvisionerCalled bool InitProvisionerName string InitProvisionerProvisioner provisioners.Interface InitProvisionerError error ProvisionerCalled bool ProvisionerName string ProvisionerProvisioner provisioners.Interface ProvisionerSchemaCalled bool ProvisionerSchemaName string ProvisionerSchemaSchema *configschema.Block CloseProvisionerCalled bool CloseProvisionerName string CloseProvisionerProvisioner provisioners.Interface EvaluateBlockCalled bool EvaluateBlockBody hcl.Body EvaluateBlockSchema *configschema.Block EvaluateBlockSelf addrs.Referenceable EvaluateBlockKeyData InstanceKeyEvalData EvaluateBlockResultFunc func( body hcl.Body, schema *configschema.Block, self addrs.Referenceable, keyData InstanceKeyEvalData, ) (cty.Value, hcl.Body, tfdiags.Diagnostics) // overrides the other values below, if set EvaluateBlockResult cty.Value EvaluateBlockExpandedBody hcl.Body EvaluateBlockDiags tfdiags.Diagnostics EvaluateExprCalled bool EvaluateExprExpr hcl.Expression EvaluateExprWantType cty.Type EvaluateExprSelf addrs.Referenceable EvaluateExprResultFunc func( expr hcl.Expression, wantType cty.Type, self addrs.Referenceable, ) (cty.Value, tfdiags.Diagnostics) // overrides the other values below, if set EvaluateExprResult cty.Value EvaluateExprDiags tfdiags.Diagnostics EvaluationScopeCalled bool EvaluationScopeSelf addrs.Referenceable EvaluationScopeKeyData InstanceKeyEvalData EvaluationScopeScope *lang.Scope PathCalled bool PathPath addrs.ModuleInstance SetModuleCallArgumentsCalled bool SetModuleCallArgumentsModule addrs.ModuleCallInstance SetModuleCallArgumentsValues map[string]cty.Value GetVariableValueCalled bool GetVariableValueAddr addrs.AbsInputVariableInstance GetVariableValueValue cty.Value ChangesCalled bool ChangesChanges *plans.ChangesSync StateCalled bool StateState *states.SyncState InstanceExpanderCalled bool InstanceExpanderExpander *instances.Expander } // MockEvalContext implements EvalContext var _ EvalContext = (*MockEvalContext)(nil) func (c *MockEvalContext) Stopped() <-chan struct{} { c.StoppedCalled = true return c.StoppedValue } func (c *MockEvalContext) Hook(fn func(Hook) (HookAction, error)) error { c.HookCalled = true if c.HookHook != nil { if _, err := fn(c.HookHook); err != nil { return err } } return c.HookError } func (c *MockEvalContext) Input() UIInput { c.InputCalled = true return c.InputInput } func (c *MockEvalContext) InitProvider(addr addrs.AbsProviderConfig) (providers.Interface, error) { c.InitProviderCalled = true c.InitProviderType = addr.String() c.InitProviderAddr = addr return c.InitProviderProvider, c.InitProviderError } func (c *MockEvalContext) Provider(addr addrs.AbsProviderConfig) providers.Interface { c.ProviderCalled = true c.ProviderAddr = addr return c.ProviderProvider } func (c *MockEvalContext) ProviderSchema(addr addrs.AbsProviderConfig) *ProviderSchema { c.ProviderSchemaCalled = true c.ProviderSchemaAddr = addr return c.ProviderSchemaSchema } func (c *MockEvalContext) CloseProvider(addr addrs.AbsProviderConfig) error { c.CloseProviderCalled = true c.CloseProviderAddr = addr return nil } func (c *MockEvalContext) ConfigureProvider(addr addrs.AbsProviderConfig, cfg cty.Value) tfdiags.Diagnostics { c.ConfigureProviderCalled = true c.ConfigureProviderAddr = addr c.ConfigureProviderConfig = cfg return c.ConfigureProviderDiags } func (c *MockEvalContext) ProviderInput(addr addrs.AbsProviderConfig) map[string]cty.Value { c.ProviderInputCalled = true c.ProviderInputAddr = addr return c.ProviderInputValues } func (c *MockEvalContext) SetProviderInput(addr addrs.AbsProviderConfig, vals map[string]cty.Value) { c.SetProviderInputCalled = true c.SetProviderInputAddr = addr c.SetProviderInputValues = vals } func (c *MockEvalContext) InitProvisioner(n string) error { c.InitProvisionerCalled = true c.InitProvisionerName = n return c.InitProvisionerError } func (c *MockEvalContext) Provisioner(n string) provisioners.Interface { c.ProvisionerCalled = true c.ProvisionerName = n return c.ProvisionerProvisioner } func (c *MockEvalContext) ProvisionerSchema(n string) *configschema.Block { c.ProvisionerSchemaCalled = true c.ProvisionerSchemaName = n return c.ProvisionerSchemaSchema } func (c *MockEvalContext) CloseProvisioner(n string) error { c.CloseProvisionerCalled = true c.CloseProvisionerName = n return nil } func (c *MockEvalContext) EvaluateBlock(body hcl.Body, schema *configschema.Block, self addrs.Referenceable, keyData InstanceKeyEvalData) (cty.Value, hcl.Body, tfdiags.Diagnostics) { c.EvaluateBlockCalled = true c.EvaluateBlockBody = body c.EvaluateBlockSchema = schema c.EvaluateBlockSelf = self c.EvaluateBlockKeyData = keyData if c.EvaluateBlockResultFunc != nil { return c.EvaluateBlockResultFunc(body, schema, self, keyData) } return c.EvaluateBlockResult, c.EvaluateBlockExpandedBody, c.EvaluateBlockDiags } func (c *MockEvalContext) EvaluateExpr(expr hcl.Expression, wantType cty.Type, self addrs.Referenceable) (cty.Value, tfdiags.Diagnostics) { c.EvaluateExprCalled = true c.EvaluateExprExpr = expr c.EvaluateExprWantType = wantType c.EvaluateExprSelf = self if c.EvaluateExprResultFunc != nil { return c.EvaluateExprResultFunc(expr, wantType, self) } return c.EvaluateExprResult, c.EvaluateExprDiags } // installSimpleEval is a helper to install a simple mock implementation of // both EvaluateBlock and EvaluateExpr into the receiver. // // These default implementations will either evaluate the given input against // the scope in field EvaluationScopeScope or, if it is nil, with no eval // context at all so that only constant values may be used. // // This function overwrites any existing functions installed in fields // EvaluateBlockResultFunc and EvaluateExprResultFunc. func (c *MockEvalContext) installSimpleEval() { c.EvaluateBlockResultFunc = func(body hcl.Body, schema *configschema.Block, self addrs.Referenceable, keyData InstanceKeyEvalData) (cty.Value, hcl.Body, tfdiags.Diagnostics) { if scope := c.EvaluationScopeScope; scope != nil { // Fully-functional codepath. var diags tfdiags.Diagnostics body, diags = scope.ExpandBlock(body, schema) if diags.HasErrors() { return cty.DynamicVal, body, diags } val, evalDiags := c.EvaluationScopeScope.EvalBlock(body, schema) diags = diags.Append(evalDiags) if evalDiags.HasErrors() { return cty.DynamicVal, body, diags } return val, body, diags } // Fallback codepath supporting constant values only. val, hclDiags := hcldec.Decode(body, schema.DecoderSpec(), nil) return val, body, tfdiags.Diagnostics(nil).Append(hclDiags) } c.EvaluateExprResultFunc = func(expr hcl.Expression, wantType cty.Type, self addrs.Referenceable) (cty.Value, tfdiags.Diagnostics) { if scope := c.EvaluationScopeScope; scope != nil { // Fully-functional codepath. return scope.EvalExpr(expr, wantType) } // Fallback codepath supporting constant values only. var diags tfdiags.Diagnostics val, hclDiags := expr.Value(nil) diags = diags.Append(hclDiags) if hclDiags.HasErrors() { return cty.DynamicVal, diags } var err error val, err = convert.Convert(val, wantType) if err != nil { diags = diags.Append(err) return cty.DynamicVal, diags } return val, diags } } func (c *MockEvalContext) EvaluationScope(self addrs.Referenceable, keyData InstanceKeyEvalData) *lang.Scope { c.EvaluationScopeCalled = true c.EvaluationScopeSelf = self c.EvaluationScopeKeyData = keyData return c.EvaluationScopeScope } func (c *MockEvalContext) WithPath(path addrs.ModuleInstance) EvalContext { newC := *c newC.PathPath = path return &newC } func (c *MockEvalContext) Path() addrs.ModuleInstance { c.PathCalled = true return c.PathPath } func (c *MockEvalContext) SetModuleCallArguments(n addrs.ModuleCallInstance, values map[string]cty.Value) { c.SetModuleCallArgumentsCalled = true c.SetModuleCallArgumentsModule = n c.SetModuleCallArgumentsValues = values } func (c *MockEvalContext) GetVariableValue(addr addrs.AbsInputVariableInstance) cty.Value { c.GetVariableValueCalled = true c.GetVariableValueAddr = addr return c.GetVariableValueValue } func (c *MockEvalContext) Changes() *plans.ChangesSync { c.ChangesCalled = true return c.ChangesChanges } func (c *MockEvalContext) State() *states.SyncState { c.StateCalled = true return c.StateState } func (c *MockEvalContext) InstanceExpander() *instances.Expander { c.InstanceExpanderCalled = true return c.InstanceExpanderExpander }
terraform/eval_context_mock.go
1
https://github.com/hashicorp/terraform/commit/d6a586709cf8eee53b46b56bcf00fa7fa44d6441
[ 0.7416344285011292, 0.02281353250145912, 0.00016742605657782406, 0.0003457686980254948, 0.12332039326429367 ]
{ "id": 1, "code_window": [ "\tProvisionerLock *sync.Mutex\n", "\tChangesValue *plans.ChangesSync\n", "\tStateValue *states.SyncState\n", "\tInstanceExpanderValue *instances.Expander\n", "}\n", "\n", "// BuiltinEvalContext implements EvalContext\n", "var _ EvalContext = (*BuiltinEvalContext)(nil)\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tRefreshStateValue *states.SyncState\n" ], "file_path": "terraform/eval_context_builtin.go", "type": "add", "edit_start_line_idx": 73 }
// Package token defines constants representing the lexical tokens for HCL // (HashiCorp Configuration Language) package token import ( "fmt" "strconv" "strings" hclstrconv "github.com/hashicorp/hcl/hcl/strconv" ) // Token defines a single HCL token which can be obtained via the Scanner type Token struct { Type Type Pos Pos Text string JSON bool } // Type is the set of lexical tokens of the HCL (HashiCorp Configuration Language) type Type int const ( // Special tokens ILLEGAL Type = iota EOF COMMENT identifier_beg IDENT // literals literal_beg NUMBER // 12345 FLOAT // 123.45 BOOL // true,false STRING // "abc" HEREDOC // <<FOO\nbar\nFOO literal_end identifier_end operator_beg LBRACK // [ LBRACE // { COMMA // , PERIOD // . RBRACK // ] RBRACE // } ASSIGN // = ADD // + SUB // - operator_end ) var tokens = [...]string{ ILLEGAL: "ILLEGAL", EOF: "EOF", COMMENT: "COMMENT", IDENT: "IDENT", NUMBER: "NUMBER", FLOAT: "FLOAT", BOOL: "BOOL", STRING: "STRING", LBRACK: "LBRACK", LBRACE: "LBRACE", COMMA: "COMMA", PERIOD: "PERIOD", HEREDOC: "HEREDOC", RBRACK: "RBRACK", RBRACE: "RBRACE", ASSIGN: "ASSIGN", ADD: "ADD", SUB: "SUB", } // String returns the string corresponding to the token tok. func (t Type) String() string { s := "" if 0 <= t && t < Type(len(tokens)) { s = tokens[t] } if s == "" { s = "token(" + strconv.Itoa(int(t)) + ")" } return s } // IsIdentifier returns true for tokens corresponding to identifiers and basic // type literals; it returns false otherwise. func (t Type) IsIdentifier() bool { return identifier_beg < t && t < identifier_end } // IsLiteral returns true for tokens corresponding to basic type literals; it // returns false otherwise. func (t Type) IsLiteral() bool { return literal_beg < t && t < literal_end } // IsOperator returns true for tokens corresponding to operators and // delimiters; it returns false otherwise. func (t Type) IsOperator() bool { return operator_beg < t && t < operator_end } // String returns the token's literal text. Note that this is only // applicable for certain token types, such as token.IDENT, // token.STRING, etc.. func (t Token) String() string { return fmt.Sprintf("%s %s %s", t.Pos.String(), t.Type.String(), t.Text) } // Value returns the properly typed value for this token. The type of // the returned interface{} is guaranteed based on the Type field. // // This can only be called for literal types. If it is called for any other // type, this will panic. func (t Token) Value() interface{} { switch t.Type { case BOOL: if t.Text == "true" { return true } else if t.Text == "false" { return false } panic("unknown bool value: " + t.Text) case FLOAT: v, err := strconv.ParseFloat(t.Text, 64) if err != nil { panic(err) } return float64(v) case NUMBER: v, err := strconv.ParseInt(t.Text, 0, 64) if err != nil { panic(err) } return int64(v) case IDENT: return t.Text case HEREDOC: return unindentHeredoc(t.Text) case STRING: // Determine the Unquote method to use. If it came from JSON, // then we need to use the built-in unquote since we have to // escape interpolations there. f := hclstrconv.Unquote if t.JSON { f = strconv.Unquote } // This case occurs if json null is used if t.Text == "" { return "" } v, err := f(t.Text) if err != nil { panic(fmt.Sprintf("unquote %s err: %s", t.Text, err)) } return v default: panic(fmt.Sprintf("unimplemented Value for type: %s", t.Type)) } } // unindentHeredoc returns the string content of a HEREDOC if it is started with << // and the content of a HEREDOC with the hanging indent removed if it is started with // a <<-, and the terminating line is at least as indented as the least indented line. func unindentHeredoc(heredoc string) string { // We need to find the end of the marker idx := strings.IndexByte(heredoc, '\n') if idx == -1 { panic("heredoc doesn't contain newline") } unindent := heredoc[2] == '-' // We can optimize if the heredoc isn't marked for indentation if !unindent { return string(heredoc[idx+1 : len(heredoc)-idx+1]) } // We need to unindent each line based on the indentation level of the marker lines := strings.Split(string(heredoc[idx+1:len(heredoc)-idx+2]), "\n") whitespacePrefix := lines[len(lines)-1] isIndented := true for _, v := range lines { if strings.HasPrefix(v, whitespacePrefix) { continue } isIndented = false break } // If all lines are not at least as indented as the terminating mark, return the // heredoc as is, but trim the leading space from the marker on the final line. if !isIndented { return strings.TrimRight(string(heredoc[idx+1:len(heredoc)-idx+1]), " \t") } unindentedLines := make([]string, len(lines)) for k, v := range lines { if k == len(lines)-1 { unindentedLines[k] = "" break } unindentedLines[k] = strings.TrimPrefix(v, whitespacePrefix) } return strings.Join(unindentedLines, "\n") }
vendor/github.com/hashicorp/hcl/hcl/token/token.go
0
https://github.com/hashicorp/terraform/commit/d6a586709cf8eee53b46b56bcf00fa7fa44d6441
[ 0.00017630329239182174, 0.00016924994997680187, 0.00016008935926947743, 0.00016850174870342016, 0.000004712228019343456 ]
{ "id": 1, "code_window": [ "\tProvisionerLock *sync.Mutex\n", "\tChangesValue *plans.ChangesSync\n", "\tStateValue *states.SyncState\n", "\tInstanceExpanderValue *instances.Expander\n", "}\n", "\n", "// BuiltinEvalContext implements EvalContext\n", "var _ EvalContext = (*BuiltinEvalContext)(nil)\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tRefreshStateValue *states.SyncState\n" ], "file_path": "terraform/eval_context_builtin.go", "type": "add", "edit_start_line_idx": 73 }
// Copyright 2016 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "encoding/binary" ) // NewUUID returns a Version 1 UUID based on the current NodeID and clock // sequence, and the current time. If the NodeID has not been set by SetNodeID // or SetNodeInterface then it will be set automatically. If the NodeID cannot // be set NewUUID returns nil. If clock sequence has not been set by // SetClockSequence then it will be set automatically. If GetTime fails to // return the current NewUUID returns nil and an error. // // In most cases, New should be used. func NewUUID() (UUID, error) { nodeMu.Lock() if nodeID == zeroID { setNodeInterface("") } nodeMu.Unlock() var uuid UUID now, seq, err := GetTime() if err != nil { return uuid, err } timeLow := uint32(now & 0xffffffff) timeMid := uint16((now >> 32) & 0xffff) timeHi := uint16((now >> 48) & 0x0fff) timeHi |= 0x1000 // Version 1 binary.BigEndian.PutUint32(uuid[0:], timeLow) binary.BigEndian.PutUint16(uuid[4:], timeMid) binary.BigEndian.PutUint16(uuid[6:], timeHi) binary.BigEndian.PutUint16(uuid[8:], seq) copy(uuid[10:], nodeID[:]) return uuid, nil }
vendor/github.com/google/uuid/version1.go
0
https://github.com/hashicorp/terraform/commit/d6a586709cf8eee53b46b56bcf00fa7fa44d6441
[ 0.00017742915952112526, 0.000173190186615102, 0.00016572528693359345, 0.0001748781796777621, 0.000004065717803314328 ]
{ "id": 1, "code_window": [ "\tProvisionerLock *sync.Mutex\n", "\tChangesValue *plans.ChangesSync\n", "\tStateValue *states.SyncState\n", "\tInstanceExpanderValue *instances.Expander\n", "}\n", "\n", "// BuiltinEvalContext implements EvalContext\n", "var _ EvalContext = (*BuiltinEvalContext)(nil)\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tRefreshStateValue *states.SyncState\n" ], "file_path": "terraform/eval_context_builtin.go", "type": "add", "edit_start_line_idx": 73 }
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: k8s.io/kubernetes/vendor/k8s.io/api/authentication/v1beta1/generated.proto /* Package v1beta1 is a generated protocol buffer package. It is generated from these files: k8s.io/kubernetes/vendor/k8s.io/api/authentication/v1beta1/generated.proto It has these top-level messages: ExtraValue TokenReview TokenReviewSpec TokenReviewStatus UserInfo */ package v1beta1 import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" import github_com_gogo_protobuf_sortkeys "github.com/gogo/protobuf/sortkeys" import strings "strings" import reflect "reflect" import io "io" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package func (m *ExtraValue) Reset() { *m = ExtraValue{} } func (*ExtraValue) ProtoMessage() {} func (*ExtraValue) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{0} } func (m *TokenReview) Reset() { *m = TokenReview{} } func (*TokenReview) ProtoMessage() {} func (*TokenReview) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{1} } func (m *TokenReviewSpec) Reset() { *m = TokenReviewSpec{} } func (*TokenReviewSpec) ProtoMessage() {} func (*TokenReviewSpec) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{2} } func (m *TokenReviewStatus) Reset() { *m = TokenReviewStatus{} } func (*TokenReviewStatus) ProtoMessage() {} func (*TokenReviewStatus) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{3} } func (m *UserInfo) Reset() { *m = UserInfo{} } func (*UserInfo) ProtoMessage() {} func (*UserInfo) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{4} } func init() { proto.RegisterType((*ExtraValue)(nil), "k8s.io.api.authentication.v1beta1.ExtraValue") proto.RegisterType((*TokenReview)(nil), "k8s.io.api.authentication.v1beta1.TokenReview") proto.RegisterType((*TokenReviewSpec)(nil), "k8s.io.api.authentication.v1beta1.TokenReviewSpec") proto.RegisterType((*TokenReviewStatus)(nil), "k8s.io.api.authentication.v1beta1.TokenReviewStatus") proto.RegisterType((*UserInfo)(nil), "k8s.io.api.authentication.v1beta1.UserInfo") } func (m ExtraValue) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m ExtraValue) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l if len(m) > 0 { for _, s := range m { dAtA[i] = 0xa i++ l = len(s) for l >= 1<<7 { dAtA[i] = uint8(uint64(l)&0x7f | 0x80) l >>= 7 i++ } dAtA[i] = uint8(l) i++ i += copy(dAtA[i:], s) } } return i, nil } func (m *TokenReview) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *TokenReview) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l dAtA[i] = 0xa i++ i = encodeVarintGenerated(dAtA, i, uint64(m.ObjectMeta.Size())) n1, err := m.ObjectMeta.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n1 dAtA[i] = 0x12 i++ i = encodeVarintGenerated(dAtA, i, uint64(m.Spec.Size())) n2, err := m.Spec.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n2 dAtA[i] = 0x1a i++ i = encodeVarintGenerated(dAtA, i, uint64(m.Status.Size())) n3, err := m.Status.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n3 return i, nil } func (m *TokenReviewSpec) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *TokenReviewSpec) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l dAtA[i] = 0xa i++ i = encodeVarintGenerated(dAtA, i, uint64(len(m.Token))) i += copy(dAtA[i:], m.Token) if len(m.Audiences) > 0 { for _, s := range m.Audiences { dAtA[i] = 0x12 i++ l = len(s) for l >= 1<<7 { dAtA[i] = uint8(uint64(l)&0x7f | 0x80) l >>= 7 i++ } dAtA[i] = uint8(l) i++ i += copy(dAtA[i:], s) } } return i, nil } func (m *TokenReviewStatus) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *TokenReviewStatus) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l dAtA[i] = 0x8 i++ if m.Authenticated { dAtA[i] = 1 } else { dAtA[i] = 0 } i++ dAtA[i] = 0x12 i++ i = encodeVarintGenerated(dAtA, i, uint64(m.User.Size())) n4, err := m.User.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n4 dAtA[i] = 0x1a i++ i = encodeVarintGenerated(dAtA, i, uint64(len(m.Error))) i += copy(dAtA[i:], m.Error) if len(m.Audiences) > 0 { for _, s := range m.Audiences { dAtA[i] = 0x22 i++ l = len(s) for l >= 1<<7 { dAtA[i] = uint8(uint64(l)&0x7f | 0x80) l >>= 7 i++ } dAtA[i] = uint8(l) i++ i += copy(dAtA[i:], s) } } return i, nil } func (m *UserInfo) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *UserInfo) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l dAtA[i] = 0xa i++ i = encodeVarintGenerated(dAtA, i, uint64(len(m.Username))) i += copy(dAtA[i:], m.Username) dAtA[i] = 0x12 i++ i = encodeVarintGenerated(dAtA, i, uint64(len(m.UID))) i += copy(dAtA[i:], m.UID) if len(m.Groups) > 0 { for _, s := range m.Groups { dAtA[i] = 0x1a i++ l = len(s) for l >= 1<<7 { dAtA[i] = uint8(uint64(l)&0x7f | 0x80) l >>= 7 i++ } dAtA[i] = uint8(l) i++ i += copy(dAtA[i:], s) } } if len(m.Extra) > 0 { keysForExtra := make([]string, 0, len(m.Extra)) for k := range m.Extra { keysForExtra = append(keysForExtra, string(k)) } github_com_gogo_protobuf_sortkeys.Strings(keysForExtra) for _, k := range keysForExtra { dAtA[i] = 0x22 i++ v := m.Extra[string(k)] msgSize := 0 if (&v) != nil { msgSize = (&v).Size() msgSize += 1 + sovGenerated(uint64(msgSize)) } mapSize := 1 + len(k) + sovGenerated(uint64(len(k))) + msgSize i = encodeVarintGenerated(dAtA, i, uint64(mapSize)) dAtA[i] = 0xa i++ i = encodeVarintGenerated(dAtA, i, uint64(len(k))) i += copy(dAtA[i:], k) dAtA[i] = 0x12 i++ i = encodeVarintGenerated(dAtA, i, uint64((&v).Size())) n5, err := (&v).MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n5 } } return i, nil } func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return offset + 1 } func (m ExtraValue) Size() (n int) { var l int _ = l if len(m) > 0 { for _, s := range m { l = len(s) n += 1 + l + sovGenerated(uint64(l)) } } return n } func (m *TokenReview) Size() (n int) { var l int _ = l l = m.ObjectMeta.Size() n += 1 + l + sovGenerated(uint64(l)) l = m.Spec.Size() n += 1 + l + sovGenerated(uint64(l)) l = m.Status.Size() n += 1 + l + sovGenerated(uint64(l)) return n } func (m *TokenReviewSpec) Size() (n int) { var l int _ = l l = len(m.Token) n += 1 + l + sovGenerated(uint64(l)) if len(m.Audiences) > 0 { for _, s := range m.Audiences { l = len(s) n += 1 + l + sovGenerated(uint64(l)) } } return n } func (m *TokenReviewStatus) Size() (n int) { var l int _ = l n += 2 l = m.User.Size() n += 1 + l + sovGenerated(uint64(l)) l = len(m.Error) n += 1 + l + sovGenerated(uint64(l)) if len(m.Audiences) > 0 { for _, s := range m.Audiences { l = len(s) n += 1 + l + sovGenerated(uint64(l)) } } return n } func (m *UserInfo) Size() (n int) { var l int _ = l l = len(m.Username) n += 1 + l + sovGenerated(uint64(l)) l = len(m.UID) n += 1 + l + sovGenerated(uint64(l)) if len(m.Groups) > 0 { for _, s := range m.Groups { l = len(s) n += 1 + l + sovGenerated(uint64(l)) } } if len(m.Extra) > 0 { for k, v := range m.Extra { _ = k _ = v l = v.Size() mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + l + sovGenerated(uint64(l)) n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) } } return n } func sovGenerated(x uint64) (n int) { for { n++ x >>= 7 if x == 0 { break } } return n } func sozGenerated(x uint64) (n int) { return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (this *TokenReview) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&TokenReview{`, `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_apimachinery_pkg_apis_meta_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "TokenReviewSpec", "TokenReviewSpec", 1), `&`, ``, 1) + `,`, `Status:` + strings.Replace(strings.Replace(this.Status.String(), "TokenReviewStatus", "TokenReviewStatus", 1), `&`, ``, 1) + `,`, `}`, }, "") return s } func (this *TokenReviewSpec) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&TokenReviewSpec{`, `Token:` + fmt.Sprintf("%v", this.Token) + `,`, `Audiences:` + fmt.Sprintf("%v", this.Audiences) + `,`, `}`, }, "") return s } func (this *TokenReviewStatus) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&TokenReviewStatus{`, `Authenticated:` + fmt.Sprintf("%v", this.Authenticated) + `,`, `User:` + strings.Replace(strings.Replace(this.User.String(), "UserInfo", "UserInfo", 1), `&`, ``, 1) + `,`, `Error:` + fmt.Sprintf("%v", this.Error) + `,`, `Audiences:` + fmt.Sprintf("%v", this.Audiences) + `,`, `}`, }, "") return s } func (this *UserInfo) String() string { if this == nil { return "nil" } keysForExtra := make([]string, 0, len(this.Extra)) for k := range this.Extra { keysForExtra = append(keysForExtra, k) } github_com_gogo_protobuf_sortkeys.Strings(keysForExtra) mapStringForExtra := "map[string]ExtraValue{" for _, k := range keysForExtra { mapStringForExtra += fmt.Sprintf("%v: %v,", k, this.Extra[k]) } mapStringForExtra += "}" s := strings.Join([]string{`&UserInfo{`, `Username:` + fmt.Sprintf("%v", this.Username) + `,`, `UID:` + fmt.Sprintf("%v", this.UID) + `,`, `Groups:` + fmt.Sprintf("%v", this.Groups) + `,`, `Extra:` + mapStringForExtra + `,`, `}`, }, "") return s } func valueToStringGenerated(v interface{}) string { rv := reflect.ValueOf(v) if rv.IsNil() { return "nil" } pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("*%v", pv) } func (m *ExtraValue) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: ExtraValue: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: ExtraValue: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } *m = append(*m, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *TokenReview) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: TokenReview: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: TokenReview: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *TokenReviewSpec) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: TokenReviewSpec: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: TokenReviewSpec: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Token", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.Token = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Audiences", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.Audiences = append(m.Audiences, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *TokenReviewStatus) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: TokenReviewStatus: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: TokenReviewStatus: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Authenticated", wireType) } var v int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (int(b) & 0x7F) << shift if b < 0x80 { break } } m.Authenticated = bool(v != 0) case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field User", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := m.User.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.Error = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Audiences", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.Audiences = append(m.Audiences, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *UserInfo) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: UserInfo: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: UserInfo: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Username", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.Username = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field UID", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.UID = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Groups", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.Groups = append(m.Groups, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Extra", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if m.Extra == nil { m.Extra = make(map[string]ExtraValue) } var mapkey string mapvalue := &ExtraValue{} for iNdEx < postIndex { entryPreIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) if fieldNum == 1 { var stringLenmapkey uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLenmapkey |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLenmapkey := int(stringLenmapkey) if intStringLenmapkey < 0 { return ErrInvalidLengthGenerated } postStringIndexmapkey := iNdEx + intStringLenmapkey if postStringIndexmapkey > l { return io.ErrUnexpectedEOF } mapkey = string(dAtA[iNdEx:postStringIndexmapkey]) iNdEx = postStringIndexmapkey } else if fieldNum == 2 { var mapmsglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ mapmsglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if mapmsglen < 0 { return ErrInvalidLengthGenerated } postmsgIndex := iNdEx + mapmsglen if mapmsglen < 0 { return ErrInvalidLengthGenerated } if postmsgIndex > l { return io.ErrUnexpectedEOF } mapvalue = &ExtraValue{} if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { return err } iNdEx = postmsgIndex } else { iNdEx = entryPreIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > postIndex { return io.ErrUnexpectedEOF } iNdEx += skippy } } m.Extra[mapkey] = *mapvalue iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipGenerated(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } return iNdEx, nil case 1: iNdEx += 8 return iNdEx, nil case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } iNdEx += length if length < 0 { return 0, ErrInvalidLengthGenerated } return iNdEx, nil case 3: for { var innerWire uint64 var start int = iNdEx for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ innerWire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } innerWireType := int(innerWire & 0x7) if innerWireType == 4 { break } next, err := skipGenerated(dAtA[start:]) if err != nil { return 0, err } iNdEx = start + next } return iNdEx, nil case 4: return iNdEx, nil case 5: iNdEx += 4 return iNdEx, nil default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } } panic("unreachable") } var ( ErrInvalidLengthGenerated = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowGenerated = fmt.Errorf("proto: integer overflow") ) func init() { proto.RegisterFile("k8s.io/kubernetes/vendor/k8s.io/api/authentication/v1beta1/generated.proto", fileDescriptorGenerated) } var fileDescriptorGenerated = []byte{ // 663 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x53, 0xcd, 0x4e, 0x14, 0x4d, 0x14, 0xed, 0x9e, 0x1f, 0xbe, 0x99, 0x9a, 0x6f, 0x14, 0x2b, 0x31, 0x99, 0x4c, 0x62, 0x0f, 0x8e, 0x1b, 0x12, 0xa4, 0x5a, 0x08, 0x41, 0x82, 0x2b, 0x5a, 0x89, 0xc1, 0x84, 0x98, 0x94, 0xe0, 0x42, 0x5d, 0x58, 0xd3, 0x73, 0xe9, 0x69, 0xc7, 0xfe, 0x49, 0x55, 0xf5, 0x28, 0x3b, 0x1e, 0xc1, 0xa5, 0x4b, 0x13, 0x9f, 0xc4, 0x1d, 0x4b, 0x96, 0x2c, 0xcc, 0x44, 0xda, 0x27, 0xf0, 0x0d, 0x4c, 0x55, 0x17, 0xcc, 0x00, 0x31, 0xc0, 0xae, 0xeb, 0xdc, 0x7b, 0xce, 0x3d, 0xf7, 0x54, 0x17, 0x7a, 0x31, 0x5c, 0x13, 0x24, 0x4c, 0xdc, 0x61, 0xd6, 0x03, 0x1e, 0x83, 0x04, 0xe1, 0x8e, 0x20, 0xee, 0x27, 0xdc, 0x35, 0x05, 0x96, 0x86, 0x2e, 0xcb, 0xe4, 0x00, 0x62, 0x19, 0xfa, 0x4c, 0x86, 0x49, 0xec, 0x8e, 0x96, 0x7a, 0x20, 0xd9, 0x92, 0x1b, 0x40, 0x0c, 0x9c, 0x49, 0xe8, 0x93, 0x94, 0x27, 0x32, 0xc1, 0xf7, 0x0b, 0x0a, 0x61, 0x69, 0x48, 0xce, 0x53, 0x88, 0xa1, 0xb4, 0x17, 0x83, 0x50, 0x0e, 0xb2, 0x1e, 0xf1, 0x93, 0xc8, 0x0d, 0x92, 0x20, 0x71, 0x35, 0xb3, 0x97, 0xed, 0xe9, 0x93, 0x3e, 0xe8, 0xaf, 0x42, 0xb1, 0xbd, 0x32, 0x31, 0x11, 0x31, 0x7f, 0x10, 0xc6, 0xc0, 0xf7, 0xdd, 0x74, 0x18, 0x28, 0x40, 0xb8, 0x11, 0x48, 0xe6, 0x8e, 0x2e, 0xf9, 0x68, 0xbb, 0xff, 0x62, 0xf1, 0x2c, 0x96, 0x61, 0x04, 0x97, 0x08, 0xab, 0x57, 0x11, 0x84, 0x3f, 0x80, 0x88, 0x5d, 0xe4, 0x75, 0x1f, 0x23, 0xb4, 0xf9, 0x59, 0x72, 0xf6, 0x9a, 0x7d, 0xcc, 0x00, 0x77, 0x50, 0x35, 0x94, 0x10, 0x89, 0x96, 0x3d, 0x57, 0x9e, 0xaf, 0x7b, 0xf5, 0x7c, 0xdc, 0xa9, 0x6e, 0x29, 0x80, 0x16, 0xf8, 0x7a, 0xed, 0xeb, 0xb7, 0x8e, 0x75, 0xf0, 0x73, 0xce, 0xea, 0x7e, 0x2f, 0xa1, 0xc6, 0x4e, 0x32, 0x84, 0x98, 0xc2, 0x28, 0x84, 0x4f, 0xf8, 0x3d, 0xaa, 0xa9, 0x65, 0xfa, 0x4c, 0xb2, 0x96, 0x3d, 0x67, 0xcf, 0x37, 0x96, 0x1f, 0x91, 0x49, 0x98, 0x67, 0x9e, 0x48, 0x3a, 0x0c, 0x14, 0x20, 0x88, 0xea, 0x26, 0xa3, 0x25, 0xf2, 0xb2, 0xf7, 0x01, 0x7c, 0xb9, 0x0d, 0x92, 0x79, 0xf8, 0x70, 0xdc, 0xb1, 0xf2, 0x71, 0x07, 0x4d, 0x30, 0x7a, 0xa6, 0x8a, 0x77, 0x50, 0x45, 0xa4, 0xe0, 0xb7, 0x4a, 0x5a, 0x7d, 0x99, 0x5c, 0x79, 0x55, 0x64, 0xca, 0xdf, 0xab, 0x14, 0x7c, 0xef, 0x7f, 0xa3, 0x5f, 0x51, 0x27, 0xaa, 0xd5, 0xf0, 0x3b, 0x34, 0x23, 0x24, 0x93, 0x99, 0x68, 0x95, 0xb5, 0xee, 0xca, 0x0d, 0x75, 0x35, 0xd7, 0xbb, 0x65, 0x94, 0x67, 0x8a, 0x33, 0x35, 0x9a, 0x5d, 0x1f, 0xdd, 0xbe, 0x60, 0x02, 0x3f, 0x40, 0x55, 0xa9, 0x20, 0x9d, 0x52, 0xdd, 0x6b, 0x1a, 0x66, 0xb5, 0xe8, 0x2b, 0x6a, 0x78, 0x01, 0xd5, 0x59, 0xd6, 0x0f, 0x21, 0xf6, 0x41, 0xb4, 0x4a, 0xfa, 0x32, 0x9a, 0xf9, 0xb8, 0x53, 0xdf, 0x38, 0x05, 0xe9, 0xa4, 0xde, 0xfd, 0x63, 0xa3, 0x3b, 0x97, 0x2c, 0xe1, 0x27, 0xa8, 0x39, 0x65, 0x1f, 0xfa, 0x7a, 0x5e, 0xcd, 0xbb, 0x6b, 0xe6, 0x35, 0x37, 0xa6, 0x8b, 0xf4, 0x7c, 0x2f, 0xde, 0x46, 0x95, 0x4c, 0x00, 0x37, 0x59, 0x2f, 0x5c, 0x23, 0x93, 0x5d, 0x01, 0x7c, 0x2b, 0xde, 0x4b, 0x26, 0x21, 0x2b, 0x84, 0x6a, 0x19, 0xb5, 0x33, 0x70, 0x9e, 0x70, 0x9d, 0xf1, 0xd4, 0xce, 0x9b, 0x0a, 0xa4, 0x45, 0xed, 0xfc, 0xce, 0x95, 0x2b, 0x76, 0xfe, 0x51, 0x42, 0xb5, 0xd3, 0x91, 0xf8, 0x21, 0xaa, 0xa9, 0x31, 0x31, 0x8b, 0xc0, 0xa4, 0x3a, 0x6b, 0x26, 0xe8, 0x1e, 0x85, 0xd3, 0xb3, 0x0e, 0x7c, 0x0f, 0x95, 0xb3, 0xb0, 0xaf, 0x57, 0xab, 0x7b, 0x0d, 0xd3, 0x58, 0xde, 0xdd, 0x7a, 0x46, 0x15, 0x8e, 0xbb, 0x68, 0x26, 0xe0, 0x49, 0x96, 0xaa, 0x1f, 0x42, 0x79, 0x40, 0xea, 0x5a, 0x9f, 0x6b, 0x84, 0x9a, 0x0a, 0x7e, 0x8b, 0xaa, 0xa0, 0x5e, 0x8d, 0xb6, 0xd9, 0x58, 0x5e, 0xbd, 0x41, 0x3e, 0x44, 0x3f, 0xb7, 0xcd, 0x58, 0xf2, 0xfd, 0xa9, 0x1c, 0x14, 0x46, 0x0b, 0xcd, 0x76, 0x60, 0x9e, 0xa4, 0xee, 0xc1, 0xb3, 0xa8, 0x3c, 0x84, 0xfd, 0x62, 0x2d, 0xaa, 0x3e, 0xf1, 0x53, 0x54, 0x1d, 0xa9, 0xd7, 0x6a, 0x2e, 0x67, 0xf1, 0x1a, 0xc3, 0x27, 0x4f, 0x9c, 0x16, 0xdc, 0xf5, 0xd2, 0x9a, 0xed, 0x2d, 0x1e, 0x9e, 0x38, 0xd6, 0xd1, 0x89, 0x63, 0x1d, 0x9f, 0x38, 0xd6, 0x41, 0xee, 0xd8, 0x87, 0xb9, 0x63, 0x1f, 0xe5, 0x8e, 0x7d, 0x9c, 0x3b, 0xf6, 0xaf, 0xdc, 0xb1, 0xbf, 0xfc, 0x76, 0xac, 0x37, 0xff, 0x19, 0x91, 0xbf, 0x01, 0x00, 0x00, 0xff, 0xff, 0xf7, 0xd6, 0x32, 0x28, 0x68, 0x05, 0x00, 0x00, }
vendor/k8s.io/api/authentication/v1beta1/generated.pb.go
0
https://github.com/hashicorp/terraform/commit/d6a586709cf8eee53b46b56bcf00fa7fa44d6441
[ 0.00018761359388008714, 0.0001722054003039375, 0.00016232929192483425, 0.00017279943858738989, 0.000003370803824509494 ]
{ "id": 2, "code_window": [ "\n", "func (ctx *BuiltinEvalContext) State() *states.SyncState {\n", "\treturn ctx.StateValue\n", "}\n", "\n", "func (ctx *BuiltinEvalContext) InstanceExpander() *instances.Expander {\n", "\treturn ctx.InstanceExpanderValue\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "func (ctx *BuiltinEvalContext) RefreshState() *states.SyncState {\n", "\treturn ctx.RefreshStateValue\n", "}\n", "\n" ], "file_path": "terraform/eval_context_builtin.go", "type": "add", "edit_start_line_idx": 352 }
package terraform import ( "context" "fmt" "log" "sync" "github.com/hashicorp/terraform/instances" "github.com/hashicorp/terraform/plans" "github.com/hashicorp/terraform/providers" "github.com/hashicorp/terraform/provisioners" "github.com/hashicorp/terraform/version" "github.com/hashicorp/terraform/states" "github.com/hashicorp/hcl/v2" "github.com/hashicorp/terraform/configs/configschema" "github.com/hashicorp/terraform/lang" "github.com/hashicorp/terraform/tfdiags" "github.com/hashicorp/terraform/addrs" "github.com/zclconf/go-cty/cty" ) // BuiltinEvalContext is an EvalContext implementation that is used by // Terraform by default. type BuiltinEvalContext struct { // StopContext is the context used to track whether we're complete StopContext context.Context // PathValue is the Path that this context is operating within. PathValue addrs.ModuleInstance // pathSet indicates that this context was explicitly created for a // specific path, and can be safely used for evaluation. This lets us // differentiate between PathValue being unset, and the zero value which is // equivalent to RootModuleInstance. Path and Evaluation methods will // panic if this is not set. pathSet bool // Evaluator is used for evaluating expressions within the scope of this // eval context. Evaluator *Evaluator // Schemas is a repository of all of the schemas we should need to // decode configuration blocks and expressions. This must be constructed by // the caller to include schemas for all of the providers, resource types, // data sources and provisioners used by the given configuration and // state. // // This must not be mutated during evaluation. Schemas *Schemas // VariableValues contains the variable values across all modules. This // structure is shared across the entire containing context, and so it // may be accessed only when holding VariableValuesLock. // The keys of the first level of VariableValues are the string // representations of addrs.ModuleInstance values. The second-level keys // are variable names within each module instance. VariableValues map[string]map[string]cty.Value VariableValuesLock *sync.Mutex Components contextComponentFactory Hooks []Hook InputValue UIInput ProviderCache map[string]providers.Interface ProviderInputConfig map[string]map[string]cty.Value ProviderLock *sync.Mutex ProvisionerCache map[string]provisioners.Interface ProvisionerLock *sync.Mutex ChangesValue *plans.ChangesSync StateValue *states.SyncState InstanceExpanderValue *instances.Expander } // BuiltinEvalContext implements EvalContext var _ EvalContext = (*BuiltinEvalContext)(nil) func (ctx *BuiltinEvalContext) WithPath(path addrs.ModuleInstance) EvalContext { ctx.pathSet = true newCtx := *ctx newCtx.PathValue = path return &newCtx } func (ctx *BuiltinEvalContext) Stopped() <-chan struct{} { // This can happen during tests. During tests, we just block forever. if ctx.StopContext == nil { return nil } return ctx.StopContext.Done() } func (ctx *BuiltinEvalContext) Hook(fn func(Hook) (HookAction, error)) error { for _, h := range ctx.Hooks { action, err := fn(h) if err != nil { return err } switch action { case HookActionContinue: continue case HookActionHalt: // Return an early exit error to trigger an early exit log.Printf("[WARN] Early exit triggered by hook: %T", h) return EvalEarlyExitError{} } } return nil } func (ctx *BuiltinEvalContext) Input() UIInput { return ctx.InputValue } func (ctx *BuiltinEvalContext) InitProvider(addr addrs.AbsProviderConfig) (providers.Interface, error) { // If we already initialized, it is an error if p := ctx.Provider(addr); p != nil { return nil, fmt.Errorf("%s is already initialized", addr) } // Warning: make sure to acquire these locks AFTER the call to Provider // above, since it also acquires locks. ctx.ProviderLock.Lock() defer ctx.ProviderLock.Unlock() key := addr.String() p, err := ctx.Components.ResourceProvider(addr.Provider) if err != nil { return nil, err } log.Printf("[TRACE] BuiltinEvalContext: Initialized %q provider for %s", addr.String(), addr) ctx.ProviderCache[key] = p return p, nil } func (ctx *BuiltinEvalContext) Provider(addr addrs.AbsProviderConfig) providers.Interface { ctx.ProviderLock.Lock() defer ctx.ProviderLock.Unlock() return ctx.ProviderCache[addr.String()] } func (ctx *BuiltinEvalContext) ProviderSchema(addr addrs.AbsProviderConfig) *ProviderSchema { return ctx.Schemas.ProviderSchema(addr.Provider) } func (ctx *BuiltinEvalContext) CloseProvider(addr addrs.AbsProviderConfig) error { ctx.ProviderLock.Lock() defer ctx.ProviderLock.Unlock() key := addr.String() provider := ctx.ProviderCache[key] if provider != nil { delete(ctx.ProviderCache, key) return provider.Close() } return nil } func (ctx *BuiltinEvalContext) ConfigureProvider(addr addrs.AbsProviderConfig, cfg cty.Value) tfdiags.Diagnostics { var diags tfdiags.Diagnostics if !addr.Module.Equal(ctx.Path().Module()) { // This indicates incorrect use of ConfigureProvider: it should be used // only from the module that the provider configuration belongs to. panic(fmt.Sprintf("%s configured by wrong module %s", addr, ctx.Path())) } p := ctx.Provider(addr) if p == nil { diags = diags.Append(fmt.Errorf("%s not initialized", addr)) return diags } providerSchema := ctx.ProviderSchema(addr) if providerSchema == nil { diags = diags.Append(fmt.Errorf("schema for %s is not available", addr)) return diags } req := providers.ConfigureRequest{ TerraformVersion: version.String(), Config: cfg, } resp := p.Configure(req) return resp.Diagnostics } func (ctx *BuiltinEvalContext) ProviderInput(pc addrs.AbsProviderConfig) map[string]cty.Value { ctx.ProviderLock.Lock() defer ctx.ProviderLock.Unlock() if !pc.Module.Equal(ctx.Path().Module()) { // This indicates incorrect use of InitProvider: it should be used // only from the module that the provider configuration belongs to. panic(fmt.Sprintf("%s initialized by wrong module %s", pc, ctx.Path())) } if !ctx.Path().IsRoot() { // Only root module provider configurations can have input. return nil } return ctx.ProviderInputConfig[pc.String()] } func (ctx *BuiltinEvalContext) SetProviderInput(pc addrs.AbsProviderConfig, c map[string]cty.Value) { absProvider := pc if !pc.Module.IsRoot() { // Only root module provider configurations can have input. log.Printf("[WARN] BuiltinEvalContext: attempt to SetProviderInput for non-root module") return } // Save the configuration ctx.ProviderLock.Lock() ctx.ProviderInputConfig[absProvider.String()] = c ctx.ProviderLock.Unlock() } func (ctx *BuiltinEvalContext) InitProvisioner(n string) error { // If we already initialized, it is an error if p := ctx.Provisioner(n); p != nil { return fmt.Errorf("Provisioner '%s' already initialized", n) } // Warning: make sure to acquire these locks AFTER the call to Provisioner // above, since it also acquires locks. ctx.ProvisionerLock.Lock() defer ctx.ProvisionerLock.Unlock() p, err := ctx.Components.ResourceProvisioner(n) if err != nil { return err } ctx.ProvisionerCache[n] = p return nil } func (ctx *BuiltinEvalContext) Provisioner(n string) provisioners.Interface { ctx.ProvisionerLock.Lock() defer ctx.ProvisionerLock.Unlock() return ctx.ProvisionerCache[n] } func (ctx *BuiltinEvalContext) ProvisionerSchema(n string) *configschema.Block { return ctx.Schemas.ProvisionerConfig(n) } func (ctx *BuiltinEvalContext) CloseProvisioner(n string) error { ctx.ProvisionerLock.Lock() defer ctx.ProvisionerLock.Unlock() prov := ctx.ProvisionerCache[n] if prov != nil { return prov.Close() } return nil } func (ctx *BuiltinEvalContext) EvaluateBlock(body hcl.Body, schema *configschema.Block, self addrs.Referenceable, keyData InstanceKeyEvalData) (cty.Value, hcl.Body, tfdiags.Diagnostics) { var diags tfdiags.Diagnostics scope := ctx.EvaluationScope(self, keyData) body, evalDiags := scope.ExpandBlock(body, schema) diags = diags.Append(evalDiags) val, evalDiags := scope.EvalBlock(body, schema) diags = diags.Append(evalDiags) return val, body, diags } func (ctx *BuiltinEvalContext) EvaluateExpr(expr hcl.Expression, wantType cty.Type, self addrs.Referenceable) (cty.Value, tfdiags.Diagnostics) { scope := ctx.EvaluationScope(self, EvalDataForNoInstanceKey) return scope.EvalExpr(expr, wantType) } func (ctx *BuiltinEvalContext) EvaluationScope(self addrs.Referenceable, keyData InstanceKeyEvalData) *lang.Scope { if !ctx.pathSet { panic("context path not set") } data := &evaluationStateData{ Evaluator: ctx.Evaluator, ModulePath: ctx.PathValue, InstanceKeyData: keyData, Operation: ctx.Evaluator.Operation, } return ctx.Evaluator.Scope(data, self) } func (ctx *BuiltinEvalContext) Path() addrs.ModuleInstance { if !ctx.pathSet { panic("context path not set") } return ctx.PathValue } func (ctx *BuiltinEvalContext) SetModuleCallArguments(n addrs.ModuleCallInstance, vals map[string]cty.Value) { ctx.VariableValuesLock.Lock() defer ctx.VariableValuesLock.Unlock() if !ctx.pathSet { panic("context path not set") } childPath := n.ModuleInstance(ctx.PathValue) key := childPath.String() args := ctx.VariableValues[key] if args == nil { args = make(map[string]cty.Value) ctx.VariableValues[key] = vals return } for k, v := range vals { args[k] = v } } func (ctx *BuiltinEvalContext) GetVariableValue(addr addrs.AbsInputVariableInstance) cty.Value { ctx.VariableValuesLock.Lock() defer ctx.VariableValuesLock.Unlock() modKey := addr.Module.String() modVars := ctx.VariableValues[modKey] val, ok := modVars[addr.Variable.Name] if !ok { return cty.DynamicVal } return val } func (ctx *BuiltinEvalContext) Changes() *plans.ChangesSync { return ctx.ChangesValue } func (ctx *BuiltinEvalContext) State() *states.SyncState { return ctx.StateValue } func (ctx *BuiltinEvalContext) InstanceExpander() *instances.Expander { return ctx.InstanceExpanderValue }
terraform/eval_context_builtin.go
1
https://github.com/hashicorp/terraform/commit/d6a586709cf8eee53b46b56bcf00fa7fa44d6441
[ 0.9700844287872314, 0.25779813528060913, 0.00016753720410633832, 0.024033887311816216, 0.3502471148967743 ]
{ "id": 2, "code_window": [ "\n", "func (ctx *BuiltinEvalContext) State() *states.SyncState {\n", "\treturn ctx.StateValue\n", "}\n", "\n", "func (ctx *BuiltinEvalContext) InstanceExpander() *instances.Expander {\n", "\treturn ctx.InstanceExpanderValue\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "func (ctx *BuiltinEvalContext) RefreshState() *states.SyncState {\n", "\treturn ctx.RefreshStateValue\n", "}\n", "\n" ], "file_path": "terraform/eval_context_builtin.go", "type": "add", "edit_start_line_idx": 352 }
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package sts import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/client/metadata" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/signer/v4" "github.com/aws/aws-sdk-go/private/protocol/query" ) // STS provides the API operation methods for making requests to // AWS Security Token Service. See this package's package overview docs // for details on the service. // // STS methods are safe to use concurrently. It is not safe to // modify mutate any of the struct's properties though. type STS struct { *client.Client } // Used for custom client initialization logic var initClient func(*client.Client) // Used for custom request initialization logic var initRequest func(*request.Request) // Service information constants const ( ServiceName = "sts" // Name of service. EndpointsID = ServiceName // ID to lookup a service endpoint with. ServiceID = "STS" // ServiceID is a unique identifier of a specific service. ) // New creates a new instance of the STS client with a session. // If additional configuration is needed for the client instance use the optional // aws.Config parameter to add your extra config. // // Example: // mySession := session.Must(session.NewSession()) // // // Create a STS client from just a session. // svc := sts.New(mySession) // // // Create a STS client with additional configuration // svc := sts.New(mySession, aws.NewConfig().WithRegion("us-west-2")) func New(p client.ConfigProvider, cfgs ...*aws.Config) *STS { c := p.ClientConfig(EndpointsID, cfgs...) return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName) } // newClient creates, initializes and returns a new service client instance. func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *STS { svc := &STS{ Client: client.New( cfg, metadata.ClientInfo{ ServiceName: ServiceName, ServiceID: ServiceID, SigningName: signingName, SigningRegion: signingRegion, PartitionID: partitionID, Endpoint: endpoint, APIVersion: "2011-06-15", }, handlers, ), } // Handlers svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) svc.Handlers.Build.PushBackNamed(query.BuildHandler) svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) // Run custom client initialization if present if initClient != nil { initClient(svc.Client) } return svc } // newRequest creates a new request for a STS operation and runs any // custom request initialization. func (c *STS) newRequest(op *request.Operation, params, data interface{}) *request.Request { req := c.NewRequest(op, params, data) // Run custom request initialization if present if initRequest != nil { initRequest(req) } return req }
vendor/github.com/aws/aws-sdk-go/service/sts/service.go
0
https://github.com/hashicorp/terraform/commit/d6a586709cf8eee53b46b56bcf00fa7fa44d6441
[ 0.0003655701584648341, 0.00019848791998811066, 0.00016813042748253793, 0.00017413057503290474, 0.00005775904355687089 ]
{ "id": 2, "code_window": [ "\n", "func (ctx *BuiltinEvalContext) State() *states.SyncState {\n", "\treturn ctx.StateValue\n", "}\n", "\n", "func (ctx *BuiltinEvalContext) InstanceExpander() *instances.Expander {\n", "\treturn ctx.InstanceExpanderValue\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "func (ctx *BuiltinEvalContext) RefreshState() *states.SyncState {\n", "\treturn ctx.RefreshStateValue\n", "}\n", "\n" ], "file_path": "terraform/eval_context_builtin.go", "type": "add", "edit_start_line_idx": 352 }
package jsoniter import ( "strconv" ) type int32Any struct { baseAny val int32 } func (any *int32Any) LastError() error { return nil } func (any *int32Any) ValueType() ValueType { return NumberValue } func (any *int32Any) MustBeValid() Any { return any } func (any *int32Any) ToBool() bool { return any.val != 0 } func (any *int32Any) ToInt() int { return int(any.val) } func (any *int32Any) ToInt32() int32 { return any.val } func (any *int32Any) ToInt64() int64 { return int64(any.val) } func (any *int32Any) ToUint() uint { return uint(any.val) } func (any *int32Any) ToUint32() uint32 { return uint32(any.val) } func (any *int32Any) ToUint64() uint64 { return uint64(any.val) } func (any *int32Any) ToFloat32() float32 { return float32(any.val) } func (any *int32Any) ToFloat64() float64 { return float64(any.val) } func (any *int32Any) ToString() string { return strconv.FormatInt(int64(any.val), 10) } func (any *int32Any) WriteTo(stream *Stream) { stream.WriteInt32(any.val) } func (any *int32Any) Parse() *Iterator { return nil } func (any *int32Any) GetInterface() interface{} { return any.val }
vendor/github.com/json-iterator/go/any_int32.go
0
https://github.com/hashicorp/terraform/commit/d6a586709cf8eee53b46b56bcf00fa7fa44d6441
[ 0.0015132559929043055, 0.0006668336573056877, 0.00017058104276657104, 0.000619142665527761, 0.00041044101817533374 ]
{ "id": 2, "code_window": [ "\n", "func (ctx *BuiltinEvalContext) State() *states.SyncState {\n", "\treturn ctx.StateValue\n", "}\n", "\n", "func (ctx *BuiltinEvalContext) InstanceExpander() *instances.Expander {\n", "\treturn ctx.InstanceExpanderValue\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "func (ctx *BuiltinEvalContext) RefreshState() *states.SyncState {\n", "\treturn ctx.RefreshStateValue\n", "}\n", "\n" ], "file_path": "terraform/eval_context_builtin.go", "type": "add", "edit_start_line_idx": 352 }
// go run mkasm_darwin.go arm64 // Code generated by the command above; DO NOT EDIT. // +build go1.12 #include "textflag.h" TEXT ·libc_getgroups_trampoline(SB),NOSPLIT,$0-0 JMP libc_getgroups(SB) TEXT ·libc_setgroups_trampoline(SB),NOSPLIT,$0-0 JMP libc_setgroups(SB) TEXT ·libc_wait4_trampoline(SB),NOSPLIT,$0-0 JMP libc_wait4(SB) TEXT ·libc_accept_trampoline(SB),NOSPLIT,$0-0 JMP libc_accept(SB) TEXT ·libc_bind_trampoline(SB),NOSPLIT,$0-0 JMP libc_bind(SB) TEXT ·libc_connect_trampoline(SB),NOSPLIT,$0-0 JMP libc_connect(SB) TEXT ·libc_socket_trampoline(SB),NOSPLIT,$0-0 JMP libc_socket(SB) TEXT ·libc_getsockopt_trampoline(SB),NOSPLIT,$0-0 JMP libc_getsockopt(SB) TEXT ·libc_setsockopt_trampoline(SB),NOSPLIT,$0-0 JMP libc_setsockopt(SB) TEXT ·libc_getpeername_trampoline(SB),NOSPLIT,$0-0 JMP libc_getpeername(SB) TEXT ·libc_getsockname_trampoline(SB),NOSPLIT,$0-0 JMP libc_getsockname(SB) TEXT ·libc_shutdown_trampoline(SB),NOSPLIT,$0-0 JMP libc_shutdown(SB) TEXT ·libc_socketpair_trampoline(SB),NOSPLIT,$0-0 JMP libc_socketpair(SB) TEXT ·libc_recvfrom_trampoline(SB),NOSPLIT,$0-0 JMP libc_recvfrom(SB) TEXT ·libc_sendto_trampoline(SB),NOSPLIT,$0-0 JMP libc_sendto(SB) TEXT ·libc_recvmsg_trampoline(SB),NOSPLIT,$0-0 JMP libc_recvmsg(SB) TEXT ·libc_sendmsg_trampoline(SB),NOSPLIT,$0-0 JMP libc_sendmsg(SB) TEXT ·libc_kevent_trampoline(SB),NOSPLIT,$0-0 JMP libc_kevent(SB) TEXT ·libc_utimes_trampoline(SB),NOSPLIT,$0-0 JMP libc_utimes(SB) TEXT ·libc_futimes_trampoline(SB),NOSPLIT,$0-0 JMP libc_futimes(SB) TEXT ·libc_poll_trampoline(SB),NOSPLIT,$0-0 JMP libc_poll(SB) TEXT ·libc_madvise_trampoline(SB),NOSPLIT,$0-0 JMP libc_madvise(SB) TEXT ·libc_mlock_trampoline(SB),NOSPLIT,$0-0 JMP libc_mlock(SB) TEXT ·libc_mlockall_trampoline(SB),NOSPLIT,$0-0 JMP libc_mlockall(SB) TEXT ·libc_mprotect_trampoline(SB),NOSPLIT,$0-0 JMP libc_mprotect(SB) TEXT ·libc_msync_trampoline(SB),NOSPLIT,$0-0 JMP libc_msync(SB) TEXT ·libc_munlock_trampoline(SB),NOSPLIT,$0-0 JMP libc_munlock(SB) TEXT ·libc_munlockall_trampoline(SB),NOSPLIT,$0-0 JMP libc_munlockall(SB) TEXT ·libc_getattrlist_trampoline(SB),NOSPLIT,$0-0 JMP libc_getattrlist(SB) TEXT ·libc_pipe_trampoline(SB),NOSPLIT,$0-0 JMP libc_pipe(SB) TEXT ·libc_getxattr_trampoline(SB),NOSPLIT,$0-0 JMP libc_getxattr(SB) TEXT ·libc_fgetxattr_trampoline(SB),NOSPLIT,$0-0 JMP libc_fgetxattr(SB) TEXT ·libc_setxattr_trampoline(SB),NOSPLIT,$0-0 JMP libc_setxattr(SB) TEXT ·libc_fsetxattr_trampoline(SB),NOSPLIT,$0-0 JMP libc_fsetxattr(SB) TEXT ·libc_removexattr_trampoline(SB),NOSPLIT,$0-0 JMP libc_removexattr(SB) TEXT ·libc_fremovexattr_trampoline(SB),NOSPLIT,$0-0 JMP libc_fremovexattr(SB) TEXT ·libc_listxattr_trampoline(SB),NOSPLIT,$0-0 JMP libc_listxattr(SB) TEXT ·libc_flistxattr_trampoline(SB),NOSPLIT,$0-0 JMP libc_flistxattr(SB) TEXT ·libc_setattrlist_trampoline(SB),NOSPLIT,$0-0 JMP libc_setattrlist(SB) TEXT ·libc_fcntl_trampoline(SB),NOSPLIT,$0-0 JMP libc_fcntl(SB) TEXT ·libc_kill_trampoline(SB),NOSPLIT,$0-0 JMP libc_kill(SB) TEXT ·libc_ioctl_trampoline(SB),NOSPLIT,$0-0 JMP libc_ioctl(SB) TEXT ·libc_sysctl_trampoline(SB),NOSPLIT,$0-0 JMP libc_sysctl(SB) TEXT ·libc_sendfile_trampoline(SB),NOSPLIT,$0-0 JMP libc_sendfile(SB) TEXT ·libc_access_trampoline(SB),NOSPLIT,$0-0 JMP libc_access(SB) TEXT ·libc_adjtime_trampoline(SB),NOSPLIT,$0-0 JMP libc_adjtime(SB) TEXT ·libc_chdir_trampoline(SB),NOSPLIT,$0-0 JMP libc_chdir(SB) TEXT ·libc_chflags_trampoline(SB),NOSPLIT,$0-0 JMP libc_chflags(SB) TEXT ·libc_chmod_trampoline(SB),NOSPLIT,$0-0 JMP libc_chmod(SB) TEXT ·libc_chown_trampoline(SB),NOSPLIT,$0-0 JMP libc_chown(SB) TEXT ·libc_chroot_trampoline(SB),NOSPLIT,$0-0 JMP libc_chroot(SB) TEXT ·libc_clock_gettime_trampoline(SB),NOSPLIT,$0-0 JMP libc_clock_gettime(SB) TEXT ·libc_close_trampoline(SB),NOSPLIT,$0-0 JMP libc_close(SB) TEXT ·libc_dup_trampoline(SB),NOSPLIT,$0-0 JMP libc_dup(SB) TEXT ·libc_dup2_trampoline(SB),NOSPLIT,$0-0 JMP libc_dup2(SB) TEXT ·libc_exchangedata_trampoline(SB),NOSPLIT,$0-0 JMP libc_exchangedata(SB) TEXT ·libc_exit_trampoline(SB),NOSPLIT,$0-0 JMP libc_exit(SB) TEXT ·libc_faccessat_trampoline(SB),NOSPLIT,$0-0 JMP libc_faccessat(SB) TEXT ·libc_fchdir_trampoline(SB),NOSPLIT,$0-0 JMP libc_fchdir(SB) TEXT ·libc_fchflags_trampoline(SB),NOSPLIT,$0-0 JMP libc_fchflags(SB) TEXT ·libc_fchmod_trampoline(SB),NOSPLIT,$0-0 JMP libc_fchmod(SB) TEXT ·libc_fchmodat_trampoline(SB),NOSPLIT,$0-0 JMP libc_fchmodat(SB) TEXT ·libc_fchown_trampoline(SB),NOSPLIT,$0-0 JMP libc_fchown(SB) TEXT ·libc_fchownat_trampoline(SB),NOSPLIT,$0-0 JMP libc_fchownat(SB) TEXT ·libc_flock_trampoline(SB),NOSPLIT,$0-0 JMP libc_flock(SB) TEXT ·libc_fpathconf_trampoline(SB),NOSPLIT,$0-0 JMP libc_fpathconf(SB) TEXT ·libc_fsync_trampoline(SB),NOSPLIT,$0-0 JMP libc_fsync(SB) TEXT ·libc_ftruncate_trampoline(SB),NOSPLIT,$0-0 JMP libc_ftruncate(SB) TEXT ·libc_getdtablesize_trampoline(SB),NOSPLIT,$0-0 JMP libc_getdtablesize(SB) TEXT ·libc_getegid_trampoline(SB),NOSPLIT,$0-0 JMP libc_getegid(SB) TEXT ·libc_geteuid_trampoline(SB),NOSPLIT,$0-0 JMP libc_geteuid(SB) TEXT ·libc_getgid_trampoline(SB),NOSPLIT,$0-0 JMP libc_getgid(SB) TEXT ·libc_getpgid_trampoline(SB),NOSPLIT,$0-0 JMP libc_getpgid(SB) TEXT ·libc_getpgrp_trampoline(SB),NOSPLIT,$0-0 JMP libc_getpgrp(SB) TEXT ·libc_getpid_trampoline(SB),NOSPLIT,$0-0 JMP libc_getpid(SB) TEXT ·libc_getppid_trampoline(SB),NOSPLIT,$0-0 JMP libc_getppid(SB) TEXT ·libc_getpriority_trampoline(SB),NOSPLIT,$0-0 JMP libc_getpriority(SB) TEXT ·libc_getrlimit_trampoline(SB),NOSPLIT,$0-0 JMP libc_getrlimit(SB) TEXT ·libc_getrusage_trampoline(SB),NOSPLIT,$0-0 JMP libc_getrusage(SB) TEXT ·libc_getsid_trampoline(SB),NOSPLIT,$0-0 JMP libc_getsid(SB) TEXT ·libc_getuid_trampoline(SB),NOSPLIT,$0-0 JMP libc_getuid(SB) TEXT ·libc_issetugid_trampoline(SB),NOSPLIT,$0-0 JMP libc_issetugid(SB) TEXT ·libc_kqueue_trampoline(SB),NOSPLIT,$0-0 JMP libc_kqueue(SB) TEXT ·libc_lchown_trampoline(SB),NOSPLIT,$0-0 JMP libc_lchown(SB) TEXT ·libc_link_trampoline(SB),NOSPLIT,$0-0 JMP libc_link(SB) TEXT ·libc_linkat_trampoline(SB),NOSPLIT,$0-0 JMP libc_linkat(SB) TEXT ·libc_listen_trampoline(SB),NOSPLIT,$0-0 JMP libc_listen(SB) TEXT ·libc_mkdir_trampoline(SB),NOSPLIT,$0-0 JMP libc_mkdir(SB) TEXT ·libc_mkdirat_trampoline(SB),NOSPLIT,$0-0 JMP libc_mkdirat(SB) TEXT ·libc_mkfifo_trampoline(SB),NOSPLIT,$0-0 JMP libc_mkfifo(SB) TEXT ·libc_mknod_trampoline(SB),NOSPLIT,$0-0 JMP libc_mknod(SB) TEXT ·libc_open_trampoline(SB),NOSPLIT,$0-0 JMP libc_open(SB) TEXT ·libc_openat_trampoline(SB),NOSPLIT,$0-0 JMP libc_openat(SB) TEXT ·libc_pathconf_trampoline(SB),NOSPLIT,$0-0 JMP libc_pathconf(SB) TEXT ·libc_pread_trampoline(SB),NOSPLIT,$0-0 JMP libc_pread(SB) TEXT ·libc_pwrite_trampoline(SB),NOSPLIT,$0-0 JMP libc_pwrite(SB) TEXT ·libc_read_trampoline(SB),NOSPLIT,$0-0 JMP libc_read(SB) TEXT ·libc_readlink_trampoline(SB),NOSPLIT,$0-0 JMP libc_readlink(SB) TEXT ·libc_readlinkat_trampoline(SB),NOSPLIT,$0-0 JMP libc_readlinkat(SB) TEXT ·libc_rename_trampoline(SB),NOSPLIT,$0-0 JMP libc_rename(SB) TEXT ·libc_renameat_trampoline(SB),NOSPLIT,$0-0 JMP libc_renameat(SB) TEXT ·libc_revoke_trampoline(SB),NOSPLIT,$0-0 JMP libc_revoke(SB) TEXT ·libc_rmdir_trampoline(SB),NOSPLIT,$0-0 JMP libc_rmdir(SB) TEXT ·libc_lseek_trampoline(SB),NOSPLIT,$0-0 JMP libc_lseek(SB) TEXT ·libc_select_trampoline(SB),NOSPLIT,$0-0 JMP libc_select(SB) TEXT ·libc_setegid_trampoline(SB),NOSPLIT,$0-0 JMP libc_setegid(SB) TEXT ·libc_seteuid_trampoline(SB),NOSPLIT,$0-0 JMP libc_seteuid(SB) TEXT ·libc_setgid_trampoline(SB),NOSPLIT,$0-0 JMP libc_setgid(SB) TEXT ·libc_setlogin_trampoline(SB),NOSPLIT,$0-0 JMP libc_setlogin(SB) TEXT ·libc_setpgid_trampoline(SB),NOSPLIT,$0-0 JMP libc_setpgid(SB) TEXT ·libc_setpriority_trampoline(SB),NOSPLIT,$0-0 JMP libc_setpriority(SB) TEXT ·libc_setprivexec_trampoline(SB),NOSPLIT,$0-0 JMP libc_setprivexec(SB) TEXT ·libc_setregid_trampoline(SB),NOSPLIT,$0-0 JMP libc_setregid(SB) TEXT ·libc_setreuid_trampoline(SB),NOSPLIT,$0-0 JMP libc_setreuid(SB) TEXT ·libc_setrlimit_trampoline(SB),NOSPLIT,$0-0 JMP libc_setrlimit(SB) TEXT ·libc_setsid_trampoline(SB),NOSPLIT,$0-0 JMP libc_setsid(SB) TEXT ·libc_settimeofday_trampoline(SB),NOSPLIT,$0-0 JMP libc_settimeofday(SB) TEXT ·libc_setuid_trampoline(SB),NOSPLIT,$0-0 JMP libc_setuid(SB) TEXT ·libc_symlink_trampoline(SB),NOSPLIT,$0-0 JMP libc_symlink(SB) TEXT ·libc_symlinkat_trampoline(SB),NOSPLIT,$0-0 JMP libc_symlinkat(SB) TEXT ·libc_sync_trampoline(SB),NOSPLIT,$0-0 JMP libc_sync(SB) TEXT ·libc_truncate_trampoline(SB),NOSPLIT,$0-0 JMP libc_truncate(SB) TEXT ·libc_umask_trampoline(SB),NOSPLIT,$0-0 JMP libc_umask(SB) TEXT ·libc_undelete_trampoline(SB),NOSPLIT,$0-0 JMP libc_undelete(SB) TEXT ·libc_unlink_trampoline(SB),NOSPLIT,$0-0 JMP libc_unlink(SB) TEXT ·libc_unlinkat_trampoline(SB),NOSPLIT,$0-0 JMP libc_unlinkat(SB) TEXT ·libc_unmount_trampoline(SB),NOSPLIT,$0-0 JMP libc_unmount(SB) TEXT ·libc_write_trampoline(SB),NOSPLIT,$0-0 JMP libc_write(SB) TEXT ·libc_mmap_trampoline(SB),NOSPLIT,$0-0 JMP libc_mmap(SB) TEXT ·libc_munmap_trampoline(SB),NOSPLIT,$0-0 JMP libc_munmap(SB) TEXT ·libc_gettimeofday_trampoline(SB),NOSPLIT,$0-0 JMP libc_gettimeofday(SB) TEXT ·libc_fstat_trampoline(SB),NOSPLIT,$0-0 JMP libc_fstat(SB) TEXT ·libc_fstatat_trampoline(SB),NOSPLIT,$0-0 JMP libc_fstatat(SB) TEXT ·libc_fstatfs_trampoline(SB),NOSPLIT,$0-0 JMP libc_fstatfs(SB) TEXT ·libc_getfsstat_trampoline(SB),NOSPLIT,$0-0 JMP libc_getfsstat(SB) TEXT ·libc_lstat_trampoline(SB),NOSPLIT,$0-0 JMP libc_lstat(SB) TEXT ·libc_stat_trampoline(SB),NOSPLIT,$0-0 JMP libc_stat(SB) TEXT ·libc_statfs_trampoline(SB),NOSPLIT,$0-0 JMP libc_statfs(SB)
vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s
0
https://github.com/hashicorp/terraform/commit/d6a586709cf8eee53b46b56bcf00fa7fa44d6441
[ 0.0001726082555251196, 0.00017168765771202743, 0.00016988000425044447, 0.0001719065912766382, 7.366876957348722e-7 ]
{ "id": 3, "code_window": [ "\tStateCalled bool\n", "\tStateState *states.SyncState\n", "\n", "\tInstanceExpanderCalled bool\n", "\tInstanceExpanderExpander *instances.Expander\n", "}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tRefreshStateCalled bool\n", "\tRefreshStateState *states.SyncState\n", "\n" ], "file_path": "terraform/eval_context_mock.go", "type": "add", "edit_start_line_idx": 128 }
package terraform import ( "context" "fmt" "log" "sync" "github.com/hashicorp/terraform/instances" "github.com/hashicorp/terraform/plans" "github.com/hashicorp/terraform/providers" "github.com/hashicorp/terraform/provisioners" "github.com/hashicorp/terraform/version" "github.com/hashicorp/terraform/states" "github.com/hashicorp/hcl/v2" "github.com/hashicorp/terraform/configs/configschema" "github.com/hashicorp/terraform/lang" "github.com/hashicorp/terraform/tfdiags" "github.com/hashicorp/terraform/addrs" "github.com/zclconf/go-cty/cty" ) // BuiltinEvalContext is an EvalContext implementation that is used by // Terraform by default. type BuiltinEvalContext struct { // StopContext is the context used to track whether we're complete StopContext context.Context // PathValue is the Path that this context is operating within. PathValue addrs.ModuleInstance // pathSet indicates that this context was explicitly created for a // specific path, and can be safely used for evaluation. This lets us // differentiate between PathValue being unset, and the zero value which is // equivalent to RootModuleInstance. Path and Evaluation methods will // panic if this is not set. pathSet bool // Evaluator is used for evaluating expressions within the scope of this // eval context. Evaluator *Evaluator // Schemas is a repository of all of the schemas we should need to // decode configuration blocks and expressions. This must be constructed by // the caller to include schemas for all of the providers, resource types, // data sources and provisioners used by the given configuration and // state. // // This must not be mutated during evaluation. Schemas *Schemas // VariableValues contains the variable values across all modules. This // structure is shared across the entire containing context, and so it // may be accessed only when holding VariableValuesLock. // The keys of the first level of VariableValues are the string // representations of addrs.ModuleInstance values. The second-level keys // are variable names within each module instance. VariableValues map[string]map[string]cty.Value VariableValuesLock *sync.Mutex Components contextComponentFactory Hooks []Hook InputValue UIInput ProviderCache map[string]providers.Interface ProviderInputConfig map[string]map[string]cty.Value ProviderLock *sync.Mutex ProvisionerCache map[string]provisioners.Interface ProvisionerLock *sync.Mutex ChangesValue *plans.ChangesSync StateValue *states.SyncState InstanceExpanderValue *instances.Expander } // BuiltinEvalContext implements EvalContext var _ EvalContext = (*BuiltinEvalContext)(nil) func (ctx *BuiltinEvalContext) WithPath(path addrs.ModuleInstance) EvalContext { ctx.pathSet = true newCtx := *ctx newCtx.PathValue = path return &newCtx } func (ctx *BuiltinEvalContext) Stopped() <-chan struct{} { // This can happen during tests. During tests, we just block forever. if ctx.StopContext == nil { return nil } return ctx.StopContext.Done() } func (ctx *BuiltinEvalContext) Hook(fn func(Hook) (HookAction, error)) error { for _, h := range ctx.Hooks { action, err := fn(h) if err != nil { return err } switch action { case HookActionContinue: continue case HookActionHalt: // Return an early exit error to trigger an early exit log.Printf("[WARN] Early exit triggered by hook: %T", h) return EvalEarlyExitError{} } } return nil } func (ctx *BuiltinEvalContext) Input() UIInput { return ctx.InputValue } func (ctx *BuiltinEvalContext) InitProvider(addr addrs.AbsProviderConfig) (providers.Interface, error) { // If we already initialized, it is an error if p := ctx.Provider(addr); p != nil { return nil, fmt.Errorf("%s is already initialized", addr) } // Warning: make sure to acquire these locks AFTER the call to Provider // above, since it also acquires locks. ctx.ProviderLock.Lock() defer ctx.ProviderLock.Unlock() key := addr.String() p, err := ctx.Components.ResourceProvider(addr.Provider) if err != nil { return nil, err } log.Printf("[TRACE] BuiltinEvalContext: Initialized %q provider for %s", addr.String(), addr) ctx.ProviderCache[key] = p return p, nil } func (ctx *BuiltinEvalContext) Provider(addr addrs.AbsProviderConfig) providers.Interface { ctx.ProviderLock.Lock() defer ctx.ProviderLock.Unlock() return ctx.ProviderCache[addr.String()] } func (ctx *BuiltinEvalContext) ProviderSchema(addr addrs.AbsProviderConfig) *ProviderSchema { return ctx.Schemas.ProviderSchema(addr.Provider) } func (ctx *BuiltinEvalContext) CloseProvider(addr addrs.AbsProviderConfig) error { ctx.ProviderLock.Lock() defer ctx.ProviderLock.Unlock() key := addr.String() provider := ctx.ProviderCache[key] if provider != nil { delete(ctx.ProviderCache, key) return provider.Close() } return nil } func (ctx *BuiltinEvalContext) ConfigureProvider(addr addrs.AbsProviderConfig, cfg cty.Value) tfdiags.Diagnostics { var diags tfdiags.Diagnostics if !addr.Module.Equal(ctx.Path().Module()) { // This indicates incorrect use of ConfigureProvider: it should be used // only from the module that the provider configuration belongs to. panic(fmt.Sprintf("%s configured by wrong module %s", addr, ctx.Path())) } p := ctx.Provider(addr) if p == nil { diags = diags.Append(fmt.Errorf("%s not initialized", addr)) return diags } providerSchema := ctx.ProviderSchema(addr) if providerSchema == nil { diags = diags.Append(fmt.Errorf("schema for %s is not available", addr)) return diags } req := providers.ConfigureRequest{ TerraformVersion: version.String(), Config: cfg, } resp := p.Configure(req) return resp.Diagnostics } func (ctx *BuiltinEvalContext) ProviderInput(pc addrs.AbsProviderConfig) map[string]cty.Value { ctx.ProviderLock.Lock() defer ctx.ProviderLock.Unlock() if !pc.Module.Equal(ctx.Path().Module()) { // This indicates incorrect use of InitProvider: it should be used // only from the module that the provider configuration belongs to. panic(fmt.Sprintf("%s initialized by wrong module %s", pc, ctx.Path())) } if !ctx.Path().IsRoot() { // Only root module provider configurations can have input. return nil } return ctx.ProviderInputConfig[pc.String()] } func (ctx *BuiltinEvalContext) SetProviderInput(pc addrs.AbsProviderConfig, c map[string]cty.Value) { absProvider := pc if !pc.Module.IsRoot() { // Only root module provider configurations can have input. log.Printf("[WARN] BuiltinEvalContext: attempt to SetProviderInput for non-root module") return } // Save the configuration ctx.ProviderLock.Lock() ctx.ProviderInputConfig[absProvider.String()] = c ctx.ProviderLock.Unlock() } func (ctx *BuiltinEvalContext) InitProvisioner(n string) error { // If we already initialized, it is an error if p := ctx.Provisioner(n); p != nil { return fmt.Errorf("Provisioner '%s' already initialized", n) } // Warning: make sure to acquire these locks AFTER the call to Provisioner // above, since it also acquires locks. ctx.ProvisionerLock.Lock() defer ctx.ProvisionerLock.Unlock() p, err := ctx.Components.ResourceProvisioner(n) if err != nil { return err } ctx.ProvisionerCache[n] = p return nil } func (ctx *BuiltinEvalContext) Provisioner(n string) provisioners.Interface { ctx.ProvisionerLock.Lock() defer ctx.ProvisionerLock.Unlock() return ctx.ProvisionerCache[n] } func (ctx *BuiltinEvalContext) ProvisionerSchema(n string) *configschema.Block { return ctx.Schemas.ProvisionerConfig(n) } func (ctx *BuiltinEvalContext) CloseProvisioner(n string) error { ctx.ProvisionerLock.Lock() defer ctx.ProvisionerLock.Unlock() prov := ctx.ProvisionerCache[n] if prov != nil { return prov.Close() } return nil } func (ctx *BuiltinEvalContext) EvaluateBlock(body hcl.Body, schema *configschema.Block, self addrs.Referenceable, keyData InstanceKeyEvalData) (cty.Value, hcl.Body, tfdiags.Diagnostics) { var diags tfdiags.Diagnostics scope := ctx.EvaluationScope(self, keyData) body, evalDiags := scope.ExpandBlock(body, schema) diags = diags.Append(evalDiags) val, evalDiags := scope.EvalBlock(body, schema) diags = diags.Append(evalDiags) return val, body, diags } func (ctx *BuiltinEvalContext) EvaluateExpr(expr hcl.Expression, wantType cty.Type, self addrs.Referenceable) (cty.Value, tfdiags.Diagnostics) { scope := ctx.EvaluationScope(self, EvalDataForNoInstanceKey) return scope.EvalExpr(expr, wantType) } func (ctx *BuiltinEvalContext) EvaluationScope(self addrs.Referenceable, keyData InstanceKeyEvalData) *lang.Scope { if !ctx.pathSet { panic("context path not set") } data := &evaluationStateData{ Evaluator: ctx.Evaluator, ModulePath: ctx.PathValue, InstanceKeyData: keyData, Operation: ctx.Evaluator.Operation, } return ctx.Evaluator.Scope(data, self) } func (ctx *BuiltinEvalContext) Path() addrs.ModuleInstance { if !ctx.pathSet { panic("context path not set") } return ctx.PathValue } func (ctx *BuiltinEvalContext) SetModuleCallArguments(n addrs.ModuleCallInstance, vals map[string]cty.Value) { ctx.VariableValuesLock.Lock() defer ctx.VariableValuesLock.Unlock() if !ctx.pathSet { panic("context path not set") } childPath := n.ModuleInstance(ctx.PathValue) key := childPath.String() args := ctx.VariableValues[key] if args == nil { args = make(map[string]cty.Value) ctx.VariableValues[key] = vals return } for k, v := range vals { args[k] = v } } func (ctx *BuiltinEvalContext) GetVariableValue(addr addrs.AbsInputVariableInstance) cty.Value { ctx.VariableValuesLock.Lock() defer ctx.VariableValuesLock.Unlock() modKey := addr.Module.String() modVars := ctx.VariableValues[modKey] val, ok := modVars[addr.Variable.Name] if !ok { return cty.DynamicVal } return val } func (ctx *BuiltinEvalContext) Changes() *plans.ChangesSync { return ctx.ChangesValue } func (ctx *BuiltinEvalContext) State() *states.SyncState { return ctx.StateValue } func (ctx *BuiltinEvalContext) InstanceExpander() *instances.Expander { return ctx.InstanceExpanderValue }
terraform/eval_context_builtin.go
1
https://github.com/hashicorp/terraform/commit/d6a586709cf8eee53b46b56bcf00fa7fa44d6441
[ 0.027134841307997704, 0.0012707982677966356, 0.0001646556193009019, 0.00017112912610173225, 0.004747998900711536 ]
{ "id": 3, "code_window": [ "\tStateCalled bool\n", "\tStateState *states.SyncState\n", "\n", "\tInstanceExpanderCalled bool\n", "\tInstanceExpanderExpander *instances.Expander\n", "}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tRefreshStateCalled bool\n", "\tRefreshStateState *states.SyncState\n", "\n" ], "file_path": "terraform/eval_context_mock.go", "type": "add", "edit_start_line_idx": 128 }
package terraform import ( "log" "github.com/hashicorp/terraform/addrs" "github.com/hashicorp/terraform/configs" "github.com/hashicorp/terraform/states" ) // RemovedModuleTransformer implements GraphTransformer to add nodes indicating // when a module was removed from the configuration. type RemovedModuleTransformer struct { Config *configs.Config // root node in the config tree State *states.State } func (t *RemovedModuleTransformer) Transform(g *Graph) error { // nothing to remove if there's no state! if t.State == nil { return nil } removed := map[string]addrs.Module{} for _, m := range t.State.Modules { cc := t.Config.DescendentForInstance(m.Addr) if cc != nil { continue } removed[m.Addr.Module().String()] = m.Addr.Module() log.Printf("[DEBUG] %s is no longer in configuration\n", m.Addr) } // add closers to collect any module instances we're removing for _, modAddr := range removed { closer := &nodeCloseModule{ Addr: modAddr, } g.Add(closer) } return nil }
terraform/transform_removed_modules.go
0
https://github.com/hashicorp/terraform/commit/d6a586709cf8eee53b46b56bcf00fa7fa44d6441
[ 0.010303820483386517, 0.002212673891335726, 0.00017042644321918488, 0.00017743914213497192, 0.0040456573478877544 ]
{ "id": 3, "code_window": [ "\tStateCalled bool\n", "\tStateState *states.SyncState\n", "\n", "\tInstanceExpanderCalled bool\n", "\tInstanceExpanderExpander *instances.Expander\n", "}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tRefreshStateCalled bool\n", "\tRefreshStateState *states.SyncState\n", "\n" ], "file_path": "terraform/eval_context_mock.go", "type": "add", "edit_start_line_idx": 128 }
variable "input" { }
terraform/testdata/plan-destroy-interpolated-count/mod/main.tf
0
https://github.com/hashicorp/terraform/commit/d6a586709cf8eee53b46b56bcf00fa7fa44d6441
[ 0.0001788305671652779, 0.0001788305671652779, 0.0001788305671652779, 0.0001788305671652779, 0 ]
{ "id": 3, "code_window": [ "\tStateCalled bool\n", "\tStateState *states.SyncState\n", "\n", "\tInstanceExpanderCalled bool\n", "\tInstanceExpanderExpander *instances.Expander\n", "}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tRefreshStateCalled bool\n", "\tRefreshStateState *states.SyncState\n", "\n" ], "file_path": "terraform/eval_context_mock.go", "type": "add", "edit_start_line_idx": 128 }
/* * Copyright (c) 2013-2016 Dave Collins <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "bytes" "fmt" "io" "reflect" "sort" "strconv" ) // Some constants in the form of bytes to avoid string overhead. This mirrors // the technique used in the fmt package. var ( panicBytes = []byte("(PANIC=") plusBytes = []byte("+") iBytes = []byte("i") trueBytes = []byte("true") falseBytes = []byte("false") interfaceBytes = []byte("(interface {})") commaNewlineBytes = []byte(",\n") newlineBytes = []byte("\n") openBraceBytes = []byte("{") openBraceNewlineBytes = []byte("{\n") closeBraceBytes = []byte("}") asteriskBytes = []byte("*") colonBytes = []byte(":") colonSpaceBytes = []byte(": ") openParenBytes = []byte("(") closeParenBytes = []byte(")") spaceBytes = []byte(" ") pointerChainBytes = []byte("->") nilAngleBytes = []byte("<nil>") maxNewlineBytes = []byte("<max depth reached>\n") maxShortBytes = []byte("<max>") circularBytes = []byte("<already shown>") circularShortBytes = []byte("<shown>") invalidAngleBytes = []byte("<invalid>") openBracketBytes = []byte("[") closeBracketBytes = []byte("]") percentBytes = []byte("%") precisionBytes = []byte(".") openAngleBytes = []byte("<") closeAngleBytes = []byte(">") openMapBytes = []byte("map[") closeMapBytes = []byte("]") lenEqualsBytes = []byte("len=") capEqualsBytes = []byte("cap=") ) // hexDigits is used to map a decimal value to a hex digit. var hexDigits = "0123456789abcdef" // catchPanic handles any panics that might occur during the handleMethods // calls. func catchPanic(w io.Writer, v reflect.Value) { if err := recover(); err != nil { w.Write(panicBytes) fmt.Fprintf(w, "%v", err) w.Write(closeParenBytes) } } // handleMethods attempts to call the Error and String methods on the underlying // type the passed reflect.Value represents and outputes the result to Writer w. // // It handles panics in any called methods by catching and displaying the error // as the formatted value. func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) { // We need an interface to check if the type implements the error or // Stringer interface. However, the reflect package won't give us an // interface on certain things like unexported struct fields in order // to enforce visibility rules. We use unsafe, when it's available, // to bypass these restrictions since this package does not mutate the // values. if !v.CanInterface() { if UnsafeDisabled { return false } v = unsafeReflectValue(v) } // Choose whether or not to do error and Stringer interface lookups against // the base type or a pointer to the base type depending on settings. // Technically calling one of these methods with a pointer receiver can // mutate the value, however, types which choose to satisify an error or // Stringer interface with a pointer receiver should not be mutating their // state inside these interface methods. if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() { v = unsafeReflectValue(v) } if v.CanAddr() { v = v.Addr() } // Is it an error or Stringer? switch iface := v.Interface().(type) { case error: defer catchPanic(w, v) if cs.ContinueOnMethod { w.Write(openParenBytes) w.Write([]byte(iface.Error())) w.Write(closeParenBytes) w.Write(spaceBytes) return false } w.Write([]byte(iface.Error())) return true case fmt.Stringer: defer catchPanic(w, v) if cs.ContinueOnMethod { w.Write(openParenBytes) w.Write([]byte(iface.String())) w.Write(closeParenBytes) w.Write(spaceBytes) return false } w.Write([]byte(iface.String())) return true } return false } // printBool outputs a boolean value as true or false to Writer w. func printBool(w io.Writer, val bool) { if val { w.Write(trueBytes) } else { w.Write(falseBytes) } } // printInt outputs a signed integer value to Writer w. func printInt(w io.Writer, val int64, base int) { w.Write([]byte(strconv.FormatInt(val, base))) } // printUint outputs an unsigned integer value to Writer w. func printUint(w io.Writer, val uint64, base int) { w.Write([]byte(strconv.FormatUint(val, base))) } // printFloat outputs a floating point value using the specified precision, // which is expected to be 32 or 64bit, to Writer w. func printFloat(w io.Writer, val float64, precision int) { w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision))) } // printComplex outputs a complex value using the specified float precision // for the real and imaginary parts to Writer w. func printComplex(w io.Writer, c complex128, floatPrecision int) { r := real(c) w.Write(openParenBytes) w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision))) i := imag(c) if i >= 0 { w.Write(plusBytes) } w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision))) w.Write(iBytes) w.Write(closeParenBytes) } // printHexPtr outputs a uintptr formatted as hexadecimal with a leading '0x' // prefix to Writer w. func printHexPtr(w io.Writer, p uintptr) { // Null pointer. num := uint64(p) if num == 0 { w.Write(nilAngleBytes) return } // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix buf := make([]byte, 18) // It's simpler to construct the hex string right to left. base := uint64(16) i := len(buf) - 1 for num >= base { buf[i] = hexDigits[num%base] num /= base i-- } buf[i] = hexDigits[num] // Add '0x' prefix. i-- buf[i] = 'x' i-- buf[i] = '0' // Strip unused leading bytes. buf = buf[i:] w.Write(buf) } // valuesSorter implements sort.Interface to allow a slice of reflect.Value // elements to be sorted. type valuesSorter struct { values []reflect.Value strings []string // either nil or same len and values cs *ConfigState } // newValuesSorter initializes a valuesSorter instance, which holds a set of // surrogate keys on which the data should be sorted. It uses flags in // ConfigState to decide if and how to populate those surrogate keys. func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface { vs := &valuesSorter{values: values, cs: cs} if canSortSimply(vs.values[0].Kind()) { return vs } if !cs.DisableMethods { vs.strings = make([]string, len(values)) for i := range vs.values { b := bytes.Buffer{} if !handleMethods(cs, &b, vs.values[i]) { vs.strings = nil break } vs.strings[i] = b.String() } } if vs.strings == nil && cs.SpewKeys { vs.strings = make([]string, len(values)) for i := range vs.values { vs.strings[i] = Sprintf("%#v", vs.values[i].Interface()) } } return vs } // canSortSimply tests whether a reflect.Kind is a primitive that can be sorted // directly, or whether it should be considered for sorting by surrogate keys // (if the ConfigState allows it). func canSortSimply(kind reflect.Kind) bool { // This switch parallels valueSortLess, except for the default case. switch kind { case reflect.Bool: return true case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: return true case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: return true case reflect.Float32, reflect.Float64: return true case reflect.String: return true case reflect.Uintptr: return true case reflect.Array: return true } return false } // Len returns the number of values in the slice. It is part of the // sort.Interface implementation. func (s *valuesSorter) Len() int { return len(s.values) } // Swap swaps the values at the passed indices. It is part of the // sort.Interface implementation. func (s *valuesSorter) Swap(i, j int) { s.values[i], s.values[j] = s.values[j], s.values[i] if s.strings != nil { s.strings[i], s.strings[j] = s.strings[j], s.strings[i] } } // valueSortLess returns whether the first value should sort before the second // value. It is used by valueSorter.Less as part of the sort.Interface // implementation. func valueSortLess(a, b reflect.Value) bool { switch a.Kind() { case reflect.Bool: return !a.Bool() && b.Bool() case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: return a.Int() < b.Int() case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: return a.Uint() < b.Uint() case reflect.Float32, reflect.Float64: return a.Float() < b.Float() case reflect.String: return a.String() < b.String() case reflect.Uintptr: return a.Uint() < b.Uint() case reflect.Array: // Compare the contents of both arrays. l := a.Len() for i := 0; i < l; i++ { av := a.Index(i) bv := b.Index(i) if av.Interface() == bv.Interface() { continue } return valueSortLess(av, bv) } } return a.String() < b.String() } // Less returns whether the value at index i should sort before the // value at index j. It is part of the sort.Interface implementation. func (s *valuesSorter) Less(i, j int) bool { if s.strings == nil { return valueSortLess(s.values[i], s.values[j]) } return s.strings[i] < s.strings[j] } // sortValues is a sort function that handles both native types and any type that // can be converted to error or Stringer. Other inputs are sorted according to // their Value.String() value to ensure display stability. func sortValues(values []reflect.Value, cs *ConfigState) { if len(values) == 0 { return } sort.Sort(newValuesSorter(values, cs)) }
vendor/github.com/davecgh/go-spew/spew/common.go
0
https://github.com/hashicorp/terraform/commit/d6a586709cf8eee53b46b56bcf00fa7fa44d6441
[ 0.00040974828880280256, 0.00017782161012291908, 0.00016305682947859168, 0.00017016289348248392, 0.00003995268343714997 ]
{ "id": 4, "code_window": [ "\tc.StateCalled = true\n", "\treturn c.StateState\n", "}\n", "\n", "func (c *MockEvalContext) InstanceExpander() *instances.Expander {\n", "\tc.InstanceExpanderCalled = true\n", "\treturn c.InstanceExpanderExpander\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "func (c *MockEvalContext) RefreshState() *states.SyncState {\n", "\tc.RefreshStateCalled = true\n", "\treturn c.RefreshStateState\n", "}\n", "\n" ], "file_path": "terraform/eval_context_mock.go", "type": "add", "edit_start_line_idx": 340 }
package terraform import ( "github.com/hashicorp/hcl/v2" "github.com/hashicorp/terraform/addrs" "github.com/hashicorp/terraform/configs/configschema" "github.com/hashicorp/terraform/instances" "github.com/hashicorp/terraform/lang" "github.com/hashicorp/terraform/plans" "github.com/hashicorp/terraform/providers" "github.com/hashicorp/terraform/provisioners" "github.com/hashicorp/terraform/states" "github.com/hashicorp/terraform/tfdiags" "github.com/zclconf/go-cty/cty" ) // EvalContext is the interface that is given to eval nodes to execute. type EvalContext interface { // Stopped returns a channel that is closed when evaluation is stopped // via Terraform.Context.Stop() Stopped() <-chan struct{} // Path is the current module path. Path() addrs.ModuleInstance // Hook is used to call hook methods. The callback is called for each // hook and should return the hook action to take and the error. Hook(func(Hook) (HookAction, error)) error // Input is the UIInput object for interacting with the UI. Input() UIInput // InitProvider initializes the provider with the given address, and returns // the implementation of the resource provider or an error. // // It is an error to initialize the same provider more than once. This // method will panic if the module instance address of the given provider // configuration does not match the Path() of the EvalContext. InitProvider(addr addrs.AbsProviderConfig) (providers.Interface, error) // Provider gets the provider instance with the given address (already // initialized) or returns nil if the provider isn't initialized. // // This method expects an _absolute_ provider configuration address, since // resources in one module are able to use providers from other modules. // InitProvider must've been called on the EvalContext of the module // that owns the given provider before calling this method. Provider(addrs.AbsProviderConfig) providers.Interface // ProviderSchema retrieves the schema for a particular provider, which // must have already been initialized with InitProvider. // // This method expects an _absolute_ provider configuration address, since // resources in one module are able to use providers from other modules. ProviderSchema(addrs.AbsProviderConfig) *ProviderSchema // CloseProvider closes provider connections that aren't needed anymore. // // This method will panic if the module instance address of the given // provider configuration does not match the Path() of the EvalContext. CloseProvider(addrs.AbsProviderConfig) error // ConfigureProvider configures the provider with the given // configuration. This is a separate context call because this call // is used to store the provider configuration for inheritance lookups // with ParentProviderConfig(). // // This method will panic if the module instance address of the given // provider configuration does not match the Path() of the EvalContext. ConfigureProvider(addrs.AbsProviderConfig, cty.Value) tfdiags.Diagnostics // ProviderInput and SetProviderInput are used to configure providers // from user input. // // These methods will panic if the module instance address of the given // provider configuration does not match the Path() of the EvalContext. ProviderInput(addrs.AbsProviderConfig) map[string]cty.Value SetProviderInput(addrs.AbsProviderConfig, map[string]cty.Value) // InitProvisioner initializes the provisioner with the given name. // It is an error to initialize the same provisioner more than once. InitProvisioner(string) error // Provisioner gets the provisioner instance with the given name (already // initialized) or returns nil if the provisioner isn't initialized. Provisioner(string) provisioners.Interface // ProvisionerSchema retrieves the main configuration schema for a // particular provisioner, which must have already been initialized with // InitProvisioner. ProvisionerSchema(string) *configschema.Block // CloseProvisioner closes provisioner connections that aren't needed // anymore. CloseProvisioner(string) error // EvaluateBlock takes the given raw configuration block and associated // schema and evaluates it to produce a value of an object type that // conforms to the implied type of the schema. // // The "self" argument is optional. If given, it is the referenceable // address that the name "self" should behave as an alias for when // evaluating. Set this to nil if the "self" object should not be available. // // The "key" argument is also optional. If given, it is the instance key // of the current object within the multi-instance container it belongs // to. For example, on a resource block with "count" set this should be // set to a different addrs.IntKey for each instance created from that // block. Set this to addrs.NoKey if not appropriate. // // The returned body is an expanded version of the given body, with any // "dynamic" blocks replaced with zero or more static blocks. This can be // used to extract correct source location information about attributes of // the returned object value. EvaluateBlock(body hcl.Body, schema *configschema.Block, self addrs.Referenceable, keyData InstanceKeyEvalData) (cty.Value, hcl.Body, tfdiags.Diagnostics) // EvaluateExpr takes the given HCL expression and evaluates it to produce // a value. // // The "self" argument is optional. If given, it is the referenceable // address that the name "self" should behave as an alias for when // evaluating. Set this to nil if the "self" object should not be available. EvaluateExpr(expr hcl.Expression, wantType cty.Type, self addrs.Referenceable) (cty.Value, tfdiags.Diagnostics) // EvaluationScope returns a scope that can be used to evaluate reference // addresses in this context. EvaluationScope(self addrs.Referenceable, keyData InstanceKeyEvalData) *lang.Scope // SetModuleCallArguments defines values for the variables of a particular // child module call. // // Calling this function multiple times has merging behavior, keeping any // previously-set keys that are not present in the new map. SetModuleCallArguments(addrs.ModuleCallInstance, map[string]cty.Value) // GetVariableValue returns the value provided for the input variable with // the given address, or cty.DynamicVal if the variable hasn't been assigned // a value yet. // // Most callers should deal with variable values only indirectly via // EvaluationScope and the other expression evaluation functions, but // this is provided because variables tend to be evaluated outside of // the context of the module they belong to and so we sometimes need to // override the normal expression evaluation behavior. GetVariableValue(addr addrs.AbsInputVariableInstance) cty.Value // Changes returns the writer object that can be used to write new proposed // changes into the global changes set. Changes() *plans.ChangesSync // State returns a wrapper object that provides safe concurrent access to // the global state. State() *states.SyncState // InstanceExpander returns a helper object for tracking the expansion of // graph nodes during the plan phase in response to "count" and "for_each" // arguments. // // The InstanceExpander is a global object that is shared across all of the // EvalContext objects for a given configuration. InstanceExpander() *instances.Expander // WithPath returns a copy of the context with the internal path set to the // path argument. WithPath(path addrs.ModuleInstance) EvalContext }
terraform/eval_context.go
1
https://github.com/hashicorp/terraform/commit/d6a586709cf8eee53b46b56bcf00fa7fa44d6441
[ 0.9117540717124939, 0.09913652390241623, 0.00016311158833559602, 0.0001837702002376318, 0.27146053314208984 ]
{ "id": 4, "code_window": [ "\tc.StateCalled = true\n", "\treturn c.StateState\n", "}\n", "\n", "func (c *MockEvalContext) InstanceExpander() *instances.Expander {\n", "\tc.InstanceExpanderCalled = true\n", "\treturn c.InstanceExpanderExpander\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "func (c *MockEvalContext) RefreshState() *states.SyncState {\n", "\tc.RefreshStateCalled = true\n", "\treturn c.RefreshStateState\n", "}\n", "\n" ], "file_path": "terraform/eval_context_mock.go", "type": "add", "edit_start_line_idx": 340 }
resource "aws_instance" "foo" {} resource "aws_instance" "web" { count = "${aws_instance.foo.bar}" } resource "aws_load_balancer" "weblb" { members = "${aws_instance.web.*.id}" }
terraform/testdata/graph-count-var-resource/main.tf
0
https://github.com/hashicorp/terraform/commit/d6a586709cf8eee53b46b56bcf00fa7fa44d6441
[ 0.00016918248729780316, 0.00016918248729780316, 0.00016918248729780316, 0.00016918248729780316, 0 ]
{ "id": 4, "code_window": [ "\tc.StateCalled = true\n", "\treturn c.StateState\n", "}\n", "\n", "func (c *MockEvalContext) InstanceExpander() *instances.Expander {\n", "\tc.InstanceExpanderCalled = true\n", "\treturn c.InstanceExpanderExpander\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "func (c *MockEvalContext) RefreshState() *states.SyncState {\n", "\tc.RefreshStateCalled = true\n", "\treturn c.RefreshStateState\n", "}\n", "\n" ], "file_path": "terraform/eval_context_mock.go", "type": "add", "edit_start_line_idx": 340 }
package objchange import ( "github.com/hashicorp/terraform/configs/configschema" "github.com/zclconf/go-cty/cty" ) // NormalizeObjectFromLegacySDK takes an object that may have been generated // by the legacy Terraform SDK (i.e. returned from a provider with the // LegacyTypeSystem opt-out set) and does its best to normalize it for the // assumptions we would normally enforce if the provider had not opted out. // // In particular, this function guarantees that a value representing a nested // block will never itself be unknown or null, instead representing that as // a non-null value that may contain null/unknown values. // // The input value must still conform to the implied type of the given schema, // or else this function may produce garbage results or panic. This is usually // okay because type consistency is enforced when deserializing the value // returned from the provider over the RPC wire protocol anyway. func NormalizeObjectFromLegacySDK(val cty.Value, schema *configschema.Block) cty.Value { if val == cty.NilVal || val.IsNull() { // This should never happen in reasonable use, but we'll allow it // and normalize to a null of the expected type rather than panicking // below. return cty.NullVal(schema.ImpliedType()) } vals := make(map[string]cty.Value) for name := range schema.Attributes { // No normalization for attributes, since them being type-conformant // is all that we require. vals[name] = val.GetAttr(name) } for name, blockS := range schema.BlockTypes { lv := val.GetAttr(name) // Legacy SDK never generates dynamically-typed attributes and so our // normalization code doesn't deal with them, but we need to make sure // we still pass them through properly so that we don't interfere with // objects generated by other SDKs. if ty := blockS.Block.ImpliedType(); ty.HasDynamicTypes() { vals[name] = lv continue } switch blockS.Nesting { case configschema.NestingSingle, configschema.NestingGroup: if lv.IsKnown() { if lv.IsNull() && blockS.Nesting == configschema.NestingGroup { vals[name] = blockS.EmptyValue() } else { vals[name] = NormalizeObjectFromLegacySDK(lv, &blockS.Block) } } else { vals[name] = unknownBlockStub(&blockS.Block) } case configschema.NestingList: switch { case !lv.IsKnown(): vals[name] = cty.ListVal([]cty.Value{unknownBlockStub(&blockS.Block)}) case lv.IsNull() || lv.LengthInt() == 0: vals[name] = cty.ListValEmpty(blockS.Block.ImpliedType()) default: subVals := make([]cty.Value, 0, lv.LengthInt()) for it := lv.ElementIterator(); it.Next(); { _, subVal := it.Element() subVals = append(subVals, NormalizeObjectFromLegacySDK(subVal, &blockS.Block)) } vals[name] = cty.ListVal(subVals) } case configschema.NestingSet: switch { case !lv.IsKnown(): vals[name] = cty.SetVal([]cty.Value{unknownBlockStub(&blockS.Block)}) case lv.IsNull() || lv.LengthInt() == 0: vals[name] = cty.SetValEmpty(blockS.Block.ImpliedType()) default: subVals := make([]cty.Value, 0, lv.LengthInt()) for it := lv.ElementIterator(); it.Next(); { _, subVal := it.Element() subVals = append(subVals, NormalizeObjectFromLegacySDK(subVal, &blockS.Block)) } vals[name] = cty.SetVal(subVals) } default: // The legacy SDK doesn't support NestingMap, so we just assume // maps are always okay. (If not, we would've detected and returned // an error to the user before we got here.) vals[name] = lv } } return cty.ObjectVal(vals) } // unknownBlockStub constructs an object value that approximates an unknown // block by producing a known block object with all of its leaf attribute // values set to unknown. // // Blocks themselves cannot be unknown, so if the legacy SDK tries to return // such a thing, we'll use this result instead. This convention mimics how // the dynamic block feature deals with being asked to iterate over an unknown // value, because our value-checking functions already accept this convention // as a special case. func unknownBlockStub(schema *configschema.Block) cty.Value { vals := make(map[string]cty.Value) for name, attrS := range schema.Attributes { vals[name] = cty.UnknownVal(attrS.Type) } for name, blockS := range schema.BlockTypes { switch blockS.Nesting { case configschema.NestingSingle, configschema.NestingGroup: vals[name] = unknownBlockStub(&blockS.Block) case configschema.NestingList: // In principle we may be expected to produce a tuple value here, // if there are any dynamically-typed attributes in our nested block, // but the legacy SDK doesn't support that, so we just assume it'll // never be necessary to normalize those. (Incorrect usage in any // other SDK would be caught and returned as an error before we // get here.) vals[name] = cty.ListVal([]cty.Value{unknownBlockStub(&blockS.Block)}) case configschema.NestingSet: vals[name] = cty.SetVal([]cty.Value{unknownBlockStub(&blockS.Block)}) case configschema.NestingMap: // A nesting map can never be unknown since we then wouldn't know // what the keys are. (Legacy SDK doesn't support NestingMap anyway, // so this should never arise.) vals[name] = cty.MapValEmpty(blockS.Block.ImpliedType()) } } return cty.ObjectVal(vals) }
plans/objchange/normalize_obj.go
0
https://github.com/hashicorp/terraform/commit/d6a586709cf8eee53b46b56bcf00fa7fa44d6441
[ 0.0001739229919621721, 0.0001697664993116632, 0.0001639629917917773, 0.00016972243611235172, 0.0000025572057893441524 ]
{ "id": 4, "code_window": [ "\tc.StateCalled = true\n", "\treturn c.StateState\n", "}\n", "\n", "func (c *MockEvalContext) InstanceExpander() *instances.Expander {\n", "\tc.InstanceExpanderCalled = true\n", "\treturn c.InstanceExpanderExpander\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "func (c *MockEvalContext) RefreshState() *states.SyncState {\n", "\tc.RefreshStateCalled = true\n", "\treturn c.RefreshStateState\n", "}\n", "\n" ], "file_path": "terraform/eval_context_mock.go", "type": "add", "edit_start_line_idx": 340 }
// +build !appengine package msgpack import ( "unsafe" ) // bytesToString converts byte slice to string. func bytesToString(b []byte) string { //nolint:deadcode,unused return *(*string)(unsafe.Pointer(&b)) } // stringToBytes converts string to byte slice. func stringToBytes(s string) []byte { return *(*[]byte)(unsafe.Pointer( &struct { string Cap int }{s, len(s)}, )) }
vendor/github.com/vmihailenco/msgpack/v4/unsafe.go
0
https://github.com/hashicorp/terraform/commit/d6a586709cf8eee53b46b56bcf00fa7fa44d6441
[ 0.0003134869912173599, 0.00022125219402369112, 0.0001714761892799288, 0.00017879338702186942, 0.00006528822996187955 ]
{ "id": 0, "code_window": [ "<!-- END STRIP_FOR_RELEASE -->\n", "\n", "<!-- END MUNGE: UNVERSIONED_WARNING -->\n", "\n", "---\n", "assignees:\n", "- asridharan\n", "- brendandburns\n", "- fgrzadkowski\n", "\n", "---\n", "\n", "**Stop. This guide has been superseded by [Minikube](https://github.com/kubernetes/minikube) which is the recommended method of running Kubernetes on your local machine.**\n", "\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/devel/local-cluster/docker.md", "type": "replace", "edit_start_line_idx": 29 }
<!-- 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. Documentation for other releases can be found at [releases.k8s.io](http://releases.k8s.io). </strong> -- <!-- END STRIP_FOR_RELEASE --> <!-- END MUNGE: UNVERSIONED_WARNING --> --- assignees: - asridharan - brendandburns - fgrzadkowski --- **Stop. This guide has been superseded by [Minikube](https://github.com/kubernetes/minikube) which is the recommended method of running Kubernetes on your local machine.** The following instructions show you how to set up a simple, single node Kubernetes cluster using Docker. Here's a diagram of what the final result will look like: ![Kubernetes Single Node on Docker](../../getting-started-guides/k8s-singlenode-docker.png) * TOC {:toc} ## Prerequisites **Note: These steps have not been tested with the [Docker For Mac or Docker For Windows beta programs](https://blog.docker.com/2016/03/docker-for-mac-windows-beta/).** 1. You need to have Docker version >= "1.10" installed on the machine. 2. Enable mount propagation. Hyperkube is running in a container which has to mount volumes for other containers, for example in case of persistent storage. The required steps depend on the init system. In case of **systemd**, change MountFlags in the Docker unit file to shared. ```shell DOCKER_CONF=$(systemctl cat docker | head -1 | awk '{print $2}') sed -i.bak 's/^\(MountFlags=\).*/\1shared/' $DOCKER_CONF systemctl daemon-reload systemctl restart docker ``` **Otherwise**, manually set the mount point used by Hyperkube to be shared: ```shell mkdir -p /var/lib/kubelet mount --bind /var/lib/kubelet /var/lib/kubelet mount --make-shared /var/lib/kubelet ``` ### Run it 1. Decide which Kubernetes version to use. Set the `${K8S_VERSION}` variable to a version of Kubernetes >= "v1.2.0". If you'd like to use the current **stable** version of Kubernetes, run the following: ```sh export K8S_VERSION=$(curl -sS https://storage.googleapis.com/kubernetes-release/release/stable.txt) ``` and for the **latest** available version (including unstable releases): ```sh export K8S_VERSION=$(curl -sS https://storage.googleapis.com/kubernetes-release/release/latest.txt) ``` 2. Start Hyperkube ```shell export ARCH=amd64 docker run -d \ --volume=/sys:/sys:rw \ --volume=/var/lib/docker/:/var/lib/docker:rw \ --volume=/var/lib/kubelet/:/var/lib/kubelet:rw,shared \ --volume=/var/run:/var/run:rw \ --net=host \ --pid=host \ --privileged \ --name=kubelet \ gcr.io/google_containers/hyperkube-${ARCH}:${K8S_VERSION} \ /hyperkube kubelet \ --hostname-override=127.0.0.1 \ --api-servers=http://localhost:8080 \ --config=/etc/kubernetes/manifests \ --cluster-dns=10.0.0.10 \ --cluster-domain=cluster.local \ --allow-privileged --v=2 ``` > Note that `--cluster-dns` and `--cluster-domain` is used to deploy dns, feel free to discard them if dns is not needed. > If you would like to mount an external device as a volume, add `--volume=/dev:/dev` to the command above. It may however, cause some problems described in [#18230](https://github.com/kubernetes/kubernetes/issues/18230) > Architectures other than `amd64` are experimental and sometimes unstable, but feel free to try them out! Valid values: `arm`, `arm64` and `ppc64le`. ARM is available with Kubernetes version `v1.3.0-alpha.2` and higher. ARM 64-bit and PowerPC 64 little-endian are available with `v1.3.0-alpha.3` and higher. Track progress on multi-arch support [here](https://github.com/kubernetes/kubernetes/issues/17981) > If you are behind a proxy, you need to pass the proxy setup to curl in the containers to pull the certificates. Create a .curlrc under /root folder (because the containers are running as root) with the following line: ``` proxy = <your_proxy_server>:<port> ``` This actually runs the kubelet, which in turn runs a [pod](http://kubernetes.io/docs/user-guide/pods/) that contains the other master components. ** **SECURITY WARNING** ** services exposed via Kubernetes using Hyperkube are available on the host node's public network interface / IP address. Because of this, this guide is not suitable for any host node/server that is directly internet accessible. Refer to [#21735](https://github.com/kubernetes/kubernetes/issues/21735) for addtional info. ### Download `kubectl` At this point you should have a running Kubernetes cluster. You can test it out by downloading the kubectl binary for `${K8S_VERSION}` (in this example: `{{page.version}}.0`). Downloads: - `linux/amd64`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/linux/amd64/kubectl - `linux/386`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/linux/386/kubectl - `linux/arm`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/linux/arm/kubectl - `linux/arm64`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/linux/arm64/kubectl - `linux/ppc64le`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/linux/ppc64le/kubectl - `OS X/amd64`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/darwin/amd64/kubectl - `OS X/386`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/darwin/386/kubectl - `windows/amd64`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/windows/amd64/kubectl.exe - `windows/386`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/windows/386/kubectl.exe The generic download path is: ``` http://storage.googleapis.com/kubernetes-release/release/${K8S_VERSION}/bin/${GOOS}/${GOARCH}/${K8S_BINARY} ``` An example install with `linux/amd64`: ``` curl -sSL "https://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/linux/amd64/kubectl" > /usr/bin/kubectl chmod +x /usr/bin/kubectl ``` On OS X, to make the API server accessible locally, setup a ssh tunnel. ```shell docker-machine ssh `docker-machine active` -N -L 8080:localhost:8080 ``` Setting up a ssh tunnel is applicable to remote docker hosts as well. (Optional) Create kubernetes cluster configuration: ```shell kubectl config set-cluster test-doc --server=http://localhost:8080 kubectl config set-context test-doc --cluster=test-doc kubectl config use-context test-doc ``` ### Test it out List the nodes in your cluster by running: ```shell kubectl get nodes ``` This should print: ```shell NAME STATUS AGE 127.0.0.1 Ready 1h ``` ### Run an application ```shell kubectl run nginx --image=nginx --port=80 ``` Now run `docker ps` you should see nginx running. You may need to wait a few minutes for the image to get pulled. ### Expose it as a service ```shell kubectl expose deployment nginx --port=80 ``` Run the following command to obtain the cluster local IP of this service we just created: ```shell{% raw %} ip=$(kubectl get svc nginx --template={{.spec.clusterIP}}) echo $ip {% endraw %}``` Hit the webserver with this IP: ```shell{% raw %} curl $ip {% endraw %}``` On OS X, since docker is running inside a VM, run the following command instead: ```shell docker-machine ssh `docker-machine active` curl $ip ``` ### Turning down your cluster 1\. Delete the nginx service and deployment: If you plan on re-creating your nginx deployment and service you will need to clean it up. ```shell kubectl delete service,deployments nginx ``` 2\. Delete all the containers including the kubelet: ```shell docker rm -f kubelet docker rm -f `docker ps | grep k8s | awk '{print $1}'` ``` 3\. Cleanup the filesystem: On OS X, first ssh into the docker VM: ```shell docker-machine ssh `docker-machine active` ``` ```shell grep /var/lib/kubelet /proc/mounts | awk '{print $2}' | sudo xargs -n1 umount sudo rm -rf /var/lib/kubelet ``` ### Troubleshooting #### Node is in `NotReady` state If you see your node as `NotReady` it's possible that your OS does not have memcg enabled. 1. Your kernel should support memory accounting. Ensure that the following configs are turned on in your linux kernel: ```shell CONFIG_RESOURCE_COUNTERS=y CONFIG_MEMCG=y ``` 2. Enable the memory accounting in the kernel, at boot, as command line parameters as follows: ```shell GRUB_CMDLINE_LINUX="cgroup_enable=memory=1" ``` NOTE: The above is specifically for GRUB2. You can check the command line parameters passed to your kernel by looking at the output of /proc/cmdline: ```shell $ cat /proc/cmdline BOOT_IMAGE=/boot/vmlinuz-3.18.4-aufs root=/dev/sda5 ro cgroup_enable=memory=1 ``` ## Support Level IaaS Provider | Config. Mgmt | OS | Networking | Conforms | Support Level -------------------- | ------------ | ------ | ---------- | ---------| ---------------------------- Docker Single Node | custom | N/A | local | | Project ([@brendandburns](https://github.com/brendandburns)) ## Further reading Please see the [Kubernetes docs](http://kubernetes.io/docs) for more details on administering and using a Kubernetes cluster. <!-- BEGIN MUNGE: GENERATED_ANALYTICS --> [![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/devel/local-cluster/docker.md?pixel)]() <!-- END MUNGE: GENERATED_ANALYTICS -->
docs/devel/local-cluster/docker.md
1
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.022455761209130287, 0.001108467229641974, 0.0001619755057618022, 0.00020499282982200384, 0.00395092973485589 ]
{ "id": 0, "code_window": [ "<!-- END STRIP_FOR_RELEASE -->\n", "\n", "<!-- END MUNGE: UNVERSIONED_WARNING -->\n", "\n", "---\n", "assignees:\n", "- asridharan\n", "- brendandburns\n", "- fgrzadkowski\n", "\n", "---\n", "\n", "**Stop. This guide has been superseded by [Minikube](https://github.com/kubernetes/minikube) which is the recommended method of running Kubernetes on your local machine.**\n", "\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/devel/local-cluster/docker.md", "type": "replace", "edit_start_line_idx": 29 }
/* 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 unversioned import ( api "k8s.io/kubernetes/pkg/api" registered "k8s.io/kubernetes/pkg/apimachinery/registered" restclient "k8s.io/kubernetes/pkg/client/restclient" ) type BatchInterface interface { GetRESTClient() *restclient.RESTClient JobsGetter ScheduledJobsGetter } // BatchClient is used to interact with features provided by the Batch group. type BatchClient struct { *restclient.RESTClient } func (c *BatchClient) Jobs(namespace string) JobInterface { return newJobs(c, namespace) } func (c *BatchClient) ScheduledJobs(namespace string) ScheduledJobInterface { return newScheduledJobs(c, namespace) } // NewForConfig creates a new BatchClient for the given config. func NewForConfig(c *restclient.Config) (*BatchClient, error) { config := *c if err := setConfigDefaults(&config); err != nil { return nil, err } client, err := restclient.RESTClientFor(&config) if err != nil { return nil, err } return &BatchClient{client}, nil } // NewForConfigOrDie creates a new BatchClient for the given config and // panics if there is an error in the config. func NewForConfigOrDie(c *restclient.Config) *BatchClient { client, err := NewForConfig(c) if err != nil { panic(err) } return client } // New creates a new BatchClient for the given RESTClient. func New(c *restclient.RESTClient) *BatchClient { return &BatchClient{c} } func setConfigDefaults(config *restclient.Config) error { // if batch group is not registered, return an error g, err := registered.Group("batch") if err != nil { return err } config.APIPath = "/apis" if config.UserAgent == "" { config.UserAgent = restclient.DefaultKubernetesUserAgent() } // TODO: Unconditionally set the config.Version, until we fix the config. //if config.Version == "" { copyGroupVersion := g.GroupVersion config.GroupVersion = &copyGroupVersion //} config.NegotiatedSerializer = api.Codecs if config.QPS == 0 { config.QPS = 5 } if config.Burst == 0 { config.Burst = 10 } return nil } // GetRESTClient returns a RESTClient that is used to communicate // with API server by this client implementation. func (c *BatchClient) GetRESTClient() *restclient.RESTClient { if c == nil { return nil } return c.RESTClient }
pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/batch_client.go
0
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.0011721088085323572, 0.0002633407711982727, 0.00016158292419277132, 0.00016615993808954954, 0.0002878054801840335 ]
{ "id": 0, "code_window": [ "<!-- END STRIP_FOR_RELEASE -->\n", "\n", "<!-- END MUNGE: UNVERSIONED_WARNING -->\n", "\n", "---\n", "assignees:\n", "- asridharan\n", "- brendandburns\n", "- fgrzadkowski\n", "\n", "---\n", "\n", "**Stop. This guide has been superseded by [Minikube](https://github.com/kubernetes/minikube) which is the recommended method of running Kubernetes on your local machine.**\n", "\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/devel/local-cluster/docker.md", "type": "replace", "edit_start_line_idx": 29 }
/* 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 format import ( "fmt" "sort" "strings" "k8s.io/kubernetes/pkg/api" ) // ResourceList returns a string representation of a resource list in a human readable format. func ResourceList(resources api.ResourceList) string { resourceStrings := make([]string, 0, len(resources)) for key, value := range resources { resourceStrings = append(resourceStrings, fmt.Sprintf("%v=%v", key, value.String())) } // sort the results for consistent log output sort.Strings(resourceStrings) return strings.Join(resourceStrings, ",") }
pkg/kubelet/util/format/resources.go
0
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.0001800396858016029, 0.0001754155382514, 0.00017056673823390156, 0.00017552784993313253, 0.0000036425872167455964 ]
{ "id": 0, "code_window": [ "<!-- END STRIP_FOR_RELEASE -->\n", "\n", "<!-- END MUNGE: UNVERSIONED_WARNING -->\n", "\n", "---\n", "assignees:\n", "- asridharan\n", "- brendandburns\n", "- fgrzadkowski\n", "\n", "---\n", "\n", "**Stop. This guide has been superseded by [Minikube](https://github.com/kubernetes/minikube) which is the recommended method of running Kubernetes on your local machine.**\n", "\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/devel/local-cluster/docker.md", "type": "replace", "edit_start_line_idx": 29 }
/* 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 unversioned import ( "encoding/json" "net/http" "net/http/httptest" "net/url" "path" "reflect" "strconv" "strings" "testing" "time" cadvisorapi "github.com/google/cadvisor/info/v1" cadvisorapitest "github.com/google/cadvisor/info/v1/test" ) func testHTTPContainerInfoGetter( req *cadvisorapi.ContainerInfoRequest, cinfo *cadvisorapi.ContainerInfo, podID string, containerID string, status int, t *testing.T, ) { expectedPath := "/stats" if len(podID) > 0 && len(containerID) > 0 { expectedPath = path.Join(expectedPath, podID, containerID) } ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if status != 0 { w.WriteHeader(status) } if strings.TrimRight(r.URL.Path, "/") != strings.TrimRight(expectedPath, "/") { t.Fatalf("Received request to an invalid path. Should be %v. got %v", expectedPath, r.URL.Path) } var receivedReq cadvisorapi.ContainerInfoRequest err := json.NewDecoder(r.Body).Decode(&receivedReq) if err != nil { t.Fatal(err) } // Note: This will not make a deep copy of req. // So changing req after Get*Info would be a race. expectedReq := req // Fill any empty fields with default value if !expectedReq.Equals(receivedReq) { t.Errorf("received wrong request") } err = json.NewEncoder(w).Encode(cinfo) if err != nil { t.Fatal(err) } })) defer ts.Close() hostURL, err := url.Parse(ts.URL) if err != nil { t.Fatal(err) } parts := strings.Split(hostURL.Host, ":") port, err := strconv.Atoi(parts[1]) if err != nil { t.Fatal(err) } containerInfoGetter := &HTTPContainerInfoGetter{ Client: http.DefaultClient, Port: port, } var receivedContainerInfo *cadvisorapi.ContainerInfo if len(podID) > 0 && len(containerID) > 0 { receivedContainerInfo, err = containerInfoGetter.GetContainerInfo(parts[0], podID, containerID, req) } else { receivedContainerInfo, err = containerInfoGetter.GetRootInfo(parts[0], req) } if status == 0 || status == http.StatusOK { if err != nil { t.Errorf("received unexpected error: %v", err) } if !receivedContainerInfo.Eq(cinfo) { t.Error("received unexpected container info") } } else { if err == nil { t.Error("did not receive expected error.") } } } func TestHTTPContainerInfoGetterGetContainerInfoSuccessfully(t *testing.T) { req := &cadvisorapi.ContainerInfoRequest{ NumStats: 10, } cinfo := cadvisorapitest.GenerateRandomContainerInfo( "dockerIDWhichWillNotBeChecked", // docker ID 2, // Number of cores req, 1*time.Second, ) testHTTPContainerInfoGetter(req, cinfo, "somePodID", "containerNameInK8S", 0, t) } func TestHTTPContainerInfoGetterGetRootInfoSuccessfully(t *testing.T) { req := &cadvisorapi.ContainerInfoRequest{ NumStats: 10, } cinfo := cadvisorapitest.GenerateRandomContainerInfo( "dockerIDWhichWillNotBeChecked", // docker ID 2, // Number of cores req, 1*time.Second, ) testHTTPContainerInfoGetter(req, cinfo, "", "", 0, t) } func TestHTTPContainerInfoGetterGetContainerInfoWithError(t *testing.T) { req := &cadvisorapi.ContainerInfoRequest{ NumStats: 10, } cinfo := cadvisorapitest.GenerateRandomContainerInfo( "dockerIDWhichWillNotBeChecked", // docker ID 2, // Number of cores req, 1*time.Second, ) testHTTPContainerInfoGetter(req, cinfo, "somePodID", "containerNameInK8S", http.StatusNotFound, t) } func TestHTTPContainerInfoGetterGetRootInfoWithError(t *testing.T) { req := &cadvisorapi.ContainerInfoRequest{ NumStats: 10, } cinfo := cadvisorapitest.GenerateRandomContainerInfo( "dockerIDWhichWillNotBeChecked", // docker ID 2, // Number of cores req, 1*time.Second, ) testHTTPContainerInfoGetter(req, cinfo, "", "", http.StatusNotFound, t) } func TestHTTPGetMachineInfo(t *testing.T) { mspec := &cadvisorapi.MachineInfo{ NumCores: 4, MemoryCapacity: 2048, } ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { err := json.NewEncoder(w).Encode(mspec) if err != nil { t.Fatal(err) } })) defer ts.Close() hostURL, err := url.Parse(ts.URL) if err != nil { t.Fatal(err) } parts := strings.Split(hostURL.Host, ":") port, err := strconv.Atoi(parts[1]) if err != nil { t.Fatal(err) } containerInfoGetter := &HTTPContainerInfoGetter{ Client: http.DefaultClient, Port: port, } received, err := containerInfoGetter.GetMachineInfo(parts[0]) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(received, mspec) { t.Errorf("received wrong machine spec") } }
pkg/client/unversioned/containerinfo_test.go
0
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.00018610787810757756, 0.00017205034964717925, 0.00016495358431711793, 0.0001715630933176726, 0.000005752991000917973 ]
{ "id": 1, "code_window": [ "Here's a diagram of what the final result will look like:\n", "\n", "![Kubernetes Single Node on Docker](../../getting-started-guides/k8s-singlenode-docker.png)\n", "\n", "* TOC\n", "{:toc}\n", "\n", "## Prerequisites\n", "\n", "**Note: These steps have not been tested with the [Docker For Mac or Docker For Windows beta programs](https://blog.docker.com/2016/03/docker-for-mac-windows-beta/).**\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/devel/local-cluster/docker.md", "type": "replace", "edit_start_line_idx": 46 }
<!-- 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. Documentation for other releases can be found at [releases.k8s.io](http://releases.k8s.io). </strong> -- <!-- END STRIP_FOR_RELEASE --> <!-- END MUNGE: UNVERSIONED_WARNING --> --- assignees: - brendandburns - derekwaynecarr - jbeda --- did no Running Kubernetes with Vagrant (and VirtualBox) is an easy way to run/test/develop on your local machine (Linux, Mac OS X). * TOC {:toc} ### Prerequisites 1. Install latest version >= 1.7.4 of [Vagrant](http://www.vagrantup.com/downloads.html) 2. Install one of: 1. The latest version of [Virtual Box](https://www.virtualbox.org/wiki/Downloads) 2. [VMWare Fusion](https://www.vmware.com/products/fusion/) version 5 or greater as well as the appropriate [Vagrant VMWare Fusion provider](https://www.vagrantup.com/vmware) 3. [VMWare Workstation](https://www.vmware.com/products/workstation/) version 9 or greater as well as the [Vagrant VMWare Workstation provider](https://www.vagrantup.com/vmware) 4. [Parallels Desktop](https://www.parallels.com/products/desktop/) version 9 or greater as well as the [Vagrant Parallels provider](https://parallels.github.io/vagrant-parallels/) 5. libvirt with KVM and enable support of hardware virtualisation. [Vagrant-libvirt](https://github.com/pradels/vagrant-libvirt). For fedora provided official rpm, and possible to use `yum install vagrant-libvirt` ### Setup Setting up a cluster is as simple as running: ```sh export KUBERNETES_PROVIDER=vagrant curl -sS https://get.k8s.io | bash ``` Alternatively, you can download [Kubernetes release](https://github.com/kubernetes/kubernetes/releases) and extract the archive. To start your local cluster, open a shell and run: ```sh cd kubernetes export KUBERNETES_PROVIDER=vagrant ./cluster/kube-up.sh ``` The `KUBERNETES_PROVIDER` environment variable tells all of the various cluster management scripts which variant to use. If you forget to set this, the assumption is you are running on Google Compute Engine. By default, the Vagrant setup will create a single master VM (called kubernetes-master) and one node (called kubernetes-node-1). Each VM will take 1 GB, so make sure you have at least 2GB to 4GB of free memory (plus appropriate free disk space). If you'd like more than one node, set the `NUM_NODES` environment variable to the number you want: ```sh export NUM_NODES=3 ``` Vagrant will provision each machine in the cluster with all the necessary components to run Kubernetes. The initial setup can take a few minutes to complete on each machine. If you installed more than one Vagrant provider, Kubernetes will usually pick the appropriate one. However, you can override which one Kubernetes will use by setting the [`VAGRANT_DEFAULT_PROVIDER`](https://docs.vagrantup.com/v2/providers/default.html) environment variable: ```sh export VAGRANT_DEFAULT_PROVIDER=parallels export KUBERNETES_PROVIDER=vagrant ./cluster/kube-up.sh ``` By default, each VM in the cluster is running Fedora. To access the master or any node: ```sh vagrant ssh master vagrant ssh node-1 ``` If you are running more than one node, you can access the others by: ```sh vagrant ssh node-2 vagrant ssh node-3 ``` Each node in the cluster installs the docker daemon and the kubelet. The master node instantiates the Kubernetes master components as pods on the machine. To view the service status and/or logs on the kubernetes-master: ```console [vagrant@kubernetes-master ~] $ vagrant ssh master [vagrant@kubernetes-master ~] $ sudo su [root@kubernetes-master ~] $ systemctl status kubelet [root@kubernetes-master ~] $ journalctl -ru kubelet [root@kubernetes-master ~] $ systemctl status docker [root@kubernetes-master ~] $ journalctl -ru docker [root@kubernetes-master ~] $ tail -f /var/log/kube-apiserver.log [root@kubernetes-master ~] $ tail -f /var/log/kube-controller-manager.log [root@kubernetes-master ~] $ tail -f /var/log/kube-scheduler.log ``` To view the services on any of the nodes: ```console [vagrant@kubernetes-master ~] $ vagrant ssh node-1 [vagrant@kubernetes-master ~] $ sudo su [root@kubernetes-master ~] $ systemctl status kubelet [root@kubernetes-master ~] $ journalctl -ru kubelet [root@kubernetes-master ~] $ systemctl status docker [root@kubernetes-master ~] $ journalctl -ru docker ``` ### Interacting with your Kubernetes cluster with Vagrant. With your Kubernetes cluster up, you can manage the nodes in your cluster with the regular Vagrant commands. To push updates to new Kubernetes code after making source changes: ```sh ./cluster/kube-push.sh ``` To stop and then restart the cluster: ```sh vagrant halt ./cluster/kube-up.sh ``` To destroy the cluster: ```sh vagrant destroy ``` Once your Vagrant machines are up and provisioned, the first thing to do is to check that you can use the `kubectl.sh` script. You may need to build the binaries first, you can do this with `make` ```console $ ./cluster/kubectl.sh get nodes NAME LABELS 10.245.1.4 <none> 10.245.1.5 <none> 10.245.1.3 <none> ``` ### Authenticating with your master When using the vagrant provider in Kubernetes, the `cluster/kubectl.sh` script will cache your credentials in a `~/.kubernetes_vagrant_auth` file so you will not be prompted for them in the future. ```sh cat ~/.kubernetes_vagrant_auth ``` ```json { "User": "vagrant", "Password": "vagrant", "CAFile": "/home/k8s_user/.kubernetes.vagrant.ca.crt", "CertFile": "/home/k8s_user/.kubecfg.vagrant.crt", "KeyFile": "/home/k8s_user/.kubecfg.vagrant.key" } ``` You should now be set to use the `cluster/kubectl.sh` script. For example try to list the nodes that you have started with: ```sh ./cluster/kubectl.sh get nodes ``` ### Running containers Your cluster is running, you can list the nodes in your cluster: ```sh $ ./cluster/kubectl.sh get nodes NAME LABELS 10.245.2.4 <none> 10.245.2.3 <none> 10.245.2.2 <none> ``` Now start running some containers! You can now use any of the `cluster/kube-*.sh` commands to interact with your VM machines. Before starting a container there will be no pods, services and replication controllers. ```sh $ ./cluster/kubectl.sh get pods NAME READY STATUS RESTARTS AGE $ ./cluster/kubectl.sh get services NAME CLUSTER_IP EXTERNAL_IP PORT(S) SELECTOR AGE $ ./cluster/kubectl.sh get replicationcontrollers CONTROLLER CONTAINER(S) IMAGE(S) SELECTOR REPLICAS ``` Start a container running nginx with a replication controller and three replicas ```sh $ ./cluster/kubectl.sh run my-nginx --image=nginx --replicas=3 --port=80 ``` When listing the pods, you will see that three containers have been started and are in Waiting state: ```sh $ ./cluster/kubectl.sh get pods NAME READY STATUS RESTARTS AGE my-nginx-5kq0g 0/1 Pending 0 10s my-nginx-gr3hh 0/1 Pending 0 10s my-nginx-xql4j 0/1 Pending 0 10s ``` You need to wait for the provisioning to complete, you can monitor the nodes by doing: ```sh $ vagrant ssh node-1 -c 'sudo docker images' kubernetes-node-1: REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE <none> <none> 96864a7d2df3 26 hours ago 204.4 MB google/cadvisor latest e0575e677c50 13 days ago 12.64 MB kubernetes/pause latest 6c4579af347b 8 weeks ago 239.8 kB ``` Once the docker image for nginx has been downloaded, the container will start and you can list it: ```sh $ vagrant ssh node-1 -c 'sudo docker ps' kubernetes-node-1: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES dbe79bf6e25b nginx:latest "nginx" 21 seconds ago Up 19 seconds k8s--mynginx.8c5b8a3a--7813c8bd_-_3ffe_-_11e4_-_9036_-_0800279696e1.etcd--7813c8bd_-_3ffe_-_11e4_-_9036_-_0800279696e1--fcfa837f fa0e29c94501 kubernetes/pause:latest "/pause" 8 minutes ago Up 8 minutes 0.0.0.0:8080->80/tcp k8s--net.a90e7ce4--7813c8bd_-_3ffe_-_11e4_-_9036_-_0800279696e1.etcd--7813c8bd_-_3ffe_-_11e4_-_9036_-_0800279696e1--baf5b21b aa2ee3ed844a google/cadvisor:latest "/usr/bin/cadvisor" 38 minutes ago Up 38 minutes k8s--cadvisor.9e90d182--cadvisor_-_agent.file--4626b3a2 65a3a926f357 kubernetes/pause:latest "/pause" 39 minutes ago Up 39 minutes 0.0.0.0:4194->8080/tcp k8s--net.c5ba7f0e--cadvisor_-_agent.file--342fd561 ``` Going back to listing the pods, services and replicationcontrollers, you now have: ```sh $ ./cluster/kubectl.sh get pods NAME READY STATUS RESTARTS AGE my-nginx-5kq0g 1/1 Running 0 1m my-nginx-gr3hh 1/1 Running 0 1m my-nginx-xql4j 1/1 Running 0 1m $ ./cluster/kubectl.sh get services NAME CLUSTER_IP EXTERNAL_IP PORT(S) SELECTOR AGE $ ./cluster/kubectl.sh get replicationcontrollers CONTROLLER CONTAINER(S) IMAGE(S) SELECTOR REPLICAS AGE my-nginx my-nginx nginx run=my-nginx 3 1m ``` We did not start any services, hence there are none listed. But we see three replicas displayed properly. Learn about [running your first containers](http://kubernetes.io/docs/user-guide/simple-nginx/) application to learn how to create a service. You can already play with scaling the replicas with: ```sh $ ./cluster/kubectl.sh scale rc my-nginx --replicas=2 $ ./cluster/kubectl.sh get pods NAME READY STATUS RESTARTS AGE my-nginx-5kq0g 1/1 Running 0 2m my-nginx-gr3hh 1/1 Running 0 2m ``` Congratulations! ## Troubleshooting #### I keep downloading the same (large) box all the time! By default the Vagrantfile will download the box from S3. You can change this (and cache the box locally) by providing a name and an alternate URL when calling `kube-up.sh` ```sh export KUBERNETES_BOX_NAME=choose_your_own_name_for_your_kuber_box export KUBERNETES_BOX_URL=path_of_your_kuber_box export KUBERNETES_PROVIDER=vagrant ./cluster/kube-up.sh ``` #### I am getting timeouts when trying to curl the master from my host! During provision of the cluster, you may see the following message: ```sh Validating node-1 ............. Waiting for each node to be registered with cloud provider error: couldn't read version from server: Get https://10.245.1.2/api: dial tcp 10.245.1.2:443: i/o timeout ``` Some users have reported VPNs may prevent traffic from being routed to the host machine into the virtual machine network. To debug, first verify that the master is binding to the proper IP address: ```sh $ vagrant ssh master $ ifconfig | grep eth1 -C 2 eth1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 10.245.1.2 netmask 255.255.255.0 broadcast 10.245.1.255 ``` Then verify that your host machine has a network connection to a bridge that can serve that address: ```sh $ ifconfig | grep 10.245.1 -C 2 vboxnet5: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 10.245.1.1 netmask 255.255.255.0 broadcast 10.245.1.255 inet6 fe80::800:27ff:fe00:5 prefixlen 64 scopeid 0x20<link> ether 0a:00:27:00:00:05 txqueuelen 1000 (Ethernet) ``` If you do not see a response on your host machine, you will most likely need to connect your host to the virtual network created by the virtualization provider. If you do see a network, but are still unable to ping the machine, check if your VPN is blocking the request. #### I just created the cluster, but I am getting authorization errors! You probably have an incorrect ~/.kubernetes_vagrant_auth file for the cluster you are attempting to contact. ```sh rm ~/.kubernetes_vagrant_auth ``` After using kubectl.sh make sure that the correct credentials are set: ```sh cat ~/.kubernetes_vagrant_auth ``` ```json { "User": "vagrant", "Password": "vagrant" } ``` #### I just created the cluster, but I do not see my container running! If this is your first time creating the cluster, the kubelet on each node schedules a number of docker pull requests to fetch prerequisite images. This can take some time and as a result may delay your initial pod getting provisioned. #### I have brought Vagrant up but the nodes cannot validate! Log on to one of the nodes (`vagrant ssh node-1`) and inspect the salt minion log (`sudo cat /var/log/salt/minion`). #### I want to change the number of nodes! You can control the number of nodes that are instantiated via the environment variable `NUM_NODES` on your host machine. If you plan to work with replicas, we strongly encourage you to work with enough nodes to satisfy your largest intended replica size. If you do not plan to work with replicas, you can save some system resources by running with a single node. You do this, by setting `NUM_NODES` to 1 like so: ```sh export NUM_NODES=1 ``` #### I want my VMs to have more memory! You can control the memory allotted to virtual machines with the `KUBERNETES_MEMORY` environment variable. Just set it to the number of megabytes you would like the machines to have. For example: ```sh export KUBERNETES_MEMORY=2048 ``` If you need more granular control, you can set the amount of memory for the master and nodes independently. For example: ```sh export KUBERNETES_MASTER_MEMORY=1536 export KUBERNETES_NODE_MEMORY=2048 ``` #### I want to set proxy settings for my Kubernetes cluster boot strapping! If you are behind a proxy, you need to install vagrant proxy plugin and set the proxy settings by ```sh vagrant plugin install vagrant-proxyconf export VAGRANT_HTTP_PROXY=http://username:password@proxyaddr:proxyport export VAGRANT_HTTPS_PROXY=https://username:password@proxyaddr:proxyport ``` Optionally you can specify addresses to not proxy, for example ```sh export VAGRANT_NO_PROXY=127.0.0.1 ``` If you are using sudo to make kubernetes build for example make quick-release, you need run `sudo -E make quick-release` to pass the environment variables. #### I ran vagrant suspend and nothing works! `vagrant suspend` seems to mess up the network. This is not supported at this time. #### I want vagrant to sync folders via nfs! You can ensure that vagrant uses nfs to sync folders with virtual machines by setting the KUBERNETES_VAGRANT_USE_NFS environment variable to 'true'. nfs is faster than virtualbox or vmware's 'shared folders' and does not require guest additions. See the [vagrant docs](http://docs.vagrantup.com/v2/synced-folders/nfs.html) for details on configuring nfs on the host. This setting will have no effect on the libvirt provider, which uses nfs by default. For example: ```sh export KUBERNETES_VAGRANT_USE_NFS=true ``` <!-- BEGIN MUNGE: GENERATED_ANALYTICS --> [![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/devel/local-cluster/vagrant.md?pixel)]() <!-- END MUNGE: GENERATED_ANALYTICS -->
docs/devel/local-cluster/vagrant.md
1
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.001995071303099394, 0.00027071672957390547, 0.0001629744510864839, 0.00016855087596923113, 0.0003555479634087533 ]
{ "id": 1, "code_window": [ "Here's a diagram of what the final result will look like:\n", "\n", "![Kubernetes Single Node on Docker](../../getting-started-guides/k8s-singlenode-docker.png)\n", "\n", "* TOC\n", "{:toc}\n", "\n", "## Prerequisites\n", "\n", "**Note: These steps have not been tested with the [Docker For Mac or Docker For Windows beta programs](https://blog.docker.com/2016/03/docker-for-mac-windows-beta/).**\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/devel/local-cluster/docker.md", "type": "replace", "edit_start_line_idx": 46 }
/* 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 pod import ( "testing" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" ) func TestParsePodFullName(t *testing.T) { type nameTuple struct { Name string Namespace string } successfulCases := map[string]nameTuple{ "bar_foo": {Name: "bar", Namespace: "foo"}, "bar.org_foo.com": {Name: "bar.org", Namespace: "foo.com"}, "bar-bar_foo": {Name: "bar-bar", Namespace: "foo"}, } failedCases := []string{"barfoo", "bar_foo_foo", ""} for podFullName, expected := range successfulCases { name, namespace, err := kubecontainer.ParsePodFullName(podFullName) if err != nil { t.Errorf("unexpected error when parsing the full name: %v", err) continue } if name != expected.Name || namespace != expected.Namespace { t.Errorf("expected name %q, namespace %q; got name %q, namespace %q", expected.Name, expected.Namespace, name, namespace) } } for _, podFullName := range failedCases { _, _, err := kubecontainer.ParsePodFullName(podFullName) if err == nil { t.Errorf("expected error when parsing the full name, got none") } } }
pkg/kubelet/pod/mirror_client_test.go
0
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.0002369050052948296, 0.00018243142403662205, 0.0001683744485490024, 0.00017205948824994266, 0.000024566146748838946 ]
{ "id": 1, "code_window": [ "Here's a diagram of what the final result will look like:\n", "\n", "![Kubernetes Single Node on Docker](../../getting-started-guides/k8s-singlenode-docker.png)\n", "\n", "* TOC\n", "{:toc}\n", "\n", "## Prerequisites\n", "\n", "**Note: These steps have not been tested with the [Docker For Mac or Docker For Windows beta programs](https://blog.docker.com/2016/03/docker-for-mac-windows-beta/).**\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/devel/local-cluster/docker.md", "type": "replace", "edit_start_line_idx": 46 }
/* 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 openstack import ( "errors" "fmt" "io/ioutil" "path" "strings" "github.com/rackspace/gophercloud" "github.com/rackspace/gophercloud/openstack" "github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes" "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach" "github.com/rackspace/gophercloud/pagination" "github.com/golang/glog" ) // Attaches given cinder volume to the compute running kubelet func (os *OpenStack) AttachDisk(instanceID string, diskName string) (string, error) { disk, err := os.getVolume(diskName) if err != nil { return "", err } cClient, err := openstack.NewComputeV2(os.provider, gophercloud.EndpointOpts{ Region: os.region, }) if err != nil || cClient == nil { glog.Errorf("Unable to initialize nova client for region: %s", os.region) return "", err } if len(disk.Attachments) > 0 && disk.Attachments[0]["server_id"] != nil { if instanceID == disk.Attachments[0]["server_id"] { glog.V(4).Infof("Disk: %q is already attached to compute: %q", diskName, instanceID) return disk.ID, nil } else { errMsg := fmt.Sprintf("Disk %q is attached to a different compute: %q, should be detached before proceeding", diskName, disk.Attachments[0]["server_id"]) glog.Errorf(errMsg) return "", errors.New(errMsg) } } // add read only flag here if possible spothanis _, err = volumeattach.Create(cClient, instanceID, &volumeattach.CreateOpts{ VolumeID: disk.ID, }).Extract() if err != nil { glog.Errorf("Failed to attach %s volume to %s compute", diskName, instanceID) return "", err } glog.V(2).Infof("Successfully attached %s volume to %s compute", diskName, instanceID) return disk.ID, nil } // Detaches given cinder volume from the compute running kubelet func (os *OpenStack) DetachDisk(instanceID string, partialDiskId string) error { disk, err := os.getVolume(partialDiskId) if err != nil { return err } cClient, err := openstack.NewComputeV2(os.provider, gophercloud.EndpointOpts{ Region: os.region, }) if err != nil || cClient == nil { glog.Errorf("Unable to initialize nova client for region: %s", os.region) return err } if len(disk.Attachments) > 0 && disk.Attachments[0]["server_id"] != nil && instanceID == disk.Attachments[0]["server_id"] { // This is a blocking call and effects kubelet's performance directly. // We should consider kicking it out into a separate routine, if it is bad. err = volumeattach.Delete(cClient, instanceID, disk.ID).ExtractErr() if err != nil { glog.Errorf("Failed to delete volume %s from compute %s attached %v", disk.ID, instanceID, err) return err } glog.V(2).Infof("Successfully detached volume: %s from compute: %s", disk.ID, instanceID) } else { errMsg := fmt.Sprintf("Disk: %s has no attachments or is not attached to compute: %s", disk.Name, instanceID) glog.Errorf(errMsg) return errors.New(errMsg) } return nil } // Takes a partial/full disk id or diskname func (os *OpenStack) getVolume(diskName string) (volumes.Volume, error) { sClient, err := openstack.NewBlockStorageV1(os.provider, gophercloud.EndpointOpts{ Region: os.region, }) var volume volumes.Volume if err != nil || sClient == nil { glog.Errorf("Unable to initialize cinder client for region: %s", os.region) return volume, err } err = volumes.List(sClient, nil).EachPage(func(page pagination.Page) (bool, error) { vols, err := volumes.ExtractVolumes(page) if err != nil { glog.Errorf("Failed to extract volumes: %v", err) return false, err } else { for _, v := range vols { glog.V(4).Infof("%s %s %v", v.ID, v.Name, v.Attachments) if v.Name == diskName || strings.Contains(v.ID, diskName) { volume = v return true, nil } } } // if it reached here then no disk with the given name was found. errmsg := fmt.Sprintf("Unable to find disk: %s in region %s", diskName, os.region) return false, errors.New(errmsg) }) if err != nil { glog.Errorf("Error occured getting volume: %s", diskName) return volume, err } return volume, err } // Create a volume of given size (in GiB) func (os *OpenStack) CreateVolume(name string, size int, tags *map[string]string) (volumeName string, err error) { sClient, err := openstack.NewBlockStorageV1(os.provider, gophercloud.EndpointOpts{ Region: os.region, }) if err != nil || sClient == nil { glog.Errorf("Unable to initialize cinder client for region: %s", os.region) return "", err } opts := volumes.CreateOpts{ Name: name, Size: size, } if tags != nil { opts.Metadata = *tags } vol, err := volumes.Create(sClient, opts).Extract() if err != nil { glog.Errorf("Failed to create a %d GB volume: %v", size, err) return "", err } glog.Infof("Created volume %v", vol.ID) return vol.ID, err } // GetDevicePath returns the path of an attached block storage volume, specified by its id. func (os *OpenStack) GetDevicePath(diskId string) string { files, _ := ioutil.ReadDir("/dev/disk/by-id/") for _, f := range files { if strings.Contains(f.Name(), "virtio-") { devid_prefix := f.Name()[len("virtio-"):len(f.Name())] if strings.Contains(diskId, devid_prefix) { glog.V(4).Infof("Found disk attached as %q; full devicepath: %s\n", f.Name(), path.Join("/dev/disk/by-id/", f.Name())) return path.Join("/dev/disk/by-id/", f.Name()) } } } glog.Warningf("Failed to find device for the diskid: %q\n", diskId) return "" } func (os *OpenStack) DeleteVolume(volumeName string) error { sClient, err := openstack.NewBlockStorageV1(os.provider, gophercloud.EndpointOpts{ Region: os.region, }) if err != nil || sClient == nil { glog.Errorf("Unable to initialize cinder client for region: %s", os.region) return err } err = volumes.Delete(sClient, volumeName).ExtractErr() if err != nil { glog.Errorf("Cannot delete volume %s: %v", volumeName, err) } return err } // Get device path of attached volume to the compute running kubelet func (os *OpenStack) GetAttachmentDiskPath(instanceID string, diskName string) (string, error) { disk, err := os.getVolume(diskName) if err != nil { return "", err } if len(disk.Attachments) > 0 && disk.Attachments[0]["server_id"] != nil { if instanceID == disk.Attachments[0]["server_id"] { // Attachment[0]["device"] points to the device path // see http://developer.openstack.org/api-ref-blockstorage-v1.html return disk.Attachments[0]["device"].(string), nil } else { errMsg := fmt.Sprintf("Disk %q is attached to a different compute: %q, should be detached before proceeding", diskName, disk.Attachments[0]["server_id"]) glog.Errorf(errMsg) return "", errors.New(errMsg) } } return "", fmt.Errorf("volume %s is not attached to %s", diskName, instanceID) } // query if a volume is attached to a compute instance func (os *OpenStack) DiskIsAttached(diskName, instanceID string) (bool, error) { disk, err := os.getVolume(diskName) if err != nil { return false, err } if len(disk.Attachments) > 0 && disk.Attachments[0]["server_id"] != nil && instanceID == disk.Attachments[0]["server_id"] { return true, nil } return false, nil }
pkg/cloudprovider/providers/openstack/openstack_volumes.go
0
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.00017706191283650696, 0.00017069138993974775, 0.00016583861724939197, 0.00017055585340131074, 0.000002593365252323565 ]
{ "id": 1, "code_window": [ "Here's a diagram of what the final result will look like:\n", "\n", "![Kubernetes Single Node on Docker](../../getting-started-guides/k8s-singlenode-docker.png)\n", "\n", "* TOC\n", "{:toc}\n", "\n", "## Prerequisites\n", "\n", "**Note: These steps have not been tested with the [Docker For Mac or Docker For Windows beta programs](https://blog.docker.com/2016/03/docker-for-mac-windows-beta/).**\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/devel/local-cluster/docker.md", "type": "replace", "edit_start_line_idx": 46 }
// Extensions for Protocol Buffers to create more go like structures. // // Copyright (c) 2015, Vastech SA (PTY) LTD. All rights reserved. // http://github.com/gogo/protobuf/gogoproto // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package vanity import descriptor "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" func ForEachFile(files []*descriptor.FileDescriptorProto, f func(file *descriptor.FileDescriptorProto)) { for _, file := range files { f(file) } } func OnlyProto2(files []*descriptor.FileDescriptorProto) []*descriptor.FileDescriptorProto { outs := make([]*descriptor.FileDescriptorProto, 0, len(files)) for i, file := range files { if file.GetSyntax() == "proto3" { continue } outs = append(outs, files[i]) } return outs } func OnlyProto3(files []*descriptor.FileDescriptorProto) []*descriptor.FileDescriptorProto { outs := make([]*descriptor.FileDescriptorProto, 0, len(files)) for i, file := range files { if file.GetSyntax() != "proto3" { continue } outs = append(outs, files[i]) } return outs } func ForEachMessageInFiles(files []*descriptor.FileDescriptorProto, f func(msg *descriptor.DescriptorProto)) { for _, file := range files { ForEachMessage(file.MessageType, f) } } func ForEachMessage(msgs []*descriptor.DescriptorProto, f func(msg *descriptor.DescriptorProto)) { for _, msg := range msgs { f(msg) ForEachMessage(msg.NestedType, f) } } func ForEachFieldInFilesExcludingExtensions(files []*descriptor.FileDescriptorProto, f func(field *descriptor.FieldDescriptorProto)) { for _, file := range files { ForEachFieldExcludingExtensions(file.MessageType, f) } } func ForEachFieldInFiles(files []*descriptor.FileDescriptorProto, f func(field *descriptor.FieldDescriptorProto)) { for _, file := range files { for _, ext := range file.Extension { f(ext) } ForEachField(file.MessageType, f) } } func ForEachFieldExcludingExtensions(msgs []*descriptor.DescriptorProto, f func(field *descriptor.FieldDescriptorProto)) { for _, msg := range msgs { for _, field := range msg.Field { f(field) } ForEachField(msg.NestedType, f) } } func ForEachField(msgs []*descriptor.DescriptorProto, f func(field *descriptor.FieldDescriptorProto)) { for _, msg := range msgs { for _, field := range msg.Field { f(field) } for _, ext := range msg.Extension { f(ext) } ForEachField(msg.NestedType, f) } } func ForEachEnumInFiles(files []*descriptor.FileDescriptorProto, f func(enum *descriptor.EnumDescriptorProto)) { for _, file := range files { for _, enum := range file.EnumType { f(enum) } } } func ForEachEnum(msgs []*descriptor.DescriptorProto, f func(field *descriptor.EnumDescriptorProto)) { for _, msg := range msgs { for _, field := range msg.EnumType { f(field) } ForEachEnum(msg.NestedType, f) } }
vendor/github.com/gogo/protobuf/vanity/foreach.go
0
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.00017367028340231627, 0.00017019669758155942, 0.00016707951726857573, 0.0001699109561741352, 0.0000022181961867318023 ]
{ "id": 2, "code_window": [ "\n", "```shell\n", "docker-machine ssh `docker-machine active` curl $ip\n", "```\n", "\n", "### Turning down your cluster\n", "\n", "1\\. Delete the nginx service and deployment:\n", "\n", "If you plan on re-creating your nginx deployment and service you will need to clean it up.\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "## Deploy a DNS\n", "\n", "Read [documentation for manually deploying a DNS](http://kubernetes.io/docs/getting-started-guides/docker-multinode/#deploy-dns-manually-for-v12x) for instructions.\n", "\n" ], "file_path": "docs/devel/local-cluster/docker.md", "type": "add", "edit_start_line_idx": 227 }
<!-- 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. Documentation for other releases can be found at [releases.k8s.io](http://releases.k8s.io). </strong> -- <!-- END STRIP_FOR_RELEASE --> <!-- END MUNGE: UNVERSIONED_WARNING --> --- assignees: - erictune - mikedanese - thockin --- * TOC {:toc} **Stop. This guide has been superseded by [Minikube](https://github.com/kubernetes/minikube) which is the recommended method of running Kubernetes on your local machine.** ### Requirements #### Linux Not running Linux? Consider running Linux in a local virtual machine with [vagrant](https://www.vagrantup.com/), or on a cloud provider like Google Compute Engine #### Docker At least [Docker](https://docs.docker.com/installation/#installation) 1.8.3+. Ensure the Docker daemon is running and can be contacted (try `docker ps`). Some of the Kubernetes components need to run as root, which normally works fine with docker. #### etcd You need an [etcd](https://github.com/coreos/etcd/releases) in your path, please make sure it is installed and in your ``$PATH``. #### go You need [go](https://golang.org/doc/install) at least 1.4+ in your path, please make sure it is installed and in your ``$PATH``. ### Starting the cluster First, you need to [download Kubernetes](http://kubernetes.io/docs/getting-started-guides/binary_release/). Then open a separate tab of your terminal and run the following (since one needs sudo access to start/stop Kubernetes daemons, it is easier to run the entire script as root): ```shell cd kubernetes hack/local-up-cluster.sh ``` This will build and start a lightweight local cluster, consisting of a master and a single node. Type Control-C to shut it down. You can use the cluster/kubectl.sh script to interact with the local cluster. hack/local-up-cluster.sh will print the commands to run to point kubectl at the local cluster. ### Running a container Your cluster is running, and you want to start running containers! You can now use any of the cluster/kubectl.sh commands to interact with your local setup. ```shell export KUBERNETES_PROVIDER=local cluster/kubectl.sh get pods cluster/kubectl.sh get services cluster/kubectl.sh get deployments cluster/kubectl.sh run my-nginx --image=nginx --replicas=2 --port=80 ## begin wait for provision to complete, you can monitor the docker pull by opening a new terminal sudo docker images ## you should see it pulling the nginx image, once the above command returns it sudo docker ps ## you should see your container running! exit ## end wait ## create a service for nginx, which serves on port 80 cluster/kubectl.sh expose deployment my-nginx --port=80 --name=my-nginx ## introspect Kubernetes! cluster/kubectl.sh get pods cluster/kubectl.sh get services cluster/kubectl.sh get deployments ## Test the nginx service with the IP/port from "get services" command curl http://10.X.X.X:80/ ``` ### Running a user defined pod Note the difference between a [container](http://kubernetes.io/docs/user-guide/containers/) and a [pod](http://kubernetes.io/docs/user-guide/pods/). Since you only asked for the former, Kubernetes will create a wrapper pod for you. However you cannot view the nginx start page on localhost. To verify that nginx is running you need to run `curl` within the docker container (try `docker exec`). You can control the specifications of a pod via a user defined manifest, and reach nginx through your browser on the port specified therein: ```shell cluster/kubectl.sh create -f docs/user-guide/pod.yaml ``` Congratulations! ### FAQs #### I cannot reach service IPs on the network. Some firewall software that uses iptables may not interact well with kubernetes. If you have trouble around networking, try disabling any firewall or other iptables-using systems, first. Also, you can check if SELinux is blocking anything by running a command such as `journalctl --since yesterday | grep avc`. By default the IP range for service cluster IPs is 10.0.*.* - depending on your docker installation, this may conflict with IPs for containers. If you find containers running with IPs in this range, edit hack/local-cluster-up.sh and change the service-cluster-ip-range flag to something else. #### I changed Kubernetes code, how do I run it? ```shell cd kubernetes hack/build-go.sh hack/local-up-cluster.sh ``` #### kubectl claims to start a container but `get pods` and `docker ps` don't show it. One or more of the Kubernetes daemons might've crashed. Tail the [logs](http://kubernetes.io/docs/admin/cluster-troubleshooting/#looking-at-logs) of each in /tmp. ```shell $ ls /tmp/kube*.log $ tail -f /tmp/kube-apiserver.log ``` #### The pods fail to connect to the services by host names The local-up-cluster.sh script doesn't start a DNS service. Similar situation can be found [here](http://issue.k8s.io/6667). You can start a manually. <!-- BEGIN MUNGE: GENERATED_ANALYTICS --> [![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/devel/local-cluster/local.md?pixel)]() <!-- END MUNGE: GENERATED_ANALYTICS -->
docs/devel/local-cluster/local.md
1
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.006391829811036587, 0.0015960369491949677, 0.0001682807196630165, 0.0007887727115303278, 0.0019014334538951516 ]
{ "id": 2, "code_window": [ "\n", "```shell\n", "docker-machine ssh `docker-machine active` curl $ip\n", "```\n", "\n", "### Turning down your cluster\n", "\n", "1\\. Delete the nginx service and deployment:\n", "\n", "If you plan on re-creating your nginx deployment and service you will need to clean it up.\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "## Deploy a DNS\n", "\n", "Read [documentation for manually deploying a DNS](http://kubernetes.io/docs/getting-started-guides/docker-multinode/#deploy-dns-manually-for-v12x) for instructions.\n", "\n" ], "file_path": "docs/devel/local-cluster/docker.md", "type": "add", "edit_start_line_idx": 227 }
This folder contains the sources needed to build the gen-swagger-doc container. To build the container image, ``` $ sudo docker build -t gcr.io/google_containers/gen-swagger-docs:v1 . ``` To generate the html docs, ``` $ ./run-gen-swagger-docs.sh <API version> <absolute output path, default to PWD> ``` The generated definitions.html and operations.html will be stored in output paths. [![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/hack/gen-swagger-doc/README.md?pixel)]()
hack/gen-swagger-doc/README.md
0
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.0002110274654114619, 0.00020364791271276772, 0.00019626834546215832, 0.00020364791271276772, 0.000007379559974651784 ]
{ "id": 2, "code_window": [ "\n", "```shell\n", "docker-machine ssh `docker-machine active` curl $ip\n", "```\n", "\n", "### Turning down your cluster\n", "\n", "1\\. Delete the nginx service and deployment:\n", "\n", "If you plan on re-creating your nginx deployment and service you will need to clean it up.\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "## Deploy a DNS\n", "\n", "Read [documentation for manually deploying a DNS](http://kubernetes.io/docs/getting-started-guides/docker-multinode/#deploy-dns-manually-for-v12x) for instructions.\n", "\n" ], "file_path": "docs/devel/local-cluster/docker.md", "type": "add", "edit_start_line_idx": 227 }
// Copyright 2012 Gary Burd // // Licensed under the Apache License, Version 2.0 (the "License"): you may // not use this file except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-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 redis // Error represents an error returned in a command reply. type Error string func (err Error) Error() string { return string(err) } // Conn represents a connection to a Redis server. type Conn interface { // Close closes the connection. Close() error // Err returns a non-nil value if the connection is broken. The returned // value is either the first non-nil value returned from the underlying // network connection or a protocol parsing error. Applications should // close broken connections. Err() error // Do sends a command to the server and returns the received reply. Do(commandName string, args ...interface{}) (reply interface{}, err error) // Send writes the command to the client's output buffer. Send(commandName string, args ...interface{}) error // Flush flushes the output buffer to the Redis server. Flush() error // Receive receives a single reply from the Redis server Receive() (reply interface{}, err error) }
vendor/github.com/garyburd/redigo/redis/redis.go
0
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.00022165761038195342, 0.00018555481801740825, 0.00016816282004583627, 0.00017407978884875774, 0.000020441324522835203 ]
{ "id": 2, "code_window": [ "\n", "```shell\n", "docker-machine ssh `docker-machine active` curl $ip\n", "```\n", "\n", "### Turning down your cluster\n", "\n", "1\\. Delete the nginx service and deployment:\n", "\n", "If you plan on re-creating your nginx deployment and service you will need to clean it up.\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "## Deploy a DNS\n", "\n", "Read [documentation for manually deploying a DNS](http://kubernetes.io/docs/getting-started-guides/docker-multinode/#deploy-dns-manually-for-v12x) for instructions.\n", "\n" ], "file_path": "docs/devel/local-cluster/docker.md", "type": "add", "edit_start_line_idx": 227 }
package bolt // maxMapSize represents the largest mmap size supported by Bolt. const maxMapSize = 0x7FFFFFFF // 2GB // maxAllocSize is the size used when creating array pointers. const maxAllocSize = 0xFFFFFFF
vendor/github.com/boltdb/bolt/bolt_386.go
0
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.00016974384197965264, 0.00016974384197965264, 0.00016974384197965264, 0.00016974384197965264, 0 ]
{ "id": 3, "code_window": [ "<!-- END STRIP_FOR_RELEASE -->\n", "\n", "<!-- END MUNGE: UNVERSIONED_WARNING -->\n", "\n", "---\n", "assignees:\n", "- erictune\n", "- mikedanese\n", "- thockin\n", "\n", "---\n", "\n", "\n", "\n", "* TOC\n", "{:toc}\n", "\n", "**Stop. This guide has been superseded by [Minikube](https://github.com/kubernetes/minikube) which is the recommended method of running Kubernetes on your local machine.**\n", "\n", "### Requirements\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/devel/local-cluster/local.md", "type": "replace", "edit_start_line_idx": 29 }
<!-- 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. Documentation for other releases can be found at [releases.k8s.io](http://releases.k8s.io). </strong> -- <!-- END STRIP_FOR_RELEASE --> <!-- END MUNGE: UNVERSIONED_WARNING --> --- assignees: - asridharan - brendandburns - fgrzadkowski --- **Stop. This guide has been superseded by [Minikube](https://github.com/kubernetes/minikube) which is the recommended method of running Kubernetes on your local machine.** The following instructions show you how to set up a simple, single node Kubernetes cluster using Docker. Here's a diagram of what the final result will look like: ![Kubernetes Single Node on Docker](../../getting-started-guides/k8s-singlenode-docker.png) * TOC {:toc} ## Prerequisites **Note: These steps have not been tested with the [Docker For Mac or Docker For Windows beta programs](https://blog.docker.com/2016/03/docker-for-mac-windows-beta/).** 1. You need to have Docker version >= "1.10" installed on the machine. 2. Enable mount propagation. Hyperkube is running in a container which has to mount volumes for other containers, for example in case of persistent storage. The required steps depend on the init system. In case of **systemd**, change MountFlags in the Docker unit file to shared. ```shell DOCKER_CONF=$(systemctl cat docker | head -1 | awk '{print $2}') sed -i.bak 's/^\(MountFlags=\).*/\1shared/' $DOCKER_CONF systemctl daemon-reload systemctl restart docker ``` **Otherwise**, manually set the mount point used by Hyperkube to be shared: ```shell mkdir -p /var/lib/kubelet mount --bind /var/lib/kubelet /var/lib/kubelet mount --make-shared /var/lib/kubelet ``` ### Run it 1. Decide which Kubernetes version to use. Set the `${K8S_VERSION}` variable to a version of Kubernetes >= "v1.2.0". If you'd like to use the current **stable** version of Kubernetes, run the following: ```sh export K8S_VERSION=$(curl -sS https://storage.googleapis.com/kubernetes-release/release/stable.txt) ``` and for the **latest** available version (including unstable releases): ```sh export K8S_VERSION=$(curl -sS https://storage.googleapis.com/kubernetes-release/release/latest.txt) ``` 2. Start Hyperkube ```shell export ARCH=amd64 docker run -d \ --volume=/sys:/sys:rw \ --volume=/var/lib/docker/:/var/lib/docker:rw \ --volume=/var/lib/kubelet/:/var/lib/kubelet:rw,shared \ --volume=/var/run:/var/run:rw \ --net=host \ --pid=host \ --privileged \ --name=kubelet \ gcr.io/google_containers/hyperkube-${ARCH}:${K8S_VERSION} \ /hyperkube kubelet \ --hostname-override=127.0.0.1 \ --api-servers=http://localhost:8080 \ --config=/etc/kubernetes/manifests \ --cluster-dns=10.0.0.10 \ --cluster-domain=cluster.local \ --allow-privileged --v=2 ``` > Note that `--cluster-dns` and `--cluster-domain` is used to deploy dns, feel free to discard them if dns is not needed. > If you would like to mount an external device as a volume, add `--volume=/dev:/dev` to the command above. It may however, cause some problems described in [#18230](https://github.com/kubernetes/kubernetes/issues/18230) > Architectures other than `amd64` are experimental and sometimes unstable, but feel free to try them out! Valid values: `arm`, `arm64` and `ppc64le`. ARM is available with Kubernetes version `v1.3.0-alpha.2` and higher. ARM 64-bit and PowerPC 64 little-endian are available with `v1.3.0-alpha.3` and higher. Track progress on multi-arch support [here](https://github.com/kubernetes/kubernetes/issues/17981) > If you are behind a proxy, you need to pass the proxy setup to curl in the containers to pull the certificates. Create a .curlrc under /root folder (because the containers are running as root) with the following line: ``` proxy = <your_proxy_server>:<port> ``` This actually runs the kubelet, which in turn runs a [pod](http://kubernetes.io/docs/user-guide/pods/) that contains the other master components. ** **SECURITY WARNING** ** services exposed via Kubernetes using Hyperkube are available on the host node's public network interface / IP address. Because of this, this guide is not suitable for any host node/server that is directly internet accessible. Refer to [#21735](https://github.com/kubernetes/kubernetes/issues/21735) for addtional info. ### Download `kubectl` At this point you should have a running Kubernetes cluster. You can test it out by downloading the kubectl binary for `${K8S_VERSION}` (in this example: `{{page.version}}.0`). Downloads: - `linux/amd64`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/linux/amd64/kubectl - `linux/386`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/linux/386/kubectl - `linux/arm`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/linux/arm/kubectl - `linux/arm64`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/linux/arm64/kubectl - `linux/ppc64le`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/linux/ppc64le/kubectl - `OS X/amd64`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/darwin/amd64/kubectl - `OS X/386`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/darwin/386/kubectl - `windows/amd64`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/windows/amd64/kubectl.exe - `windows/386`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/windows/386/kubectl.exe The generic download path is: ``` http://storage.googleapis.com/kubernetes-release/release/${K8S_VERSION}/bin/${GOOS}/${GOARCH}/${K8S_BINARY} ``` An example install with `linux/amd64`: ``` curl -sSL "https://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/linux/amd64/kubectl" > /usr/bin/kubectl chmod +x /usr/bin/kubectl ``` On OS X, to make the API server accessible locally, setup a ssh tunnel. ```shell docker-machine ssh `docker-machine active` -N -L 8080:localhost:8080 ``` Setting up a ssh tunnel is applicable to remote docker hosts as well. (Optional) Create kubernetes cluster configuration: ```shell kubectl config set-cluster test-doc --server=http://localhost:8080 kubectl config set-context test-doc --cluster=test-doc kubectl config use-context test-doc ``` ### Test it out List the nodes in your cluster by running: ```shell kubectl get nodes ``` This should print: ```shell NAME STATUS AGE 127.0.0.1 Ready 1h ``` ### Run an application ```shell kubectl run nginx --image=nginx --port=80 ``` Now run `docker ps` you should see nginx running. You may need to wait a few minutes for the image to get pulled. ### Expose it as a service ```shell kubectl expose deployment nginx --port=80 ``` Run the following command to obtain the cluster local IP of this service we just created: ```shell{% raw %} ip=$(kubectl get svc nginx --template={{.spec.clusterIP}}) echo $ip {% endraw %}``` Hit the webserver with this IP: ```shell{% raw %} curl $ip {% endraw %}``` On OS X, since docker is running inside a VM, run the following command instead: ```shell docker-machine ssh `docker-machine active` curl $ip ``` ### Turning down your cluster 1\. Delete the nginx service and deployment: If you plan on re-creating your nginx deployment and service you will need to clean it up. ```shell kubectl delete service,deployments nginx ``` 2\. Delete all the containers including the kubelet: ```shell docker rm -f kubelet docker rm -f `docker ps | grep k8s | awk '{print $1}'` ``` 3\. Cleanup the filesystem: On OS X, first ssh into the docker VM: ```shell docker-machine ssh `docker-machine active` ``` ```shell grep /var/lib/kubelet /proc/mounts | awk '{print $2}' | sudo xargs -n1 umount sudo rm -rf /var/lib/kubelet ``` ### Troubleshooting #### Node is in `NotReady` state If you see your node as `NotReady` it's possible that your OS does not have memcg enabled. 1. Your kernel should support memory accounting. Ensure that the following configs are turned on in your linux kernel: ```shell CONFIG_RESOURCE_COUNTERS=y CONFIG_MEMCG=y ``` 2. Enable the memory accounting in the kernel, at boot, as command line parameters as follows: ```shell GRUB_CMDLINE_LINUX="cgroup_enable=memory=1" ``` NOTE: The above is specifically for GRUB2. You can check the command line parameters passed to your kernel by looking at the output of /proc/cmdline: ```shell $ cat /proc/cmdline BOOT_IMAGE=/boot/vmlinuz-3.18.4-aufs root=/dev/sda5 ro cgroup_enable=memory=1 ``` ## Support Level IaaS Provider | Config. Mgmt | OS | Networking | Conforms | Support Level -------------------- | ------------ | ------ | ---------- | ---------| ---------------------------- Docker Single Node | custom | N/A | local | | Project ([@brendandburns](https://github.com/brendandburns)) ## Further reading Please see the [Kubernetes docs](http://kubernetes.io/docs) for more details on administering and using a Kubernetes cluster. <!-- BEGIN MUNGE: GENERATED_ANALYTICS --> [![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/devel/local-cluster/docker.md?pixel)]() <!-- END MUNGE: GENERATED_ANALYTICS -->
docs/devel/local-cluster/docker.md
1
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.0007090079598128796, 0.00023692275863140821, 0.0001608843303984031, 0.00018214798183180392, 0.00012708482972811908 ]
{ "id": 3, "code_window": [ "<!-- END STRIP_FOR_RELEASE -->\n", "\n", "<!-- END MUNGE: UNVERSIONED_WARNING -->\n", "\n", "---\n", "assignees:\n", "- erictune\n", "- mikedanese\n", "- thockin\n", "\n", "---\n", "\n", "\n", "\n", "* TOC\n", "{:toc}\n", "\n", "**Stop. This guide has been superseded by [Minikube](https://github.com/kubernetes/minikube) which is the recommended method of running Kubernetes on your local machine.**\n", "\n", "### Requirements\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/devel/local-cluster/local.md", "type": "replace", "edit_start_line_idx": 29 }
// 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 atom provides integer codes (also known as atoms) for a fixed set of // frequently occurring HTML strings: tag names and attribute keys such as "p" // and "id". // // Sharing an atom's name between all elements with the same tag can result in // fewer string allocations when tokenizing and parsing HTML. Integer // comparisons are also generally faster than string comparisons. // // The value of an atom's particular code is not guaranteed to stay the same // between versions of this package. Neither is any ordering guaranteed: // whether atom.H1 < atom.H2 may also change. The codes are not guaranteed to // be dense. The only guarantees are that e.g. looking up "div" will yield // atom.Div, calling atom.Div.String will return "div", and atom.Div != 0. package atom // Atom is an integer code for a string. The zero value maps to "". type Atom uint32 // String returns the atom's name. func (a Atom) String() string { start := uint32(a >> 8) n := uint32(a & 0xff) if start+n > uint32(len(atomText)) { return "" } return atomText[start : start+n] } func (a Atom) string() string { return atomText[a>>8 : a>>8+a&0xff] } // fnv computes the FNV hash with an arbitrary starting value h. func fnv(h uint32, s []byte) uint32 { for i := range s { h ^= uint32(s[i]) h *= 16777619 } return h } func match(s string, t []byte) bool { for i, c := range t { if s[i] != c { return false } } return true } // Lookup returns the atom whose name is s. It returns zero if there is no // such atom. The lookup is case sensitive. func Lookup(s []byte) Atom { if len(s) == 0 || len(s) > maxAtomLen { return 0 } h := fnv(hash0, s) if a := table[h&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) { return a } if a := table[(h>>16)&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) { return a } return 0 } // String returns a string whose contents are equal to s. In that sense, it is // equivalent to string(s) but may be more efficient. func String(s []byte) string { if a := Lookup(s); a != 0 { return a.String() } return string(s) }
vendor/golang.org/x/net/html/atom/atom.go
0
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.001135392696596682, 0.0002898094244301319, 0.00016380577289965004, 0.0001687881158431992, 0.000319622311508283 ]
{ "id": 3, "code_window": [ "<!-- END STRIP_FOR_RELEASE -->\n", "\n", "<!-- END MUNGE: UNVERSIONED_WARNING -->\n", "\n", "---\n", "assignees:\n", "- erictune\n", "- mikedanese\n", "- thockin\n", "\n", "---\n", "\n", "\n", "\n", "* TOC\n", "{:toc}\n", "\n", "**Stop. This guide has been superseded by [Minikube](https://github.com/kubernetes/minikube) which is the recommended method of running Kubernetes on your local machine.**\n", "\n", "### Requirements\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/devel/local-cluster/local.md", "type": "replace", "edit_start_line_idx": 29 }
package matchers import ( "fmt" "github.com/onsi/gomega/format" ) type BeFalseMatcher struct { } func (matcher *BeFalseMatcher) Match(actual interface{}) (success bool, err error) { if !isBool(actual) { return false, fmt.Errorf("Expected a boolean. Got:\n%s", format.Object(actual, 1)) } return actual == false, nil } func (matcher *BeFalseMatcher) FailureMessage(actual interface{}) (message string) { return format.Message(actual, "to be false") } func (matcher *BeFalseMatcher) NegatedFailureMessage(actual interface{}) (message string) { return format.Message(actual, "not to be false") }
vendor/github.com/onsi/gomega/matchers/be_false_matcher.go
0
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.00016807368956506252, 0.00016653636703267694, 0.00016494728333782405, 0.00016658809909131378, 0.000001276874286304519 ]
{ "id": 3, "code_window": [ "<!-- END STRIP_FOR_RELEASE -->\n", "\n", "<!-- END MUNGE: UNVERSIONED_WARNING -->\n", "\n", "---\n", "assignees:\n", "- erictune\n", "- mikedanese\n", "- thockin\n", "\n", "---\n", "\n", "\n", "\n", "* TOC\n", "{:toc}\n", "\n", "**Stop. This guide has been superseded by [Minikube](https://github.com/kubernetes/minikube) which is the recommended method of running Kubernetes on your local machine.**\n", "\n", "### Requirements\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/devel/local-cluster/local.md", "type": "replace", "edit_start_line_idx": 29 }
seqdiag { activation = none; admin[label = "Manual Admin"]; ca[label = "Manual CA"] master; kubelet[stacked]; admin => ca [label="create\n- master-cert"]; admin ->> master [label="start\n- ca-root\n- master-cert"]; admin => ca [label="create\n- kubelet-cert"]; admin ->> kubelet [label="start\n- ca-root\n- kubelet-cert\n- master-location"]; kubelet => master [label="register\n- kubelet-location"]; }
docs/design/clustering/static.seqdiag
0
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.00016802178288344294, 0.00016799951845314354, 0.00016797725402284414, 0.00016799951845314354, 2.2264430299401283e-8 ]
{ "id": 4, "code_window": [ "\n", "<!-- END STRIP_FOR_RELEASE -->\n", "\n", "<!-- END MUNGE: UNVERSIONED_WARNING -->\n", "\n", "---\n", "assignees:\n", "- brendandburns\n", "- derekwaynecarr\n", "- jbeda\n", "---\n", "\n", "did no\n", "\n", "Running Kubernetes with Vagrant (and VirtualBox) is an easy way to run/test/develop on your local machine (Linux, Mac OS X).\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "docs/devel/local-cluster/vagrant.md", "type": "replace", "edit_start_line_idx": 29 }
<!-- 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. Documentation for other releases can be found at [releases.k8s.io](http://releases.k8s.io). </strong> -- <!-- END STRIP_FOR_RELEASE --> <!-- END MUNGE: UNVERSIONED_WARNING --> --- assignees: - brendandburns - derekwaynecarr - jbeda --- did no Running Kubernetes with Vagrant (and VirtualBox) is an easy way to run/test/develop on your local machine (Linux, Mac OS X). * TOC {:toc} ### Prerequisites 1. Install latest version >= 1.7.4 of [Vagrant](http://www.vagrantup.com/downloads.html) 2. Install one of: 1. The latest version of [Virtual Box](https://www.virtualbox.org/wiki/Downloads) 2. [VMWare Fusion](https://www.vmware.com/products/fusion/) version 5 or greater as well as the appropriate [Vagrant VMWare Fusion provider](https://www.vagrantup.com/vmware) 3. [VMWare Workstation](https://www.vmware.com/products/workstation/) version 9 or greater as well as the [Vagrant VMWare Workstation provider](https://www.vagrantup.com/vmware) 4. [Parallels Desktop](https://www.parallels.com/products/desktop/) version 9 or greater as well as the [Vagrant Parallels provider](https://parallels.github.io/vagrant-parallels/) 5. libvirt with KVM and enable support of hardware virtualisation. [Vagrant-libvirt](https://github.com/pradels/vagrant-libvirt). For fedora provided official rpm, and possible to use `yum install vagrant-libvirt` ### Setup Setting up a cluster is as simple as running: ```sh export KUBERNETES_PROVIDER=vagrant curl -sS https://get.k8s.io | bash ``` Alternatively, you can download [Kubernetes release](https://github.com/kubernetes/kubernetes/releases) and extract the archive. To start your local cluster, open a shell and run: ```sh cd kubernetes export KUBERNETES_PROVIDER=vagrant ./cluster/kube-up.sh ``` The `KUBERNETES_PROVIDER` environment variable tells all of the various cluster management scripts which variant to use. If you forget to set this, the assumption is you are running on Google Compute Engine. By default, the Vagrant setup will create a single master VM (called kubernetes-master) and one node (called kubernetes-node-1). Each VM will take 1 GB, so make sure you have at least 2GB to 4GB of free memory (plus appropriate free disk space). If you'd like more than one node, set the `NUM_NODES` environment variable to the number you want: ```sh export NUM_NODES=3 ``` Vagrant will provision each machine in the cluster with all the necessary components to run Kubernetes. The initial setup can take a few minutes to complete on each machine. If you installed more than one Vagrant provider, Kubernetes will usually pick the appropriate one. However, you can override which one Kubernetes will use by setting the [`VAGRANT_DEFAULT_PROVIDER`](https://docs.vagrantup.com/v2/providers/default.html) environment variable: ```sh export VAGRANT_DEFAULT_PROVIDER=parallels export KUBERNETES_PROVIDER=vagrant ./cluster/kube-up.sh ``` By default, each VM in the cluster is running Fedora. To access the master or any node: ```sh vagrant ssh master vagrant ssh node-1 ``` If you are running more than one node, you can access the others by: ```sh vagrant ssh node-2 vagrant ssh node-3 ``` Each node in the cluster installs the docker daemon and the kubelet. The master node instantiates the Kubernetes master components as pods on the machine. To view the service status and/or logs on the kubernetes-master: ```console [vagrant@kubernetes-master ~] $ vagrant ssh master [vagrant@kubernetes-master ~] $ sudo su [root@kubernetes-master ~] $ systemctl status kubelet [root@kubernetes-master ~] $ journalctl -ru kubelet [root@kubernetes-master ~] $ systemctl status docker [root@kubernetes-master ~] $ journalctl -ru docker [root@kubernetes-master ~] $ tail -f /var/log/kube-apiserver.log [root@kubernetes-master ~] $ tail -f /var/log/kube-controller-manager.log [root@kubernetes-master ~] $ tail -f /var/log/kube-scheduler.log ``` To view the services on any of the nodes: ```console [vagrant@kubernetes-master ~] $ vagrant ssh node-1 [vagrant@kubernetes-master ~] $ sudo su [root@kubernetes-master ~] $ systemctl status kubelet [root@kubernetes-master ~] $ journalctl -ru kubelet [root@kubernetes-master ~] $ systemctl status docker [root@kubernetes-master ~] $ journalctl -ru docker ``` ### Interacting with your Kubernetes cluster with Vagrant. With your Kubernetes cluster up, you can manage the nodes in your cluster with the regular Vagrant commands. To push updates to new Kubernetes code after making source changes: ```sh ./cluster/kube-push.sh ``` To stop and then restart the cluster: ```sh vagrant halt ./cluster/kube-up.sh ``` To destroy the cluster: ```sh vagrant destroy ``` Once your Vagrant machines are up and provisioned, the first thing to do is to check that you can use the `kubectl.sh` script. You may need to build the binaries first, you can do this with `make` ```console $ ./cluster/kubectl.sh get nodes NAME LABELS 10.245.1.4 <none> 10.245.1.5 <none> 10.245.1.3 <none> ``` ### Authenticating with your master When using the vagrant provider in Kubernetes, the `cluster/kubectl.sh` script will cache your credentials in a `~/.kubernetes_vagrant_auth` file so you will not be prompted for them in the future. ```sh cat ~/.kubernetes_vagrant_auth ``` ```json { "User": "vagrant", "Password": "vagrant", "CAFile": "/home/k8s_user/.kubernetes.vagrant.ca.crt", "CertFile": "/home/k8s_user/.kubecfg.vagrant.crt", "KeyFile": "/home/k8s_user/.kubecfg.vagrant.key" } ``` You should now be set to use the `cluster/kubectl.sh` script. For example try to list the nodes that you have started with: ```sh ./cluster/kubectl.sh get nodes ``` ### Running containers Your cluster is running, you can list the nodes in your cluster: ```sh $ ./cluster/kubectl.sh get nodes NAME LABELS 10.245.2.4 <none> 10.245.2.3 <none> 10.245.2.2 <none> ``` Now start running some containers! You can now use any of the `cluster/kube-*.sh` commands to interact with your VM machines. Before starting a container there will be no pods, services and replication controllers. ```sh $ ./cluster/kubectl.sh get pods NAME READY STATUS RESTARTS AGE $ ./cluster/kubectl.sh get services NAME CLUSTER_IP EXTERNAL_IP PORT(S) SELECTOR AGE $ ./cluster/kubectl.sh get replicationcontrollers CONTROLLER CONTAINER(S) IMAGE(S) SELECTOR REPLICAS ``` Start a container running nginx with a replication controller and three replicas ```sh $ ./cluster/kubectl.sh run my-nginx --image=nginx --replicas=3 --port=80 ``` When listing the pods, you will see that three containers have been started and are in Waiting state: ```sh $ ./cluster/kubectl.sh get pods NAME READY STATUS RESTARTS AGE my-nginx-5kq0g 0/1 Pending 0 10s my-nginx-gr3hh 0/1 Pending 0 10s my-nginx-xql4j 0/1 Pending 0 10s ``` You need to wait for the provisioning to complete, you can monitor the nodes by doing: ```sh $ vagrant ssh node-1 -c 'sudo docker images' kubernetes-node-1: REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE <none> <none> 96864a7d2df3 26 hours ago 204.4 MB google/cadvisor latest e0575e677c50 13 days ago 12.64 MB kubernetes/pause latest 6c4579af347b 8 weeks ago 239.8 kB ``` Once the docker image for nginx has been downloaded, the container will start and you can list it: ```sh $ vagrant ssh node-1 -c 'sudo docker ps' kubernetes-node-1: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES dbe79bf6e25b nginx:latest "nginx" 21 seconds ago Up 19 seconds k8s--mynginx.8c5b8a3a--7813c8bd_-_3ffe_-_11e4_-_9036_-_0800279696e1.etcd--7813c8bd_-_3ffe_-_11e4_-_9036_-_0800279696e1--fcfa837f fa0e29c94501 kubernetes/pause:latest "/pause" 8 minutes ago Up 8 minutes 0.0.0.0:8080->80/tcp k8s--net.a90e7ce4--7813c8bd_-_3ffe_-_11e4_-_9036_-_0800279696e1.etcd--7813c8bd_-_3ffe_-_11e4_-_9036_-_0800279696e1--baf5b21b aa2ee3ed844a google/cadvisor:latest "/usr/bin/cadvisor" 38 minutes ago Up 38 minutes k8s--cadvisor.9e90d182--cadvisor_-_agent.file--4626b3a2 65a3a926f357 kubernetes/pause:latest "/pause" 39 minutes ago Up 39 minutes 0.0.0.0:4194->8080/tcp k8s--net.c5ba7f0e--cadvisor_-_agent.file--342fd561 ``` Going back to listing the pods, services and replicationcontrollers, you now have: ```sh $ ./cluster/kubectl.sh get pods NAME READY STATUS RESTARTS AGE my-nginx-5kq0g 1/1 Running 0 1m my-nginx-gr3hh 1/1 Running 0 1m my-nginx-xql4j 1/1 Running 0 1m $ ./cluster/kubectl.sh get services NAME CLUSTER_IP EXTERNAL_IP PORT(S) SELECTOR AGE $ ./cluster/kubectl.sh get replicationcontrollers CONTROLLER CONTAINER(S) IMAGE(S) SELECTOR REPLICAS AGE my-nginx my-nginx nginx run=my-nginx 3 1m ``` We did not start any services, hence there are none listed. But we see three replicas displayed properly. Learn about [running your first containers](http://kubernetes.io/docs/user-guide/simple-nginx/) application to learn how to create a service. You can already play with scaling the replicas with: ```sh $ ./cluster/kubectl.sh scale rc my-nginx --replicas=2 $ ./cluster/kubectl.sh get pods NAME READY STATUS RESTARTS AGE my-nginx-5kq0g 1/1 Running 0 2m my-nginx-gr3hh 1/1 Running 0 2m ``` Congratulations! ## Troubleshooting #### I keep downloading the same (large) box all the time! By default the Vagrantfile will download the box from S3. You can change this (and cache the box locally) by providing a name and an alternate URL when calling `kube-up.sh` ```sh export KUBERNETES_BOX_NAME=choose_your_own_name_for_your_kuber_box export KUBERNETES_BOX_URL=path_of_your_kuber_box export KUBERNETES_PROVIDER=vagrant ./cluster/kube-up.sh ``` #### I am getting timeouts when trying to curl the master from my host! During provision of the cluster, you may see the following message: ```sh Validating node-1 ............. Waiting for each node to be registered with cloud provider error: couldn't read version from server: Get https://10.245.1.2/api: dial tcp 10.245.1.2:443: i/o timeout ``` Some users have reported VPNs may prevent traffic from being routed to the host machine into the virtual machine network. To debug, first verify that the master is binding to the proper IP address: ```sh $ vagrant ssh master $ ifconfig | grep eth1 -C 2 eth1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 10.245.1.2 netmask 255.255.255.0 broadcast 10.245.1.255 ``` Then verify that your host machine has a network connection to a bridge that can serve that address: ```sh $ ifconfig | grep 10.245.1 -C 2 vboxnet5: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 10.245.1.1 netmask 255.255.255.0 broadcast 10.245.1.255 inet6 fe80::800:27ff:fe00:5 prefixlen 64 scopeid 0x20<link> ether 0a:00:27:00:00:05 txqueuelen 1000 (Ethernet) ``` If you do not see a response on your host machine, you will most likely need to connect your host to the virtual network created by the virtualization provider. If you do see a network, but are still unable to ping the machine, check if your VPN is blocking the request. #### I just created the cluster, but I am getting authorization errors! You probably have an incorrect ~/.kubernetes_vagrant_auth file for the cluster you are attempting to contact. ```sh rm ~/.kubernetes_vagrant_auth ``` After using kubectl.sh make sure that the correct credentials are set: ```sh cat ~/.kubernetes_vagrant_auth ``` ```json { "User": "vagrant", "Password": "vagrant" } ``` #### I just created the cluster, but I do not see my container running! If this is your first time creating the cluster, the kubelet on each node schedules a number of docker pull requests to fetch prerequisite images. This can take some time and as a result may delay your initial pod getting provisioned. #### I have brought Vagrant up but the nodes cannot validate! Log on to one of the nodes (`vagrant ssh node-1`) and inspect the salt minion log (`sudo cat /var/log/salt/minion`). #### I want to change the number of nodes! You can control the number of nodes that are instantiated via the environment variable `NUM_NODES` on your host machine. If you plan to work with replicas, we strongly encourage you to work with enough nodes to satisfy your largest intended replica size. If you do not plan to work with replicas, you can save some system resources by running with a single node. You do this, by setting `NUM_NODES` to 1 like so: ```sh export NUM_NODES=1 ``` #### I want my VMs to have more memory! You can control the memory allotted to virtual machines with the `KUBERNETES_MEMORY` environment variable. Just set it to the number of megabytes you would like the machines to have. For example: ```sh export KUBERNETES_MEMORY=2048 ``` If you need more granular control, you can set the amount of memory for the master and nodes independently. For example: ```sh export KUBERNETES_MASTER_MEMORY=1536 export KUBERNETES_NODE_MEMORY=2048 ``` #### I want to set proxy settings for my Kubernetes cluster boot strapping! If you are behind a proxy, you need to install vagrant proxy plugin and set the proxy settings by ```sh vagrant plugin install vagrant-proxyconf export VAGRANT_HTTP_PROXY=http://username:password@proxyaddr:proxyport export VAGRANT_HTTPS_PROXY=https://username:password@proxyaddr:proxyport ``` Optionally you can specify addresses to not proxy, for example ```sh export VAGRANT_NO_PROXY=127.0.0.1 ``` If you are using sudo to make kubernetes build for example make quick-release, you need run `sudo -E make quick-release` to pass the environment variables. #### I ran vagrant suspend and nothing works! `vagrant suspend` seems to mess up the network. This is not supported at this time. #### I want vagrant to sync folders via nfs! You can ensure that vagrant uses nfs to sync folders with virtual machines by setting the KUBERNETES_VAGRANT_USE_NFS environment variable to 'true'. nfs is faster than virtualbox or vmware's 'shared folders' and does not require guest additions. See the [vagrant docs](http://docs.vagrantup.com/v2/synced-folders/nfs.html) for details on configuring nfs on the host. This setting will have no effect on the libvirt provider, which uses nfs by default. For example: ```sh export KUBERNETES_VAGRANT_USE_NFS=true ``` <!-- BEGIN MUNGE: GENERATED_ANALYTICS --> [![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/devel/local-cluster/vagrant.md?pixel)]() <!-- END MUNGE: GENERATED_ANALYTICS -->
docs/devel/local-cluster/vagrant.md
1
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.5549432039260864, 0.013795237988233566, 0.0001634037762414664, 0.0008870535530149937, 0.08253402262926102 ]
{ "id": 4, "code_window": [ "\n", "<!-- END STRIP_FOR_RELEASE -->\n", "\n", "<!-- END MUNGE: UNVERSIONED_WARNING -->\n", "\n", "---\n", "assignees:\n", "- brendandburns\n", "- derekwaynecarr\n", "- jbeda\n", "---\n", "\n", "did no\n", "\n", "Running Kubernetes with Vagrant (and VirtualBox) is an easy way to run/test/develop on your local machine (Linux, Mac OS X).\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "docs/devel/local-cluster/vagrant.md", "type": "replace", "edit_start_line_idx": 29 }
test:{SHA}qvTGHdzF6KLavt4PO0gs2a6pQ00= test2:$apr1$a0j62R97$mYqFkloXH0/UOaUnAiV2b0
vendor/github.com/abbot/go-http-auth/test.htpasswd
0
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.0001663128932705149, 0.0001663128932705149, 0.0001663128932705149, 0.0001663128932705149, 0 ]
{ "id": 4, "code_window": [ "\n", "<!-- END STRIP_FOR_RELEASE -->\n", "\n", "<!-- END MUNGE: UNVERSIONED_WARNING -->\n", "\n", "---\n", "assignees:\n", "- brendandburns\n", "- derekwaynecarr\n", "- jbeda\n", "---\n", "\n", "did no\n", "\n", "Running Kubernetes with Vagrant (and VirtualBox) is an easy way to run/test/develop on your local machine (Linux, Mac OS X).\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "docs/devel/local-cluster/vagrant.md", "type": "replace", "edit_start_line_idx": 29 }
/* 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 podsecuritypolicy import ( "fmt" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/apis/extensions" psputil "k8s.io/kubernetes/pkg/security/podsecuritypolicy/util" "k8s.io/kubernetes/pkg/util/validation/field" ) // used to pass in the field being validated for reusable group strategies so they // can create informative error messages. const ( fsGroupField = "fsGroup" supplementalGroupsField = "supplementalGroups" ) // simpleProvider is the default implementation of Provider. type simpleProvider struct { psp *extensions.PodSecurityPolicy strategies *ProviderStrategies } // ensure we implement the interface correctly. var _ Provider = &simpleProvider{} // NewSimpleProvider creates a new Provider instance. func NewSimpleProvider(psp *extensions.PodSecurityPolicy, namespace string, strategyFactory StrategyFactory) (Provider, error) { if psp == nil { return nil, fmt.Errorf("NewSimpleProvider requires a PodSecurityPolicy") } if strategyFactory == nil { return nil, fmt.Errorf("NewSimpleProvider requires a StrategyFactory") } strategies, err := strategyFactory.CreateStrategies(psp, namespace) if err != nil { return nil, err } return &simpleProvider{ psp: psp, strategies: strategies, }, nil } // Create a PodSecurityContext based on the given constraints. If a setting is already set // on the PodSecurityContext it will not be changed. Validate should be used after the context // is created to ensure it complies with the required restrictions. // // NOTE: this method works on a copy of the PodSecurityContext. It is up to the caller to // apply the PSC if validation passes. func (s *simpleProvider) CreatePodSecurityContext(pod *api.Pod) (*api.PodSecurityContext, error) { var sc *api.PodSecurityContext = nil if pod.Spec.SecurityContext != nil { // work with a copy copy := *pod.Spec.SecurityContext sc = &copy } else { sc = &api.PodSecurityContext{} } if len(sc.SupplementalGroups) == 0 { supGroups, err := s.strategies.SupplementalGroupStrategy.Generate(pod) if err != nil { return nil, err } sc.SupplementalGroups = supGroups } if sc.FSGroup == nil { fsGroup, err := s.strategies.FSGroupStrategy.GenerateSingle(pod) if err != nil { return nil, err } sc.FSGroup = fsGroup } if sc.SELinuxOptions == nil { seLinux, err := s.strategies.SELinuxStrategy.Generate(pod, nil) if err != nil { return nil, err } sc.SELinuxOptions = seLinux } return sc, nil } // Create a SecurityContext based on the given constraints. If a setting is already set on the // container's security context then it will not be changed. Validation should be used after // the context is created to ensure it complies with the required restrictions. // // NOTE: this method works on a copy of the SC of the container. It is up to the caller to apply // the SC if validation passes. func (s *simpleProvider) CreateContainerSecurityContext(pod *api.Pod, container *api.Container) (*api.SecurityContext, error) { var sc *api.SecurityContext = nil if container.SecurityContext != nil { // work with a copy of the original copy := *container.SecurityContext sc = &copy } else { sc = &api.SecurityContext{} } if sc.RunAsUser == nil { uid, err := s.strategies.RunAsUserStrategy.Generate(pod, container) if err != nil { return nil, err } sc.RunAsUser = uid } if sc.SELinuxOptions == nil { seLinux, err := s.strategies.SELinuxStrategy.Generate(pod, container) if err != nil { return nil, err } sc.SELinuxOptions = seLinux } if sc.Privileged == nil { priv := false sc.Privileged = &priv } // if we're using the non-root strategy set the marker that this container should not be // run as root which will signal to the kubelet to do a final check either on the runAsUser // or, if runAsUser is not set, the image UID will be checked. if s.psp.Spec.RunAsUser.Rule == extensions.RunAsUserStrategyMustRunAsNonRoot { nonRoot := true sc.RunAsNonRoot = &nonRoot } caps, err := s.strategies.CapabilitiesStrategy.Generate(pod, container) if err != nil { return nil, err } sc.Capabilities = caps // if the PSP requires a read only root filesystem and the container has not made a specific // request then default ReadOnlyRootFilesystem to true. if s.psp.Spec.ReadOnlyRootFilesystem && sc.ReadOnlyRootFilesystem == nil { readOnlyRootFS := true sc.ReadOnlyRootFilesystem = &readOnlyRootFS } return sc, nil } // Ensure a pod's SecurityContext is in compliance with the given constraints. func (s *simpleProvider) ValidatePodSecurityContext(pod *api.Pod, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} if pod.Spec.SecurityContext == nil { allErrs = append(allErrs, field.Invalid(fldPath.Child("securityContext"), pod.Spec.SecurityContext, "No security context is set")) return allErrs } fsGroups := []int64{} if pod.Spec.SecurityContext.FSGroup != nil { fsGroups = append(fsGroups, *pod.Spec.SecurityContext.FSGroup) } allErrs = append(allErrs, s.strategies.FSGroupStrategy.Validate(pod, fsGroups)...) allErrs = append(allErrs, s.strategies.SupplementalGroupStrategy.Validate(pod, pod.Spec.SecurityContext.SupplementalGroups)...) // make a dummy container context to reuse the selinux strategies container := &api.Container{ Name: pod.Name, SecurityContext: &api.SecurityContext{ SELinuxOptions: pod.Spec.SecurityContext.SELinuxOptions, }, } allErrs = append(allErrs, s.strategies.SELinuxStrategy.Validate(pod, container)...) if !s.psp.Spec.HostNetwork && pod.Spec.SecurityContext.HostNetwork { allErrs = append(allErrs, field.Invalid(fldPath.Child("hostNetwork"), pod.Spec.SecurityContext.HostNetwork, "Host network is not allowed to be used")) } if !s.psp.Spec.HostPID && pod.Spec.SecurityContext.HostPID { allErrs = append(allErrs, field.Invalid(fldPath.Child("hostPID"), pod.Spec.SecurityContext.HostPID, "Host PID is not allowed to be used")) } if !s.psp.Spec.HostIPC && pod.Spec.SecurityContext.HostIPC { allErrs = append(allErrs, field.Invalid(fldPath.Child("hostIPC"), pod.Spec.SecurityContext.HostIPC, "Host IPC is not allowed to be used")) } return allErrs } // Ensure a container's SecurityContext is in compliance with the given constraints func (s *simpleProvider) ValidateContainerSecurityContext(pod *api.Pod, container *api.Container, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} if container.SecurityContext == nil { allErrs = append(allErrs, field.Invalid(fldPath.Child("securityContext"), container.SecurityContext, "No security context is set")) return allErrs } sc := container.SecurityContext allErrs = append(allErrs, s.strategies.RunAsUserStrategy.Validate(pod, container)...) allErrs = append(allErrs, s.strategies.SELinuxStrategy.Validate(pod, container)...) if !s.psp.Spec.Privileged && *sc.Privileged { allErrs = append(allErrs, field.Invalid(fldPath.Child("privileged"), *sc.Privileged, "Privileged containers are not allowed")) } allErrs = append(allErrs, s.strategies.CapabilitiesStrategy.Validate(pod, container)...) if len(pod.Spec.Volumes) > 0 && !psputil.PSPAllowsAllVolumes(s.psp) { allowedVolumes := psputil.FSTypeToStringSet(s.psp.Spec.Volumes) for i, v := range pod.Spec.Volumes { fsType, err := psputil.GetVolumeFSType(v) if err != nil { allErrs = append(allErrs, field.Invalid(fldPath.Child("volumes").Index(i), string(fsType), err.Error())) continue } if !allowedVolumes.Has(string(fsType)) { allErrs = append(allErrs, field.Invalid( fldPath.Child("volumes").Index(i), string(fsType), fmt.Sprintf("%s volumes are not allowed to be used", string(fsType)))) } } } if !s.psp.Spec.HostNetwork && pod.Spec.SecurityContext.HostNetwork { allErrs = append(allErrs, field.Invalid(fldPath.Child("hostNetwork"), pod.Spec.SecurityContext.HostNetwork, "Host network is not allowed to be used")) } containersPath := fldPath.Child("containers") for idx, c := range pod.Spec.Containers { idxPath := containersPath.Index(idx) allErrs = append(allErrs, s.hasInvalidHostPort(&c, idxPath)...) } containersPath = fldPath.Child("initContainers") for idx, c := range pod.Spec.InitContainers { idxPath := containersPath.Index(idx) allErrs = append(allErrs, s.hasInvalidHostPort(&c, idxPath)...) } if !s.psp.Spec.HostPID && pod.Spec.SecurityContext.HostPID { allErrs = append(allErrs, field.Invalid(fldPath.Child("hostPID"), pod.Spec.SecurityContext.HostPID, "Host PID is not allowed to be used")) } if !s.psp.Spec.HostIPC && pod.Spec.SecurityContext.HostIPC { allErrs = append(allErrs, field.Invalid(fldPath.Child("hostIPC"), pod.Spec.SecurityContext.HostIPC, "Host IPC is not allowed to be used")) } if s.psp.Spec.ReadOnlyRootFilesystem { if sc.ReadOnlyRootFilesystem == nil { allErrs = append(allErrs, field.Invalid(fldPath.Child("readOnlyRootFilesystem"), sc.ReadOnlyRootFilesystem, "ReadOnlyRootFilesystem may not be nil and must be set to true")) } else if !*sc.ReadOnlyRootFilesystem { allErrs = append(allErrs, field.Invalid(fldPath.Child("readOnlyRootFilesystem"), *sc.ReadOnlyRootFilesystem, "ReadOnlyRootFilesystem must be set to true")) } } return allErrs } // hasHostPort checks the port definitions on the container for HostPort > 0. func (s *simpleProvider) hasInvalidHostPort(container *api.Container, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} for _, cp := range container.Ports { if cp.HostPort > 0 && !s.isValidHostPort(int(cp.HostPort)) { detail := fmt.Sprintf("Host port %d is not allowed to be used. Allowed ports: %v", cp.HostPort, s.psp.Spec.HostPorts) allErrs = append(allErrs, field.Invalid(fldPath.Child("hostPort"), cp.HostPort, detail)) } } return allErrs } // isValidHostPort returns true if the port falls in any range allowed by the PSP. func (s *simpleProvider) isValidHostPort(port int) bool { for _, hostPortRange := range s.psp.Spec.HostPorts { if port >= hostPortRange.Min && port <= hostPortRange.Max { return true } } return false } // Get the name of the PSP that this provider was initialized with. func (s *simpleProvider) GetPSPName() string { return s.psp.Name }
pkg/security/podsecuritypolicy/provider.go
0
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.0004448340623639524, 0.0001780746824806556, 0.00016324491298291832, 0.00016977134509943426, 0.000048809684813022614 ]
{ "id": 4, "code_window": [ "\n", "<!-- END STRIP_FOR_RELEASE -->\n", "\n", "<!-- END MUNGE: UNVERSIONED_WARNING -->\n", "\n", "---\n", "assignees:\n", "- brendandburns\n", "- derekwaynecarr\n", "- jbeda\n", "---\n", "\n", "did no\n", "\n", "Running Kubernetes with Vagrant (and VirtualBox) is an easy way to run/test/develop on your local machine (Linux, Mac OS X).\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "docs/devel/local-cluster/vagrant.md", "type": "replace", "edit_start_line_idx": 29 }
/* 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 aws import ( "io" "reflect" "strings" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/elb" "github.com/aws/aws-sdk-go/service/autoscaling" "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/util/sets" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) const TestClusterId = "clusterid.test" const TestClusterName = "testCluster" func TestReadAWSCloudConfig(t *testing.T) { tests := []struct { name string reader io.Reader aws Services expectError bool zone string }{ { "No config reader", nil, nil, true, "", }, { "Empty config, no metadata", strings.NewReader(""), nil, true, "", }, { "No zone in config, no metadata", strings.NewReader("[global]\n"), nil, true, "", }, { "Zone in config, no metadata", strings.NewReader("[global]\nzone = eu-west-1a"), nil, false, "eu-west-1a", }, { "No zone in config, metadata does not have zone", strings.NewReader("[global]\n"), NewFakeAWSServices().withAz(""), true, "", }, { "No zone in config, metadata has zone", strings.NewReader("[global]\n"), NewFakeAWSServices(), false, "us-east-1a", }, { "Zone in config should take precedence over metadata", strings.NewReader("[global]\nzone = eu-west-1a"), NewFakeAWSServices(), false, "eu-west-1a", }, } for _, test := range tests { t.Logf("Running test case %s", test.name) var metadata EC2Metadata if test.aws != nil { metadata, _ = test.aws.Metadata() } cfg, err := readAWSCloudConfig(test.reader, metadata) if test.expectError { if err == nil { t.Errorf("Should error for case %s (cfg=%v)", test.name, cfg) } } else { if err != nil { t.Errorf("Should succeed for case: %s", test.name) } if cfg.Global.Zone != test.zone { t.Errorf("Incorrect zone value (%s vs %s) for case: %s", cfg.Global.Zone, test.zone, test.name) } } } } type FakeAWSServices struct { region string instances []*ec2.Instance selfInstance *ec2.Instance networkInterfacesMacs []string networkInterfacesVpcIDs []string ec2 *FakeEC2 elb *FakeELB asg *FakeASG metadata *FakeMetadata } func NewFakeAWSServices() *FakeAWSServices { s := &FakeAWSServices{} s.region = "us-east-1" s.ec2 = &FakeEC2{aws: s} s.elb = &FakeELB{aws: s} s.asg = &FakeASG{aws: s} s.metadata = &FakeMetadata{aws: s} s.networkInterfacesMacs = []string{"aa:bb:cc:dd:ee:00", "aa:bb:cc:dd:ee:01"} s.networkInterfacesVpcIDs = []string{"vpc-mac0", "vpc-mac1"} selfInstance := &ec2.Instance{} selfInstance.InstanceId = aws.String("i-self") selfInstance.Placement = &ec2.Placement{ AvailabilityZone: aws.String("us-east-1a"), } selfInstance.PrivateDnsName = aws.String("ip-172-20-0-100.ec2.internal") selfInstance.PrivateIpAddress = aws.String("192.168.0.1") selfInstance.PublicIpAddress = aws.String("1.2.3.4") s.selfInstance = selfInstance s.instances = []*ec2.Instance{selfInstance} var tag ec2.Tag tag.Key = aws.String(TagNameKubernetesCluster) tag.Value = aws.String(TestClusterId) selfInstance.Tags = []*ec2.Tag{&tag} return s } func (s *FakeAWSServices) withAz(az string) *FakeAWSServices { if s.selfInstance.Placement == nil { s.selfInstance.Placement = &ec2.Placement{} } s.selfInstance.Placement.AvailabilityZone = aws.String(az) return s } func (s *FakeAWSServices) Compute(region string) (EC2, error) { return s.ec2, nil } func (s *FakeAWSServices) LoadBalancing(region string) (ELB, error) { return s.elb, nil } func (s *FakeAWSServices) Autoscaling(region string) (ASG, error) { return s.asg, nil } func (s *FakeAWSServices) Metadata() (EC2Metadata, error) { return s.metadata, nil } func TestFilterTags(t *testing.T) { awsServices := NewFakeAWSServices() c, err := newAWSCloud(strings.NewReader("[global]"), awsServices) if err != nil { t.Errorf("Error building aws cloud: %v", err) return } if len(c.filterTags) != 1 { t.Errorf("unexpected filter tags: %v", c.filterTags) return } if c.filterTags[TagNameKubernetesCluster] != TestClusterId { t.Errorf("unexpected filter tags: %v", c.filterTags) } } func TestNewAWSCloud(t *testing.T) { tests := []struct { name string reader io.Reader awsServices Services expectError bool region string }{ { "No config reader", nil, NewFakeAWSServices().withAz(""), true, "", }, { "Config specified invalid zone", strings.NewReader("[global]\nzone = blahonga"), NewFakeAWSServices(), true, "", }, { "Config specifies valid zone", strings.NewReader("[global]\nzone = eu-west-1a"), NewFakeAWSServices(), false, "eu-west-1", }, { "Gets zone from metadata when not in config", strings.NewReader("[global]\n"), NewFakeAWSServices(), false, "us-east-1", }, { "No zone in config or metadata", strings.NewReader("[global]\n"), NewFakeAWSServices().withAz(""), true, "", }, } for _, test := range tests { t.Logf("Running test case %s", test.name) c, err := newAWSCloud(test.reader, test.awsServices) if test.expectError { if err == nil { t.Errorf("Should error for case %s", test.name) } } else { if err != nil { t.Errorf("Should succeed for case: %s, got %v", test.name, err) } else if c.region != test.region { t.Errorf("Incorrect region value (%s vs %s) for case: %s", c.region, test.region, test.name) } } } } type FakeEC2 struct { aws *FakeAWSServices Subnets []*ec2.Subnet DescribeSubnetsInput *ec2.DescribeSubnetsInput RouteTables []*ec2.RouteTable DescribeRouteTablesInput *ec2.DescribeRouteTablesInput mock.Mock } func contains(haystack []*string, needle string) bool { for _, s := range haystack { // (deliberately panic if s == nil) if needle == *s { return true } } return false } func instanceMatchesFilter(instance *ec2.Instance, filter *ec2.Filter) bool { name := *filter.Name if name == "private-dns-name" { if instance.PrivateDnsName == nil { return false } return contains(filter.Values, *instance.PrivateDnsName) } if name == "instance-state-name" { return contains(filter.Values, *instance.State.Name) } if strings.HasPrefix(name, "tag:") { tagName := name[4:] for _, instanceTag := range instance.Tags { if aws.StringValue(instanceTag.Key) == tagName && contains(filter.Values, aws.StringValue(instanceTag.Value)) { return true } } } panic("Unknown filter name: " + name) } func (self *FakeEC2) DescribeInstances(request *ec2.DescribeInstancesInput) ([]*ec2.Instance, error) { matches := []*ec2.Instance{} for _, instance := range self.aws.instances { if request.InstanceIds != nil { if instance.InstanceId == nil { glog.Warning("Instance with no instance id: ", instance) continue } found := false for _, instanceID := range request.InstanceIds { if *instanceID == *instance.InstanceId { found = true break } } if !found { continue } } if request.Filters != nil { allMatch := true for _, filter := range request.Filters { if !instanceMatchesFilter(instance, filter) { allMatch = false break } } if !allMatch { continue } } matches = append(matches, instance) } return matches, nil } type FakeMetadata struct { aws *FakeAWSServices } func (self *FakeMetadata) GetMetadata(key string) (string, error) { networkInterfacesPrefix := "network/interfaces/macs/" i := self.aws.selfInstance if key == "placement/availability-zone" { az := "" if i.Placement != nil { az = aws.StringValue(i.Placement.AvailabilityZone) } return az, nil } else if key == "instance-id" { return aws.StringValue(i.InstanceId), nil } else if key == "local-hostname" { return aws.StringValue(i.PrivateDnsName), nil } else if key == "local-ipv4" { return aws.StringValue(i.PrivateIpAddress), nil } else if key == "public-ipv4" { return aws.StringValue(i.PublicIpAddress), nil } else if strings.HasPrefix(key, networkInterfacesPrefix) { if key == networkInterfacesPrefix { return strings.Join(self.aws.networkInterfacesMacs, "/\n") + "/\n", nil } else { keySplit := strings.Split(key, "/") macParam := keySplit[3] if len(keySplit) == 5 && keySplit[4] == "vpc-id" { for i, macElem := range self.aws.networkInterfacesMacs { if macParam == macElem { return self.aws.networkInterfacesVpcIDs[i], nil } } } return "", nil } } else { return "", nil } } func (ec2 *FakeEC2) AttachVolume(request *ec2.AttachVolumeInput) (resp *ec2.VolumeAttachment, err error) { panic("Not implemented") } func (ec2 *FakeEC2) DetachVolume(request *ec2.DetachVolumeInput) (resp *ec2.VolumeAttachment, err error) { panic("Not implemented") } func (e *FakeEC2) DescribeVolumes(request *ec2.DescribeVolumesInput) ([]*ec2.Volume, error) { args := e.Called(request) return args.Get(0).([]*ec2.Volume), nil } func (ec2 *FakeEC2) CreateVolume(request *ec2.CreateVolumeInput) (resp *ec2.Volume, err error) { panic("Not implemented") } func (ec2 *FakeEC2) DeleteVolume(request *ec2.DeleteVolumeInput) (resp *ec2.DeleteVolumeOutput, err error) { panic("Not implemented") } func (ec2 *FakeEC2) DescribeSecurityGroups(request *ec2.DescribeSecurityGroupsInput) ([]*ec2.SecurityGroup, error) { panic("Not implemented") } func (ec2 *FakeEC2) CreateSecurityGroup(*ec2.CreateSecurityGroupInput) (*ec2.CreateSecurityGroupOutput, error) { panic("Not implemented") } func (ec2 *FakeEC2) DeleteSecurityGroup(*ec2.DeleteSecurityGroupInput) (*ec2.DeleteSecurityGroupOutput, error) { panic("Not implemented") } func (ec2 *FakeEC2) AuthorizeSecurityGroupIngress(*ec2.AuthorizeSecurityGroupIngressInput) (*ec2.AuthorizeSecurityGroupIngressOutput, error) { panic("Not implemented") } func (ec2 *FakeEC2) RevokeSecurityGroupIngress(*ec2.RevokeSecurityGroupIngressInput) (*ec2.RevokeSecurityGroupIngressOutput, error) { panic("Not implemented") } func (ec2 *FakeEC2) DescribeSubnets(request *ec2.DescribeSubnetsInput) ([]*ec2.Subnet, error) { ec2.DescribeSubnetsInput = request return ec2.Subnets, nil } func (ec2 *FakeEC2) CreateTags(*ec2.CreateTagsInput) (*ec2.CreateTagsOutput, error) { panic("Not implemented") } func (ec2 *FakeEC2) DescribeRouteTables(request *ec2.DescribeRouteTablesInput) ([]*ec2.RouteTable, error) { ec2.DescribeRouteTablesInput = request return ec2.RouteTables, nil } func (s *FakeEC2) CreateRoute(request *ec2.CreateRouteInput) (*ec2.CreateRouteOutput, error) { panic("Not implemented") } func (s *FakeEC2) DeleteRoute(request *ec2.DeleteRouteInput) (*ec2.DeleteRouteOutput, error) { panic("Not implemented") } func (s *FakeEC2) ModifyInstanceAttribute(request *ec2.ModifyInstanceAttributeInput) (*ec2.ModifyInstanceAttributeOutput, error) { panic("Not implemented") } type FakeELB struct { aws *FakeAWSServices mock.Mock } func (ec2 *FakeELB) CreateLoadBalancer(*elb.CreateLoadBalancerInput) (*elb.CreateLoadBalancerOutput, error) { panic("Not implemented") } func (ec2 *FakeELB) DeleteLoadBalancer(input *elb.DeleteLoadBalancerInput) (*elb.DeleteLoadBalancerOutput, error) { panic("Not implemented") } func (ec2 *FakeELB) DescribeLoadBalancers(input *elb.DescribeLoadBalancersInput) (*elb.DescribeLoadBalancersOutput, error) { args := ec2.Called(input) return args.Get(0).(*elb.DescribeLoadBalancersOutput), nil } func (ec2 *FakeELB) RegisterInstancesWithLoadBalancer(*elb.RegisterInstancesWithLoadBalancerInput) (*elb.RegisterInstancesWithLoadBalancerOutput, error) { panic("Not implemented") } func (ec2 *FakeELB) DeregisterInstancesFromLoadBalancer(*elb.DeregisterInstancesFromLoadBalancerInput) (*elb.DeregisterInstancesFromLoadBalancerOutput, error) { panic("Not implemented") } func (ec2 *FakeELB) DetachLoadBalancerFromSubnets(*elb.DetachLoadBalancerFromSubnetsInput) (*elb.DetachLoadBalancerFromSubnetsOutput, error) { panic("Not implemented") } func (ec2 *FakeELB) AttachLoadBalancerToSubnets(*elb.AttachLoadBalancerToSubnetsInput) (*elb.AttachLoadBalancerToSubnetsOutput, error) { panic("Not implemented") } func (ec2 *FakeELB) CreateLoadBalancerListeners(*elb.CreateLoadBalancerListenersInput) (*elb.CreateLoadBalancerListenersOutput, error) { panic("Not implemented") } func (ec2 *FakeELB) DeleteLoadBalancerListeners(*elb.DeleteLoadBalancerListenersInput) (*elb.DeleteLoadBalancerListenersOutput, error) { panic("Not implemented") } func (ec2 *FakeELB) ApplySecurityGroupsToLoadBalancer(*elb.ApplySecurityGroupsToLoadBalancerInput) (*elb.ApplySecurityGroupsToLoadBalancerOutput, error) { panic("Not implemented") } func (elb *FakeELB) ConfigureHealthCheck(*elb.ConfigureHealthCheckInput) (*elb.ConfigureHealthCheckOutput, error) { panic("Not implemented") } func (elb *FakeELB) CreateLoadBalancerPolicy(*elb.CreateLoadBalancerPolicyInput) (*elb.CreateLoadBalancerPolicyOutput, error) { panic("Not implemented") } func (elb *FakeELB) SetLoadBalancerPoliciesForBackendServer(*elb.SetLoadBalancerPoliciesForBackendServerInput) (*elb.SetLoadBalancerPoliciesForBackendServerOutput, error) { panic("Not implemented") } type FakeASG struct { aws *FakeAWSServices } func (a *FakeASG) UpdateAutoScalingGroup(*autoscaling.UpdateAutoScalingGroupInput) (*autoscaling.UpdateAutoScalingGroupOutput, error) { panic("Not implemented") } func (a *FakeASG) DescribeAutoScalingGroups(*autoscaling.DescribeAutoScalingGroupsInput) (*autoscaling.DescribeAutoScalingGroupsOutput, error) { panic("Not implemented") } func mockInstancesResp(selfInstance *ec2.Instance, instances []*ec2.Instance) (*Cloud, *FakeAWSServices) { awsServices := NewFakeAWSServices() awsServices.instances = instances awsServices.selfInstance = selfInstance awsCloud, err := newAWSCloud(nil, awsServices) if err != nil { panic(err) } return awsCloud, awsServices } func mockAvailabilityZone(availabilityZone string) *Cloud { awsServices := NewFakeAWSServices().withAz(availabilityZone) awsCloud, err := newAWSCloud(nil, awsServices) if err != nil { panic(err) } return awsCloud } func TestList(t *testing.T) { // TODO this setup is not very clean and could probably be improved var instance0 ec2.Instance var instance1 ec2.Instance var instance2 ec2.Instance var instance3 ec2.Instance //0 tag0 := ec2.Tag{ Key: aws.String("Name"), Value: aws.String("foo"), } instance0.Tags = []*ec2.Tag{&tag0} instance0.InstanceId = aws.String("instance0") instance0.PrivateDnsName = aws.String("instance0.ec2.internal") instance0.Placement = &ec2.Placement{AvailabilityZone: aws.String("us-east-1a")} state0 := ec2.InstanceState{ Name: aws.String("running"), } instance0.State = &state0 //1 tag1 := ec2.Tag{ Key: aws.String("Name"), Value: aws.String("bar"), } instance1.Tags = []*ec2.Tag{&tag1} instance1.InstanceId = aws.String("instance1") instance1.PrivateDnsName = aws.String("instance1.ec2.internal") instance1.Placement = &ec2.Placement{AvailabilityZone: aws.String("us-east-1a")} state1 := ec2.InstanceState{ Name: aws.String("running"), } instance1.State = &state1 //2 tag2 := ec2.Tag{ Key: aws.String("Name"), Value: aws.String("baz"), } instance2.Tags = []*ec2.Tag{&tag2} instance2.InstanceId = aws.String("instance2") instance2.PrivateDnsName = aws.String("instance2.ec2.internal") instance2.Placement = &ec2.Placement{AvailabilityZone: aws.String("us-east-1a")} state2 := ec2.InstanceState{ Name: aws.String("running"), } instance2.State = &state2 //3 tag3 := ec2.Tag{ Key: aws.String("Name"), Value: aws.String("quux"), } instance3.Tags = []*ec2.Tag{&tag3} instance3.InstanceId = aws.String("instance3") instance3.PrivateDnsName = aws.String("instance3.ec2.internal") instance3.Placement = &ec2.Placement{AvailabilityZone: aws.String("us-east-1a")} state3 := ec2.InstanceState{ Name: aws.String("running"), } instance3.State = &state3 instances := []*ec2.Instance{&instance0, &instance1, &instance2, &instance3} aws, _ := mockInstancesResp(&instance0, instances) table := []struct { input string expect []string }{ {"blahonga", []string{}}, {"quux", []string{"instance3.ec2.internal"}}, {"a", []string{"instance1.ec2.internal", "instance2.ec2.internal"}}, } for _, item := range table { result, err := aws.List(item.input) if err != nil { t.Errorf("Expected call with %v to succeed, failed with %v", item.input, err) } if e, a := item.expect, result; !reflect.DeepEqual(e, a) { t.Errorf("Expected %v, got %v", e, a) } } } func testHasNodeAddress(t *testing.T, addrs []api.NodeAddress, addressType api.NodeAddressType, address string) { for _, addr := range addrs { if addr.Type == addressType && addr.Address == address { return } } t.Errorf("Did not find expected address: %s:%s in %v", addressType, address, addrs) } func TestNodeAddresses(t *testing.T) { // Note these instances have the same name // (we test that this produces an error) var instance0 ec2.Instance var instance1 ec2.Instance var instance2 ec2.Instance //0 instance0.InstanceId = aws.String("i-0") instance0.PrivateDnsName = aws.String("instance-same.ec2.internal") instance0.PrivateIpAddress = aws.String("192.168.0.1") instance0.PublicIpAddress = aws.String("1.2.3.4") instance0.InstanceType = aws.String("c3.large") instance0.Placement = &ec2.Placement{AvailabilityZone: aws.String("us-east-1a")} state0 := ec2.InstanceState{ Name: aws.String("running"), } instance0.State = &state0 //1 instance1.InstanceId = aws.String("i-1") instance1.PrivateDnsName = aws.String("instance-same.ec2.internal") instance1.PrivateIpAddress = aws.String("192.168.0.2") instance1.InstanceType = aws.String("c3.large") instance1.Placement = &ec2.Placement{AvailabilityZone: aws.String("us-east-1a")} state1 := ec2.InstanceState{ Name: aws.String("running"), } instance1.State = &state1 //2 instance2.InstanceId = aws.String("i-2") instance2.PrivateDnsName = aws.String("instance-other.ec2.internal") instance2.PrivateIpAddress = aws.String("192.168.0.1") instance2.PublicIpAddress = aws.String("1.2.3.4") instance2.InstanceType = aws.String("c3.large") instance2.Placement = &ec2.Placement{AvailabilityZone: aws.String("us-east-1a")} state2 := ec2.InstanceState{ Name: aws.String("running"), } instance2.State = &state2 instances := []*ec2.Instance{&instance0, &instance1, &instance2} aws1, _ := mockInstancesResp(&instance0, []*ec2.Instance{&instance0}) _, err1 := aws1.NodeAddresses("instance-mismatch.ec2.internal") if err1 == nil { t.Errorf("Should error when no instance found") } aws2, _ := mockInstancesResp(&instance2, instances) _, err2 := aws2.NodeAddresses("instance-same.ec2.internal") if err2 == nil { t.Errorf("Should error when multiple instances found") } aws3, _ := mockInstancesResp(&instance0, instances[0:1]) addrs3, err3 := aws3.NodeAddresses("instance-same.ec2.internal") if err3 != nil { t.Errorf("Should not error when instance found") } if len(addrs3) != 3 { t.Errorf("Should return exactly 3 NodeAddresses") } testHasNodeAddress(t, addrs3, api.NodeInternalIP, "192.168.0.1") testHasNodeAddress(t, addrs3, api.NodeLegacyHostIP, "192.168.0.1") testHasNodeAddress(t, addrs3, api.NodeExternalIP, "1.2.3.4") // Fetch from metadata aws4, fakeServices := mockInstancesResp(&instance0, []*ec2.Instance{&instance0}) fakeServices.selfInstance.PublicIpAddress = aws.String("2.3.4.5") fakeServices.selfInstance.PrivateIpAddress = aws.String("192.168.0.2") addrs4, err4 := aws4.NodeAddresses(*instance0.PrivateDnsName) if err4 != nil { t.Errorf("unexpected error: %v", err4) } testHasNodeAddress(t, addrs4, api.NodeInternalIP, "192.168.0.2") testHasNodeAddress(t, addrs4, api.NodeExternalIP, "2.3.4.5") } func TestGetRegion(t *testing.T) { aws := mockAvailabilityZone("us-west-2e") zones, ok := aws.Zones() if !ok { t.Fatalf("Unexpected missing zones impl") } zone, err := zones.GetZone() if err != nil { t.Fatalf("unexpected error %v", err) } if zone.Region != "us-west-2" { t.Errorf("Unexpected region: %s", zone.Region) } if zone.FailureDomain != "us-west-2e" { t.Errorf("Unexpected FailureDomain: %s", zone.FailureDomain) } } func TestFindVPCID(t *testing.T) { awsServices := NewFakeAWSServices() c, err := newAWSCloud(strings.NewReader("[global]"), awsServices) if err != nil { t.Errorf("Error building aws cloud: %v", err) return } vpcID, err := c.findVPCID() if err != nil { t.Errorf("Unexpected error: %v", err) } if vpcID != "vpc-mac0" { t.Errorf("Unexpected vpcID: %s", vpcID) } } func constructSubnets(subnetsIn map[int]map[string]string) (subnetsOut []*ec2.Subnet) { for i := range subnetsIn { subnetsOut = append( subnetsOut, constructSubnet( subnetsIn[i]["id"], subnetsIn[i]["az"], ), ) } return } func constructSubnet(id string, az string) *ec2.Subnet { return &ec2.Subnet{ SubnetId: &id, AvailabilityZone: &az, } } func constructRouteTables(routeTablesIn map[string]bool) (routeTablesOut []*ec2.RouteTable) { routeTablesOut = append(routeTablesOut, &ec2.RouteTable{ Associations: []*ec2.RouteTableAssociation{{Main: aws.Bool(true)}}, Routes: []*ec2.Route{{ DestinationCidrBlock: aws.String("0.0.0.0/0"), GatewayId: aws.String("igw-main"), }}, }) for subnetID := range routeTablesIn { routeTablesOut = append( routeTablesOut, constructRouteTable( subnetID, routeTablesIn[subnetID], ), ) } return } func constructRouteTable(subnetID string, public bool) *ec2.RouteTable { var gatewayID string if public { gatewayID = "igw-" + subnetID[len(subnetID)-8:8] } else { gatewayID = "vgw-" + subnetID[len(subnetID)-8:8] } return &ec2.RouteTable{ Associations: []*ec2.RouteTableAssociation{{SubnetId: aws.String(subnetID)}}, Routes: []*ec2.Route{{ DestinationCidrBlock: aws.String("0.0.0.0/0"), GatewayId: aws.String(gatewayID), }}, } } func TestSubnetIDsinVPC(t *testing.T) { awsServices := NewFakeAWSServices() c, err := newAWSCloud(strings.NewReader("[global]"), awsServices) if err != nil { t.Errorf("Error building aws cloud: %v", err) return } // test with 3 subnets from 3 different AZs subnets := make(map[int]map[string]string) subnets[0] = make(map[string]string) subnets[0]["id"] = "subnet-a0000001" subnets[0]["az"] = "af-south-1a" subnets[1] = make(map[string]string) subnets[1]["id"] = "subnet-b0000001" subnets[1]["az"] = "af-south-1b" subnets[2] = make(map[string]string) subnets[2]["id"] = "subnet-c0000001" subnets[2]["az"] = "af-south-1c" awsServices.ec2.Subnets = constructSubnets(subnets) routeTables := map[string]bool{ "subnet-a0000001": true, "subnet-b0000001": true, "subnet-c0000001": true, } awsServices.ec2.RouteTables = constructRouteTables(routeTables) result, err := c.findELBSubnets(false) if err != nil { t.Errorf("Error listing subnets: %v", err) return } if len(result) != 3 { t.Errorf("Expected 3 subnets but got %d", len(result)) return } result_set := make(map[string]bool) for _, v := range result { result_set[v] = true } for i := range subnets { if !result_set[subnets[i]["id"]] { t.Errorf("Expected subnet%d '%s' in result: %v", i, subnets[i]["id"], result) return } } // test implicit routing table - when subnets are not explicitly linked to a table they should use main awsServices.ec2.RouteTables = constructRouteTables(map[string]bool{}) result, err = c.findELBSubnets(false) if err != nil { t.Errorf("Error listing subnets: %v", err) return } if len(result) != 3 { t.Errorf("Expected 3 subnets but got %d", len(result)) return } result_set = make(map[string]bool) for _, v := range result { result_set[v] = true } for i := range subnets { if !result_set[subnets[i]["id"]] { t.Errorf("Expected subnet%d '%s' in result: %v", i, subnets[i]["id"], result) return } } // test with 4 subnets from 3 different AZs // add duplicate az subnet subnets[3] = make(map[string]string) subnets[3]["id"] = "subnet-c0000002" subnets[3]["az"] = "af-south-1c" awsServices.ec2.Subnets = constructSubnets(subnets) routeTables["subnet-c0000002"] = true awsServices.ec2.RouteTables = constructRouteTables(routeTables) result, err = c.findELBSubnets(false) if err != nil { t.Errorf("Error listing subnets: %v", err) return } if len(result) != 3 { t.Errorf("Expected 3 subnets but got %d", len(result)) return } // test with 6 subnets from 3 different AZs // with 3 private subnets subnets[4] = make(map[string]string) subnets[4]["id"] = "subnet-d0000001" subnets[4]["az"] = "af-south-1a" subnets[5] = make(map[string]string) subnets[5]["id"] = "subnet-d0000002" subnets[5]["az"] = "af-south-1b" awsServices.ec2.Subnets = constructSubnets(subnets) routeTables["subnet-a0000001"] = false routeTables["subnet-b0000001"] = false routeTables["subnet-c0000001"] = false routeTables["subnet-c0000002"] = true routeTables["subnet-d0000001"] = true routeTables["subnet-d0000002"] = true awsServices.ec2.RouteTables = constructRouteTables(routeTables) result, err = c.findELBSubnets(false) if err != nil { t.Errorf("Error listing subnets: %v", err) return } if len(result) != 3 { t.Errorf("Expected 3 subnets but got %d", len(result)) return } expected := []*string{aws.String("subnet-c0000002"), aws.String("subnet-d0000001"), aws.String("subnet-d0000002")} for _, s := range result { if !contains(expected, s) { t.Errorf("Unexpected subnet '%s' found", s) return } } } func TestIpPermissionExistsHandlesMultipleGroupIds(t *testing.T) { oldIpPermission := ec2.IpPermission{ UserIdGroupPairs: []*ec2.UserIdGroupPair{ {GroupId: aws.String("firstGroupId")}, {GroupId: aws.String("secondGroupId")}, {GroupId: aws.String("thirdGroupId")}, }, } existingIpPermission := ec2.IpPermission{ UserIdGroupPairs: []*ec2.UserIdGroupPair{ {GroupId: aws.String("secondGroupId")}, }, } newIpPermission := ec2.IpPermission{ UserIdGroupPairs: []*ec2.UserIdGroupPair{ {GroupId: aws.String("fourthGroupId")}, }, } equals := ipPermissionExists(&existingIpPermission, &oldIpPermission, false) if !equals { t.Errorf("Should have been considered equal since first is in the second array of groups") } equals = ipPermissionExists(&newIpPermission, &oldIpPermission, false) if equals { t.Errorf("Should have not been considered equal since first is not in the second array of groups") } } func TestIpPermissionExistsHandlesRangeSubsets(t *testing.T) { // Two existing scenarios we'll test against emptyIpPermission := ec2.IpPermission{} oldIpPermission := ec2.IpPermission{ IpRanges: []*ec2.IpRange{ {CidrIp: aws.String("10.0.0.0/8")}, {CidrIp: aws.String("192.168.1.0/24")}, }, } // Two already existing ranges and a new one existingIpPermission := ec2.IpPermission{ IpRanges: []*ec2.IpRange{ {CidrIp: aws.String("10.0.0.0/8")}, }, } existingIpPermission2 := ec2.IpPermission{ IpRanges: []*ec2.IpRange{ {CidrIp: aws.String("192.168.1.0/24")}, }, } newIpPermission := ec2.IpPermission{ IpRanges: []*ec2.IpRange{ {CidrIp: aws.String("172.16.0.0/16")}, }, } exists := ipPermissionExists(&emptyIpPermission, &emptyIpPermission, false) if !exists { t.Errorf("Should have been considered existing since we're comparing a range array against itself") } exists = ipPermissionExists(&oldIpPermission, &oldIpPermission, false) if !exists { t.Errorf("Should have been considered existing since we're comparing a range array against itself") } exists = ipPermissionExists(&existingIpPermission, &oldIpPermission, false) if !exists { t.Errorf("Should have been considered existing since 10.* is in oldIpPermission's array of ranges") } exists = ipPermissionExists(&existingIpPermission2, &oldIpPermission, false) if !exists { t.Errorf("Should have been considered existing since 192.* is in oldIpPermission2's array of ranges") } exists = ipPermissionExists(&newIpPermission, &emptyIpPermission, false) if exists { t.Errorf("Should have not been considered existing since we compared against a missing array of ranges") } exists = ipPermissionExists(&newIpPermission, &oldIpPermission, false) if exists { t.Errorf("Should have not been considered existing since 172.* is not in oldIpPermission's array of ranges") } } func TestIpPermissionExistsHandlesMultipleGroupIdsWithUserIds(t *testing.T) { oldIpPermission := ec2.IpPermission{ UserIdGroupPairs: []*ec2.UserIdGroupPair{ {GroupId: aws.String("firstGroupId"), UserId: aws.String("firstUserId")}, {GroupId: aws.String("secondGroupId"), UserId: aws.String("secondUserId")}, {GroupId: aws.String("thirdGroupId"), UserId: aws.String("thirdUserId")}, }, } existingIpPermission := ec2.IpPermission{ UserIdGroupPairs: []*ec2.UserIdGroupPair{ {GroupId: aws.String("secondGroupId"), UserId: aws.String("secondUserId")}, }, } newIpPermission := ec2.IpPermission{ UserIdGroupPairs: []*ec2.UserIdGroupPair{ {GroupId: aws.String("secondGroupId"), UserId: aws.String("anotherUserId")}, }, } equals := ipPermissionExists(&existingIpPermission, &oldIpPermission, true) if !equals { t.Errorf("Should have been considered equal since first is in the second array of groups") } equals = ipPermissionExists(&newIpPermission, &oldIpPermission, true) if equals { t.Errorf("Should have not been considered equal since first is not in the second array of groups") } } func TestFindInstanceByNodeNameExcludesTerminatedInstances(t *testing.T) { awsServices := NewFakeAWSServices() nodeName := "my-dns.internal" var tag ec2.Tag tag.Key = aws.String(TagNameKubernetesCluster) tag.Value = aws.String(TestClusterId) tags := []*ec2.Tag{&tag} var runningInstance ec2.Instance runningInstance.InstanceId = aws.String("i-running") runningInstance.PrivateDnsName = aws.String(nodeName) runningInstance.State = &ec2.InstanceState{Code: aws.Int64(16), Name: aws.String("running")} runningInstance.Tags = tags var terminatedInstance ec2.Instance terminatedInstance.InstanceId = aws.String("i-terminated") terminatedInstance.PrivateDnsName = aws.String(nodeName) terminatedInstance.State = &ec2.InstanceState{Code: aws.Int64(48), Name: aws.String("terminated")} terminatedInstance.Tags = tags instances := []*ec2.Instance{&terminatedInstance, &runningInstance} awsServices.instances = append(awsServices.instances, instances...) c, err := newAWSCloud(strings.NewReader("[global]"), awsServices) if err != nil { t.Errorf("Error building aws cloud: %v", err) return } instance, err := c.findInstanceByNodeName(nodeName) if err != nil { t.Errorf("Failed to find instance: %v", err) return } if *instance.InstanceId != "i-running" { t.Errorf("Expected running instance but got %v", *instance.InstanceId) } } func TestFindInstancesByNodeNameCached(t *testing.T) { awsServices := NewFakeAWSServices() nodeNameOne := "my-dns.internal" nodeNameTwo := "my-dns-two.internal" var tag ec2.Tag tag.Key = aws.String(TagNameKubernetesCluster) tag.Value = aws.String(TestClusterId) tags := []*ec2.Tag{&tag} var runningInstance ec2.Instance runningInstance.InstanceId = aws.String("i-running") runningInstance.PrivateDnsName = aws.String(nodeNameOne) runningInstance.State = &ec2.InstanceState{Code: aws.Int64(16), Name: aws.String("running")} runningInstance.Tags = tags var secondInstance ec2.Instance secondInstance.InstanceId = aws.String("i-running") secondInstance.PrivateDnsName = aws.String(nodeNameTwo) secondInstance.State = &ec2.InstanceState{Code: aws.Int64(48), Name: aws.String("running")} secondInstance.Tags = tags var terminatedInstance ec2.Instance terminatedInstance.InstanceId = aws.String("i-terminated") terminatedInstance.PrivateDnsName = aws.String(nodeNameOne) terminatedInstance.State = &ec2.InstanceState{Code: aws.Int64(48), Name: aws.String("terminated")} terminatedInstance.Tags = tags instances := []*ec2.Instance{&secondInstance, &runningInstance, &terminatedInstance} awsServices.instances = append(awsServices.instances, instances...) c, err := newAWSCloud(strings.NewReader("[global]"), awsServices) if err != nil { t.Errorf("Error building aws cloud: %v", err) return } nodeNames := sets.NewString(nodeNameOne) returnedInstances, errr := c.getInstancesByNodeNamesCached(nodeNames) if errr != nil { t.Errorf("Failed to find instance: %v", err) return } if len(returnedInstances) != 1 { t.Errorf("Expected a single isntance but found: %v", returnedInstances) } if *returnedInstances[0].PrivateDnsName != nodeNameOne { t.Errorf("Expected node name %v but got %v", nodeNameOne, returnedInstances[0].PrivateDnsName) } } func TestGetVolumeLabels(t *testing.T) { awsServices := NewFakeAWSServices() c, err := newAWSCloud(strings.NewReader("[global]"), awsServices) assert.Nil(t, err, "Error building aws cloud: %v", err) volumeId := aws.String("vol-VolumeId") expectedVolumeRequest := &ec2.DescribeVolumesInput{VolumeIds: []*string{volumeId}} awsServices.ec2.On("DescribeVolumes", expectedVolumeRequest).Return([]*ec2.Volume{ { VolumeId: volumeId, AvailabilityZone: aws.String("us-east-1a"), }, }) labels, err := c.GetVolumeLabels(*volumeId) assert.Nil(t, err, "Error creating Volume %v", err) assert.Equal(t, map[string]string{ unversioned.LabelZoneFailureDomain: "us-east-1a", unversioned.LabelZoneRegion: "us-east-1"}, labels) awsServices.ec2.AssertExpectations(t) } func (self *FakeELB) expectDescribeLoadBalancers(loadBalancerName string) { self.On("DescribeLoadBalancers", &elb.DescribeLoadBalancersInput{LoadBalancerNames: []*string{aws.String(loadBalancerName)}}).Return(&elb.DescribeLoadBalancersOutput{ LoadBalancerDescriptions: []*elb.LoadBalancerDescription{{}}, }) } func TestDescribeLoadBalancerOnDelete(t *testing.T) { awsServices := NewFakeAWSServices() c, _ := newAWSCloud(strings.NewReader("[global]"), awsServices) awsServices.elb.expectDescribeLoadBalancers("aid") c.EnsureLoadBalancerDeleted(TestClusterName, &api.Service{ObjectMeta: api.ObjectMeta{Name: "myservice", UID: "id"}}) } func TestDescribeLoadBalancerOnUpdate(t *testing.T) { awsServices := NewFakeAWSServices() c, _ := newAWSCloud(strings.NewReader("[global]"), awsServices) awsServices.elb.expectDescribeLoadBalancers("aid") c.UpdateLoadBalancer(TestClusterName, &api.Service{ObjectMeta: api.ObjectMeta{Name: "myservice", UID: "id"}}, []string{}) } func TestDescribeLoadBalancerOnGet(t *testing.T) { awsServices := NewFakeAWSServices() c, _ := newAWSCloud(strings.NewReader("[global]"), awsServices) awsServices.elb.expectDescribeLoadBalancers("aid") c.GetLoadBalancer(TestClusterName, &api.Service{ObjectMeta: api.ObjectMeta{Name: "myservice", UID: "id"}}) } func TestDescribeLoadBalancerOnEnsure(t *testing.T) { awsServices := NewFakeAWSServices() c, _ := newAWSCloud(strings.NewReader("[global]"), awsServices) awsServices.elb.expectDescribeLoadBalancers("aid") c.EnsureLoadBalancer(TestClusterName, &api.Service{ObjectMeta: api.ObjectMeta{Name: "myservice", UID: "id"}}, []string{}) } func TestBuildListener(t *testing.T) { tests := []struct { name string lbPort int64 portName string instancePort int64 backendProtocolAnnotation string certAnnotation string sslPortAnnotation string expectError bool lbProtocol string instanceProtocol string certID string }{ { "No cert or BE protocol annotation, passthrough", 80, "", 7999, "", "", "", false, "tcp", "tcp", "", }, { "Cert annotation without BE protocol specified, SSL->TCP", 80, "", 8000, "", "cert", "", false, "ssl", "tcp", "cert", }, { "BE protocol without cert annotation, passthrough", 443, "", 8001, "https", "", "", false, "tcp", "tcp", "", }, { "Invalid cert annotation, bogus backend protocol", 443, "", 8002, "bacon", "foo", "", true, "tcp", "tcp", "", }, { "Invalid cert annotation, protocol followed by equal sign", 443, "", 8003, "http=", "=", "", true, "tcp", "tcp", "", }, { "HTTPS->HTTPS", 443, "", 8004, "https", "cert", "", false, "https", "https", "cert", }, { "HTTPS->HTTP", 443, "", 8005, "http", "cert", "", false, "https", "http", "cert", }, { "SSL->SSL", 443, "", 8006, "ssl", "cert", "", false, "ssl", "ssl", "cert", }, { "SSL->TCP", 443, "", 8007, "tcp", "cert", "", false, "ssl", "tcp", "cert", }, { "Port in whitelist", 1234, "", 8008, "tcp", "cert", "1234,5678", false, "ssl", "tcp", "cert", }, { "Port not in whitelist, passthrough", 443, "", 8009, "tcp", "cert", "1234,5678", false, "tcp", "tcp", "", }, { "Named port in whitelist", 1234, "bar", 8010, "tcp", "cert", "foo,bar", false, "ssl", "tcp", "cert", }, { "Named port not in whitelist, passthrough", 443, "", 8011, "tcp", "cert", "foo,bar", false, "tcp", "tcp", "", }, } for _, test := range tests { t.Logf("Running test case %s", test.name) annotations := make(map[string]string) if test.backendProtocolAnnotation != "" { annotations[ServiceAnnotationLoadBalancerBEProtocol] = test.backendProtocolAnnotation } if test.certAnnotation != "" { annotations[ServiceAnnotationLoadBalancerCertificate] = test.certAnnotation } ports := getPortSets(test.sslPortAnnotation) l, err := buildListener(api.ServicePort{ NodePort: int32(test.instancePort), Port: int32(test.lbPort), Name: test.portName, Protocol: api.Protocol("tcp"), }, annotations, ports) if test.expectError { if err == nil { t.Errorf("Should error for case %s", test.name) } } else { if err != nil { t.Errorf("Should succeed for case: %s, got %v", test.name, err) } else { var cert *string if test.certID != "" { cert = &test.certID } expected := &elb.Listener{ InstancePort: &test.instancePort, InstanceProtocol: &test.instanceProtocol, LoadBalancerPort: &test.lbPort, Protocol: &test.lbProtocol, SSLCertificateId: cert, } if !reflect.DeepEqual(l, expected) { t.Errorf("Incorrect listener (%v vs expected %v) for case: %s", l, expected, test.name) } } } } } func TestProxyProtocolEnabled(t *testing.T) { policies := sets.NewString(ProxyProtocolPolicyName, "FooBarFoo") fakeBackend := &elb.BackendServerDescription{ InstancePort: aws.Int64(80), PolicyNames: stringSetToPointers(policies), } result := proxyProtocolEnabled(fakeBackend) assert.True(t, result, "expected to find %s in %s", ProxyProtocolPolicyName, policies) policies = sets.NewString("FooBarFoo") fakeBackend = &elb.BackendServerDescription{ InstancePort: aws.Int64(80), PolicyNames: []*string{ aws.String("FooBarFoo"), }, } result = proxyProtocolEnabled(fakeBackend) assert.False(t, result, "did not expect to find %s in %s", ProxyProtocolPolicyName, policies) policies = sets.NewString() fakeBackend = &elb.BackendServerDescription{ InstancePort: aws.Int64(80), } result = proxyProtocolEnabled(fakeBackend) assert.False(t, result, "did not expect to find %s in %s", ProxyProtocolPolicyName, policies) }
pkg/cloudprovider/providers/aws/aws_test.go
0
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.0013710075290873647, 0.0001966757554328069, 0.00016224061255343258, 0.00017071056936401874, 0.00012434538803063333 ]
{ "id": 5, "code_window": [ "Running Kubernetes with Vagrant (and VirtualBox) is an easy way to run/test/develop on your local machine (Linux, Mac OS X).\n", "\n", "* TOC\n", "{:toc}\n", "\n", "### Prerequisites\n", "\n", "1. Install latest version >= 1.7.4 of [Vagrant](http://www.vagrantup.com/downloads.html)\n", "2. Install one of:\n", " 1. The latest version of [Virtual Box](https://www.virtualbox.org/wiki/Downloads)\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/devel/local-cluster/vagrant.md", "type": "replace", "edit_start_line_idx": 40 }
<!-- 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. Documentation for other releases can be found at [releases.k8s.io](http://releases.k8s.io). </strong> -- <!-- END STRIP_FOR_RELEASE --> <!-- END MUNGE: UNVERSIONED_WARNING --> --- assignees: - asridharan - brendandburns - fgrzadkowski --- **Stop. This guide has been superseded by [Minikube](https://github.com/kubernetes/minikube) which is the recommended method of running Kubernetes on your local machine.** The following instructions show you how to set up a simple, single node Kubernetes cluster using Docker. Here's a diagram of what the final result will look like: ![Kubernetes Single Node on Docker](../../getting-started-guides/k8s-singlenode-docker.png) * TOC {:toc} ## Prerequisites **Note: These steps have not been tested with the [Docker For Mac or Docker For Windows beta programs](https://blog.docker.com/2016/03/docker-for-mac-windows-beta/).** 1. You need to have Docker version >= "1.10" installed on the machine. 2. Enable mount propagation. Hyperkube is running in a container which has to mount volumes for other containers, for example in case of persistent storage. The required steps depend on the init system. In case of **systemd**, change MountFlags in the Docker unit file to shared. ```shell DOCKER_CONF=$(systemctl cat docker | head -1 | awk '{print $2}') sed -i.bak 's/^\(MountFlags=\).*/\1shared/' $DOCKER_CONF systemctl daemon-reload systemctl restart docker ``` **Otherwise**, manually set the mount point used by Hyperkube to be shared: ```shell mkdir -p /var/lib/kubelet mount --bind /var/lib/kubelet /var/lib/kubelet mount --make-shared /var/lib/kubelet ``` ### Run it 1. Decide which Kubernetes version to use. Set the `${K8S_VERSION}` variable to a version of Kubernetes >= "v1.2.0". If you'd like to use the current **stable** version of Kubernetes, run the following: ```sh export K8S_VERSION=$(curl -sS https://storage.googleapis.com/kubernetes-release/release/stable.txt) ``` and for the **latest** available version (including unstable releases): ```sh export K8S_VERSION=$(curl -sS https://storage.googleapis.com/kubernetes-release/release/latest.txt) ``` 2. Start Hyperkube ```shell export ARCH=amd64 docker run -d \ --volume=/sys:/sys:rw \ --volume=/var/lib/docker/:/var/lib/docker:rw \ --volume=/var/lib/kubelet/:/var/lib/kubelet:rw,shared \ --volume=/var/run:/var/run:rw \ --net=host \ --pid=host \ --privileged \ --name=kubelet \ gcr.io/google_containers/hyperkube-${ARCH}:${K8S_VERSION} \ /hyperkube kubelet \ --hostname-override=127.0.0.1 \ --api-servers=http://localhost:8080 \ --config=/etc/kubernetes/manifests \ --cluster-dns=10.0.0.10 \ --cluster-domain=cluster.local \ --allow-privileged --v=2 ``` > Note that `--cluster-dns` and `--cluster-domain` is used to deploy dns, feel free to discard them if dns is not needed. > If you would like to mount an external device as a volume, add `--volume=/dev:/dev` to the command above. It may however, cause some problems described in [#18230](https://github.com/kubernetes/kubernetes/issues/18230) > Architectures other than `amd64` are experimental and sometimes unstable, but feel free to try them out! Valid values: `arm`, `arm64` and `ppc64le`. ARM is available with Kubernetes version `v1.3.0-alpha.2` and higher. ARM 64-bit and PowerPC 64 little-endian are available with `v1.3.0-alpha.3` and higher. Track progress on multi-arch support [here](https://github.com/kubernetes/kubernetes/issues/17981) > If you are behind a proxy, you need to pass the proxy setup to curl in the containers to pull the certificates. Create a .curlrc under /root folder (because the containers are running as root) with the following line: ``` proxy = <your_proxy_server>:<port> ``` This actually runs the kubelet, which in turn runs a [pod](http://kubernetes.io/docs/user-guide/pods/) that contains the other master components. ** **SECURITY WARNING** ** services exposed via Kubernetes using Hyperkube are available on the host node's public network interface / IP address. Because of this, this guide is not suitable for any host node/server that is directly internet accessible. Refer to [#21735](https://github.com/kubernetes/kubernetes/issues/21735) for addtional info. ### Download `kubectl` At this point you should have a running Kubernetes cluster. You can test it out by downloading the kubectl binary for `${K8S_VERSION}` (in this example: `{{page.version}}.0`). Downloads: - `linux/amd64`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/linux/amd64/kubectl - `linux/386`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/linux/386/kubectl - `linux/arm`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/linux/arm/kubectl - `linux/arm64`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/linux/arm64/kubectl - `linux/ppc64le`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/linux/ppc64le/kubectl - `OS X/amd64`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/darwin/amd64/kubectl - `OS X/386`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/darwin/386/kubectl - `windows/amd64`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/windows/amd64/kubectl.exe - `windows/386`: http://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/windows/386/kubectl.exe The generic download path is: ``` http://storage.googleapis.com/kubernetes-release/release/${K8S_VERSION}/bin/${GOOS}/${GOARCH}/${K8S_BINARY} ``` An example install with `linux/amd64`: ``` curl -sSL "https://storage.googleapis.com/kubernetes-release/release/{{page.version}}.0/bin/linux/amd64/kubectl" > /usr/bin/kubectl chmod +x /usr/bin/kubectl ``` On OS X, to make the API server accessible locally, setup a ssh tunnel. ```shell docker-machine ssh `docker-machine active` -N -L 8080:localhost:8080 ``` Setting up a ssh tunnel is applicable to remote docker hosts as well. (Optional) Create kubernetes cluster configuration: ```shell kubectl config set-cluster test-doc --server=http://localhost:8080 kubectl config set-context test-doc --cluster=test-doc kubectl config use-context test-doc ``` ### Test it out List the nodes in your cluster by running: ```shell kubectl get nodes ``` This should print: ```shell NAME STATUS AGE 127.0.0.1 Ready 1h ``` ### Run an application ```shell kubectl run nginx --image=nginx --port=80 ``` Now run `docker ps` you should see nginx running. You may need to wait a few minutes for the image to get pulled. ### Expose it as a service ```shell kubectl expose deployment nginx --port=80 ``` Run the following command to obtain the cluster local IP of this service we just created: ```shell{% raw %} ip=$(kubectl get svc nginx --template={{.spec.clusterIP}}) echo $ip {% endraw %}``` Hit the webserver with this IP: ```shell{% raw %} curl $ip {% endraw %}``` On OS X, since docker is running inside a VM, run the following command instead: ```shell docker-machine ssh `docker-machine active` curl $ip ``` ### Turning down your cluster 1\. Delete the nginx service and deployment: If you plan on re-creating your nginx deployment and service you will need to clean it up. ```shell kubectl delete service,deployments nginx ``` 2\. Delete all the containers including the kubelet: ```shell docker rm -f kubelet docker rm -f `docker ps | grep k8s | awk '{print $1}'` ``` 3\. Cleanup the filesystem: On OS X, first ssh into the docker VM: ```shell docker-machine ssh `docker-machine active` ``` ```shell grep /var/lib/kubelet /proc/mounts | awk '{print $2}' | sudo xargs -n1 umount sudo rm -rf /var/lib/kubelet ``` ### Troubleshooting #### Node is in `NotReady` state If you see your node as `NotReady` it's possible that your OS does not have memcg enabled. 1. Your kernel should support memory accounting. Ensure that the following configs are turned on in your linux kernel: ```shell CONFIG_RESOURCE_COUNTERS=y CONFIG_MEMCG=y ``` 2. Enable the memory accounting in the kernel, at boot, as command line parameters as follows: ```shell GRUB_CMDLINE_LINUX="cgroup_enable=memory=1" ``` NOTE: The above is specifically for GRUB2. You can check the command line parameters passed to your kernel by looking at the output of /proc/cmdline: ```shell $ cat /proc/cmdline BOOT_IMAGE=/boot/vmlinuz-3.18.4-aufs root=/dev/sda5 ro cgroup_enable=memory=1 ``` ## Support Level IaaS Provider | Config. Mgmt | OS | Networking | Conforms | Support Level -------------------- | ------------ | ------ | ---------- | ---------| ---------------------------- Docker Single Node | custom | N/A | local | | Project ([@brendandburns](https://github.com/brendandburns)) ## Further reading Please see the [Kubernetes docs](http://kubernetes.io/docs) for more details on administering and using a Kubernetes cluster. <!-- BEGIN MUNGE: GENERATED_ANALYTICS --> [![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/devel/local-cluster/docker.md?pixel)]() <!-- END MUNGE: GENERATED_ANALYTICS -->
docs/devel/local-cluster/docker.md
1
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.0007505824905820191, 0.00025074920267798007, 0.00016447031521238387, 0.00019724745652638376, 0.00012910267105326056 ]
{ "id": 5, "code_window": [ "Running Kubernetes with Vagrant (and VirtualBox) is an easy way to run/test/develop on your local machine (Linux, Mac OS X).\n", "\n", "* TOC\n", "{:toc}\n", "\n", "### Prerequisites\n", "\n", "1. Install latest version >= 1.7.4 of [Vagrant](http://www.vagrantup.com/downloads.html)\n", "2. Install one of:\n", " 1. The latest version of [Virtual Box](https://www.virtualbox.org/wiki/Downloads)\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/devel/local-cluster/vagrant.md", "type": "replace", "edit_start_line_idx": 40 }
/* 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 thirdpartyresource import ( "fmt" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/rest" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/apis/extensions/validation" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/validation/field" ) // strategy implements behavior for ThirdPartyResource objects type strategy struct { runtime.ObjectTyper } // Strategy is the default logic that applies when creating and updating ThirdPartyResource // objects via the REST API. var Strategy = strategy{api.Scheme} var _ = rest.RESTCreateStrategy(Strategy) var _ = rest.RESTUpdateStrategy(Strategy) func (strategy) NamespaceScoped() bool { return false } func (strategy) GenerateName(base string) string { return "" } func (strategy) PrepareForCreate(obj runtime.Object) { } func (strategy) Validate(ctx api.Context, obj runtime.Object) field.ErrorList { return validation.ValidateThirdPartyResource(obj.(*extensions.ThirdPartyResource)) } // Canonicalize normalizes the object after validation. func (strategy) Canonicalize(obj runtime.Object) { } func (strategy) AllowCreateOnUpdate() bool { return false } func (strategy) PrepareForUpdate(obj, old runtime.Object) { } func (strategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) field.ErrorList { return validation.ValidateThirdPartyResourceUpdate(obj.(*extensions.ThirdPartyResource), old.(*extensions.ThirdPartyResource)) } func (strategy) AllowUnconditionalUpdate() bool { return true } // Matcher returns a generic matcher for a given label and field selector. func Matcher(label labels.Selector, field fields.Selector) generic.Matcher { return generic.MatcherFunc(func(obj runtime.Object) (bool, error) { sa, ok := obj.(*extensions.ThirdPartyResource) if !ok { return false, fmt.Errorf("not a ThirdPartyResource") } fields := SelectableFields(sa) return label.Matches(labels.Set(sa.Labels)) && field.Matches(fields), nil }) } // SelectableFields returns a label set that can be used for filter selection func SelectableFields(obj *extensions.ThirdPartyResource) labels.Set { return labels.Set{} }
pkg/registry/thirdpartyresource/strategy.go
0
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.00017421727534383535, 0.00016936002066358924, 0.00016643885464873165, 0.00016873802815098315, 0.000002342970219615381 ]
{ "id": 5, "code_window": [ "Running Kubernetes with Vagrant (and VirtualBox) is an easy way to run/test/develop on your local machine (Linux, Mac OS X).\n", "\n", "* TOC\n", "{:toc}\n", "\n", "### Prerequisites\n", "\n", "1. Install latest version >= 1.7.4 of [Vagrant](http://www.vagrantup.com/downloads.html)\n", "2. Install one of:\n", " 1. The latest version of [Virtual Box](https://www.virtualbox.org/wiki/Downloads)\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/devel/local-cluster/vagrant.md", "type": "replace", "edit_start_line_idx": 40 }
// Copyright 2013 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package googleapi import ( "encoding/json" "strconv" ) // Int64s is a slice of int64s that marshal as quoted strings in JSON. type Int64s []int64 func (q *Int64s) UnmarshalJSON(raw []byte) error { *q = (*q)[:0] var ss []string if err := json.Unmarshal(raw, &ss); err != nil { return err } for _, s := range ss { v, err := strconv.ParseInt(s, 10, 64) if err != nil { return err } *q = append(*q, int64(v)) } return nil } // Int32s is a slice of int32s that marshal as quoted strings in JSON. type Int32s []int32 func (q *Int32s) UnmarshalJSON(raw []byte) error { *q = (*q)[:0] var ss []string if err := json.Unmarshal(raw, &ss); err != nil { return err } for _, s := range ss { v, err := strconv.ParseInt(s, 10, 32) if err != nil { return err } *q = append(*q, int32(v)) } return nil } // Uint64s is a slice of uint64s that marshal as quoted strings in JSON. type Uint64s []uint64 func (q *Uint64s) UnmarshalJSON(raw []byte) error { *q = (*q)[:0] var ss []string if err := json.Unmarshal(raw, &ss); err != nil { return err } for _, s := range ss { v, err := strconv.ParseUint(s, 10, 64) if err != nil { return err } *q = append(*q, uint64(v)) } return nil } // Uint32s is a slice of uint32s that marshal as quoted strings in JSON. type Uint32s []uint32 func (q *Uint32s) UnmarshalJSON(raw []byte) error { *q = (*q)[:0] var ss []string if err := json.Unmarshal(raw, &ss); err != nil { return err } for _, s := range ss { v, err := strconv.ParseUint(s, 10, 32) if err != nil { return err } *q = append(*q, uint32(v)) } return nil } // Float64s is a slice of float64s that marshal as quoted strings in JSON. type Float64s []float64 func (q *Float64s) UnmarshalJSON(raw []byte) error { *q = (*q)[:0] var ss []string if err := json.Unmarshal(raw, &ss); err != nil { return err } for _, s := range ss { v, err := strconv.ParseFloat(s, 64) if err != nil { return err } *q = append(*q, float64(v)) } return nil } func quotedList(n int, fn func(dst []byte, i int) []byte) ([]byte, error) { dst := make([]byte, 0, 2+n*10) // somewhat arbitrary dst = append(dst, '[') for i := 0; i < n; i++ { if i > 0 { dst = append(dst, ',') } dst = append(dst, '"') dst = fn(dst, i) dst = append(dst, '"') } dst = append(dst, ']') return dst, nil } func (s Int64s) MarshalJSON() ([]byte, error) { return quotedList(len(s), func(dst []byte, i int) []byte { return strconv.AppendInt(dst, s[i], 10) }) } func (s Int32s) MarshalJSON() ([]byte, error) { return quotedList(len(s), func(dst []byte, i int) []byte { return strconv.AppendInt(dst, int64(s[i]), 10) }) } func (s Uint64s) MarshalJSON() ([]byte, error) { return quotedList(len(s), func(dst []byte, i int) []byte { return strconv.AppendUint(dst, s[i], 10) }) } func (s Uint32s) MarshalJSON() ([]byte, error) { return quotedList(len(s), func(dst []byte, i int) []byte { return strconv.AppendUint(dst, uint64(s[i]), 10) }) } func (s Float64s) MarshalJSON() ([]byte, error) { return quotedList(len(s), func(dst []byte, i int) []byte { return strconv.AppendFloat(dst, s[i], 'g', -1, 64) }) } /* * Helper routines for simplifying the creation of optional fields of basic type. */ // Bool is a helper routine that allocates a new bool value // to store v and returns a pointer to it. func Bool(v bool) *bool { return &v } // Int32 is a helper routine that allocates a new int32 value // to store v and returns a pointer to it. func Int32(v int32) *int32 { return &v } // Int64 is a helper routine that allocates a new int64 value // to store v and returns a pointer to it. func Int64(v int64) *int64 { return &v } // Float64 is a helper routine that allocates a new float64 value // to store v and returns a pointer to it. func Float64(v float64) *float64 { return &v } // Uint32 is a helper routine that allocates a new uint32 value // to store v and returns a pointer to it. func Uint32(v uint32) *uint32 { return &v } // Uint64 is a helper routine that allocates a new uint64 value // to store v and returns a pointer to it. func Uint64(v uint64) *uint64 { return &v } // String is a helper routine that allocates a new string value // to store v and returns a pointer to it. func String(v string) *string { return &v }
vendor/google.golang.org/api/googleapi/types.go
0
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.0007853429997339845, 0.00022233370691537857, 0.00016664943541400135, 0.00017235252016689628, 0.00013833734556101263 ]
{ "id": 5, "code_window": [ "Running Kubernetes with Vagrant (and VirtualBox) is an easy way to run/test/develop on your local machine (Linux, Mac OS X).\n", "\n", "* TOC\n", "{:toc}\n", "\n", "### Prerequisites\n", "\n", "1. Install latest version >= 1.7.4 of [Vagrant](http://www.vagrantup.com/downloads.html)\n", "2. Install one of:\n", " 1. The latest version of [Virtual Box](https://www.virtualbox.org/wiki/Downloads)\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "docs/devel/local-cluster/vagrant.md", "type": "replace", "edit_start_line_idx": 40 }
/* 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 kubelet import ( "testing" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/types" ) func TestReasonCache(t *testing.T) { // Create test sync result syncResult := kubecontainer.PodSyncResult{} results := []*kubecontainer.SyncResult{ // reason cache should be set for SyncResult with StartContainer action and error kubecontainer.NewSyncResult(kubecontainer.StartContainer, "container_1"), // reason cache should not be set for SyncResult with StartContainer action but without error kubecontainer.NewSyncResult(kubecontainer.StartContainer, "container_2"), // reason cache should not be set for SyncResult with other actions kubecontainer.NewSyncResult(kubecontainer.KillContainer, "container_3"), } results[0].Fail(kubecontainer.ErrRunContainer, "message_1") results[2].Fail(kubecontainer.ErrKillContainer, "message_3") syncResult.AddSyncResult(results...) uid := types.UID("pod_1") reasonCache := NewReasonCache() reasonCache.Update(uid, syncResult) assertReasonInfo(t, reasonCache, uid, results[0], true) assertReasonInfo(t, reasonCache, uid, results[1], false) assertReasonInfo(t, reasonCache, uid, results[2], false) reasonCache.Remove(uid, results[0].Target.(string)) assertReasonInfo(t, reasonCache, uid, results[0], false) } func assertReasonInfo(t *testing.T, cache *ReasonCache, uid types.UID, result *kubecontainer.SyncResult, found bool) { name := result.Target.(string) actualReason, actualMessage, ok := cache.Get(uid, name) if ok && !found { t.Fatalf("unexpected cache hit: %v, %q", actualReason, actualMessage) } if !ok && found { t.Fatalf("corresponding reason info not found") } if !found { return } reason := result.Error message := result.Message if actualReason != reason || actualMessage != message { t.Errorf("expected %v %q, got %v %q", reason, message, actualReason, actualMessage) } }
pkg/kubelet/reason_cache_test.go
0
https://github.com/kubernetes/kubernetes/commit/5546dfd3dcc02e14299b2a0d5977db3873e88c8e
[ 0.00019323601736687124, 0.00017374110757373273, 0.00016800864250399172, 0.0001709449861664325, 0.00000813187853054842 ]
{ "id": 0, "code_window": [ " \"//pkg/util/validation:go_default_library\",\n", " \"//pkg/util/validation/field:go_default_library\",\n", " \"//pkg/util/wait:go_default_library\",\n", " \"//pkg/version:go_default_library\",\n", " \"//pkg/volume:go_default_library\",\n", " \"//pkg/volume/util/types:go_default_library\",\n", " \"//pkg/volume/util/volumehelper:go_default_library\",\n", " \"//plugin/pkg/scheduler/algorithm/predicates:go_default_library\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " \"//pkg/volume/util:go_default_library\",\n" ], "file_path": "pkg/kubelet/BUILD", "type": "add", "edit_start_line_idx": 115 }
package(default_visibility = ["//visibility:public"]) licenses(["notice"]) load( "@io_bazel_rules_go//go:def.bzl", "go_library", "go_test", ) go_library( name = "go_default_library", srcs = [ "active_deadline.go", "disk_manager.go", "doc.go", "kubelet.go", "kubelet_cadvisor.go", "kubelet_getters.go", "kubelet_network.go", "kubelet_node_status.go", "kubelet_pods.go", "kubelet_resources.go", "kubelet_volumes.go", "networks.go", "oom_watcher.go", "pod_container_deletor.go", "pod_workers.go", "reason_cache.go", "runonce.go", "runtime.go", "util.go", "volume_host.go", ], tags = ["automanaged"], deps = [ "//cmd/kubelet/app/options:go_default_library", "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/v1:go_default_library", "//pkg/api/v1/pod:go_default_library", "//pkg/api/v1/validation:go_default_library", "//pkg/apis/componentconfig:go_default_library", "//pkg/apis/componentconfig/v1alpha1:go_default_library", "//pkg/apis/meta/v1:go_default_library", "//pkg/capabilities:go_default_library", "//pkg/client/cache:go_default_library", "//pkg/client/clientset_generated/clientset:go_default_library", "//pkg/client/record:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/conversion:go_default_library", "//pkg/fieldpath:go_default_library", "//pkg/fields:go_default_library", "//pkg/kubelet/api:go_default_library", "//pkg/kubelet/cadvisor:go_default_library", "//pkg/kubelet/cm:go_default_library", "//pkg/kubelet/config:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/kubelet/dockershim:go_default_library", "//pkg/kubelet/dockershim/remote:go_default_library", "//pkg/kubelet/dockertools:go_default_library", "//pkg/kubelet/envvars:go_default_library", "//pkg/kubelet/events:go_default_library", "//pkg/kubelet/eviction:go_default_library", "//pkg/kubelet/images:go_default_library", "//pkg/kubelet/kuberuntime:go_default_library", "//pkg/kubelet/lifecycle:go_default_library", "//pkg/kubelet/metrics:go_default_library", "//pkg/kubelet/network:go_default_library", "//pkg/kubelet/pleg:go_default_library", "//pkg/kubelet/pod:go_default_library", "//pkg/kubelet/prober:go_default_library", "//pkg/kubelet/prober/results:go_default_library", "//pkg/kubelet/remote:go_default_library", "//pkg/kubelet/rkt:go_default_library", "//pkg/kubelet/server:go_default_library", "//pkg/kubelet/server/remotecommand:go_default_library", "//pkg/kubelet/server/stats:go_default_library", "//pkg/kubelet/server/streaming:go_default_library", "//pkg/kubelet/status:go_default_library", "//pkg/kubelet/sysctl:go_default_library", "//pkg/kubelet/types:go_default_library", "//pkg/kubelet/util/format:go_default_library", "//pkg/kubelet/util/queue:go_default_library", "//pkg/kubelet/util/sliceutils:go_default_library", "//pkg/kubelet/volumemanager:go_default_library", "//pkg/labels:go_default_library", "//pkg/security/apparmor:go_default_library", "//pkg/securitycontext:go_default_library", "//pkg/types:go_default_library", "//pkg/util:go_default_library", "//pkg/util/bandwidth:go_default_library", "//pkg/util/clock:go_default_library", "//pkg/util/config:go_default_library", "//pkg/util/dbus:go_default_library", "//pkg/util/errors:go_default_library", "//pkg/util/exec:go_default_library", "//pkg/util/flowcontrol:go_default_library", "//pkg/util/integer:go_default_library", "//pkg/util/io:go_default_library", "//pkg/util/iptables:go_default_library", "//pkg/util/mount:go_default_library", "//pkg/util/net:go_default_library", "//pkg/util/node:go_default_library", "//pkg/util/oom:go_default_library", "//pkg/util/procfs:go_default_library", "//pkg/util/runtime:go_default_library", "//pkg/util/sets:go_default_library", "//pkg/util/term:go_default_library", "//pkg/util/validation:go_default_library", "//pkg/util/validation/field:go_default_library", "//pkg/util/wait:go_default_library", "//pkg/version:go_default_library", "//pkg/volume:go_default_library", "//pkg/volume/util/types:go_default_library", "//pkg/volume/util/volumehelper:go_default_library", "//plugin/pkg/scheduler/algorithm/predicates:go_default_library", "//third_party/forked/golang/expansion:go_default_library", "//vendor:github.com/golang/glog", "//vendor:github.com/golang/groupcache/lru", "//vendor:github.com/google/cadvisor/events", "//vendor:github.com/google/cadvisor/info/v1", "//vendor:github.com/google/cadvisor/info/v2", ], ) go_test( name = "go_default_test", srcs = [ "active_deadline_test.go", "disk_manager_test.go", "kubelet_cadvisor_test.go", "kubelet_getters_test.go", "kubelet_network_test.go", "kubelet_node_status_test.go", "kubelet_pods_test.go", "kubelet_resources_test.go", "kubelet_test.go", "kubelet_volumes_test.go", "oom_watcher_test.go", "pod_container_deletor_test.go", "pod_workers_test.go", "reason_cache_test.go", "runonce_test.go", ], library = "go_default_library", tags = ["automanaged"], deps = [ "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", "//pkg/apis/componentconfig:go_default_library", "//pkg/apis/meta/v1:go_default_library", "//pkg/capabilities:go_default_library", "//pkg/client/clientset_generated/clientset/fake:go_default_library", "//pkg/client/record:go_default_library", "//pkg/client/testing/core:go_default_library", "//pkg/kubelet/cadvisor/testing:go_default_library", "//pkg/kubelet/cm:go_default_library", "//pkg/kubelet/config:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/kubelet/container/testing:go_default_library", "//pkg/kubelet/eviction:go_default_library", "//pkg/kubelet/images:go_default_library", "//pkg/kubelet/lifecycle:go_default_library", "//pkg/kubelet/network:go_default_library", "//pkg/kubelet/network/testing:go_default_library", "//pkg/kubelet/pleg:go_default_library", "//pkg/kubelet/pod:go_default_library", "//pkg/kubelet/pod/testing:go_default_library", "//pkg/kubelet/prober/results:go_default_library", "//pkg/kubelet/prober/testing:go_default_library", "//pkg/kubelet/server/remotecommand:go_default_library", "//pkg/kubelet/server/stats:go_default_library", "//pkg/kubelet/status:go_default_library", "//pkg/kubelet/types:go_default_library", "//pkg/kubelet/util/queue:go_default_library", "//pkg/kubelet/util/sliceutils:go_default_library", "//pkg/kubelet/volumemanager:go_default_library", "//pkg/labels:go_default_library", "//pkg/runtime:go_default_library", "//pkg/types:go_default_library", "//pkg/util/bandwidth:go_default_library", "//pkg/util/clock:go_default_library", "//pkg/util/diff:go_default_library", "//pkg/util/flowcontrol:go_default_library", "//pkg/util/mount:go_default_library", "//pkg/util/rand:go_default_library", "//pkg/util/runtime:go_default_library", "//pkg/util/sets:go_default_library", "//pkg/util/strategicpatch:go_default_library", "//pkg/util/testing:go_default_library", "//pkg/util/uuid:go_default_library", "//pkg/util/wait:go_default_library", "//pkg/version:go_default_library", "//pkg/volume:go_default_library", "//pkg/volume/host_path:go_default_library", "//pkg/volume/testing:go_default_library", "//pkg/volume/util/volumehelper:go_default_library", "//vendor:github.com/google/cadvisor/info/v1", "//vendor:github.com/google/cadvisor/info/v2", "//vendor:github.com/stretchr/testify/assert", "//vendor:github.com/stretchr/testify/require", ], )
pkg/kubelet/BUILD
1
https://github.com/kubernetes/kubernetes/commit/3fbf68ef6847264f8dcf1934951ef1cd5548d2a8
[ 0.9484266638755798, 0.05367730185389519, 0.00016476855671498924, 0.007315534166991711, 0.20026971399784088 ]
{ "id": 0, "code_window": [ " \"//pkg/util/validation:go_default_library\",\n", " \"//pkg/util/validation/field:go_default_library\",\n", " \"//pkg/util/wait:go_default_library\",\n", " \"//pkg/version:go_default_library\",\n", " \"//pkg/volume:go_default_library\",\n", " \"//pkg/volume/util/types:go_default_library\",\n", " \"//pkg/volume/util/volumehelper:go_default_library\",\n", " \"//plugin/pkg/scheduler/algorithm/predicates:go_default_library\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " \"//pkg/volume/util:go_default_library\",\n" ], "file_path": "pkg/kubelet/BUILD", "type": "add", "edit_start_line_idx": 115 }
// +build !ignore_autogenerated /* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // This file was autogenerated by deepcopy-gen. Do not edit it manually! package v1beta1 import ( v1 "k8s.io/client-go/pkg/api/v1" meta_v1 "k8s.io/client-go/pkg/apis/meta/v1" conversion "k8s.io/client-go/pkg/conversion" runtime "k8s.io/client-go/pkg/runtime" intstr "k8s.io/client-go/pkg/util/intstr" reflect "reflect" ) func init() { SchemeBuilder.Register(RegisterDeepCopies) } // RegisterDeepCopies adds deep-copy functions to the given scheme. Public // to allow building arbitrary schemes. func RegisterDeepCopies(scheme *runtime.Scheme) error { return scheme.AddGeneratedDeepCopyFuncs( conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_APIVersion, InType: reflect.TypeOf(&APIVersion{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_CPUTargetUtilization, InType: reflect.TypeOf(&CPUTargetUtilization{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_CustomMetricCurrentStatus, InType: reflect.TypeOf(&CustomMetricCurrentStatus{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_CustomMetricCurrentStatusList, InType: reflect.TypeOf(&CustomMetricCurrentStatusList{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_CustomMetricTarget, InType: reflect.TypeOf(&CustomMetricTarget{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_CustomMetricTargetList, InType: reflect.TypeOf(&CustomMetricTargetList{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_DaemonSet, InType: reflect.TypeOf(&DaemonSet{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_DaemonSetList, InType: reflect.TypeOf(&DaemonSetList{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_DaemonSetSpec, InType: reflect.TypeOf(&DaemonSetSpec{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_DaemonSetStatus, InType: reflect.TypeOf(&DaemonSetStatus{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_Deployment, InType: reflect.TypeOf(&Deployment{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_DeploymentCondition, InType: reflect.TypeOf(&DeploymentCondition{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_DeploymentList, InType: reflect.TypeOf(&DeploymentList{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_DeploymentRollback, InType: reflect.TypeOf(&DeploymentRollback{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_DeploymentSpec, InType: reflect.TypeOf(&DeploymentSpec{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_DeploymentStatus, InType: reflect.TypeOf(&DeploymentStatus{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_DeploymentStrategy, InType: reflect.TypeOf(&DeploymentStrategy{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_FSGroupStrategyOptions, InType: reflect.TypeOf(&FSGroupStrategyOptions{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_HTTPIngressPath, InType: reflect.TypeOf(&HTTPIngressPath{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_HTTPIngressRuleValue, InType: reflect.TypeOf(&HTTPIngressRuleValue{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_HorizontalPodAutoscaler, InType: reflect.TypeOf(&HorizontalPodAutoscaler{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_HorizontalPodAutoscalerList, InType: reflect.TypeOf(&HorizontalPodAutoscalerList{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_HorizontalPodAutoscalerSpec, InType: reflect.TypeOf(&HorizontalPodAutoscalerSpec{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_HorizontalPodAutoscalerStatus, InType: reflect.TypeOf(&HorizontalPodAutoscalerStatus{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_HostPortRange, InType: reflect.TypeOf(&HostPortRange{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_IDRange, InType: reflect.TypeOf(&IDRange{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_Ingress, InType: reflect.TypeOf(&Ingress{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_IngressBackend, InType: reflect.TypeOf(&IngressBackend{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_IngressList, InType: reflect.TypeOf(&IngressList{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_IngressRule, InType: reflect.TypeOf(&IngressRule{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_IngressRuleValue, InType: reflect.TypeOf(&IngressRuleValue{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_IngressSpec, InType: reflect.TypeOf(&IngressSpec{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_IngressStatus, InType: reflect.TypeOf(&IngressStatus{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_IngressTLS, InType: reflect.TypeOf(&IngressTLS{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_NetworkPolicy, InType: reflect.TypeOf(&NetworkPolicy{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_NetworkPolicyIngressRule, InType: reflect.TypeOf(&NetworkPolicyIngressRule{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_NetworkPolicyList, InType: reflect.TypeOf(&NetworkPolicyList{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_NetworkPolicyPeer, InType: reflect.TypeOf(&NetworkPolicyPeer{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_NetworkPolicyPort, InType: reflect.TypeOf(&NetworkPolicyPort{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_NetworkPolicySpec, InType: reflect.TypeOf(&NetworkPolicySpec{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_PodSecurityPolicy, InType: reflect.TypeOf(&PodSecurityPolicy{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_PodSecurityPolicyList, InType: reflect.TypeOf(&PodSecurityPolicyList{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_PodSecurityPolicySpec, InType: reflect.TypeOf(&PodSecurityPolicySpec{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ReplicaSet, InType: reflect.TypeOf(&ReplicaSet{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ReplicaSetCondition, InType: reflect.TypeOf(&ReplicaSetCondition{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ReplicaSetList, InType: reflect.TypeOf(&ReplicaSetList{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ReplicaSetSpec, InType: reflect.TypeOf(&ReplicaSetSpec{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ReplicaSetStatus, InType: reflect.TypeOf(&ReplicaSetStatus{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ReplicationControllerDummy, InType: reflect.TypeOf(&ReplicationControllerDummy{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_RollbackConfig, InType: reflect.TypeOf(&RollbackConfig{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_RollingUpdateDeployment, InType: reflect.TypeOf(&RollingUpdateDeployment{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_RunAsUserStrategyOptions, InType: reflect.TypeOf(&RunAsUserStrategyOptions{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_SELinuxStrategyOptions, InType: reflect.TypeOf(&SELinuxStrategyOptions{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_Scale, InType: reflect.TypeOf(&Scale{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ScaleSpec, InType: reflect.TypeOf(&ScaleSpec{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ScaleStatus, InType: reflect.TypeOf(&ScaleStatus{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_SubresourceReference, InType: reflect.TypeOf(&SubresourceReference{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_SupplementalGroupsStrategyOptions, InType: reflect.TypeOf(&SupplementalGroupsStrategyOptions{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ThirdPartyResource, InType: reflect.TypeOf(&ThirdPartyResource{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ThirdPartyResourceData, InType: reflect.TypeOf(&ThirdPartyResourceData{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ThirdPartyResourceDataList, InType: reflect.TypeOf(&ThirdPartyResourceDataList{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ThirdPartyResourceList, InType: reflect.TypeOf(&ThirdPartyResourceList{})}, ) } func DeepCopy_v1beta1_APIVersion(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*APIVersion) out := out.(*APIVersion) out.Name = in.Name return nil } } func DeepCopy_v1beta1_CPUTargetUtilization(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*CPUTargetUtilization) out := out.(*CPUTargetUtilization) out.TargetPercentage = in.TargetPercentage return nil } } func DeepCopy_v1beta1_CustomMetricCurrentStatus(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*CustomMetricCurrentStatus) out := out.(*CustomMetricCurrentStatus) out.Name = in.Name out.CurrentValue = in.CurrentValue.DeepCopy() return nil } } func DeepCopy_v1beta1_CustomMetricCurrentStatusList(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*CustomMetricCurrentStatusList) out := out.(*CustomMetricCurrentStatusList) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]CustomMetricCurrentStatus, len(*in)) for i := range *in { if err := DeepCopy_v1beta1_CustomMetricCurrentStatus(&(*in)[i], &(*out)[i], c); err != nil { return err } } } else { out.Items = nil } return nil } } func DeepCopy_v1beta1_CustomMetricTarget(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*CustomMetricTarget) out := out.(*CustomMetricTarget) out.Name = in.Name out.TargetValue = in.TargetValue.DeepCopy() return nil } } func DeepCopy_v1beta1_CustomMetricTargetList(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*CustomMetricTargetList) out := out.(*CustomMetricTargetList) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]CustomMetricTarget, len(*in)) for i := range *in { if err := DeepCopy_v1beta1_CustomMetricTarget(&(*in)[i], &(*out)[i], c); err != nil { return err } } } else { out.Items = nil } return nil } } func DeepCopy_v1beta1_DaemonSet(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*DaemonSet) out := out.(*DaemonSet) out.TypeMeta = in.TypeMeta if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { return err } if err := DeepCopy_v1beta1_DaemonSetSpec(&in.Spec, &out.Spec, c); err != nil { return err } out.Status = in.Status return nil } } func DeepCopy_v1beta1_DaemonSetList(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*DaemonSetList) out := out.(*DaemonSetList) out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]DaemonSet, len(*in)) for i := range *in { if err := DeepCopy_v1beta1_DaemonSet(&(*in)[i], &(*out)[i], c); err != nil { return err } } } else { out.Items = nil } return nil } } func DeepCopy_v1beta1_DaemonSetSpec(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*DaemonSetSpec) out := out.(*DaemonSetSpec) if in.Selector != nil { in, out := &in.Selector, &out.Selector *out = new(meta_v1.LabelSelector) if err := meta_v1.DeepCopy_v1_LabelSelector(*in, *out, c); err != nil { return err } } else { out.Selector = nil } if err := v1.DeepCopy_v1_PodTemplateSpec(&in.Template, &out.Template, c); err != nil { return err } return nil } } func DeepCopy_v1beta1_DaemonSetStatus(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*DaemonSetStatus) out := out.(*DaemonSetStatus) out.CurrentNumberScheduled = in.CurrentNumberScheduled out.NumberMisscheduled = in.NumberMisscheduled out.DesiredNumberScheduled = in.DesiredNumberScheduled out.NumberReady = in.NumberReady return nil } } func DeepCopy_v1beta1_Deployment(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*Deployment) out := out.(*Deployment) out.TypeMeta = in.TypeMeta if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { return err } if err := DeepCopy_v1beta1_DeploymentSpec(&in.Spec, &out.Spec, c); err != nil { return err } if err := DeepCopy_v1beta1_DeploymentStatus(&in.Status, &out.Status, c); err != nil { return err } return nil } } func DeepCopy_v1beta1_DeploymentCondition(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*DeploymentCondition) out := out.(*DeploymentCondition) out.Type = in.Type out.Status = in.Status out.LastUpdateTime = in.LastUpdateTime.DeepCopy() out.LastTransitionTime = in.LastTransitionTime.DeepCopy() out.Reason = in.Reason out.Message = in.Message return nil } } func DeepCopy_v1beta1_DeploymentList(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*DeploymentList) out := out.(*DeploymentList) out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Deployment, len(*in)) for i := range *in { if err := DeepCopy_v1beta1_Deployment(&(*in)[i], &(*out)[i], c); err != nil { return err } } } else { out.Items = nil } return nil } } func DeepCopy_v1beta1_DeploymentRollback(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*DeploymentRollback) out := out.(*DeploymentRollback) out.TypeMeta = in.TypeMeta out.Name = in.Name if in.UpdatedAnnotations != nil { in, out := &in.UpdatedAnnotations, &out.UpdatedAnnotations *out = make(map[string]string) for key, val := range *in { (*out)[key] = val } } else { out.UpdatedAnnotations = nil } out.RollbackTo = in.RollbackTo return nil } } func DeepCopy_v1beta1_DeploymentSpec(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*DeploymentSpec) out := out.(*DeploymentSpec) if in.Replicas != nil { in, out := &in.Replicas, &out.Replicas *out = new(int32) **out = **in } else { out.Replicas = nil } if in.Selector != nil { in, out := &in.Selector, &out.Selector *out = new(meta_v1.LabelSelector) if err := meta_v1.DeepCopy_v1_LabelSelector(*in, *out, c); err != nil { return err } } else { out.Selector = nil } if err := v1.DeepCopy_v1_PodTemplateSpec(&in.Template, &out.Template, c); err != nil { return err } if err := DeepCopy_v1beta1_DeploymentStrategy(&in.Strategy, &out.Strategy, c); err != nil { return err } out.MinReadySeconds = in.MinReadySeconds if in.RevisionHistoryLimit != nil { in, out := &in.RevisionHistoryLimit, &out.RevisionHistoryLimit *out = new(int32) **out = **in } else { out.RevisionHistoryLimit = nil } out.Paused = in.Paused if in.RollbackTo != nil { in, out := &in.RollbackTo, &out.RollbackTo *out = new(RollbackConfig) **out = **in } else { out.RollbackTo = nil } if in.ProgressDeadlineSeconds != nil { in, out := &in.ProgressDeadlineSeconds, &out.ProgressDeadlineSeconds *out = new(int32) **out = **in } else { out.ProgressDeadlineSeconds = nil } return nil } } func DeepCopy_v1beta1_DeploymentStatus(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*DeploymentStatus) out := out.(*DeploymentStatus) out.ObservedGeneration = in.ObservedGeneration out.Replicas = in.Replicas out.UpdatedReplicas = in.UpdatedReplicas out.AvailableReplicas = in.AvailableReplicas out.UnavailableReplicas = in.UnavailableReplicas if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions *out = make([]DeploymentCondition, len(*in)) for i := range *in { if err := DeepCopy_v1beta1_DeploymentCondition(&(*in)[i], &(*out)[i], c); err != nil { return err } } } else { out.Conditions = nil } return nil } } func DeepCopy_v1beta1_DeploymentStrategy(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*DeploymentStrategy) out := out.(*DeploymentStrategy) out.Type = in.Type if in.RollingUpdate != nil { in, out := &in.RollingUpdate, &out.RollingUpdate *out = new(RollingUpdateDeployment) if err := DeepCopy_v1beta1_RollingUpdateDeployment(*in, *out, c); err != nil { return err } } else { out.RollingUpdate = nil } return nil } } func DeepCopy_v1beta1_FSGroupStrategyOptions(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*FSGroupStrategyOptions) out := out.(*FSGroupStrategyOptions) out.Rule = in.Rule if in.Ranges != nil { in, out := &in.Ranges, &out.Ranges *out = make([]IDRange, len(*in)) for i := range *in { (*out)[i] = (*in)[i] } } else { out.Ranges = nil } return nil } } func DeepCopy_v1beta1_HTTPIngressPath(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*HTTPIngressPath) out := out.(*HTTPIngressPath) out.Path = in.Path out.Backend = in.Backend return nil } } func DeepCopy_v1beta1_HTTPIngressRuleValue(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*HTTPIngressRuleValue) out := out.(*HTTPIngressRuleValue) if in.Paths != nil { in, out := &in.Paths, &out.Paths *out = make([]HTTPIngressPath, len(*in)) for i := range *in { (*out)[i] = (*in)[i] } } else { out.Paths = nil } return nil } } func DeepCopy_v1beta1_HorizontalPodAutoscaler(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*HorizontalPodAutoscaler) out := out.(*HorizontalPodAutoscaler) out.TypeMeta = in.TypeMeta if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { return err } if err := DeepCopy_v1beta1_HorizontalPodAutoscalerSpec(&in.Spec, &out.Spec, c); err != nil { return err } if err := DeepCopy_v1beta1_HorizontalPodAutoscalerStatus(&in.Status, &out.Status, c); err != nil { return err } return nil } } func DeepCopy_v1beta1_HorizontalPodAutoscalerList(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*HorizontalPodAutoscalerList) out := out.(*HorizontalPodAutoscalerList) out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]HorizontalPodAutoscaler, len(*in)) for i := range *in { if err := DeepCopy_v1beta1_HorizontalPodAutoscaler(&(*in)[i], &(*out)[i], c); err != nil { return err } } } else { out.Items = nil } return nil } } func DeepCopy_v1beta1_HorizontalPodAutoscalerSpec(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*HorizontalPodAutoscalerSpec) out := out.(*HorizontalPodAutoscalerSpec) out.ScaleRef = in.ScaleRef if in.MinReplicas != nil { in, out := &in.MinReplicas, &out.MinReplicas *out = new(int32) **out = **in } else { out.MinReplicas = nil } out.MaxReplicas = in.MaxReplicas if in.CPUUtilization != nil { in, out := &in.CPUUtilization, &out.CPUUtilization *out = new(CPUTargetUtilization) **out = **in } else { out.CPUUtilization = nil } return nil } } func DeepCopy_v1beta1_HorizontalPodAutoscalerStatus(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*HorizontalPodAutoscalerStatus) out := out.(*HorizontalPodAutoscalerStatus) if in.ObservedGeneration != nil { in, out := &in.ObservedGeneration, &out.ObservedGeneration *out = new(int64) **out = **in } else { out.ObservedGeneration = nil } if in.LastScaleTime != nil { in, out := &in.LastScaleTime, &out.LastScaleTime *out = new(meta_v1.Time) **out = (*in).DeepCopy() } else { out.LastScaleTime = nil } out.CurrentReplicas = in.CurrentReplicas out.DesiredReplicas = in.DesiredReplicas if in.CurrentCPUUtilizationPercentage != nil { in, out := &in.CurrentCPUUtilizationPercentage, &out.CurrentCPUUtilizationPercentage *out = new(int32) **out = **in } else { out.CurrentCPUUtilizationPercentage = nil } return nil } } func DeepCopy_v1beta1_HostPortRange(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*HostPortRange) out := out.(*HostPortRange) out.Min = in.Min out.Max = in.Max return nil } } func DeepCopy_v1beta1_IDRange(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*IDRange) out := out.(*IDRange) out.Min = in.Min out.Max = in.Max return nil } } func DeepCopy_v1beta1_Ingress(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*Ingress) out := out.(*Ingress) out.TypeMeta = in.TypeMeta if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { return err } if err := DeepCopy_v1beta1_IngressSpec(&in.Spec, &out.Spec, c); err != nil { return err } if err := DeepCopy_v1beta1_IngressStatus(&in.Status, &out.Status, c); err != nil { return err } return nil } } func DeepCopy_v1beta1_IngressBackend(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*IngressBackend) out := out.(*IngressBackend) out.ServiceName = in.ServiceName out.ServicePort = in.ServicePort return nil } } func DeepCopy_v1beta1_IngressList(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*IngressList) out := out.(*IngressList) out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Ingress, len(*in)) for i := range *in { if err := DeepCopy_v1beta1_Ingress(&(*in)[i], &(*out)[i], c); err != nil { return err } } } else { out.Items = nil } return nil } } func DeepCopy_v1beta1_IngressRule(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*IngressRule) out := out.(*IngressRule) out.Host = in.Host if err := DeepCopy_v1beta1_IngressRuleValue(&in.IngressRuleValue, &out.IngressRuleValue, c); err != nil { return err } return nil } } func DeepCopy_v1beta1_IngressRuleValue(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*IngressRuleValue) out := out.(*IngressRuleValue) if in.HTTP != nil { in, out := &in.HTTP, &out.HTTP *out = new(HTTPIngressRuleValue) if err := DeepCopy_v1beta1_HTTPIngressRuleValue(*in, *out, c); err != nil { return err } } else { out.HTTP = nil } return nil } } func DeepCopy_v1beta1_IngressSpec(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*IngressSpec) out := out.(*IngressSpec) if in.Backend != nil { in, out := &in.Backend, &out.Backend *out = new(IngressBackend) **out = **in } else { out.Backend = nil } if in.TLS != nil { in, out := &in.TLS, &out.TLS *out = make([]IngressTLS, len(*in)) for i := range *in { if err := DeepCopy_v1beta1_IngressTLS(&(*in)[i], &(*out)[i], c); err != nil { return err } } } else { out.TLS = nil } if in.Rules != nil { in, out := &in.Rules, &out.Rules *out = make([]IngressRule, len(*in)) for i := range *in { if err := DeepCopy_v1beta1_IngressRule(&(*in)[i], &(*out)[i], c); err != nil { return err } } } else { out.Rules = nil } return nil } } func DeepCopy_v1beta1_IngressStatus(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*IngressStatus) out := out.(*IngressStatus) if err := v1.DeepCopy_v1_LoadBalancerStatus(&in.LoadBalancer, &out.LoadBalancer, c); err != nil { return err } return nil } } func DeepCopy_v1beta1_IngressTLS(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*IngressTLS) out := out.(*IngressTLS) if in.Hosts != nil { in, out := &in.Hosts, &out.Hosts *out = make([]string, len(*in)) copy(*out, *in) } else { out.Hosts = nil } out.SecretName = in.SecretName return nil } } func DeepCopy_v1beta1_NetworkPolicy(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*NetworkPolicy) out := out.(*NetworkPolicy) out.TypeMeta = in.TypeMeta if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { return err } if err := DeepCopy_v1beta1_NetworkPolicySpec(&in.Spec, &out.Spec, c); err != nil { return err } return nil } } func DeepCopy_v1beta1_NetworkPolicyIngressRule(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*NetworkPolicyIngressRule) out := out.(*NetworkPolicyIngressRule) if in.Ports != nil { in, out := &in.Ports, &out.Ports *out = make([]NetworkPolicyPort, len(*in)) for i := range *in { if err := DeepCopy_v1beta1_NetworkPolicyPort(&(*in)[i], &(*out)[i], c); err != nil { return err } } } else { out.Ports = nil } if in.From != nil { in, out := &in.From, &out.From *out = make([]NetworkPolicyPeer, len(*in)) for i := range *in { if err := DeepCopy_v1beta1_NetworkPolicyPeer(&(*in)[i], &(*out)[i], c); err != nil { return err } } } else { out.From = nil } return nil } } func DeepCopy_v1beta1_NetworkPolicyList(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*NetworkPolicyList) out := out.(*NetworkPolicyList) out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]NetworkPolicy, len(*in)) for i := range *in { if err := DeepCopy_v1beta1_NetworkPolicy(&(*in)[i], &(*out)[i], c); err != nil { return err } } } else { out.Items = nil } return nil } } func DeepCopy_v1beta1_NetworkPolicyPeer(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*NetworkPolicyPeer) out := out.(*NetworkPolicyPeer) if in.PodSelector != nil { in, out := &in.PodSelector, &out.PodSelector *out = new(meta_v1.LabelSelector) if err := meta_v1.DeepCopy_v1_LabelSelector(*in, *out, c); err != nil { return err } } else { out.PodSelector = nil } if in.NamespaceSelector != nil { in, out := &in.NamespaceSelector, &out.NamespaceSelector *out = new(meta_v1.LabelSelector) if err := meta_v1.DeepCopy_v1_LabelSelector(*in, *out, c); err != nil { return err } } else { out.NamespaceSelector = nil } return nil } } func DeepCopy_v1beta1_NetworkPolicyPort(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*NetworkPolicyPort) out := out.(*NetworkPolicyPort) if in.Protocol != nil { in, out := &in.Protocol, &out.Protocol *out = new(v1.Protocol) **out = **in } else { out.Protocol = nil } if in.Port != nil { in, out := &in.Port, &out.Port *out = new(intstr.IntOrString) **out = **in } else { out.Port = nil } return nil } } func DeepCopy_v1beta1_NetworkPolicySpec(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*NetworkPolicySpec) out := out.(*NetworkPolicySpec) if err := meta_v1.DeepCopy_v1_LabelSelector(&in.PodSelector, &out.PodSelector, c); err != nil { return err } if in.Ingress != nil { in, out := &in.Ingress, &out.Ingress *out = make([]NetworkPolicyIngressRule, len(*in)) for i := range *in { if err := DeepCopy_v1beta1_NetworkPolicyIngressRule(&(*in)[i], &(*out)[i], c); err != nil { return err } } } else { out.Ingress = nil } return nil } } func DeepCopy_v1beta1_PodSecurityPolicy(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*PodSecurityPolicy) out := out.(*PodSecurityPolicy) out.TypeMeta = in.TypeMeta if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { return err } if err := DeepCopy_v1beta1_PodSecurityPolicySpec(&in.Spec, &out.Spec, c); err != nil { return err } return nil } } func DeepCopy_v1beta1_PodSecurityPolicyList(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*PodSecurityPolicyList) out := out.(*PodSecurityPolicyList) out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]PodSecurityPolicy, len(*in)) for i := range *in { if err := DeepCopy_v1beta1_PodSecurityPolicy(&(*in)[i], &(*out)[i], c); err != nil { return err } } } else { out.Items = nil } return nil } } func DeepCopy_v1beta1_PodSecurityPolicySpec(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*PodSecurityPolicySpec) out := out.(*PodSecurityPolicySpec) out.Privileged = in.Privileged if in.DefaultAddCapabilities != nil { in, out := &in.DefaultAddCapabilities, &out.DefaultAddCapabilities *out = make([]v1.Capability, len(*in)) for i := range *in { (*out)[i] = (*in)[i] } } else { out.DefaultAddCapabilities = nil } if in.RequiredDropCapabilities != nil { in, out := &in.RequiredDropCapabilities, &out.RequiredDropCapabilities *out = make([]v1.Capability, len(*in)) for i := range *in { (*out)[i] = (*in)[i] } } else { out.RequiredDropCapabilities = nil } if in.AllowedCapabilities != nil { in, out := &in.AllowedCapabilities, &out.AllowedCapabilities *out = make([]v1.Capability, len(*in)) for i := range *in { (*out)[i] = (*in)[i] } } else { out.AllowedCapabilities = nil } if in.Volumes != nil { in, out := &in.Volumes, &out.Volumes *out = make([]FSType, len(*in)) for i := range *in { (*out)[i] = (*in)[i] } } else { out.Volumes = nil } out.HostNetwork = in.HostNetwork if in.HostPorts != nil { in, out := &in.HostPorts, &out.HostPorts *out = make([]HostPortRange, len(*in)) for i := range *in { (*out)[i] = (*in)[i] } } else { out.HostPorts = nil } out.HostPID = in.HostPID out.HostIPC = in.HostIPC if err := DeepCopy_v1beta1_SELinuxStrategyOptions(&in.SELinux, &out.SELinux, c); err != nil { return err } if err := DeepCopy_v1beta1_RunAsUserStrategyOptions(&in.RunAsUser, &out.RunAsUser, c); err != nil { return err } if err := DeepCopy_v1beta1_SupplementalGroupsStrategyOptions(&in.SupplementalGroups, &out.SupplementalGroups, c); err != nil { return err } if err := DeepCopy_v1beta1_FSGroupStrategyOptions(&in.FSGroup, &out.FSGroup, c); err != nil { return err } out.ReadOnlyRootFilesystem = in.ReadOnlyRootFilesystem return nil } } func DeepCopy_v1beta1_ReplicaSet(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*ReplicaSet) out := out.(*ReplicaSet) out.TypeMeta = in.TypeMeta if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { return err } if err := DeepCopy_v1beta1_ReplicaSetSpec(&in.Spec, &out.Spec, c); err != nil { return err } if err := DeepCopy_v1beta1_ReplicaSetStatus(&in.Status, &out.Status, c); err != nil { return err } return nil } } func DeepCopy_v1beta1_ReplicaSetCondition(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*ReplicaSetCondition) out := out.(*ReplicaSetCondition) out.Type = in.Type out.Status = in.Status out.LastTransitionTime = in.LastTransitionTime.DeepCopy() out.Reason = in.Reason out.Message = in.Message return nil } } func DeepCopy_v1beta1_ReplicaSetList(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*ReplicaSetList) out := out.(*ReplicaSetList) out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]ReplicaSet, len(*in)) for i := range *in { if err := DeepCopy_v1beta1_ReplicaSet(&(*in)[i], &(*out)[i], c); err != nil { return err } } } else { out.Items = nil } return nil } } func DeepCopy_v1beta1_ReplicaSetSpec(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*ReplicaSetSpec) out := out.(*ReplicaSetSpec) if in.Replicas != nil { in, out := &in.Replicas, &out.Replicas *out = new(int32) **out = **in } else { out.Replicas = nil } out.MinReadySeconds = in.MinReadySeconds if in.Selector != nil { in, out := &in.Selector, &out.Selector *out = new(meta_v1.LabelSelector) if err := meta_v1.DeepCopy_v1_LabelSelector(*in, *out, c); err != nil { return err } } else { out.Selector = nil } if err := v1.DeepCopy_v1_PodTemplateSpec(&in.Template, &out.Template, c); err != nil { return err } return nil } } func DeepCopy_v1beta1_ReplicaSetStatus(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*ReplicaSetStatus) out := out.(*ReplicaSetStatus) out.Replicas = in.Replicas out.FullyLabeledReplicas = in.FullyLabeledReplicas out.ReadyReplicas = in.ReadyReplicas out.AvailableReplicas = in.AvailableReplicas out.ObservedGeneration = in.ObservedGeneration if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions *out = make([]ReplicaSetCondition, len(*in)) for i := range *in { if err := DeepCopy_v1beta1_ReplicaSetCondition(&(*in)[i], &(*out)[i], c); err != nil { return err } } } else { out.Conditions = nil } return nil } } func DeepCopy_v1beta1_ReplicationControllerDummy(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*ReplicationControllerDummy) out := out.(*ReplicationControllerDummy) out.TypeMeta = in.TypeMeta return nil } } func DeepCopy_v1beta1_RollbackConfig(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*RollbackConfig) out := out.(*RollbackConfig) out.Revision = in.Revision return nil } } func DeepCopy_v1beta1_RollingUpdateDeployment(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*RollingUpdateDeployment) out := out.(*RollingUpdateDeployment) if in.MaxUnavailable != nil { in, out := &in.MaxUnavailable, &out.MaxUnavailable *out = new(intstr.IntOrString) **out = **in } else { out.MaxUnavailable = nil } if in.MaxSurge != nil { in, out := &in.MaxSurge, &out.MaxSurge *out = new(intstr.IntOrString) **out = **in } else { out.MaxSurge = nil } return nil } } func DeepCopy_v1beta1_RunAsUserStrategyOptions(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*RunAsUserStrategyOptions) out := out.(*RunAsUserStrategyOptions) out.Rule = in.Rule if in.Ranges != nil { in, out := &in.Ranges, &out.Ranges *out = make([]IDRange, len(*in)) for i := range *in { (*out)[i] = (*in)[i] } } else { out.Ranges = nil } return nil } } func DeepCopy_v1beta1_SELinuxStrategyOptions(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*SELinuxStrategyOptions) out := out.(*SELinuxStrategyOptions) out.Rule = in.Rule if in.SELinuxOptions != nil { in, out := &in.SELinuxOptions, &out.SELinuxOptions *out = new(v1.SELinuxOptions) **out = **in } else { out.SELinuxOptions = nil } return nil } } func DeepCopy_v1beta1_Scale(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*Scale) out := out.(*Scale) out.TypeMeta = in.TypeMeta if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { return err } out.Spec = in.Spec if err := DeepCopy_v1beta1_ScaleStatus(&in.Status, &out.Status, c); err != nil { return err } return nil } } func DeepCopy_v1beta1_ScaleSpec(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*ScaleSpec) out := out.(*ScaleSpec) out.Replicas = in.Replicas return nil } } func DeepCopy_v1beta1_ScaleStatus(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*ScaleStatus) out := out.(*ScaleStatus) out.Replicas = in.Replicas if in.Selector != nil { in, out := &in.Selector, &out.Selector *out = make(map[string]string) for key, val := range *in { (*out)[key] = val } } else { out.Selector = nil } out.TargetSelector = in.TargetSelector return nil } } func DeepCopy_v1beta1_SubresourceReference(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*SubresourceReference) out := out.(*SubresourceReference) out.Kind = in.Kind out.Name = in.Name out.APIVersion = in.APIVersion out.Subresource = in.Subresource return nil } } func DeepCopy_v1beta1_SupplementalGroupsStrategyOptions(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*SupplementalGroupsStrategyOptions) out := out.(*SupplementalGroupsStrategyOptions) out.Rule = in.Rule if in.Ranges != nil { in, out := &in.Ranges, &out.Ranges *out = make([]IDRange, len(*in)) for i := range *in { (*out)[i] = (*in)[i] } } else { out.Ranges = nil } return nil } } func DeepCopy_v1beta1_ThirdPartyResource(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*ThirdPartyResource) out := out.(*ThirdPartyResource) out.TypeMeta = in.TypeMeta if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { return err } out.Description = in.Description if in.Versions != nil { in, out := &in.Versions, &out.Versions *out = make([]APIVersion, len(*in)) for i := range *in { (*out)[i] = (*in)[i] } } else { out.Versions = nil } return nil } } func DeepCopy_v1beta1_ThirdPartyResourceData(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*ThirdPartyResourceData) out := out.(*ThirdPartyResourceData) out.TypeMeta = in.TypeMeta if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { return err } if in.Data != nil { in, out := &in.Data, &out.Data *out = make([]byte, len(*in)) copy(*out, *in) } else { out.Data = nil } return nil } } func DeepCopy_v1beta1_ThirdPartyResourceDataList(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*ThirdPartyResourceDataList) out := out.(*ThirdPartyResourceDataList) out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]ThirdPartyResourceData, len(*in)) for i := range *in { if err := DeepCopy_v1beta1_ThirdPartyResourceData(&(*in)[i], &(*out)[i], c); err != nil { return err } } } else { out.Items = nil } return nil } } func DeepCopy_v1beta1_ThirdPartyResourceList(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*ThirdPartyResourceList) out := out.(*ThirdPartyResourceList) out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]ThirdPartyResource, len(*in)) for i := range *in { if err := DeepCopy_v1beta1_ThirdPartyResource(&(*in)[i], &(*out)[i], c); err != nil { return err } } } else { out.Items = nil } return nil } }
staging/src/k8s.io/client-go/pkg/apis/extensions/v1beta1/zz_generated.deepcopy.go
0
https://github.com/kubernetes/kubernetes/commit/3fbf68ef6847264f8dcf1934951ef1cd5548d2a8
[ 0.0012804912403225899, 0.00019340899598319083, 0.0001629421312827617, 0.0001714327954687178, 0.00010855672735488042 ]
{ "id": 0, "code_window": [ " \"//pkg/util/validation:go_default_library\",\n", " \"//pkg/util/validation/field:go_default_library\",\n", " \"//pkg/util/wait:go_default_library\",\n", " \"//pkg/version:go_default_library\",\n", " \"//pkg/volume:go_default_library\",\n", " \"//pkg/volume/util/types:go_default_library\",\n", " \"//pkg/volume/util/volumehelper:go_default_library\",\n", " \"//plugin/pkg/scheduler/algorithm/predicates:go_default_library\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " \"//pkg/volume/util:go_default_library\",\n" ], "file_path": "pkg/kubelet/BUILD", "type": "add", "edit_start_line_idx": 115 }
package(default_visibility = ["//visibility:public"]) licenses(["notice"]) load( "@io_bazel_rules_go//go:def.bzl", "go_library", "go_test", ) go_library( name = "go_default_library", srcs = [ "error.go", "metadata.go", "predicates.go", "utils.go", ], tags = ["automanaged"], deps = [ "//pkg/api/v1:go_default_library", "//pkg/apis/meta/v1:go_default_library", "//pkg/client/cache:go_default_library", "//pkg/kubelet/qos:go_default_library", "//pkg/labels:go_default_library", "//pkg/util/runtime:go_default_library", "//pkg/util/workqueue:go_default_library", "//plugin/pkg/scheduler/algorithm:go_default_library", "//plugin/pkg/scheduler/algorithm/priorities/util:go_default_library", "//plugin/pkg/scheduler/schedulercache:go_default_library", "//vendor:github.com/golang/glog", ], ) go_test( name = "go_default_test", srcs = [ "predicates_test.go", "utils_test.go", ], library = "go_default_library", tags = ["automanaged"], deps = [ "//pkg/api/resource:go_default_library", "//pkg/api/v1:go_default_library", "//pkg/labels:go_default_library", "//plugin/pkg/scheduler/algorithm:go_default_library", "//plugin/pkg/scheduler/algorithm/priorities/util:go_default_library", "//plugin/pkg/scheduler/schedulercache:go_default_library", ], )
plugin/pkg/scheduler/algorithm/predicates/BUILD
0
https://github.com/kubernetes/kubernetes/commit/3fbf68ef6847264f8dcf1934951ef1cd5548d2a8
[ 0.041504617780447006, 0.01253864448517561, 0.00016705879534129053, 0.0036522820591926575, 0.01586737111210823 ]
{ "id": 0, "code_window": [ " \"//pkg/util/validation:go_default_library\",\n", " \"//pkg/util/validation/field:go_default_library\",\n", " \"//pkg/util/wait:go_default_library\",\n", " \"//pkg/version:go_default_library\",\n", " \"//pkg/volume:go_default_library\",\n", " \"//pkg/volume/util/types:go_default_library\",\n", " \"//pkg/volume/util/volumehelper:go_default_library\",\n", " \"//plugin/pkg/scheduler/algorithm/predicates:go_default_library\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " \"//pkg/volume/util:go_default_library\",\n" ], "file_path": "pkg/kubelet/BUILD", "type": "add", "edit_start_line_idx": 115 }
apiVersion: extensions/v1beta1 kind: DaemonSet metadata: name: kube-registry-proxy namespace: kube-system labels: k8s-app: kube-registry kubernetes.io/cluster-service: "true" version: v0.4 spec: template: metadata: labels: k8s-app: kube-registry kubernetes.io/name: "kube-registry-proxy" kubernetes.io/cluster-service: "true" version: v0.4 spec: containers: - name: kube-registry-proxy image: gcr.io/google_containers/kube-registry-proxy:0.4 resources: limits: cpu: 100m memory: 50Mi env: - name: REGISTRY_HOST value: kube-registry.kube-system.svc.cluster.local - name: REGISTRY_PORT value: "5000" ports: - name: registry containerPort: 80 hostPort: 5000
cluster/saltbase/salt/kube-registry-proxy/kube-registry-proxy.yaml
0
https://github.com/kubernetes/kubernetes/commit/3fbf68ef6847264f8dcf1934951ef1cd5548d2a8
[ 0.00017691086395643651, 0.0001738076825859025, 0.00017126572492998093, 0.00017352704890072346, 0.000002511512093406054 ]