id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
157,800
juju/juju
worker/uniter/runner/factory.go
NewFactory
func NewFactory( state *uniter.State, paths context.Paths, contextFactory context.ContextFactory, ) ( Factory, error, ) { f := &factory{ state: state, paths: paths, contextFactory: contextFactory, } return f, nil }
go
func NewFactory( state *uniter.State, paths context.Paths, contextFactory context.ContextFactory, ) ( Factory, error, ) { f := &factory{ state: state, paths: paths, contextFactory: contextFactory, } return f, nil }
[ "func", "NewFactory", "(", "state", "*", "uniter", ".", "State", ",", "paths", "context", ".", "Paths", ",", "contextFactory", "context", ".", "ContextFactory", ",", ")", "(", "Factory", ",", "error", ",", ")", "{", "f", ":=", "&", "factory", "{", "state", ":", "state", ",", "paths", ":", "paths", ",", "contextFactory", ":", "contextFactory", ",", "}", "\n\n", "return", "f", ",", "nil", "\n", "}" ]
// NewFactory returns a Factory capable of creating runners for executing // charm hooks, actions and commands.
[ "NewFactory", "returns", "a", "Factory", "capable", "of", "creating", "runners", "for", "executing", "charm", "hooks", "actions", "and", "commands", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/factory.go#L38-L52
157,801
juju/juju
worker/uniter/runner/factory.go
NewCommandRunner
func (f *factory) NewCommandRunner(commandInfo context.CommandInfo) (Runner, error) { ctx, err := f.contextFactory.CommandContext(commandInfo) if err != nil { return nil, errors.Trace(err) } runner := NewRunner(ctx, f.paths) return runner, nil }
go
func (f *factory) NewCommandRunner(commandInfo context.CommandInfo) (Runner, error) { ctx, err := f.contextFactory.CommandContext(commandInfo) if err != nil { return nil, errors.Trace(err) } runner := NewRunner(ctx, f.paths) return runner, nil }
[ "func", "(", "f", "*", "factory", ")", "NewCommandRunner", "(", "commandInfo", "context", ".", "CommandInfo", ")", "(", "Runner", ",", "error", ")", "{", "ctx", ",", "err", ":=", "f", ".", "contextFactory", ".", "CommandContext", "(", "commandInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "runner", ":=", "NewRunner", "(", "ctx", ",", "f", ".", "paths", ")", "\n", "return", "runner", ",", "nil", "\n", "}" ]
// NewCommandRunner exists to satisfy the Factory interface.
[ "NewCommandRunner", "exists", "to", "satisfy", "the", "Factory", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/factory.go#L65-L72
157,802
juju/juju
worker/uniter/runner/factory.go
NewHookRunner
func (f *factory) NewHookRunner(hookInfo hook.Info) (Runner, error) { if err := hookInfo.Validate(); err != nil { return nil, errors.Trace(err) } ctx, err := f.contextFactory.HookContext(hookInfo) if err != nil { return nil, errors.Trace(err) } runner := NewRunner(ctx, f.paths) return runner, nil }
go
func (f *factory) NewHookRunner(hookInfo hook.Info) (Runner, error) { if err := hookInfo.Validate(); err != nil { return nil, errors.Trace(err) } ctx, err := f.contextFactory.HookContext(hookInfo) if err != nil { return nil, errors.Trace(err) } runner := NewRunner(ctx, f.paths) return runner, nil }
[ "func", "(", "f", "*", "factory", ")", "NewHookRunner", "(", "hookInfo", "hook", ".", "Info", ")", "(", "Runner", ",", "error", ")", "{", "if", "err", ":=", "hookInfo", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "ctx", ",", "err", ":=", "f", ".", "contextFactory", ".", "HookContext", "(", "hookInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "runner", ":=", "NewRunner", "(", "ctx", ",", "f", ".", "paths", ")", "\n", "return", "runner", ",", "nil", "\n", "}" ]
// NewHookRunner exists to satisfy the Factory interface.
[ "NewHookRunner", "exists", "to", "satisfy", "the", "Factory", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/factory.go#L75-L86
157,803
juju/juju
worker/uniter/runner/factory.go
NewActionRunner
func (f *factory) NewActionRunner(actionId string) (Runner, error) { ch, err := getCharm(f.paths.GetCharmDir()) if err != nil { return nil, errors.Trace(err) } ok := names.IsValidAction(actionId) if !ok { return nil, charmrunner.NewBadActionError(actionId, "not valid actionId") } tag := names.NewActionTag(actionId) action, err := f.state.Action(tag) if params.IsCodeNotFoundOrCodeUnauthorized(err) { return nil, charmrunner.ErrActionNotAvailable } else if params.IsCodeActionNotAvailable(err) { return nil, charmrunner.ErrActionNotAvailable } else if err != nil { return nil, errors.Trace(err) } name := action.Name() spec, ok := actions.PredefinedActionsSpec[name] if !ok { var ok bool spec, ok = ch.Actions().ActionSpecs[name] if !ok { return nil, charmrunner.NewBadActionError(name, "not defined") } } params := action.Params() if err := spec.ValidateParams(params); err != nil { return nil, charmrunner.NewBadActionError(name, err.Error()) } actionData := context.NewActionData(name, &tag, params) ctx, err := f.contextFactory.ActionContext(actionData) runner := NewRunner(ctx, f.paths) return runner, nil }
go
func (f *factory) NewActionRunner(actionId string) (Runner, error) { ch, err := getCharm(f.paths.GetCharmDir()) if err != nil { return nil, errors.Trace(err) } ok := names.IsValidAction(actionId) if !ok { return nil, charmrunner.NewBadActionError(actionId, "not valid actionId") } tag := names.NewActionTag(actionId) action, err := f.state.Action(tag) if params.IsCodeNotFoundOrCodeUnauthorized(err) { return nil, charmrunner.ErrActionNotAvailable } else if params.IsCodeActionNotAvailable(err) { return nil, charmrunner.ErrActionNotAvailable } else if err != nil { return nil, errors.Trace(err) } name := action.Name() spec, ok := actions.PredefinedActionsSpec[name] if !ok { var ok bool spec, ok = ch.Actions().ActionSpecs[name] if !ok { return nil, charmrunner.NewBadActionError(name, "not defined") } } params := action.Params() if err := spec.ValidateParams(params); err != nil { return nil, charmrunner.NewBadActionError(name, err.Error()) } actionData := context.NewActionData(name, &tag, params) ctx, err := f.contextFactory.ActionContext(actionData) runner := NewRunner(ctx, f.paths) return runner, nil }
[ "func", "(", "f", "*", "factory", ")", "NewActionRunner", "(", "actionId", "string", ")", "(", "Runner", ",", "error", ")", "{", "ch", ",", "err", ":=", "getCharm", "(", "f", ".", "paths", ".", "GetCharmDir", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "ok", ":=", "names", ".", "IsValidAction", "(", "actionId", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "charmrunner", ".", "NewBadActionError", "(", "actionId", ",", "\"", "\"", ")", "\n", "}", "\n", "tag", ":=", "names", ".", "NewActionTag", "(", "actionId", ")", "\n", "action", ",", "err", ":=", "f", ".", "state", ".", "Action", "(", "tag", ")", "\n", "if", "params", ".", "IsCodeNotFoundOrCodeUnauthorized", "(", "err", ")", "{", "return", "nil", ",", "charmrunner", ".", "ErrActionNotAvailable", "\n", "}", "else", "if", "params", ".", "IsCodeActionNotAvailable", "(", "err", ")", "{", "return", "nil", ",", "charmrunner", ".", "ErrActionNotAvailable", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "name", ":=", "action", ".", "Name", "(", ")", "\n\n", "spec", ",", "ok", ":=", "actions", ".", "PredefinedActionsSpec", "[", "name", "]", "\n", "if", "!", "ok", "{", "var", "ok", "bool", "\n", "spec", ",", "ok", "=", "ch", ".", "Actions", "(", ")", ".", "ActionSpecs", "[", "name", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "charmrunner", ".", "NewBadActionError", "(", "name", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "params", ":=", "action", ".", "Params", "(", ")", "\n", "if", "err", ":=", "spec", ".", "ValidateParams", "(", "params", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "charmrunner", ".", "NewBadActionError", "(", "name", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "actionData", ":=", "context", ".", "NewActionData", "(", "name", ",", "&", "tag", ",", "params", ")", "\n", "ctx", ",", "err", ":=", "f", ".", "contextFactory", ".", "ActionContext", "(", "actionData", ")", "\n", "runner", ":=", "NewRunner", "(", "ctx", ",", "f", ".", "paths", ")", "\n", "return", "runner", ",", "nil", "\n", "}" ]
// NewActionRunner exists to satisfy the Factory interface.
[ "NewActionRunner", "exists", "to", "satisfy", "the", "Factory", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/factory.go#L89-L129
157,804
juju/juju
provider/lxd/environ_instance.go
prefixedInstances
func (env *environ) prefixedInstances(prefix string) ([]*environInstance, error) { containers, err := env.server().AliveContainers(prefix) err = errors.Trace(err) // Turn lxd.Container values into *environInstance values, // whether or not we got an error. var results []*environInstance for _, c := range containers { c := c inst := newInstance(&c, env) results = append(results, inst) } return results, err }
go
func (env *environ) prefixedInstances(prefix string) ([]*environInstance, error) { containers, err := env.server().AliveContainers(prefix) err = errors.Trace(err) // Turn lxd.Container values into *environInstance values, // whether or not we got an error. var results []*environInstance for _, c := range containers { c := c inst := newInstance(&c, env) results = append(results, inst) } return results, err }
[ "func", "(", "env", "*", "environ", ")", "prefixedInstances", "(", "prefix", "string", ")", "(", "[", "]", "*", "environInstance", ",", "error", ")", "{", "containers", ",", "err", ":=", "env", ".", "server", "(", ")", ".", "AliveContainers", "(", "prefix", ")", "\n", "err", "=", "errors", ".", "Trace", "(", "err", ")", "\n\n", "// Turn lxd.Container values into *environInstance values,", "// whether or not we got an error.", "var", "results", "[", "]", "*", "environInstance", "\n", "for", "_", ",", "c", ":=", "range", "containers", "{", "c", ":=", "c", "\n", "inst", ":=", "newInstance", "(", "&", "c", ",", "env", ")", "\n", "results", "=", "append", "(", "results", ",", "inst", ")", "\n", "}", "\n", "return", "results", ",", "err", "\n", "}" ]
// prefixedInstances returns instances with the specified prefix.
[ "prefixedInstances", "returns", "instances", "with", "the", "specified", "prefix", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/lxd/environ_instance.go#L81-L94
157,805
juju/juju
provider/lxd/environ_instance.go
AdoptResources
func (env *environ) AdoptResources(ctx context.ProviderCallContext, controllerUUID string, fromVersion version.Number) error { instances, err := env.AllInstances(ctx) if err != nil { common.HandleCredentialError(IsAuthorisationFailure, err, ctx) return errors.Annotate(err, "all instances") } var failed []instance.Id qualifiedKey := lxd.UserNamespacePrefix + tags.JujuController for _, instance := range instances { id := instance.Id() // TODO (manadart 2018-06-27) This is a smell. // Everywhere else, we update the container config on a container and then call WriteContainer. // If we added a method directly to environInstance to do this, we wouldn't need this // implementation of UpdateContainerConfig at all, and the container representation we are // holding would be consistent with that on the server. err := env.server().UpdateContainerConfig(string(id), map[string]string{qualifiedKey: controllerUUID}) if err != nil { logger.Errorf("error setting controller uuid tag for %q: %v", id, err) failed = append(failed, id) } } if len(failed) != 0 { return errors.Errorf("failed to update controller for some instances: %v", failed) } return nil }
go
func (env *environ) AdoptResources(ctx context.ProviderCallContext, controllerUUID string, fromVersion version.Number) error { instances, err := env.AllInstances(ctx) if err != nil { common.HandleCredentialError(IsAuthorisationFailure, err, ctx) return errors.Annotate(err, "all instances") } var failed []instance.Id qualifiedKey := lxd.UserNamespacePrefix + tags.JujuController for _, instance := range instances { id := instance.Id() // TODO (manadart 2018-06-27) This is a smell. // Everywhere else, we update the container config on a container and then call WriteContainer. // If we added a method directly to environInstance to do this, we wouldn't need this // implementation of UpdateContainerConfig at all, and the container representation we are // holding would be consistent with that on the server. err := env.server().UpdateContainerConfig(string(id), map[string]string{qualifiedKey: controllerUUID}) if err != nil { logger.Errorf("error setting controller uuid tag for %q: %v", id, err) failed = append(failed, id) } } if len(failed) != 0 { return errors.Errorf("failed to update controller for some instances: %v", failed) } return nil }
[ "func", "(", "env", "*", "environ", ")", "AdoptResources", "(", "ctx", "context", ".", "ProviderCallContext", ",", "controllerUUID", "string", ",", "fromVersion", "version", ".", "Number", ")", "error", "{", "instances", ",", "err", ":=", "env", ".", "AllInstances", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "common", ".", "HandleCredentialError", "(", "IsAuthorisationFailure", ",", "err", ",", "ctx", ")", "\n", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "var", "failed", "[", "]", "instance", ".", "Id", "\n", "qualifiedKey", ":=", "lxd", ".", "UserNamespacePrefix", "+", "tags", ".", "JujuController", "\n", "for", "_", ",", "instance", ":=", "range", "instances", "{", "id", ":=", "instance", ".", "Id", "(", ")", "\n", "// TODO (manadart 2018-06-27) This is a smell.", "// Everywhere else, we update the container config on a container and then call WriteContainer.", "// If we added a method directly to environInstance to do this, we wouldn't need this", "// implementation of UpdateContainerConfig at all, and the container representation we are", "// holding would be consistent with that on the server.", "err", ":=", "env", ".", "server", "(", ")", ".", "UpdateContainerConfig", "(", "string", "(", "id", ")", ",", "map", "[", "string", "]", "string", "{", "qualifiedKey", ":", "controllerUUID", "}", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "id", ",", "err", ")", "\n", "failed", "=", "append", "(", "failed", ",", "id", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "failed", ")", "!=", "0", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "failed", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// AdoptResources updates the controller tags on all instances to have the // new controller id. It's part of the Environ interface.
[ "AdoptResources", "updates", "the", "controller", "tags", "on", "all", "instances", "to", "have", "the", "new", "controller", "id", ".", "It", "s", "part", "of", "the", "Environ", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/lxd/environ_instance.go#L122-L148
157,806
juju/juju
apiserver/facades/controller/crossmodelrelations/crossmodelrelations.go
NewStateCrossModelRelationsAPI
func NewStateCrossModelRelationsAPI(ctx facade.Context) (*CrossModelRelationsAPI, error) { authCtxt := ctx.Resources().Get("offerAccessAuthContext").(common.ValueResource).Value st := ctx.State() model, err := st.Model() if err != nil { return nil, err } return NewCrossModelRelationsAPI( stateShim{ st: st, Backend: commoncrossmodel.GetBackend(st), }, firewall.StateShim(st, model), ctx.Resources(), ctx.Auth(), authCtxt.(*commoncrossmodel.AuthContext), firewall.WatchEgressAddressesForRelations, watchRelationLifeSuspendedStatus, watchOfferStatus, ) }
go
func NewStateCrossModelRelationsAPI(ctx facade.Context) (*CrossModelRelationsAPI, error) { authCtxt := ctx.Resources().Get("offerAccessAuthContext").(common.ValueResource).Value st := ctx.State() model, err := st.Model() if err != nil { return nil, err } return NewCrossModelRelationsAPI( stateShim{ st: st, Backend: commoncrossmodel.GetBackend(st), }, firewall.StateShim(st, model), ctx.Resources(), ctx.Auth(), authCtxt.(*commoncrossmodel.AuthContext), firewall.WatchEgressAddressesForRelations, watchRelationLifeSuspendedStatus, watchOfferStatus, ) }
[ "func", "NewStateCrossModelRelationsAPI", "(", "ctx", "facade", ".", "Context", ")", "(", "*", "CrossModelRelationsAPI", ",", "error", ")", "{", "authCtxt", ":=", "ctx", ".", "Resources", "(", ")", ".", "Get", "(", "\"", "\"", ")", ".", "(", "common", ".", "ValueResource", ")", ".", "Value", "\n", "st", ":=", "ctx", ".", "State", "(", ")", "\n", "model", ",", "err", ":=", "st", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "NewCrossModelRelationsAPI", "(", "stateShim", "{", "st", ":", "st", ",", "Backend", ":", "commoncrossmodel", ".", "GetBackend", "(", "st", ")", ",", "}", ",", "firewall", ".", "StateShim", "(", "st", ",", "model", ")", ",", "ctx", ".", "Resources", "(", ")", ",", "ctx", ".", "Auth", "(", ")", ",", "authCtxt", ".", "(", "*", "commoncrossmodel", ".", "AuthContext", ")", ",", "firewall", ".", "WatchEgressAddressesForRelations", ",", "watchRelationLifeSuspendedStatus", ",", "watchOfferStatus", ",", ")", "\n", "}" ]
// NewStateCrossModelRelationsAPI creates a new server-side CrossModelRelations API facade // backed by global state.
[ "NewStateCrossModelRelationsAPI", "creates", "a", "new", "server", "-", "side", "CrossModelRelations", "API", "facade", "backed", "by", "global", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/crossmodelrelations/crossmodelrelations.go#L49-L68
157,807
juju/juju
apiserver/facades/controller/crossmodelrelations/crossmodelrelations.go
NewCrossModelRelationsAPI
func NewCrossModelRelationsAPI( st CrossModelRelationsState, fw firewall.State, resources facade.Resources, authorizer facade.Authorizer, authCtxt *commoncrossmodel.AuthContext, egressAddressWatcher egressAddressWatcherFunc, relationStatusWatcher relationStatusWatcherFunc, offerStatusWatcher offerStatusWatcherFunc, ) (*CrossModelRelationsAPI, error) { return &CrossModelRelationsAPI{ st: st, fw: fw, resources: resources, authorizer: authorizer, authCtxt: authCtxt, egressAddressWatcher: egressAddressWatcher, relationStatusWatcher: relationStatusWatcher, offerStatusWatcher: offerStatusWatcher, relationToOffer: make(map[string]string), }, nil }
go
func NewCrossModelRelationsAPI( st CrossModelRelationsState, fw firewall.State, resources facade.Resources, authorizer facade.Authorizer, authCtxt *commoncrossmodel.AuthContext, egressAddressWatcher egressAddressWatcherFunc, relationStatusWatcher relationStatusWatcherFunc, offerStatusWatcher offerStatusWatcherFunc, ) (*CrossModelRelationsAPI, error) { return &CrossModelRelationsAPI{ st: st, fw: fw, resources: resources, authorizer: authorizer, authCtxt: authCtxt, egressAddressWatcher: egressAddressWatcher, relationStatusWatcher: relationStatusWatcher, offerStatusWatcher: offerStatusWatcher, relationToOffer: make(map[string]string), }, nil }
[ "func", "NewCrossModelRelationsAPI", "(", "st", "CrossModelRelationsState", ",", "fw", "firewall", ".", "State", ",", "resources", "facade", ".", "Resources", ",", "authorizer", "facade", ".", "Authorizer", ",", "authCtxt", "*", "commoncrossmodel", ".", "AuthContext", ",", "egressAddressWatcher", "egressAddressWatcherFunc", ",", "relationStatusWatcher", "relationStatusWatcherFunc", ",", "offerStatusWatcher", "offerStatusWatcherFunc", ",", ")", "(", "*", "CrossModelRelationsAPI", ",", "error", ")", "{", "return", "&", "CrossModelRelationsAPI", "{", "st", ":", "st", ",", "fw", ":", "fw", ",", "resources", ":", "resources", ",", "authorizer", ":", "authorizer", ",", "authCtxt", ":", "authCtxt", ",", "egressAddressWatcher", ":", "egressAddressWatcher", ",", "relationStatusWatcher", ":", "relationStatusWatcher", ",", "offerStatusWatcher", ":", "offerStatusWatcher", ",", "relationToOffer", ":", "make", "(", "map", "[", "string", "]", "string", ")", ",", "}", ",", "nil", "\n", "}" ]
// NewCrossModelRelationsAPI returns a new server-side CrossModelRelationsAPI facade.
[ "NewCrossModelRelationsAPI", "returns", "a", "new", "server", "-", "side", "CrossModelRelationsAPI", "facade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/crossmodelrelations/crossmodelrelations.go#L71-L92
157,808
juju/juju
apiserver/facades/controller/crossmodelrelations/crossmodelrelations.go
PublishRelationChanges
func (api *CrossModelRelationsAPI) PublishRelationChanges( changes params.RemoteRelationsChanges, ) (params.ErrorResults, error) { results := params.ErrorResults{ Results: make([]params.ErrorResult, len(changes.Changes)), } for i, change := range changes.Changes { relationTag, err := api.st.GetRemoteEntity(change.RelationToken) if err != nil { if errors.IsNotFound(err) { logger.Debugf("no relation tag %+v in model %v, exit early", change.RelationToken, api.st.ModelUUID()) continue } results.Results[i].Error = common.ServerError(err) continue } logger.Debugf("relation tag for token %+v is %v", change.RelationToken, relationTag) if err := api.checkMacaroonsForRelation(relationTag, change.Macaroons); err != nil { results.Results[i].Error = common.ServerError(err) continue } if err := commoncrossmodel.PublishRelationChange(api.st, relationTag, change); err != nil { results.Results[i].Error = common.ServerError(err) continue } if change.Life != params.Alive { delete(api.relationToOffer, relationTag.Id()) } } return results, nil }
go
func (api *CrossModelRelationsAPI) PublishRelationChanges( changes params.RemoteRelationsChanges, ) (params.ErrorResults, error) { results := params.ErrorResults{ Results: make([]params.ErrorResult, len(changes.Changes)), } for i, change := range changes.Changes { relationTag, err := api.st.GetRemoteEntity(change.RelationToken) if err != nil { if errors.IsNotFound(err) { logger.Debugf("no relation tag %+v in model %v, exit early", change.RelationToken, api.st.ModelUUID()) continue } results.Results[i].Error = common.ServerError(err) continue } logger.Debugf("relation tag for token %+v is %v", change.RelationToken, relationTag) if err := api.checkMacaroonsForRelation(relationTag, change.Macaroons); err != nil { results.Results[i].Error = common.ServerError(err) continue } if err := commoncrossmodel.PublishRelationChange(api.st, relationTag, change); err != nil { results.Results[i].Error = common.ServerError(err) continue } if change.Life != params.Alive { delete(api.relationToOffer, relationTag.Id()) } } return results, nil }
[ "func", "(", "api", "*", "CrossModelRelationsAPI", ")", "PublishRelationChanges", "(", "changes", "params", ".", "RemoteRelationsChanges", ",", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "results", ":=", "params", ".", "ErrorResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "changes", ".", "Changes", ")", ")", ",", "}", "\n", "for", "i", ",", "change", ":=", "range", "changes", ".", "Changes", "{", "relationTag", ",", "err", ":=", "api", ".", "st", ".", "GetRemoteEntity", "(", "change", ".", "RelationToken", ")", "\n", "if", "err", "!=", "nil", "{", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "change", ".", "RelationToken", ",", "api", ".", "st", ".", "ModelUUID", "(", ")", ")", "\n", "continue", "\n", "}", "\n", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "change", ".", "RelationToken", ",", "relationTag", ")", "\n", "if", "err", ":=", "api", ".", "checkMacaroonsForRelation", "(", "relationTag", ",", "change", ".", "Macaroons", ")", ";", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "err", ":=", "commoncrossmodel", ".", "PublishRelationChange", "(", "api", ".", "st", ",", "relationTag", ",", "change", ")", ";", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "change", ".", "Life", "!=", "params", ".", "Alive", "{", "delete", "(", "api", ".", "relationToOffer", ",", "relationTag", ".", "Id", "(", ")", ")", "\n", "}", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// PublishRelationChanges publishes relation changes to the // model hosting the remote application involved in the relation.
[ "PublishRelationChanges", "publishes", "relation", "changes", "to", "the", "model", "hosting", "the", "remote", "application", "involved", "in", "the", "relation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/crossmodelrelations/crossmodelrelations.go#L112-L142
157,809
juju/juju
apiserver/facades/controller/crossmodelrelations/crossmodelrelations.go
RegisterRemoteRelations
func (api *CrossModelRelationsAPI) RegisterRemoteRelations( relations params.RegisterRemoteRelationArgs, ) (params.RegisterRemoteRelationResults, error) { results := params.RegisterRemoteRelationResults{ Results: make([]params.RegisterRemoteRelationResult, len(relations.Relations)), } for i, relation := range relations.Relations { id, err := api.registerRemoteRelation(relation) results.Results[i].Result = id results.Results[i].Error = common.ServerError(err) } return results, nil }
go
func (api *CrossModelRelationsAPI) RegisterRemoteRelations( relations params.RegisterRemoteRelationArgs, ) (params.RegisterRemoteRelationResults, error) { results := params.RegisterRemoteRelationResults{ Results: make([]params.RegisterRemoteRelationResult, len(relations.Relations)), } for i, relation := range relations.Relations { id, err := api.registerRemoteRelation(relation) results.Results[i].Result = id results.Results[i].Error = common.ServerError(err) } return results, nil }
[ "func", "(", "api", "*", "CrossModelRelationsAPI", ")", "RegisterRemoteRelations", "(", "relations", "params", ".", "RegisterRemoteRelationArgs", ",", ")", "(", "params", ".", "RegisterRemoteRelationResults", ",", "error", ")", "{", "results", ":=", "params", ".", "RegisterRemoteRelationResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "RegisterRemoteRelationResult", ",", "len", "(", "relations", ".", "Relations", ")", ")", ",", "}", "\n", "for", "i", ",", "relation", ":=", "range", "relations", ".", "Relations", "{", "id", ",", "err", ":=", "api", ".", "registerRemoteRelation", "(", "relation", ")", "\n", "results", ".", "Results", "[", "i", "]", ".", "Result", "=", "id", "\n", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// RegisterRemoteRelationArgs sets up the model to participate // in the specified relations. This operation is idempotent.
[ "RegisterRemoteRelationArgs", "sets", "up", "the", "model", "to", "participate", "in", "the", "specified", "relations", ".", "This", "operation", "is", "idempotent", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/crossmodelrelations/crossmodelrelations.go#L146-L158
157,810
juju/juju
apiserver/facades/controller/crossmodelrelations/crossmodelrelations.go
WatchRelationUnits
func (api *CrossModelRelationsAPI) WatchRelationUnits(remoteRelationArgs params.RemoteEntityArgs) (params.RelationUnitsWatchResults, error) { results := params.RelationUnitsWatchResults{ Results: make([]params.RelationUnitsWatchResult, len(remoteRelationArgs.Args)), } for i, arg := range remoteRelationArgs.Args { relationTag, err := api.st.GetRemoteEntity(arg.Token) if err != nil { results.Results[i].Error = common.ServerError(err) continue } if err := api.checkMacaroonsForRelation(relationTag, arg.Macaroons); err != nil { results.Results[i].Error = common.ServerError(err) continue } w, err := commoncrossmodel.WatchRelationUnits(api.st, relationTag.(names.RelationTag)) if err != nil { results.Results[i].Error = common.ServerError(err) continue } changes, ok := <-w.Changes() if !ok { results.Results[i].Error = common.ServerError(watcher.EnsureErr(w)) continue } results.Results[i].RelationUnitsWatcherId = api.resources.Register(w) results.Results[i].Changes = changes } return results, nil }
go
func (api *CrossModelRelationsAPI) WatchRelationUnits(remoteRelationArgs params.RemoteEntityArgs) (params.RelationUnitsWatchResults, error) { results := params.RelationUnitsWatchResults{ Results: make([]params.RelationUnitsWatchResult, len(remoteRelationArgs.Args)), } for i, arg := range remoteRelationArgs.Args { relationTag, err := api.st.GetRemoteEntity(arg.Token) if err != nil { results.Results[i].Error = common.ServerError(err) continue } if err := api.checkMacaroonsForRelation(relationTag, arg.Macaroons); err != nil { results.Results[i].Error = common.ServerError(err) continue } w, err := commoncrossmodel.WatchRelationUnits(api.st, relationTag.(names.RelationTag)) if err != nil { results.Results[i].Error = common.ServerError(err) continue } changes, ok := <-w.Changes() if !ok { results.Results[i].Error = common.ServerError(watcher.EnsureErr(w)) continue } results.Results[i].RelationUnitsWatcherId = api.resources.Register(w) results.Results[i].Changes = changes } return results, nil }
[ "func", "(", "api", "*", "CrossModelRelationsAPI", ")", "WatchRelationUnits", "(", "remoteRelationArgs", "params", ".", "RemoteEntityArgs", ")", "(", "params", ".", "RelationUnitsWatchResults", ",", "error", ")", "{", "results", ":=", "params", ".", "RelationUnitsWatchResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "RelationUnitsWatchResult", ",", "len", "(", "remoteRelationArgs", ".", "Args", ")", ")", ",", "}", "\n", "for", "i", ",", "arg", ":=", "range", "remoteRelationArgs", ".", "Args", "{", "relationTag", ",", "err", ":=", "api", ".", "st", ".", "GetRemoteEntity", "(", "arg", ".", "Token", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "err", ":=", "api", ".", "checkMacaroonsForRelation", "(", "relationTag", ",", "arg", ".", "Macaroons", ")", ";", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "w", ",", "err", ":=", "commoncrossmodel", ".", "WatchRelationUnits", "(", "api", ".", "st", ",", "relationTag", ".", "(", "names", ".", "RelationTag", ")", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "changes", ",", "ok", ":=", "<-", "w", ".", "Changes", "(", ")", "\n", "if", "!", "ok", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "watcher", ".", "EnsureErr", "(", "w", ")", ")", "\n", "continue", "\n", "}", "\n", "results", ".", "Results", "[", "i", "]", ".", "RelationUnitsWatcherId", "=", "api", ".", "resources", ".", "Register", "(", "w", ")", "\n", "results", ".", "Results", "[", "i", "]", ".", "Changes", "=", "changes", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// WatchRelationUnits starts a RelationUnitsWatcher for watching the // relation units involved in each specified relation, and returns the // watcher IDs and initial values, or an error if the relation units could not be watched.
[ "WatchRelationUnits", "starts", "a", "RelationUnitsWatcher", "for", "watching", "the", "relation", "units", "involved", "in", "each", "specified", "relation", "and", "returns", "the", "watcher", "IDs", "and", "initial", "values", "or", "an", "error", "if", "the", "relation", "units", "could", "not", "be", "watched", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/crossmodelrelations/crossmodelrelations.go#L311-L339
157,811
juju/juju
apiserver/facades/controller/crossmodelrelations/crossmodelrelations.go
RelationUnitSettings
func (api *CrossModelRelationsAPI) RelationUnitSettings(relationUnits params.RemoteRelationUnits) (params.SettingsResults, error) { results := params.SettingsResults{ Results: make([]params.SettingsResult, len(relationUnits.RelationUnits)), } for i, arg := range relationUnits.RelationUnits { relationTag, err := api.st.GetRemoteEntity(arg.RelationToken) if err != nil { results.Results[i].Error = common.ServerError(err) continue } if err := api.checkMacaroonsForRelation(relationTag, arg.Macaroons); err != nil { results.Results[i].Error = common.ServerError(err) continue } ru := params.RelationUnit{ Relation: relationTag.String(), Unit: arg.Unit, } settings, err := commoncrossmodel.RelationUnitSettings(api.st, ru) if err != nil { results.Results[i].Error = common.ServerError(err) continue } results.Results[i].Settings = settings } return results, nil }
go
func (api *CrossModelRelationsAPI) RelationUnitSettings(relationUnits params.RemoteRelationUnits) (params.SettingsResults, error) { results := params.SettingsResults{ Results: make([]params.SettingsResult, len(relationUnits.RelationUnits)), } for i, arg := range relationUnits.RelationUnits { relationTag, err := api.st.GetRemoteEntity(arg.RelationToken) if err != nil { results.Results[i].Error = common.ServerError(err) continue } if err := api.checkMacaroonsForRelation(relationTag, arg.Macaroons); err != nil { results.Results[i].Error = common.ServerError(err) continue } ru := params.RelationUnit{ Relation: relationTag.String(), Unit: arg.Unit, } settings, err := commoncrossmodel.RelationUnitSettings(api.st, ru) if err != nil { results.Results[i].Error = common.ServerError(err) continue } results.Results[i].Settings = settings } return results, nil }
[ "func", "(", "api", "*", "CrossModelRelationsAPI", ")", "RelationUnitSettings", "(", "relationUnits", "params", ".", "RemoteRelationUnits", ")", "(", "params", ".", "SettingsResults", ",", "error", ")", "{", "results", ":=", "params", ".", "SettingsResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "SettingsResult", ",", "len", "(", "relationUnits", ".", "RelationUnits", ")", ")", ",", "}", "\n", "for", "i", ",", "arg", ":=", "range", "relationUnits", ".", "RelationUnits", "{", "relationTag", ",", "err", ":=", "api", ".", "st", ".", "GetRemoteEntity", "(", "arg", ".", "RelationToken", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "err", ":=", "api", ".", "checkMacaroonsForRelation", "(", "relationTag", ",", "arg", ".", "Macaroons", ")", ";", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n\n", "ru", ":=", "params", ".", "RelationUnit", "{", "Relation", ":", "relationTag", ".", "String", "(", ")", ",", "Unit", ":", "arg", ".", "Unit", ",", "}", "\n", "settings", ",", "err", ":=", "commoncrossmodel", ".", "RelationUnitSettings", "(", "api", ".", "st", ",", "ru", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "results", ".", "Results", "[", "i", "]", ".", "Settings", "=", "settings", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// RelationUnitSettings returns the relation unit settings for the given relation units.
[ "RelationUnitSettings", "returns", "the", "relation", "unit", "settings", "for", "the", "given", "relation", "units", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/crossmodelrelations/crossmodelrelations.go#L342-L369
157,812
juju/juju
apiserver/facades/controller/crossmodelrelations/crossmodelrelations.go
WatchRelationsSuspendedStatus
func (api *CrossModelRelationsAPI) WatchRelationsSuspendedStatus( remoteRelationArgs params.RemoteEntityArgs, ) (params.RelationStatusWatchResults, error) { results := params.RelationStatusWatchResults{ Results: make([]params.RelationLifeSuspendedStatusWatchResult, len(remoteRelationArgs.Args)), } for i, arg := range remoteRelationArgs.Args { relationTag, err := api.st.GetRemoteEntity(arg.Token) if err != nil { results.Results[i].Error = common.ServerError(err) continue } if err := api.checkMacaroonsForRelation(relationTag, arg.Macaroons); err != nil { results.Results[i].Error = common.ServerError(err) continue } w, err := api.relationStatusWatcher(api.st, relationTag.(names.RelationTag)) if err != nil { results.Results[i].Error = common.ServerError(err) continue } changes, ok := <-w.Changes() if !ok { results.Results[i].Error = common.ServerError(watcher.EnsureErr(w)) continue } changesParams := make([]params.RelationLifeSuspendedStatusChange, len(changes)) for j, key := range changes { change, err := commoncrossmodel.GetRelationLifeSuspendedStatusChange(api.st, key) if err != nil { results.Results[i].Error = common.ServerError(err) changesParams = nil w.Stop() break } changesParams[j] = *change } results.Results[i].Changes = changesParams results.Results[i].RelationStatusWatcherId = api.resources.Register(w) } return results, nil }
go
func (api *CrossModelRelationsAPI) WatchRelationsSuspendedStatus( remoteRelationArgs params.RemoteEntityArgs, ) (params.RelationStatusWatchResults, error) { results := params.RelationStatusWatchResults{ Results: make([]params.RelationLifeSuspendedStatusWatchResult, len(remoteRelationArgs.Args)), } for i, arg := range remoteRelationArgs.Args { relationTag, err := api.st.GetRemoteEntity(arg.Token) if err != nil { results.Results[i].Error = common.ServerError(err) continue } if err := api.checkMacaroonsForRelation(relationTag, arg.Macaroons); err != nil { results.Results[i].Error = common.ServerError(err) continue } w, err := api.relationStatusWatcher(api.st, relationTag.(names.RelationTag)) if err != nil { results.Results[i].Error = common.ServerError(err) continue } changes, ok := <-w.Changes() if !ok { results.Results[i].Error = common.ServerError(watcher.EnsureErr(w)) continue } changesParams := make([]params.RelationLifeSuspendedStatusChange, len(changes)) for j, key := range changes { change, err := commoncrossmodel.GetRelationLifeSuspendedStatusChange(api.st, key) if err != nil { results.Results[i].Error = common.ServerError(err) changesParams = nil w.Stop() break } changesParams[j] = *change } results.Results[i].Changes = changesParams results.Results[i].RelationStatusWatcherId = api.resources.Register(w) } return results, nil }
[ "func", "(", "api", "*", "CrossModelRelationsAPI", ")", "WatchRelationsSuspendedStatus", "(", "remoteRelationArgs", "params", ".", "RemoteEntityArgs", ",", ")", "(", "params", ".", "RelationStatusWatchResults", ",", "error", ")", "{", "results", ":=", "params", ".", "RelationStatusWatchResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "RelationLifeSuspendedStatusWatchResult", ",", "len", "(", "remoteRelationArgs", ".", "Args", ")", ")", ",", "}", "\n\n", "for", "i", ",", "arg", ":=", "range", "remoteRelationArgs", ".", "Args", "{", "relationTag", ",", "err", ":=", "api", ".", "st", ".", "GetRemoteEntity", "(", "arg", ".", "Token", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "err", ":=", "api", ".", "checkMacaroonsForRelation", "(", "relationTag", ",", "arg", ".", "Macaroons", ")", ";", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "w", ",", "err", ":=", "api", ".", "relationStatusWatcher", "(", "api", ".", "st", ",", "relationTag", ".", "(", "names", ".", "RelationTag", ")", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "changes", ",", "ok", ":=", "<-", "w", ".", "Changes", "(", ")", "\n", "if", "!", "ok", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "watcher", ".", "EnsureErr", "(", "w", ")", ")", "\n", "continue", "\n", "}", "\n", "changesParams", ":=", "make", "(", "[", "]", "params", ".", "RelationLifeSuspendedStatusChange", ",", "len", "(", "changes", ")", ")", "\n", "for", "j", ",", "key", ":=", "range", "changes", "{", "change", ",", "err", ":=", "commoncrossmodel", ".", "GetRelationLifeSuspendedStatusChange", "(", "api", ".", "st", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "changesParams", "=", "nil", "\n", "w", ".", "Stop", "(", ")", "\n", "break", "\n", "}", "\n", "changesParams", "[", "j", "]", "=", "*", "change", "\n", "}", "\n", "results", ".", "Results", "[", "i", "]", ".", "Changes", "=", "changesParams", "\n", "results", ".", "Results", "[", "i", "]", ".", "RelationStatusWatcherId", "=", "api", ".", "resources", ".", "Register", "(", "w", ")", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// WatchRelationsSuspendedStatus starts a RelationStatusWatcher for // watching the life and suspended status of a relation.
[ "WatchRelationsSuspendedStatus", "starts", "a", "RelationStatusWatcher", "for", "watching", "the", "life", "and", "suspended", "status", "of", "a", "relation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/crossmodelrelations/crossmodelrelations.go#L381-L423
157,813
juju/juju
apiserver/facades/controller/crossmodelrelations/crossmodelrelations.go
WatchOfferStatus
func (api *CrossModelRelationsAPI) WatchOfferStatus( offerArgs params.OfferArgs, ) (params.OfferStatusWatchResults, error) { results := params.OfferStatusWatchResults{ Results: make([]params.OfferStatusWatchResult, len(offerArgs.Args)), } for i, arg := range offerArgs.Args { // Ensure the supplied macaroon allows access. auth := api.authCtxt.Authenticator(api.st.ModelUUID(), arg.OfferUUID) _, err := auth.CheckOfferMacaroons(arg.OfferUUID, arg.Macaroons) if err != nil { results.Results[i].Error = common.ServerError(err) continue } w, err := api.offerStatusWatcher(api.st, arg.OfferUUID) if err != nil { results.Results[i].Error = common.ServerError(err) continue } _, ok := <-w.Changes() if !ok { results.Results[i].Error = common.ServerError(watcher.EnsureErr(w)) continue } change, err := commoncrossmodel.GetOfferStatusChange(api.st, arg.OfferUUID) if err != nil { results.Results[i].Error = common.ServerError(err) w.Stop() break } results.Results[i].Changes = []params.OfferStatusChange{*change} results.Results[i].OfferStatusWatcherId = api.resources.Register(w) } return results, nil }
go
func (api *CrossModelRelationsAPI) WatchOfferStatus( offerArgs params.OfferArgs, ) (params.OfferStatusWatchResults, error) { results := params.OfferStatusWatchResults{ Results: make([]params.OfferStatusWatchResult, len(offerArgs.Args)), } for i, arg := range offerArgs.Args { // Ensure the supplied macaroon allows access. auth := api.authCtxt.Authenticator(api.st.ModelUUID(), arg.OfferUUID) _, err := auth.CheckOfferMacaroons(arg.OfferUUID, arg.Macaroons) if err != nil { results.Results[i].Error = common.ServerError(err) continue } w, err := api.offerStatusWatcher(api.st, arg.OfferUUID) if err != nil { results.Results[i].Error = common.ServerError(err) continue } _, ok := <-w.Changes() if !ok { results.Results[i].Error = common.ServerError(watcher.EnsureErr(w)) continue } change, err := commoncrossmodel.GetOfferStatusChange(api.st, arg.OfferUUID) if err != nil { results.Results[i].Error = common.ServerError(err) w.Stop() break } results.Results[i].Changes = []params.OfferStatusChange{*change} results.Results[i].OfferStatusWatcherId = api.resources.Register(w) } return results, nil }
[ "func", "(", "api", "*", "CrossModelRelationsAPI", ")", "WatchOfferStatus", "(", "offerArgs", "params", ".", "OfferArgs", ",", ")", "(", "params", ".", "OfferStatusWatchResults", ",", "error", ")", "{", "results", ":=", "params", ".", "OfferStatusWatchResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "OfferStatusWatchResult", ",", "len", "(", "offerArgs", ".", "Args", ")", ")", ",", "}", "\n\n", "for", "i", ",", "arg", ":=", "range", "offerArgs", ".", "Args", "{", "// Ensure the supplied macaroon allows access.", "auth", ":=", "api", ".", "authCtxt", ".", "Authenticator", "(", "api", ".", "st", ".", "ModelUUID", "(", ")", ",", "arg", ".", "OfferUUID", ")", "\n", "_", ",", "err", ":=", "auth", ".", "CheckOfferMacaroons", "(", "arg", ".", "OfferUUID", ",", "arg", ".", "Macaroons", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n\n", "w", ",", "err", ":=", "api", ".", "offerStatusWatcher", "(", "api", ".", "st", ",", "arg", ".", "OfferUUID", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "_", ",", "ok", ":=", "<-", "w", ".", "Changes", "(", ")", "\n", "if", "!", "ok", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "watcher", ".", "EnsureErr", "(", "w", ")", ")", "\n", "continue", "\n", "}", "\n", "change", ",", "err", ":=", "commoncrossmodel", ".", "GetOfferStatusChange", "(", "api", ".", "st", ",", "arg", ".", "OfferUUID", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "w", ".", "Stop", "(", ")", "\n", "break", "\n", "}", "\n", "results", ".", "Results", "[", "i", "]", ".", "Changes", "=", "[", "]", "params", ".", "OfferStatusChange", "{", "*", "change", "}", "\n", "results", ".", "Results", "[", "i", "]", ".", "OfferStatusWatcherId", "=", "api", ".", "resources", ".", "Register", "(", "w", ")", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// WatchOfferStatus starts an OfferStatusWatcher for // watching the status of an offer.
[ "WatchOfferStatus", "starts", "an", "OfferStatusWatcher", "for", "watching", "the", "status", "of", "an", "offer", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/crossmodelrelations/crossmodelrelations.go#L450-L486
157,814
juju/juju
apiserver/facades/controller/crossmodelrelations/crossmodelrelations.go
PublishIngressNetworkChanges
func (api *CrossModelRelationsAPI) PublishIngressNetworkChanges( changes params.IngressNetworksChanges, ) (params.ErrorResults, error) { results := params.ErrorResults{ Results: make([]params.ErrorResult, len(changes.Changes)), } for i, change := range changes.Changes { relationTag, err := api.st.GetRemoteEntity(change.RelationToken) if err != nil { results.Results[i].Error = common.ServerError(err) continue } logger.Debugf("relation tag for token %+v is %v", change.RelationToken, relationTag) if err := api.checkMacaroonsForRelation(relationTag, change.Macaroons); err != nil { results.Results[i].Error = common.ServerError(err) continue } if err := commoncrossmodel.PublishIngressNetworkChange(api.st, relationTag, change); err != nil { results.Results[i].Error = common.ServerError(err) continue } } return results, nil }
go
func (api *CrossModelRelationsAPI) PublishIngressNetworkChanges( changes params.IngressNetworksChanges, ) (params.ErrorResults, error) { results := params.ErrorResults{ Results: make([]params.ErrorResult, len(changes.Changes)), } for i, change := range changes.Changes { relationTag, err := api.st.GetRemoteEntity(change.RelationToken) if err != nil { results.Results[i].Error = common.ServerError(err) continue } logger.Debugf("relation tag for token %+v is %v", change.RelationToken, relationTag) if err := api.checkMacaroonsForRelation(relationTag, change.Macaroons); err != nil { results.Results[i].Error = common.ServerError(err) continue } if err := commoncrossmodel.PublishIngressNetworkChange(api.st, relationTag, change); err != nil { results.Results[i].Error = common.ServerError(err) continue } } return results, nil }
[ "func", "(", "api", "*", "CrossModelRelationsAPI", ")", "PublishIngressNetworkChanges", "(", "changes", "params", ".", "IngressNetworksChanges", ",", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "results", ":=", "params", ".", "ErrorResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "changes", ".", "Changes", ")", ")", ",", "}", "\n", "for", "i", ",", "change", ":=", "range", "changes", ".", "Changes", "{", "relationTag", ",", "err", ":=", "api", ".", "st", ".", "GetRemoteEntity", "(", "change", ".", "RelationToken", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "change", ".", "RelationToken", ",", "relationTag", ")", "\n\n", "if", "err", ":=", "api", ".", "checkMacaroonsForRelation", "(", "relationTag", ",", "change", ".", "Macaroons", ")", ";", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "err", ":=", "commoncrossmodel", ".", "PublishIngressNetworkChange", "(", "api", ".", "st", ",", "relationTag", ",", "change", ")", ";", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// PublishIngressNetworkChanges publishes changes to the required // ingress addresses to the model hosting the offer in the relation.
[ "PublishIngressNetworkChanges", "publishes", "changes", "to", "the", "required", "ingress", "addresses", "to", "the", "model", "hosting", "the", "offer", "in", "the", "relation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/crossmodelrelations/crossmodelrelations.go#L490-L514
157,815
juju/juju
api/common/network.go
InterfaceAddresses
func (n *netPackageConfigSource) InterfaceAddresses(name string) ([]net.Addr, error) { iface, err := net.InterfaceByName(name) if err != nil { return nil, errors.Trace(err) } return iface.Addrs() }
go
func (n *netPackageConfigSource) InterfaceAddresses(name string) ([]net.Addr, error) { iface, err := net.InterfaceByName(name) if err != nil { return nil, errors.Trace(err) } return iface.Addrs() }
[ "func", "(", "n", "*", "netPackageConfigSource", ")", "InterfaceAddresses", "(", "name", "string", ")", "(", "[", "]", "net", ".", "Addr", ",", "error", ")", "{", "iface", ",", "err", ":=", "net", ".", "InterfaceByName", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "iface", ".", "Addrs", "(", ")", "\n", "}" ]
// InterfaceAddresses implements NetworkConfigSource.
[ "InterfaceAddresses", "implements", "NetworkConfigSource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/common/network.go#L52-L58
157,816
juju/juju
payload/api/client/public.go
ListFull
func (c PublicClient) ListFull(patterns ...string) ([]payload.FullPayloadInfo, error) { var result params.PayloadListResults args := params.PayloadListArgs{ Patterns: patterns, } if err := c.FacadeCall("List", &args, &result); err != nil { return nil, errors.Trace(err) } payloads := make([]payload.FullPayloadInfo, len(result.Results)) for i, apiInfo := range result.Results { payload, err := api.API2Payload(apiInfo) if err != nil { // We should never see this happen; we control the input safely. return nil, errors.Trace(err) } payloads[i] = payload } return payloads, nil }
go
func (c PublicClient) ListFull(patterns ...string) ([]payload.FullPayloadInfo, error) { var result params.PayloadListResults args := params.PayloadListArgs{ Patterns: patterns, } if err := c.FacadeCall("List", &args, &result); err != nil { return nil, errors.Trace(err) } payloads := make([]payload.FullPayloadInfo, len(result.Results)) for i, apiInfo := range result.Results { payload, err := api.API2Payload(apiInfo) if err != nil { // We should never see this happen; we control the input safely. return nil, errors.Trace(err) } payloads[i] = payload } return payloads, nil }
[ "func", "(", "c", "PublicClient", ")", "ListFull", "(", "patterns", "...", "string", ")", "(", "[", "]", "payload", ".", "FullPayloadInfo", ",", "error", ")", "{", "var", "result", "params", ".", "PayloadListResults", "\n\n", "args", ":=", "params", ".", "PayloadListArgs", "{", "Patterns", ":", "patterns", ",", "}", "\n", "if", "err", ":=", "c", ".", "FacadeCall", "(", "\"", "\"", ",", "&", "args", ",", "&", "result", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "payloads", ":=", "make", "(", "[", "]", "payload", ".", "FullPayloadInfo", ",", "len", "(", "result", ".", "Results", ")", ")", "\n", "for", "i", ",", "apiInfo", ":=", "range", "result", ".", "Results", "{", "payload", ",", "err", ":=", "api", ".", "API2Payload", "(", "apiInfo", ")", "\n", "if", "err", "!=", "nil", "{", "// We should never see this happen; we control the input safely.", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "payloads", "[", "i", "]", "=", "payload", "\n", "}", "\n", "return", "payloads", ",", "nil", "\n", "}" ]
// ListFull calls the List API server method.
[ "ListFull", "calls", "the", "List", "API", "server", "method", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/payload/api/client/public.go#L39-L59
157,817
juju/juju
cmd/juju/commands/run.go
ConvertActionResults
func ConvertActionResults(result params.ActionResult, query actionQuery) map[string]interface{} { values := make(map[string]interface{}) values[query.receiver.receiverType] = query.receiver.tag.Id() if result.Error != nil { values["Error"] = result.Error.Error() values["Action"] = query.actionTag.Id() return values } if result.Action.Tag != query.actionTag.String() { values["Error"] = fmt.Sprintf("expected action tag %q, got %q", query.actionTag.String(), result.Action.Tag) values["Action"] = query.actionTag.Id() return values } if result.Action.Receiver != query.receiver.tag.String() { values["Error"] = fmt.Sprintf("expected action receiver %q, got %q", query.receiver.tag.String(), result.Action.Receiver) values["Action"] = query.actionTag.Id() return values } if result.Message != "" { values["Message"] = result.Message } // We always want to have a string for stdout, but only show stderr, // code and error if they are there. if res, ok := result.Output["Stdout"].(string); ok { values["Stdout"] = strings.Replace(res, "\r\n", "\n", -1) if res, ok := result.Output["StdoutEncoding"].(string); ok && res != "" { values["Stdout.encoding"] = res } } else { values["Stdout"] = "" } if res, ok := result.Output["Stderr"].(string); ok && res != "" { values["Stderr"] = strings.Replace(res, "\r\n", "\n", -1) if res, ok := result.Output["StderrEncoding"].(string); ok && res != "" { values["Stderr.encoding"] = res } } if res, ok := result.Output["Code"].(string); ok { code, err := strconv.Atoi(res) if err == nil && code != 0 { values["ReturnCode"] = code } } return values }
go
func ConvertActionResults(result params.ActionResult, query actionQuery) map[string]interface{} { values := make(map[string]interface{}) values[query.receiver.receiverType] = query.receiver.tag.Id() if result.Error != nil { values["Error"] = result.Error.Error() values["Action"] = query.actionTag.Id() return values } if result.Action.Tag != query.actionTag.String() { values["Error"] = fmt.Sprintf("expected action tag %q, got %q", query.actionTag.String(), result.Action.Tag) values["Action"] = query.actionTag.Id() return values } if result.Action.Receiver != query.receiver.tag.String() { values["Error"] = fmt.Sprintf("expected action receiver %q, got %q", query.receiver.tag.String(), result.Action.Receiver) values["Action"] = query.actionTag.Id() return values } if result.Message != "" { values["Message"] = result.Message } // We always want to have a string for stdout, but only show stderr, // code and error if they are there. if res, ok := result.Output["Stdout"].(string); ok { values["Stdout"] = strings.Replace(res, "\r\n", "\n", -1) if res, ok := result.Output["StdoutEncoding"].(string); ok && res != "" { values["Stdout.encoding"] = res } } else { values["Stdout"] = "" } if res, ok := result.Output["Stderr"].(string); ok && res != "" { values["Stderr"] = strings.Replace(res, "\r\n", "\n", -1) if res, ok := result.Output["StderrEncoding"].(string); ok && res != "" { values["Stderr.encoding"] = res } } if res, ok := result.Output["Code"].(string); ok { code, err := strconv.Atoi(res) if err == nil && code != 0 { values["ReturnCode"] = code } } return values }
[ "func", "ConvertActionResults", "(", "result", "params", ".", "ActionResult", ",", "query", "actionQuery", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "values", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "values", "[", "query", ".", "receiver", ".", "receiverType", "]", "=", "query", ".", "receiver", ".", "tag", ".", "Id", "(", ")", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "values", "[", "\"", "\"", "]", "=", "result", ".", "Error", ".", "Error", "(", ")", "\n", "values", "[", "\"", "\"", "]", "=", "query", ".", "actionTag", ".", "Id", "(", ")", "\n", "return", "values", "\n", "}", "\n", "if", "result", ".", "Action", ".", "Tag", "!=", "query", ".", "actionTag", ".", "String", "(", ")", "{", "values", "[", "\"", "\"", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "query", ".", "actionTag", ".", "String", "(", ")", ",", "result", ".", "Action", ".", "Tag", ")", "\n", "values", "[", "\"", "\"", "]", "=", "query", ".", "actionTag", ".", "Id", "(", ")", "\n", "return", "values", "\n", "}", "\n", "if", "result", ".", "Action", ".", "Receiver", "!=", "query", ".", "receiver", ".", "tag", ".", "String", "(", ")", "{", "values", "[", "\"", "\"", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "query", ".", "receiver", ".", "tag", ".", "String", "(", ")", ",", "result", ".", "Action", ".", "Receiver", ")", "\n", "values", "[", "\"", "\"", "]", "=", "query", ".", "actionTag", ".", "Id", "(", ")", "\n", "return", "values", "\n", "}", "\n", "if", "result", ".", "Message", "!=", "\"", "\"", "{", "values", "[", "\"", "\"", "]", "=", "result", ".", "Message", "\n", "}", "\n", "// We always want to have a string for stdout, but only show stderr,", "// code and error if they are there.", "if", "res", ",", "ok", ":=", "result", ".", "Output", "[", "\"", "\"", "]", ".", "(", "string", ")", ";", "ok", "{", "values", "[", "\"", "\"", "]", "=", "strings", ".", "Replace", "(", "res", ",", "\"", "\\r", "\\n", "\"", ",", "\"", "\\n", "\"", ",", "-", "1", ")", "\n", "if", "res", ",", "ok", ":=", "result", ".", "Output", "[", "\"", "\"", "]", ".", "(", "string", ")", ";", "ok", "&&", "res", "!=", "\"", "\"", "{", "values", "[", "\"", "\"", "]", "=", "res", "\n", "}", "\n", "}", "else", "{", "values", "[", "\"", "\"", "]", "=", "\"", "\"", "\n", "}", "\n", "if", "res", ",", "ok", ":=", "result", ".", "Output", "[", "\"", "\"", "]", ".", "(", "string", ")", ";", "ok", "&&", "res", "!=", "\"", "\"", "{", "values", "[", "\"", "\"", "]", "=", "strings", ".", "Replace", "(", "res", ",", "\"", "\\r", "\\n", "\"", ",", "\"", "\\n", "\"", ",", "-", "1", ")", "\n", "if", "res", ",", "ok", ":=", "result", ".", "Output", "[", "\"", "\"", "]", ".", "(", "string", ")", ";", "ok", "&&", "res", "!=", "\"", "\"", "{", "values", "[", "\"", "\"", "]", "=", "res", "\n", "}", "\n", "}", "\n", "if", "res", ",", "ok", ":=", "result", ".", "Output", "[", "\"", "\"", "]", ".", "(", "string", ")", ";", "ok", "{", "code", ",", "err", ":=", "strconv", ".", "Atoi", "(", "res", ")", "\n", "if", "err", "==", "nil", "&&", "code", "!=", "0", "{", "values", "[", "\"", "\"", "]", "=", "code", "\n", "}", "\n", "}", "\n", "return", "values", "\n", "}" ]
// ConvertActionResults takes the results from the api and creates a map // suitable for format conversion to YAML or JSON.
[ "ConvertActionResults", "takes", "the", "results", "from", "the", "api", "and", "creates", "a", "map", "suitable", "for", "format", "conversion", "to", "YAML", "or", "JSON", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/run.go#L194-L238
157,818
juju/juju
cmd/juju/commands/run.go
entities
func entities(actions []actionQuery) params.Entities { entities := params.Entities{ Entities: make([]params.Entity, len(actions)), } for i, action := range actions { entities.Entities[i].Tag = action.actionTag.String() } return entities }
go
func entities(actions []actionQuery) params.Entities { entities := params.Entities{ Entities: make([]params.Entity, len(actions)), } for i, action := range actions { entities.Entities[i].Tag = action.actionTag.String() } return entities }
[ "func", "entities", "(", "actions", "[", "]", "actionQuery", ")", "params", ".", "Entities", "{", "entities", ":=", "params", ".", "Entities", "{", "Entities", ":", "make", "(", "[", "]", "params", ".", "Entity", ",", "len", "(", "actions", ")", ")", ",", "}", "\n", "for", "i", ",", "action", ":=", "range", "actions", "{", "entities", ".", "Entities", "[", "i", "]", ".", "Tag", "=", "action", ".", "actionTag", ".", "String", "(", ")", "\n", "}", "\n", "return", "entities", "\n", "}" ]
// entities is a convenience constructor for params.Entities.
[ "entities", "is", "a", "convenience", "constructor", "for", "params", ".", "Entities", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/run.go#L431-L439
157,819
juju/juju
api/application/client.go
SetMetricCredentials
func (c *Client) SetMetricCredentials(application string, credentials []byte) error { creds := []params.ApplicationMetricCredential{ {application, credentials}, } p := params.ApplicationMetricCredentials{Creds: creds} results := new(params.ErrorResults) err := c.facade.FacadeCall("SetMetricCredentials", p, results) if err != nil { return errors.Trace(err) } return errors.Trace(results.OneError()) }
go
func (c *Client) SetMetricCredentials(application string, credentials []byte) error { creds := []params.ApplicationMetricCredential{ {application, credentials}, } p := params.ApplicationMetricCredentials{Creds: creds} results := new(params.ErrorResults) err := c.facade.FacadeCall("SetMetricCredentials", p, results) if err != nil { return errors.Trace(err) } return errors.Trace(results.OneError()) }
[ "func", "(", "c", "*", "Client", ")", "SetMetricCredentials", "(", "application", "string", ",", "credentials", "[", "]", "byte", ")", "error", "{", "creds", ":=", "[", "]", "params", ".", "ApplicationMetricCredential", "{", "{", "application", ",", "credentials", "}", ",", "}", "\n", "p", ":=", "params", ".", "ApplicationMetricCredentials", "{", "Creds", ":", "creds", "}", "\n", "results", ":=", "new", "(", "params", ".", "ErrorResults", ")", "\n", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "p", ",", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "results", ".", "OneError", "(", ")", ")", "\n", "}" ]
// SetMetricCredentials sets the metric credentials for the application specified.
[ "SetMetricCredentials", "sets", "the", "metric", "credentials", "for", "the", "application", "specified", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/application/client.go#L45-L56
157,820
juju/juju
api/application/client.go
ModelUUID
func (c *Client) ModelUUID() string { tag, ok := c.st.ModelTag() if !ok { logger.Warningf("controller-only API connection has no model tag") } return tag.Id() }
go
func (c *Client) ModelUUID() string { tag, ok := c.st.ModelTag() if !ok { logger.Warningf("controller-only API connection has no model tag") } return tag.Id() }
[ "func", "(", "c", "*", "Client", ")", "ModelUUID", "(", ")", "string", "{", "tag", ",", "ok", ":=", "c", ".", "st", ".", "ModelTag", "(", ")", "\n", "if", "!", "ok", "{", "logger", ".", "Warningf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "tag", ".", "Id", "(", ")", "\n", "}" ]
// ModelUUID returns the model UUID from the client connection.
[ "ModelUUID", "returns", "the", "model", "UUID", "from", "the", "client", "connection", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/application/client.go#L59-L65
157,821
juju/juju
api/application/client.go
Deploy
func (c *Client) Deploy(args DeployArgs) error { if len(args.AttachStorage) > 0 { if args.NumUnits != 1 { return errors.New("cannot attach existing storage when more than one unit is requested") } if c.BestAPIVersion() < 5 { return errors.New("this juju controller does not support AttachStorage") } } attachStorage := make([]string, len(args.AttachStorage)) for i, id := range args.AttachStorage { if !names.IsValidStorage(id) { return errors.NotValidf("storage ID %q", id) } attachStorage[i] = names.NewStorageTag(id).String() } deployArgs := params.ApplicationsDeploy{ Applications: []params.ApplicationDeploy{{ ApplicationName: args.ApplicationName, Series: args.Series, CharmURL: args.CharmID.URL.String(), Channel: string(args.CharmID.Channel), NumUnits: args.NumUnits, ConfigYAML: args.ConfigYAML, Config: args.Config, Constraints: args.Cons, Placement: args.Placement, Storage: args.Storage, Devices: args.Devices, AttachStorage: attachStorage, EndpointBindings: args.EndpointBindings, Resources: args.Resources, }}, } var results params.ErrorResults var err error err = c.facade.FacadeCall("Deploy", deployArgs, &results) if err != nil { return errors.Trace(err) } return errors.Trace(results.OneError()) }
go
func (c *Client) Deploy(args DeployArgs) error { if len(args.AttachStorage) > 0 { if args.NumUnits != 1 { return errors.New("cannot attach existing storage when more than one unit is requested") } if c.BestAPIVersion() < 5 { return errors.New("this juju controller does not support AttachStorage") } } attachStorage := make([]string, len(args.AttachStorage)) for i, id := range args.AttachStorage { if !names.IsValidStorage(id) { return errors.NotValidf("storage ID %q", id) } attachStorage[i] = names.NewStorageTag(id).String() } deployArgs := params.ApplicationsDeploy{ Applications: []params.ApplicationDeploy{{ ApplicationName: args.ApplicationName, Series: args.Series, CharmURL: args.CharmID.URL.String(), Channel: string(args.CharmID.Channel), NumUnits: args.NumUnits, ConfigYAML: args.ConfigYAML, Config: args.Config, Constraints: args.Cons, Placement: args.Placement, Storage: args.Storage, Devices: args.Devices, AttachStorage: attachStorage, EndpointBindings: args.EndpointBindings, Resources: args.Resources, }}, } var results params.ErrorResults var err error err = c.facade.FacadeCall("Deploy", deployArgs, &results) if err != nil { return errors.Trace(err) } return errors.Trace(results.OneError()) }
[ "func", "(", "c", "*", "Client", ")", "Deploy", "(", "args", "DeployArgs", ")", "error", "{", "if", "len", "(", "args", ".", "AttachStorage", ")", ">", "0", "{", "if", "args", ".", "NumUnits", "!=", "1", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "BestAPIVersion", "(", ")", "<", "5", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "attachStorage", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "args", ".", "AttachStorage", ")", ")", "\n", "for", "i", ",", "id", ":=", "range", "args", ".", "AttachStorage", "{", "if", "!", "names", ".", "IsValidStorage", "(", "id", ")", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "id", ")", "\n", "}", "\n", "attachStorage", "[", "i", "]", "=", "names", ".", "NewStorageTag", "(", "id", ")", ".", "String", "(", ")", "\n", "}", "\n", "deployArgs", ":=", "params", ".", "ApplicationsDeploy", "{", "Applications", ":", "[", "]", "params", ".", "ApplicationDeploy", "{", "{", "ApplicationName", ":", "args", ".", "ApplicationName", ",", "Series", ":", "args", ".", "Series", ",", "CharmURL", ":", "args", ".", "CharmID", ".", "URL", ".", "String", "(", ")", ",", "Channel", ":", "string", "(", "args", ".", "CharmID", ".", "Channel", ")", ",", "NumUnits", ":", "args", ".", "NumUnits", ",", "ConfigYAML", ":", "args", ".", "ConfigYAML", ",", "Config", ":", "args", ".", "Config", ",", "Constraints", ":", "args", ".", "Cons", ",", "Placement", ":", "args", ".", "Placement", ",", "Storage", ":", "args", ".", "Storage", ",", "Devices", ":", "args", ".", "Devices", ",", "AttachStorage", ":", "attachStorage", ",", "EndpointBindings", ":", "args", ".", "EndpointBindings", ",", "Resources", ":", "args", ".", "Resources", ",", "}", "}", ",", "}", "\n", "var", "results", "params", ".", "ErrorResults", "\n", "var", "err", "error", "\n", "err", "=", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "deployArgs", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "results", ".", "OneError", "(", ")", ")", "\n", "}" ]
// Deploy obtains the charm, either locally or from the charm store, and deploys // it. Placement directives, if provided, specify the machine on which the charm // is deployed.
[ "Deploy", "obtains", "the", "charm", "either", "locally", "or", "from", "the", "charm", "store", "and", "deploys", "it", ".", "Placement", "directives", "if", "provided", "specify", "the", "machine", "on", "which", "the", "charm", "is", "deployed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/application/client.go#L121-L162
157,822
juju/juju
api/application/client.go
GetConfig
func (c *Client) GetConfig(branchName string, appNames ...string) ([]map[string]interface{}, error) { v := c.BestAPIVersion() if v < 5 { settings, err := c.getConfigV4(branchName, appNames) return settings, errors.Trace(err) } callName := "CharmConfig" if v < 6 { callName = "GetConfig" } var callArg interface{} if v < 9 { arg := params.Entities{Entities: make([]params.Entity, len(appNames))} for i, appName := range appNames { arg.Entities[i] = params.Entity{Tag: names.NewApplicationTag(appName).String()} } callArg = arg } else { // Version 9 of the API introduces generational config. arg := params.ApplicationGetArgs{Args: make([]params.ApplicationGet, len(appNames))} for i, appName := range appNames { arg.Args[i] = params.ApplicationGet{ApplicationName: appName, BranchName: branchName} } callArg = arg } var results params.ApplicationGetConfigResults err := c.facade.FacadeCall(callName, callArg, &results) if err != nil { return nil, errors.Trace(err) } var settings []map[string]interface{} for i, result := range results.Results { if result.Error != nil { return nil, errors.Annotatef(err, "unable to get settings for %q", appNames[i]) } settings = append(settings, result.Config) } return settings, nil }
go
func (c *Client) GetConfig(branchName string, appNames ...string) ([]map[string]interface{}, error) { v := c.BestAPIVersion() if v < 5 { settings, err := c.getConfigV4(branchName, appNames) return settings, errors.Trace(err) } callName := "CharmConfig" if v < 6 { callName = "GetConfig" } var callArg interface{} if v < 9 { arg := params.Entities{Entities: make([]params.Entity, len(appNames))} for i, appName := range appNames { arg.Entities[i] = params.Entity{Tag: names.NewApplicationTag(appName).String()} } callArg = arg } else { // Version 9 of the API introduces generational config. arg := params.ApplicationGetArgs{Args: make([]params.ApplicationGet, len(appNames))} for i, appName := range appNames { arg.Args[i] = params.ApplicationGet{ApplicationName: appName, BranchName: branchName} } callArg = arg } var results params.ApplicationGetConfigResults err := c.facade.FacadeCall(callName, callArg, &results) if err != nil { return nil, errors.Trace(err) } var settings []map[string]interface{} for i, result := range results.Results { if result.Error != nil { return nil, errors.Annotatef(err, "unable to get settings for %q", appNames[i]) } settings = append(settings, result.Config) } return settings, nil }
[ "func", "(", "c", "*", "Client", ")", "GetConfig", "(", "branchName", "string", ",", "appNames", "...", "string", ")", "(", "[", "]", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "v", ":=", "c", ".", "BestAPIVersion", "(", ")", "\n\n", "if", "v", "<", "5", "{", "settings", ",", "err", ":=", "c", ".", "getConfigV4", "(", "branchName", ",", "appNames", ")", "\n", "return", "settings", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "callName", ":=", "\"", "\"", "\n", "if", "v", "<", "6", "{", "callName", "=", "\"", "\"", "\n", "}", "\n\n", "var", "callArg", "interface", "{", "}", "\n", "if", "v", "<", "9", "{", "arg", ":=", "params", ".", "Entities", "{", "Entities", ":", "make", "(", "[", "]", "params", ".", "Entity", ",", "len", "(", "appNames", ")", ")", "}", "\n", "for", "i", ",", "appName", ":=", "range", "appNames", "{", "arg", ".", "Entities", "[", "i", "]", "=", "params", ".", "Entity", "{", "Tag", ":", "names", ".", "NewApplicationTag", "(", "appName", ")", ".", "String", "(", ")", "}", "\n", "}", "\n", "callArg", "=", "arg", "\n", "}", "else", "{", "// Version 9 of the API introduces generational config.", "arg", ":=", "params", ".", "ApplicationGetArgs", "{", "Args", ":", "make", "(", "[", "]", "params", ".", "ApplicationGet", ",", "len", "(", "appNames", ")", ")", "}", "\n", "for", "i", ",", "appName", ":=", "range", "appNames", "{", "arg", ".", "Args", "[", "i", "]", "=", "params", ".", "ApplicationGet", "{", "ApplicationName", ":", "appName", ",", "BranchName", ":", "branchName", "}", "\n", "}", "\n", "callArg", "=", "arg", "\n", "}", "\n\n", "var", "results", "params", ".", "ApplicationGetConfigResults", "\n", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(", "callName", ",", "callArg", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "var", "settings", "[", "]", "map", "[", "string", "]", "interface", "{", "}", "\n", "for", "i", ",", "result", ":=", "range", "results", ".", "Results", "{", "if", "result", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "appNames", "[", "i", "]", ")", "\n", "}", "\n", "settings", "=", "append", "(", "settings", ",", "result", ".", "Config", ")", "\n", "}", "\n", "return", "settings", ",", "nil", "\n", "}" ]
// GetConfig returns the charm configuration settings for each of the // applications. If any of the applications are not found, an error is // returned.
[ "GetConfig", "returns", "the", "charm", "configuration", "settings", "for", "each", "of", "the", "applications", ".", "If", "any", "of", "the", "applications", "are", "not", "found", "an", "error", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/application/client.go#L185-L228
157,823
juju/juju
api/application/client.go
getConfigV4
func (c *Client) getConfigV4(branchName string, appNames []string) ([]map[string]interface{}, error) { var allSettings []map[string]interface{} for _, appName := range appNames { results, err := c.Get(branchName, appName) if err != nil { return nil, errors.Annotatef(err, "unable to get settings for %q", appName) } settings, err := describeV5(results.CharmConfig) if err != nil { return nil, errors.Annotatef(err, "unable to process settings for %q", appName) } allSettings = append(allSettings, settings) } return allSettings, nil }
go
func (c *Client) getConfigV4(branchName string, appNames []string) ([]map[string]interface{}, error) { var allSettings []map[string]interface{} for _, appName := range appNames { results, err := c.Get(branchName, appName) if err != nil { return nil, errors.Annotatef(err, "unable to get settings for %q", appName) } settings, err := describeV5(results.CharmConfig) if err != nil { return nil, errors.Annotatef(err, "unable to process settings for %q", appName) } allSettings = append(allSettings, settings) } return allSettings, nil }
[ "func", "(", "c", "*", "Client", ")", "getConfigV4", "(", "branchName", "string", ",", "appNames", "[", "]", "string", ")", "(", "[", "]", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "var", "allSettings", "[", "]", "map", "[", "string", "]", "interface", "{", "}", "\n", "for", "_", ",", "appName", ":=", "range", "appNames", "{", "results", ",", "err", ":=", "c", ".", "Get", "(", "branchName", ",", "appName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "appName", ")", "\n", "}", "\n", "settings", ",", "err", ":=", "describeV5", "(", "results", ".", "CharmConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "appName", ")", "\n", "}", "\n", "allSettings", "=", "append", "(", "allSettings", ",", "settings", ")", "\n", "}", "\n", "return", "allSettings", ",", "nil", "\n", "}" ]
// getConfigV4 retrieves application config for versions of the API < 5.
[ "getConfigV4", "retrieves", "application", "config", "for", "versions", "of", "the", "API", "<", "5", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/application/client.go#L231-L245
157,824
juju/juju
api/application/client.go
describeV5
func describeV5(config map[string]interface{}) (map[string]interface{}, error) { for _, value := range config { vMap, ok := value.(map[string]interface{}) if !ok { return nil, errors.Errorf("expected settings map got %v (%T) ", value, value) } if _, found := vMap["default"]; found { v, hasValue := vMap["value"] if hasValue { vMap["default"] = v vMap["source"] = "default" } else { delete(vMap, "default") vMap["source"] = "unset" } } else { // If default isn't set, then the source is user. // And we have no idea what the charm default is or whether // there is one. vMap["source"] = "user" } } return config, nil }
go
func describeV5(config map[string]interface{}) (map[string]interface{}, error) { for _, value := range config { vMap, ok := value.(map[string]interface{}) if !ok { return nil, errors.Errorf("expected settings map got %v (%T) ", value, value) } if _, found := vMap["default"]; found { v, hasValue := vMap["value"] if hasValue { vMap["default"] = v vMap["source"] = "default" } else { delete(vMap, "default") vMap["source"] = "unset" } } else { // If default isn't set, then the source is user. // And we have no idea what the charm default is or whether // there is one. vMap["source"] = "user" } } return config, nil }
[ "func", "describeV5", "(", "config", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "for", "_", ",", "value", ":=", "range", "config", "{", "vMap", ",", "ok", ":=", "value", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "value", ",", "value", ")", "\n", "}", "\n", "if", "_", ",", "found", ":=", "vMap", "[", "\"", "\"", "]", ";", "found", "{", "v", ",", "hasValue", ":=", "vMap", "[", "\"", "\"", "]", "\n", "if", "hasValue", "{", "vMap", "[", "\"", "\"", "]", "=", "v", "\n", "vMap", "[", "\"", "\"", "]", "=", "\"", "\"", "\n", "}", "else", "{", "delete", "(", "vMap", ",", "\"", "\"", ")", "\n", "vMap", "[", "\"", "\"", "]", "=", "\"", "\"", "\n", "}", "\n", "}", "else", "{", "// If default isn't set, then the source is user.", "// And we have no idea what the charm default is or whether", "// there is one.", "vMap", "[", "\"", "\"", "]", "=", "\"", "\"", "\n", "}", "\n", "}", "\n", "return", "config", ",", "nil", "\n", "}" ]
// describeV5 will take the results of describeV4 from the apiserver // and remove the "default" boolean, and add in "source". // Mutates and returns the config map.
[ "describeV5", "will", "take", "the", "results", "of", "describeV4", "from", "the", "apiserver", "and", "remove", "the", "default", "boolean", "and", "add", "in", "source", ".", "Mutates", "and", "returns", "the", "config", "map", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/application/client.go#L250-L273
157,825
juju/juju
api/application/client.go
SetCharm
func (c *Client) SetCharm(branchName string, cfg SetCharmConfig) error { var storageConstraints map[string]params.StorageConstraints if len(cfg.StorageConstraints) > 0 { storageConstraints = make(map[string]params.StorageConstraints) for name, cons := range cfg.StorageConstraints { size, count := cons.Size, cons.Count var sizePtr, countPtr *uint64 if size > 0 { sizePtr = &size } if count > 0 { countPtr = &count } storageConstraints[name] = params.StorageConstraints{ Pool: cons.Pool, Size: sizePtr, Count: countPtr, } } } args := params.ApplicationSetCharm{ ApplicationName: cfg.ApplicationName, CharmURL: cfg.CharmID.URL.String(), Channel: string(cfg.CharmID.Channel), ConfigSettings: cfg.ConfigSettings, ConfigSettingsYAML: cfg.ConfigSettingsYAML, Force: cfg.Force, ForceSeries: cfg.ForceSeries, ForceUnits: cfg.ForceUnits, ResourceIDs: cfg.ResourceIDs, StorageConstraints: storageConstraints, Generation: branchName, } return c.facade.FacadeCall("SetCharm", args, nil) }
go
func (c *Client) SetCharm(branchName string, cfg SetCharmConfig) error { var storageConstraints map[string]params.StorageConstraints if len(cfg.StorageConstraints) > 0 { storageConstraints = make(map[string]params.StorageConstraints) for name, cons := range cfg.StorageConstraints { size, count := cons.Size, cons.Count var sizePtr, countPtr *uint64 if size > 0 { sizePtr = &size } if count > 0 { countPtr = &count } storageConstraints[name] = params.StorageConstraints{ Pool: cons.Pool, Size: sizePtr, Count: countPtr, } } } args := params.ApplicationSetCharm{ ApplicationName: cfg.ApplicationName, CharmURL: cfg.CharmID.URL.String(), Channel: string(cfg.CharmID.Channel), ConfigSettings: cfg.ConfigSettings, ConfigSettingsYAML: cfg.ConfigSettingsYAML, Force: cfg.Force, ForceSeries: cfg.ForceSeries, ForceUnits: cfg.ForceUnits, ResourceIDs: cfg.ResourceIDs, StorageConstraints: storageConstraints, Generation: branchName, } return c.facade.FacadeCall("SetCharm", args, nil) }
[ "func", "(", "c", "*", "Client", ")", "SetCharm", "(", "branchName", "string", ",", "cfg", "SetCharmConfig", ")", "error", "{", "var", "storageConstraints", "map", "[", "string", "]", "params", ".", "StorageConstraints", "\n", "if", "len", "(", "cfg", ".", "StorageConstraints", ")", ">", "0", "{", "storageConstraints", "=", "make", "(", "map", "[", "string", "]", "params", ".", "StorageConstraints", ")", "\n", "for", "name", ",", "cons", ":=", "range", "cfg", ".", "StorageConstraints", "{", "size", ",", "count", ":=", "cons", ".", "Size", ",", "cons", ".", "Count", "\n", "var", "sizePtr", ",", "countPtr", "*", "uint64", "\n", "if", "size", ">", "0", "{", "sizePtr", "=", "&", "size", "\n", "}", "\n", "if", "count", ">", "0", "{", "countPtr", "=", "&", "count", "\n", "}", "\n", "storageConstraints", "[", "name", "]", "=", "params", ".", "StorageConstraints", "{", "Pool", ":", "cons", ".", "Pool", ",", "Size", ":", "sizePtr", ",", "Count", ":", "countPtr", ",", "}", "\n", "}", "\n", "}", "\n", "args", ":=", "params", ".", "ApplicationSetCharm", "{", "ApplicationName", ":", "cfg", ".", "ApplicationName", ",", "CharmURL", ":", "cfg", ".", "CharmID", ".", "URL", ".", "String", "(", ")", ",", "Channel", ":", "string", "(", "cfg", ".", "CharmID", ".", "Channel", ")", ",", "ConfigSettings", ":", "cfg", ".", "ConfigSettings", ",", "ConfigSettingsYAML", ":", "cfg", ".", "ConfigSettingsYAML", ",", "Force", ":", "cfg", ".", "Force", ",", "ForceSeries", ":", "cfg", ".", "ForceSeries", ",", "ForceUnits", ":", "cfg", ".", "ForceUnits", ",", "ResourceIDs", ":", "cfg", ".", "ResourceIDs", ",", "StorageConstraints", ":", "storageConstraints", ",", "Generation", ":", "branchName", ",", "}", "\n", "return", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "nil", ")", "\n", "}" ]
// SetCharm sets the charm for a given application.
[ "SetCharm", "sets", "the", "charm", "for", "a", "given", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/application/client.go#L321-L355
157,826
juju/juju
api/application/client.go
Update
func (c *Client) Update(args params.ApplicationUpdate) error { return c.facade.FacadeCall("Update", args, nil) }
go
func (c *Client) Update(args params.ApplicationUpdate) error { return c.facade.FacadeCall("Update", args, nil) }
[ "func", "(", "c", "*", "Client", ")", "Update", "(", "args", "params", ".", "ApplicationUpdate", ")", "error", "{", "return", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "nil", ")", "\n", "}" ]
// Update updates the application attributes, including charm URL, // minimum number of units, settings and constraints.
[ "Update", "updates", "the", "application", "attributes", "including", "charm", "URL", "minimum", "number", "of", "units", "settings", "and", "constraints", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/application/client.go#L359-L361
157,827
juju/juju
api/application/client.go
UpdateApplicationSeries
func (c *Client) UpdateApplicationSeries(appName, series string, force bool) error { args := params.UpdateSeriesArgs{ Args: []params.UpdateSeriesArg{{ Entity: params.Entity{Tag: names.NewApplicationTag(appName).String()}, Force: force, Series: series, }}, } results := new(params.ErrorResults) err := c.facade.FacadeCall("UpdateApplicationSeries", args, results) if err != nil { return errors.Trace(err) } return results.OneError() }
go
func (c *Client) UpdateApplicationSeries(appName, series string, force bool) error { args := params.UpdateSeriesArgs{ Args: []params.UpdateSeriesArg{{ Entity: params.Entity{Tag: names.NewApplicationTag(appName).String()}, Force: force, Series: series, }}, } results := new(params.ErrorResults) err := c.facade.FacadeCall("UpdateApplicationSeries", args, results) if err != nil { return errors.Trace(err) } return results.OneError() }
[ "func", "(", "c", "*", "Client", ")", "UpdateApplicationSeries", "(", "appName", ",", "series", "string", ",", "force", "bool", ")", "error", "{", "args", ":=", "params", ".", "UpdateSeriesArgs", "{", "Args", ":", "[", "]", "params", ".", "UpdateSeriesArg", "{", "{", "Entity", ":", "params", ".", "Entity", "{", "Tag", ":", "names", ".", "NewApplicationTag", "(", "appName", ")", ".", "String", "(", ")", "}", ",", "Force", ":", "force", ",", "Series", ":", "series", ",", "}", "}", ",", "}", "\n\n", "results", ":=", "new", "(", "params", ".", "ErrorResults", ")", "\n", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "results", ".", "OneError", "(", ")", "\n", "}" ]
// UpdateApplicationSeries updates the application series in the db.
[ "UpdateApplicationSeries", "updates", "the", "application", "series", "in", "the", "db", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/application/client.go#L364-L379
157,828
juju/juju
api/application/client.go
AddUnits
func (c *Client) AddUnits(args AddUnitsParams) ([]string, error) { if len(args.AttachStorage) > 0 { if args.NumUnits != 1 { return nil, errors.New("cannot attach existing storage when more than one unit is requested") } if c.BestAPIVersion() < 5 { return nil, errors.New("this juju controller does not support AttachStorage") } } attachStorage := make([]string, len(args.AttachStorage)) for i, id := range args.AttachStorage { if !names.IsValidStorage(id) { return nil, errors.NotValidf("storage ID %q", id) } attachStorage[i] = names.NewStorageTag(id).String() } results := new(params.AddApplicationUnitsResults) err := c.facade.FacadeCall("AddUnits", params.AddApplicationUnits{ ApplicationName: args.ApplicationName, NumUnits: args.NumUnits, Placement: args.Placement, Policy: args.Policy, AttachStorage: attachStorage, }, results) return results.Units, err }
go
func (c *Client) AddUnits(args AddUnitsParams) ([]string, error) { if len(args.AttachStorage) > 0 { if args.NumUnits != 1 { return nil, errors.New("cannot attach existing storage when more than one unit is requested") } if c.BestAPIVersion() < 5 { return nil, errors.New("this juju controller does not support AttachStorage") } } attachStorage := make([]string, len(args.AttachStorage)) for i, id := range args.AttachStorage { if !names.IsValidStorage(id) { return nil, errors.NotValidf("storage ID %q", id) } attachStorage[i] = names.NewStorageTag(id).String() } results := new(params.AddApplicationUnitsResults) err := c.facade.FacadeCall("AddUnits", params.AddApplicationUnits{ ApplicationName: args.ApplicationName, NumUnits: args.NumUnits, Placement: args.Placement, Policy: args.Policy, AttachStorage: attachStorage, }, results) return results.Units, err }
[ "func", "(", "c", "*", "Client", ")", "AddUnits", "(", "args", "AddUnitsParams", ")", "(", "[", "]", "string", ",", "error", ")", "{", "if", "len", "(", "args", ".", "AttachStorage", ")", ">", "0", "{", "if", "args", ".", "NumUnits", "!=", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "BestAPIVersion", "(", ")", "<", "5", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "attachStorage", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "args", ".", "AttachStorage", ")", ")", "\n", "for", "i", ",", "id", ":=", "range", "args", ".", "AttachStorage", "{", "if", "!", "names", ".", "IsValidStorage", "(", "id", ")", "{", "return", "nil", ",", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "id", ")", "\n", "}", "\n", "attachStorage", "[", "i", "]", "=", "names", ".", "NewStorageTag", "(", "id", ")", ".", "String", "(", ")", "\n", "}", "\n", "results", ":=", "new", "(", "params", ".", "AddApplicationUnitsResults", ")", "\n", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "params", ".", "AddApplicationUnits", "{", "ApplicationName", ":", "args", ".", "ApplicationName", ",", "NumUnits", ":", "args", ".", "NumUnits", ",", "Placement", ":", "args", ".", "Placement", ",", "Policy", ":", "args", ".", "Policy", ",", "AttachStorage", ":", "attachStorage", ",", "}", ",", "results", ")", "\n", "return", "results", ".", "Units", ",", "err", "\n", "}" ]
// AddUnits adds a given number of units to an application using the specified // placement directives to assign units to machines.
[ "AddUnits", "adds", "a", "given", "number", "of", "units", "to", "an", "application", "using", "the", "specified", "placement", "directives", "to", "assign", "units", "to", "machines", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/application/client.go#L406-L431
157,829
juju/juju
api/application/client.go
DestroyUnits
func (c *Client) DestroyUnits(in DestroyUnitsParams) ([]params.DestroyUnitResult, error) { argsV5 := params.DestroyUnitsParams{ Units: make([]params.DestroyUnitParams, 0, len(in.Units)), } allResults := make([]params.DestroyUnitResult, len(in.Units)) index := make([]int, 0, len(in.Units)) for i, name := range in.Units { if !names.IsValidUnit(name) { allResults[i].Error = &params.Error{ Message: errors.NotValidf("unit ID %q", name).Error(), } continue } index = append(index, i) argsV5.Units = append(argsV5.Units, params.DestroyUnitParams{ UnitTag: names.NewUnitTag(name).String(), DestroyStorage: in.DestroyStorage, Force: in.Force, MaxWait: in.MaxWait, }) } if len(argsV5.Units) == 0 { return allResults, nil } args := interface{}(argsV5) if c.BestAPIVersion() < 5 { if in.DestroyStorage { return nil, errors.New("this controller does not support --destroy-storage") } argsV4 := params.Entities{ Entities: make([]params.Entity, len(argsV5.Units)), } for i, arg := range argsV5.Units { argsV4.Entities[i].Tag = arg.UnitTag } args = argsV4 } var result params.DestroyUnitResults if err := c.facade.FacadeCall("DestroyUnit", args, &result); err != nil { return nil, errors.Trace(err) } if n := len(result.Results); n != len(argsV5.Units) { return nil, errors.Errorf("expected %d result(s), got %d", len(argsV5.Units), n) } for i, result := range result.Results { allResults[index[i]] = result } return allResults, nil }
go
func (c *Client) DestroyUnits(in DestroyUnitsParams) ([]params.DestroyUnitResult, error) { argsV5 := params.DestroyUnitsParams{ Units: make([]params.DestroyUnitParams, 0, len(in.Units)), } allResults := make([]params.DestroyUnitResult, len(in.Units)) index := make([]int, 0, len(in.Units)) for i, name := range in.Units { if !names.IsValidUnit(name) { allResults[i].Error = &params.Error{ Message: errors.NotValidf("unit ID %q", name).Error(), } continue } index = append(index, i) argsV5.Units = append(argsV5.Units, params.DestroyUnitParams{ UnitTag: names.NewUnitTag(name).String(), DestroyStorage: in.DestroyStorage, Force: in.Force, MaxWait: in.MaxWait, }) } if len(argsV5.Units) == 0 { return allResults, nil } args := interface{}(argsV5) if c.BestAPIVersion() < 5 { if in.DestroyStorage { return nil, errors.New("this controller does not support --destroy-storage") } argsV4 := params.Entities{ Entities: make([]params.Entity, len(argsV5.Units)), } for i, arg := range argsV5.Units { argsV4.Entities[i].Tag = arg.UnitTag } args = argsV4 } var result params.DestroyUnitResults if err := c.facade.FacadeCall("DestroyUnit", args, &result); err != nil { return nil, errors.Trace(err) } if n := len(result.Results); n != len(argsV5.Units) { return nil, errors.Errorf("expected %d result(s), got %d", len(argsV5.Units), n) } for i, result := range result.Results { allResults[index[i]] = result } return allResults, nil }
[ "func", "(", "c", "*", "Client", ")", "DestroyUnits", "(", "in", "DestroyUnitsParams", ")", "(", "[", "]", "params", ".", "DestroyUnitResult", ",", "error", ")", "{", "argsV5", ":=", "params", ".", "DestroyUnitsParams", "{", "Units", ":", "make", "(", "[", "]", "params", ".", "DestroyUnitParams", ",", "0", ",", "len", "(", "in", ".", "Units", ")", ")", ",", "}", "\n", "allResults", ":=", "make", "(", "[", "]", "params", ".", "DestroyUnitResult", ",", "len", "(", "in", ".", "Units", ")", ")", "\n", "index", ":=", "make", "(", "[", "]", "int", ",", "0", ",", "len", "(", "in", ".", "Units", ")", ")", "\n", "for", "i", ",", "name", ":=", "range", "in", ".", "Units", "{", "if", "!", "names", ".", "IsValidUnit", "(", "name", ")", "{", "allResults", "[", "i", "]", ".", "Error", "=", "&", "params", ".", "Error", "{", "Message", ":", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "name", ")", ".", "Error", "(", ")", ",", "}", "\n", "continue", "\n", "}", "\n", "index", "=", "append", "(", "index", ",", "i", ")", "\n", "argsV5", ".", "Units", "=", "append", "(", "argsV5", ".", "Units", ",", "params", ".", "DestroyUnitParams", "{", "UnitTag", ":", "names", ".", "NewUnitTag", "(", "name", ")", ".", "String", "(", ")", ",", "DestroyStorage", ":", "in", ".", "DestroyStorage", ",", "Force", ":", "in", ".", "Force", ",", "MaxWait", ":", "in", ".", "MaxWait", ",", "}", ")", "\n", "}", "\n", "if", "len", "(", "argsV5", ".", "Units", ")", "==", "0", "{", "return", "allResults", ",", "nil", "\n", "}", "\n\n", "args", ":=", "interface", "{", "}", "(", "argsV5", ")", "\n", "if", "c", ".", "BestAPIVersion", "(", ")", "<", "5", "{", "if", "in", ".", "DestroyStorage", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "argsV4", ":=", "params", ".", "Entities", "{", "Entities", ":", "make", "(", "[", "]", "params", ".", "Entity", ",", "len", "(", "argsV5", ".", "Units", ")", ")", ",", "}", "\n", "for", "i", ",", "arg", ":=", "range", "argsV5", ".", "Units", "{", "argsV4", ".", "Entities", "[", "i", "]", ".", "Tag", "=", "arg", ".", "UnitTag", "\n", "}", "\n", "args", "=", "argsV4", "\n", "}", "\n\n", "var", "result", "params", ".", "DestroyUnitResults", "\n", "if", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "result", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "n", ":=", "len", "(", "result", ".", "Results", ")", ";", "n", "!=", "len", "(", "argsV5", ".", "Units", ")", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "argsV5", ".", "Units", ")", ",", "n", ")", "\n", "}", "\n", "for", "i", ",", "result", ":=", "range", "result", ".", "Results", "{", "allResults", "[", "index", "[", "i", "]", "]", "=", "result", "\n", "}", "\n", "return", "allResults", ",", "nil", "\n", "}" ]
// DestroyUnits decreases the number of units dedicated to one or more // applications.
[ "DestroyUnits", "decreases", "the", "number", "of", "units", "dedicated", "to", "one", "or", "more", "applications", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/application/client.go#L467-L517
157,830
vitessio/vitess
go/vt/vtgate/planbuilder/ordered_aggregate.go
SetGroupBy
func (oa *orderedAggregate) SetGroupBy(groupBy sqlparser.GroupBy) error { colnum := -1 for _, expr := range groupBy { switch node := expr.(type) { case *sqlparser.ColName: c := node.Metadata.(*column) if c.Origin() == oa { return fmt.Errorf("group by expression cannot reference an aggregate function: %v", sqlparser.String(node)) } for i, rc := range oa.resultColumns { if rc.column == c { colnum = i break } } if colnum == -1 { return errors.New("unsupported: in scatter query: group by column must reference column in SELECT list") } case *sqlparser.SQLVal: num, err := ResultFromNumber(oa.resultColumns, node) if err != nil { return err } colnum = num default: return errors.New("unsupported: in scatter query: only simple references allowed") } oa.eaggr.Keys = append(oa.eaggr.Keys, colnum) } _ = oa.input.SetGroupBy(groupBy) return nil }
go
func (oa *orderedAggregate) SetGroupBy(groupBy sqlparser.GroupBy) error { colnum := -1 for _, expr := range groupBy { switch node := expr.(type) { case *sqlparser.ColName: c := node.Metadata.(*column) if c.Origin() == oa { return fmt.Errorf("group by expression cannot reference an aggregate function: %v", sqlparser.String(node)) } for i, rc := range oa.resultColumns { if rc.column == c { colnum = i break } } if colnum == -1 { return errors.New("unsupported: in scatter query: group by column must reference column in SELECT list") } case *sqlparser.SQLVal: num, err := ResultFromNumber(oa.resultColumns, node) if err != nil { return err } colnum = num default: return errors.New("unsupported: in scatter query: only simple references allowed") } oa.eaggr.Keys = append(oa.eaggr.Keys, colnum) } _ = oa.input.SetGroupBy(groupBy) return nil }
[ "func", "(", "oa", "*", "orderedAggregate", ")", "SetGroupBy", "(", "groupBy", "sqlparser", ".", "GroupBy", ")", "error", "{", "colnum", ":=", "-", "1", "\n", "for", "_", ",", "expr", ":=", "range", "groupBy", "{", "switch", "node", ":=", "expr", ".", "(", "type", ")", "{", "case", "*", "sqlparser", ".", "ColName", ":", "c", ":=", "node", ".", "Metadata", ".", "(", "*", "column", ")", "\n", "if", "c", ".", "Origin", "(", ")", "==", "oa", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "sqlparser", ".", "String", "(", "node", ")", ")", "\n", "}", "\n", "for", "i", ",", "rc", ":=", "range", "oa", ".", "resultColumns", "{", "if", "rc", ".", "column", "==", "c", "{", "colnum", "=", "i", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "colnum", "==", "-", "1", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "case", "*", "sqlparser", ".", "SQLVal", ":", "num", ",", "err", ":=", "ResultFromNumber", "(", "oa", ".", "resultColumns", ",", "node", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "colnum", "=", "num", "\n", "default", ":", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "oa", ".", "eaggr", ".", "Keys", "=", "append", "(", "oa", ".", "eaggr", ".", "Keys", ",", "colnum", ")", "\n", "}", "\n\n", "_", "=", "oa", ".", "input", ".", "SetGroupBy", "(", "groupBy", ")", "\n", "return", "nil", "\n", "}" ]
// SetGroupBy satisfies the builder interface.
[ "SetGroupBy", "satisfies", "the", "builder", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/ordered_aggregate.go#L329-L361
157,831
vitessio/vitess
go/vt/vtgate/planbuilder/ordered_aggregate.go
SetUpperLimit
func (oa *orderedAggregate) SetUpperLimit(count *sqlparser.SQLVal) { oa.input.SetUpperLimit(count) }
go
func (oa *orderedAggregate) SetUpperLimit(count *sqlparser.SQLVal) { oa.input.SetUpperLimit(count) }
[ "func", "(", "oa", "*", "orderedAggregate", ")", "SetUpperLimit", "(", "count", "*", "sqlparser", ".", "SQLVal", ")", "{", "oa", ".", "input", ".", "SetUpperLimit", "(", "count", ")", "\n", "}" ]
// SetUpperLimit satisfies the builder interface.
[ "SetUpperLimit", "satisfies", "the", "builder", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/ordered_aggregate.go#L455-L457
157,832
vitessio/vitess
go/vt/vtgate/planbuilder/ordered_aggregate.go
Wireup
func (oa *orderedAggregate) Wireup(bldr builder, jt *jointab) error { for i, colnum := range oa.eaggr.Keys { if sqltypes.IsText(oa.resultColumns[colnum].column.typ) { // len(oa.resultColumns) does not change. No harm using the value multiple times. oa.eaggr.TruncateColumnCount = len(oa.resultColumns) oa.eaggr.Keys[i] = oa.input.SupplyWeightString(colnum) } } return oa.input.Wireup(bldr, jt) }
go
func (oa *orderedAggregate) Wireup(bldr builder, jt *jointab) error { for i, colnum := range oa.eaggr.Keys { if sqltypes.IsText(oa.resultColumns[colnum].column.typ) { // len(oa.resultColumns) does not change. No harm using the value multiple times. oa.eaggr.TruncateColumnCount = len(oa.resultColumns) oa.eaggr.Keys[i] = oa.input.SupplyWeightString(colnum) } } return oa.input.Wireup(bldr, jt) }
[ "func", "(", "oa", "*", "orderedAggregate", ")", "Wireup", "(", "bldr", "builder", ",", "jt", "*", "jointab", ")", "error", "{", "for", "i", ",", "colnum", ":=", "range", "oa", ".", "eaggr", ".", "Keys", "{", "if", "sqltypes", ".", "IsText", "(", "oa", ".", "resultColumns", "[", "colnum", "]", ".", "column", ".", "typ", ")", "{", "// len(oa.resultColumns) does not change. No harm using the value multiple times.", "oa", ".", "eaggr", ".", "TruncateColumnCount", "=", "len", "(", "oa", ".", "resultColumns", ")", "\n", "oa", ".", "eaggr", ".", "Keys", "[", "i", "]", "=", "oa", ".", "input", ".", "SupplyWeightString", "(", "colnum", ")", "\n", "}", "\n", "}", "\n", "return", "oa", ".", "input", ".", "Wireup", "(", "bldr", ",", "jt", ")", "\n", "}" ]
// Wireup satisfies the builder interface. // If text columns are detected in the keys, then the function modifies // the primitive to pull a corresponding weight_string from mysql and // compare those instead. This is because we currently don't have the // ability to mimic mysql's collation behavior.
[ "Wireup", "satisfies", "the", "builder", "interface", ".", "If", "text", "columns", "are", "detected", "in", "the", "keys", "then", "the", "function", "modifies", "the", "primitive", "to", "pull", "a", "corresponding", "weight_string", "from", "mysql", "and", "compare", "those", "instead", ".", "This", "is", "because", "we", "currently", "don", "t", "have", "the", "ability", "to", "mimic", "mysql", "s", "collation", "behavior", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/ordered_aggregate.go#L469-L478
157,833
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_query.go
ExecuteFetchAsDba
func (agent *ActionAgent) ExecuteFetchAsDba(ctx context.Context, query []byte, dbName string, maxrows int, disableBinlogs bool, reloadSchema bool) (*querypb.QueryResult, error) { // get a connection conn, err := agent.MysqlDaemon.GetDbaConnection() if err != nil { return nil, err } defer conn.Close() // disable binlogs if necessary if disableBinlogs { _, err := conn.ExecuteFetch("SET sql_log_bin = OFF", 0, false) if err != nil { return nil, err } } if dbName != "" { // This execute might fail if db does not exist. // Error is ignored because given query might create this database. conn.ExecuteFetch("USE "+dbName, 1, false) } // run the query result, err := conn.ExecuteFetch(string(query), maxrows, true /*wantFields*/) // re-enable binlogs if necessary if disableBinlogs && !conn.IsClosed() { _, err := conn.ExecuteFetch("SET sql_log_bin = ON", 0, false) if err != nil { // if we can't reset the sql_log_bin flag, // let's just close the connection. conn.Close() } } if err == nil && reloadSchema { reloadErr := agent.QueryServiceControl.ReloadSchema(ctx) if reloadErr != nil { log.Errorf("failed to reload the schema %v", reloadErr) } } return sqltypes.ResultToProto3(result), err }
go
func (agent *ActionAgent) ExecuteFetchAsDba(ctx context.Context, query []byte, dbName string, maxrows int, disableBinlogs bool, reloadSchema bool) (*querypb.QueryResult, error) { // get a connection conn, err := agent.MysqlDaemon.GetDbaConnection() if err != nil { return nil, err } defer conn.Close() // disable binlogs if necessary if disableBinlogs { _, err := conn.ExecuteFetch("SET sql_log_bin = OFF", 0, false) if err != nil { return nil, err } } if dbName != "" { // This execute might fail if db does not exist. // Error is ignored because given query might create this database. conn.ExecuteFetch("USE "+dbName, 1, false) } // run the query result, err := conn.ExecuteFetch(string(query), maxrows, true /*wantFields*/) // re-enable binlogs if necessary if disableBinlogs && !conn.IsClosed() { _, err := conn.ExecuteFetch("SET sql_log_bin = ON", 0, false) if err != nil { // if we can't reset the sql_log_bin flag, // let's just close the connection. conn.Close() } } if err == nil && reloadSchema { reloadErr := agent.QueryServiceControl.ReloadSchema(ctx) if reloadErr != nil { log.Errorf("failed to reload the schema %v", reloadErr) } } return sqltypes.ResultToProto3(result), err }
[ "func", "(", "agent", "*", "ActionAgent", ")", "ExecuteFetchAsDba", "(", "ctx", "context", ".", "Context", ",", "query", "[", "]", "byte", ",", "dbName", "string", ",", "maxrows", "int", ",", "disableBinlogs", "bool", ",", "reloadSchema", "bool", ")", "(", "*", "querypb", ".", "QueryResult", ",", "error", ")", "{", "// get a connection", "conn", ",", "err", ":=", "agent", ".", "MysqlDaemon", ".", "GetDbaConnection", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "conn", ".", "Close", "(", ")", "\n\n", "// disable binlogs if necessary", "if", "disableBinlogs", "{", "_", ",", "err", ":=", "conn", ".", "ExecuteFetch", "(", "\"", "\"", ",", "0", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "if", "dbName", "!=", "\"", "\"", "{", "// This execute might fail if db does not exist.", "// Error is ignored because given query might create this database.", "conn", ".", "ExecuteFetch", "(", "\"", "\"", "+", "dbName", ",", "1", ",", "false", ")", "\n", "}", "\n\n", "// run the query", "result", ",", "err", ":=", "conn", ".", "ExecuteFetch", "(", "string", "(", "query", ")", ",", "maxrows", ",", "true", "/*wantFields*/", ")", "\n\n", "// re-enable binlogs if necessary", "if", "disableBinlogs", "&&", "!", "conn", ".", "IsClosed", "(", ")", "{", "_", ",", "err", ":=", "conn", ".", "ExecuteFetch", "(", "\"", "\"", ",", "0", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "// if we can't reset the sql_log_bin flag,", "// let's just close the connection.", "conn", ".", "Close", "(", ")", "\n", "}", "\n", "}", "\n\n", "if", "err", "==", "nil", "&&", "reloadSchema", "{", "reloadErr", ":=", "agent", ".", "QueryServiceControl", ".", "ReloadSchema", "(", "ctx", ")", "\n", "if", "reloadErr", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "reloadErr", ")", "\n", "}", "\n", "}", "\n", "return", "sqltypes", ".", "ResultToProto3", "(", "result", ")", ",", "err", "\n", "}" ]
// ExecuteFetchAsDba will execute the given query, possibly disabling binlogs and reload schema.
[ "ExecuteFetchAsDba", "will", "execute", "the", "given", "query", "possibly", "disabling", "binlogs", "and", "reload", "schema", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_query.go#L28-L70
157,834
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_query.go
ExecuteFetchAsAllPrivs
func (agent *ActionAgent) ExecuteFetchAsAllPrivs(ctx context.Context, query []byte, dbName string, maxrows int, reloadSchema bool) (*querypb.QueryResult, error) { // get a connection conn, err := agent.MysqlDaemon.GetAllPrivsConnection() if err != nil { return nil, err } defer conn.Close() if dbName != "" { // This execute might fail if db does not exist. // Error is ignored because given query might create this database. conn.ExecuteFetch("USE "+dbName, 1, false) } // run the query result, err := conn.ExecuteFetch(string(query), maxrows, true /*wantFields*/) if err == nil && reloadSchema { reloadErr := agent.QueryServiceControl.ReloadSchema(ctx) if reloadErr != nil { log.Errorf("failed to reload the schema %v", reloadErr) } } return sqltypes.ResultToProto3(result), err }
go
func (agent *ActionAgent) ExecuteFetchAsAllPrivs(ctx context.Context, query []byte, dbName string, maxrows int, reloadSchema bool) (*querypb.QueryResult, error) { // get a connection conn, err := agent.MysqlDaemon.GetAllPrivsConnection() if err != nil { return nil, err } defer conn.Close() if dbName != "" { // This execute might fail if db does not exist. // Error is ignored because given query might create this database. conn.ExecuteFetch("USE "+dbName, 1, false) } // run the query result, err := conn.ExecuteFetch(string(query), maxrows, true /*wantFields*/) if err == nil && reloadSchema { reloadErr := agent.QueryServiceControl.ReloadSchema(ctx) if reloadErr != nil { log.Errorf("failed to reload the schema %v", reloadErr) } } return sqltypes.ResultToProto3(result), err }
[ "func", "(", "agent", "*", "ActionAgent", ")", "ExecuteFetchAsAllPrivs", "(", "ctx", "context", ".", "Context", ",", "query", "[", "]", "byte", ",", "dbName", "string", ",", "maxrows", "int", ",", "reloadSchema", "bool", ")", "(", "*", "querypb", ".", "QueryResult", ",", "error", ")", "{", "// get a connection", "conn", ",", "err", ":=", "agent", ".", "MysqlDaemon", ".", "GetAllPrivsConnection", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "conn", ".", "Close", "(", ")", "\n\n", "if", "dbName", "!=", "\"", "\"", "{", "// This execute might fail if db does not exist.", "// Error is ignored because given query might create this database.", "conn", ".", "ExecuteFetch", "(", "\"", "\"", "+", "dbName", ",", "1", ",", "false", ")", "\n", "}", "\n\n", "// run the query", "result", ",", "err", ":=", "conn", ".", "ExecuteFetch", "(", "string", "(", "query", ")", ",", "maxrows", ",", "true", "/*wantFields*/", ")", "\n\n", "if", "err", "==", "nil", "&&", "reloadSchema", "{", "reloadErr", ":=", "agent", ".", "QueryServiceControl", ".", "ReloadSchema", "(", "ctx", ")", "\n", "if", "reloadErr", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "reloadErr", ")", "\n", "}", "\n", "}", "\n", "return", "sqltypes", ".", "ResultToProto3", "(", "result", ")", ",", "err", "\n", "}" ]
// ExecuteFetchAsAllPrivs will execute the given query, possibly reloading schema.
[ "ExecuteFetchAsAllPrivs", "will", "execute", "the", "given", "query", "possibly", "reloading", "schema", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_query.go#L73-L97
157,835
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_query.go
ExecuteFetchAsApp
func (agent *ActionAgent) ExecuteFetchAsApp(ctx context.Context, query []byte, maxrows int) (*querypb.QueryResult, error) { // get a connection conn, err := agent.MysqlDaemon.GetAppConnection(ctx) if err != nil { return nil, err } defer conn.Recycle() result, err := conn.ExecuteFetch(string(query), maxrows, true /*wantFields*/) return sqltypes.ResultToProto3(result), err }
go
func (agent *ActionAgent) ExecuteFetchAsApp(ctx context.Context, query []byte, maxrows int) (*querypb.QueryResult, error) { // get a connection conn, err := agent.MysqlDaemon.GetAppConnection(ctx) if err != nil { return nil, err } defer conn.Recycle() result, err := conn.ExecuteFetch(string(query), maxrows, true /*wantFields*/) return sqltypes.ResultToProto3(result), err }
[ "func", "(", "agent", "*", "ActionAgent", ")", "ExecuteFetchAsApp", "(", "ctx", "context", ".", "Context", ",", "query", "[", "]", "byte", ",", "maxrows", "int", ")", "(", "*", "querypb", ".", "QueryResult", ",", "error", ")", "{", "// get a connection", "conn", ",", "err", ":=", "agent", ".", "MysqlDaemon", ".", "GetAppConnection", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "conn", ".", "Recycle", "(", ")", "\n", "result", ",", "err", ":=", "conn", ".", "ExecuteFetch", "(", "string", "(", "query", ")", ",", "maxrows", ",", "true", "/*wantFields*/", ")", "\n", "return", "sqltypes", ".", "ResultToProto3", "(", "result", ")", ",", "err", "\n", "}" ]
// ExecuteFetchAsApp will execute the given query.
[ "ExecuteFetchAsApp", "will", "execute", "the", "given", "query", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_query.go#L100-L109
157,836
vitessio/vitess
go/vt/worker/key_resolver.go
newV2Resolver
func newV2Resolver(keyspaceInfo *topo.KeyspaceInfo, td *tabletmanagerdatapb.TableDefinition) (keyspaceIDResolver, error) { if keyspaceInfo.ShardingColumnName == "" { return nil, vterrors.New(vtrpc.Code_FAILED_PRECONDITION, "ShardingColumnName needs to be set for a v2 sharding key") } if keyspaceInfo.ShardingColumnType == topodatapb.KeyspaceIdType_UNSET { return nil, vterrors.New(vtrpc.Code_FAILED_PRECONDITION, "ShardingColumnType needs to be set for a v2 sharding key") } if td.Type != tmutils.TableBaseTable { return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "a keyspaceID resolver can only be created for a base table, got %v", td.Type) } // Find the sharding key column index. columnIndex, ok := tmutils.TableDefinitionGetColumn(td, keyspaceInfo.ShardingColumnName) if !ok { return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "table %v doesn't have a column named '%v'", td.Name, keyspaceInfo.ShardingColumnName) } return &v2Resolver{keyspaceInfo, columnIndex}, nil }
go
func newV2Resolver(keyspaceInfo *topo.KeyspaceInfo, td *tabletmanagerdatapb.TableDefinition) (keyspaceIDResolver, error) { if keyspaceInfo.ShardingColumnName == "" { return nil, vterrors.New(vtrpc.Code_FAILED_PRECONDITION, "ShardingColumnName needs to be set for a v2 sharding key") } if keyspaceInfo.ShardingColumnType == topodatapb.KeyspaceIdType_UNSET { return nil, vterrors.New(vtrpc.Code_FAILED_PRECONDITION, "ShardingColumnType needs to be set for a v2 sharding key") } if td.Type != tmutils.TableBaseTable { return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "a keyspaceID resolver can only be created for a base table, got %v", td.Type) } // Find the sharding key column index. columnIndex, ok := tmutils.TableDefinitionGetColumn(td, keyspaceInfo.ShardingColumnName) if !ok { return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "table %v doesn't have a column named '%v'", td.Name, keyspaceInfo.ShardingColumnName) } return &v2Resolver{keyspaceInfo, columnIndex}, nil }
[ "func", "newV2Resolver", "(", "keyspaceInfo", "*", "topo", ".", "KeyspaceInfo", ",", "td", "*", "tabletmanagerdatapb", ".", "TableDefinition", ")", "(", "keyspaceIDResolver", ",", "error", ")", "{", "if", "keyspaceInfo", ".", "ShardingColumnName", "==", "\"", "\"", "{", "return", "nil", ",", "vterrors", ".", "New", "(", "vtrpc", ".", "Code_FAILED_PRECONDITION", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "keyspaceInfo", ".", "ShardingColumnType", "==", "topodatapb", ".", "KeyspaceIdType_UNSET", "{", "return", "nil", ",", "vterrors", ".", "New", "(", "vtrpc", ".", "Code_FAILED_PRECONDITION", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "td", ".", "Type", "!=", "tmutils", ".", "TableBaseTable", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_FAILED_PRECONDITION", ",", "\"", "\"", ",", "td", ".", "Type", ")", "\n", "}", "\n\n", "// Find the sharding key column index.", "columnIndex", ",", "ok", ":=", "tmutils", ".", "TableDefinitionGetColumn", "(", "td", ",", "keyspaceInfo", ".", "ShardingColumnName", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_FAILED_PRECONDITION", ",", "\"", "\"", ",", "td", ".", "Name", ",", "keyspaceInfo", ".", "ShardingColumnName", ")", "\n", "}", "\n\n", "return", "&", "v2Resolver", "{", "keyspaceInfo", ",", "columnIndex", "}", ",", "nil", "\n", "}" ]
// newV2Resolver returns a keyspaceIDResolver for a v2 table. // V2 keyspaces have a preset sharding column name and type.
[ "newV2Resolver", "returns", "a", "keyspaceIDResolver", "for", "a", "v2", "table", ".", "V2", "keyspaces", "have", "a", "preset", "sharding", "column", "name", "and", "type", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/key_resolver.go#L54-L72
157,837
vitessio/vitess
go/vt/worker/key_resolver.go
newV3ResolverFromTableDefinition
func newV3ResolverFromTableDefinition(keyspaceSchema *vindexes.KeyspaceSchema, td *tabletmanagerdatapb.TableDefinition) (keyspaceIDResolver, error) { if td.Type != tmutils.TableBaseTable { return nil, vterrors.Errorf(vtrpc.Code_INVALID_ARGUMENT, "a keyspaceID resolver can only be created for a base table, got %v", td.Type) } tableSchema, ok := keyspaceSchema.Tables[td.Name] if !ok { return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "no vschema definition for table %v", td.Name) } // use the lowest cost unique vindex as the sharding key colVindex, err := vindexes.FindVindexForSharding(td.Name, tableSchema.ColumnVindexes) if err != nil { return nil, err } // Find the sharding key column index. columnIndex, ok := tmutils.TableDefinitionGetColumn(td, colVindex.Columns[0].String()) if !ok { return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "table %v has a Vindex on unknown column %v", td.Name, colVindex.Columns[0]) } return &v3Resolver{ shardingColumnIndex: columnIndex, vindex: colVindex.Vindex, }, nil }
go
func newV3ResolverFromTableDefinition(keyspaceSchema *vindexes.KeyspaceSchema, td *tabletmanagerdatapb.TableDefinition) (keyspaceIDResolver, error) { if td.Type != tmutils.TableBaseTable { return nil, vterrors.Errorf(vtrpc.Code_INVALID_ARGUMENT, "a keyspaceID resolver can only be created for a base table, got %v", td.Type) } tableSchema, ok := keyspaceSchema.Tables[td.Name] if !ok { return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "no vschema definition for table %v", td.Name) } // use the lowest cost unique vindex as the sharding key colVindex, err := vindexes.FindVindexForSharding(td.Name, tableSchema.ColumnVindexes) if err != nil { return nil, err } // Find the sharding key column index. columnIndex, ok := tmutils.TableDefinitionGetColumn(td, colVindex.Columns[0].String()) if !ok { return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "table %v has a Vindex on unknown column %v", td.Name, colVindex.Columns[0]) } return &v3Resolver{ shardingColumnIndex: columnIndex, vindex: colVindex.Vindex, }, nil }
[ "func", "newV3ResolverFromTableDefinition", "(", "keyspaceSchema", "*", "vindexes", ".", "KeyspaceSchema", ",", "td", "*", "tabletmanagerdatapb", ".", "TableDefinition", ")", "(", "keyspaceIDResolver", ",", "error", ")", "{", "if", "td", ".", "Type", "!=", "tmutils", ".", "TableBaseTable", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "td", ".", "Type", ")", "\n", "}", "\n", "tableSchema", ",", "ok", ":=", "keyspaceSchema", ".", "Tables", "[", "td", ".", "Name", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_FAILED_PRECONDITION", ",", "\"", "\"", ",", "td", ".", "Name", ")", "\n", "}", "\n", "// use the lowest cost unique vindex as the sharding key", "colVindex", ",", "err", ":=", "vindexes", ".", "FindVindexForSharding", "(", "td", ".", "Name", ",", "tableSchema", ".", "ColumnVindexes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Find the sharding key column index.", "columnIndex", ",", "ok", ":=", "tmutils", ".", "TableDefinitionGetColumn", "(", "td", ",", "colVindex", ".", "Columns", "[", "0", "]", ".", "String", "(", ")", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_FAILED_PRECONDITION", ",", "\"", "\"", ",", "td", ".", "Name", ",", "colVindex", ".", "Columns", "[", "0", "]", ")", "\n", "}", "\n\n", "return", "&", "v3Resolver", "{", "shardingColumnIndex", ":", "columnIndex", ",", "vindex", ":", "colVindex", ".", "Vindex", ",", "}", ",", "nil", "\n", "}" ]
// newV3ResolverFromTableDefinition returns a keyspaceIDResolver for a v3 table.
[ "newV3ResolverFromTableDefinition", "returns", "a", "keyspaceIDResolver", "for", "a", "v3", "table", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/key_resolver.go#L100-L124
157,838
vitessio/vitess
go/vt/worker/key_resolver.go
newV3ResolverFromColumnList
func newV3ResolverFromColumnList(keyspaceSchema *vindexes.KeyspaceSchema, name string, columns []string) (keyspaceIDResolver, error) { tableSchema, ok := keyspaceSchema.Tables[name] if !ok { return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "no vschema definition for table %v", name) } // use the lowest cost unique vindex as the sharding key colVindex, err := vindexes.FindVindexForSharding(name, tableSchema.ColumnVindexes) if err != nil { return nil, err } // Find the sharding key column index. columnIndex := -1 for i, n := range columns { if colVindex.Columns[0].EqualString(n) { columnIndex = i break } } if columnIndex == -1 { return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "table %v has a Vindex on unknown column %v", name, colVindex.Columns[0]) } return &v3Resolver{ shardingColumnIndex: columnIndex, vindex: colVindex.Vindex, }, nil }
go
func newV3ResolverFromColumnList(keyspaceSchema *vindexes.KeyspaceSchema, name string, columns []string) (keyspaceIDResolver, error) { tableSchema, ok := keyspaceSchema.Tables[name] if !ok { return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "no vschema definition for table %v", name) } // use the lowest cost unique vindex as the sharding key colVindex, err := vindexes.FindVindexForSharding(name, tableSchema.ColumnVindexes) if err != nil { return nil, err } // Find the sharding key column index. columnIndex := -1 for i, n := range columns { if colVindex.Columns[0].EqualString(n) { columnIndex = i break } } if columnIndex == -1 { return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "table %v has a Vindex on unknown column %v", name, colVindex.Columns[0]) } return &v3Resolver{ shardingColumnIndex: columnIndex, vindex: colVindex.Vindex, }, nil }
[ "func", "newV3ResolverFromColumnList", "(", "keyspaceSchema", "*", "vindexes", ".", "KeyspaceSchema", ",", "name", "string", ",", "columns", "[", "]", "string", ")", "(", "keyspaceIDResolver", ",", "error", ")", "{", "tableSchema", ",", "ok", ":=", "keyspaceSchema", ".", "Tables", "[", "name", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_FAILED_PRECONDITION", ",", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "// use the lowest cost unique vindex as the sharding key", "colVindex", ",", "err", ":=", "vindexes", ".", "FindVindexForSharding", "(", "name", ",", "tableSchema", ".", "ColumnVindexes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Find the sharding key column index.", "columnIndex", ":=", "-", "1", "\n", "for", "i", ",", "n", ":=", "range", "columns", "{", "if", "colVindex", ".", "Columns", "[", "0", "]", ".", "EqualString", "(", "n", ")", "{", "columnIndex", "=", "i", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "columnIndex", "==", "-", "1", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_FAILED_PRECONDITION", ",", "\"", "\"", ",", "name", ",", "colVindex", ".", "Columns", "[", "0", "]", ")", "\n", "}", "\n\n", "return", "&", "v3Resolver", "{", "shardingColumnIndex", ":", "columnIndex", ",", "vindex", ":", "colVindex", ".", "Vindex", ",", "}", ",", "nil", "\n", "}" ]
// newV3ResolverFromColumnList returns a keyspaceIDResolver for a v3 table.
[ "newV3ResolverFromColumnList", "returns", "a", "keyspaceIDResolver", "for", "a", "v3", "table", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/key_resolver.go#L127-L154
157,839
vitessio/vitess
go/vt/zkctl/zkctl.go
Shutdown
func (zkd *Zkd) Shutdown() error { log.Infof("zkctl.Shutdown") pidData, err := ioutil.ReadFile(zkd.config.PidFile()) if err != nil { return err } pid, err := strconv.Atoi(string(bytes.TrimSpace(pidData))) if err != nil { return err } err = syscall.Kill(pid, syscall.SIGKILL) if err != nil && err != syscall.ESRCH { return err } for i := 0; i < shutdownWaitTime; i++ { if syscall.Kill(pid, syscall.SIGKILL) == syscall.ESRCH { return nil } time.Sleep(time.Second) } return fmt.Errorf("Shutdown didn't kill process %v", pid) }
go
func (zkd *Zkd) Shutdown() error { log.Infof("zkctl.Shutdown") pidData, err := ioutil.ReadFile(zkd.config.PidFile()) if err != nil { return err } pid, err := strconv.Atoi(string(bytes.TrimSpace(pidData))) if err != nil { return err } err = syscall.Kill(pid, syscall.SIGKILL) if err != nil && err != syscall.ESRCH { return err } for i := 0; i < shutdownWaitTime; i++ { if syscall.Kill(pid, syscall.SIGKILL) == syscall.ESRCH { return nil } time.Sleep(time.Second) } return fmt.Errorf("Shutdown didn't kill process %v", pid) }
[ "func", "(", "zkd", "*", "Zkd", ")", "Shutdown", "(", ")", "error", "{", "log", ".", "Infof", "(", "\"", "\"", ")", "\n", "pidData", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "zkd", ".", "config", ".", "PidFile", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "pid", ",", "err", ":=", "strconv", ".", "Atoi", "(", "string", "(", "bytes", ".", "TrimSpace", "(", "pidData", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "syscall", ".", "Kill", "(", "pid", ",", "syscall", ".", "SIGKILL", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "syscall", ".", "ESRCH", "{", "return", "err", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "shutdownWaitTime", ";", "i", "++", "{", "if", "syscall", ".", "Kill", "(", "pid", ",", "syscall", ".", "SIGKILL", ")", "==", "syscall", ".", "ESRCH", "{", "return", "nil", "\n", "}", "\n", "time", ".", "Sleep", "(", "time", ".", "Second", ")", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pid", ")", "\n", "}" ]
// Shutdown kills a ZooKeeper server, but keeps its data dir intact.
[ "Shutdown", "kills", "a", "ZooKeeper", "server", "but", "keeps", "its", "data", "dir", "intact", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/zkctl/zkctl.go#L127-L148
157,840
vitessio/vitess
go/vt/zkctl/zkctl.go
Init
func (zkd *Zkd) Init() error { if zkd.Inited() { return fmt.Errorf("zk already inited") } log.Infof("zkd.Init") for _, path := range zkd.config.DirectoryList() { if err := os.MkdirAll(path, 0775); err != nil { log.Errorf("%v", err) return err } // FIXME(msolomon) validate permissions? } configData, err := zkd.makeCfg() if err == nil { err = ioutil.WriteFile(zkd.config.ConfigFile(), []byte(configData), 0664) } if err != nil { log.Errorf("failed creating %v: %v", zkd.config.ConfigFile(), err) return err } err = zkd.config.WriteMyid() if err != nil { log.Errorf("failed creating %v: %v", zkd.config.MyidFile(), err) return err } if err = zkd.Start(); err != nil { log.Errorf("failed starting, check %v", zkd.config.LogDir()) return err } zkAddr := fmt.Sprintf("localhost:%v", zkd.config.ClientPort) zk, session, err := zookeeper.Connect([]string{zkAddr}, startWaitTime*time.Second) if err != nil { return err } event := <-session if event.State != zookeeper.StateConnecting { return event.Err } event = <-session if event.State != zookeeper.StateConnected { return event.Err } defer zk.Close() return nil }
go
func (zkd *Zkd) Init() error { if zkd.Inited() { return fmt.Errorf("zk already inited") } log.Infof("zkd.Init") for _, path := range zkd.config.DirectoryList() { if err := os.MkdirAll(path, 0775); err != nil { log.Errorf("%v", err) return err } // FIXME(msolomon) validate permissions? } configData, err := zkd.makeCfg() if err == nil { err = ioutil.WriteFile(zkd.config.ConfigFile(), []byte(configData), 0664) } if err != nil { log.Errorf("failed creating %v: %v", zkd.config.ConfigFile(), err) return err } err = zkd.config.WriteMyid() if err != nil { log.Errorf("failed creating %v: %v", zkd.config.MyidFile(), err) return err } if err = zkd.Start(); err != nil { log.Errorf("failed starting, check %v", zkd.config.LogDir()) return err } zkAddr := fmt.Sprintf("localhost:%v", zkd.config.ClientPort) zk, session, err := zookeeper.Connect([]string{zkAddr}, startWaitTime*time.Second) if err != nil { return err } event := <-session if event.State != zookeeper.StateConnecting { return event.Err } event = <-session if event.State != zookeeper.StateConnected { return event.Err } defer zk.Close() return nil }
[ "func", "(", "zkd", "*", "Zkd", ")", "Init", "(", ")", "error", "{", "if", "zkd", ".", "Inited", "(", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ")", "\n", "for", "_", ",", "path", ":=", "range", "zkd", ".", "config", ".", "DirectoryList", "(", ")", "{", "if", "err", ":=", "os", ".", "MkdirAll", "(", "path", ",", "0775", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "// FIXME(msolomon) validate permissions?", "}", "\n\n", "configData", ",", "err", ":=", "zkd", ".", "makeCfg", "(", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "ioutil", ".", "WriteFile", "(", "zkd", ".", "config", ".", "ConfigFile", "(", ")", ",", "[", "]", "byte", "(", "configData", ")", ",", "0664", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "zkd", ".", "config", ".", "ConfigFile", "(", ")", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "err", "=", "zkd", ".", "config", ".", "WriteMyid", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "zkd", ".", "config", ".", "MyidFile", "(", ")", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "if", "err", "=", "zkd", ".", "Start", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "zkd", ".", "config", ".", "LogDir", "(", ")", ")", "\n", "return", "err", "\n", "}", "\n\n", "zkAddr", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "zkd", ".", "config", ".", "ClientPort", ")", "\n", "zk", ",", "session", ",", "err", ":=", "zookeeper", ".", "Connect", "(", "[", "]", "string", "{", "zkAddr", "}", ",", "startWaitTime", "*", "time", ".", "Second", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "event", ":=", "<-", "session", "\n", "if", "event", ".", "State", "!=", "zookeeper", ".", "StateConnecting", "{", "return", "event", ".", "Err", "\n", "}", "\n", "event", "=", "<-", "session", "\n", "if", "event", ".", "State", "!=", "zookeeper", ".", "StateConnected", "{", "return", "event", ".", "Err", "\n", "}", "\n", "defer", "zk", ".", "Close", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// Init generates a new config and then starts ZooKeeper.
[ "Init", "generates", "a", "new", "config", "and", "then", "starts", "ZooKeeper", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/zkctl/zkctl.go#L160-L210
157,841
vitessio/vitess
go/vt/zkctl/zkctl.go
Teardown
func (zkd *Zkd) Teardown() error { log.Infof("zkctl.Teardown") if err := zkd.Shutdown(); err != nil { log.Warningf("failed zookeeper shutdown: %v", err.Error()) } var removalErr error for _, dir := range zkd.config.DirectoryList() { log.V(6).Infof("remove data dir %v", dir) if err := os.RemoveAll(dir); err != nil { log.Errorf("failed removing %v: %v", dir, err.Error()) removalErr = err } } return removalErr }
go
func (zkd *Zkd) Teardown() error { log.Infof("zkctl.Teardown") if err := zkd.Shutdown(); err != nil { log.Warningf("failed zookeeper shutdown: %v", err.Error()) } var removalErr error for _, dir := range zkd.config.DirectoryList() { log.V(6).Infof("remove data dir %v", dir) if err := os.RemoveAll(dir); err != nil { log.Errorf("failed removing %v: %v", dir, err.Error()) removalErr = err } } return removalErr }
[ "func", "(", "zkd", "*", "Zkd", ")", "Teardown", "(", ")", "error", "{", "log", ".", "Infof", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "zkd", ".", "Shutdown", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "var", "removalErr", "error", "\n", "for", "_", ",", "dir", ":=", "range", "zkd", ".", "config", ".", "DirectoryList", "(", ")", "{", "log", ".", "V", "(", "6", ")", ".", "Infof", "(", "\"", "\"", ",", "dir", ")", "\n", "if", "err", ":=", "os", ".", "RemoveAll", "(", "dir", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "dir", ",", "err", ".", "Error", "(", ")", ")", "\n", "removalErr", "=", "err", "\n", "}", "\n", "}", "\n", "return", "removalErr", "\n", "}" ]
// Teardown shuts down the server and removes its data dir.
[ "Teardown", "shuts", "down", "the", "server", "and", "removes", "its", "data", "dir", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/zkctl/zkctl.go#L213-L227
157,842
vitessio/vitess
go/vt/zkctl/zkctl.go
Inited
func (zkd *Zkd) Inited() bool { myidFile := zkd.config.MyidFile() _, statErr := os.Stat(myidFile) if statErr == nil { return true } else if statErr.(*os.PathError).Err != syscall.ENOENT { panic("can't access file " + myidFile + ": " + statErr.Error()) } return false }
go
func (zkd *Zkd) Inited() bool { myidFile := zkd.config.MyidFile() _, statErr := os.Stat(myidFile) if statErr == nil { return true } else if statErr.(*os.PathError).Err != syscall.ENOENT { panic("can't access file " + myidFile + ": " + statErr.Error()) } return false }
[ "func", "(", "zkd", "*", "Zkd", ")", "Inited", "(", ")", "bool", "{", "myidFile", ":=", "zkd", ".", "config", ".", "MyidFile", "(", ")", "\n", "_", ",", "statErr", ":=", "os", ".", "Stat", "(", "myidFile", ")", "\n", "if", "statErr", "==", "nil", "{", "return", "true", "\n", "}", "else", "if", "statErr", ".", "(", "*", "os", ".", "PathError", ")", ".", "Err", "!=", "syscall", ".", "ENOENT", "{", "panic", "(", "\"", "\"", "+", "myidFile", "+", "\"", "\"", "+", "statErr", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Inited returns true if the server config has been initialized.
[ "Inited", "returns", "true", "if", "the", "server", "config", "has", "been", "initialized", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/zkctl/zkctl.go#L230-L239
157,843
vitessio/vitess
go/vt/servenv/servenv.go
Init
func Init() { mu.Lock() defer mu.Unlock() if inited { log.Fatal("servenv.Init called second time") } inited = true // Once you run as root, you pretty much destroy the chances of a // non-privileged user starting the program correctly. if uid := os.Getuid(); uid == 0 { log.Exitf("servenv.Init: running this as root makes no sense") } runtime.MemProfileRate = *memProfileRate if *mutexProfileFraction != 0 { log.Infof("setting mutex profile fraction to %v", *mutexProfileFraction) runtime.SetMutexProfileFraction(*mutexProfileFraction) } // We used to set this limit directly, but you pretty much have to // use a root account to allow increasing a limit reliably. Dropping // privileges is also tricky. The best strategy is to make a shell // script set up the limits as root and switch users before starting // the server. fdLimit := &syscall.Rlimit{} if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, fdLimit); err != nil { log.Errorf("max-open-fds failed: %v", err) } fdl := stats.NewGauge("MaxFds", "File descriptor limit") fdl.Set(int64(fdLimit.Cur)) onInitHooks.Fire() }
go
func Init() { mu.Lock() defer mu.Unlock() if inited { log.Fatal("servenv.Init called second time") } inited = true // Once you run as root, you pretty much destroy the chances of a // non-privileged user starting the program correctly. if uid := os.Getuid(); uid == 0 { log.Exitf("servenv.Init: running this as root makes no sense") } runtime.MemProfileRate = *memProfileRate if *mutexProfileFraction != 0 { log.Infof("setting mutex profile fraction to %v", *mutexProfileFraction) runtime.SetMutexProfileFraction(*mutexProfileFraction) } // We used to set this limit directly, but you pretty much have to // use a root account to allow increasing a limit reliably. Dropping // privileges is also tricky. The best strategy is to make a shell // script set up the limits as root and switch users before starting // the server. fdLimit := &syscall.Rlimit{} if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, fdLimit); err != nil { log.Errorf("max-open-fds failed: %v", err) } fdl := stats.NewGauge("MaxFds", "File descriptor limit") fdl.Set(int64(fdLimit.Cur)) onInitHooks.Fire() }
[ "func", "Init", "(", ")", "{", "mu", ".", "Lock", "(", ")", "\n", "defer", "mu", ".", "Unlock", "(", ")", "\n", "if", "inited", "{", "log", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "inited", "=", "true", "\n\n", "// Once you run as root, you pretty much destroy the chances of a", "// non-privileged user starting the program correctly.", "if", "uid", ":=", "os", ".", "Getuid", "(", ")", ";", "uid", "==", "0", "{", "log", ".", "Exitf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "runtime", ".", "MemProfileRate", "=", "*", "memProfileRate", "\n\n", "if", "*", "mutexProfileFraction", "!=", "0", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "*", "mutexProfileFraction", ")", "\n", "runtime", ".", "SetMutexProfileFraction", "(", "*", "mutexProfileFraction", ")", "\n", "}", "\n\n", "// We used to set this limit directly, but you pretty much have to", "// use a root account to allow increasing a limit reliably. Dropping", "// privileges is also tricky. The best strategy is to make a shell", "// script set up the limits as root and switch users before starting", "// the server.", "fdLimit", ":=", "&", "syscall", ".", "Rlimit", "{", "}", "\n", "if", "err", ":=", "syscall", ".", "Getrlimit", "(", "syscall", ".", "RLIMIT_NOFILE", ",", "fdLimit", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "fdl", ":=", "stats", ".", "NewGauge", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "fdl", ".", "Set", "(", "int64", "(", "fdLimit", ".", "Cur", ")", ")", "\n\n", "onInitHooks", ".", "Fire", "(", ")", "\n", "}" ]
// Init is the first phase of the server startup.
[ "Init", "is", "the", "first", "phase", "of", "the", "server", "startup", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/servenv/servenv.go#L77-L111
157,844
vitessio/vitess
go/vt/servenv/servenv.go
fireOnTermSyncHooks
func fireOnTermSyncHooks(timeout time.Duration) bool { log.Infof("Firing synchronous OnTermSync hooks and waiting up to %v for them", timeout) timer := time.NewTimer(timeout) defer timer.Stop() done := make(chan struct{}) go func() { onTermSyncHooks.Fire() close(done) }() select { case <-done: log.Infof("OnTermSync hooks finished") return true case <-timer.C: log.Infof("OnTermSync hooks timed out") return false } }
go
func fireOnTermSyncHooks(timeout time.Duration) bool { log.Infof("Firing synchronous OnTermSync hooks and waiting up to %v for them", timeout) timer := time.NewTimer(timeout) defer timer.Stop() done := make(chan struct{}) go func() { onTermSyncHooks.Fire() close(done) }() select { case <-done: log.Infof("OnTermSync hooks finished") return true case <-timer.C: log.Infof("OnTermSync hooks timed out") return false } }
[ "func", "fireOnTermSyncHooks", "(", "timeout", "time", ".", "Duration", ")", "bool", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "timeout", ")", "\n\n", "timer", ":=", "time", ".", "NewTimer", "(", "timeout", ")", "\n", "defer", "timer", ".", "Stop", "(", ")", "\n\n", "done", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "go", "func", "(", ")", "{", "onTermSyncHooks", ".", "Fire", "(", ")", "\n", "close", "(", "done", ")", "\n", "}", "(", ")", "\n\n", "select", "{", "case", "<-", "done", ":", "log", ".", "Infof", "(", "\"", "\"", ")", "\n", "return", "true", "\n", "case", "<-", "timer", ".", "C", ":", "log", ".", "Infof", "(", "\"", "\"", ")", "\n", "return", "false", "\n", "}", "\n", "}" ]
// fireOnTermSyncHooks returns true iff all the hooks finish before the timeout.
[ "fireOnTermSyncHooks", "returns", "true", "iff", "all", "the", "hooks", "finish", "before", "the", "timeout", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/servenv/servenv.go#L157-L177
157,845
vitessio/vitess
go/vt/servenv/servenv.go
ParseFlags
func ParseFlags(cmd string) { flag.Parse() if *Version { AppVersion.Print() os.Exit(0) } args := flag.Args() if len(args) > 0 { flag.Usage() log.Exitf("%s doesn't take any positional arguments, got '%s'", cmd, strings.Join(args, " ")) } }
go
func ParseFlags(cmd string) { flag.Parse() if *Version { AppVersion.Print() os.Exit(0) } args := flag.Args() if len(args) > 0 { flag.Usage() log.Exitf("%s doesn't take any positional arguments, got '%s'", cmd, strings.Join(args, " ")) } }
[ "func", "ParseFlags", "(", "cmd", "string", ")", "{", "flag", ".", "Parse", "(", ")", "\n\n", "if", "*", "Version", "{", "AppVersion", ".", "Print", "(", ")", "\n", "os", ".", "Exit", "(", "0", ")", "\n", "}", "\n\n", "args", ":=", "flag", ".", "Args", "(", ")", "\n", "if", "len", "(", "args", ")", ">", "0", "{", "flag", ".", "Usage", "(", ")", "\n", "log", ".", "Exitf", "(", "\"", "\"", ",", "cmd", ",", "strings", ".", "Join", "(", "args", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "}" ]
// ParseFlags initializes flags and handles the common case when no positional // arguments are expected.
[ "ParseFlags", "initializes", "flags", "and", "handles", "the", "common", "case", "when", "no", "positional", "arguments", "are", "expected", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/servenv/servenv.go#L206-L219
157,846
vitessio/vitess
go/vt/servenv/servenv.go
ParseFlagsWithArgs
func ParseFlagsWithArgs(cmd string) []string { flag.Parse() if *Version { AppVersion.Print() os.Exit(0) } args := flag.Args() if len(args) == 0 { log.Exitf("%s expected at least one positional argument", cmd) } return args }
go
func ParseFlagsWithArgs(cmd string) []string { flag.Parse() if *Version { AppVersion.Print() os.Exit(0) } args := flag.Args() if len(args) == 0 { log.Exitf("%s expected at least one positional argument", cmd) } return args }
[ "func", "ParseFlagsWithArgs", "(", "cmd", "string", ")", "[", "]", "string", "{", "flag", ".", "Parse", "(", ")", "\n\n", "if", "*", "Version", "{", "AppVersion", ".", "Print", "(", ")", "\n", "os", ".", "Exit", "(", "0", ")", "\n", "}", "\n\n", "args", ":=", "flag", ".", "Args", "(", ")", "\n", "if", "len", "(", "args", ")", "==", "0", "{", "log", ".", "Exitf", "(", "\"", "\"", ",", "cmd", ")", "\n", "}", "\n\n", "return", "args", "\n", "}" ]
// ParseFlagsWithArgs initializes flags and returns the positional arguments
[ "ParseFlagsWithArgs", "initializes", "flags", "and", "returns", "the", "positional", "arguments" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/servenv/servenv.go#L222-L236
157,847
vitessio/vitess
go/vt/vttablet/tabletserver/tx_engine.go
NewTxEngine
func NewTxEngine(checker connpool.MySQLChecker, config tabletenv.TabletConfig) *TxEngine { te := &TxEngine{ shutdownGracePeriod: time.Duration(config.TxShutDownGracePeriod * 1e9), } limiter := txlimiter.New( config.TransactionCap, config.TransactionLimitPerUser, config.EnableTransactionLimit, config.EnableTransactionLimitDryRun, config.TransactionLimitByUsername, config.TransactionLimitByPrincipal, config.TransactionLimitByComponent, config.TransactionLimitBySubcomponent, ) te.txPool = NewTxPool( config.PoolNamePrefix, config.TransactionCap, config.FoundRowsPoolSize, time.Duration(config.TransactionTimeout*1e9), time.Duration(config.IdleTimeout*1e9), config.TxPoolWaiterCap, checker, limiter, ) te.twopcEnabled = config.TwoPCEnable if te.twopcEnabled { if config.TwoPCCoordinatorAddress == "" { log.Error("Coordinator address not specified: Disabling 2PC") te.twopcEnabled = false } if config.TwoPCAbandonAge <= 0 { log.Error("2PC abandon age not specified: Disabling 2PC") te.twopcEnabled = false } } te.coordinatorAddress = config.TwoPCCoordinatorAddress te.abandonAge = time.Duration(config.TwoPCAbandonAge * 1e9) te.ticks = timer.NewTimer(te.abandonAge / 2) // Set the prepared pool capacity to something lower than // tx pool capacity. Those spare connections are needed to // perform metadata state change operations. Without this, // the system can deadlock if all connections get moved to // the TxPreparedPool. te.preparedPool = NewTxPreparedPool(config.TransactionCap - 2) readPool := connpool.New( config.PoolNamePrefix+"TxReadPool", 3, time.Duration(config.IdleTimeout*1e9), checker, ) te.twoPC = NewTwoPC(readPool) te.transitionSignal = make(chan struct{}) // By immediately closing this channel, all state changes can simply be made blocking by issuing the // state change desired, and then selecting on this channel. It will contain an open channel while // transitioning. close(te.transitionSignal) te.nextState = -1 te.state = NotServing return te }
go
func NewTxEngine(checker connpool.MySQLChecker, config tabletenv.TabletConfig) *TxEngine { te := &TxEngine{ shutdownGracePeriod: time.Duration(config.TxShutDownGracePeriod * 1e9), } limiter := txlimiter.New( config.TransactionCap, config.TransactionLimitPerUser, config.EnableTransactionLimit, config.EnableTransactionLimitDryRun, config.TransactionLimitByUsername, config.TransactionLimitByPrincipal, config.TransactionLimitByComponent, config.TransactionLimitBySubcomponent, ) te.txPool = NewTxPool( config.PoolNamePrefix, config.TransactionCap, config.FoundRowsPoolSize, time.Duration(config.TransactionTimeout*1e9), time.Duration(config.IdleTimeout*1e9), config.TxPoolWaiterCap, checker, limiter, ) te.twopcEnabled = config.TwoPCEnable if te.twopcEnabled { if config.TwoPCCoordinatorAddress == "" { log.Error("Coordinator address not specified: Disabling 2PC") te.twopcEnabled = false } if config.TwoPCAbandonAge <= 0 { log.Error("2PC abandon age not specified: Disabling 2PC") te.twopcEnabled = false } } te.coordinatorAddress = config.TwoPCCoordinatorAddress te.abandonAge = time.Duration(config.TwoPCAbandonAge * 1e9) te.ticks = timer.NewTimer(te.abandonAge / 2) // Set the prepared pool capacity to something lower than // tx pool capacity. Those spare connections are needed to // perform metadata state change operations. Without this, // the system can deadlock if all connections get moved to // the TxPreparedPool. te.preparedPool = NewTxPreparedPool(config.TransactionCap - 2) readPool := connpool.New( config.PoolNamePrefix+"TxReadPool", 3, time.Duration(config.IdleTimeout*1e9), checker, ) te.twoPC = NewTwoPC(readPool) te.transitionSignal = make(chan struct{}) // By immediately closing this channel, all state changes can simply be made blocking by issuing the // state change desired, and then selecting on this channel. It will contain an open channel while // transitioning. close(te.transitionSignal) te.nextState = -1 te.state = NotServing return te }
[ "func", "NewTxEngine", "(", "checker", "connpool", ".", "MySQLChecker", ",", "config", "tabletenv", ".", "TabletConfig", ")", "*", "TxEngine", "{", "te", ":=", "&", "TxEngine", "{", "shutdownGracePeriod", ":", "time", ".", "Duration", "(", "config", ".", "TxShutDownGracePeriod", "*", "1e9", ")", ",", "}", "\n", "limiter", ":=", "txlimiter", ".", "New", "(", "config", ".", "TransactionCap", ",", "config", ".", "TransactionLimitPerUser", ",", "config", ".", "EnableTransactionLimit", ",", "config", ".", "EnableTransactionLimitDryRun", ",", "config", ".", "TransactionLimitByUsername", ",", "config", ".", "TransactionLimitByPrincipal", ",", "config", ".", "TransactionLimitByComponent", ",", "config", ".", "TransactionLimitBySubcomponent", ",", ")", "\n", "te", ".", "txPool", "=", "NewTxPool", "(", "config", ".", "PoolNamePrefix", ",", "config", ".", "TransactionCap", ",", "config", ".", "FoundRowsPoolSize", ",", "time", ".", "Duration", "(", "config", ".", "TransactionTimeout", "*", "1e9", ")", ",", "time", ".", "Duration", "(", "config", ".", "IdleTimeout", "*", "1e9", ")", ",", "config", ".", "TxPoolWaiterCap", ",", "checker", ",", "limiter", ",", ")", "\n", "te", ".", "twopcEnabled", "=", "config", ".", "TwoPCEnable", "\n", "if", "te", ".", "twopcEnabled", "{", "if", "config", ".", "TwoPCCoordinatorAddress", "==", "\"", "\"", "{", "log", ".", "Error", "(", "\"", "\"", ")", "\n", "te", ".", "twopcEnabled", "=", "false", "\n", "}", "\n", "if", "config", ".", "TwoPCAbandonAge", "<=", "0", "{", "log", ".", "Error", "(", "\"", "\"", ")", "\n", "te", ".", "twopcEnabled", "=", "false", "\n", "}", "\n", "}", "\n", "te", ".", "coordinatorAddress", "=", "config", ".", "TwoPCCoordinatorAddress", "\n", "te", ".", "abandonAge", "=", "time", ".", "Duration", "(", "config", ".", "TwoPCAbandonAge", "*", "1e9", ")", "\n", "te", ".", "ticks", "=", "timer", ".", "NewTimer", "(", "te", ".", "abandonAge", "/", "2", ")", "\n\n", "// Set the prepared pool capacity to something lower than", "// tx pool capacity. Those spare connections are needed to", "// perform metadata state change operations. Without this,", "// the system can deadlock if all connections get moved to", "// the TxPreparedPool.", "te", ".", "preparedPool", "=", "NewTxPreparedPool", "(", "config", ".", "TransactionCap", "-", "2", ")", "\n", "readPool", ":=", "connpool", ".", "New", "(", "config", ".", "PoolNamePrefix", "+", "\"", "\"", ",", "3", ",", "time", ".", "Duration", "(", "config", ".", "IdleTimeout", "*", "1e9", ")", ",", "checker", ",", ")", "\n", "te", ".", "twoPC", "=", "NewTwoPC", "(", "readPool", ")", "\n", "te", ".", "transitionSignal", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "// By immediately closing this channel, all state changes can simply be made blocking by issuing the", "// state change desired, and then selecting on this channel. It will contain an open channel while", "// transitioning.", "close", "(", "te", ".", "transitionSignal", ")", "\n", "te", ".", "nextState", "=", "-", "1", "\n", "te", ".", "state", "=", "NotServing", "\n", "return", "te", "\n", "}" ]
// NewTxEngine creates a new TxEngine.
[ "NewTxEngine", "creates", "a", "new", "TxEngine", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_engine.go#L101-L161
157,848
vitessio/vitess
go/vt/vttablet/tabletserver/tx_engine.go
AcceptReadWrite
func (te *TxEngine) AcceptReadWrite() error { te.beginRequests.Wait() te.stateLock.Lock() switch te.state { case AcceptingReadAndWrite: // Nothing to do te.stateLock.Unlock() return nil case NotServing: te.state = AcceptingReadAndWrite te.open() te.stateLock.Unlock() return nil case Transitioning: te.nextState = AcceptingReadAndWrite te.stateLock.Unlock() te.blockUntilEndOfTransition() return nil case AcceptingReadOnly: // We need to restart the tx-pool to make sure we handle 2PC correctly te.close(true) te.state = AcceptingReadAndWrite te.open() te.stateLock.Unlock() return nil default: return te.unknownStateError() } }
go
func (te *TxEngine) AcceptReadWrite() error { te.beginRequests.Wait() te.stateLock.Lock() switch te.state { case AcceptingReadAndWrite: // Nothing to do te.stateLock.Unlock() return nil case NotServing: te.state = AcceptingReadAndWrite te.open() te.stateLock.Unlock() return nil case Transitioning: te.nextState = AcceptingReadAndWrite te.stateLock.Unlock() te.blockUntilEndOfTransition() return nil case AcceptingReadOnly: // We need to restart the tx-pool to make sure we handle 2PC correctly te.close(true) te.state = AcceptingReadAndWrite te.open() te.stateLock.Unlock() return nil default: return te.unknownStateError() } }
[ "func", "(", "te", "*", "TxEngine", ")", "AcceptReadWrite", "(", ")", "error", "{", "te", ".", "beginRequests", ".", "Wait", "(", ")", "\n", "te", ".", "stateLock", ".", "Lock", "(", ")", "\n\n", "switch", "te", ".", "state", "{", "case", "AcceptingReadAndWrite", ":", "// Nothing to do", "te", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n\n", "case", "NotServing", ":", "te", ".", "state", "=", "AcceptingReadAndWrite", "\n", "te", ".", "open", "(", ")", "\n", "te", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n\n", "case", "Transitioning", ":", "te", ".", "nextState", "=", "AcceptingReadAndWrite", "\n", "te", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "te", ".", "blockUntilEndOfTransition", "(", ")", "\n", "return", "nil", "\n\n", "case", "AcceptingReadOnly", ":", "// We need to restart the tx-pool to make sure we handle 2PC correctly", "te", ".", "close", "(", "true", ")", "\n", "te", ".", "state", "=", "AcceptingReadAndWrite", "\n", "te", ".", "open", "(", ")", "\n", "te", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n\n", "default", ":", "return", "te", ".", "unknownStateError", "(", ")", "\n", "}", "\n", "}" ]
// AcceptReadWrite will start accepting all transactions. // If transitioning from RO mode, transactions might need to be // rolled back before new transactions can be accepts.
[ "AcceptReadWrite", "will", "start", "accepting", "all", "transactions", ".", "If", "transitioning", "from", "RO", "mode", "transactions", "might", "need", "to", "be", "rolled", "back", "before", "new", "transactions", "can", "be", "accepts", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_engine.go#L199-L232
157,849
vitessio/vitess
go/vt/vttablet/tabletserver/tx_engine.go
AcceptReadOnly
func (te *TxEngine) AcceptReadOnly() error { te.beginRequests.Wait() te.stateLock.Lock() switch te.state { case AcceptingReadOnly: // Nothing to do te.stateLock.Unlock() return nil case NotServing: te.state = AcceptingReadOnly te.open() te.stateLock.Unlock() return nil case AcceptingReadAndWrite: return te.transitionTo(AcceptingReadOnly) case Transitioning: te.nextState = AcceptingReadOnly te.stateLock.Unlock() te.blockUntilEndOfTransition() return nil default: te.stateLock.Unlock() return te.unknownStateError() } }
go
func (te *TxEngine) AcceptReadOnly() error { te.beginRequests.Wait() te.stateLock.Lock() switch te.state { case AcceptingReadOnly: // Nothing to do te.stateLock.Unlock() return nil case NotServing: te.state = AcceptingReadOnly te.open() te.stateLock.Unlock() return nil case AcceptingReadAndWrite: return te.transitionTo(AcceptingReadOnly) case Transitioning: te.nextState = AcceptingReadOnly te.stateLock.Unlock() te.blockUntilEndOfTransition() return nil default: te.stateLock.Unlock() return te.unknownStateError() } }
[ "func", "(", "te", "*", "TxEngine", ")", "AcceptReadOnly", "(", ")", "error", "{", "te", ".", "beginRequests", ".", "Wait", "(", ")", "\n", "te", ".", "stateLock", ".", "Lock", "(", ")", "\n", "switch", "te", ".", "state", "{", "case", "AcceptingReadOnly", ":", "// Nothing to do", "te", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n\n", "case", "NotServing", ":", "te", ".", "state", "=", "AcceptingReadOnly", "\n", "te", ".", "open", "(", ")", "\n", "te", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n\n", "case", "AcceptingReadAndWrite", ":", "return", "te", ".", "transitionTo", "(", "AcceptingReadOnly", ")", "\n\n", "case", "Transitioning", ":", "te", ".", "nextState", "=", "AcceptingReadOnly", "\n", "te", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "te", ".", "blockUntilEndOfTransition", "(", ")", "\n", "return", "nil", "\n\n", "default", ":", "te", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "return", "te", ".", "unknownStateError", "(", ")", "\n", "}", "\n", "}" ]
// AcceptReadOnly will start accepting read-only transactions, but not full read and write transactions. // If the engine is currently accepting full read and write transactions, they need to // be rolled back.
[ "AcceptReadOnly", "will", "start", "accepting", "read", "-", "only", "transactions", "but", "not", "full", "read", "and", "write", "transactions", ".", "If", "the", "engine", "is", "currently", "accepting", "full", "read", "and", "write", "transactions", "they", "need", "to", "be", "rolled", "back", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_engine.go#L237-L265
157,850
vitessio/vitess
go/vt/vttablet/tabletserver/tx_engine.go
Init
func (te *TxEngine) Init() error { if te.twopcEnabled { return te.twoPC.Init(te.dbconfigs.SidecarDBName.Get(), te.dbconfigs.DbaWithDB()) } return nil }
go
func (te *TxEngine) Init() error { if te.twopcEnabled { return te.twoPC.Init(te.dbconfigs.SidecarDBName.Get(), te.dbconfigs.DbaWithDB()) } return nil }
[ "func", "(", "te", "*", "TxEngine", ")", "Init", "(", ")", "error", "{", "if", "te", ".", "twopcEnabled", "{", "return", "te", ".", "twoPC", ".", "Init", "(", "te", ".", "dbconfigs", ".", "SidecarDBName", ".", "Get", "(", ")", ",", "te", ".", "dbconfigs", ".", "DbaWithDB", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Init must be called once when vttablet starts for setting // up the metadata tables.
[ "Init", "must", "be", "called", "once", "when", "vttablet", "starts", "for", "setting", "up", "the", "metadata", "tables", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_engine.go#L366-L371
157,851
vitessio/vitess
go/vt/vttablet/tabletserver/tx_engine.go
open
func (te *TxEngine) open() { te.txPool.Open(te.dbconfigs.AppWithDB(), te.dbconfigs.DbaWithDB(), te.dbconfigs.AppDebugWithDB()) if te.twopcEnabled && te.state == AcceptingReadAndWrite { te.twoPC.Open(te.dbconfigs) if err := te.prepareFromRedo(); err != nil { // If this operation fails, we choose to raise an alert and // continue anyway. Serving traffic is considered more important // than blocking everything for the sake of a few transactions. tabletenv.InternalErrors.Add("TwopcResurrection", 1) log.Errorf("Could not prepare transactions: %v", err) } te.startWatchdog() } }
go
func (te *TxEngine) open() { te.txPool.Open(te.dbconfigs.AppWithDB(), te.dbconfigs.DbaWithDB(), te.dbconfigs.AppDebugWithDB()) if te.twopcEnabled && te.state == AcceptingReadAndWrite { te.twoPC.Open(te.dbconfigs) if err := te.prepareFromRedo(); err != nil { // If this operation fails, we choose to raise an alert and // continue anyway. Serving traffic is considered more important // than blocking everything for the sake of a few transactions. tabletenv.InternalErrors.Add("TwopcResurrection", 1) log.Errorf("Could not prepare transactions: %v", err) } te.startWatchdog() } }
[ "func", "(", "te", "*", "TxEngine", ")", "open", "(", ")", "{", "te", ".", "txPool", ".", "Open", "(", "te", ".", "dbconfigs", ".", "AppWithDB", "(", ")", ",", "te", ".", "dbconfigs", ".", "DbaWithDB", "(", ")", ",", "te", ".", "dbconfigs", ".", "AppDebugWithDB", "(", ")", ")", "\n\n", "if", "te", ".", "twopcEnabled", "&&", "te", ".", "state", "==", "AcceptingReadAndWrite", "{", "te", ".", "twoPC", ".", "Open", "(", "te", ".", "dbconfigs", ")", "\n", "if", "err", ":=", "te", ".", "prepareFromRedo", "(", ")", ";", "err", "!=", "nil", "{", "// If this operation fails, we choose to raise an alert and", "// continue anyway. Serving traffic is considered more important", "// than blocking everything for the sake of a few transactions.", "tabletenv", ".", "InternalErrors", ".", "Add", "(", "\"", "\"", ",", "1", ")", "\n", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "te", ".", "startWatchdog", "(", ")", "\n", "}", "\n", "}" ]
// open opens the TxEngine. If 2pc is enabled, it restores // all previously prepared transactions from the redo log. // this should only be called when the state is already locked
[ "open", "opens", "the", "TxEngine", ".", "If", "2pc", "is", "enabled", "it", "restores", "all", "previously", "prepared", "transactions", "from", "the", "redo", "log", ".", "this", "should", "only", "be", "called", "when", "the", "state", "is", "already", "locked" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_engine.go#L376-L390
157,852
vitessio/vitess
go/vt/vttablet/tabletserver/tx_engine.go
StopGently
func (te *TxEngine) StopGently() { te.stateLock.Lock() defer te.stateLock.Unlock() te.close(false) te.state = NotServing }
go
func (te *TxEngine) StopGently() { te.stateLock.Lock() defer te.stateLock.Unlock() te.close(false) te.state = NotServing }
[ "func", "(", "te", "*", "TxEngine", ")", "StopGently", "(", ")", "{", "te", ".", "stateLock", ".", "Lock", "(", ")", "\n", "defer", "te", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "te", ".", "close", "(", "false", ")", "\n", "te", ".", "state", "=", "NotServing", "\n", "}" ]
// StopGently will disregard common rules for when to kill transactions // and wait forever for transactions to wrap up
[ "StopGently", "will", "disregard", "common", "rules", "for", "when", "to", "kill", "transactions", "and", "wait", "forever", "for", "transactions", "to", "wrap", "up" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_engine.go#L394-L399
157,853
vitessio/vitess
go/vt/vttablet/tabletserver/tx_engine.go
close
func (te *TxEngine) close(immediate bool) { // Shut down functions are idempotent. // No need to check if 2pc is enabled. te.stopWatchdog() poolEmpty := make(chan bool) rollbackDone := make(chan bool) // This goroutine decides if transactions have to be // forced to rollback, and if so, when. Once done, // the function closes rollbackDone, which can be // verified to make sure it won't kick in later. go func() { defer func() { tabletenv.LogError() close(rollbackDone) }() if immediate { // Immediately rollback everything and return. log.Info("Immediate shutdown: rolling back now.") te.rollbackTransactions() return } if te.shutdownGracePeriod <= 0 { // No grace period was specified. Never rollback. te.rollbackPrepared() log.Info("No grace period specified: performing normal wait.") return } tmr := time.NewTimer(te.shutdownGracePeriod) defer tmr.Stop() select { case <-tmr.C: log.Info("Grace period exceeded: rolling back now.") te.rollbackTransactions() case <-poolEmpty: // The pool cleared before the timer kicked in. Just return. log.Info("Transactions completed before grace period: shutting down.") } }() te.txPool.WaitForEmpty() // If the goroutine is still running, signal that it can exit. close(poolEmpty) // Make sure the goroutine has returned. <-rollbackDone te.txPool.Close() te.twoPC.Close() }
go
func (te *TxEngine) close(immediate bool) { // Shut down functions are idempotent. // No need to check if 2pc is enabled. te.stopWatchdog() poolEmpty := make(chan bool) rollbackDone := make(chan bool) // This goroutine decides if transactions have to be // forced to rollback, and if so, when. Once done, // the function closes rollbackDone, which can be // verified to make sure it won't kick in later. go func() { defer func() { tabletenv.LogError() close(rollbackDone) }() if immediate { // Immediately rollback everything and return. log.Info("Immediate shutdown: rolling back now.") te.rollbackTransactions() return } if te.shutdownGracePeriod <= 0 { // No grace period was specified. Never rollback. te.rollbackPrepared() log.Info("No grace period specified: performing normal wait.") return } tmr := time.NewTimer(te.shutdownGracePeriod) defer tmr.Stop() select { case <-tmr.C: log.Info("Grace period exceeded: rolling back now.") te.rollbackTransactions() case <-poolEmpty: // The pool cleared before the timer kicked in. Just return. log.Info("Transactions completed before grace period: shutting down.") } }() te.txPool.WaitForEmpty() // If the goroutine is still running, signal that it can exit. close(poolEmpty) // Make sure the goroutine has returned. <-rollbackDone te.txPool.Close() te.twoPC.Close() }
[ "func", "(", "te", "*", "TxEngine", ")", "close", "(", "immediate", "bool", ")", "{", "// Shut down functions are idempotent.", "// No need to check if 2pc is enabled.", "te", ".", "stopWatchdog", "(", ")", "\n\n", "poolEmpty", ":=", "make", "(", "chan", "bool", ")", "\n", "rollbackDone", ":=", "make", "(", "chan", "bool", ")", "\n", "// This goroutine decides if transactions have to be", "// forced to rollback, and if so, when. Once done,", "// the function closes rollbackDone, which can be", "// verified to make sure it won't kick in later.", "go", "func", "(", ")", "{", "defer", "func", "(", ")", "{", "tabletenv", ".", "LogError", "(", ")", "\n", "close", "(", "rollbackDone", ")", "\n", "}", "(", ")", "\n", "if", "immediate", "{", "// Immediately rollback everything and return.", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "te", ".", "rollbackTransactions", "(", ")", "\n", "return", "\n", "}", "\n", "if", "te", ".", "shutdownGracePeriod", "<=", "0", "{", "// No grace period was specified. Never rollback.", "te", ".", "rollbackPrepared", "(", ")", "\n", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "tmr", ":=", "time", ".", "NewTimer", "(", "te", ".", "shutdownGracePeriod", ")", "\n", "defer", "tmr", ".", "Stop", "(", ")", "\n", "select", "{", "case", "<-", "tmr", ".", "C", ":", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "te", ".", "rollbackTransactions", "(", ")", "\n", "case", "<-", "poolEmpty", ":", "// The pool cleared before the timer kicked in. Just return.", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "(", ")", "\n", "te", ".", "txPool", ".", "WaitForEmpty", "(", ")", "\n", "// If the goroutine is still running, signal that it can exit.", "close", "(", "poolEmpty", ")", "\n", "// Make sure the goroutine has returned.", "<-", "rollbackDone", "\n\n", "te", ".", "txPool", ".", "Close", "(", ")", "\n", "te", ".", "twoPC", ".", "Close", "(", ")", "\n", "}" ]
// Close closes the TxEngine. If the immediate flag is on, // then all current transactions are immediately rolled back. // Otherwise, the function waits for all current transactions // to conclude. If a shutdown grace period was specified, // the transactions are rolled back if they're not resolved // by that time.
[ "Close", "closes", "the", "TxEngine", ".", "If", "the", "immediate", "flag", "is", "on", "then", "all", "current", "transactions", "are", "immediately", "rolled", "back", ".", "Otherwise", "the", "function", "waits", "for", "all", "current", "transactions", "to", "conclude", ".", "If", "a", "shutdown", "grace", "period", "was", "specified", "the", "transactions", "are", "rolled", "back", "if", "they", "re", "not", "resolved", "by", "that", "time", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_engine.go#L407-L454
157,854
vitessio/vitess
go/vt/vttablet/tabletserver/tx_engine.go
prepareFromRedo
func (te *TxEngine) prepareFromRedo() error { ctx := tabletenv.LocalContext() var allErr concurrency.AllErrorRecorder prepared, failed, err := te.twoPC.ReadAllRedo(ctx) if err != nil { return err } maxid := int64(0) outer: for _, tx := range prepared { txid, err := dtids.TransactionID(tx.Dtid) if err != nil { log.Errorf("Error extracting transaction ID from ditd: %v", err) } if txid > maxid { maxid = txid } conn, _, err := te.txPool.LocalBegin(ctx, &querypb.ExecuteOptions{}) if err != nil { allErr.RecordError(err) continue } for _, stmt := range tx.Queries { conn.RecordQuery(stmt) _, err := conn.Exec(ctx, stmt, 1, false) if err != nil { allErr.RecordError(err) te.txPool.LocalConclude(ctx, conn) continue outer } } // We should not use the external Prepare because // we don't want to write again to the redo log. err = te.preparedPool.Put(conn, tx.Dtid) if err != nil { allErr.RecordError(err) continue } } for _, tx := range failed { txid, err := dtids.TransactionID(tx.Dtid) if err != nil { log.Errorf("Error extracting transaction ID from ditd: %v", err) } if txid > maxid { maxid = txid } te.preparedPool.SetFailed(tx.Dtid) } te.txPool.AdjustLastID(maxid) log.Infof("Prepared %d transactions, and registered %d failures.", len(prepared), len(failed)) return allErr.Error() }
go
func (te *TxEngine) prepareFromRedo() error { ctx := tabletenv.LocalContext() var allErr concurrency.AllErrorRecorder prepared, failed, err := te.twoPC.ReadAllRedo(ctx) if err != nil { return err } maxid := int64(0) outer: for _, tx := range prepared { txid, err := dtids.TransactionID(tx.Dtid) if err != nil { log.Errorf("Error extracting transaction ID from ditd: %v", err) } if txid > maxid { maxid = txid } conn, _, err := te.txPool.LocalBegin(ctx, &querypb.ExecuteOptions{}) if err != nil { allErr.RecordError(err) continue } for _, stmt := range tx.Queries { conn.RecordQuery(stmt) _, err := conn.Exec(ctx, stmt, 1, false) if err != nil { allErr.RecordError(err) te.txPool.LocalConclude(ctx, conn) continue outer } } // We should not use the external Prepare because // we don't want to write again to the redo log. err = te.preparedPool.Put(conn, tx.Dtid) if err != nil { allErr.RecordError(err) continue } } for _, tx := range failed { txid, err := dtids.TransactionID(tx.Dtid) if err != nil { log.Errorf("Error extracting transaction ID from ditd: %v", err) } if txid > maxid { maxid = txid } te.preparedPool.SetFailed(tx.Dtid) } te.txPool.AdjustLastID(maxid) log.Infof("Prepared %d transactions, and registered %d failures.", len(prepared), len(failed)) return allErr.Error() }
[ "func", "(", "te", "*", "TxEngine", ")", "prepareFromRedo", "(", ")", "error", "{", "ctx", ":=", "tabletenv", ".", "LocalContext", "(", ")", "\n", "var", "allErr", "concurrency", ".", "AllErrorRecorder", "\n", "prepared", ",", "failed", ",", "err", ":=", "te", ".", "twoPC", ".", "ReadAllRedo", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "maxid", ":=", "int64", "(", "0", ")", "\n", "outer", ":", "for", "_", ",", "tx", ":=", "range", "prepared", "{", "txid", ",", "err", ":=", "dtids", ".", "TransactionID", "(", "tx", ".", "Dtid", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "txid", ">", "maxid", "{", "maxid", "=", "txid", "\n", "}", "\n", "conn", ",", "_", ",", "err", ":=", "te", ".", "txPool", ".", "LocalBegin", "(", "ctx", ",", "&", "querypb", ".", "ExecuteOptions", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "allErr", ".", "RecordError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "for", "_", ",", "stmt", ":=", "range", "tx", ".", "Queries", "{", "conn", ".", "RecordQuery", "(", "stmt", ")", "\n", "_", ",", "err", ":=", "conn", ".", "Exec", "(", "ctx", ",", "stmt", ",", "1", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "allErr", ".", "RecordError", "(", "err", ")", "\n", "te", ".", "txPool", ".", "LocalConclude", "(", "ctx", ",", "conn", ")", "\n", "continue", "outer", "\n", "}", "\n", "}", "\n", "// We should not use the external Prepare because", "// we don't want to write again to the redo log.", "err", "=", "te", ".", "preparedPool", ".", "Put", "(", "conn", ",", "tx", ".", "Dtid", ")", "\n", "if", "err", "!=", "nil", "{", "allErr", ".", "RecordError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "}", "\n", "for", "_", ",", "tx", ":=", "range", "failed", "{", "txid", ",", "err", ":=", "dtids", ".", "TransactionID", "(", "tx", ".", "Dtid", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "txid", ">", "maxid", "{", "maxid", "=", "txid", "\n", "}", "\n", "te", ".", "preparedPool", ".", "SetFailed", "(", "tx", ".", "Dtid", ")", "\n", "}", "\n", "te", ".", "txPool", ".", "AdjustLastID", "(", "maxid", ")", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "len", "(", "prepared", ")", ",", "len", "(", "failed", ")", ")", "\n", "return", "allErr", ".", "Error", "(", ")", "\n", "}" ]
// prepareFromRedo replays and prepares the transactions // from the redo log, loads previously failed transactions // into the reserved list, and adjusts the txPool LastID // to ensure there are no future collisions.
[ "prepareFromRedo", "replays", "and", "prepares", "the", "transactions", "from", "the", "redo", "log", "loads", "previously", "failed", "transactions", "into", "the", "reserved", "list", "and", "adjusts", "the", "txPool", "LastID", "to", "ensure", "there", "are", "no", "future", "collisions", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_engine.go#L460-L513
157,855
vitessio/vitess
go/vt/vttablet/tabletserver/tx_engine.go
rollbackTransactions
func (te *TxEngine) rollbackTransactions() { ctx := tabletenv.LocalContext() for _, c := range te.preparedPool.FetchAll() { te.txPool.LocalConclude(ctx, c) } // The order of rollbacks is currently not material because // we don't allow new statements or commits during // this function. In case of any such change, this will // have to be revisited. te.txPool.RollbackNonBusy(ctx) }
go
func (te *TxEngine) rollbackTransactions() { ctx := tabletenv.LocalContext() for _, c := range te.preparedPool.FetchAll() { te.txPool.LocalConclude(ctx, c) } // The order of rollbacks is currently not material because // we don't allow new statements or commits during // this function. In case of any such change, this will // have to be revisited. te.txPool.RollbackNonBusy(ctx) }
[ "func", "(", "te", "*", "TxEngine", ")", "rollbackTransactions", "(", ")", "{", "ctx", ":=", "tabletenv", ".", "LocalContext", "(", ")", "\n", "for", "_", ",", "c", ":=", "range", "te", ".", "preparedPool", ".", "FetchAll", "(", ")", "{", "te", ".", "txPool", ".", "LocalConclude", "(", "ctx", ",", "c", ")", "\n", "}", "\n", "// The order of rollbacks is currently not material because", "// we don't allow new statements or commits during", "// this function. In case of any such change, this will", "// have to be revisited.", "te", ".", "txPool", ".", "RollbackNonBusy", "(", "ctx", ")", "\n", "}" ]
// rollbackTransactions rolls back all open transactions // including the prepared ones. // This is used for transitioning from a master to a non-master // serving type.
[ "rollbackTransactions", "rolls", "back", "all", "open", "transactions", "including", "the", "prepared", "ones", ".", "This", "is", "used", "for", "transitioning", "from", "a", "master", "to", "a", "non", "-", "master", "serving", "type", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_engine.go#L519-L529
157,856
vitessio/vitess
go/vt/vttablet/tabletserver/tx_engine.go
startWatchdog
func (te *TxEngine) startWatchdog() { te.ticks.Start(func() { ctx, cancel := context.WithTimeout(tabletenv.LocalContext(), te.abandonAge/4) defer cancel() // Raise alerts on prepares that have been unresolved for too long. // Use 5x abandonAge to give opportunity for watchdog to resolve these. count, err := te.twoPC.CountUnresolvedRedo(ctx, time.Now().Add(-te.abandonAge*5)) if err != nil { tabletenv.InternalErrors.Add("WatchdogFail", 1) log.Errorf("Error reading unresolved prepares: '%v': %v", te.coordinatorAddress, err) } tabletenv.Unresolved.Set("Prepares", count) // Resolve lingering distributed transactions. txs, err := te.twoPC.ReadAbandoned(ctx, time.Now().Add(-te.abandonAge)) if err != nil { tabletenv.InternalErrors.Add("WatchdogFail", 1) log.Errorf("Error reading transactions for 2pc watchdog: %v", err) return } if len(txs) == 0 { return } coordConn, err := vtgateconn.Dial(ctx, te.coordinatorAddress) if err != nil { tabletenv.InternalErrors.Add("WatchdogFail", 1) log.Errorf("Error connecting to coordinator '%v': %v", te.coordinatorAddress, err) return } defer coordConn.Close() var wg sync.WaitGroup for tx := range txs { wg.Add(1) go func(dtid string) { defer wg.Done() if err := coordConn.ResolveTransaction(ctx, dtid); err != nil { tabletenv.InternalErrors.Add("WatchdogFail", 1) log.Errorf("Error notifying for dtid %s: %v", dtid, err) } }(tx) } wg.Wait() }) }
go
func (te *TxEngine) startWatchdog() { te.ticks.Start(func() { ctx, cancel := context.WithTimeout(tabletenv.LocalContext(), te.abandonAge/4) defer cancel() // Raise alerts on prepares that have been unresolved for too long. // Use 5x abandonAge to give opportunity for watchdog to resolve these. count, err := te.twoPC.CountUnresolvedRedo(ctx, time.Now().Add(-te.abandonAge*5)) if err != nil { tabletenv.InternalErrors.Add("WatchdogFail", 1) log.Errorf("Error reading unresolved prepares: '%v': %v", te.coordinatorAddress, err) } tabletenv.Unresolved.Set("Prepares", count) // Resolve lingering distributed transactions. txs, err := te.twoPC.ReadAbandoned(ctx, time.Now().Add(-te.abandonAge)) if err != nil { tabletenv.InternalErrors.Add("WatchdogFail", 1) log.Errorf("Error reading transactions for 2pc watchdog: %v", err) return } if len(txs) == 0 { return } coordConn, err := vtgateconn.Dial(ctx, te.coordinatorAddress) if err != nil { tabletenv.InternalErrors.Add("WatchdogFail", 1) log.Errorf("Error connecting to coordinator '%v': %v", te.coordinatorAddress, err) return } defer coordConn.Close() var wg sync.WaitGroup for tx := range txs { wg.Add(1) go func(dtid string) { defer wg.Done() if err := coordConn.ResolveTransaction(ctx, dtid); err != nil { tabletenv.InternalErrors.Add("WatchdogFail", 1) log.Errorf("Error notifying for dtid %s: %v", dtid, err) } }(tx) } wg.Wait() }) }
[ "func", "(", "te", "*", "TxEngine", ")", "startWatchdog", "(", ")", "{", "te", ".", "ticks", ".", "Start", "(", "func", "(", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "tabletenv", ".", "LocalContext", "(", ")", ",", "te", ".", "abandonAge", "/", "4", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "// Raise alerts on prepares that have been unresolved for too long.", "// Use 5x abandonAge to give opportunity for watchdog to resolve these.", "count", ",", "err", ":=", "te", ".", "twoPC", ".", "CountUnresolvedRedo", "(", "ctx", ",", "time", ".", "Now", "(", ")", ".", "Add", "(", "-", "te", ".", "abandonAge", "*", "5", ")", ")", "\n", "if", "err", "!=", "nil", "{", "tabletenv", ".", "InternalErrors", ".", "Add", "(", "\"", "\"", ",", "1", ")", "\n", "log", ".", "Errorf", "(", "\"", "\"", ",", "te", ".", "coordinatorAddress", ",", "err", ")", "\n", "}", "\n", "tabletenv", ".", "Unresolved", ".", "Set", "(", "\"", "\"", ",", "count", ")", "\n\n", "// Resolve lingering distributed transactions.", "txs", ",", "err", ":=", "te", ".", "twoPC", ".", "ReadAbandoned", "(", "ctx", ",", "time", ".", "Now", "(", ")", ".", "Add", "(", "-", "te", ".", "abandonAge", ")", ")", "\n", "if", "err", "!=", "nil", "{", "tabletenv", ".", "InternalErrors", ".", "Add", "(", "\"", "\"", ",", "1", ")", "\n", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "len", "(", "txs", ")", "==", "0", "{", "return", "\n", "}", "\n\n", "coordConn", ",", "err", ":=", "vtgateconn", ".", "Dial", "(", "ctx", ",", "te", ".", "coordinatorAddress", ")", "\n", "if", "err", "!=", "nil", "{", "tabletenv", ".", "InternalErrors", ".", "Add", "(", "\"", "\"", ",", "1", ")", "\n", "log", ".", "Errorf", "(", "\"", "\"", ",", "te", ".", "coordinatorAddress", ",", "err", ")", "\n", "return", "\n", "}", "\n", "defer", "coordConn", ".", "Close", "(", ")", "\n\n", "var", "wg", "sync", ".", "WaitGroup", "\n", "for", "tx", ":=", "range", "txs", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "dtid", "string", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "if", "err", ":=", "coordConn", ".", "ResolveTransaction", "(", "ctx", ",", "dtid", ")", ";", "err", "!=", "nil", "{", "tabletenv", ".", "InternalErrors", ".", "Add", "(", "\"", "\"", ",", "1", ")", "\n", "log", ".", "Errorf", "(", "\"", "\"", ",", "dtid", ",", "err", ")", "\n", "}", "\n", "}", "(", "tx", ")", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "}", ")", "\n", "}" ]
// startWatchdog starts the watchdog goroutine, which looks for abandoned // transactions and calls the notifier on them.
[ "startWatchdog", "starts", "the", "watchdog", "goroutine", "which", "looks", "for", "abandoned", "transactions", "and", "calls", "the", "notifier", "on", "them", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_engine.go#L540-L586
157,857
vitessio/vitess
go/vt/vtgate/tx_conn.go
NewTxConn
func NewTxConn(gw gateway.Gateway, txMode vtgatepb.TransactionMode) *TxConn { return &TxConn{ gateway: gw, mode: txMode, } }
go
func NewTxConn(gw gateway.Gateway, txMode vtgatepb.TransactionMode) *TxConn { return &TxConn{ gateway: gw, mode: txMode, } }
[ "func", "NewTxConn", "(", "gw", "gateway", ".", "Gateway", ",", "txMode", "vtgatepb", ".", "TransactionMode", ")", "*", "TxConn", "{", "return", "&", "TxConn", "{", "gateway", ":", "gw", ",", "mode", ":", "txMode", ",", "}", "\n", "}" ]
// NewTxConn builds a new TxConn.
[ "NewTxConn", "builds", "a", "new", "TxConn", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/tx_conn.go#L42-L47
157,858
vitessio/vitess
go/vt/vtgate/tx_conn.go
Begin
func (txc *TxConn) Begin(ctx context.Context, session *SafeSession) error { if session.InTransaction() { if err := txc.Commit(ctx, session); err != nil { return err } } // UNSPECIFIED & SINGLE mode are always allowed. switch session.TransactionMode { case vtgatepb.TransactionMode_MULTI: if txc.mode == vtgatepb.TransactionMode_SINGLE { return vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "requested transaction mode %v disallowed: vtgate must be started with --transaction_mode=MULTI (or TWOPC). Current transaction mode: %v", session.TransactionMode, txc.mode) } case vtgatepb.TransactionMode_TWOPC: if txc.mode != vtgatepb.TransactionMode_TWOPC { return vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "requested transaction mode %v disallowed: vtgate must be started with --transaction_mode=TWOPC. Current transaction mode: %v", session.TransactionMode, txc.mode) } } session.Session.InTransaction = true return nil }
go
func (txc *TxConn) Begin(ctx context.Context, session *SafeSession) error { if session.InTransaction() { if err := txc.Commit(ctx, session); err != nil { return err } } // UNSPECIFIED & SINGLE mode are always allowed. switch session.TransactionMode { case vtgatepb.TransactionMode_MULTI: if txc.mode == vtgatepb.TransactionMode_SINGLE { return vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "requested transaction mode %v disallowed: vtgate must be started with --transaction_mode=MULTI (or TWOPC). Current transaction mode: %v", session.TransactionMode, txc.mode) } case vtgatepb.TransactionMode_TWOPC: if txc.mode != vtgatepb.TransactionMode_TWOPC { return vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "requested transaction mode %v disallowed: vtgate must be started with --transaction_mode=TWOPC. Current transaction mode: %v", session.TransactionMode, txc.mode) } } session.Session.InTransaction = true return nil }
[ "func", "(", "txc", "*", "TxConn", ")", "Begin", "(", "ctx", "context", ".", "Context", ",", "session", "*", "SafeSession", ")", "error", "{", "if", "session", ".", "InTransaction", "(", ")", "{", "if", "err", ":=", "txc", ".", "Commit", "(", "ctx", ",", "session", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "// UNSPECIFIED & SINGLE mode are always allowed.", "switch", "session", ".", "TransactionMode", "{", "case", "vtgatepb", ".", "TransactionMode_MULTI", ":", "if", "txc", ".", "mode", "==", "vtgatepb", ".", "TransactionMode_SINGLE", "{", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_FAILED_PRECONDITION", ",", "\"", "\"", ",", "session", ".", "TransactionMode", ",", "txc", ".", "mode", ")", "\n", "}", "\n", "case", "vtgatepb", ".", "TransactionMode_TWOPC", ":", "if", "txc", ".", "mode", "!=", "vtgatepb", ".", "TransactionMode_TWOPC", "{", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_FAILED_PRECONDITION", ",", "\"", "\"", ",", "session", ".", "TransactionMode", ",", "txc", ".", "mode", ")", "\n", "}", "\n", "}", "\n", "session", ".", "Session", ".", "InTransaction", "=", "true", "\n", "return", "nil", "\n", "}" ]
// Begin begins a new transaction. If one is already in progress, it commmits it // and starts a new one.
[ "Begin", "begins", "a", "new", "transaction", ".", "If", "one", "is", "already", "in", "progress", "it", "commmits", "it", "and", "starts", "a", "new", "one", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/tx_conn.go#L51-L70
157,859
vitessio/vitess
go/vt/vtgate/tx_conn.go
Commit
func (txc *TxConn) Commit(ctx context.Context, session *SafeSession) error { defer session.Reset() if !session.InTransaction() { return nil } twopc := false switch session.TransactionMode { case vtgatepb.TransactionMode_TWOPC: if txc.mode != vtgatepb.TransactionMode_TWOPC { txc.Rollback(ctx, session) return vterrors.New(vtrpcpb.Code_FAILED_PRECONDITION, "2pc transaction disallowed") } twopc = true case vtgatepb.TransactionMode_UNSPECIFIED: twopc = (txc.mode == vtgatepb.TransactionMode_TWOPC) } if twopc { return txc.commit2PC(ctx, session) } return txc.commitNormal(ctx, session) }
go
func (txc *TxConn) Commit(ctx context.Context, session *SafeSession) error { defer session.Reset() if !session.InTransaction() { return nil } twopc := false switch session.TransactionMode { case vtgatepb.TransactionMode_TWOPC: if txc.mode != vtgatepb.TransactionMode_TWOPC { txc.Rollback(ctx, session) return vterrors.New(vtrpcpb.Code_FAILED_PRECONDITION, "2pc transaction disallowed") } twopc = true case vtgatepb.TransactionMode_UNSPECIFIED: twopc = (txc.mode == vtgatepb.TransactionMode_TWOPC) } if twopc { return txc.commit2PC(ctx, session) } return txc.commitNormal(ctx, session) }
[ "func", "(", "txc", "*", "TxConn", ")", "Commit", "(", "ctx", "context", ".", "Context", ",", "session", "*", "SafeSession", ")", "error", "{", "defer", "session", ".", "Reset", "(", ")", "\n", "if", "!", "session", ".", "InTransaction", "(", ")", "{", "return", "nil", "\n", "}", "\n\n", "twopc", ":=", "false", "\n", "switch", "session", ".", "TransactionMode", "{", "case", "vtgatepb", ".", "TransactionMode_TWOPC", ":", "if", "txc", ".", "mode", "!=", "vtgatepb", ".", "TransactionMode_TWOPC", "{", "txc", ".", "Rollback", "(", "ctx", ",", "session", ")", "\n", "return", "vterrors", ".", "New", "(", "vtrpcpb", ".", "Code_FAILED_PRECONDITION", ",", "\"", "\"", ")", "\n", "}", "\n", "twopc", "=", "true", "\n", "case", "vtgatepb", ".", "TransactionMode_UNSPECIFIED", ":", "twopc", "=", "(", "txc", ".", "mode", "==", "vtgatepb", ".", "TransactionMode_TWOPC", ")", "\n", "}", "\n", "if", "twopc", "{", "return", "txc", ".", "commit2PC", "(", "ctx", ",", "session", ")", "\n", "}", "\n", "return", "txc", ".", "commitNormal", "(", "ctx", ",", "session", ")", "\n", "}" ]
// Commit commits the current transaction. The type of commit can be // best effort or 2pc depending on the session setting.
[ "Commit", "commits", "the", "current", "transaction", ".", "The", "type", "of", "commit", "can", "be", "best", "effort", "or", "2pc", "depending", "on", "the", "session", "setting", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/tx_conn.go#L74-L95
157,860
vitessio/vitess
go/vt/vtgate/tx_conn.go
Rollback
func (txc *TxConn) Rollback(ctx context.Context, session *SafeSession) error { if !session.InTransaction() { return nil } defer session.Reset() return txc.runSessions(session.ShardSessions, func(s *vtgatepb.Session_ShardSession) error { return txc.gateway.Rollback(ctx, s.Target, s.TransactionId) }) }
go
func (txc *TxConn) Rollback(ctx context.Context, session *SafeSession) error { if !session.InTransaction() { return nil } defer session.Reset() return txc.runSessions(session.ShardSessions, func(s *vtgatepb.Session_ShardSession) error { return txc.gateway.Rollback(ctx, s.Target, s.TransactionId) }) }
[ "func", "(", "txc", "*", "TxConn", ")", "Rollback", "(", "ctx", "context", ".", "Context", ",", "session", "*", "SafeSession", ")", "error", "{", "if", "!", "session", ".", "InTransaction", "(", ")", "{", "return", "nil", "\n", "}", "\n", "defer", "session", ".", "Reset", "(", ")", "\n\n", "return", "txc", ".", "runSessions", "(", "session", ".", "ShardSessions", ",", "func", "(", "s", "*", "vtgatepb", ".", "Session_ShardSession", ")", "error", "{", "return", "txc", ".", "gateway", ".", "Rollback", "(", "ctx", ",", "s", ".", "Target", ",", "s", ".", "TransactionId", ")", "\n", "}", ")", "\n", "}" ]
// Rollback rolls back the current transaction. There are no retries on this operation.
[ "Rollback", "rolls", "back", "the", "current", "transaction", ".", "There", "are", "no", "retries", "on", "this", "operation", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/tx_conn.go#L160-L169
157,861
vitessio/vitess
go/vt/vtgate/tx_conn.go
Resolve
func (txc *TxConn) Resolve(ctx context.Context, dtid string) error { mmShard, err := dtids.ShardSession(dtid) if err != nil { return err } transaction, err := txc.gateway.ReadTransaction(ctx, mmShard.Target, dtid) if err != nil { return err } if transaction == nil || transaction.Dtid == "" { // It was already resolved. return nil } switch transaction.State { case querypb.TransactionState_PREPARE: // If state is PREPARE, make a decision to rollback and // fallthrough to the rollback workflow. if err := txc.gateway.SetRollback(ctx, mmShard.Target, transaction.Dtid, mmShard.TransactionId); err != nil { return err } fallthrough case querypb.TransactionState_ROLLBACK: if err := txc.resumeRollback(ctx, mmShard.Target, transaction); err != nil { return err } case querypb.TransactionState_COMMIT: if err := txc.resumeCommit(ctx, mmShard.Target, transaction); err != nil { return err } default: // Should never happen. return vterrors.Errorf(vtrpcpb.Code_INTERNAL, "invalid state: %v", transaction.State) } return nil }
go
func (txc *TxConn) Resolve(ctx context.Context, dtid string) error { mmShard, err := dtids.ShardSession(dtid) if err != nil { return err } transaction, err := txc.gateway.ReadTransaction(ctx, mmShard.Target, dtid) if err != nil { return err } if transaction == nil || transaction.Dtid == "" { // It was already resolved. return nil } switch transaction.State { case querypb.TransactionState_PREPARE: // If state is PREPARE, make a decision to rollback and // fallthrough to the rollback workflow. if err := txc.gateway.SetRollback(ctx, mmShard.Target, transaction.Dtid, mmShard.TransactionId); err != nil { return err } fallthrough case querypb.TransactionState_ROLLBACK: if err := txc.resumeRollback(ctx, mmShard.Target, transaction); err != nil { return err } case querypb.TransactionState_COMMIT: if err := txc.resumeCommit(ctx, mmShard.Target, transaction); err != nil { return err } default: // Should never happen. return vterrors.Errorf(vtrpcpb.Code_INTERNAL, "invalid state: %v", transaction.State) } return nil }
[ "func", "(", "txc", "*", "TxConn", ")", "Resolve", "(", "ctx", "context", ".", "Context", ",", "dtid", "string", ")", "error", "{", "mmShard", ",", "err", ":=", "dtids", ".", "ShardSession", "(", "dtid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "transaction", ",", "err", ":=", "txc", ".", "gateway", ".", "ReadTransaction", "(", "ctx", ",", "mmShard", ".", "Target", ",", "dtid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "transaction", "==", "nil", "||", "transaction", ".", "Dtid", "==", "\"", "\"", "{", "// It was already resolved.", "return", "nil", "\n", "}", "\n", "switch", "transaction", ".", "State", "{", "case", "querypb", ".", "TransactionState_PREPARE", ":", "// If state is PREPARE, make a decision to rollback and", "// fallthrough to the rollback workflow.", "if", "err", ":=", "txc", ".", "gateway", ".", "SetRollback", "(", "ctx", ",", "mmShard", ".", "Target", ",", "transaction", ".", "Dtid", ",", "mmShard", ".", "TransactionId", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "fallthrough", "\n", "case", "querypb", ".", "TransactionState_ROLLBACK", ":", "if", "err", ":=", "txc", ".", "resumeRollback", "(", "ctx", ",", "mmShard", ".", "Target", ",", "transaction", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "querypb", ".", "TransactionState_COMMIT", ":", "if", "err", ":=", "txc", ".", "resumeCommit", "(", "ctx", ",", "mmShard", ".", "Target", ",", "transaction", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "default", ":", "// Should never happen.", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INTERNAL", ",", "\"", "\"", ",", "transaction", ".", "State", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Resolve resolves the specified 2PC transaction.
[ "Resolve", "resolves", "the", "specified", "2PC", "transaction", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/tx_conn.go#L172-L207
157,862
vitessio/vitess
go/vt/vtgate/tx_conn.go
runSessions
func (txc *TxConn) runSessions(shardSessions []*vtgatepb.Session_ShardSession, action func(*vtgatepb.Session_ShardSession) error) error { // Fastpath. if len(shardSessions) == 1 { return action(shardSessions[0]) } allErrors := new(concurrency.AllErrorRecorder) var wg sync.WaitGroup for _, s := range shardSessions { wg.Add(1) go func(s *vtgatepb.Session_ShardSession) { defer wg.Done() if err := action(s); err != nil { allErrors.RecordError(err) } }(s) } wg.Wait() return allErrors.AggrError(vterrors.Aggregate) }
go
func (txc *TxConn) runSessions(shardSessions []*vtgatepb.Session_ShardSession, action func(*vtgatepb.Session_ShardSession) error) error { // Fastpath. if len(shardSessions) == 1 { return action(shardSessions[0]) } allErrors := new(concurrency.AllErrorRecorder) var wg sync.WaitGroup for _, s := range shardSessions { wg.Add(1) go func(s *vtgatepb.Session_ShardSession) { defer wg.Done() if err := action(s); err != nil { allErrors.RecordError(err) } }(s) } wg.Wait() return allErrors.AggrError(vterrors.Aggregate) }
[ "func", "(", "txc", "*", "TxConn", ")", "runSessions", "(", "shardSessions", "[", "]", "*", "vtgatepb", ".", "Session_ShardSession", ",", "action", "func", "(", "*", "vtgatepb", ".", "Session_ShardSession", ")", "error", ")", "error", "{", "// Fastpath.", "if", "len", "(", "shardSessions", ")", "==", "1", "{", "return", "action", "(", "shardSessions", "[", "0", "]", ")", "\n", "}", "\n\n", "allErrors", ":=", "new", "(", "concurrency", ".", "AllErrorRecorder", ")", "\n", "var", "wg", "sync", ".", "WaitGroup", "\n", "for", "_", ",", "s", ":=", "range", "shardSessions", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "s", "*", "vtgatepb", ".", "Session_ShardSession", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "if", "err", ":=", "action", "(", "s", ")", ";", "err", "!=", "nil", "{", "allErrors", ".", "RecordError", "(", "err", ")", "\n", "}", "\n", "}", "(", "s", ")", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "return", "allErrors", ".", "AggrError", "(", "vterrors", ".", "Aggregate", ")", "\n", "}" ]
// runSessions executes the action for all shardSessions in parallel and returns a consolildated error.
[ "runSessions", "executes", "the", "action", "for", "all", "shardSessions", "in", "parallel", "and", "returns", "a", "consolildated", "error", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/tx_conn.go#L230-L249
157,863
vitessio/vitess
go/vt/vtgate/tx_conn.go
runTargets
func (txc *TxConn) runTargets(targets []*querypb.Target, action func(*querypb.Target) error) error { if len(targets) == 1 { return action(targets[0]) } allErrors := new(concurrency.AllErrorRecorder) var wg sync.WaitGroup for _, t := range targets { wg.Add(1) go func(t *querypb.Target) { defer wg.Done() if err := action(t); err != nil { allErrors.RecordError(err) } }(t) } wg.Wait() return allErrors.AggrError(vterrors.Aggregate) }
go
func (txc *TxConn) runTargets(targets []*querypb.Target, action func(*querypb.Target) error) error { if len(targets) == 1 { return action(targets[0]) } allErrors := new(concurrency.AllErrorRecorder) var wg sync.WaitGroup for _, t := range targets { wg.Add(1) go func(t *querypb.Target) { defer wg.Done() if err := action(t); err != nil { allErrors.RecordError(err) } }(t) } wg.Wait() return allErrors.AggrError(vterrors.Aggregate) }
[ "func", "(", "txc", "*", "TxConn", ")", "runTargets", "(", "targets", "[", "]", "*", "querypb", ".", "Target", ",", "action", "func", "(", "*", "querypb", ".", "Target", ")", "error", ")", "error", "{", "if", "len", "(", "targets", ")", "==", "1", "{", "return", "action", "(", "targets", "[", "0", "]", ")", "\n", "}", "\n", "allErrors", ":=", "new", "(", "concurrency", ".", "AllErrorRecorder", ")", "\n", "var", "wg", "sync", ".", "WaitGroup", "\n", "for", "_", ",", "t", ":=", "range", "targets", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "t", "*", "querypb", ".", "Target", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "if", "err", ":=", "action", "(", "t", ")", ";", "err", "!=", "nil", "{", "allErrors", ".", "RecordError", "(", "err", ")", "\n", "}", "\n", "}", "(", "t", ")", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "return", "allErrors", ".", "AggrError", "(", "vterrors", ".", "Aggregate", ")", "\n", "}" ]
// runTargets executes the action for all targets in parallel and returns a consolildated error. // Flow is identical to runSessions.
[ "runTargets", "executes", "the", "action", "for", "all", "targets", "in", "parallel", "and", "returns", "a", "consolildated", "error", ".", "Flow", "is", "identical", "to", "runSessions", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/tx_conn.go#L253-L270
157,864
vitessio/vitess
go/vt/vttablet/tabletmanager/action_agent.go
NewComboActionAgent
func NewComboActionAgent(batchCtx context.Context, ts *topo.Server, tabletAlias *topodatapb.TabletAlias, vtPort, grpcPort int32, queryServiceControl tabletserver.Controller, dbcfgs *dbconfigs.DBConfigs, mysqlDaemon mysqlctl.MysqlDaemon, keyspace, shard, dbname, tabletType string) *ActionAgent { agent := &ActionAgent{ QueryServiceControl: queryServiceControl, UpdateStream: binlog.NewUpdateStreamControlMock(), HealthReporter: health.DefaultAggregator, batchCtx: batchCtx, TopoServer: ts, TabletAlias: tabletAlias, Cnf: nil, MysqlDaemon: mysqlDaemon, DBConfigs: dbcfgs, VREngine: vreplication.NewEngine(nil, "", nil, nil, ""), gotMysqlPort: true, History: history.New(historyLength), _healthy: fmt.Errorf("healthcheck not run yet"), } agent.registerQueryRuleSources() // Initialize the tablet. *initDbNameOverride = dbname *initKeyspace = keyspace *initShard = shard *initTabletType = tabletType if err := agent.InitTablet(vtPort, grpcPort); err != nil { panic(vterrors.Wrap(err, "agent.InitTablet failed")) } // Start the agent. if err := agent.Start(batchCtx, "", 0, vtPort, grpcPort, false); err != nil { panic(vterrors.Wrapf(err, "agent.Start(%v) failed", tabletAlias)) } // And update our running state (need to take the Action lock). if err := agent.lock(batchCtx); err != nil { panic(vterrors.Wrap(err, "agent.lock() failed")) } defer agent.unlock() if err := agent.refreshTablet(batchCtx, "Start"); err != nil { panic(vterrors.Wrapf(err, "agent.refreshTablet(%v) failed", tabletAlias)) } return agent }
go
func NewComboActionAgent(batchCtx context.Context, ts *topo.Server, tabletAlias *topodatapb.TabletAlias, vtPort, grpcPort int32, queryServiceControl tabletserver.Controller, dbcfgs *dbconfigs.DBConfigs, mysqlDaemon mysqlctl.MysqlDaemon, keyspace, shard, dbname, tabletType string) *ActionAgent { agent := &ActionAgent{ QueryServiceControl: queryServiceControl, UpdateStream: binlog.NewUpdateStreamControlMock(), HealthReporter: health.DefaultAggregator, batchCtx: batchCtx, TopoServer: ts, TabletAlias: tabletAlias, Cnf: nil, MysqlDaemon: mysqlDaemon, DBConfigs: dbcfgs, VREngine: vreplication.NewEngine(nil, "", nil, nil, ""), gotMysqlPort: true, History: history.New(historyLength), _healthy: fmt.Errorf("healthcheck not run yet"), } agent.registerQueryRuleSources() // Initialize the tablet. *initDbNameOverride = dbname *initKeyspace = keyspace *initShard = shard *initTabletType = tabletType if err := agent.InitTablet(vtPort, grpcPort); err != nil { panic(vterrors.Wrap(err, "agent.InitTablet failed")) } // Start the agent. if err := agent.Start(batchCtx, "", 0, vtPort, grpcPort, false); err != nil { panic(vterrors.Wrapf(err, "agent.Start(%v) failed", tabletAlias)) } // And update our running state (need to take the Action lock). if err := agent.lock(batchCtx); err != nil { panic(vterrors.Wrap(err, "agent.lock() failed")) } defer agent.unlock() if err := agent.refreshTablet(batchCtx, "Start"); err != nil { panic(vterrors.Wrapf(err, "agent.refreshTablet(%v) failed", tabletAlias)) } return agent }
[ "func", "NewComboActionAgent", "(", "batchCtx", "context", ".", "Context", ",", "ts", "*", "topo", ".", "Server", ",", "tabletAlias", "*", "topodatapb", ".", "TabletAlias", ",", "vtPort", ",", "grpcPort", "int32", ",", "queryServiceControl", "tabletserver", ".", "Controller", ",", "dbcfgs", "*", "dbconfigs", ".", "DBConfigs", ",", "mysqlDaemon", "mysqlctl", ".", "MysqlDaemon", ",", "keyspace", ",", "shard", ",", "dbname", ",", "tabletType", "string", ")", "*", "ActionAgent", "{", "agent", ":=", "&", "ActionAgent", "{", "QueryServiceControl", ":", "queryServiceControl", ",", "UpdateStream", ":", "binlog", ".", "NewUpdateStreamControlMock", "(", ")", ",", "HealthReporter", ":", "health", ".", "DefaultAggregator", ",", "batchCtx", ":", "batchCtx", ",", "TopoServer", ":", "ts", ",", "TabletAlias", ":", "tabletAlias", ",", "Cnf", ":", "nil", ",", "MysqlDaemon", ":", "mysqlDaemon", ",", "DBConfigs", ":", "dbcfgs", ",", "VREngine", ":", "vreplication", ".", "NewEngine", "(", "nil", ",", "\"", "\"", ",", "nil", ",", "nil", ",", "\"", "\"", ")", ",", "gotMysqlPort", ":", "true", ",", "History", ":", "history", ".", "New", "(", "historyLength", ")", ",", "_healthy", ":", "fmt", ".", "Errorf", "(", "\"", "\"", ")", ",", "}", "\n", "agent", ".", "registerQueryRuleSources", "(", ")", "\n\n", "// Initialize the tablet.", "*", "initDbNameOverride", "=", "dbname", "\n", "*", "initKeyspace", "=", "keyspace", "\n", "*", "initShard", "=", "shard", "\n", "*", "initTabletType", "=", "tabletType", "\n", "if", "err", ":=", "agent", ".", "InitTablet", "(", "vtPort", ",", "grpcPort", ")", ";", "err", "!=", "nil", "{", "panic", "(", "vterrors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", ")", "\n", "}", "\n\n", "// Start the agent.", "if", "err", ":=", "agent", ".", "Start", "(", "batchCtx", ",", "\"", "\"", ",", "0", ",", "vtPort", ",", "grpcPort", ",", "false", ")", ";", "err", "!=", "nil", "{", "panic", "(", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "tabletAlias", ")", ")", "\n", "}", "\n\n", "// And update our running state (need to take the Action lock).", "if", "err", ":=", "agent", ".", "lock", "(", "batchCtx", ")", ";", "err", "!=", "nil", "{", "panic", "(", "vterrors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "defer", "agent", ".", "unlock", "(", ")", "\n", "if", "err", ":=", "agent", ".", "refreshTablet", "(", "batchCtx", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "panic", "(", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "tabletAlias", ")", ")", "\n", "}", "\n\n", "return", "agent", "\n", "}" ]
// NewComboActionAgent creates an agent tailored specifically to run // within the vtcombo binary. It cannot be called concurrently, // as it changes the flags.
[ "NewComboActionAgent", "creates", "an", "agent", "tailored", "specifically", "to", "run", "within", "the", "vtcombo", "binary", ".", "It", "cannot", "be", "called", "concurrently", "as", "it", "changes", "the", "flags", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/action_agent.go#L384-L426
157,865
vitessio/vitess
go/vt/vttablet/tabletmanager/action_agent.go
Healthy
func (agent *ActionAgent) Healthy() (time.Duration, error) { agent.mutex.Lock() defer agent.mutex.Unlock() healthy := agent._healthy if healthy == nil { timeSinceLastCheck := time.Since(agent._healthyTime) if timeSinceLastCheck > *healthCheckInterval*3 { healthy = fmt.Errorf("last health check is too old: %s > %s", timeSinceLastCheck, *healthCheckInterval*3) } } return agent._replicationDelay, healthy }
go
func (agent *ActionAgent) Healthy() (time.Duration, error) { agent.mutex.Lock() defer agent.mutex.Unlock() healthy := agent._healthy if healthy == nil { timeSinceLastCheck := time.Since(agent._healthyTime) if timeSinceLastCheck > *healthCheckInterval*3 { healthy = fmt.Errorf("last health check is too old: %s > %s", timeSinceLastCheck, *healthCheckInterval*3) } } return agent._replicationDelay, healthy }
[ "func", "(", "agent", "*", "ActionAgent", ")", "Healthy", "(", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "agent", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "agent", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "healthy", ":=", "agent", ".", "_healthy", "\n", "if", "healthy", "==", "nil", "{", "timeSinceLastCheck", ":=", "time", ".", "Since", "(", "agent", ".", "_healthyTime", ")", "\n", "if", "timeSinceLastCheck", ">", "*", "healthCheckInterval", "*", "3", "{", "healthy", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "timeSinceLastCheck", ",", "*", "healthCheckInterval", "*", "3", ")", "\n", "}", "\n", "}", "\n\n", "return", "agent", ".", "_replicationDelay", ",", "healthy", "\n", "}" ]
// Healthy reads the result of the latest healthcheck, protected by mutex. // If that status is too old, it means healthcheck hasn't run for a while, // and is probably stuck, this is not good, we're not healthy.
[ "Healthy", "reads", "the", "result", "of", "the", "latest", "healthcheck", "protected", "by", "mutex", ".", "If", "that", "status", "is", "too", "old", "it", "means", "healthcheck", "hasn", "t", "run", "for", "a", "while", "and", "is", "probably", "stuck", "this", "is", "not", "good", "we", "re", "not", "healthy", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/action_agent.go#L450-L463
157,866
vitessio/vitess
go/vt/vttablet/tabletmanager/action_agent.go
BlacklistedTables
func (agent *ActionAgent) BlacklistedTables() []string { agent.mutex.Lock() defer agent.mutex.Unlock() return agent._blacklistedTables }
go
func (agent *ActionAgent) BlacklistedTables() []string { agent.mutex.Lock() defer agent.mutex.Unlock() return agent._blacklistedTables }
[ "func", "(", "agent", "*", "ActionAgent", ")", "BlacklistedTables", "(", ")", "[", "]", "string", "{", "agent", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "agent", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "agent", ".", "_blacklistedTables", "\n", "}" ]
// BlacklistedTables returns the list of currently blacklisted tables.
[ "BlacklistedTables", "returns", "the", "list", "of", "currently", "blacklisted", "tables", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/action_agent.go#L466-L470
157,867
vitessio/vitess
go/vt/vttablet/tabletmanager/action_agent.go
DisallowQueryService
func (agent *ActionAgent) DisallowQueryService() string { agent.mutex.Lock() defer agent.mutex.Unlock() return agent._disallowQueryService }
go
func (agent *ActionAgent) DisallowQueryService() string { agent.mutex.Lock() defer agent.mutex.Unlock() return agent._disallowQueryService }
[ "func", "(", "agent", "*", "ActionAgent", ")", "DisallowQueryService", "(", ")", "string", "{", "agent", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "agent", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "agent", ".", "_disallowQueryService", "\n", "}" ]
// DisallowQueryService returns the reason the query service should be // disabled, if any.
[ "DisallowQueryService", "returns", "the", "reason", "the", "query", "service", "should", "be", "disabled", "if", "any", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/action_agent.go#L474-L478
157,868
vitessio/vitess
go/vt/vttablet/tabletmanager/action_agent.go
EnableUpdateStream
func (agent *ActionAgent) EnableUpdateStream() bool { agent.mutex.Lock() defer agent.mutex.Unlock() return agent._enableUpdateStream }
go
func (agent *ActionAgent) EnableUpdateStream() bool { agent.mutex.Lock() defer agent.mutex.Unlock() return agent._enableUpdateStream }
[ "func", "(", "agent", "*", "ActionAgent", ")", "EnableUpdateStream", "(", ")", "bool", "{", "agent", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "agent", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "agent", ".", "_enableUpdateStream", "\n", "}" ]
// EnableUpdateStream returns if we should enable update stream or not
[ "EnableUpdateStream", "returns", "if", "we", "should", "enable", "update", "stream", "or", "not" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/action_agent.go#L481-L485
157,869
vitessio/vitess
go/vt/vttablet/tabletmanager/action_agent.go
Close
func (agent *ActionAgent) Close() { // cleanup initialized fields in the tablet entry f := func(tablet *topodatapb.Tablet) error { if err := topotools.CheckOwnership(agent.initialTablet, tablet); err != nil { return err } tablet.Hostname = "" tablet.MysqlHostname = "" tablet.PortMap = nil return nil } if _, err := agent.TopoServer.UpdateTabletFields(context.Background(), agent.TabletAlias, f); err != nil { log.Warningf("Failed to update tablet record, may contain stale identifiers: %v", err) } }
go
func (agent *ActionAgent) Close() { // cleanup initialized fields in the tablet entry f := func(tablet *topodatapb.Tablet) error { if err := topotools.CheckOwnership(agent.initialTablet, tablet); err != nil { return err } tablet.Hostname = "" tablet.MysqlHostname = "" tablet.PortMap = nil return nil } if _, err := agent.TopoServer.UpdateTabletFields(context.Background(), agent.TabletAlias, f); err != nil { log.Warningf("Failed to update tablet record, may contain stale identifiers: %v", err) } }
[ "func", "(", "agent", "*", "ActionAgent", ")", "Close", "(", ")", "{", "// cleanup initialized fields in the tablet entry", "f", ":=", "func", "(", "tablet", "*", "topodatapb", ".", "Tablet", ")", "error", "{", "if", "err", ":=", "topotools", ".", "CheckOwnership", "(", "agent", ".", "initialTablet", ",", "tablet", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "tablet", ".", "Hostname", "=", "\"", "\"", "\n", "tablet", ".", "MysqlHostname", "=", "\"", "\"", "\n", "tablet", ".", "PortMap", "=", "nil", "\n", "return", "nil", "\n", "}", "\n", "if", "_", ",", "err", ":=", "agent", ".", "TopoServer", ".", "UpdateTabletFields", "(", "context", ".", "Background", "(", ")", ",", "agent", ".", "TabletAlias", ",", "f", ")", ";", "err", "!=", "nil", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// Close prepares a tablet for shutdown. First we check our tablet ownership and // then prune the tablet topology entry of all post-init fields. This prevents // stale identifiers from hanging around in topology.
[ "Close", "prepares", "a", "tablet", "for", "shutdown", ".", "First", "we", "check", "our", "tablet", "ownership", "and", "then", "prune", "the", "tablet", "topology", "entry", "of", "all", "post", "-", "init", "fields", ".", "This", "prevents", "stale", "identifiers", "from", "hanging", "around", "in", "topology", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/action_agent.go#L677-L691
157,870
vitessio/vitess
go/vt/vttablet/tabletmanager/action_agent.go
Stop
func (agent *ActionAgent) Stop() { if agent.UpdateStream != nil { agent.UpdateStream.Disable() } agent.VREngine.Close() if agent.MysqlDaemon != nil { agent.MysqlDaemon.Close() } }
go
func (agent *ActionAgent) Stop() { if agent.UpdateStream != nil { agent.UpdateStream.Disable() } agent.VREngine.Close() if agent.MysqlDaemon != nil { agent.MysqlDaemon.Close() } }
[ "func", "(", "agent", "*", "ActionAgent", ")", "Stop", "(", ")", "{", "if", "agent", ".", "UpdateStream", "!=", "nil", "{", "agent", ".", "UpdateStream", ".", "Disable", "(", ")", "\n", "}", "\n", "agent", ".", "VREngine", ".", "Close", "(", ")", "\n", "if", "agent", ".", "MysqlDaemon", "!=", "nil", "{", "agent", ".", "MysqlDaemon", ".", "Close", "(", ")", "\n", "}", "\n", "}" ]
// Stop shuts down the agent. Normally this is not necessary, since we use // servenv OnTerm and OnClose hooks to coordinate shutdown automatically, // while taking lameduck into account. However, this may be useful for tests, // when you want to clean up an agent immediately.
[ "Stop", "shuts", "down", "the", "agent", ".", "Normally", "this", "is", "not", "necessary", "since", "we", "use", "servenv", "OnTerm", "and", "OnClose", "hooks", "to", "coordinate", "shutdown", "automatically", "while", "taking", "lameduck", "into", "account", ".", "However", "this", "may", "be", "useful", "for", "tests", "when", "you", "want", "to", "clean", "up", "an", "agent", "immediately", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/action_agent.go#L697-L705
157,871
vitessio/vitess
go/vt/vttablet/tabletmanager/action_agent.go
hookExtraEnv
func (agent *ActionAgent) hookExtraEnv() map[string]string { return map[string]string{"TABLET_ALIAS": topoproto.TabletAliasString(agent.TabletAlias)} }
go
func (agent *ActionAgent) hookExtraEnv() map[string]string { return map[string]string{"TABLET_ALIAS": topoproto.TabletAliasString(agent.TabletAlias)} }
[ "func", "(", "agent", "*", "ActionAgent", ")", "hookExtraEnv", "(", ")", "map", "[", "string", "]", "string", "{", "return", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "topoproto", ".", "TabletAliasString", "(", "agent", ".", "TabletAlias", ")", "}", "\n", "}" ]
// hookExtraEnv returns the map to pass to local hooks
[ "hookExtraEnv", "returns", "the", "map", "to", "pass", "to", "local", "hooks" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/action_agent.go#L708-L710
157,872
vitessio/vitess
go/vt/vttablet/tabletmanager/action_agent.go
checkTabletMysqlPort
func (agent *ActionAgent) checkTabletMysqlPort(ctx context.Context, tablet *topodatapb.Tablet) *topodatapb.Tablet { agent.checkLock() mport, err := agent.MysqlDaemon.GetMysqlPort() if err != nil { // Only log the first time, so we don't spam the logs. if !agent.waitingForMysql { log.Warningf("Cannot get current mysql port, not checking it (will retry at healthcheck interval): %v", err) agent.waitingForMysql = true } return nil } if mport == topoproto.MysqlPort(tablet) { // The topology record contains the right port. // Remember we successfully checked it, and that we're // not waiting on MySQL to start any more. agent.gotMysqlPort = true agent.waitingForMysql = false return nil } // Update the port in the topology. Use a shorter timeout, so if // the topo server is busy / throttling us, we don't hang forever here. // The healthcheck go routine will try again next time. ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() if !agent.waitingForMysql { log.Warningf("MySQL port has changed from %v to %v, updating it in tablet record", topoproto.MysqlPort(tablet), mport) } newTablet, err := agent.TopoServer.UpdateTabletFields(ctx, tablet.Alias, func(t *topodatapb.Tablet) error { if err := topotools.CheckOwnership(agent.initialTablet, tablet); err != nil { return err } topoproto.SetMysqlPort(t, mport) return nil }) if err != nil { if !agent.waitingForMysql { // After this, we will try again on every // heartbeat to go through this code, but we // won't log it. log.Warningf("Failed to update tablet record, may use old mysql port: %v", err) agent.waitingForMysql = true } return nil } // Update worked, return the new record, so the agent can save it. // This should not happen often, so we can log it. log.Infof("MySQL port has changed from %v to %v, successfully updated the tablet record in topology", topoproto.MysqlPort(tablet), mport) agent.gotMysqlPort = true agent.waitingForMysql = false return newTablet }
go
func (agent *ActionAgent) checkTabletMysqlPort(ctx context.Context, tablet *topodatapb.Tablet) *topodatapb.Tablet { agent.checkLock() mport, err := agent.MysqlDaemon.GetMysqlPort() if err != nil { // Only log the first time, so we don't spam the logs. if !agent.waitingForMysql { log.Warningf("Cannot get current mysql port, not checking it (will retry at healthcheck interval): %v", err) agent.waitingForMysql = true } return nil } if mport == topoproto.MysqlPort(tablet) { // The topology record contains the right port. // Remember we successfully checked it, and that we're // not waiting on MySQL to start any more. agent.gotMysqlPort = true agent.waitingForMysql = false return nil } // Update the port in the topology. Use a shorter timeout, so if // the topo server is busy / throttling us, we don't hang forever here. // The healthcheck go routine will try again next time. ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() if !agent.waitingForMysql { log.Warningf("MySQL port has changed from %v to %v, updating it in tablet record", topoproto.MysqlPort(tablet), mport) } newTablet, err := agent.TopoServer.UpdateTabletFields(ctx, tablet.Alias, func(t *topodatapb.Tablet) error { if err := topotools.CheckOwnership(agent.initialTablet, tablet); err != nil { return err } topoproto.SetMysqlPort(t, mport) return nil }) if err != nil { if !agent.waitingForMysql { // After this, we will try again on every // heartbeat to go through this code, but we // won't log it. log.Warningf("Failed to update tablet record, may use old mysql port: %v", err) agent.waitingForMysql = true } return nil } // Update worked, return the new record, so the agent can save it. // This should not happen often, so we can log it. log.Infof("MySQL port has changed from %v to %v, successfully updated the tablet record in topology", topoproto.MysqlPort(tablet), mport) agent.gotMysqlPort = true agent.waitingForMysql = false return newTablet }
[ "func", "(", "agent", "*", "ActionAgent", ")", "checkTabletMysqlPort", "(", "ctx", "context", ".", "Context", ",", "tablet", "*", "topodatapb", ".", "Tablet", ")", "*", "topodatapb", ".", "Tablet", "{", "agent", ".", "checkLock", "(", ")", "\n", "mport", ",", "err", ":=", "agent", ".", "MysqlDaemon", ".", "GetMysqlPort", "(", ")", "\n", "if", "err", "!=", "nil", "{", "// Only log the first time, so we don't spam the logs.", "if", "!", "agent", ".", "waitingForMysql", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "agent", ".", "waitingForMysql", "=", "true", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "if", "mport", "==", "topoproto", ".", "MysqlPort", "(", "tablet", ")", "{", "// The topology record contains the right port.", "// Remember we successfully checked it, and that we're", "// not waiting on MySQL to start any more.", "agent", ".", "gotMysqlPort", "=", "true", "\n", "agent", ".", "waitingForMysql", "=", "false", "\n", "return", "nil", "\n", "}", "\n\n", "// Update the port in the topology. Use a shorter timeout, so if", "// the topo server is busy / throttling us, we don't hang forever here.", "// The healthcheck go routine will try again next time.", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "ctx", ",", "10", "*", "time", ".", "Second", ")", "\n", "defer", "cancel", "(", ")", "\n", "if", "!", "agent", ".", "waitingForMysql", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "topoproto", ".", "MysqlPort", "(", "tablet", ")", ",", "mport", ")", "\n", "}", "\n", "newTablet", ",", "err", ":=", "agent", ".", "TopoServer", ".", "UpdateTabletFields", "(", "ctx", ",", "tablet", ".", "Alias", ",", "func", "(", "t", "*", "topodatapb", ".", "Tablet", ")", "error", "{", "if", "err", ":=", "topotools", ".", "CheckOwnership", "(", "agent", ".", "initialTablet", ",", "tablet", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "topoproto", ".", "SetMysqlPort", "(", "t", ",", "mport", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "agent", ".", "waitingForMysql", "{", "// After this, we will try again on every", "// heartbeat to go through this code, but we", "// won't log it.", "log", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "agent", ".", "waitingForMysql", "=", "true", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "// Update worked, return the new record, so the agent can save it.", "// This should not happen often, so we can log it.", "log", ".", "Infof", "(", "\"", "\"", ",", "topoproto", ".", "MysqlPort", "(", "tablet", ")", ",", "mport", ")", "\n", "agent", ".", "gotMysqlPort", "=", "true", "\n", "agent", ".", "waitingForMysql", "=", "false", "\n", "return", "newTablet", "\n", "}" ]
// checkTabletMysqlPort will check the mysql port for the tablet is good, // and if not will try to update it. It returns the modified Tablet record, // if it was updated successfully in the topology server. // // We use the agent.waitingForMysql flag to log only the first // error we get when trying to get the port from MySQL, and store it in the // topology. That way we don't spam the logs. // // The actionMutex lock must be held when calling this function.
[ "checkTabletMysqlPort", "will", "check", "the", "mysql", "port", "for", "the", "tablet", "is", "good", "and", "if", "not", "will", "try", "to", "update", "it", ".", "It", "returns", "the", "modified", "Tablet", "record", "if", "it", "was", "updated", "successfully", "in", "the", "topology", "server", ".", "We", "use", "the", "agent", ".", "waitingForMysql", "flag", "to", "log", "only", "the", "first", "error", "we", "get", "when", "trying", "to", "get", "the", "port", "from", "MySQL", "and", "store", "it", "in", "the", "topology", ".", "That", "way", "we", "don", "t", "spam", "the", "logs", ".", "The", "actionMutex", "lock", "must", "be", "held", "when", "calling", "this", "function", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/action_agent.go#L721-L774
157,873
vitessio/vitess
go/sqltypes/proto3.go
ResultToProto3
func ResultToProto3(qr *Result) *querypb.QueryResult { if qr == nil { return nil } return &querypb.QueryResult{ Fields: qr.Fields, RowsAffected: qr.RowsAffected, InsertId: qr.InsertID, Rows: RowsToProto3(qr.Rows), Extras: qr.Extras, } }
go
func ResultToProto3(qr *Result) *querypb.QueryResult { if qr == nil { return nil } return &querypb.QueryResult{ Fields: qr.Fields, RowsAffected: qr.RowsAffected, InsertId: qr.InsertID, Rows: RowsToProto3(qr.Rows), Extras: qr.Extras, } }
[ "func", "ResultToProto3", "(", "qr", "*", "Result", ")", "*", "querypb", ".", "QueryResult", "{", "if", "qr", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "&", "querypb", ".", "QueryResult", "{", "Fields", ":", "qr", ".", "Fields", ",", "RowsAffected", ":", "qr", ".", "RowsAffected", ",", "InsertId", ":", "qr", ".", "InsertID", ",", "Rows", ":", "RowsToProto3", "(", "qr", ".", "Rows", ")", ",", "Extras", ":", "qr", ".", "Extras", ",", "}", "\n", "}" ]
// ResultToProto3 converts Result to proto3.
[ "ResultToProto3", "converts", "Result", "to", "proto3", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/proto3.go#L85-L96
157,874
vitessio/vitess
go/sqltypes/proto3.go
Proto3ToResult
func Proto3ToResult(qr *querypb.QueryResult) *Result { if qr == nil { return nil } return &Result{ Fields: qr.Fields, RowsAffected: qr.RowsAffected, InsertID: qr.InsertId, Rows: proto3ToRows(qr.Fields, qr.Rows), Extras: qr.Extras, } }
go
func Proto3ToResult(qr *querypb.QueryResult) *Result { if qr == nil { return nil } return &Result{ Fields: qr.Fields, RowsAffected: qr.RowsAffected, InsertID: qr.InsertId, Rows: proto3ToRows(qr.Fields, qr.Rows), Extras: qr.Extras, } }
[ "func", "Proto3ToResult", "(", "qr", "*", "querypb", ".", "QueryResult", ")", "*", "Result", "{", "if", "qr", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "&", "Result", "{", "Fields", ":", "qr", ".", "Fields", ",", "RowsAffected", ":", "qr", ".", "RowsAffected", ",", "InsertID", ":", "qr", ".", "InsertId", ",", "Rows", ":", "proto3ToRows", "(", "qr", ".", "Fields", ",", "qr", ".", "Rows", ")", ",", "Extras", ":", "qr", ".", "Extras", ",", "}", "\n", "}" ]
// Proto3ToResult converts a proto3 Result to an internal data structure. This function // should be used only if the field info is populated in qr.
[ "Proto3ToResult", "converts", "a", "proto3", "Result", "to", "an", "internal", "data", "structure", ".", "This", "function", "should", "be", "used", "only", "if", "the", "field", "info", "is", "populated", "in", "qr", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/proto3.go#L100-L111
157,875
vitessio/vitess
go/sqltypes/proto3.go
CustomProto3ToResult
func CustomProto3ToResult(fields []*querypb.Field, qr *querypb.QueryResult) *Result { if qr == nil { return nil } return &Result{ Fields: qr.Fields, RowsAffected: qr.RowsAffected, InsertID: qr.InsertId, Rows: proto3ToRows(fields, qr.Rows), Extras: qr.Extras, } }
go
func CustomProto3ToResult(fields []*querypb.Field, qr *querypb.QueryResult) *Result { if qr == nil { return nil } return &Result{ Fields: qr.Fields, RowsAffected: qr.RowsAffected, InsertID: qr.InsertId, Rows: proto3ToRows(fields, qr.Rows), Extras: qr.Extras, } }
[ "func", "CustomProto3ToResult", "(", "fields", "[", "]", "*", "querypb", ".", "Field", ",", "qr", "*", "querypb", ".", "QueryResult", ")", "*", "Result", "{", "if", "qr", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "&", "Result", "{", "Fields", ":", "qr", ".", "Fields", ",", "RowsAffected", ":", "qr", ".", "RowsAffected", ",", "InsertID", ":", "qr", ".", "InsertId", ",", "Rows", ":", "proto3ToRows", "(", "fields", ",", "qr", ".", "Rows", ")", ",", "Extras", ":", "qr", ".", "Extras", ",", "}", "\n", "}" ]
// CustomProto3ToResult converts a proto3 Result to an internal data structure. This function // takes a separate fields input because not all QueryResults contain the field info. // In particular, only the first packet of streaming queries contain the field info.
[ "CustomProto3ToResult", "converts", "a", "proto3", "Result", "to", "an", "internal", "data", "structure", ".", "This", "function", "takes", "a", "separate", "fields", "input", "because", "not", "all", "QueryResults", "contain", "the", "field", "info", ".", "In", "particular", "only", "the", "first", "packet", "of", "streaming", "queries", "contain", "the", "field", "info", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/proto3.go#L116-L127
157,876
vitessio/vitess
go/sqltypes/proto3.go
Proto3ResultsEqual
func Proto3ResultsEqual(r1, r2 []*querypb.QueryResult) bool { if len(r1) != len(r2) { return false } for i, r := range r1 { if !proto.Equal(r, r2[i]) { return false } } return true }
go
func Proto3ResultsEqual(r1, r2 []*querypb.QueryResult) bool { if len(r1) != len(r2) { return false } for i, r := range r1 { if !proto.Equal(r, r2[i]) { return false } } return true }
[ "func", "Proto3ResultsEqual", "(", "r1", ",", "r2", "[", "]", "*", "querypb", ".", "QueryResult", ")", "bool", "{", "if", "len", "(", "r1", ")", "!=", "len", "(", "r2", ")", "{", "return", "false", "\n", "}", "\n", "for", "i", ",", "r", ":=", "range", "r1", "{", "if", "!", "proto", ".", "Equal", "(", "r", ",", "r2", "[", "i", "]", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Proto3ResultsEqual compares two arrays of proto3 Result. // reflect.DeepEqual shouldn't be used because of the protos.
[ "Proto3ResultsEqual", "compares", "two", "arrays", "of", "proto3", "Result", ".", "reflect", ".", "DeepEqual", "shouldn", "t", "be", "used", "because", "of", "the", "protos", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/proto3.go#L185-L195
157,877
vitessio/vitess
go/sqltypes/proto3.go
Proto3QueryResponsesEqual
func Proto3QueryResponsesEqual(r1, r2 []*querypb.ResultWithError) bool { if len(r1) != len(r2) { return false } for i, r := range r1 { if !proto.Equal(r, r2[i]) { return false } } return true }
go
func Proto3QueryResponsesEqual(r1, r2 []*querypb.ResultWithError) bool { if len(r1) != len(r2) { return false } for i, r := range r1 { if !proto.Equal(r, r2[i]) { return false } } return true }
[ "func", "Proto3QueryResponsesEqual", "(", "r1", ",", "r2", "[", "]", "*", "querypb", ".", "ResultWithError", ")", "bool", "{", "if", "len", "(", "r1", ")", "!=", "len", "(", "r2", ")", "{", "return", "false", "\n", "}", "\n", "for", "i", ",", "r", ":=", "range", "r1", "{", "if", "!", "proto", ".", "Equal", "(", "r", ",", "r2", "[", "i", "]", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Proto3QueryResponsesEqual compares two arrays of proto3 QueryResponse. // reflect.DeepEqual shouldn't be used because of the protos.
[ "Proto3QueryResponsesEqual", "compares", "two", "arrays", "of", "proto3", "QueryResponse", ".", "reflect", ".", "DeepEqual", "shouldn", "t", "be", "used", "because", "of", "the", "protos", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/proto3.go#L199-L209
157,878
vitessio/vitess
go/sqltypes/proto3.go
Proto3ValuesEqual
func Proto3ValuesEqual(v1, v2 []*querypb.Value) bool { if len(v1) != len(v2) { return false } for i, v := range v1 { if !proto.Equal(v, v2[i]) { return false } } return true }
go
func Proto3ValuesEqual(v1, v2 []*querypb.Value) bool { if len(v1) != len(v2) { return false } for i, v := range v1 { if !proto.Equal(v, v2[i]) { return false } } return true }
[ "func", "Proto3ValuesEqual", "(", "v1", ",", "v2", "[", "]", "*", "querypb", ".", "Value", ")", "bool", "{", "if", "len", "(", "v1", ")", "!=", "len", "(", "v2", ")", "{", "return", "false", "\n", "}", "\n", "for", "i", ",", "v", ":=", "range", "v1", "{", "if", "!", "proto", ".", "Equal", "(", "v", ",", "v2", "[", "i", "]", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Proto3ValuesEqual compares two arrays of proto3 Value.
[ "Proto3ValuesEqual", "compares", "two", "arrays", "of", "proto3", "Value", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/proto3.go#L212-L222
157,879
vitessio/vitess
go/sqltypes/proto3.go
SplitQueryResponsePartsEqual
func SplitQueryResponsePartsEqual(s1, s2 []*vtgatepb.SplitQueryResponse_Part) bool { if len(s1) != len(s2) { return false } for i, s := range s1 { if !proto.Equal(s, s2[i]) { return false } } return true }
go
func SplitQueryResponsePartsEqual(s1, s2 []*vtgatepb.SplitQueryResponse_Part) bool { if len(s1) != len(s2) { return false } for i, s := range s1 { if !proto.Equal(s, s2[i]) { return false } } return true }
[ "func", "SplitQueryResponsePartsEqual", "(", "s1", ",", "s2", "[", "]", "*", "vtgatepb", ".", "SplitQueryResponse_Part", ")", "bool", "{", "if", "len", "(", "s1", ")", "!=", "len", "(", "s2", ")", "{", "return", "false", "\n", "}", "\n", "for", "i", ",", "s", ":=", "range", "s1", "{", "if", "!", "proto", ".", "Equal", "(", "s", ",", "s2", "[", "i", "]", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// SplitQueryResponsePartsEqual compares two arrays of SplitQueryResponse_Part.
[ "SplitQueryResponsePartsEqual", "compares", "two", "arrays", "of", "SplitQueryResponse_Part", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/proto3.go#L225-L235
157,880
vitessio/vitess
go/vt/sqlparser/ast.go
ParseStrictDDL
func ParseStrictDDL(sql string) (Statement, error) { tokenizer := NewStringTokenizer(sql) if yyParsePooled(tokenizer) != 0 { return nil, tokenizer.LastError } if tokenizer.ParseTree == nil { return nil, ErrEmpty } return tokenizer.ParseTree, nil }
go
func ParseStrictDDL(sql string) (Statement, error) { tokenizer := NewStringTokenizer(sql) if yyParsePooled(tokenizer) != 0 { return nil, tokenizer.LastError } if tokenizer.ParseTree == nil { return nil, ErrEmpty } return tokenizer.ParseTree, nil }
[ "func", "ParseStrictDDL", "(", "sql", "string", ")", "(", "Statement", ",", "error", ")", "{", "tokenizer", ":=", "NewStringTokenizer", "(", "sql", ")", "\n", "if", "yyParsePooled", "(", "tokenizer", ")", "!=", "0", "{", "return", "nil", ",", "tokenizer", ".", "LastError", "\n", "}", "\n", "if", "tokenizer", ".", "ParseTree", "==", "nil", "{", "return", "nil", ",", "ErrEmpty", "\n", "}", "\n", "return", "tokenizer", ".", "ParseTree", ",", "nil", "\n", "}" ]
// ParseStrictDDL is the same as Parse except it errors on // partially parsed DDL statements.
[ "ParseStrictDDL", "is", "the", "same", "as", "Parse", "except", "it", "errors", "on", "partially", "parsed", "DDL", "statements", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/ast.go#L108-L117
157,881
vitessio/vitess
go/vt/sqlparser/ast.go
SplitStatement
func SplitStatement(blob string) (string, string, error) { tokenizer := NewStringTokenizer(blob) tkn := 0 for { tkn, _ = tokenizer.Scan() if tkn == 0 || tkn == ';' || tkn == eofChar { break } } if tokenizer.LastError != nil { return "", "", tokenizer.LastError } if tkn == ';' { return blob[:tokenizer.Position-2], blob[tokenizer.Position-1:], nil } return blob, "", nil }
go
func SplitStatement(blob string) (string, string, error) { tokenizer := NewStringTokenizer(blob) tkn := 0 for { tkn, _ = tokenizer.Scan() if tkn == 0 || tkn == ';' || tkn == eofChar { break } } if tokenizer.LastError != nil { return "", "", tokenizer.LastError } if tkn == ';' { return blob[:tokenizer.Position-2], blob[tokenizer.Position-1:], nil } return blob, "", nil }
[ "func", "SplitStatement", "(", "blob", "string", ")", "(", "string", ",", "string", ",", "error", ")", "{", "tokenizer", ":=", "NewStringTokenizer", "(", "blob", ")", "\n", "tkn", ":=", "0", "\n", "for", "{", "tkn", ",", "_", "=", "tokenizer", ".", "Scan", "(", ")", "\n", "if", "tkn", "==", "0", "||", "tkn", "==", "';'", "||", "tkn", "==", "eofChar", "{", "break", "\n", "}", "\n", "}", "\n", "if", "tokenizer", ".", "LastError", "!=", "nil", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "tokenizer", ".", "LastError", "\n", "}", "\n", "if", "tkn", "==", "';'", "{", "return", "blob", "[", ":", "tokenizer", ".", "Position", "-", "2", "]", ",", "blob", "[", "tokenizer", ".", "Position", "-", "1", ":", "]", ",", "nil", "\n", "}", "\n", "return", "blob", ",", "\"", "\"", ",", "nil", "\n", "}" ]
// SplitStatement returns the first sql statement up to either a ; or EOF // and the remainder from the given buffer
[ "SplitStatement", "returns", "the", "first", "sql", "statement", "up", "to", "either", "a", ";", "or", "EOF", "and", "the", "remainder", "from", "the", "given", "buffer" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/ast.go#L169-L185
157,882
vitessio/vitess
go/vt/sqlparser/ast.go
SplitStatementToPieces
func SplitStatementToPieces(blob string) (pieces []string, err error) { pieces = make([]string, 0, 16) tokenizer := NewStringTokenizer(blob) tkn := 0 var stmt string stmtBegin := 0 for { tkn, _ = tokenizer.Scan() if tkn == ';' { stmt = blob[stmtBegin : tokenizer.Position-2] pieces = append(pieces, stmt) stmtBegin = tokenizer.Position - 1 } else if tkn == 0 || tkn == eofChar { blobTail := tokenizer.Position - 2 if stmtBegin < blobTail { stmt = blob[stmtBegin : blobTail+1] pieces = append(pieces, stmt) } break } } err = tokenizer.LastError return }
go
func SplitStatementToPieces(blob string) (pieces []string, err error) { pieces = make([]string, 0, 16) tokenizer := NewStringTokenizer(blob) tkn := 0 var stmt string stmtBegin := 0 for { tkn, _ = tokenizer.Scan() if tkn == ';' { stmt = blob[stmtBegin : tokenizer.Position-2] pieces = append(pieces, stmt) stmtBegin = tokenizer.Position - 1 } else if tkn == 0 || tkn == eofChar { blobTail := tokenizer.Position - 2 if stmtBegin < blobTail { stmt = blob[stmtBegin : blobTail+1] pieces = append(pieces, stmt) } break } } err = tokenizer.LastError return }
[ "func", "SplitStatementToPieces", "(", "blob", "string", ")", "(", "pieces", "[", "]", "string", ",", "err", "error", ")", "{", "pieces", "=", "make", "(", "[", "]", "string", ",", "0", ",", "16", ")", "\n", "tokenizer", ":=", "NewStringTokenizer", "(", "blob", ")", "\n\n", "tkn", ":=", "0", "\n", "var", "stmt", "string", "\n", "stmtBegin", ":=", "0", "\n", "for", "{", "tkn", ",", "_", "=", "tokenizer", ".", "Scan", "(", ")", "\n", "if", "tkn", "==", "';'", "{", "stmt", "=", "blob", "[", "stmtBegin", ":", "tokenizer", ".", "Position", "-", "2", "]", "\n", "pieces", "=", "append", "(", "pieces", ",", "stmt", ")", "\n", "stmtBegin", "=", "tokenizer", ".", "Position", "-", "1", "\n\n", "}", "else", "if", "tkn", "==", "0", "||", "tkn", "==", "eofChar", "{", "blobTail", ":=", "tokenizer", ".", "Position", "-", "2", "\n\n", "if", "stmtBegin", "<", "blobTail", "{", "stmt", "=", "blob", "[", "stmtBegin", ":", "blobTail", "+", "1", "]", "\n", "pieces", "=", "append", "(", "pieces", ",", "stmt", ")", "\n", "}", "\n", "break", "\n", "}", "\n", "}", "\n\n", "err", "=", "tokenizer", ".", "LastError", "\n", "return", "\n", "}" ]
// SplitStatementToPieces split raw sql statement that may have multi sql pieces to sql pieces // returns the sql pieces blob contains; or error if sql cannot be parsed
[ "SplitStatementToPieces", "split", "raw", "sql", "statement", "that", "may", "have", "multi", "sql", "pieces", "to", "sql", "pieces", "returns", "the", "sql", "pieces", "blob", "contains", ";", "or", "error", "if", "sql", "cannot", "be", "parsed" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/ast.go#L189-L216
157,883
vitessio/vitess
go/vt/sqlparser/ast.go
Walk
func Walk(visit Visit, nodes ...SQLNode) error { for _, node := range nodes { if node == nil { continue } kontinue, err := visit(node) if err != nil { return err } if kontinue { err = node.walkSubtree(visit) if err != nil { return err } } } return nil }
go
func Walk(visit Visit, nodes ...SQLNode) error { for _, node := range nodes { if node == nil { continue } kontinue, err := visit(node) if err != nil { return err } if kontinue { err = node.walkSubtree(visit) if err != nil { return err } } } return nil }
[ "func", "Walk", "(", "visit", "Visit", ",", "nodes", "...", "SQLNode", ")", "error", "{", "for", "_", ",", "node", ":=", "range", "nodes", "{", "if", "node", "==", "nil", "{", "continue", "\n", "}", "\n", "kontinue", ",", "err", ":=", "visit", "(", "node", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "kontinue", "{", "err", "=", "node", ".", "walkSubtree", "(", "visit", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Walk calls visit on every node. // If visit returns true, the underlying nodes // are also visited. If it returns an error, walking // is interrupted, and the error is returned.
[ "Walk", "calls", "visit", "on", "every", "node", ".", "If", "visit", "returns", "true", "the", "underlying", "nodes", "are", "also", "visited", ".", "If", "it", "returns", "an", "error", "walking", "is", "interrupted", "and", "the", "error", "is", "returned", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/ast.go#L236-L253
157,884
vitessio/vitess
go/vt/sqlparser/ast.go
String
func String(node SQLNode) string { if node == nil { return "<nil>" } buf := NewTrackedBuffer(nil) buf.Myprintf("%v", node) return buf.String() }
go
func String(node SQLNode) string { if node == nil { return "<nil>" } buf := NewTrackedBuffer(nil) buf.Myprintf("%v", node) return buf.String() }
[ "func", "String", "(", "node", "SQLNode", ")", "string", "{", "if", "node", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n\n", "buf", ":=", "NewTrackedBuffer", "(", "nil", ")", "\n", "buf", ".", "Myprintf", "(", "\"", "\"", ",", "node", ")", "\n", "return", "buf", ".", "String", "(", ")", "\n", "}" ]
// String returns a string representation of an SQLNode.
[ "String", "returns", "a", "string", "representation", "of", "an", "SQLNode", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/ast.go#L256-L264
157,885
vitessio/vitess
go/vt/sqlparser/ast.go
Append
func Append(buf *strings.Builder, node SQLNode) { tbuf := &TrackedBuffer{ Builder: buf, } node.Format(tbuf) }
go
func Append(buf *strings.Builder, node SQLNode) { tbuf := &TrackedBuffer{ Builder: buf, } node.Format(tbuf) }
[ "func", "Append", "(", "buf", "*", "strings", ".", "Builder", ",", "node", "SQLNode", ")", "{", "tbuf", ":=", "&", "TrackedBuffer", "{", "Builder", ":", "buf", ",", "}", "\n", "node", ".", "Format", "(", "tbuf", ")", "\n", "}" ]
// Append appends the SQLNode to the buffer.
[ "Append", "appends", "the", "SQLNode", "to", "the", "buffer", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/ast.go#L267-L272
157,886
vitessio/vitess
go/vt/sqlparser/ast.go
AddWhere
func (node *Select) AddWhere(expr Expr) { if _, ok := expr.(*OrExpr); ok { expr = &ParenExpr{Expr: expr} } if node.Where == nil { node.Where = &Where{ Type: WhereStr, Expr: expr, } return } node.Where.Expr = &AndExpr{ Left: node.Where.Expr, Right: expr, } }
go
func (node *Select) AddWhere(expr Expr) { if _, ok := expr.(*OrExpr); ok { expr = &ParenExpr{Expr: expr} } if node.Where == nil { node.Where = &Where{ Type: WhereStr, Expr: expr, } return } node.Where.Expr = &AndExpr{ Left: node.Where.Expr, Right: expr, } }
[ "func", "(", "node", "*", "Select", ")", "AddWhere", "(", "expr", "Expr", ")", "{", "if", "_", ",", "ok", ":=", "expr", ".", "(", "*", "OrExpr", ")", ";", "ok", "{", "expr", "=", "&", "ParenExpr", "{", "Expr", ":", "expr", "}", "\n", "}", "\n", "if", "node", ".", "Where", "==", "nil", "{", "node", ".", "Where", "=", "&", "Where", "{", "Type", ":", "WhereStr", ",", "Expr", ":", "expr", ",", "}", "\n", "return", "\n", "}", "\n", "node", ".", "Where", ".", "Expr", "=", "&", "AndExpr", "{", "Left", ":", "node", ".", "Where", ".", "Expr", ",", "Right", ":", "expr", ",", "}", "\n", "}" ]
// AddWhere adds the boolean expression to the // WHERE clause as an AND condition. If the expression // is an OR clause, it parenthesizes it. Currently, // the OR operator is the only one that's lower precedence // than AND.
[ "AddWhere", "adds", "the", "boolean", "expression", "to", "the", "WHERE", "clause", "as", "an", "AND", "condition", ".", "If", "the", "expression", "is", "an", "OR", "clause", "it", "parenthesizes", "it", ".", "Currently", "the", "OR", "operator", "is", "the", "only", "one", "that", "s", "lower", "precedence", "than", "AND", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/ast.go#L391-L406
157,887
vitessio/vitess
go/vt/sqlparser/ast.go
AddHaving
func (node *Select) AddHaving(expr Expr) { if _, ok := expr.(*OrExpr); ok { expr = &ParenExpr{Expr: expr} } if node.Having == nil { node.Having = &Where{ Type: HavingStr, Expr: expr, } return } node.Having.Expr = &AndExpr{ Left: node.Having.Expr, Right: expr, } }
go
func (node *Select) AddHaving(expr Expr) { if _, ok := expr.(*OrExpr); ok { expr = &ParenExpr{Expr: expr} } if node.Having == nil { node.Having = &Where{ Type: HavingStr, Expr: expr, } return } node.Having.Expr = &AndExpr{ Left: node.Having.Expr, Right: expr, } }
[ "func", "(", "node", "*", "Select", ")", "AddHaving", "(", "expr", "Expr", ")", "{", "if", "_", ",", "ok", ":=", "expr", ".", "(", "*", "OrExpr", ")", ";", "ok", "{", "expr", "=", "&", "ParenExpr", "{", "Expr", ":", "expr", "}", "\n", "}", "\n", "if", "node", ".", "Having", "==", "nil", "{", "node", ".", "Having", "=", "&", "Where", "{", "Type", ":", "HavingStr", ",", "Expr", ":", "expr", ",", "}", "\n", "return", "\n", "}", "\n", "node", ".", "Having", ".", "Expr", "=", "&", "AndExpr", "{", "Left", ":", "node", ".", "Having", ".", "Expr", ",", "Right", ":", "expr", ",", "}", "\n", "}" ]
// AddHaving adds the boolean expression to the // HAVING clause as an AND condition. If the expression // is an OR clause, it parenthesizes it. Currently, // the OR operator is the only one that's lower precedence // than AND.
[ "AddHaving", "adds", "the", "boolean", "expression", "to", "the", "HAVING", "clause", "as", "an", "AND", "condition", ".", "If", "the", "expression", "is", "an", "OR", "clause", "it", "parenthesizes", "it", ".", "Currently", "the", "OR", "operator", "is", "the", "only", "one", "that", "s", "lower", "precedence", "than", "AND", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/ast.go#L413-L428
157,888
vitessio/vitess
go/vt/sqlparser/ast.go
AffectedTables
func (node *DDL) AffectedTables() TableNames { if node.Action == RenameStr || node.Action == DropStr { list := make(TableNames, 0, len(node.FromTables)+len(node.ToTables)) list = append(list, node.FromTables...) list = append(list, node.ToTables...) return list } return TableNames{node.Table} }
go
func (node *DDL) AffectedTables() TableNames { if node.Action == RenameStr || node.Action == DropStr { list := make(TableNames, 0, len(node.FromTables)+len(node.ToTables)) list = append(list, node.FromTables...) list = append(list, node.ToTables...) return list } return TableNames{node.Table} }
[ "func", "(", "node", "*", "DDL", ")", "AffectedTables", "(", ")", "TableNames", "{", "if", "node", ".", "Action", "==", "RenameStr", "||", "node", ".", "Action", "==", "DropStr", "{", "list", ":=", "make", "(", "TableNames", ",", "0", ",", "len", "(", "node", ".", "FromTables", ")", "+", "len", "(", "node", ".", "ToTables", ")", ")", "\n", "list", "=", "append", "(", "list", ",", "node", ".", "FromTables", "...", ")", "\n", "list", "=", "append", "(", "list", ",", "node", ".", "ToTables", "...", ")", "\n", "return", "list", "\n", "}", "\n", "return", "TableNames", "{", "node", ".", "Table", "}", "\n", "}" ]
// AffectedTables returns the list table names affected by the DDL.
[ "AffectedTables", "returns", "the", "list", "table", "names", "affected", "by", "the", "DDL", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/ast.go#L834-L842
157,889
vitessio/vitess
go/vt/sqlparser/ast.go
AddColumn
func (ts *TableSpec) AddColumn(cd *ColumnDefinition) { ts.Columns = append(ts.Columns, cd) }
go
func (ts *TableSpec) AddColumn(cd *ColumnDefinition) { ts.Columns = append(ts.Columns, cd) }
[ "func", "(", "ts", "*", "TableSpec", ")", "AddColumn", "(", "cd", "*", "ColumnDefinition", ")", "{", "ts", ".", "Columns", "=", "append", "(", "ts", ".", "Columns", ",", "cd", ")", "\n", "}" ]
// AddColumn appends the given column to the list in the spec
[ "AddColumn", "appends", "the", "given", "column", "to", "the", "list", "in", "the", "spec" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/ast.go#L960-L962
157,890
vitessio/vitess
go/vt/sqlparser/ast.go
AddIndex
func (ts *TableSpec) AddIndex(id *IndexDefinition) { ts.Indexes = append(ts.Indexes, id) }
go
func (ts *TableSpec) AddIndex(id *IndexDefinition) { ts.Indexes = append(ts.Indexes, id) }
[ "func", "(", "ts", "*", "TableSpec", ")", "AddIndex", "(", "id", "*", "IndexDefinition", ")", "{", "ts", ".", "Indexes", "=", "append", "(", "ts", ".", "Indexes", ",", "id", ")", "\n", "}" ]
// AddIndex appends the given index to the list in the spec
[ "AddIndex", "appends", "the", "given", "index", "to", "the", "list", "in", "the", "spec" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/ast.go#L965-L967
157,891
vitessio/vitess
go/vt/sqlparser/ast.go
AddConstraint
func (ts *TableSpec) AddConstraint(cd *ConstraintDefinition) { ts.Constraints = append(ts.Constraints, cd) }
go
func (ts *TableSpec) AddConstraint(cd *ConstraintDefinition) { ts.Constraints = append(ts.Constraints, cd) }
[ "func", "(", "ts", "*", "TableSpec", ")", "AddConstraint", "(", "cd", "*", "ConstraintDefinition", ")", "{", "ts", ".", "Constraints", "=", "append", "(", "ts", ".", "Constraints", ",", "cd", ")", "\n", "}" ]
// AddConstraint appends the given index to the list in the spec
[ "AddConstraint", "appends", "the", "given", "index", "to", "the", "list", "in", "the", "spec" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/ast.go#L970-L972
157,892
vitessio/vitess
go/vt/sqlparser/ast.go
Format
func (ct *ColumnType) Format(buf *TrackedBuffer) { buf.Myprintf("%s", ct.Type) if ct.Length != nil && ct.Scale != nil { buf.Myprintf("(%v,%v)", ct.Length, ct.Scale) } else if ct.Length != nil { buf.Myprintf("(%v)", ct.Length) } if ct.EnumValues != nil { buf.Myprintf("(%s)", strings.Join(ct.EnumValues, ", ")) } opts := make([]string, 0, 16) if ct.Unsigned { opts = append(opts, keywordStrings[UNSIGNED]) } if ct.Zerofill { opts = append(opts, keywordStrings[ZEROFILL]) } if ct.Charset != "" { opts = append(opts, keywordStrings[CHARACTER], keywordStrings[SET], ct.Charset) } if ct.Collate != "" { opts = append(opts, keywordStrings[COLLATE], ct.Collate) } if ct.NotNull { opts = append(opts, keywordStrings[NOT], keywordStrings[NULL]) } if ct.Default != nil { opts = append(opts, keywordStrings[DEFAULT], String(ct.Default)) } if ct.OnUpdate != nil { opts = append(opts, keywordStrings[ON], keywordStrings[UPDATE], String(ct.OnUpdate)) } if ct.Autoincrement { opts = append(opts, keywordStrings[AUTO_INCREMENT]) } if ct.Comment != nil { opts = append(opts, keywordStrings[COMMENT_KEYWORD], String(ct.Comment)) } if ct.KeyOpt == colKeyPrimary { opts = append(opts, keywordStrings[PRIMARY], keywordStrings[KEY]) } if ct.KeyOpt == colKeyUnique { opts = append(opts, keywordStrings[UNIQUE]) } if ct.KeyOpt == colKeyUniqueKey { opts = append(opts, keywordStrings[UNIQUE], keywordStrings[KEY]) } if ct.KeyOpt == colKeySpatialKey { opts = append(opts, keywordStrings[SPATIAL], keywordStrings[KEY]) } if ct.KeyOpt == colKey { opts = append(opts, keywordStrings[KEY]) } if len(opts) != 0 { buf.Myprintf(" %s", strings.Join(opts, " ")) } }
go
func (ct *ColumnType) Format(buf *TrackedBuffer) { buf.Myprintf("%s", ct.Type) if ct.Length != nil && ct.Scale != nil { buf.Myprintf("(%v,%v)", ct.Length, ct.Scale) } else if ct.Length != nil { buf.Myprintf("(%v)", ct.Length) } if ct.EnumValues != nil { buf.Myprintf("(%s)", strings.Join(ct.EnumValues, ", ")) } opts := make([]string, 0, 16) if ct.Unsigned { opts = append(opts, keywordStrings[UNSIGNED]) } if ct.Zerofill { opts = append(opts, keywordStrings[ZEROFILL]) } if ct.Charset != "" { opts = append(opts, keywordStrings[CHARACTER], keywordStrings[SET], ct.Charset) } if ct.Collate != "" { opts = append(opts, keywordStrings[COLLATE], ct.Collate) } if ct.NotNull { opts = append(opts, keywordStrings[NOT], keywordStrings[NULL]) } if ct.Default != nil { opts = append(opts, keywordStrings[DEFAULT], String(ct.Default)) } if ct.OnUpdate != nil { opts = append(opts, keywordStrings[ON], keywordStrings[UPDATE], String(ct.OnUpdate)) } if ct.Autoincrement { opts = append(opts, keywordStrings[AUTO_INCREMENT]) } if ct.Comment != nil { opts = append(opts, keywordStrings[COMMENT_KEYWORD], String(ct.Comment)) } if ct.KeyOpt == colKeyPrimary { opts = append(opts, keywordStrings[PRIMARY], keywordStrings[KEY]) } if ct.KeyOpt == colKeyUnique { opts = append(opts, keywordStrings[UNIQUE]) } if ct.KeyOpt == colKeyUniqueKey { opts = append(opts, keywordStrings[UNIQUE], keywordStrings[KEY]) } if ct.KeyOpt == colKeySpatialKey { opts = append(opts, keywordStrings[SPATIAL], keywordStrings[KEY]) } if ct.KeyOpt == colKey { opts = append(opts, keywordStrings[KEY]) } if len(opts) != 0 { buf.Myprintf(" %s", strings.Join(opts, " ")) } }
[ "func", "(", "ct", "*", "ColumnType", ")", "Format", "(", "buf", "*", "TrackedBuffer", ")", "{", "buf", ".", "Myprintf", "(", "\"", "\"", ",", "ct", ".", "Type", ")", "\n\n", "if", "ct", ".", "Length", "!=", "nil", "&&", "ct", ".", "Scale", "!=", "nil", "{", "buf", ".", "Myprintf", "(", "\"", "\"", ",", "ct", ".", "Length", ",", "ct", ".", "Scale", ")", "\n\n", "}", "else", "if", "ct", ".", "Length", "!=", "nil", "{", "buf", ".", "Myprintf", "(", "\"", "\"", ",", "ct", ".", "Length", ")", "\n", "}", "\n\n", "if", "ct", ".", "EnumValues", "!=", "nil", "{", "buf", ".", "Myprintf", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "ct", ".", "EnumValues", ",", "\"", "\"", ")", ")", "\n", "}", "\n\n", "opts", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "16", ")", "\n", "if", "ct", ".", "Unsigned", "{", "opts", "=", "append", "(", "opts", ",", "keywordStrings", "[", "UNSIGNED", "]", ")", "\n", "}", "\n", "if", "ct", ".", "Zerofill", "{", "opts", "=", "append", "(", "opts", ",", "keywordStrings", "[", "ZEROFILL", "]", ")", "\n", "}", "\n", "if", "ct", ".", "Charset", "!=", "\"", "\"", "{", "opts", "=", "append", "(", "opts", ",", "keywordStrings", "[", "CHARACTER", "]", ",", "keywordStrings", "[", "SET", "]", ",", "ct", ".", "Charset", ")", "\n", "}", "\n", "if", "ct", ".", "Collate", "!=", "\"", "\"", "{", "opts", "=", "append", "(", "opts", ",", "keywordStrings", "[", "COLLATE", "]", ",", "ct", ".", "Collate", ")", "\n", "}", "\n", "if", "ct", ".", "NotNull", "{", "opts", "=", "append", "(", "opts", ",", "keywordStrings", "[", "NOT", "]", ",", "keywordStrings", "[", "NULL", "]", ")", "\n", "}", "\n", "if", "ct", ".", "Default", "!=", "nil", "{", "opts", "=", "append", "(", "opts", ",", "keywordStrings", "[", "DEFAULT", "]", ",", "String", "(", "ct", ".", "Default", ")", ")", "\n", "}", "\n", "if", "ct", ".", "OnUpdate", "!=", "nil", "{", "opts", "=", "append", "(", "opts", ",", "keywordStrings", "[", "ON", "]", ",", "keywordStrings", "[", "UPDATE", "]", ",", "String", "(", "ct", ".", "OnUpdate", ")", ")", "\n", "}", "\n", "if", "ct", ".", "Autoincrement", "{", "opts", "=", "append", "(", "opts", ",", "keywordStrings", "[", "AUTO_INCREMENT", "]", ")", "\n", "}", "\n", "if", "ct", ".", "Comment", "!=", "nil", "{", "opts", "=", "append", "(", "opts", ",", "keywordStrings", "[", "COMMENT_KEYWORD", "]", ",", "String", "(", "ct", ".", "Comment", ")", ")", "\n", "}", "\n", "if", "ct", ".", "KeyOpt", "==", "colKeyPrimary", "{", "opts", "=", "append", "(", "opts", ",", "keywordStrings", "[", "PRIMARY", "]", ",", "keywordStrings", "[", "KEY", "]", ")", "\n", "}", "\n", "if", "ct", ".", "KeyOpt", "==", "colKeyUnique", "{", "opts", "=", "append", "(", "opts", ",", "keywordStrings", "[", "UNIQUE", "]", ")", "\n", "}", "\n", "if", "ct", ".", "KeyOpt", "==", "colKeyUniqueKey", "{", "opts", "=", "append", "(", "opts", ",", "keywordStrings", "[", "UNIQUE", "]", ",", "keywordStrings", "[", "KEY", "]", ")", "\n", "}", "\n", "if", "ct", ".", "KeyOpt", "==", "colKeySpatialKey", "{", "opts", "=", "append", "(", "opts", ",", "keywordStrings", "[", "SPATIAL", "]", ",", "keywordStrings", "[", "KEY", "]", ")", "\n", "}", "\n", "if", "ct", ".", "KeyOpt", "==", "colKey", "{", "opts", "=", "append", "(", "opts", ",", "keywordStrings", "[", "KEY", "]", ")", "\n", "}", "\n\n", "if", "len", "(", "opts", ")", "!=", "0", "{", "buf", ".", "Myprintf", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "opts", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "}" ]
// Format returns a canonical string representation of the type and all relevant options
[ "Format", "returns", "a", "canonical", "string", "representation", "of", "the", "type", "and", "all", "relevant", "options" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/ast.go#L1053-L1114
157,893
vitessio/vitess
go/vt/sqlparser/ast.go
DescribeType
func (ct *ColumnType) DescribeType() string { buf := NewTrackedBuffer(nil) buf.Myprintf("%s", ct.Type) if ct.Length != nil && ct.Scale != nil { buf.Myprintf("(%v,%v)", ct.Length, ct.Scale) } else if ct.Length != nil { buf.Myprintf("(%v)", ct.Length) } opts := make([]string, 0, 16) if ct.Unsigned { opts = append(opts, keywordStrings[UNSIGNED]) } if ct.Zerofill { opts = append(opts, keywordStrings[ZEROFILL]) } if len(opts) != 0 { buf.Myprintf(" %s", strings.Join(opts, " ")) } return buf.String() }
go
func (ct *ColumnType) DescribeType() string { buf := NewTrackedBuffer(nil) buf.Myprintf("%s", ct.Type) if ct.Length != nil && ct.Scale != nil { buf.Myprintf("(%v,%v)", ct.Length, ct.Scale) } else if ct.Length != nil { buf.Myprintf("(%v)", ct.Length) } opts := make([]string, 0, 16) if ct.Unsigned { opts = append(opts, keywordStrings[UNSIGNED]) } if ct.Zerofill { opts = append(opts, keywordStrings[ZEROFILL]) } if len(opts) != 0 { buf.Myprintf(" %s", strings.Join(opts, " ")) } return buf.String() }
[ "func", "(", "ct", "*", "ColumnType", ")", "DescribeType", "(", ")", "string", "{", "buf", ":=", "NewTrackedBuffer", "(", "nil", ")", "\n", "buf", ".", "Myprintf", "(", "\"", "\"", ",", "ct", ".", "Type", ")", "\n", "if", "ct", ".", "Length", "!=", "nil", "&&", "ct", ".", "Scale", "!=", "nil", "{", "buf", ".", "Myprintf", "(", "\"", "\"", ",", "ct", ".", "Length", ",", "ct", ".", "Scale", ")", "\n", "}", "else", "if", "ct", ".", "Length", "!=", "nil", "{", "buf", ".", "Myprintf", "(", "\"", "\"", ",", "ct", ".", "Length", ")", "\n", "}", "\n\n", "opts", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "16", ")", "\n", "if", "ct", ".", "Unsigned", "{", "opts", "=", "append", "(", "opts", ",", "keywordStrings", "[", "UNSIGNED", "]", ")", "\n", "}", "\n", "if", "ct", ".", "Zerofill", "{", "opts", "=", "append", "(", "opts", ",", "keywordStrings", "[", "ZEROFILL", "]", ")", "\n", "}", "\n", "if", "len", "(", "opts", ")", "!=", "0", "{", "buf", ".", "Myprintf", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "opts", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "buf", ".", "String", "(", ")", "\n", "}" ]
// DescribeType returns the abbreviated type information as required for // describe table
[ "DescribeType", "returns", "the", "abbreviated", "type", "information", "as", "required", "for", "describe", "table" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/ast.go#L1118-L1138
157,894
vitessio/vitess
go/vt/sqlparser/ast.go
ParseParams
func (node *VindexSpec) ParseParams() (string, map[string]string) { var owner string params := map[string]string{} for _, p := range node.Params { if p.Key.Lowered() == VindexOwnerStr { owner = p.Val } else { params[p.Key.String()] = p.Val } } return owner, params }
go
func (node *VindexSpec) ParseParams() (string, map[string]string) { var owner string params := map[string]string{} for _, p := range node.Params { if p.Key.Lowered() == VindexOwnerStr { owner = p.Val } else { params[p.Key.String()] = p.Val } } return owner, params }
[ "func", "(", "node", "*", "VindexSpec", ")", "ParseParams", "(", ")", "(", "string", ",", "map", "[", "string", "]", "string", ")", "{", "var", "owner", "string", "\n", "params", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "for", "_", ",", "p", ":=", "range", "node", ".", "Params", "{", "if", "p", ".", "Key", ".", "Lowered", "(", ")", "==", "VindexOwnerStr", "{", "owner", "=", "p", ".", "Val", "\n", "}", "else", "{", "params", "[", "p", ".", "Key", ".", "String", "(", ")", "]", "=", "p", ".", "Val", "\n", "}", "\n", "}", "\n", "return", "owner", ",", "params", "\n", "}" ]
// ParseParams parses the vindex parameter list, pulling out the special-case // "owner" parameter
[ "ParseParams", "parses", "the", "vindex", "parameter", "list", "pulling", "out", "the", "special", "-", "case", "owner", "parameter" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/ast.go#L1357-L1368
157,895
vitessio/vitess
go/vt/sqlparser/ast.go
Format
func (node *VindexSpec) Format(buf *TrackedBuffer) { buf.Myprintf("using %v", node.Type) numParams := len(node.Params) if numParams != 0 { buf.Myprintf(" with ") for i, p := range node.Params { if i != 0 { buf.Myprintf(", ") } buf.Myprintf("%v", p) } } }
go
func (node *VindexSpec) Format(buf *TrackedBuffer) { buf.Myprintf("using %v", node.Type) numParams := len(node.Params) if numParams != 0 { buf.Myprintf(" with ") for i, p := range node.Params { if i != 0 { buf.Myprintf(", ") } buf.Myprintf("%v", p) } } }
[ "func", "(", "node", "*", "VindexSpec", ")", "Format", "(", "buf", "*", "TrackedBuffer", ")", "{", "buf", ".", "Myprintf", "(", "\"", "\"", ",", "node", ".", "Type", ")", "\n\n", "numParams", ":=", "len", "(", "node", ".", "Params", ")", "\n", "if", "numParams", "!=", "0", "{", "buf", ".", "Myprintf", "(", "\"", "\"", ")", "\n", "for", "i", ",", "p", ":=", "range", "node", ".", "Params", "{", "if", "i", "!=", "0", "{", "buf", ".", "Myprintf", "(", "\"", "\"", ")", "\n", "}", "\n", "buf", ".", "Myprintf", "(", "\"", "\"", ",", "p", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Format formats the node. The "CREATE VINDEX" preamble was formatted in // the containing DDL node Format, so this just prints the type, any // parameters, and optionally the owner
[ "Format", "formats", "the", "node", ".", "The", "CREATE", "VINDEX", "preamble", "was", "formatted", "in", "the", "containing", "DDL", "node", "Format", "so", "this", "just", "prints", "the", "type", "any", "parameters", "and", "optionally", "the", "owner" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/ast.go#L1373-L1386
157,896
vitessio/vitess
go/vt/sqlparser/ast.go
FindColumn
func (node Columns) FindColumn(col ColIdent) int { for i, colName := range node { if colName.Equal(col) { return i } } return -1 }
go
func (node Columns) FindColumn(col ColIdent) int { for i, colName := range node { if colName.Equal(col) { return i } } return -1 }
[ "func", "(", "node", "Columns", ")", "FindColumn", "(", "col", "ColIdent", ")", "int", "{", "for", "i", ",", "colName", ":=", "range", "node", "{", "if", "colName", ".", "Equal", "(", "col", ")", "{", "return", "i", "\n", "}", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// FindColumn finds a column in the column list, returning // the index if it exists or -1 otherwise
[ "FindColumn", "finds", "a", "column", "in", "the", "column", "list", "returning", "the", "index", "if", "it", "exists", "or", "-", "1", "otherwise" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/ast.go#L1817-L1824
157,897
vitessio/vitess
go/vt/sqlparser/ast.go
RemoveHints
func (node *AliasedTableExpr) RemoveHints() *AliasedTableExpr { noHints := *node noHints.Hints = nil return &noHints }
go
func (node *AliasedTableExpr) RemoveHints() *AliasedTableExpr { noHints := *node noHints.Hints = nil return &noHints }
[ "func", "(", "node", "*", "AliasedTableExpr", ")", "RemoveHints", "(", ")", "*", "AliasedTableExpr", "{", "noHints", ":=", "*", "node", "\n", "noHints", ".", "Hints", "=", "nil", "\n", "return", "&", "noHints", "\n", "}" ]
// RemoveHints returns a new AliasedTableExpr with the hints removed.
[ "RemoveHints", "returns", "a", "new", "AliasedTableExpr", "with", "the", "hints", "removed", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/ast.go#L1917-L1921
157,898
vitessio/vitess
go/vt/sqlparser/ast.go
ToViewName
func (node TableName) ToViewName() TableName { return TableName{ Qualifier: node.Qualifier, Name: NewTableIdent(strings.ToLower(node.Name.v)), } }
go
func (node TableName) ToViewName() TableName { return TableName{ Qualifier: node.Qualifier, Name: NewTableIdent(strings.ToLower(node.Name.v)), } }
[ "func", "(", "node", "TableName", ")", "ToViewName", "(", ")", "TableName", "{", "return", "TableName", "{", "Qualifier", ":", "node", ".", "Qualifier", ",", "Name", ":", "NewTableIdent", "(", "strings", ".", "ToLower", "(", "node", ".", "Name", ".", "v", ")", ")", ",", "}", "\n", "}" ]
// ToViewName returns a TableName acceptable for use as a VIEW. VIEW names are // always lowercase, so ToViewName lowercasese the name. Databases are case-sensitive // so Qualifier is left untouched.
[ "ToViewName", "returns", "a", "TableName", "acceptable", "for", "use", "as", "a", "VIEW", ".", "VIEW", "names", "are", "always", "lowercase", "so", "ToViewName", "lowercasese", "the", "name", ".", "Databases", "are", "case", "-", "sensitive", "so", "Qualifier", "is", "left", "untouched", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/ast.go#L1990-L1995
157,899
vitessio/vitess
go/vt/sqlparser/ast.go
ReplaceExpr
func ReplaceExpr(root, from, to Expr) Expr { if root == from { return to } root.replace(from, to) return root }
go
func ReplaceExpr(root, from, to Expr) Expr { if root == from { return to } root.replace(from, to) return root }
[ "func", "ReplaceExpr", "(", "root", ",", "from", ",", "to", "Expr", ")", "Expr", "{", "if", "root", "==", "from", "{", "return", "to", "\n", "}", "\n", "root", ".", "replace", "(", "from", ",", "to", ")", "\n", "return", "root", "\n", "}" ]
// ReplaceExpr finds the from expression from root // and replaces it with to. If from matches root, // then to is returned.
[ "ReplaceExpr", "finds", "the", "from", "expression", "from", "root", "and", "replaces", "it", "with", "to", ".", "If", "from", "matches", "root", "then", "to", "is", "returned", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/ast.go#L2197-L2203