本文整理汇总了Golang中github.com/hashicorp/errwrap.ContainsType函数的典型用法代码示例。如果您正苦于以下问题:Golang ContainsType函数的具体用法?Golang ContainsType怎么用?Golang ContainsType使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ContainsType函数的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: handleSysUnseal
func handleSysUnseal(core *vault.Core) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "PUT":
case "POST":
default:
respondError(w, http.StatusMethodNotAllowed, nil)
return
}
// Parse the request
var req UnsealRequest
if err := parseRequest(r, &req); err != nil {
respondError(w, http.StatusBadRequest, err)
return
}
if !req.Reset && req.Key == "" {
respondError(
w, http.StatusBadRequest,
errors.New("'key' must specified in request body as JSON, or 'reset' set to true"))
return
}
if req.Reset {
sealed, err := core.Sealed()
if err != nil {
respondError(w, http.StatusInternalServerError, err)
return
}
if !sealed {
respondError(w, http.StatusBadRequest, errors.New("vault is unsealed"))
return
}
core.ResetUnsealProcess()
} else {
// Decode the key, which is hex encoded
key, err := hex.DecodeString(req.Key)
if err != nil {
respondError(
w, http.StatusBadRequest,
errors.New("'key' must be a valid hex-string"))
return
}
// Attempt the unseal
if _, err := core.Unseal(key); err != nil {
// Ignore ErrInvalidKey because its a user error that we
// mask away. We just show them the seal status.
if !errwrap.ContainsType(err, new(vault.ErrInvalidKey)) {
respondError(w, http.StatusInternalServerError, err)
return
}
}
}
// Return the seal status
handleSysSealStatusRaw(core, w, r)
})
}
示例2: respondErrorStatus
// Determines the type of the error being returned and sets the HTTP
// status code appropriately
func respondErrorStatus(w http.ResponseWriter, err error) {
status := http.StatusInternalServerError
switch {
// Keep adding more error types here to appropriate the status codes
case err != nil && errwrap.ContainsType(err, new(vault.StatusBadRequest)):
status = http.StatusBadRequest
}
respondError(w, status, err)
}
示例3: handleSysInitPut
func handleSysInitPut(core *vault.Core, w http.ResponseWriter, r *http.Request) {
// Parse the request
var req InitRequest
if err := parseRequest(r, &req); err != nil {
respondError(w, http.StatusBadRequest, err)
return
}
// Initialize
barrierConfig := &vault.SealConfig{
SecretShares: req.SecretShares,
SecretThreshold: req.SecretThreshold,
StoredShares: req.StoredShares,
PGPKeys: req.PGPKeys,
}
recoveryConfig := &vault.SealConfig{
SecretShares: req.RecoveryShares,
SecretThreshold: req.RecoveryThreshold,
PGPKeys: req.RecoveryPGPKeys,
}
result, initErr := core.Initialize(barrierConfig, recoveryConfig)
if initErr != nil {
if !errwrap.ContainsType(initErr, new(vault.NonFatalError)) {
respondError(w, http.StatusBadRequest, initErr)
return
} else {
// Add a warnings field? The error will be logged in the vault log
// already.
}
}
// Encode the keys
keys := make([]string, 0, len(result.SecretShares))
for _, k := range result.SecretShares {
keys = append(keys, hex.EncodeToString(k))
}
resp := &InitResponse{
Keys: keys,
RootToken: result.RootToken,
}
if len(result.RecoveryShares) > 0 {
resp.RecoveryKeys = make([]string, 0, len(result.RecoveryShares))
for _, k := range result.RecoveryShares {
resp.RecoveryKeys = append(resp.RecoveryKeys, hex.EncodeToString(k))
}
}
core.UnsealWithStoredKeys()
respondOk(w, resp)
}
示例4: respondErrorCommon
func respondErrorCommon(w http.ResponseWriter, resp *logical.Response, err error) bool {
// If there are no errors return
if err == nil && (resp == nil || !resp.IsError()) {
return false
}
// Start out with internal server error since in most of these cases there
// won't be a response so this won't be overridden
statusCode := http.StatusInternalServerError
// If we actually have a response, start out with bad request
if resp != nil {
statusCode = http.StatusBadRequest
}
// Now, check the error itself; if it has a specific logical error, set the
// appropriate code
if err != nil {
switch {
case errwrap.ContainsType(err, new(vault.StatusBadRequest)):
statusCode = http.StatusBadRequest
case errwrap.Contains(err, logical.ErrPermissionDenied.Error()):
statusCode = http.StatusForbidden
case errwrap.Contains(err, logical.ErrUnsupportedOperation.Error()):
statusCode = http.StatusMethodNotAllowed
case errwrap.Contains(err, logical.ErrUnsupportedPath.Error()):
statusCode = http.StatusNotFound
case errwrap.Contains(err, logical.ErrInvalidRequest.Error()):
statusCode = http.StatusBadRequest
}
}
if resp != nil && resp.IsError() {
err = fmt.Errorf("%s", resp.Data["error"].(string))
}
respondError(w, statusCode, err)
return true
}
示例5: handleSysInitPut
func handleSysInitPut(core *vault.Core, w http.ResponseWriter, r *http.Request) {
// Parse the request
var req InitRequest
if err := parseRequest(r, &req); err != nil {
respondError(w, http.StatusBadRequest, err)
return
}
// Initialize
barrierConfig := &vault.SealConfig{
SecretShares: req.SecretShares,
SecretThreshold: req.SecretThreshold,
StoredShares: req.StoredShares,
PGPKeys: req.PGPKeys,
}
recoveryConfig := &vault.SealConfig{
SecretShares: req.RecoveryShares,
SecretThreshold: req.RecoveryThreshold,
PGPKeys: req.RecoveryPGPKeys,
}
if core.SealAccess().StoredKeysSupported() {
if barrierConfig.SecretShares != 1 {
respondError(w, http.StatusBadRequest, fmt.Errorf("secret shares must be 1"))
return
}
if barrierConfig.SecretThreshold != barrierConfig.SecretShares {
respondError(w, http.StatusBadRequest, fmt.Errorf("secret threshold must be same as secret shares"))
return
}
if barrierConfig.StoredShares != barrierConfig.SecretShares {
respondError(w, http.StatusBadRequest, fmt.Errorf("stored shares must be same as secret shares"))
return
}
if barrierConfig.PGPKeys != nil && len(barrierConfig.PGPKeys) > 0 {
respondError(w, http.StatusBadRequest, fmt.Errorf("PGP keys not supported when storing shares"))
return
}
} else {
if barrierConfig.StoredShares > 0 {
respondError(w, http.StatusBadRequest, fmt.Errorf("stored keys are not supported"))
return
}
}
initParams := &vault.InitParams{
BarrierConfig: barrierConfig,
RecoveryConfig: recoveryConfig,
RootTokenPGPKey: req.RootTokenPGPKey,
}
result, initErr := core.Initialize(initParams)
if initErr != nil {
if !errwrap.ContainsType(initErr, new(vault.NonFatalError)) {
respondError(w, http.StatusBadRequest, initErr)
return
} else {
// Add a warnings field? The error will be logged in the vault log
// already.
}
}
// Encode the keys
keys := make([]string, 0, len(result.SecretShares))
keysB64 := make([]string, 0, len(result.SecretShares))
for _, k := range result.SecretShares {
keys = append(keys, hex.EncodeToString(k))
keysB64 = append(keysB64, base64.StdEncoding.EncodeToString(k))
}
resp := &InitResponse{
Keys: keys,
KeysB64: keysB64,
RootToken: result.RootToken,
}
if len(result.RecoveryShares) > 0 {
resp.RecoveryKeys = make([]string, 0, len(result.RecoveryShares))
resp.RecoveryKeysB64 = make([]string, 0, len(result.RecoveryShares))
for _, k := range result.RecoveryShares {
resp.RecoveryKeys = append(resp.RecoveryKeys, hex.EncodeToString(k))
resp.RecoveryKeysB64 = append(resp.RecoveryKeysB64, base64.StdEncoding.EncodeToString(k))
}
}
core.UnsealWithStoredKeys()
respondOk(w, resp)
}
示例6: Run
//.........这里部分代码省略.........
}
coreConfig.AdvertiseAddr = config.HABackend.AdvertiseAddr
} else {
if coreConfig.HAPhysical, ok = backend.(physical.HABackend); ok {
coreConfig.AdvertiseAddr = config.Backend.AdvertiseAddr
}
}
if envAA := os.Getenv("VAULT_ADVERTISE_ADDR"); envAA != "" {
coreConfig.AdvertiseAddr = envAA
}
// Attempt to detect the advertise address possible
var detect physical.AdvertiseDetect
if coreConfig.HAPhysical != nil {
detect, ok = coreConfig.HAPhysical.(physical.AdvertiseDetect)
} else {
detect, ok = coreConfig.Physical.(physical.AdvertiseDetect)
}
if ok && coreConfig.AdvertiseAddr == "" {
advertise, err := c.detectAdvertise(detect, config)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error detecting advertise address: %s", err))
} else if advertise == "" {
c.Ui.Error("Failed to detect advertise address.")
} else {
coreConfig.AdvertiseAddr = advertise
}
}
// Initialize the core
core, newCoreError := vault.NewCore(coreConfig)
if newCoreError != nil {
if !errwrap.ContainsType(newCoreError, new(vault.NonFatalError)) {
c.Ui.Error(fmt.Sprintf("Error initializing core: %s", newCoreError))
return 1
}
}
// If we're in dev mode, then initialize the core
if dev {
init, err := c.enableDev(core, devRootTokenID)
if err != nil {
c.Ui.Error(fmt.Sprintf(
"Error initializing dev mode: %s", err))
return 1
}
export := "export"
quote := "'"
if runtime.GOOS == "windows" {
export = "set"
quote = ""
}
c.Ui.Output(fmt.Sprintf(
"==> WARNING: Dev mode is enabled!\n\n"+
"In this mode, Vault is completely in-memory and unsealed.\n"+
"Vault is configured to only have a single unseal key. The root\n"+
"token has already been authenticated with the CLI, so you can\n"+
"immediately begin using the Vault CLI.\n\n"+
"The only step you need to take is to set the following\n"+
"environment variables:\n\n"+
" "+export+" VAULT_ADDR="+quote+"http://"+config.Listeners[0].Config["address"]+quote+"\n\n"+
"The unseal key and root token are reproduced below in case you\n"+
"want to seal/unseal the Vault or play with authentication.\n\n"+
示例7: Run
//.........这里部分代码省略.........
return 1
}
host, port, err := net.SplitHostPort(u.Host)
nPort, nPortErr := strconv.Atoi(port)
if err != nil {
// assume it's due to there not being a port specified, in which case
// use 443
host = u.Host
nPort = 443
}
if nPortErr != nil {
c.Ui.Output(fmt.Sprintf("Cannot parse %s as a numeric port: %v", port, nPortErr))
return 1
}
u.Host = net.JoinHostPort(host, strconv.Itoa(nPort+1))
// Will always be TLS-secured
u.Scheme = "https"
coreConfig.ClusterAddr = u.String()
}
if coreConfig.ClusterAddr != "" {
// Force https as we'll always be TLS-secured
u, err := url.ParseRequestURI(coreConfig.ClusterAddr)
if err != nil {
c.Ui.Output(fmt.Sprintf("Error parsing cluster address %s: %v", coreConfig.RedirectAddr, err))
return 1
}
u.Scheme = "https"
coreConfig.ClusterAddr = u.String()
}
// Initialize the core
core, newCoreError := vault.NewCore(coreConfig)
if newCoreError != nil {
if !errwrap.ContainsType(newCoreError, new(vault.NonFatalError)) {
c.Ui.Output(fmt.Sprintf("Error initializing core: %s", newCoreError))
return 1
}
}
// Copy the reload funcs pointers back
c.reloadFuncs = coreConfig.ReloadFuncs
c.reloadFuncsLock = coreConfig.ReloadFuncsLock
// Compile server information for output later
info["backend"] = config.Backend.Type
info["log level"] = logLevel
info["mlock"] = fmt.Sprintf(
"supported: %v, enabled: %v",
mlock.Supported(), !config.DisableMlock && mlock.Supported())
infoKeys = append(infoKeys, "log level", "mlock", "backend")
if config.HABackend != nil {
info["HA backend"] = config.HABackend.Type
info["redirect address"] = coreConfig.RedirectAddr
infoKeys = append(infoKeys, "HA backend", "redirect address")
if coreConfig.ClusterAddr != "" {
info["cluster address"] = coreConfig.ClusterAddr
infoKeys = append(infoKeys, "cluster address")
}
} else {
// If the backend supports HA, then note it
if coreConfig.HAPhysical != nil {
if coreConfig.HAPhysical.HAEnabled() {
info["backend"] += " (HA available)"
info["redirect address"] = coreConfig.RedirectAddr
infoKeys = append(infoKeys, "redirect address")
示例8: handleSysUnseal
func handleSysUnseal(core *vault.Core) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "PUT":
case "POST":
default:
respondError(w, http.StatusMethodNotAllowed, nil)
return
}
// Parse the request
var req UnsealRequest
if err := parseRequest(r, w, &req); err != nil {
respondError(w, http.StatusBadRequest, err)
return
}
if !req.Reset && req.Key == "" {
respondError(
w, http.StatusBadRequest,
errors.New("'key' must specified in request body as JSON, or 'reset' set to true"))
return
}
if req.Reset {
sealed, err := core.Sealed()
if err != nil {
respondError(w, http.StatusInternalServerError, err)
return
}
if !sealed {
respondError(w, http.StatusBadRequest, errors.New("vault is unsealed"))
return
}
core.ResetUnsealProcess()
} else {
// Decode the key, which is base64 or hex encoded
min, max := core.BarrierKeyLength()
key, err := hex.DecodeString(req.Key)
// We check min and max here to ensure that a string that is base64
// encoded but also valid hex will not be valid and we instead base64
// decode it
if err != nil || len(key) < min || len(key) > max {
key, err = base64.StdEncoding.DecodeString(req.Key)
if err != nil {
respondError(
w, http.StatusBadRequest,
errors.New("'key' must be a valid hex or base64 string"))
return
}
}
// Attempt the unseal
if _, err := core.Unseal(key); err != nil {
switch {
case errwrap.ContainsType(err, new(vault.ErrInvalidKey)):
case errwrap.Contains(err, vault.ErrBarrierInvalidKey.Error()):
case errwrap.Contains(err, vault.ErrBarrierNotInit.Error()):
case errwrap.Contains(err, vault.ErrBarrierSealed.Error()):
case errwrap.Contains(err, vault.ErrStandby.Error()):
default:
respondError(w, http.StatusInternalServerError, err)
return
}
respondError(w, http.StatusBadRequest, err)
return
}
}
// Return the seal status
handleSysSealStatusRaw(core, w, r)
})
}
示例9: Context
// Context returns a Terraform Context taking into account the context
// options used to initialize this meta configuration.
func (m *Meta) Context(copts contextOpts) (*terraform.Context, bool, error) {
opts := m.contextOpts()
// First try to just read the plan directly from the path given.
f, err := os.Open(copts.Path)
if err == nil {
plan, err := terraform.ReadPlan(f)
f.Close()
if err == nil {
// Setup our state, force it to use our plan's state
stateOpts := m.StateOpts()
if plan != nil {
stateOpts.ForceState = plan.State
}
// Get the state
result, err := State(stateOpts)
if err != nil {
return nil, false, fmt.Errorf("Error loading plan: %s", err)
}
// Set our state
m.state = result.State
// this is used for printing the saved location later
if m.stateOutPath == "" {
m.stateOutPath = result.StatePath
}
if len(m.variables) > 0 {
return nil, false, fmt.Errorf(
"You can't set variables with the '-var' or '-var-file' flag\n" +
"when you're applying a plan file. The variables used when\n" +
"the plan was created will be used. If you wish to use different\n" +
"variable values, create a new plan file.")
}
ctx, err := plan.Context(opts)
return ctx, true, err
}
}
// Load the statePath if not given
if copts.StatePath != "" {
m.statePath = copts.StatePath
}
// Tell the context if we're in a destroy plan / apply
opts.Destroy = copts.Destroy
// Store the loaded state
state, err := m.State()
if err != nil {
return nil, false, err
}
// Load the root module
var mod *module.Tree
if copts.Path != "" {
mod, err = module.NewTreeModule("", copts.Path)
// Check for the error where we have no config files but
// allow that. If that happens, clear the error.
if errwrap.ContainsType(err, new(config.ErrNoConfigsFound)) &&
copts.PathEmptyOk {
log.Printf(
"[WARN] Empty configuration dir, ignoring: %s", copts.Path)
err = nil
mod = module.NewEmptyTree()
}
if err != nil {
return nil, false, fmt.Errorf("Error loading config: %s", err)
}
} else {
mod = module.NewEmptyTree()
}
err = mod.Load(m.moduleStorage(m.DataDir()), copts.GetMode)
if err != nil {
return nil, false, fmt.Errorf("Error downloading modules: %s", err)
}
// Validate the module right away
if err := mod.Validate(); err != nil {
return nil, false, err
}
opts.Module = mod
opts.Parallelism = copts.Parallelism
opts.State = state.State()
ctx, err := terraform.NewContext(opts)
return ctx, false, err
}