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
4,400
juju/juju
worker/raft/rafttransport/manifold.go
Manifold
func Manifold(config ManifoldConfig) dependency.Manifold { return dependency.Manifold{ Inputs: []string{ config.ClockName, config.AgentName, config.AuthenticatorName, config.HubName, config.MuxName, }, Start: config.start, Output: transportOutput, } }
go
func Manifold(config ManifoldConfig) dependency.Manifold { return dependency.Manifold{ Inputs: []string{ config.ClockName, config.AgentName, config.AuthenticatorName, config.HubName, config.MuxName, }, Start: config.start, Output: transportOutput, } }
[ "func", "Manifold", "(", "config", "ManifoldConfig", ")", "dependency", ".", "Manifold", "{", "return", "dependency", ".", "Manifold", "{", "Inputs", ":", "[", "]", "string", "{", "config", ".", "ClockName", ",", "config", ".", "AgentName", ",", "config", ".", "AuthenticatorName", ",", "config", ".", "HubName", ",", "config", ".", "MuxName", ",", "}", ",", "Start", ":", "config", ".", "start", ",", "Output", ":", "transportOutput", ",", "}", "\n", "}" ]
// Manifold returns a dependency.Manifold that will run an apiserver-based // raft transport worker.
[ "Manifold", "returns", "a", "dependency", ".", "Manifold", "that", "will", "run", "an", "apiserver", "-", "based", "raft", "transport", "worker", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/raft/rafttransport/manifold.go#L70-L82
4,401
juju/juju
apiserver/observer/metricobserver/mocks/metrics_collector_mock.go
APIRequestDuration
func (mr *MockMetricsCollectorMockRecorder) APIRequestDuration() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "APIRequestDuration", reflect.TypeOf((*MockMetricsCollector)(nil).APIRequestDuration)) }
go
func (mr *MockMetricsCollectorMockRecorder) APIRequestDuration() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "APIRequestDuration", reflect.TypeOf((*MockMetricsCollector)(nil).APIRequestDuration)) }
[ "func", "(", "mr", "*", "MockMetricsCollectorMockRecorder", ")", "APIRequestDuration", "(", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "(", "*", "MockMetricsCollector", ")", "(", "nil", ")", ".", "APIRequestDuration", ")", ")", "\n", "}" ]
// APIRequestDuration indicates an expected call of APIRequestDuration
[ "APIRequestDuration", "indicates", "an", "expected", "call", "of", "APIRequestDuration" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/observer/metricobserver/mocks/metrics_collector_mock.go#L45-L47
4,402
juju/juju
apiserver/observer/metricobserver/mocks/metrics_collector_mock.go
DeprecatedAPIRequestDuration
func (m *MockMetricsCollector) DeprecatedAPIRequestDuration() metricobserver.SummaryVec { ret := m.ctrl.Call(m, "DeprecatedAPIRequestDuration") ret0, _ := ret[0].(metricobserver.SummaryVec) return ret0 }
go
func (m *MockMetricsCollector) DeprecatedAPIRequestDuration() metricobserver.SummaryVec { ret := m.ctrl.Call(m, "DeprecatedAPIRequestDuration") ret0, _ := ret[0].(metricobserver.SummaryVec) return ret0 }
[ "func", "(", "m", "*", "MockMetricsCollector", ")", "DeprecatedAPIRequestDuration", "(", ")", "metricobserver", ".", "SummaryVec", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "metricobserver", ".", "SummaryVec", ")", "\n", "return", "ret0", "\n", "}" ]
// DeprecatedAPIRequestDuration mocks base method
[ "DeprecatedAPIRequestDuration", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/observer/metricobserver/mocks/metrics_collector_mock.go#L50-L54
4,403
juju/juju
apiserver/observer/metricobserver/mocks/metrics_collector_mock.go
DeprecatedAPIRequestsTotal
func (m *MockMetricsCollector) DeprecatedAPIRequestsTotal() metricobserver.CounterVec { ret := m.ctrl.Call(m, "DeprecatedAPIRequestsTotal") ret0, _ := ret[0].(metricobserver.CounterVec) return ret0 }
go
func (m *MockMetricsCollector) DeprecatedAPIRequestsTotal() metricobserver.CounterVec { ret := m.ctrl.Call(m, "DeprecatedAPIRequestsTotal") ret0, _ := ret[0].(metricobserver.CounterVec) return ret0 }
[ "func", "(", "m", "*", "MockMetricsCollector", ")", "DeprecatedAPIRequestsTotal", "(", ")", "metricobserver", ".", "CounterVec", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "metricobserver", ".", "CounterVec", ")", "\n", "return", "ret0", "\n", "}" ]
// DeprecatedAPIRequestsTotal mocks base method
[ "DeprecatedAPIRequestsTotal", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/observer/metricobserver/mocks/metrics_collector_mock.go#L62-L66
4,404
juju/juju
apiserver/observer/metricobserver/mocks/metrics_collector_mock.go
NewMockCounterVec
func NewMockCounterVec(ctrl *gomock.Controller) *MockCounterVec { mock := &MockCounterVec{ctrl: ctrl} mock.recorder = &MockCounterVecMockRecorder{mock} return mock }
go
func NewMockCounterVec(ctrl *gomock.Controller) *MockCounterVec { mock := &MockCounterVec{ctrl: ctrl} mock.recorder = &MockCounterVecMockRecorder{mock} return mock }
[ "func", "NewMockCounterVec", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockCounterVec", "{", "mock", ":=", "&", "MockCounterVec", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockCounterVecMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockCounterVec creates a new mock instance
[ "NewMockCounterVec", "creates", "a", "new", "mock", "instance" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/observer/metricobserver/mocks/metrics_collector_mock.go#L85-L89
4,405
juju/juju
apiserver/observer/metricobserver/mocks/metrics_collector_mock.go
NewMockSummaryVec
func NewMockSummaryVec(ctrl *gomock.Controller) *MockSummaryVec { mock := &MockSummaryVec{ctrl: ctrl} mock.recorder = &MockSummaryVecMockRecorder{mock} return mock }
go
func NewMockSummaryVec(ctrl *gomock.Controller) *MockSummaryVec { mock := &MockSummaryVec{ctrl: ctrl} mock.recorder = &MockSummaryVecMockRecorder{mock} return mock }
[ "func", "NewMockSummaryVec", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockSummaryVec", "{", "mock", ":=", "&", "MockSummaryVec", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockSummaryVecMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockSummaryVec creates a new mock instance
[ "NewMockSummaryVec", "creates", "a", "new", "mock", "instance" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/observer/metricobserver/mocks/metrics_collector_mock.go#L120-L124
4,406
juju/juju
apiserver/resources_mig.go
processPost
func (h *resourcesMigrationUploadHandler) processPost(r *http.Request, st *state.State) (resource.Resource, error) { var empty resource.Resource query := r.URL.Query() target, isUnit, err := getUploadTarget(query) if err != nil { return empty, errors.Trace(err) } userID := query.Get("user") // Is allowed to be blank res, err := queryToResource(query) if err != nil { return empty, errors.Trace(err) } rSt, err := st.Resources() if err != nil { return empty, errors.Trace(err) } reader := r.Body // Don't associate content with a placeholder resource. if isPlaceholder(query) { reader = nil } outRes, err := setResource(isUnit, target, userID, res, reader, rSt) if err != nil { return empty, errors.Annotate(err, "resource upload failed") } return outRes, nil }
go
func (h *resourcesMigrationUploadHandler) processPost(r *http.Request, st *state.State) (resource.Resource, error) { var empty resource.Resource query := r.URL.Query() target, isUnit, err := getUploadTarget(query) if err != nil { return empty, errors.Trace(err) } userID := query.Get("user") // Is allowed to be blank res, err := queryToResource(query) if err != nil { return empty, errors.Trace(err) } rSt, err := st.Resources() if err != nil { return empty, errors.Trace(err) } reader := r.Body // Don't associate content with a placeholder resource. if isPlaceholder(query) { reader = nil } outRes, err := setResource(isUnit, target, userID, res, reader, rSt) if err != nil { return empty, errors.Annotate(err, "resource upload failed") } return outRes, nil }
[ "func", "(", "h", "*", "resourcesMigrationUploadHandler", ")", "processPost", "(", "r", "*", "http", ".", "Request", ",", "st", "*", "state", ".", "State", ")", "(", "resource", ".", "Resource", ",", "error", ")", "{", "var", "empty", "resource", ".", "Resource", "\n", "query", ":=", "r", ".", "URL", ".", "Query", "(", ")", "\n\n", "target", ",", "isUnit", ",", "err", ":=", "getUploadTarget", "(", "query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "empty", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "userID", ":=", "query", ".", "Get", "(", "\"", "\"", ")", "// Is allowed to be blank", "\n", "res", ",", "err", ":=", "queryToResource", "(", "query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "empty", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "rSt", ",", "err", ":=", "st", ".", "Resources", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "empty", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "reader", ":=", "r", ".", "Body", "\n\n", "// Don't associate content with a placeholder resource.", "if", "isPlaceholder", "(", "query", ")", "{", "reader", "=", "nil", "\n", "}", "\n\n", "outRes", ",", "err", ":=", "setResource", "(", "isUnit", ",", "target", ",", "userID", ",", "res", ",", "reader", ",", "rSt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "empty", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "outRes", ",", "nil", "\n", "}" ]
// processPost handles resources upload POST request after // authentication.
[ "processPost", "handles", "resources", "upload", "POST", "request", "after", "authentication", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/resources_mig.go#L62-L93
4,407
juju/juju
mongo/open.go
DialInfo
func DialInfo(info Info, opts DialOpts) (*mgo.DialInfo, error) { if len(info.Addrs) == 0 { return nil, stderrors.New("no mongo addresses") } var tlsConfig *tls.Config if !info.DisableTLS { if len(info.CACert) == 0 { return nil, stderrors.New("missing CA certificate") } xcert, err := cert.ParseCert(info.CACert) if err != nil { return nil, fmt.Errorf("cannot parse CA certificate: %v", err) } pool := x509.NewCertPool() pool.AddCert(xcert) tlsConfig = utils.SecureTLSConfig() tlsConfig.RootCAs = pool tlsConfig.ServerName = "juju-mongodb" // TODO(natefinch): revisit this when are full-time on mongo 3. // We have to add non-ECDHE suites because mongo doesn't support ECDHE. moreSuites := []uint16{ tls.TLS_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_RSA_WITH_AES_256_GCM_SHA384, } tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, moreSuites...) } dial := func(server *mgo.ServerAddr) (_ net.Conn, err error) { if opts.PostDialServer != nil { before := time.Now() defer func() { taken := time.Now().Sub(before) opts.PostDialServer(server.String(), taken, err) }() } addr := server.TCPAddr().String() c, err := net.DialTimeout("tcp", addr, opts.Timeout) if err != nil { logger.Warningf("mongodb connection failed, will retry: %v", err) return nil, err } if tlsConfig != nil { cc := tls.Client(c, tlsConfig) if err := cc.Handshake(); err != nil { logger.Warningf("TLS handshake failed: %v", err) if err := c.Close(); err != nil { logger.Warningf("failed to close connection: %v", err) } return nil, err } c = cc } logger.Debugf("dialled mongodb server at %q", addr) return c, nil } return &mgo.DialInfo{ Addrs: info.Addrs, Timeout: opts.Timeout, DialServer: dial, Direct: opts.Direct, PoolLimit: opts.PoolLimit, }, nil }
go
func DialInfo(info Info, opts DialOpts) (*mgo.DialInfo, error) { if len(info.Addrs) == 0 { return nil, stderrors.New("no mongo addresses") } var tlsConfig *tls.Config if !info.DisableTLS { if len(info.CACert) == 0 { return nil, stderrors.New("missing CA certificate") } xcert, err := cert.ParseCert(info.CACert) if err != nil { return nil, fmt.Errorf("cannot parse CA certificate: %v", err) } pool := x509.NewCertPool() pool.AddCert(xcert) tlsConfig = utils.SecureTLSConfig() tlsConfig.RootCAs = pool tlsConfig.ServerName = "juju-mongodb" // TODO(natefinch): revisit this when are full-time on mongo 3. // We have to add non-ECDHE suites because mongo doesn't support ECDHE. moreSuites := []uint16{ tls.TLS_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_RSA_WITH_AES_256_GCM_SHA384, } tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, moreSuites...) } dial := func(server *mgo.ServerAddr) (_ net.Conn, err error) { if opts.PostDialServer != nil { before := time.Now() defer func() { taken := time.Now().Sub(before) opts.PostDialServer(server.String(), taken, err) }() } addr := server.TCPAddr().String() c, err := net.DialTimeout("tcp", addr, opts.Timeout) if err != nil { logger.Warningf("mongodb connection failed, will retry: %v", err) return nil, err } if tlsConfig != nil { cc := tls.Client(c, tlsConfig) if err := cc.Handshake(); err != nil { logger.Warningf("TLS handshake failed: %v", err) if err := c.Close(); err != nil { logger.Warningf("failed to close connection: %v", err) } return nil, err } c = cc } logger.Debugf("dialled mongodb server at %q", addr) return c, nil } return &mgo.DialInfo{ Addrs: info.Addrs, Timeout: opts.Timeout, DialServer: dial, Direct: opts.Direct, PoolLimit: opts.PoolLimit, }, nil }
[ "func", "DialInfo", "(", "info", "Info", ",", "opts", "DialOpts", ")", "(", "*", "mgo", ".", "DialInfo", ",", "error", ")", "{", "if", "len", "(", "info", ".", "Addrs", ")", "==", "0", "{", "return", "nil", ",", "stderrors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "tlsConfig", "*", "tls", ".", "Config", "\n", "if", "!", "info", ".", "DisableTLS", "{", "if", "len", "(", "info", ".", "CACert", ")", "==", "0", "{", "return", "nil", ",", "stderrors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "xcert", ",", "err", ":=", "cert", ".", "ParseCert", "(", "info", ".", "CACert", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "pool", ":=", "x509", ".", "NewCertPool", "(", ")", "\n", "pool", ".", "AddCert", "(", "xcert", ")", "\n\n", "tlsConfig", "=", "utils", ".", "SecureTLSConfig", "(", ")", "\n", "tlsConfig", ".", "RootCAs", "=", "pool", "\n", "tlsConfig", ".", "ServerName", "=", "\"", "\"", "\n\n", "// TODO(natefinch): revisit this when are full-time on mongo 3.", "// We have to add non-ECDHE suites because mongo doesn't support ECDHE.", "moreSuites", ":=", "[", "]", "uint16", "{", "tls", ".", "TLS_RSA_WITH_AES_128_GCM_SHA256", ",", "tls", ".", "TLS_RSA_WITH_AES_256_GCM_SHA384", ",", "}", "\n", "tlsConfig", ".", "CipherSuites", "=", "append", "(", "tlsConfig", ".", "CipherSuites", ",", "moreSuites", "...", ")", "\n", "}", "\n\n", "dial", ":=", "func", "(", "server", "*", "mgo", ".", "ServerAddr", ")", "(", "_", "net", ".", "Conn", ",", "err", "error", ")", "{", "if", "opts", ".", "PostDialServer", "!=", "nil", "{", "before", ":=", "time", ".", "Now", "(", ")", "\n", "defer", "func", "(", ")", "{", "taken", ":=", "time", ".", "Now", "(", ")", ".", "Sub", "(", "before", ")", "\n", "opts", ".", "PostDialServer", "(", "server", ".", "String", "(", ")", ",", "taken", ",", "err", ")", "\n", "}", "(", ")", "\n", "}", "\n\n", "addr", ":=", "server", ".", "TCPAddr", "(", ")", ".", "String", "(", ")", "\n", "c", ",", "err", ":=", "net", ".", "DialTimeout", "(", "\"", "\"", ",", "addr", ",", "opts", ".", "Timeout", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "if", "tlsConfig", "!=", "nil", "{", "cc", ":=", "tls", ".", "Client", "(", "c", ",", "tlsConfig", ")", "\n", "if", "err", ":=", "cc", ".", "Handshake", "(", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "if", "err", ":=", "c", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "c", "=", "cc", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "addr", ")", "\n", "return", "c", ",", "nil", "\n", "}", "\n\n", "return", "&", "mgo", ".", "DialInfo", "{", "Addrs", ":", "info", ".", "Addrs", ",", "Timeout", ":", "opts", ".", "Timeout", ",", "DialServer", ":", "dial", ",", "Direct", ":", "opts", ".", "Direct", ",", "PoolLimit", ":", "opts", ".", "PoolLimit", ",", "}", ",", "nil", "\n", "}" ]
// DialInfo returns information on how to dial // the state's mongo server with the given info // and dial options.
[ "DialInfo", "returns", "information", "on", "how", "to", "dial", "the", "state", "s", "mongo", "server", "with", "the", "given", "info", "and", "dial", "options", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/mongo/open.go#L118-L185
4,408
juju/juju
mongo/open.go
DialWithInfo
func DialWithInfo(info MongoInfo, opts DialOpts) (*mgo.Session, error) { if opts.Timeout == 0 { return nil, errors.New("a non-zero Timeout must be specified") } dialInfo, err := DialInfo(info.Info, opts) if err != nil { return nil, err } session, err := mgo.DialWithInfo(dialInfo) if err != nil { return nil, err } if opts.SocketTimeout == 0 { opts.SocketTimeout = SocketTimeout } session.SetSocketTimeout(opts.SocketTimeout) if opts.PostDial != nil { if err := opts.PostDial(session); err != nil { session.Close() return nil, errors.Annotate(err, "PostDial failed") } } if info.Tag != nil || info.Password != "" { user := AdminUser if info.Tag != nil { user = info.Tag.String() } if err := Login(session, user, info.Password); err != nil { session.Close() return nil, errors.Trace(err) } } return session, nil }
go
func DialWithInfo(info MongoInfo, opts DialOpts) (*mgo.Session, error) { if opts.Timeout == 0 { return nil, errors.New("a non-zero Timeout must be specified") } dialInfo, err := DialInfo(info.Info, opts) if err != nil { return nil, err } session, err := mgo.DialWithInfo(dialInfo) if err != nil { return nil, err } if opts.SocketTimeout == 0 { opts.SocketTimeout = SocketTimeout } session.SetSocketTimeout(opts.SocketTimeout) if opts.PostDial != nil { if err := opts.PostDial(session); err != nil { session.Close() return nil, errors.Annotate(err, "PostDial failed") } } if info.Tag != nil || info.Password != "" { user := AdminUser if info.Tag != nil { user = info.Tag.String() } if err := Login(session, user, info.Password); err != nil { session.Close() return nil, errors.Trace(err) } } return session, nil }
[ "func", "DialWithInfo", "(", "info", "MongoInfo", ",", "opts", "DialOpts", ")", "(", "*", "mgo", ".", "Session", ",", "error", ")", "{", "if", "opts", ".", "Timeout", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "dialInfo", ",", "err", ":=", "DialInfo", "(", "info", ".", "Info", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "session", ",", "err", ":=", "mgo", ".", "DialWithInfo", "(", "dialInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "opts", ".", "SocketTimeout", "==", "0", "{", "opts", ".", "SocketTimeout", "=", "SocketTimeout", "\n", "}", "\n", "session", ".", "SetSocketTimeout", "(", "opts", ".", "SocketTimeout", ")", "\n\n", "if", "opts", ".", "PostDial", "!=", "nil", "{", "if", "err", ":=", "opts", ".", "PostDial", "(", "session", ")", ";", "err", "!=", "nil", "{", "session", ".", "Close", "(", ")", "\n", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "if", "info", ".", "Tag", "!=", "nil", "||", "info", ".", "Password", "!=", "\"", "\"", "{", "user", ":=", "AdminUser", "\n", "if", "info", ".", "Tag", "!=", "nil", "{", "user", "=", "info", ".", "Tag", ".", "String", "(", ")", "\n", "}", "\n", "if", "err", ":=", "Login", "(", "session", ",", "user", ",", "info", ".", "Password", ")", ";", "err", "!=", "nil", "{", "session", ".", "Close", "(", ")", "\n", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "session", ",", "nil", "\n", "}" ]
// DialWithInfo establishes a new session to the cluster identified by info, // with the specified options. If either Tag or Password are specified, then // a Login call on the admin database will be made.
[ "DialWithInfo", "establishes", "a", "new", "session", "to", "the", "cluster", "identified", "by", "info", "with", "the", "specified", "options", ".", "If", "either", "Tag", "or", "Password", "are", "specified", "then", "a", "Login", "call", "on", "the", "admin", "database", "will", "be", "made", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/mongo/open.go#L190-L227
4,409
juju/juju
mongo/open.go
Login
func Login(session *mgo.Session, user, password string) error { admin := session.DB("admin") if err := admin.Login(user, password); err != nil { return MaybeUnauthorizedf(err, "cannot log in to admin database as %q", user) } return nil }
go
func Login(session *mgo.Session, user, password string) error { admin := session.DB("admin") if err := admin.Login(user, password); err != nil { return MaybeUnauthorizedf(err, "cannot log in to admin database as %q", user) } return nil }
[ "func", "Login", "(", "session", "*", "mgo", ".", "Session", ",", "user", ",", "password", "string", ")", "error", "{", "admin", ":=", "session", ".", "DB", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "admin", ".", "Login", "(", "user", ",", "password", ")", ";", "err", "!=", "nil", "{", "return", "MaybeUnauthorizedf", "(", "err", ",", "\"", "\"", ",", "user", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Login logs in to the mongodb admin database.
[ "Login", "logs", "in", "to", "the", "mongodb", "admin", "database", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/mongo/open.go#L230-L236
4,410
juju/juju
mongo/open.go
MaybeUnauthorizedf
func MaybeUnauthorizedf(err error, message string, args ...interface{}) error { if isUnauthorized(errors.Cause(err)) { err = errors.Unauthorizedf("unauthorized mongo access: %s", err) } return errors.Annotatef(err, message, args...) }
go
func MaybeUnauthorizedf(err error, message string, args ...interface{}) error { if isUnauthorized(errors.Cause(err)) { err = errors.Unauthorizedf("unauthorized mongo access: %s", err) } return errors.Annotatef(err, message, args...) }
[ "func", "MaybeUnauthorizedf", "(", "err", "error", ",", "message", "string", ",", "args", "...", "interface", "{", "}", ")", "error", "{", "if", "isUnauthorized", "(", "errors", ".", "Cause", "(", "err", ")", ")", "{", "err", "=", "errors", ".", "Unauthorizedf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "errors", ".", "Annotatef", "(", "err", ",", "message", ",", "args", "...", ")", "\n", "}" ]
// MaybeUnauthorizedf checks if the cause of the given error is a Mongo // authorization error, and if so, wraps the error with errors.Unauthorizedf.
[ "MaybeUnauthorizedf", "checks", "if", "the", "cause", "of", "the", "given", "error", "is", "a", "Mongo", "authorization", "error", "and", "if", "so", "wraps", "the", "error", "with", "errors", ".", "Unauthorizedf", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/mongo/open.go#L240-L245
4,411
juju/juju
storage/provider/dummy/provider.go
VolumeSource
func (p *StorageProvider) VolumeSource(providerConfig *storage.Config) (storage.VolumeSource, error) { p.MethodCall(p, "VolumeSource", providerConfig) if p.VolumeSourceFunc != nil { return p.VolumeSourceFunc(providerConfig) } return nil, errors.NotSupportedf("volumes") }
go
func (p *StorageProvider) VolumeSource(providerConfig *storage.Config) (storage.VolumeSource, error) { p.MethodCall(p, "VolumeSource", providerConfig) if p.VolumeSourceFunc != nil { return p.VolumeSourceFunc(providerConfig) } return nil, errors.NotSupportedf("volumes") }
[ "func", "(", "p", "*", "StorageProvider", ")", "VolumeSource", "(", "providerConfig", "*", "storage", ".", "Config", ")", "(", "storage", ".", "VolumeSource", ",", "error", ")", "{", "p", ".", "MethodCall", "(", "p", ",", "\"", "\"", ",", "providerConfig", ")", "\n", "if", "p", ".", "VolumeSourceFunc", "!=", "nil", "{", "return", "p", ".", "VolumeSourceFunc", "(", "providerConfig", ")", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "NotSupportedf", "(", "\"", "\"", ")", "\n", "}" ]
// VolumeSource is defined on storage.Provider.
[ "VolumeSource", "is", "defined", "on", "storage", ".", "Provider", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/provider/dummy/provider.go#L53-L59
4,412
juju/juju
storage/provider/dummy/provider.go
FilesystemSource
func (p *StorageProvider) FilesystemSource(providerConfig *storage.Config) (storage.FilesystemSource, error) { p.MethodCall(p, "FilesystemSource", providerConfig) if p.FilesystemSourceFunc != nil { return p.FilesystemSourceFunc(providerConfig) } return nil, errors.NotSupportedf("filesystems") }
go
func (p *StorageProvider) FilesystemSource(providerConfig *storage.Config) (storage.FilesystemSource, error) { p.MethodCall(p, "FilesystemSource", providerConfig) if p.FilesystemSourceFunc != nil { return p.FilesystemSourceFunc(providerConfig) } return nil, errors.NotSupportedf("filesystems") }
[ "func", "(", "p", "*", "StorageProvider", ")", "FilesystemSource", "(", "providerConfig", "*", "storage", ".", "Config", ")", "(", "storage", ".", "FilesystemSource", ",", "error", ")", "{", "p", ".", "MethodCall", "(", "p", ",", "\"", "\"", ",", "providerConfig", ")", "\n", "if", "p", ".", "FilesystemSourceFunc", "!=", "nil", "{", "return", "p", ".", "FilesystemSourceFunc", "(", "providerConfig", ")", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "NotSupportedf", "(", "\"", "\"", ")", "\n", "}" ]
// FilesystemSource is defined on storage.Provider.
[ "FilesystemSource", "is", "defined", "on", "storage", ".", "Provider", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/provider/dummy/provider.go#L62-L68
4,413
juju/juju
storage/provider/dummy/provider.go
ValidateConfig
func (p *StorageProvider) ValidateConfig(providerConfig *storage.Config) error { p.MethodCall(p, "ValidateConfig", providerConfig) if p.ValidateConfigFunc != nil { return p.ValidateConfigFunc(providerConfig) } return nil }
go
func (p *StorageProvider) ValidateConfig(providerConfig *storage.Config) error { p.MethodCall(p, "ValidateConfig", providerConfig) if p.ValidateConfigFunc != nil { return p.ValidateConfigFunc(providerConfig) } return nil }
[ "func", "(", "p", "*", "StorageProvider", ")", "ValidateConfig", "(", "providerConfig", "*", "storage", ".", "Config", ")", "error", "{", "p", ".", "MethodCall", "(", "p", ",", "\"", "\"", ",", "providerConfig", ")", "\n", "if", "p", ".", "ValidateConfigFunc", "!=", "nil", "{", "return", "p", ".", "ValidateConfigFunc", "(", "providerConfig", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ValidateConfig is defined on storage.Provider.
[ "ValidateConfig", "is", "defined", "on", "storage", ".", "Provider", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/provider/dummy/provider.go#L71-L77
4,414
juju/juju
storage/provider/dummy/provider.go
Supports
func (p *StorageProvider) Supports(kind storage.StorageKind) bool { p.MethodCall(p, "Supports", kind) if p.SupportsFunc != nil { return p.SupportsFunc(kind) } return true }
go
func (p *StorageProvider) Supports(kind storage.StorageKind) bool { p.MethodCall(p, "Supports", kind) if p.SupportsFunc != nil { return p.SupportsFunc(kind) } return true }
[ "func", "(", "p", "*", "StorageProvider", ")", "Supports", "(", "kind", "storage", ".", "StorageKind", ")", "bool", "{", "p", ".", "MethodCall", "(", "p", ",", "\"", "\"", ",", "kind", ")", "\n", "if", "p", ".", "SupportsFunc", "!=", "nil", "{", "return", "p", ".", "SupportsFunc", "(", "kind", ")", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Supports is defined on storage.Provider.
[ "Supports", "is", "defined", "on", "storage", ".", "Provider", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/provider/dummy/provider.go#L80-L86
4,415
juju/juju
storage/provider/dummy/provider.go
Scope
func (p *StorageProvider) Scope() storage.Scope { p.MethodCall(p, "Scope") return p.StorageScope }
go
func (p *StorageProvider) Scope() storage.Scope { p.MethodCall(p, "Scope") return p.StorageScope }
[ "func", "(", "p", "*", "StorageProvider", ")", "Scope", "(", ")", "storage", ".", "Scope", "{", "p", ".", "MethodCall", "(", "p", ",", "\"", "\"", ")", "\n", "return", "p", ".", "StorageScope", "\n", "}" ]
// Scope is defined on storage.Provider.
[ "Scope", "is", "defined", "on", "storage", ".", "Provider", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/provider/dummy/provider.go#L89-L92
4,416
juju/juju
storage/provider/dummy/provider.go
DefaultPools
func (p *StorageProvider) DefaultPools() []*storage.Config { p.MethodCall(p, "DefaultPools") return p.DefaultPools_ }
go
func (p *StorageProvider) DefaultPools() []*storage.Config { p.MethodCall(p, "DefaultPools") return p.DefaultPools_ }
[ "func", "(", "p", "*", "StorageProvider", ")", "DefaultPools", "(", ")", "[", "]", "*", "storage", ".", "Config", "{", "p", ".", "MethodCall", "(", "p", ",", "\"", "\"", ")", "\n", "return", "p", ".", "DefaultPools_", "\n", "}" ]
// DefaultPool is defined on storage.Provider.
[ "DefaultPool", "is", "defined", "on", "storage", ".", "Provider", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/provider/dummy/provider.go#L107-L110
4,417
juju/juju
caas/kubernetes/provider/mocks/rbacv1_mock.go
NewMockRbacV1Interface
func NewMockRbacV1Interface(ctrl *gomock.Controller) *MockRbacV1Interface { mock := &MockRbacV1Interface{ctrl: ctrl} mock.recorder = &MockRbacV1InterfaceMockRecorder{mock} return mock }
go
func NewMockRbacV1Interface(ctrl *gomock.Controller) *MockRbacV1Interface { mock := &MockRbacV1Interface{ctrl: ctrl} mock.recorder = &MockRbacV1InterfaceMockRecorder{mock} return mock }
[ "func", "NewMockRbacV1Interface", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockRbacV1Interface", "{", "mock", ":=", "&", "MockRbacV1Interface", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockRbacV1InterfaceMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockRbacV1Interface creates a new mock instance
[ "NewMockRbacV1Interface", "creates", "a", "new", "mock", "instance" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/rbacv1_mock.go#L30-L34
4,418
juju/juju
caas/kubernetes/provider/mocks/rbacv1_mock.go
ClusterRoleBindings
func (m *MockRbacV1Interface) ClusterRoleBindings() v11.ClusterRoleBindingInterface { ret := m.ctrl.Call(m, "ClusterRoleBindings") ret0, _ := ret[0].(v11.ClusterRoleBindingInterface) return ret0 }
go
func (m *MockRbacV1Interface) ClusterRoleBindings() v11.ClusterRoleBindingInterface { ret := m.ctrl.Call(m, "ClusterRoleBindings") ret0, _ := ret[0].(v11.ClusterRoleBindingInterface) return ret0 }
[ "func", "(", "m", "*", "MockRbacV1Interface", ")", "ClusterRoleBindings", "(", ")", "v11", ".", "ClusterRoleBindingInterface", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "v11", ".", "ClusterRoleBindingInterface", ")", "\n", "return", "ret0", "\n", "}" ]
// ClusterRoleBindings mocks base method
[ "ClusterRoleBindings", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/rbacv1_mock.go#L42-L46
4,419
juju/juju
caas/kubernetes/provider/mocks/rbacv1_mock.go
ClusterRoles
func (m *MockRbacV1Interface) ClusterRoles() v11.ClusterRoleInterface { ret := m.ctrl.Call(m, "ClusterRoles") ret0, _ := ret[0].(v11.ClusterRoleInterface) return ret0 }
go
func (m *MockRbacV1Interface) ClusterRoles() v11.ClusterRoleInterface { ret := m.ctrl.Call(m, "ClusterRoles") ret0, _ := ret[0].(v11.ClusterRoleInterface) return ret0 }
[ "func", "(", "m", "*", "MockRbacV1Interface", ")", "ClusterRoles", "(", ")", "v11", ".", "ClusterRoleInterface", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "v11", ".", "ClusterRoleInterface", ")", "\n", "return", "ret0", "\n", "}" ]
// ClusterRoles mocks base method
[ "ClusterRoles", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/rbacv1_mock.go#L54-L58
4,420
juju/juju
caas/kubernetes/provider/mocks/rbacv1_mock.go
RoleBindings
func (m *MockRbacV1Interface) RoleBindings(arg0 string) v11.RoleBindingInterface { ret := m.ctrl.Call(m, "RoleBindings", arg0) ret0, _ := ret[0].(v11.RoleBindingInterface) return ret0 }
go
func (m *MockRbacV1Interface) RoleBindings(arg0 string) v11.RoleBindingInterface { ret := m.ctrl.Call(m, "RoleBindings", arg0) ret0, _ := ret[0].(v11.RoleBindingInterface) return ret0 }
[ "func", "(", "m", "*", "MockRbacV1Interface", ")", "RoleBindings", "(", "arg0", "string", ")", "v11", ".", "RoleBindingInterface", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "v11", ".", "RoleBindingInterface", ")", "\n", "return", "ret0", "\n", "}" ]
// RoleBindings mocks base method
[ "RoleBindings", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/rbacv1_mock.go#L78-L82
4,421
juju/juju
caas/kubernetes/provider/mocks/rbacv1_mock.go
RoleBindings
func (mr *MockRbacV1InterfaceMockRecorder) RoleBindings(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RoleBindings", reflect.TypeOf((*MockRbacV1Interface)(nil).RoleBindings), arg0) }
go
func (mr *MockRbacV1InterfaceMockRecorder) RoleBindings(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RoleBindings", reflect.TypeOf((*MockRbacV1Interface)(nil).RoleBindings), arg0) }
[ "func", "(", "mr", "*", "MockRbacV1InterfaceMockRecorder", ")", "RoleBindings", "(", "arg0", "interface", "{", "}", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "(", "*", "MockRbacV1Interface", ")", "(", "nil", ")", ".", "RoleBindings", ")", ",", "arg0", ")", "\n", "}" ]
// RoleBindings indicates an expected call of RoleBindings
[ "RoleBindings", "indicates", "an", "expected", "call", "of", "RoleBindings" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/rbacv1_mock.go#L85-L87
4,422
juju/juju
caas/kubernetes/provider/mocks/rbacv1_mock.go
Roles
func (m *MockRbacV1Interface) Roles(arg0 string) v11.RoleInterface { ret := m.ctrl.Call(m, "Roles", arg0) ret0, _ := ret[0].(v11.RoleInterface) return ret0 }
go
func (m *MockRbacV1Interface) Roles(arg0 string) v11.RoleInterface { ret := m.ctrl.Call(m, "Roles", arg0) ret0, _ := ret[0].(v11.RoleInterface) return ret0 }
[ "func", "(", "m", "*", "MockRbacV1Interface", ")", "Roles", "(", "arg0", "string", ")", "v11", ".", "RoleInterface", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "v11", ".", "RoleInterface", ")", "\n", "return", "ret0", "\n", "}" ]
// Roles mocks base method
[ "Roles", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/rbacv1_mock.go#L90-L94
4,423
juju/juju
caas/kubernetes/provider/mocks/rbacv1_mock.go
NewMockClusterRoleBindingInterface
func NewMockClusterRoleBindingInterface(ctrl *gomock.Controller) *MockClusterRoleBindingInterface { mock := &MockClusterRoleBindingInterface{ctrl: ctrl} mock.recorder = &MockClusterRoleBindingInterfaceMockRecorder{mock} return mock }
go
func NewMockClusterRoleBindingInterface(ctrl *gomock.Controller) *MockClusterRoleBindingInterface { mock := &MockClusterRoleBindingInterface{ctrl: ctrl} mock.recorder = &MockClusterRoleBindingInterfaceMockRecorder{mock} return mock }
[ "func", "NewMockClusterRoleBindingInterface", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockClusterRoleBindingInterface", "{", "mock", ":=", "&", "MockClusterRoleBindingInterface", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockClusterRoleBindingInterfaceMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockClusterRoleBindingInterface creates a new mock instance
[ "NewMockClusterRoleBindingInterface", "creates", "a", "new", "mock", "instance" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/rbacv1_mock.go#L113-L117
4,424
juju/juju
caas/kubernetes/provider/mocks/rbacv1_mock.go
NewMockClusterRoleInterface
func NewMockClusterRoleInterface(ctrl *gomock.Controller) *MockClusterRoleInterface { mock := &MockClusterRoleInterface{ctrl: ctrl} mock.recorder = &MockClusterRoleInterfaceMockRecorder{mock} return mock }
go
func NewMockClusterRoleInterface(ctrl *gomock.Controller) *MockClusterRoleInterface { mock := &MockClusterRoleInterface{ctrl: ctrl} mock.recorder = &MockClusterRoleInterfaceMockRecorder{mock} return mock }
[ "func", "NewMockClusterRoleInterface", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockClusterRoleInterface", "{", "mock", ":=", "&", "MockClusterRoleInterface", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockClusterRoleInterfaceMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockClusterRoleInterface creates a new mock instance
[ "NewMockClusterRoleInterface", "creates", "a", "new", "mock", "instance" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/rbacv1_mock.go#L243-L247
4,425
juju/juju
state/mocks/database_mock.go
NewMockDatabase
func NewMockDatabase(ctrl *gomock.Controller) *MockDatabase { mock := &MockDatabase{ctrl: ctrl} mock.recorder = &MockDatabaseMockRecorder{mock} return mock }
go
func NewMockDatabase(ctrl *gomock.Controller) *MockDatabase { mock := &MockDatabase{ctrl: ctrl} mock.recorder = &MockDatabaseMockRecorder{mock} return mock }
[ "func", "NewMockDatabase", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockDatabase", "{", "mock", ":=", "&", "MockDatabase", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockDatabaseMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockDatabase creates a new mock instance
[ "NewMockDatabase", "creates", "a", "new", "mock", "instance" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/mocks/database_mock.go#L29-L33
4,426
juju/juju
state/mocks/database_mock.go
Copy
func (m *MockDatabase) Copy() (state.Database, state.SessionCloser) { ret := m.ctrl.Call(m, "Copy") ret0, _ := ret[0].(state.Database) ret1, _ := ret[1].(state.SessionCloser) return ret0, ret1 }
go
func (m *MockDatabase) Copy() (state.Database, state.SessionCloser) { ret := m.ctrl.Call(m, "Copy") ret0, _ := ret[0].(state.Database) ret1, _ := ret[1].(state.SessionCloser) return ret0, ret1 }
[ "func", "(", "m", "*", "MockDatabase", ")", "Copy", "(", ")", "(", "state", ".", "Database", ",", "state", ".", "SessionCloser", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "state", ".", "Database", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "state", ".", "SessionCloser", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// Copy mocks base method
[ "Copy", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/mocks/database_mock.go#L41-L46
4,427
juju/juju
state/mocks/database_mock.go
CopyForModel
func (m *MockDatabase) CopyForModel(arg0 string) (state.Database, state.SessionCloser) { ret := m.ctrl.Call(m, "CopyForModel", arg0) ret0, _ := ret[0].(state.Database) ret1, _ := ret[1].(state.SessionCloser) return ret0, ret1 }
go
func (m *MockDatabase) CopyForModel(arg0 string) (state.Database, state.SessionCloser) { ret := m.ctrl.Call(m, "CopyForModel", arg0) ret0, _ := ret[0].(state.Database) ret1, _ := ret[1].(state.SessionCloser) return ret0, ret1 }
[ "func", "(", "m", "*", "MockDatabase", ")", "CopyForModel", "(", "arg0", "string", ")", "(", "state", ".", "Database", ",", "state", ".", "SessionCloser", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "state", ".", "Database", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "state", ".", "SessionCloser", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// CopyForModel mocks base method
[ "CopyForModel", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/mocks/database_mock.go#L54-L59
4,428
juju/juju
state/mocks/database_mock.go
GetCollectionFor
func (m *MockDatabase) GetCollectionFor(arg0, arg1 string) (mongo.Collection, state.SessionCloser) { ret := m.ctrl.Call(m, "GetCollectionFor", arg0, arg1) ret0, _ := ret[0].(mongo.Collection) ret1, _ := ret[1].(state.SessionCloser) return ret0, ret1 }
go
func (m *MockDatabase) GetCollectionFor(arg0, arg1 string) (mongo.Collection, state.SessionCloser) { ret := m.ctrl.Call(m, "GetCollectionFor", arg0, arg1) ret0, _ := ret[0].(mongo.Collection) ret1, _ := ret[1].(state.SessionCloser) return ret0, ret1 }
[ "func", "(", "m", "*", "MockDatabase", ")", "GetCollectionFor", "(", "arg0", ",", "arg1", "string", ")", "(", "mongo", ".", "Collection", ",", "state", ".", "SessionCloser", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ",", "arg1", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "mongo", ".", "Collection", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "state", ".", "SessionCloser", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// GetCollectionFor mocks base method
[ "GetCollectionFor", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/mocks/database_mock.go#L80-L85
4,429
juju/juju
state/mocks/database_mock.go
GetRawCollection
func (m *MockDatabase) GetRawCollection(arg0 string) (*mgo_v2.Collection, state.SessionCloser) { ret := m.ctrl.Call(m, "GetRawCollection", arg0) ret0, _ := ret[0].(*mgo_v2.Collection) ret1, _ := ret[1].(state.SessionCloser) return ret0, ret1 }
go
func (m *MockDatabase) GetRawCollection(arg0 string) (*mgo_v2.Collection, state.SessionCloser) { ret := m.ctrl.Call(m, "GetRawCollection", arg0) ret0, _ := ret[0].(*mgo_v2.Collection) ret1, _ := ret[1].(state.SessionCloser) return ret0, ret1 }
[ "func", "(", "m", "*", "MockDatabase", ")", "GetRawCollection", "(", "arg0", "string", ")", "(", "*", "mgo_v2", ".", "Collection", ",", "state", ".", "SessionCloser", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "*", "mgo_v2", ".", "Collection", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "state", ".", "SessionCloser", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// GetRawCollection mocks base method
[ "GetRawCollection", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/mocks/database_mock.go#L93-L98
4,430
juju/juju
state/mocks/database_mock.go
RunRawTransaction
func (mr *MockDatabaseMockRecorder) RunRawTransaction(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RunRawTransaction", reflect.TypeOf((*MockDatabase)(nil).RunRawTransaction), arg0) }
go
func (mr *MockDatabaseMockRecorder) RunRawTransaction(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RunRawTransaction", reflect.TypeOf((*MockDatabase)(nil).RunRawTransaction), arg0) }
[ "func", "(", "mr", "*", "MockDatabaseMockRecorder", ")", "RunRawTransaction", "(", "arg0", "interface", "{", "}", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "(", "*", "MockDatabase", ")", "(", "nil", ")", ".", "RunRawTransaction", ")", ",", "arg0", ")", "\n", "}" ]
// RunRawTransaction indicates an expected call of RunRawTransaction
[ "RunRawTransaction", "indicates", "an", "expected", "call", "of", "RunRawTransaction" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/mocks/database_mock.go#L125-L127
4,431
juju/juju
state/mocks/database_mock.go
RunTransactionFor
func (m *MockDatabase) RunTransactionFor(arg0 string, arg1 []txn0.Op) error { ret := m.ctrl.Call(m, "RunTransactionFor", arg0, arg1) ret0, _ := ret[0].(error) return ret0 }
go
func (m *MockDatabase) RunTransactionFor(arg0 string, arg1 []txn0.Op) error { ret := m.ctrl.Call(m, "RunTransactionFor", arg0, arg1) ret0, _ := ret[0].(error) return ret0 }
[ "func", "(", "m", "*", "MockDatabase", ")", "RunTransactionFor", "(", "arg0", "string", ",", "arg1", "[", "]", "txn0", ".", "Op", ")", "error", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ",", "arg1", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "error", ")", "\n", "return", "ret0", "\n", "}" ]
// RunTransactionFor mocks base method
[ "RunTransactionFor", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/mocks/database_mock.go#L142-L146
4,432
juju/juju
state/mocks/database_mock.go
Schema
func (m *MockDatabase) Schema() state.CollectionSchema { ret := m.ctrl.Call(m, "Schema") ret0, _ := ret[0].(state.CollectionSchema) return ret0 }
go
func (m *MockDatabase) Schema() state.CollectionSchema { ret := m.ctrl.Call(m, "Schema") ret0, _ := ret[0].(state.CollectionSchema) return ret0 }
[ "func", "(", "m", "*", "MockDatabase", ")", "Schema", "(", ")", "state", ".", "CollectionSchema", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "state", ".", "CollectionSchema", ")", "\n", "return", "ret0", "\n", "}" ]
// Schema mocks base method
[ "Schema", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/mocks/database_mock.go#L154-L158
4,433
juju/juju
state/mocks/database_mock.go
TransactionRunner
func (m *MockDatabase) TransactionRunner() (txn.Runner, state.SessionCloser) { ret := m.ctrl.Call(m, "TransactionRunner") ret0, _ := ret[0].(txn.Runner) ret1, _ := ret[1].(state.SessionCloser) return ret0, ret1 }
go
func (m *MockDatabase) TransactionRunner() (txn.Runner, state.SessionCloser) { ret := m.ctrl.Call(m, "TransactionRunner") ret0, _ := ret[0].(txn.Runner) ret1, _ := ret[1].(state.SessionCloser) return ret0, ret1 }
[ "func", "(", "m", "*", "MockDatabase", ")", "TransactionRunner", "(", ")", "(", "txn", ".", "Runner", ",", "state", ".", "SessionCloser", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "txn", ".", "Runner", ")", "\n", "ret1", ",", "_", ":=", "ret", "[", "1", "]", ".", "(", "state", ".", "SessionCloser", ")", "\n", "return", "ret0", ",", "ret1", "\n", "}" ]
// TransactionRunner mocks base method
[ "TransactionRunner", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/mocks/database_mock.go#L166-L171
4,434
juju/juju
state/mocks/database_mock.go
TransactionRunner
func (mr *MockDatabaseMockRecorder) TransactionRunner() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TransactionRunner", reflect.TypeOf((*MockDatabase)(nil).TransactionRunner)) }
go
func (mr *MockDatabaseMockRecorder) TransactionRunner() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TransactionRunner", reflect.TypeOf((*MockDatabase)(nil).TransactionRunner)) }
[ "func", "(", "mr", "*", "MockDatabaseMockRecorder", ")", "TransactionRunner", "(", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "(", "*", "MockDatabase", ")", "(", "nil", ")", ".", "TransactionRunner", ")", ")", "\n", "}" ]
// TransactionRunner indicates an expected call of TransactionRunner
[ "TransactionRunner", "indicates", "an", "expected", "call", "of", "TransactionRunner" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/mocks/database_mock.go#L174-L176
4,435
juju/juju
environs/simplestreams/encode.go
Encode
func Encode(r io.Reader, armoredPrivateKey, passphrase string) ([]byte, error) { keyring, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(armoredPrivateKey)) if err != nil { return nil, err } privateKey := keyring[0].PrivateKey if privateKey.Encrypted { err = privateKey.Decrypt([]byte(passphrase)) if err != nil { return nil, err } } var buf bytes.Buffer plaintext, err := clearsign.Encode(&buf, privateKey, nil) if err != nil { return nil, err } metadata, err := ioutil.ReadAll(r) if err != nil { return nil, err } dataToSign := metadata if dataToSign[0] == '\n' { dataToSign = dataToSign[1:] } _, err = plaintext.Write(dataToSign) if err != nil { return nil, err } err = plaintext.Close() if err != nil { return nil, err } return buf.Bytes(), nil }
go
func Encode(r io.Reader, armoredPrivateKey, passphrase string) ([]byte, error) { keyring, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(armoredPrivateKey)) if err != nil { return nil, err } privateKey := keyring[0].PrivateKey if privateKey.Encrypted { err = privateKey.Decrypt([]byte(passphrase)) if err != nil { return nil, err } } var buf bytes.Buffer plaintext, err := clearsign.Encode(&buf, privateKey, nil) if err != nil { return nil, err } metadata, err := ioutil.ReadAll(r) if err != nil { return nil, err } dataToSign := metadata if dataToSign[0] == '\n' { dataToSign = dataToSign[1:] } _, err = plaintext.Write(dataToSign) if err != nil { return nil, err } err = plaintext.Close() if err != nil { return nil, err } return buf.Bytes(), nil }
[ "func", "Encode", "(", "r", "io", ".", "Reader", ",", "armoredPrivateKey", ",", "passphrase", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "keyring", ",", "err", ":=", "openpgp", ".", "ReadArmoredKeyRing", "(", "bytes", ".", "NewBufferString", "(", "armoredPrivateKey", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "privateKey", ":=", "keyring", "[", "0", "]", ".", "PrivateKey", "\n", "if", "privateKey", ".", "Encrypted", "{", "err", "=", "privateKey", ".", "Decrypt", "(", "[", "]", "byte", "(", "passphrase", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "var", "buf", "bytes", ".", "Buffer", "\n", "plaintext", ",", "err", ":=", "clearsign", ".", "Encode", "(", "&", "buf", ",", "privateKey", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "metadata", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "dataToSign", ":=", "metadata", "\n", "if", "dataToSign", "[", "0", "]", "==", "'\\n'", "{", "dataToSign", "=", "dataToSign", "[", "1", ":", "]", "\n", "}", "\n", "_", ",", "err", "=", "plaintext", ".", "Write", "(", "dataToSign", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "err", "=", "plaintext", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "buf", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// Encode signs the data returned by the reader and returns an inline signed copy.
[ "Encode", "signs", "the", "data", "returned", "by", "the", "reader", "and", "returns", "an", "inline", "signed", "copy", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/simplestreams/encode.go#L16-L52
4,436
juju/juju
network/netplan/netplan.go
BridgeEthernetById
func (np *Netplan) BridgeEthernetById(deviceId string, bridgeName string) (err error) { ethernet, ok := np.Network.Ethernets[deviceId] if !ok { return errors.NotFoundf("ethernet device with id %q for bridge %q", deviceId, bridgeName) } shouldCreate, err := np.shouldCreateBridge(deviceId, bridgeName) if !shouldCreate { // err may be nil, but we shouldn't continue creating return errors.Trace(err) } np.createBridgeFromInterface(bridgeName, deviceId, &ethernet.Interface) np.Network.Ethernets[deviceId] = ethernet return nil }
go
func (np *Netplan) BridgeEthernetById(deviceId string, bridgeName string) (err error) { ethernet, ok := np.Network.Ethernets[deviceId] if !ok { return errors.NotFoundf("ethernet device with id %q for bridge %q", deviceId, bridgeName) } shouldCreate, err := np.shouldCreateBridge(deviceId, bridgeName) if !shouldCreate { // err may be nil, but we shouldn't continue creating return errors.Trace(err) } np.createBridgeFromInterface(bridgeName, deviceId, &ethernet.Interface) np.Network.Ethernets[deviceId] = ethernet return nil }
[ "func", "(", "np", "*", "Netplan", ")", "BridgeEthernetById", "(", "deviceId", "string", ",", "bridgeName", "string", ")", "(", "err", "error", ")", "{", "ethernet", ",", "ok", ":=", "np", ".", "Network", ".", "Ethernets", "[", "deviceId", "]", "\n", "if", "!", "ok", "{", "return", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "deviceId", ",", "bridgeName", ")", "\n", "}", "\n", "shouldCreate", ",", "err", ":=", "np", ".", "shouldCreateBridge", "(", "deviceId", ",", "bridgeName", ")", "\n", "if", "!", "shouldCreate", "{", "// err may be nil, but we shouldn't continue creating", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "np", ".", "createBridgeFromInterface", "(", "bridgeName", ",", "deviceId", ",", "&", "ethernet", ".", "Interface", ")", "\n", "np", ".", "Network", ".", "Ethernets", "[", "deviceId", "]", "=", "ethernet", "\n", "return", "nil", "\n", "}" ]
// BridgeEthernetById takes a deviceId and creates a bridge with this device // using this devices config
[ "BridgeEthernetById", "takes", "a", "deviceId", "and", "creates", "a", "bridge", "with", "this", "device", "using", "this", "devices", "config" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/netplan/netplan.go#L204-L217
4,437
juju/juju
network/netplan/netplan.go
BridgeVLANById
func (np *Netplan) BridgeVLANById(deviceId string, bridgeName string) (err error) { vlan, ok := np.Network.VLANs[deviceId] if !ok { return errors.NotFoundf("VLAN device with id %q for bridge %q", deviceId, bridgeName) } shouldCreate, err := np.shouldCreateBridge(deviceId, bridgeName) if !shouldCreate { // err may be nil, but we shouldn't continue creating return errors.Trace(err) } np.createBridgeFromInterface(bridgeName, deviceId, &vlan.Interface) np.Network.VLANs[deviceId] = vlan return nil }
go
func (np *Netplan) BridgeVLANById(deviceId string, bridgeName string) (err error) { vlan, ok := np.Network.VLANs[deviceId] if !ok { return errors.NotFoundf("VLAN device with id %q for bridge %q", deviceId, bridgeName) } shouldCreate, err := np.shouldCreateBridge(deviceId, bridgeName) if !shouldCreate { // err may be nil, but we shouldn't continue creating return errors.Trace(err) } np.createBridgeFromInterface(bridgeName, deviceId, &vlan.Interface) np.Network.VLANs[deviceId] = vlan return nil }
[ "func", "(", "np", "*", "Netplan", ")", "BridgeVLANById", "(", "deviceId", "string", ",", "bridgeName", "string", ")", "(", "err", "error", ")", "{", "vlan", ",", "ok", ":=", "np", ".", "Network", ".", "VLANs", "[", "deviceId", "]", "\n", "if", "!", "ok", "{", "return", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "deviceId", ",", "bridgeName", ")", "\n", "}", "\n", "shouldCreate", ",", "err", ":=", "np", ".", "shouldCreateBridge", "(", "deviceId", ",", "bridgeName", ")", "\n", "if", "!", "shouldCreate", "{", "// err may be nil, but we shouldn't continue creating", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "np", ".", "createBridgeFromInterface", "(", "bridgeName", ",", "deviceId", ",", "&", "vlan", ".", "Interface", ")", "\n", "np", ".", "Network", ".", "VLANs", "[", "deviceId", "]", "=", "vlan", "\n", "return", "nil", "\n", "}" ]
// BridgeVLANById takes a deviceId and creates a bridge with this device // using this devices config
[ "BridgeVLANById", "takes", "a", "deviceId", "and", "creates", "a", "bridge", "with", "this", "device", "using", "this", "devices", "config" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/netplan/netplan.go#L221-L234
4,438
juju/juju
network/netplan/netplan.go
BridgeBondById
func (np *Netplan) BridgeBondById(deviceId string, bridgeName string) (err error) { bond, ok := np.Network.Bonds[deviceId] if !ok { return errors.NotFoundf("bond device with id %q for bridge %q", deviceId, bridgeName) } shouldCreate, err := np.shouldCreateBridge(deviceId, bridgeName) if !shouldCreate { // err may be nil, but we shouldn't continue creating return errors.Trace(err) } np.createBridgeFromInterface(bridgeName, deviceId, &bond.Interface) np.Network.Bonds[deviceId] = bond return nil }
go
func (np *Netplan) BridgeBondById(deviceId string, bridgeName string) (err error) { bond, ok := np.Network.Bonds[deviceId] if !ok { return errors.NotFoundf("bond device with id %q for bridge %q", deviceId, bridgeName) } shouldCreate, err := np.shouldCreateBridge(deviceId, bridgeName) if !shouldCreate { // err may be nil, but we shouldn't continue creating return errors.Trace(err) } np.createBridgeFromInterface(bridgeName, deviceId, &bond.Interface) np.Network.Bonds[deviceId] = bond return nil }
[ "func", "(", "np", "*", "Netplan", ")", "BridgeBondById", "(", "deviceId", "string", ",", "bridgeName", "string", ")", "(", "err", "error", ")", "{", "bond", ",", "ok", ":=", "np", ".", "Network", ".", "Bonds", "[", "deviceId", "]", "\n", "if", "!", "ok", "{", "return", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "deviceId", ",", "bridgeName", ")", "\n", "}", "\n", "shouldCreate", ",", "err", ":=", "np", ".", "shouldCreateBridge", "(", "deviceId", ",", "bridgeName", ")", "\n", "if", "!", "shouldCreate", "{", "// err may be nil, but we shouldn't continue creating", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "np", ".", "createBridgeFromInterface", "(", "bridgeName", ",", "deviceId", ",", "&", "bond", ".", "Interface", ")", "\n", "np", ".", "Network", ".", "Bonds", "[", "deviceId", "]", "=", "bond", "\n", "return", "nil", "\n", "}" ]
// BridgeBondById takes a deviceId and creates a bridge with this device // using this devices config
[ "BridgeBondById", "takes", "a", "deviceId", "and", "creates", "a", "bridge", "with", "this", "device", "using", "this", "devices", "config" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/netplan/netplan.go#L238-L251
4,439
juju/juju
network/netplan/netplan.go
shouldCreateBridge
func (np *Netplan) shouldCreateBridge(deviceId string, bridgeName string) (bool, error) { for bName, bridge := range np.Network.Bridges { for _, i := range bridge.Interfaces { if i == deviceId { // The device is already properly bridged, nothing to do if bridgeName == bName { return false, nil } else { return false, errors.AlreadyExistsf("cannot create bridge %q, device %q in bridge %q", bridgeName, deviceId, bName) } } } if bridgeName == bName { return false, errors.AlreadyExistsf( "cannot create bridge %q with device %q - bridge %q w/ interfaces %q", bridgeName, deviceId, bridgeName, strings.Join(bridge.Interfaces, ", ")) } } return true, nil }
go
func (np *Netplan) shouldCreateBridge(deviceId string, bridgeName string) (bool, error) { for bName, bridge := range np.Network.Bridges { for _, i := range bridge.Interfaces { if i == deviceId { // The device is already properly bridged, nothing to do if bridgeName == bName { return false, nil } else { return false, errors.AlreadyExistsf("cannot create bridge %q, device %q in bridge %q", bridgeName, deviceId, bName) } } } if bridgeName == bName { return false, errors.AlreadyExistsf( "cannot create bridge %q with device %q - bridge %q w/ interfaces %q", bridgeName, deviceId, bridgeName, strings.Join(bridge.Interfaces, ", ")) } } return true, nil }
[ "func", "(", "np", "*", "Netplan", ")", "shouldCreateBridge", "(", "deviceId", "string", ",", "bridgeName", "string", ")", "(", "bool", ",", "error", ")", "{", "for", "bName", ",", "bridge", ":=", "range", "np", ".", "Network", ".", "Bridges", "{", "for", "_", ",", "i", ":=", "range", "bridge", ".", "Interfaces", "{", "if", "i", "==", "deviceId", "{", "// The device is already properly bridged, nothing to do", "if", "bridgeName", "==", "bName", "{", "return", "false", ",", "nil", "\n", "}", "else", "{", "return", "false", ",", "errors", ".", "AlreadyExistsf", "(", "\"", "\"", ",", "bridgeName", ",", "deviceId", ",", "bName", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "bridgeName", "==", "bName", "{", "return", "false", ",", "errors", ".", "AlreadyExistsf", "(", "\"", "\"", ",", "bridgeName", ",", "deviceId", ",", "bridgeName", ",", "strings", ".", "Join", "(", "bridge", ".", "Interfaces", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}" ]
// shouldCreateBridge returns true only if it is clear the bridge doesn't already exist, and that the existing device // isn't in a different bridge.
[ "shouldCreateBridge", "returns", "true", "only", "if", "it", "is", "clear", "the", "bridge", "doesn", "t", "already", "exist", "and", "that", "the", "existing", "device", "isn", "t", "in", "a", "different", "bridge", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/netplan/netplan.go#L255-L274
4,440
juju/juju
network/netplan/netplan.go
createBridgeFromInterface
func (np *Netplan) createBridgeFromInterface(bridgeName, deviceId string, intf *Interface) { if np.Network.Bridges == nil { np.Network.Bridges = make(map[string]Bridge) } np.Network.Bridges[bridgeName] = Bridge{ Interfaces: []string{deviceId}, Interface: *intf, } *intf = Interface{MTU: intf.MTU} }
go
func (np *Netplan) createBridgeFromInterface(bridgeName, deviceId string, intf *Interface) { if np.Network.Bridges == nil { np.Network.Bridges = make(map[string]Bridge) } np.Network.Bridges[bridgeName] = Bridge{ Interfaces: []string{deviceId}, Interface: *intf, } *intf = Interface{MTU: intf.MTU} }
[ "func", "(", "np", "*", "Netplan", ")", "createBridgeFromInterface", "(", "bridgeName", ",", "deviceId", "string", ",", "intf", "*", "Interface", ")", "{", "if", "np", ".", "Network", ".", "Bridges", "==", "nil", "{", "np", ".", "Network", ".", "Bridges", "=", "make", "(", "map", "[", "string", "]", "Bridge", ")", "\n", "}", "\n", "np", ".", "Network", ".", "Bridges", "[", "bridgeName", "]", "=", "Bridge", "{", "Interfaces", ":", "[", "]", "string", "{", "deviceId", "}", ",", "Interface", ":", "*", "intf", ",", "}", "\n", "*", "intf", "=", "Interface", "{", "MTU", ":", "intf", ".", "MTU", "}", "\n", "}" ]
// createBridgeFromInterface will create a bridge stealing the interface details, and wiping the existing interface // except for MTU so that IP Address information is never duplicated.
[ "createBridgeFromInterface", "will", "create", "a", "bridge", "stealing", "the", "interface", "details", "and", "wiping", "the", "existing", "interface", "except", "for", "MTU", "so", "that", "IP", "Address", "information", "is", "never", "duplicated", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/netplan/netplan.go#L278-L287
4,441
juju/juju
network/netplan/netplan.go
ReadDirectory
func ReadDirectory(dirPath string) (np Netplan, err error) { fileInfos, err := ioutil.ReadDir(dirPath) if err != nil { return np, err } np.sourceDirectory = dirPath sortedFileInfos := sortableFileInfos(fileInfos) sort.Sort(sortedFileInfos) for _, fileInfo := range sortedFileInfos { if !fileInfo.IsDir() && strings.HasSuffix(fileInfo.Name(), ".yaml") { np.sourceFiles = append(np.sourceFiles, fileInfo.Name()) } } for _, fileName := range np.sourceFiles { err := np.readYamlFile(path.Join(np.sourceDirectory, fileName)) if err != nil { return np, err } } return np, nil }
go
func ReadDirectory(dirPath string) (np Netplan, err error) { fileInfos, err := ioutil.ReadDir(dirPath) if err != nil { return np, err } np.sourceDirectory = dirPath sortedFileInfos := sortableFileInfos(fileInfos) sort.Sort(sortedFileInfos) for _, fileInfo := range sortedFileInfos { if !fileInfo.IsDir() && strings.HasSuffix(fileInfo.Name(), ".yaml") { np.sourceFiles = append(np.sourceFiles, fileInfo.Name()) } } for _, fileName := range np.sourceFiles { err := np.readYamlFile(path.Join(np.sourceDirectory, fileName)) if err != nil { return np, err } } return np, nil }
[ "func", "ReadDirectory", "(", "dirPath", "string", ")", "(", "np", "Netplan", ",", "err", "error", ")", "{", "fileInfos", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "dirPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "np", ",", "err", "\n", "}", "\n", "np", ".", "sourceDirectory", "=", "dirPath", "\n", "sortedFileInfos", ":=", "sortableFileInfos", "(", "fileInfos", ")", "\n", "sort", ".", "Sort", "(", "sortedFileInfos", ")", "\n", "for", "_", ",", "fileInfo", ":=", "range", "sortedFileInfos", "{", "if", "!", "fileInfo", ".", "IsDir", "(", ")", "&&", "strings", ".", "HasSuffix", "(", "fileInfo", ".", "Name", "(", ")", ",", "\"", "\"", ")", "{", "np", ".", "sourceFiles", "=", "append", "(", "np", ".", "sourceFiles", ",", "fileInfo", ".", "Name", "(", ")", ")", "\n", "}", "\n", "}", "\n", "for", "_", ",", "fileName", ":=", "range", "np", ".", "sourceFiles", "{", "err", ":=", "np", ".", "readYamlFile", "(", "path", ".", "Join", "(", "np", ".", "sourceDirectory", ",", "fileName", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "np", ",", "err", "\n", "}", "\n", "}", "\n", "return", "np", ",", "nil", "\n", "}" ]
// ReadDirectory reads the contents of a netplan directory and // returns complete config.
[ "ReadDirectory", "reads", "the", "contents", "of", "a", "netplan", "directory", "and", "returns", "complete", "config", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/netplan/netplan.go#L388-L408
4,442
juju/juju
network/netplan/netplan.go
Write
func (np *Netplan) Write(inPath string) (filePath string, err error) { if np.writtenFile != "" { return "", errors.Errorf("Cannot write the same netplan twice") } if inPath == "" { i := 99 for ; i > 0; i-- { filePath = path.Join(np.sourceDirectory, fmt.Sprintf("%0.2d-juju.yaml", i)) _, err = os.Stat(filePath) if os.IsNotExist(err) { break } } if i == 0 { return "", errors.Errorf("Can't generate a filename for netplan YAML") } } else { filePath = inPath } tmpFilePath := fmt.Sprintf("%s.tmp.%d", filePath, time.Now().UnixNano()) out, err := Marshal(np) if err != nil { return "", err } err = ioutil.WriteFile(tmpFilePath, out, 0644) if err != nil { return "", err } err = os.Rename(tmpFilePath, filePath) if err != nil { return "", err } np.writtenFile = filePath return filePath, nil }
go
func (np *Netplan) Write(inPath string) (filePath string, err error) { if np.writtenFile != "" { return "", errors.Errorf("Cannot write the same netplan twice") } if inPath == "" { i := 99 for ; i > 0; i-- { filePath = path.Join(np.sourceDirectory, fmt.Sprintf("%0.2d-juju.yaml", i)) _, err = os.Stat(filePath) if os.IsNotExist(err) { break } } if i == 0 { return "", errors.Errorf("Can't generate a filename for netplan YAML") } } else { filePath = inPath } tmpFilePath := fmt.Sprintf("%s.tmp.%d", filePath, time.Now().UnixNano()) out, err := Marshal(np) if err != nil { return "", err } err = ioutil.WriteFile(tmpFilePath, out, 0644) if err != nil { return "", err } err = os.Rename(tmpFilePath, filePath) if err != nil { return "", err } np.writtenFile = filePath return filePath, nil }
[ "func", "(", "np", "*", "Netplan", ")", "Write", "(", "inPath", "string", ")", "(", "filePath", "string", ",", "err", "error", ")", "{", "if", "np", ".", "writtenFile", "!=", "\"", "\"", "{", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "inPath", "==", "\"", "\"", "{", "i", ":=", "99", "\n", "for", ";", "i", ">", "0", ";", "i", "--", "{", "filePath", "=", "path", ".", "Join", "(", "np", ".", "sourceDirectory", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "i", ")", ")", "\n", "_", ",", "err", "=", "os", ".", "Stat", "(", "filePath", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "break", "\n", "}", "\n", "}", "\n", "if", "i", "==", "0", "{", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "else", "{", "filePath", "=", "inPath", "\n", "}", "\n", "tmpFilePath", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "filePath", ",", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", "\n", "out", ",", "err", ":=", "Marshal", "(", "np", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "err", "=", "ioutil", ".", "WriteFile", "(", "tmpFilePath", ",", "out", ",", "0644", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "err", "=", "os", ".", "Rename", "(", "tmpFilePath", ",", "filePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "np", ".", "writtenFile", "=", "filePath", "\n", "return", "filePath", ",", "nil", "\n", "}" ]
// Write writes merged netplan yaml to file specified by path. If path is empty filename is autogenerated
[ "Write", "writes", "merged", "netplan", "yaml", "to", "file", "specified", "by", "path", ".", "If", "path", "is", "empty", "filename", "is", "autogenerated" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/netplan/netplan.go#L431-L465
4,443
juju/juju
network/netplan/netplan.go
Rollback
func (np *Netplan) Rollback() (err error) { if np.writtenFile != "" { os.Remove(np.writtenFile) } for oldFile, newFile := range np.backedFiles { err = os.Rename(newFile, oldFile) if err != nil { logger.Errorf("Cannot rename %s to %s - %q", newFile, oldFile, err.Error()) } } np.backedFiles = nil np.writtenFile = "" return nil }
go
func (np *Netplan) Rollback() (err error) { if np.writtenFile != "" { os.Remove(np.writtenFile) } for oldFile, newFile := range np.backedFiles { err = os.Rename(newFile, oldFile) if err != nil { logger.Errorf("Cannot rename %s to %s - %q", newFile, oldFile, err.Error()) } } np.backedFiles = nil np.writtenFile = "" return nil }
[ "func", "(", "np", "*", "Netplan", ")", "Rollback", "(", ")", "(", "err", "error", ")", "{", "if", "np", ".", "writtenFile", "!=", "\"", "\"", "{", "os", ".", "Remove", "(", "np", ".", "writtenFile", ")", "\n", "}", "\n", "for", "oldFile", ",", "newFile", ":=", "range", "np", ".", "backedFiles", "{", "err", "=", "os", ".", "Rename", "(", "newFile", ",", "oldFile", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "newFile", ",", "oldFile", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "\n", "np", ".", "backedFiles", "=", "nil", "\n", "np", ".", "writtenFile", "=", "\"", "\"", "\n", "return", "nil", "\n", "}" ]
// Rollback moves backed up files to original locations and removes written file
[ "Rollback", "moves", "backed", "up", "files", "to", "original", "locations", "and", "removes", "written", "file" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/netplan/netplan.go#L468-L481
4,444
juju/juju
network/netplan/netplan.go
FindDeviceByNameOrMAC
func (np *Netplan) FindDeviceByNameOrMAC(name, mac string) (string, DeviceType, error) { if name != "" { bond, err := np.FindBondByName(name) if err == nil { return bond, TypeBond, nil } if !errors.IsNotFound(err) { return "", "", errors.Trace(err) } vlan, err := np.FindVLANByName(name) if err == nil { return vlan, TypeVLAN, nil } ethernet, err := np.FindEthernetByName(name) if err == nil { return ethernet, TypeEthernet, nil } } // by MAC is less reliable because things like vlans often have the same MAC address if mac != "" { bond, err := np.FindBondByMAC(mac) if err == nil { return bond, TypeBond, nil } if !errors.IsNotFound(err) { return "", "", errors.Trace(err) } vlan, err := np.FindVLANByMAC(mac) if err == nil { return vlan, TypeVLAN, nil } ethernet, err := np.FindEthernetByMAC(mac) if err == nil { return ethernet, TypeEthernet, nil } } return "", "", errors.NotFoundf("device - name %q MAC %q", name, mac) }
go
func (np *Netplan) FindDeviceByNameOrMAC(name, mac string) (string, DeviceType, error) { if name != "" { bond, err := np.FindBondByName(name) if err == nil { return bond, TypeBond, nil } if !errors.IsNotFound(err) { return "", "", errors.Trace(err) } vlan, err := np.FindVLANByName(name) if err == nil { return vlan, TypeVLAN, nil } ethernet, err := np.FindEthernetByName(name) if err == nil { return ethernet, TypeEthernet, nil } } // by MAC is less reliable because things like vlans often have the same MAC address if mac != "" { bond, err := np.FindBondByMAC(mac) if err == nil { return bond, TypeBond, nil } if !errors.IsNotFound(err) { return "", "", errors.Trace(err) } vlan, err := np.FindVLANByMAC(mac) if err == nil { return vlan, TypeVLAN, nil } ethernet, err := np.FindEthernetByMAC(mac) if err == nil { return ethernet, TypeEthernet, nil } } return "", "", errors.NotFoundf("device - name %q MAC %q", name, mac) }
[ "func", "(", "np", "*", "Netplan", ")", "FindDeviceByNameOrMAC", "(", "name", ",", "mac", "string", ")", "(", "string", ",", "DeviceType", ",", "error", ")", "{", "if", "name", "!=", "\"", "\"", "{", "bond", ",", "err", ":=", "np", ".", "FindBondByName", "(", "name", ")", "\n", "if", "err", "==", "nil", "{", "return", "bond", ",", "TypeBond", ",", "nil", "\n", "}", "\n", "if", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "vlan", ",", "err", ":=", "np", ".", "FindVLANByName", "(", "name", ")", "\n", "if", "err", "==", "nil", "{", "return", "vlan", ",", "TypeVLAN", ",", "nil", "\n", "}", "\n", "ethernet", ",", "err", ":=", "np", ".", "FindEthernetByName", "(", "name", ")", "\n", "if", "err", "==", "nil", "{", "return", "ethernet", ",", "TypeEthernet", ",", "nil", "\n", "}", "\n\n", "}", "\n", "// by MAC is less reliable because things like vlans often have the same MAC address", "if", "mac", "!=", "\"", "\"", "{", "bond", ",", "err", ":=", "np", ".", "FindBondByMAC", "(", "mac", ")", "\n", "if", "err", "==", "nil", "{", "return", "bond", ",", "TypeBond", ",", "nil", "\n", "}", "\n", "if", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "vlan", ",", "err", ":=", "np", ".", "FindVLANByMAC", "(", "mac", ")", "\n", "if", "err", "==", "nil", "{", "return", "vlan", ",", "TypeVLAN", ",", "nil", "\n", "}", "\n", "ethernet", ",", "err", ":=", "np", ".", "FindEthernetByMAC", "(", "mac", ")", "\n", "if", "err", "==", "nil", "{", "return", "ethernet", ",", "TypeEthernet", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", ",", "\"", "\"", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "name", ",", "mac", ")", "\n", "}" ]
// FindDeviceByMACOrName will look for an Ethernet, VLAN or Bond matching the Name of the device or its MAC address. // Name is preferred to MAC address.
[ "FindDeviceByMACOrName", "will", "look", "for", "an", "Ethernet", "VLAN", "or", "Bond", "matching", "the", "Name", "of", "the", "device", "or", "its", "MAC", "address", ".", "Name", "is", "preferred", "to", "MAC", "address", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/netplan/netplan.go#L555-L593
4,445
juju/juju
apiserver/common/modelwatcher.go
NewModelWatcher
func NewModelWatcher(st state.ModelAccessor, resources facade.Resources, authorizer facade.Authorizer) *ModelWatcher { return &ModelWatcher{ st: st, resources: resources, authorizer: authorizer, } }
go
func NewModelWatcher(st state.ModelAccessor, resources facade.Resources, authorizer facade.Authorizer) *ModelWatcher { return &ModelWatcher{ st: st, resources: resources, authorizer: authorizer, } }
[ "func", "NewModelWatcher", "(", "st", "state", ".", "ModelAccessor", ",", "resources", "facade", ".", "Resources", ",", "authorizer", "facade", ".", "Authorizer", ")", "*", "ModelWatcher", "{", "return", "&", "ModelWatcher", "{", "st", ":", "st", ",", "resources", ":", "resources", ",", "authorizer", ":", "authorizer", ",", "}", "\n", "}" ]
// NewModelWatcher returns a new ModelWatcher. Active watchers // will be stored in the provided Resources. The two GetAuthFunc // callbacks will be used on each invocation of the methods to // determine current permissions. // Right now, model tags are not used, so both created AuthFuncs // are called with "" for tag, which means "the current model".
[ "NewModelWatcher", "returns", "a", "new", "ModelWatcher", ".", "Active", "watchers", "will", "be", "stored", "in", "the", "provided", "Resources", ".", "The", "two", "GetAuthFunc", "callbacks", "will", "be", "used", "on", "each", "invocation", "of", "the", "methods", "to", "determine", "current", "permissions", ".", "Right", "now", "model", "tags", "are", "not", "used", "so", "both", "created", "AuthFuncs", "are", "called", "with", "for", "tag", "which", "means", "the", "current", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/modelwatcher.go#L27-L33
4,446
juju/juju
apiserver/common/modelwatcher.go
WatchForModelConfigChanges
func (m *ModelWatcher) WatchForModelConfigChanges() (params.NotifyWatchResult, error) { result := params.NotifyWatchResult{} watch := m.st.WatchForModelConfigChanges() // Consume the initial event. Technically, API // calls to Watch 'transmit' the initial event // in the Watch response. But NotifyWatchers // have no state to transmit. if _, ok := <-watch.Changes(); ok { result.NotifyWatcherId = m.resources.Register(watch) } else { return result, watcher.EnsureErr(watch) } return result, nil }
go
func (m *ModelWatcher) WatchForModelConfigChanges() (params.NotifyWatchResult, error) { result := params.NotifyWatchResult{} watch := m.st.WatchForModelConfigChanges() // Consume the initial event. Technically, API // calls to Watch 'transmit' the initial event // in the Watch response. But NotifyWatchers // have no state to transmit. if _, ok := <-watch.Changes(); ok { result.NotifyWatcherId = m.resources.Register(watch) } else { return result, watcher.EnsureErr(watch) } return result, nil }
[ "func", "(", "m", "*", "ModelWatcher", ")", "WatchForModelConfigChanges", "(", ")", "(", "params", ".", "NotifyWatchResult", ",", "error", ")", "{", "result", ":=", "params", ".", "NotifyWatchResult", "{", "}", "\n", "watch", ":=", "m", ".", "st", ".", "WatchForModelConfigChanges", "(", ")", "\n", "// Consume the initial event. Technically, API", "// calls to Watch 'transmit' the initial event", "// in the Watch response. But NotifyWatchers", "// have no state to transmit.", "if", "_", ",", "ok", ":=", "<-", "watch", ".", "Changes", "(", ")", ";", "ok", "{", "result", ".", "NotifyWatcherId", "=", "m", ".", "resources", ".", "Register", "(", "watch", ")", "\n", "}", "else", "{", "return", "result", ",", "watcher", ".", "EnsureErr", "(", "watch", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// WatchForModelConfigChanges returns a NotifyWatcher that observes // changes to the model configuration. // Note that although the NotifyWatchResult contains an Error field, // it's not used because we are only returning a single watcher, // so we use the regular error return.
[ "WatchForModelConfigChanges", "returns", "a", "NotifyWatcher", "that", "observes", "changes", "to", "the", "model", "configuration", ".", "Note", "that", "although", "the", "NotifyWatchResult", "contains", "an", "Error", "field", "it", "s", "not", "used", "because", "we", "are", "only", "returning", "a", "single", "watcher", "so", "we", "use", "the", "regular", "error", "return", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/modelwatcher.go#L40-L53
4,447
juju/juju
apiserver/common/modelwatcher.go
ModelConfig
func (m *ModelWatcher) ModelConfig() (params.ModelConfigResult, error) { result := params.ModelConfigResult{} config, err := m.st.ModelConfig() if err != nil { return result, err } result.Config = config.AllAttrs() return result, nil }
go
func (m *ModelWatcher) ModelConfig() (params.ModelConfigResult, error) { result := params.ModelConfigResult{} config, err := m.st.ModelConfig() if err != nil { return result, err } result.Config = config.AllAttrs() return result, nil }
[ "func", "(", "m", "*", "ModelWatcher", ")", "ModelConfig", "(", ")", "(", "params", ".", "ModelConfigResult", ",", "error", ")", "{", "result", ":=", "params", ".", "ModelConfigResult", "{", "}", "\n", "config", ",", "err", ":=", "m", ".", "st", ".", "ModelConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n", "result", ".", "Config", "=", "config", ".", "AllAttrs", "(", ")", "\n", "return", "result", ",", "nil", "\n", "}" ]
// ModelConfig returns the current model's configuration.
[ "ModelConfig", "returns", "the", "current", "model", "s", "configuration", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/modelwatcher.go#L56-L64
4,448
juju/juju
worker/raft/raftbackstop/worker.go
recoverViaBootstrap
func (w *backstopWorker) recoverViaBootstrap(server *raft.Server) error { newServer := *server newServer.Suffrage = raft.Voter configuration := raft.Configuration{ Servers: []raft.Server{newServer}, } w.config.Logger.Infof("rebootstrapping raft configuration: %#v", configuration) err := w.config.Raft.BootstrapCluster(configuration).Error() if err != nil { return errors.Annotate(err, "re-bootstrapping cluster") } return nil }
go
func (w *backstopWorker) recoverViaBootstrap(server *raft.Server) error { newServer := *server newServer.Suffrage = raft.Voter configuration := raft.Configuration{ Servers: []raft.Server{newServer}, } w.config.Logger.Infof("rebootstrapping raft configuration: %#v", configuration) err := w.config.Raft.BootstrapCluster(configuration).Error() if err != nil { return errors.Annotate(err, "re-bootstrapping cluster") } return nil }
[ "func", "(", "w", "*", "backstopWorker", ")", "recoverViaBootstrap", "(", "server", "*", "raft", ".", "Server", ")", "error", "{", "newServer", ":=", "*", "server", "\n", "newServer", ".", "Suffrage", "=", "raft", ".", "Voter", "\n", "configuration", ":=", "raft", ".", "Configuration", "{", "Servers", ":", "[", "]", "raft", ".", "Server", "{", "newServer", "}", ",", "}", "\n", "w", ".", "config", ".", "Logger", ".", "Infof", "(", "\"", "\"", ",", "configuration", ")", "\n", "err", ":=", "w", ".", "config", ".", "Raft", ".", "BootstrapCluster", "(", "configuration", ")", ".", "Error", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// recoverViaBootstrap re-initializes the raft cluster. This should only be // used in the case that the raft directory has been completely wiped.
[ "recoverViaBootstrap", "re", "-", "initializes", "the", "raft", "cluster", ".", "This", "should", "only", "be", "used", "in", "the", "case", "that", "the", "raft", "directory", "has", "been", "completely", "wiped", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/raft/raftbackstop/worker.go#L240-L252
4,449
juju/juju
apiserver/facades/client/application/backend.go
NewStateApplication
func NewStateApplication(st *state.State, app *state.Application) Application { return stateApplicationShim{app, st} }
go
func NewStateApplication(st *state.State, app *state.Application) Application { return stateApplicationShim{app, st} }
[ "func", "NewStateApplication", "(", "st", "*", "state", ".", "State", ",", "app", "*", "state", ".", "Application", ")", "Application", "{", "return", "stateApplicationShim", "{", "app", ",", "st", "}", "\n", "}" ]
// NewStateApplication converts a state.Application into an Application.
[ "NewStateApplication", "converts", "a", "state", ".", "Application", "into", "an", "Application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/application/backend.go#L224-L226
4,450
juju/juju
upgrades/steps_21.go
stateStepsFor21
func stateStepsFor21() []Step { return []Step{ &upgradeStep{ description: "add attempt to migration docs", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().AddMigrationAttempt() }, }, &upgradeStep{ description: "add sequences to track used local charm revisions", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().AddLocalCharmSequences() }, }, &upgradeStep{ description: "update lxd cloud/credentials", targets: []Target{DatabaseMaster}, run: func(context Context) error { return updateLXDCloudCredentials(context.State()) }, }, } }
go
func stateStepsFor21() []Step { return []Step{ &upgradeStep{ description: "add attempt to migration docs", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().AddMigrationAttempt() }, }, &upgradeStep{ description: "add sequences to track used local charm revisions", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().AddLocalCharmSequences() }, }, &upgradeStep{ description: "update lxd cloud/credentials", targets: []Target{DatabaseMaster}, run: func(context Context) error { return updateLXDCloudCredentials(context.State()) }, }, } }
[ "func", "stateStepsFor21", "(", ")", "[", "]", "Step", "{", "return", "[", "]", "Step", "{", "&", "upgradeStep", "{", "description", ":", "\"", "\"", ",", "targets", ":", "[", "]", "Target", "{", "DatabaseMaster", "}", ",", "run", ":", "func", "(", "context", "Context", ")", "error", "{", "return", "context", ".", "State", "(", ")", ".", "AddMigrationAttempt", "(", ")", "\n", "}", ",", "}", ",", "&", "upgradeStep", "{", "description", ":", "\"", "\"", ",", "targets", ":", "[", "]", "Target", "{", "DatabaseMaster", "}", ",", "run", ":", "func", "(", "context", "Context", ")", "error", "{", "return", "context", ".", "State", "(", ")", ".", "AddLocalCharmSequences", "(", ")", "\n", "}", ",", "}", ",", "&", "upgradeStep", "{", "description", ":", "\"", "\"", ",", "targets", ":", "[", "]", "Target", "{", "DatabaseMaster", "}", ",", "run", ":", "func", "(", "context", "Context", ")", "error", "{", "return", "updateLXDCloudCredentials", "(", "context", ".", "State", "(", ")", ")", "\n", "}", ",", "}", ",", "}", "\n", "}" ]
// stateStepsFor21 returns upgrade steps for Juju 2.1 that manipulate state directly.
[ "stateStepsFor21", "returns", "upgrade", "steps", "for", "Juju", "2", ".", "1", "that", "manipulate", "state", "directly", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/upgrades/steps_21.go#L7-L31
4,451
juju/juju
payload/context/context.go
NewContext
func NewContext(api APIClient, dataDir string) *Context { return &Context{ api: api, dataDir: dataDir, payloads: make(map[string]payload.Payload), updates: make(map[string]payload.Payload), } }
go
func NewContext(api APIClient, dataDir string) *Context { return &Context{ api: api, dataDir: dataDir, payloads: make(map[string]payload.Payload), updates: make(map[string]payload.Payload), } }
[ "func", "NewContext", "(", "api", "APIClient", ",", "dataDir", "string", ")", "*", "Context", "{", "return", "&", "Context", "{", "api", ":", "api", ",", "dataDir", ":", "dataDir", ",", "payloads", ":", "make", "(", "map", "[", "string", "]", "payload", ".", "Payload", ")", ",", "updates", ":", "make", "(", "map", "[", "string", "]", "payload", ".", "Payload", ")", ",", "}", "\n", "}" ]
// NewContext returns a new hooks.ContextComponent for payloads.
[ "NewContext", "returns", "a", "new", "hooks", ".", "ContextComponent", "for", "payloads", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/payload/context/context.go#L60-L67
4,452
juju/juju
payload/context/context.go
NewContextAPI
func NewContextAPI(api APIClient, dataDir string) (*Context, error) { results, err := api.List() if err != nil { return nil, errors.Trace(err) } ctx := NewContext(api, dataDir) for _, result := range results { pl := result.Payload // TODO(ericsnow) Use id instead of pl.FullID(). ctx.payloads[pl.FullID()] = pl.Payload } return ctx, nil }
go
func NewContextAPI(api APIClient, dataDir string) (*Context, error) { results, err := api.List() if err != nil { return nil, errors.Trace(err) } ctx := NewContext(api, dataDir) for _, result := range results { pl := result.Payload // TODO(ericsnow) Use id instead of pl.FullID(). ctx.payloads[pl.FullID()] = pl.Payload } return ctx, nil }
[ "func", "NewContextAPI", "(", "api", "APIClient", ",", "dataDir", "string", ")", "(", "*", "Context", ",", "error", ")", "{", "results", ",", "err", ":=", "api", ".", "List", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "ctx", ":=", "NewContext", "(", "api", ",", "dataDir", ")", "\n", "for", "_", ",", "result", ":=", "range", "results", "{", "pl", ":=", "result", ".", "Payload", "\n", "// TODO(ericsnow) Use id instead of pl.FullID().", "ctx", ".", "payloads", "[", "pl", ".", "FullID", "(", ")", "]", "=", "pl", ".", "Payload", "\n", "}", "\n", "return", "ctx", ",", "nil", "\n", "}" ]
// NewContextAPI returns a new hooks.ContextComponent for payloads.
[ "NewContextAPI", "returns", "a", "new", "hooks", ".", "ContextComponent", "for", "payloads", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/payload/context/context.go#L70-L83
4,453
juju/juju
payload/context/context.go
ContextComponent
func ContextComponent(ctx HookContext) (Component, error) { compCtx, err := ctx.Component(payload.ComponentName) if errors.IsNotFound(err) { return nil, errors.Errorf("component %q not registered", payload.ComponentName) } if err != nil { return nil, errors.Trace(err) } if compCtx == nil { return nil, errors.Errorf("component %q disabled", payload.ComponentName) } return compCtx, nil }
go
func ContextComponent(ctx HookContext) (Component, error) { compCtx, err := ctx.Component(payload.ComponentName) if errors.IsNotFound(err) { return nil, errors.Errorf("component %q not registered", payload.ComponentName) } if err != nil { return nil, errors.Trace(err) } if compCtx == nil { return nil, errors.Errorf("component %q disabled", payload.ComponentName) } return compCtx, nil }
[ "func", "ContextComponent", "(", "ctx", "HookContext", ")", "(", "Component", ",", "error", ")", "{", "compCtx", ",", "err", ":=", "ctx", ".", "Component", "(", "payload", ".", "ComponentName", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "payload", ".", "ComponentName", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "compCtx", "==", "nil", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "payload", ".", "ComponentName", ")", "\n", "}", "\n", "return", "compCtx", ",", "nil", "\n", "}" ]
// ContextComponent returns the hook context for the payload // payload component.
[ "ContextComponent", "returns", "the", "hook", "context", "for", "the", "payload", "payload", "component", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/payload/context/context.go#L93-L105
4,454
juju/juju
payload/context/context.go
Get
func (c *Context) Get(class, id string) (*payload.Payload, error) { fullID := payload.BuildID(class, id) logger.Tracef("getting %q from hook context", fullID) actual, ok := c.updates[fullID] if !ok { actual, ok = c.payloads[fullID] if !ok { return nil, errors.NotFoundf("%s", fullID) } } return &actual, nil }
go
func (c *Context) Get(class, id string) (*payload.Payload, error) { fullID := payload.BuildID(class, id) logger.Tracef("getting %q from hook context", fullID) actual, ok := c.updates[fullID] if !ok { actual, ok = c.payloads[fullID] if !ok { return nil, errors.NotFoundf("%s", fullID) } } return &actual, nil }
[ "func", "(", "c", "*", "Context", ")", "Get", "(", "class", ",", "id", "string", ")", "(", "*", "payload", ".", "Payload", ",", "error", ")", "{", "fullID", ":=", "payload", ".", "BuildID", "(", "class", ",", "id", ")", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "fullID", ")", "\n\n", "actual", ",", "ok", ":=", "c", ".", "updates", "[", "fullID", "]", "\n", "if", "!", "ok", "{", "actual", ",", "ok", "=", "c", ".", "payloads", "[", "fullID", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "fullID", ")", "\n", "}", "\n", "}", "\n", "return", "&", "actual", ",", "nil", "\n", "}" ]
// Get returns the payload info corresponding to the given ID.
[ "Get", "returns", "the", "payload", "info", "corresponding", "to", "the", "given", "ID", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/payload/context/context.go#L134-L146
4,455
juju/juju
payload/context/context.go
List
func (c *Context) List() ([]string, error) { logger.Tracef("listing all payloads in hook context") payloads, err := c.Payloads() if err != nil { return nil, errors.Trace(err) } if len(payloads) == 0 { return nil, nil } var ids []string for _, wl := range payloads { ids = append(ids, wl.FullID()) } sort.Strings(ids) return ids, nil }
go
func (c *Context) List() ([]string, error) { logger.Tracef("listing all payloads in hook context") payloads, err := c.Payloads() if err != nil { return nil, errors.Trace(err) } if len(payloads) == 0 { return nil, nil } var ids []string for _, wl := range payloads { ids = append(ids, wl.FullID()) } sort.Strings(ids) return ids, nil }
[ "func", "(", "c", "*", "Context", ")", "List", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "logger", ".", "Tracef", "(", "\"", "\"", ")", "\n\n", "payloads", ",", "err", ":=", "c", ".", "Payloads", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "payloads", ")", "==", "0", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "var", "ids", "[", "]", "string", "\n", "for", "_", ",", "wl", ":=", "range", "payloads", "{", "ids", "=", "append", "(", "ids", ",", "wl", ".", "FullID", "(", ")", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "ids", ")", "\n", "return", "ids", ",", "nil", "\n", "}" ]
// List returns the sorted names of all registered payloads.
[ "List", "returns", "the", "sorted", "names", "of", "all", "registered", "payloads", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/payload/context/context.go#L149-L165
4,456
juju/juju
payload/context/context.go
Track
func (c *Context) Track(pl payload.Payload) error { logger.Tracef("adding %q to hook context: %#v", pl.FullID(), pl) if err := pl.Validate(); err != nil { return errors.Trace(err) } // TODO(ericsnow) We are likely missing mechanism for local persistence. id := pl.FullID() c.updates[id] = pl return nil }
go
func (c *Context) Track(pl payload.Payload) error { logger.Tracef("adding %q to hook context: %#v", pl.FullID(), pl) if err := pl.Validate(); err != nil { return errors.Trace(err) } // TODO(ericsnow) We are likely missing mechanism for local persistence. id := pl.FullID() c.updates[id] = pl return nil }
[ "func", "(", "c", "*", "Context", ")", "Track", "(", "pl", "payload", ".", "Payload", ")", "error", "{", "logger", ".", "Tracef", "(", "\"", "\"", ",", "pl", ".", "FullID", "(", ")", ",", "pl", ")", "\n\n", "if", "err", ":=", "pl", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// TODO(ericsnow) We are likely missing mechanism for local persistence.", "id", ":=", "pl", ".", "FullID", "(", ")", "\n", "c", ".", "updates", "[", "id", "]", "=", "pl", "\n", "return", "nil", "\n", "}" ]
// Track records the payload info in the hook context.
[ "Track", "records", "the", "payload", "info", "in", "the", "hook", "context", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/payload/context/context.go#L168-L179
4,457
juju/juju
payload/context/context.go
Untrack
func (c *Context) Untrack(class, id string) error { fullID := payload.BuildID(class, id) logger.Tracef("Calling untrack on payload context %q", fullID) res, err := c.api.Untrack(fullID) if err != nil { return errors.Trace(err) } // TODO(ericsnow) We should not ignore a 0-len result. if len(res) > 0 && res[0].Error != nil { return errors.Trace(res[0].Error) } delete(c.payloads, id) return nil }
go
func (c *Context) Untrack(class, id string) error { fullID := payload.BuildID(class, id) logger.Tracef("Calling untrack on payload context %q", fullID) res, err := c.api.Untrack(fullID) if err != nil { return errors.Trace(err) } // TODO(ericsnow) We should not ignore a 0-len result. if len(res) > 0 && res[0].Error != nil { return errors.Trace(res[0].Error) } delete(c.payloads, id) return nil }
[ "func", "(", "c", "*", "Context", ")", "Untrack", "(", "class", ",", "id", "string", ")", "error", "{", "fullID", ":=", "payload", ".", "BuildID", "(", "class", ",", "id", ")", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "fullID", ")", "\n\n", "res", ",", "err", ":=", "c", ".", "api", ".", "Untrack", "(", "fullID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// TODO(ericsnow) We should not ignore a 0-len result.", "if", "len", "(", "res", ")", ">", "0", "&&", "res", "[", "0", "]", ".", "Error", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "res", "[", "0", "]", ".", "Error", ")", "\n", "}", "\n", "delete", "(", "c", ".", "payloads", ",", "id", ")", "\n\n", "return", "nil", "\n", "}" ]
// Untrack tells juju to stop tracking this payload.
[ "Untrack", "tells", "juju", "to", "stop", "tracking", "this", "payload", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/payload/context/context.go#L182-L197
4,458
juju/juju
payload/context/context.go
SetStatus
func (c *Context) SetStatus(class, id, status string) error { fullID := payload.BuildID(class, id) logger.Tracef("Calling status-set on payload context %q", fullID) res, err := c.api.SetStatus(status, fullID) if err != nil { return errors.Trace(err) } // TODO(ericsnow) We should not ignore a 0-len result. if len(res) > 0 && res[0].Error != nil { // In a hook context, the case where the specified payload does // not exist is a special one. A hook tool is how a charm author // communicates the state of the charm. So returning an error // here in the "missing" case makes less sense than in other // places. We could simply ignore any error that surfaces for // that case. However, returning the error communicates to the // charm author that what they're trying to communicate doesn't // make sense. return errors.Trace(res[0].Error) } return nil }
go
func (c *Context) SetStatus(class, id, status string) error { fullID := payload.BuildID(class, id) logger.Tracef("Calling status-set on payload context %q", fullID) res, err := c.api.SetStatus(status, fullID) if err != nil { return errors.Trace(err) } // TODO(ericsnow) We should not ignore a 0-len result. if len(res) > 0 && res[0].Error != nil { // In a hook context, the case where the specified payload does // not exist is a special one. A hook tool is how a charm author // communicates the state of the charm. So returning an error // here in the "missing" case makes less sense than in other // places. We could simply ignore any error that surfaces for // that case. However, returning the error communicates to the // charm author that what they're trying to communicate doesn't // make sense. return errors.Trace(res[0].Error) } return nil }
[ "func", "(", "c", "*", "Context", ")", "SetStatus", "(", "class", ",", "id", ",", "status", "string", ")", "error", "{", "fullID", ":=", "payload", ".", "BuildID", "(", "class", ",", "id", ")", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "fullID", ")", "\n\n", "res", ",", "err", ":=", "c", ".", "api", ".", "SetStatus", "(", "status", ",", "fullID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// TODO(ericsnow) We should not ignore a 0-len result.", "if", "len", "(", "res", ")", ">", "0", "&&", "res", "[", "0", "]", ".", "Error", "!=", "nil", "{", "// In a hook context, the case where the specified payload does", "// not exist is a special one. A hook tool is how a charm author", "// communicates the state of the charm. So returning an error", "// here in the \"missing\" case makes less sense than in other", "// places. We could simply ignore any error that surfaces for", "// that case. However, returning the error communicates to the", "// charm author that what they're trying to communicate doesn't", "// make sense.", "return", "errors", ".", "Trace", "(", "res", "[", "0", "]", ".", "Error", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// SetStatus sets the identified payload's status.
[ "SetStatus", "sets", "the", "identified", "payload", "s", "status", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/payload/context/context.go#L200-L222
4,459
juju/juju
api/machineundertaker/undertaker.go
NewAPI
func NewAPI(caller base.APICaller, newWatcher NewWatcherFunc) (*API, error) { modelTag, ok := caller.ModelTag() if !ok { return nil, errors.New("machine undertaker client requires a model API connection") } api := API{ facade: base.NewFacadeCaller(caller, "MachineUndertaker"), modelTag: modelTag, newWatcher: newWatcher, } return &api, nil }
go
func NewAPI(caller base.APICaller, newWatcher NewWatcherFunc) (*API, error) { modelTag, ok := caller.ModelTag() if !ok { return nil, errors.New("machine undertaker client requires a model API connection") } api := API{ facade: base.NewFacadeCaller(caller, "MachineUndertaker"), modelTag: modelTag, newWatcher: newWatcher, } return &api, nil }
[ "func", "NewAPI", "(", "caller", "base", ".", "APICaller", ",", "newWatcher", "NewWatcherFunc", ")", "(", "*", "API", ",", "error", ")", "{", "modelTag", ",", "ok", ":=", "caller", ".", "ModelTag", "(", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "api", ":=", "API", "{", "facade", ":", "base", ".", "NewFacadeCaller", "(", "caller", ",", "\"", "\"", ")", ",", "modelTag", ":", "modelTag", ",", "newWatcher", ":", "newWatcher", ",", "}", "\n", "return", "&", "api", ",", "nil", "\n", "}" ]
// NewAPI creates a new client-side machine undertaker facade.
[ "NewAPI", "creates", "a", "new", "client", "-", "side", "machine", "undertaker", "facade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/machineundertaker/undertaker.go#L27-L38
4,460
juju/juju
api/machineundertaker/undertaker.go
AllMachineRemovals
func (api *API) AllMachineRemovals() ([]names.MachineTag, error) { var results params.EntitiesResults args := wrapEntities(api.modelTag) err := api.facade.FacadeCall("AllMachineRemovals", &args, &results) if err != nil { return nil, errors.Trace(err) } if len(results.Results) != 1 { return nil, errors.Errorf("expected one result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return nil, errors.Trace(result.Error) } machines := make([]names.MachineTag, len(result.Entities)) for i, entity := range result.Entities { tag, err := names.ParseMachineTag(entity.Tag) if err != nil { return nil, errors.Trace(err) } machines[i] = tag } return machines, nil }
go
func (api *API) AllMachineRemovals() ([]names.MachineTag, error) { var results params.EntitiesResults args := wrapEntities(api.modelTag) err := api.facade.FacadeCall("AllMachineRemovals", &args, &results) if err != nil { return nil, errors.Trace(err) } if len(results.Results) != 1 { return nil, errors.Errorf("expected one result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return nil, errors.Trace(result.Error) } machines := make([]names.MachineTag, len(result.Entities)) for i, entity := range result.Entities { tag, err := names.ParseMachineTag(entity.Tag) if err != nil { return nil, errors.Trace(err) } machines[i] = tag } return machines, nil }
[ "func", "(", "api", "*", "API", ")", "AllMachineRemovals", "(", ")", "(", "[", "]", "names", ".", "MachineTag", ",", "error", ")", "{", "var", "results", "params", ".", "EntitiesResults", "\n", "args", ":=", "wrapEntities", "(", "api", ".", "modelTag", ")", "\n", "err", ":=", "api", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "&", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "result", ":=", "results", ".", "Results", "[", "0", "]", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "result", ".", "Error", ")", "\n", "}", "\n", "machines", ":=", "make", "(", "[", "]", "names", ".", "MachineTag", ",", "len", "(", "result", ".", "Entities", ")", ")", "\n", "for", "i", ",", "entity", ":=", "range", "result", ".", "Entities", "{", "tag", ",", "err", ":=", "names", ".", "ParseMachineTag", "(", "entity", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "machines", "[", "i", "]", "=", "tag", "\n", "}", "\n", "return", "machines", ",", "nil", "\n", "}" ]
// AllMachineRemovals returns all the machines that have been marked // ready to clean up.
[ "AllMachineRemovals", "returns", "all", "the", "machines", "that", "have", "been", "marked", "ready", "to", "clean", "up", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/machineundertaker/undertaker.go#L42-L65
4,461
juju/juju
api/machineundertaker/undertaker.go
GetProviderInterfaceInfo
func (api *API) GetProviderInterfaceInfo(machine names.MachineTag) ([]network.ProviderInterfaceInfo, error) { var result params.ProviderInterfaceInfoResults args := wrapEntities(machine) err := api.facade.FacadeCall("GetMachineProviderInterfaceInfo", &args, &result) if err != nil { return nil, errors.Trace(err) } if len(result.Results) != 1 { return nil, errors.Errorf("expected one result, got %d", len(result.Results)) } item := result.Results[0] if item.MachineTag != machine.String() { return nil, errors.Errorf("expected interface info for %s but got %s", machine, item.MachineTag) } infos := make([]network.ProviderInterfaceInfo, len(item.Interfaces)) for i, info := range item.Interfaces { infos[i].InterfaceName = info.InterfaceName infos[i].MACAddress = info.MACAddress infos[i].ProviderId = network.Id(info.ProviderId) } return infos, nil }
go
func (api *API) GetProviderInterfaceInfo(machine names.MachineTag) ([]network.ProviderInterfaceInfo, error) { var result params.ProviderInterfaceInfoResults args := wrapEntities(machine) err := api.facade.FacadeCall("GetMachineProviderInterfaceInfo", &args, &result) if err != nil { return nil, errors.Trace(err) } if len(result.Results) != 1 { return nil, errors.Errorf("expected one result, got %d", len(result.Results)) } item := result.Results[0] if item.MachineTag != machine.String() { return nil, errors.Errorf("expected interface info for %s but got %s", machine, item.MachineTag) } infos := make([]network.ProviderInterfaceInfo, len(item.Interfaces)) for i, info := range item.Interfaces { infos[i].InterfaceName = info.InterfaceName infos[i].MACAddress = info.MACAddress infos[i].ProviderId = network.Id(info.ProviderId) } return infos, nil }
[ "func", "(", "api", "*", "API", ")", "GetProviderInterfaceInfo", "(", "machine", "names", ".", "MachineTag", ")", "(", "[", "]", "network", ".", "ProviderInterfaceInfo", ",", "error", ")", "{", "var", "result", "params", ".", "ProviderInterfaceInfoResults", "\n", "args", ":=", "wrapEntities", "(", "machine", ")", "\n", "err", ":=", "api", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "&", "args", ",", "&", "result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "result", ".", "Results", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "result", ".", "Results", ")", ")", "\n", "}", "\n", "item", ":=", "result", ".", "Results", "[", "0", "]", "\n", "if", "item", ".", "MachineTag", "!=", "machine", ".", "String", "(", ")", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "machine", ",", "item", ".", "MachineTag", ")", "\n", "}", "\n", "infos", ":=", "make", "(", "[", "]", "network", ".", "ProviderInterfaceInfo", ",", "len", "(", "item", ".", "Interfaces", ")", ")", "\n", "for", "i", ",", "info", ":=", "range", "item", ".", "Interfaces", "{", "infos", "[", "i", "]", ".", "InterfaceName", "=", "info", ".", "InterfaceName", "\n", "infos", "[", "i", "]", ".", "MACAddress", "=", "info", ".", "MACAddress", "\n", "infos", "[", "i", "]", ".", "ProviderId", "=", "network", ".", "Id", "(", "info", ".", "ProviderId", ")", "\n", "}", "\n", "return", "infos", ",", "nil", "\n", "}" ]
// GetProviderInterfaceInfo gets the provider details for all of the // interfaces for one machine.
[ "GetProviderInterfaceInfo", "gets", "the", "provider", "details", "for", "all", "of", "the", "interfaces", "for", "one", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/machineundertaker/undertaker.go#L69-L90
4,462
juju/juju
api/machineundertaker/undertaker.go
CompleteRemoval
func (api *API) CompleteRemoval(machine names.MachineTag) error { args := wrapEntities(machine) return api.facade.FacadeCall("CompleteMachineRemovals", &args, nil) }
go
func (api *API) CompleteRemoval(machine names.MachineTag) error { args := wrapEntities(machine) return api.facade.FacadeCall("CompleteMachineRemovals", &args, nil) }
[ "func", "(", "api", "*", "API", ")", "CompleteRemoval", "(", "machine", "names", ".", "MachineTag", ")", "error", "{", "args", ":=", "wrapEntities", "(", "machine", ")", "\n", "return", "api", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "&", "args", ",", "nil", ")", "\n", "}" ]
// CompleteRemoval finishes the removal of the machine in the database // after any provider resources are cleaned up.
[ "CompleteRemoval", "finishes", "the", "removal", "of", "the", "machine", "in", "the", "database", "after", "any", "provider", "resources", "are", "cleaned", "up", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/machineundertaker/undertaker.go#L94-L97
4,463
juju/juju
api/machineundertaker/undertaker.go
WatchMachineRemovals
func (api *API) WatchMachineRemovals() (watcher.NotifyWatcher, error) { var results params.NotifyWatchResults args := wrapEntities(api.modelTag) err := api.facade.FacadeCall("WatchMachineRemovals", &args, &results) if err != nil { return nil, errors.Trace(err) } if len(results.Results) != 1 { return nil, errors.Errorf("expected one result, got %d", len(results.Results)) } result := results.Results[0] if err := result.Error; err != nil { return nil, errors.Trace(result.Error) } w := api.newWatcher(api.facade.RawAPICaller(), result) return w, nil }
go
func (api *API) WatchMachineRemovals() (watcher.NotifyWatcher, error) { var results params.NotifyWatchResults args := wrapEntities(api.modelTag) err := api.facade.FacadeCall("WatchMachineRemovals", &args, &results) if err != nil { return nil, errors.Trace(err) } if len(results.Results) != 1 { return nil, errors.Errorf("expected one result, got %d", len(results.Results)) } result := results.Results[0] if err := result.Error; err != nil { return nil, errors.Trace(result.Error) } w := api.newWatcher(api.facade.RawAPICaller(), result) return w, nil }
[ "func", "(", "api", "*", "API", ")", "WatchMachineRemovals", "(", ")", "(", "watcher", ".", "NotifyWatcher", ",", "error", ")", "{", "var", "results", "params", ".", "NotifyWatchResults", "\n", "args", ":=", "wrapEntities", "(", "api", ".", "modelTag", ")", "\n", "err", ":=", "api", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "&", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "result", ":=", "results", ".", "Results", "[", "0", "]", "\n", "if", "err", ":=", "result", ".", "Error", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "result", ".", "Error", ")", "\n", "}", "\n", "w", ":=", "api", ".", "newWatcher", "(", "api", ".", "facade", ".", "RawAPICaller", "(", ")", ",", "result", ")", "\n", "return", "w", ",", "nil", "\n", "}" ]
// WatchMachineRemovals registers to be notified when a machine // removal is requested.
[ "WatchMachineRemovals", "registers", "to", "be", "notified", "when", "a", "machine", "removal", "is", "requested", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/machineundertaker/undertaker.go#L101-L117
4,464
juju/juju
api/modelgeneration/modelgeneration.go
AddBranch
func (c *Client) AddBranch(branchName string) error { var result params.ErrorResult err := c.facade.FacadeCall("AddBranch", argForBranch(branchName), &result) if err != nil { return errors.Trace(err) } if result.Error != nil { return errors.Trace(result.Error) } return nil }
go
func (c *Client) AddBranch(branchName string) error { var result params.ErrorResult err := c.facade.FacadeCall("AddBranch", argForBranch(branchName), &result) if err != nil { return errors.Trace(err) } if result.Error != nil { return errors.Trace(result.Error) } return nil }
[ "func", "(", "c", "*", "Client", ")", "AddBranch", "(", "branchName", "string", ")", "error", "{", "var", "result", "params", ".", "ErrorResult", "\n", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "argForBranch", "(", "branchName", ")", ",", "&", "result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "result", ".", "Error", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// AddBranch adds a new branch to the model.
[ "AddBranch", "adds", "a", "new", "branch", "to", "the", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/modelgeneration/modelgeneration.go#L32-L42
4,465
juju/juju
api/modelgeneration/modelgeneration.go
CommitBranch
func (c *Client) CommitBranch(branchName string) (int, error) { var result params.IntResult err := c.facade.FacadeCall("CommitBranch", argForBranch(branchName), &result) if err != nil { return 0, errors.Trace(err) } if result.Error != nil { return 0, errors.Trace(result.Error) } return result.Result, nil }
go
func (c *Client) CommitBranch(branchName string) (int, error) { var result params.IntResult err := c.facade.FacadeCall("CommitBranch", argForBranch(branchName), &result) if err != nil { return 0, errors.Trace(err) } if result.Error != nil { return 0, errors.Trace(result.Error) } return result.Result, nil }
[ "func", "(", "c", "*", "Client", ")", "CommitBranch", "(", "branchName", "string", ")", "(", "int", ",", "error", ")", "{", "var", "result", "params", ".", "IntResult", "\n", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "argForBranch", "(", "branchName", ")", ",", "&", "result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "0", ",", "errors", ".", "Trace", "(", "result", ".", "Error", ")", "\n", "}", "\n", "return", "result", ".", "Result", ",", "nil", "\n", "}" ]
// CommitBranch commits the branch with the input name to the model, // effectively completing it and applying all branch changes across the model. // The new generation ID of the model is returned.
[ "CommitBranch", "commits", "the", "branch", "with", "the", "input", "name", "to", "the", "model", "effectively", "completing", "it", "and", "applying", "all", "branch", "changes", "across", "the", "model", ".", "The", "new", "generation", "ID", "of", "the", "model", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/modelgeneration/modelgeneration.go#L47-L57
4,466
juju/juju
api/modelgeneration/modelgeneration.go
HasActiveBranch
func (c *Client) HasActiveBranch(branchName string) (bool, error) { var result params.BoolResult err := c.facade.FacadeCall("HasActiveBranch", argForBranch(branchName), &result) if err != nil { return false, errors.Trace(err) } if result.Error != nil { return false, errors.Trace(result.Error) } return result.Result, nil }
go
func (c *Client) HasActiveBranch(branchName string) (bool, error) { var result params.BoolResult err := c.facade.FacadeCall("HasActiveBranch", argForBranch(branchName), &result) if err != nil { return false, errors.Trace(err) } if result.Error != nil { return false, errors.Trace(result.Error) } return result.Result, nil }
[ "func", "(", "c", "*", "Client", ")", "HasActiveBranch", "(", "branchName", "string", ")", "(", "bool", ",", "error", ")", "{", "var", "result", "params", ".", "BoolResult", "\n", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "argForBranch", "(", "branchName", ")", ",", "&", "result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Trace", "(", "result", ".", "Error", ")", "\n", "}", "\n", "return", "result", ".", "Result", ",", "nil", "\n", "}" ]
// HasActiveBranch returns true if the model has an // "in-flight" branch with the input name.
[ "HasActiveBranch", "returns", "true", "if", "the", "model", "has", "an", "in", "-", "flight", "branch", "with", "the", "input", "name", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/modelgeneration/modelgeneration.go#L94-L104
4,467
juju/juju
api/modelgeneration/modelgeneration.go
BranchInfo
func (c *Client) BranchInfo( branchName string, detailed bool, formatTime func(time.Time) string, ) (model.GenerationSummaries, error) { arg := params.BranchInfoArgs{Detailed: detailed} if branchName != "" { arg.BranchNames = []string{branchName} } var result params.GenerationResults err := c.facade.FacadeCall("BranchInfo", arg, &result) if err != nil { return nil, errors.Trace(err) } if result.Error != nil { return nil, errors.Trace(result.Error) } return generationInfoFromResult(result, detailed, formatTime), nil }
go
func (c *Client) BranchInfo( branchName string, detailed bool, formatTime func(time.Time) string, ) (model.GenerationSummaries, error) { arg := params.BranchInfoArgs{Detailed: detailed} if branchName != "" { arg.BranchNames = []string{branchName} } var result params.GenerationResults err := c.facade.FacadeCall("BranchInfo", arg, &result) if err != nil { return nil, errors.Trace(err) } if result.Error != nil { return nil, errors.Trace(result.Error) } return generationInfoFromResult(result, detailed, formatTime), nil }
[ "func", "(", "c", "*", "Client", ")", "BranchInfo", "(", "branchName", "string", ",", "detailed", "bool", ",", "formatTime", "func", "(", "time", ".", "Time", ")", "string", ",", ")", "(", "model", ".", "GenerationSummaries", ",", "error", ")", "{", "arg", ":=", "params", ".", "BranchInfoArgs", "{", "Detailed", ":", "detailed", "}", "\n", "if", "branchName", "!=", "\"", "\"", "{", "arg", ".", "BranchNames", "=", "[", "]", "string", "{", "branchName", "}", "\n", "}", "\n\n", "var", "result", "params", ".", "GenerationResults", "\n", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "arg", ",", "&", "result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "result", ".", "Error", ")", "\n", "}", "\n", "return", "generationInfoFromResult", "(", "result", ",", "detailed", ",", "formatTime", ")", ",", "nil", "\n", "}" ]
// BranchInfo returns information about "in-flight" branches. // If a non-empty string is supplied for branch name, // then only information for that branch is returned. // Supplying true for detailed returns extra unit detail for the branch.
[ "BranchInfo", "returns", "information", "about", "in", "-", "flight", "branches", ".", "If", "a", "non", "-", "empty", "string", "is", "supplied", "for", "branch", "name", "then", "only", "information", "for", "that", "branch", "is", "returned", ".", "Supplying", "true", "for", "detailed", "returns", "extra", "unit", "detail", "for", "the", "branch", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/modelgeneration/modelgeneration.go#L110-L127
4,468
juju/juju
service/windows/service_windows.go
Name
func (s *enumService) Name() string { if s.name != nil { return syscall.UTF16ToString((*[1 << 16]uint16)(unsafe.Pointer(s.name))[:]) } return "" }
go
func (s *enumService) Name() string { if s.name != nil { return syscall.UTF16ToString((*[1 << 16]uint16)(unsafe.Pointer(s.name))[:]) } return "" }
[ "func", "(", "s", "*", "enumService", ")", "Name", "(", ")", "string", "{", "if", "s", ".", "name", "!=", "nil", "{", "return", "syscall", ".", "UTF16ToString", "(", "(", "*", "[", "1", "<<", "16", "]", "uint16", ")", "(", "unsafe", ".", "Pointer", "(", "s", ".", "name", ")", ")", "[", ":", "]", ")", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// Name returns the name of the service stored in enumService.
[ "Name", "returns", "the", "name", "of", "the", "service", "stored", "in", "enumService", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/windows/service_windows.go#L83-L88
4,469
juju/juju
service/windows/service_windows.go
CreateService
func (m *manager) CreateService(name, exepath string, c mgr.Config, args ...string) (windowsService, error) { // The Create function relies on the fact that this calls Connect(which connects to localhost) and not // ConnectRemote. If we get to the point where we need to call ConnectRemote we need to stop using // series.HostSeries inside Create. s, err := mgr.Connect() if err != nil { return nil, err } defer s.Disconnect() return s.CreateService(name, exepath, c, args...) }
go
func (m *manager) CreateService(name, exepath string, c mgr.Config, args ...string) (windowsService, error) { // The Create function relies on the fact that this calls Connect(which connects to localhost) and not // ConnectRemote. If we get to the point where we need to call ConnectRemote we need to stop using // series.HostSeries inside Create. s, err := mgr.Connect() if err != nil { return nil, err } defer s.Disconnect() return s.CreateService(name, exepath, c, args...) }
[ "func", "(", "m", "*", "manager", ")", "CreateService", "(", "name", ",", "exepath", "string", ",", "c", "mgr", ".", "Config", ",", "args", "...", "string", ")", "(", "windowsService", ",", "error", ")", "{", "// The Create function relies on the fact that this calls Connect(which connects to localhost) and not", "// ConnectRemote. If we get to the point where we need to call ConnectRemote we need to stop using", "// series.HostSeries inside Create.", "s", ",", "err", ":=", "mgr", ".", "Connect", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "s", ".", "Disconnect", "(", ")", "\n", "return", "s", ".", "CreateService", "(", "name", ",", "exepath", ",", "c", ",", "args", "...", ")", "\n", "}" ]
// CreateService wraps Mgr.CreateService method.
[ "CreateService", "wraps", "Mgr", ".", "CreateService", "method", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/windows/service_windows.go#L115-L125
4,470
juju/juju
service/windows/service_windows.go
OpenService
func (m *manager) OpenService(name string) (windowsService, error) { s, err := mgr.Connect() if err != nil { return nil, err } defer s.Disconnect() return s.OpenService(name) }
go
func (m *manager) OpenService(name string) (windowsService, error) { s, err := mgr.Connect() if err != nil { return nil, err } defer s.Disconnect() return s.OpenService(name) }
[ "func", "(", "m", "*", "manager", ")", "OpenService", "(", "name", "string", ")", "(", "windowsService", ",", "error", ")", "{", "s", ",", "err", ":=", "mgr", ".", "Connect", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "s", ".", "Disconnect", "(", ")", "\n", "return", "s", ".", "OpenService", "(", "name", ")", "\n", "}" ]
// CreateService wraps Mgr.OpenService method. It returns a windowsService object. // This allows us to stub out this module for testing.
[ "CreateService", "wraps", "Mgr", ".", "OpenService", "method", ".", "It", "returns", "a", "windowsService", "object", ".", "This", "allows", "us", "to", "stub", "out", "this", "module", "for", "testing", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/windows/service_windows.go#L129-L136
4,471
juju/juju
service/windows/service_windows.go
CloseHandle
func (m *manager) CloseHandle(handle windows.Handle) error { return windows.CloseServiceHandle(handle) }
go
func (m *manager) CloseHandle(handle windows.Handle) error { return windows.CloseServiceHandle(handle) }
[ "func", "(", "m", "*", "manager", ")", "CloseHandle", "(", "handle", "windows", ".", "Handle", ")", "error", "{", "return", "windows", ".", "CloseServiceHandle", "(", "handle", ")", "\n", "}" ]
// CloseHandle wraps the windows.CloseServiceHandle method. // This allows us to stub out this module for testing.
[ "CloseHandle", "wraps", "the", "windows", ".", "CloseServiceHandle", "method", ".", "This", "allows", "us", "to", "stub", "out", "this", "module", "for", "testing", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/windows/service_windows.go#L156-L158
4,472
juju/juju
service/windows/service_windows.go
Start
func (s *SvcManager) Start(name string) error { running, err := s.Running(name) if err != nil { return errors.Trace(err) } if running { return nil } service, err := s.getService(name) if err != nil { return errors.Trace(err) } defer service.Close() err = service.Start() if err != nil { return err } return nil }
go
func (s *SvcManager) Start(name string) error { running, err := s.Running(name) if err != nil { return errors.Trace(err) } if running { return nil } service, err := s.getService(name) if err != nil { return errors.Trace(err) } defer service.Close() err = service.Start() if err != nil { return err } return nil }
[ "func", "(", "s", "*", "SvcManager", ")", "Start", "(", "name", "string", ")", "error", "{", "running", ",", "err", ":=", "s", ".", "Running", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "running", "{", "return", "nil", "\n", "}", "\n", "service", ",", "err", ":=", "s", ".", "getService", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "service", ".", "Close", "(", ")", "\n", "err", "=", "service", ".", "Start", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Start starts a service.
[ "Start", "starts", "a", "service", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/windows/service_windows.go#L258-L276
4,473
juju/juju
service/windows/service_windows.go
Stop
func (s *SvcManager) Stop(name string) error { running, err := s.Running(name) if err != nil { return errors.Trace(err) } if !running { return nil } service, err := s.getService(name) if err != nil { return errors.Trace(err) } defer service.Close() _, err = service.Control(svc.Stop) if err != nil { return errors.Trace(err) } return nil }
go
func (s *SvcManager) Stop(name string) error { running, err := s.Running(name) if err != nil { return errors.Trace(err) } if !running { return nil } service, err := s.getService(name) if err != nil { return errors.Trace(err) } defer service.Close() _, err = service.Control(svc.Stop) if err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "s", "*", "SvcManager", ")", "Stop", "(", "name", "string", ")", "error", "{", "running", ",", "err", ":=", "s", ".", "Running", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "!", "running", "{", "return", "nil", "\n", "}", "\n", "service", ",", "err", ":=", "s", ".", "getService", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "service", ".", "Close", "(", ")", "\n", "_", ",", "err", "=", "service", ".", "Control", "(", "svc", ".", "Stop", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Stop stops a service.
[ "Stop", "stops", "a", "service", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/windows/service_windows.go#L314-L332
4,474
juju/juju
service/windows/service_windows.go
Delete
func (s *SvcManager) Delete(name string) error { exists, err := s.exists(name) if err != nil { return err } if !exists { return nil } service, err := s.getService(name) if err != nil { return errors.Trace(err) } defer service.Close() err = service.Delete() if err == c_ERROR_SERVICE_DOES_NOT_EXIST { return nil } else if err != nil { return errors.Trace(err) } return nil }
go
func (s *SvcManager) Delete(name string) error { exists, err := s.exists(name) if err != nil { return err } if !exists { return nil } service, err := s.getService(name) if err != nil { return errors.Trace(err) } defer service.Close() err = service.Delete() if err == c_ERROR_SERVICE_DOES_NOT_EXIST { return nil } else if err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "s", "*", "SvcManager", ")", "Delete", "(", "name", "string", ")", "error", "{", "exists", ",", "err", ":=", "s", ".", "exists", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "exists", "{", "return", "nil", "\n", "}", "\n", "service", ",", "err", ":=", "s", ".", "getService", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "service", ".", "Close", "(", ")", "\n", "err", "=", "service", ".", "Delete", "(", ")", "\n", "if", "err", "==", "c_ERROR_SERVICE_DOES_NOT_EXIST", "{", "return", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Delete deletes a service.
[ "Delete", "deletes", "a", "service", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/windows/service_windows.go#L335-L355
4,475
juju/juju
service/windows/service_windows.go
Running
func (s *SvcManager) Running(name string) (bool, error) { status, err := s.status(name) if err != nil { return false, errors.Trace(err) } logger.Infof("Service %q Status %v", name, status) if status == svc.Running { return true, nil } return false, nil }
go
func (s *SvcManager) Running(name string) (bool, error) { status, err := s.status(name) if err != nil { return false, errors.Trace(err) } logger.Infof("Service %q Status %v", name, status) if status == svc.Running { return true, nil } return false, nil }
[ "func", "(", "s", "*", "SvcManager", ")", "Running", "(", "name", "string", ")", "(", "bool", ",", "error", ")", "{", "status", ",", "err", ":=", "s", ".", "status", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "name", ",", "status", ")", "\n", "if", "status", "==", "svc", ".", "Running", "{", "return", "true", ",", "nil", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}" ]
// Running returns the status of a service.
[ "Running", "returns", "the", "status", "of", "a", "service", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/windows/service_windows.go#L397-L407
4,476
juju/juju
service/windows/service_windows.go
Config
func (s *SvcManager) Config(name string) (mgr.Config, error) { exists, err := s.exists(name) if err != nil { return mgr.Config{}, err } if !exists { return mgr.Config{}, c_ERROR_SERVICE_DOES_NOT_EXIST } service, err := s.getService(name) if err != nil { return mgr.Config{}, errors.Trace(err) } defer service.Close() return service.Config() }
go
func (s *SvcManager) Config(name string) (mgr.Config, error) { exists, err := s.exists(name) if err != nil { return mgr.Config{}, err } if !exists { return mgr.Config{}, c_ERROR_SERVICE_DOES_NOT_EXIST } service, err := s.getService(name) if err != nil { return mgr.Config{}, errors.Trace(err) } defer service.Close() return service.Config() }
[ "func", "(", "s", "*", "SvcManager", ")", "Config", "(", "name", "string", ")", "(", "mgr", ".", "Config", ",", "error", ")", "{", "exists", ",", "err", ":=", "s", ".", "exists", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "mgr", ".", "Config", "{", "}", ",", "err", "\n", "}", "\n", "if", "!", "exists", "{", "return", "mgr", ".", "Config", "{", "}", ",", "c_ERROR_SERVICE_DOES_NOT_EXIST", "\n", "}", "\n", "service", ",", "err", ":=", "s", ".", "getService", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "mgr", ".", "Config", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "service", ".", "Close", "(", ")", "\n", "return", "service", ".", "Config", "(", ")", "\n", "}" ]
// Config returns the mgr.Config of the service. This config reflects the actual // service configuration in Windows.
[ "Config", "returns", "the", "mgr", ".", "Config", "of", "the", "service", ".", "This", "config", "reflects", "the", "actual", "service", "configuration", "in", "Windows", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/windows/service_windows.go#L411-L425
4,477
juju/juju
service/windows/service_windows.go
ChangeServicePassword
func (s *SvcManager) ChangeServicePassword(svcName, newPassword string) error { currentConfig, err := s.Config(svcName) if err != nil { // If access is denied when accessing the service it means // we can't own it, so there's no reason to return an error // since we only want to change the password on services started // by us. if errors.Cause(err) == syscall.ERROR_ACCESS_DENIED { return nil } return errors.Trace(err) } if currentConfig.ServiceStartName == jujudUser { currentConfig.Password = newPassword service, err := s.getService(svcName) if err != nil { return errors.Trace(err) } defer service.Close() err = service.UpdateConfig(currentConfig) if err != nil { return errors.Trace(err) } } if err != nil { return errors.Trace(err) } return nil }
go
func (s *SvcManager) ChangeServicePassword(svcName, newPassword string) error { currentConfig, err := s.Config(svcName) if err != nil { // If access is denied when accessing the service it means // we can't own it, so there's no reason to return an error // since we only want to change the password on services started // by us. if errors.Cause(err) == syscall.ERROR_ACCESS_DENIED { return nil } return errors.Trace(err) } if currentConfig.ServiceStartName == jujudUser { currentConfig.Password = newPassword service, err := s.getService(svcName) if err != nil { return errors.Trace(err) } defer service.Close() err = service.UpdateConfig(currentConfig) if err != nil { return errors.Trace(err) } } if err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "s", "*", "SvcManager", ")", "ChangeServicePassword", "(", "svcName", ",", "newPassword", "string", ")", "error", "{", "currentConfig", ",", "err", ":=", "s", ".", "Config", "(", "svcName", ")", "\n", "if", "err", "!=", "nil", "{", "// If access is denied when accessing the service it means", "// we can't own it, so there's no reason to return an error", "// since we only want to change the password on services started", "// by us.", "if", "errors", ".", "Cause", "(", "err", ")", "==", "syscall", ".", "ERROR_ACCESS_DENIED", "{", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "currentConfig", ".", "ServiceStartName", "==", "jujudUser", "{", "currentConfig", ".", "Password", "=", "newPassword", "\n", "service", ",", "err", ":=", "s", ".", "getService", "(", "svcName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "service", ".", "Close", "(", ")", "\n", "err", "=", "service", ".", "UpdateConfig", "(", "currentConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ChangeServicePassword can change the password of a service // as long as it belongs to the user defined in this package
[ "ChangeServicePassword", "can", "change", "the", "password", "of", "a", "service", "as", "long", "as", "it", "belongs", "to", "the", "user", "defined", "in", "this", "package" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/windows/service_windows.go#L470-L498
4,478
juju/juju
api/caasoperatorupgrader/client.go
Upgrade
func (c *Client) Upgrade(agentTag string, v version.Number) error { var result params.ErrorResult arg := params.KubernetesUpgradeArg{ AgentTag: agentTag, Version: v, } if err := c.facade.FacadeCall("UpgradeOperator", arg, &result); err != nil { return errors.Trace(err) } if result.Error != nil { return errors.Trace(result.Error) } return nil }
go
func (c *Client) Upgrade(agentTag string, v version.Number) error { var result params.ErrorResult arg := params.KubernetesUpgradeArg{ AgentTag: agentTag, Version: v, } if err := c.facade.FacadeCall("UpgradeOperator", arg, &result); err != nil { return errors.Trace(err) } if result.Error != nil { return errors.Trace(result.Error) } return nil }
[ "func", "(", "c", "*", "Client", ")", "Upgrade", "(", "agentTag", "string", ",", "v", "version", ".", "Number", ")", "error", "{", "var", "result", "params", ".", "ErrorResult", "\n", "arg", ":=", "params", ".", "KubernetesUpgradeArg", "{", "AgentTag", ":", "agentTag", ",", "Version", ":", "v", ",", "}", "\n", "if", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "arg", ",", "&", "result", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "result", ".", "Error", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Upgrade upgrades the operator for the specified agent tag to v.
[ "Upgrade", "upgrades", "the", "operator", "for", "the", "specified", "agent", "tag", "to", "v", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/caasoperatorupgrader/client.go#L28-L41
4,479
juju/juju
apiserver/common/networkingcommon/subnets.go
cacheZones
func (cache *addSubnetsCache) cacheZones(ctx context.ProviderCallContext) error { if cache.allZones != nil { // Already cached. logger.Tracef("using cached zones: %v", cache.allZones.SortedValues()) return nil } allZones, err := AllZones(ctx, cache.api) if err != nil { return errors.Annotate(err, "given Zones cannot be validated") } cache.allZones = set.NewStrings() cache.availableZones = set.NewStrings() for _, zone := range allZones.Results { // AllZones() does not use the Error result field, so no // need to check it here. if cache.allZones.Contains(zone.Name) { logger.Warningf("ignoring duplicated zone %q", zone.Name) continue } if zone.Available { cache.availableZones.Add(zone.Name) } cache.allZones.Add(zone.Name) } logger.Tracef( "%d known and %d available zones cached: %v", cache.allZones.Size(), cache.availableZones.Size(), cache.allZones.SortedValues(), ) if cache.allZones.IsEmpty() { cache.allZones = nil // Cached an empty list. return errors.Errorf("no zones defined") } return nil }
go
func (cache *addSubnetsCache) cacheZones(ctx context.ProviderCallContext) error { if cache.allZones != nil { // Already cached. logger.Tracef("using cached zones: %v", cache.allZones.SortedValues()) return nil } allZones, err := AllZones(ctx, cache.api) if err != nil { return errors.Annotate(err, "given Zones cannot be validated") } cache.allZones = set.NewStrings() cache.availableZones = set.NewStrings() for _, zone := range allZones.Results { // AllZones() does not use the Error result field, so no // need to check it here. if cache.allZones.Contains(zone.Name) { logger.Warningf("ignoring duplicated zone %q", zone.Name) continue } if zone.Available { cache.availableZones.Add(zone.Name) } cache.allZones.Add(zone.Name) } logger.Tracef( "%d known and %d available zones cached: %v", cache.allZones.Size(), cache.availableZones.Size(), cache.allZones.SortedValues(), ) if cache.allZones.IsEmpty() { cache.allZones = nil // Cached an empty list. return errors.Errorf("no zones defined") } return nil }
[ "func", "(", "cache", "*", "addSubnetsCache", ")", "cacheZones", "(", "ctx", "context", ".", "ProviderCallContext", ")", "error", "{", "if", "cache", ".", "allZones", "!=", "nil", "{", "// Already cached.", "logger", ".", "Tracef", "(", "\"", "\"", ",", "cache", ".", "allZones", ".", "SortedValues", "(", ")", ")", "\n", "return", "nil", "\n", "}", "\n\n", "allZones", ",", "err", ":=", "AllZones", "(", "ctx", ",", "cache", ".", "api", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "cache", ".", "allZones", "=", "set", ".", "NewStrings", "(", ")", "\n", "cache", ".", "availableZones", "=", "set", ".", "NewStrings", "(", ")", "\n", "for", "_", ",", "zone", ":=", "range", "allZones", ".", "Results", "{", "// AllZones() does not use the Error result field, so no", "// need to check it here.", "if", "cache", ".", "allZones", ".", "Contains", "(", "zone", ".", "Name", ")", "{", "logger", ".", "Warningf", "(", "\"", "\"", ",", "zone", ".", "Name", ")", "\n", "continue", "\n", "}", "\n\n", "if", "zone", ".", "Available", "{", "cache", ".", "availableZones", ".", "Add", "(", "zone", ".", "Name", ")", "\n", "}", "\n", "cache", ".", "allZones", ".", "Add", "(", "zone", ".", "Name", ")", "\n", "}", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "cache", ".", "allZones", ".", "Size", "(", ")", ",", "cache", ".", "availableZones", ".", "Size", "(", ")", ",", "cache", ".", "allZones", ".", "SortedValues", "(", ")", ",", ")", "\n", "if", "cache", ".", "allZones", ".", "IsEmpty", "(", ")", "{", "cache", ".", "allZones", "=", "nil", "\n", "// Cached an empty list.", "return", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// cacheZones populates the allZones and availableZones cache, if it's // empty.
[ "cacheZones", "populates", "the", "allZones", "and", "availableZones", "cache", "if", "it", "s", "empty", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/networkingcommon/subnets.go#L97-L133
4,480
juju/juju
apiserver/common/networkingcommon/subnets.go
AddSubnets
func AddSubnets(ctx context.ProviderCallContext, api NetworkBacking, args params.AddSubnetsParams) (params.ErrorResults, error) { results := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Subnets)), } if len(args.Subnets) == 0 { return results, nil } cache := NewAddSubnetsCache(api) for i, arg := range args.Subnets { err := addOneSubnet(ctx, api, arg, cache) if err != nil { results.Results[i].Error = common.ServerError(err) } } return results, nil }
go
func AddSubnets(ctx context.ProviderCallContext, api NetworkBacking, args params.AddSubnetsParams) (params.ErrorResults, error) { results := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Subnets)), } if len(args.Subnets) == 0 { return results, nil } cache := NewAddSubnetsCache(api) for i, arg := range args.Subnets { err := addOneSubnet(ctx, api, arg, cache) if err != nil { results.Results[i].Error = common.ServerError(err) } } return results, nil }
[ "func", "AddSubnets", "(", "ctx", "context", ".", "ProviderCallContext", ",", "api", "NetworkBacking", ",", "args", "params", ".", "AddSubnetsParams", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "results", ":=", "params", ".", "ErrorResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "args", ".", "Subnets", ")", ")", ",", "}", "\n\n", "if", "len", "(", "args", ".", "Subnets", ")", "==", "0", "{", "return", "results", ",", "nil", "\n", "}", "\n\n", "cache", ":=", "NewAddSubnetsCache", "(", "api", ")", "\n", "for", "i", ",", "arg", ":=", "range", "args", ".", "Subnets", "{", "err", ":=", "addOneSubnet", "(", "ctx", ",", "api", ",", "arg", ",", "cache", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// AddSubnets adds.
[ "AddSubnets", "adds", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/networkingcommon/subnets.go#L366-L383
4,481
juju/juju
state/storage/storage.go
NewStorage
func NewStorage(modelUUID string, session *mgo.Session) Storage { return stateStorage{modelUUID, session} }
go
func NewStorage(modelUUID string, session *mgo.Session) Storage { return stateStorage{modelUUID, session} }
[ "func", "NewStorage", "(", "modelUUID", "string", ",", "session", "*", "mgo", ".", "Session", ")", "Storage", "{", "return", "stateStorage", "{", "modelUUID", ",", "session", "}", "\n", "}" ]
// NewStorage returns a Storage for the model with the specified UUID.
[ "NewStorage", "returns", "a", "Storage", "for", "the", "model", "with", "the", "specified", "UUID", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/storage/storage.go#L45-L47
4,482
juju/juju
provider/ec2/environ.go
resourceName
func resourceName(tag names.Tag, envName string) string { return fmt.Sprintf("juju-%s-%s", envName, tag) }
go
func resourceName(tag names.Tag, envName string) string { return fmt.Sprintf("juju-%s-%s", envName, tag) }
[ "func", "resourceName", "(", "tag", "names", ".", "Tag", ",", "envName", "string", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "envName", ",", "tag", ")", "\n", "}" ]
// resourceName returns the string to use for a resource's Name tag, // to help users identify Juju-managed resources in the AWS console.
[ "resourceName", "returns", "the", "string", "to", "use", "for", "a", "resource", "s", "Name", "tag", "to", "help", "users", "identify", "Juju", "-", "managed", "resources", "in", "the", "AWS", "console", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/environ.go#L406-L408
4,483
juju/juju
provider/ec2/environ.go
_runInstances
func _runInstances(e *ec2.EC2, ctx context.ProviderCallContext, ri *ec2.RunInstances, c environs.StatusCallbackFunc) (resp *ec2.RunInstancesResp, err error) { try := 1 for a := shortAttempt.Start(); a.Next(); { c(status.Allocating, fmt.Sprintf("Start instance attempt %d", try), nil) resp, err = e.RunInstances(ri) if err == nil || !isNotFoundError(err) { break } try++ } return resp, maybeConvertCredentialError(err, ctx) }
go
func _runInstances(e *ec2.EC2, ctx context.ProviderCallContext, ri *ec2.RunInstances, c environs.StatusCallbackFunc) (resp *ec2.RunInstancesResp, err error) { try := 1 for a := shortAttempt.Start(); a.Next(); { c(status.Allocating, fmt.Sprintf("Start instance attempt %d", try), nil) resp, err = e.RunInstances(ri) if err == nil || !isNotFoundError(err) { break } try++ } return resp, maybeConvertCredentialError(err, ctx) }
[ "func", "_runInstances", "(", "e", "*", "ec2", ".", "EC2", ",", "ctx", "context", ".", "ProviderCallContext", ",", "ri", "*", "ec2", ".", "RunInstances", ",", "c", "environs", ".", "StatusCallbackFunc", ")", "(", "resp", "*", "ec2", ".", "RunInstancesResp", ",", "err", "error", ")", "{", "try", ":=", "1", "\n", "for", "a", ":=", "shortAttempt", ".", "Start", "(", ")", ";", "a", ".", "Next", "(", ")", ";", "{", "c", "(", "status", ".", "Allocating", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "try", ")", ",", "nil", ")", "\n", "resp", ",", "err", "=", "e", ".", "RunInstances", "(", "ri", ")", "\n", "if", "err", "==", "nil", "||", "!", "isNotFoundError", "(", "err", ")", "{", "break", "\n", "}", "\n", "try", "++", "\n", "}", "\n", "return", "resp", ",", "maybeConvertCredentialError", "(", "err", ",", "ctx", ")", "\n", "}" ]
// runInstances calls ec2.RunInstances for a fixed number of attempts until // RunInstances returns an error code that does not indicate an error that // may be caused by eventual consistency.
[ "runInstances", "calls", "ec2", ".", "RunInstances", "for", "a", "fixed", "number", "of", "attempts", "until", "RunInstances", "returns", "an", "error", "code", "that", "does", "not", "indicate", "an", "error", "that", "may", "be", "caused", "by", "eventual", "consistency", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/environ.go#L846-L857
4,484
juju/juju
provider/ec2/environ.go
groupInfoByName
func (e *environ) groupInfoByName(ctx context.ProviderCallContext, groupName string) (ec2.SecurityGroupInfo, error) { resp, err := e.securityGroupsByNameOrID(groupName) if err != nil { return ec2.SecurityGroupInfo{}, maybeConvertCredentialError(err, ctx) } if len(resp.Groups) != 1 { return ec2.SecurityGroupInfo{}, errors.NewNotFound(fmt.Errorf( "expected one security group named %q, got %v", groupName, resp.Groups, ), "") } return resp.Groups[0], nil }
go
func (e *environ) groupInfoByName(ctx context.ProviderCallContext, groupName string) (ec2.SecurityGroupInfo, error) { resp, err := e.securityGroupsByNameOrID(groupName) if err != nil { return ec2.SecurityGroupInfo{}, maybeConvertCredentialError(err, ctx) } if len(resp.Groups) != 1 { return ec2.SecurityGroupInfo{}, errors.NewNotFound(fmt.Errorf( "expected one security group named %q, got %v", groupName, resp.Groups, ), "") } return resp.Groups[0], nil }
[ "func", "(", "e", "*", "environ", ")", "groupInfoByName", "(", "ctx", "context", ".", "ProviderCallContext", ",", "groupName", "string", ")", "(", "ec2", ".", "SecurityGroupInfo", ",", "error", ")", "{", "resp", ",", "err", ":=", "e", ".", "securityGroupsByNameOrID", "(", "groupName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ec2", ".", "SecurityGroupInfo", "{", "}", ",", "maybeConvertCredentialError", "(", "err", ",", "ctx", ")", "\n", "}", "\n\n", "if", "len", "(", "resp", ".", "Groups", ")", "!=", "1", "{", "return", "ec2", ".", "SecurityGroupInfo", "{", "}", ",", "errors", ".", "NewNotFound", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "groupName", ",", "resp", ".", "Groups", ",", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "resp", ".", "Groups", "[", "0", "]", ",", "nil", "\n", "}" ]
// groupInfoByName returns information on the security group // with the given name including rules and other details.
[ "groupInfoByName", "returns", "information", "on", "the", "security", "group", "with", "the", "given", "name", "including", "rules", "and", "other", "details", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/environ.go#L865-L878
4,485
juju/juju
provider/ec2/environ.go
groupByName
func (e *environ) groupByName(ctx context.ProviderCallContext, groupName string) (ec2.SecurityGroup, error) { groupInfo, err := e.groupInfoByName(ctx, groupName) return groupInfo.SecurityGroup, err }
go
func (e *environ) groupByName(ctx context.ProviderCallContext, groupName string) (ec2.SecurityGroup, error) { groupInfo, err := e.groupInfoByName(ctx, groupName) return groupInfo.SecurityGroup, err }
[ "func", "(", "e", "*", "environ", ")", "groupByName", "(", "ctx", "context", ".", "ProviderCallContext", ",", "groupName", "string", ")", "(", "ec2", ".", "SecurityGroup", ",", "error", ")", "{", "groupInfo", ",", "err", ":=", "e", ".", "groupInfoByName", "(", "ctx", ",", "groupName", ")", "\n", "return", "groupInfo", ".", "SecurityGroup", ",", "err", "\n", "}" ]
// groupByName returns the security group with the given name.
[ "groupByName", "returns", "the", "security", "group", "with", "the", "given", "name", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/environ.go#L881-L884
4,486
juju/juju
provider/ec2/environ.go
gatherInstances
func (e *environ) gatherInstances( ctx context.ProviderCallContext, ids []instance.Id, insts []instances.Instance, filter *ec2.Filter, ) error { resp, err := e.ec2.Instances(nil, filter) if err != nil { return maybeConvertCredentialError(err, ctx) } n := 0 // For each requested id, add it to the returned instances // if we find it in the response. for i, id := range ids { if insts[i] != nil { n++ continue } for j := range resp.Reservations { r := &resp.Reservations[j] for k := range r.Instances { if r.Instances[k].InstanceId != string(id) { continue } inst := r.Instances[k] // TODO(wallyworld): lookup the details to fill in the instance type data insts[i] = &ec2Instance{e: e, Instance: &inst} n++ } } } if n < len(ids) { return environs.ErrPartialInstances } return nil }
go
func (e *environ) gatherInstances( ctx context.ProviderCallContext, ids []instance.Id, insts []instances.Instance, filter *ec2.Filter, ) error { resp, err := e.ec2.Instances(nil, filter) if err != nil { return maybeConvertCredentialError(err, ctx) } n := 0 // For each requested id, add it to the returned instances // if we find it in the response. for i, id := range ids { if insts[i] != nil { n++ continue } for j := range resp.Reservations { r := &resp.Reservations[j] for k := range r.Instances { if r.Instances[k].InstanceId != string(id) { continue } inst := r.Instances[k] // TODO(wallyworld): lookup the details to fill in the instance type data insts[i] = &ec2Instance{e: e, Instance: &inst} n++ } } } if n < len(ids) { return environs.ErrPartialInstances } return nil }
[ "func", "(", "e", "*", "environ", ")", "gatherInstances", "(", "ctx", "context", ".", "ProviderCallContext", ",", "ids", "[", "]", "instance", ".", "Id", ",", "insts", "[", "]", "instances", ".", "Instance", ",", "filter", "*", "ec2", ".", "Filter", ",", ")", "error", "{", "resp", ",", "err", ":=", "e", ".", "ec2", ".", "Instances", "(", "nil", ",", "filter", ")", "\n", "if", "err", "!=", "nil", "{", "return", "maybeConvertCredentialError", "(", "err", ",", "ctx", ")", "\n", "}", "\n", "n", ":=", "0", "\n", "// For each requested id, add it to the returned instances", "// if we find it in the response.", "for", "i", ",", "id", ":=", "range", "ids", "{", "if", "insts", "[", "i", "]", "!=", "nil", "{", "n", "++", "\n", "continue", "\n", "}", "\n", "for", "j", ":=", "range", "resp", ".", "Reservations", "{", "r", ":=", "&", "resp", ".", "Reservations", "[", "j", "]", "\n", "for", "k", ":=", "range", "r", ".", "Instances", "{", "if", "r", ".", "Instances", "[", "k", "]", ".", "InstanceId", "!=", "string", "(", "id", ")", "{", "continue", "\n", "}", "\n", "inst", ":=", "r", ".", "Instances", "[", "k", "]", "\n", "// TODO(wallyworld): lookup the details to fill in the instance type data", "insts", "[", "i", "]", "=", "&", "ec2Instance", "{", "e", ":", "e", ",", "Instance", ":", "&", "inst", "}", "\n", "n", "++", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "n", "<", "len", "(", "ids", ")", "{", "return", "environs", ".", "ErrPartialInstances", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// gatherInstances tries to get information on each instance // id whose corresponding insts slot is nil. // // This function returns environs.ErrPartialInstances if the // insts slice has not been completely filled.
[ "gatherInstances", "tries", "to", "get", "information", "on", "each", "instance", "id", "whose", "corresponding", "insts", "slot", "is", "nil", ".", "This", "function", "returns", "environs", ".", "ErrPartialInstances", "if", "the", "insts", "slice", "has", "not", "been", "completely", "filled", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/environ.go#L938-L973
4,487
juju/juju
provider/ec2/environ.go
NetworkInterfaces
func (e *environ) NetworkInterfaces(ctx context.ProviderCallContext, instId instance.Id) ([]network.InterfaceInfo, error) { var err error var networkInterfacesResp *ec2.NetworkInterfacesResp for a := shortAttempt.Start(); a.Next(); { logger.Tracef("retrieving NICs for instance %q", instId) filter := ec2.NewFilter() filter.Add("attachment.instance-id", string(instId)) networkInterfacesResp, err = e.ec2.NetworkInterfaces(nil, filter) logger.Tracef("instance %q NICs: %#v (err: %v)", instId, networkInterfacesResp, err) if err != nil { err = maybeConvertCredentialError(err, ctx) if common.IsCredentialNotValid(err) { // no need to re-try: there is a problem with credentials break } logger.Errorf("failed to get instance %q interfaces: %v (retrying)", instId, err) continue } if len(networkInterfacesResp.Interfaces) == 0 { logger.Tracef("instance %q has no NIC attachment yet, retrying...", instId) continue } logger.Tracef("found instance %q NICS: %#v", instId, networkInterfacesResp.Interfaces) break } if err != nil { // either the instance doesn't exist or we couldn't get through to // the ec2 api return nil, errors.Annotatef(err, "cannot get instance %q network interfaces", instId) } ec2Interfaces := networkInterfacesResp.Interfaces result := make([]network.InterfaceInfo, len(ec2Interfaces)) for i, iface := range ec2Interfaces { resp, err := e.ec2.Subnets([]string{iface.SubnetId}, nil) if err != nil { return nil, errors.Annotatef(maybeConvertCredentialError(err, ctx), "failed to retrieve subnet %q info", iface.SubnetId) } if len(resp.Subnets) != 1 { return nil, errors.Errorf("expected 1 subnet, got %d", len(resp.Subnets)) } subnet := resp.Subnets[0] cidr := subnet.CIDRBlock result[i] = network.InterfaceInfo{ DeviceIndex: iface.Attachment.DeviceIndex, MACAddress: iface.MACAddress, CIDR: cidr, ProviderId: network.Id(iface.Id), ProviderSubnetId: network.Id(iface.SubnetId), AvailabilityZones: []string{subnet.AvailZone}, VLANTag: 0, // Not supported on EC2. // Getting the interface name is not supported on EC2, so fake it. InterfaceName: fmt.Sprintf("unsupported%d", iface.Attachment.DeviceIndex), Disabled: false, NoAutoStart: false, ConfigType: network.ConfigDHCP, InterfaceType: network.EthernetInterface, Address: network.NewScopedAddress(iface.PrivateIPAddress, network.ScopeCloudLocal), } } return result, nil }
go
func (e *environ) NetworkInterfaces(ctx context.ProviderCallContext, instId instance.Id) ([]network.InterfaceInfo, error) { var err error var networkInterfacesResp *ec2.NetworkInterfacesResp for a := shortAttempt.Start(); a.Next(); { logger.Tracef("retrieving NICs for instance %q", instId) filter := ec2.NewFilter() filter.Add("attachment.instance-id", string(instId)) networkInterfacesResp, err = e.ec2.NetworkInterfaces(nil, filter) logger.Tracef("instance %q NICs: %#v (err: %v)", instId, networkInterfacesResp, err) if err != nil { err = maybeConvertCredentialError(err, ctx) if common.IsCredentialNotValid(err) { // no need to re-try: there is a problem with credentials break } logger.Errorf("failed to get instance %q interfaces: %v (retrying)", instId, err) continue } if len(networkInterfacesResp.Interfaces) == 0 { logger.Tracef("instance %q has no NIC attachment yet, retrying...", instId) continue } logger.Tracef("found instance %q NICS: %#v", instId, networkInterfacesResp.Interfaces) break } if err != nil { // either the instance doesn't exist or we couldn't get through to // the ec2 api return nil, errors.Annotatef(err, "cannot get instance %q network interfaces", instId) } ec2Interfaces := networkInterfacesResp.Interfaces result := make([]network.InterfaceInfo, len(ec2Interfaces)) for i, iface := range ec2Interfaces { resp, err := e.ec2.Subnets([]string{iface.SubnetId}, nil) if err != nil { return nil, errors.Annotatef(maybeConvertCredentialError(err, ctx), "failed to retrieve subnet %q info", iface.SubnetId) } if len(resp.Subnets) != 1 { return nil, errors.Errorf("expected 1 subnet, got %d", len(resp.Subnets)) } subnet := resp.Subnets[0] cidr := subnet.CIDRBlock result[i] = network.InterfaceInfo{ DeviceIndex: iface.Attachment.DeviceIndex, MACAddress: iface.MACAddress, CIDR: cidr, ProviderId: network.Id(iface.Id), ProviderSubnetId: network.Id(iface.SubnetId), AvailabilityZones: []string{subnet.AvailZone}, VLANTag: 0, // Not supported on EC2. // Getting the interface name is not supported on EC2, so fake it. InterfaceName: fmt.Sprintf("unsupported%d", iface.Attachment.DeviceIndex), Disabled: false, NoAutoStart: false, ConfigType: network.ConfigDHCP, InterfaceType: network.EthernetInterface, Address: network.NewScopedAddress(iface.PrivateIPAddress, network.ScopeCloudLocal), } } return result, nil }
[ "func", "(", "e", "*", "environ", ")", "NetworkInterfaces", "(", "ctx", "context", ".", "ProviderCallContext", ",", "instId", "instance", ".", "Id", ")", "(", "[", "]", "network", ".", "InterfaceInfo", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "networkInterfacesResp", "*", "ec2", ".", "NetworkInterfacesResp", "\n", "for", "a", ":=", "shortAttempt", ".", "Start", "(", ")", ";", "a", ".", "Next", "(", ")", ";", "{", "logger", ".", "Tracef", "(", "\"", "\"", ",", "instId", ")", "\n", "filter", ":=", "ec2", ".", "NewFilter", "(", ")", "\n", "filter", ".", "Add", "(", "\"", "\"", ",", "string", "(", "instId", ")", ")", "\n", "networkInterfacesResp", ",", "err", "=", "e", ".", "ec2", ".", "NetworkInterfaces", "(", "nil", ",", "filter", ")", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "instId", ",", "networkInterfacesResp", ",", "err", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "maybeConvertCredentialError", "(", "err", ",", "ctx", ")", "\n", "if", "common", ".", "IsCredentialNotValid", "(", "err", ")", "{", "// no need to re-try: there is a problem with credentials", "break", "\n", "}", "\n", "logger", ".", "Errorf", "(", "\"", "\"", ",", "instId", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "len", "(", "networkInterfacesResp", ".", "Interfaces", ")", "==", "0", "{", "logger", ".", "Tracef", "(", "\"", "\"", ",", "instId", ")", "\n", "continue", "\n", "}", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "instId", ",", "networkInterfacesResp", ".", "Interfaces", ")", "\n", "break", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "// either the instance doesn't exist or we couldn't get through to", "// the ec2 api", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "instId", ")", "\n", "}", "\n", "ec2Interfaces", ":=", "networkInterfacesResp", ".", "Interfaces", "\n", "result", ":=", "make", "(", "[", "]", "network", ".", "InterfaceInfo", ",", "len", "(", "ec2Interfaces", ")", ")", "\n", "for", "i", ",", "iface", ":=", "range", "ec2Interfaces", "{", "resp", ",", "err", ":=", "e", ".", "ec2", ".", "Subnets", "(", "[", "]", "string", "{", "iface", ".", "SubnetId", "}", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "maybeConvertCredentialError", "(", "err", ",", "ctx", ")", ",", "\"", "\"", ",", "iface", ".", "SubnetId", ")", "\n", "}", "\n", "if", "len", "(", "resp", ".", "Subnets", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "resp", ".", "Subnets", ")", ")", "\n", "}", "\n", "subnet", ":=", "resp", ".", "Subnets", "[", "0", "]", "\n", "cidr", ":=", "subnet", ".", "CIDRBlock", "\n\n", "result", "[", "i", "]", "=", "network", ".", "InterfaceInfo", "{", "DeviceIndex", ":", "iface", ".", "Attachment", ".", "DeviceIndex", ",", "MACAddress", ":", "iface", ".", "MACAddress", ",", "CIDR", ":", "cidr", ",", "ProviderId", ":", "network", ".", "Id", "(", "iface", ".", "Id", ")", ",", "ProviderSubnetId", ":", "network", ".", "Id", "(", "iface", ".", "SubnetId", ")", ",", "AvailabilityZones", ":", "[", "]", "string", "{", "subnet", ".", "AvailZone", "}", ",", "VLANTag", ":", "0", ",", "// Not supported on EC2.", "// Getting the interface name is not supported on EC2, so fake it.", "InterfaceName", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "iface", ".", "Attachment", ".", "DeviceIndex", ")", ",", "Disabled", ":", "false", ",", "NoAutoStart", ":", "false", ",", "ConfigType", ":", "network", ".", "ConfigDHCP", ",", "InterfaceType", ":", "network", ".", "EthernetInterface", ",", "Address", ":", "network", ".", "NewScopedAddress", "(", "iface", ".", "PrivateIPAddress", ",", "network", ".", "ScopeCloudLocal", ")", ",", "}", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// NetworkInterfaces implements NetworkingEnviron.NetworkInterfaces.
[ "NetworkInterfaces", "implements", "NetworkingEnviron", ".", "NetworkInterfaces", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/environ.go#L976-L1037
4,488
juju/juju
provider/ec2/environ.go
Spaces
func (e *environ) Spaces(ctx context.ProviderCallContext) ([]network.SpaceInfo, error) { return nil, errors.NotSupportedf("Spaces") }
go
func (e *environ) Spaces(ctx context.ProviderCallContext) ([]network.SpaceInfo, error) { return nil, errors.NotSupportedf("Spaces") }
[ "func", "(", "e", "*", "environ", ")", "Spaces", "(", "ctx", "context", ".", "ProviderCallContext", ")", "(", "[", "]", "network", ".", "SpaceInfo", ",", "error", ")", "{", "return", "nil", ",", "errors", ".", "NotSupportedf", "(", "\"", "\"", ")", "\n", "}" ]
// Spaces is not implemented by the ec2 provider as we don't currently have // provider level spaces.
[ "Spaces", "is", "not", "implemented", "by", "the", "ec2", "provider", "as", "we", "don", "t", "currently", "have", "provider", "level", "spaces", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/environ.go#L1059-L1061
4,489
juju/juju
provider/ec2/environ.go
Subnets
func (e *environ) Subnets(ctx context.ProviderCallContext, instId instance.Id, subnetIds []network.Id) ([]network.SubnetInfo, error) { var results []network.SubnetInfo subIdSet := make(map[string]bool) for _, subId := range subnetIds { subIdSet[string(subId)] = false } if instId != instance.UnknownId { interfaces, err := e.NetworkInterfaces(ctx, instId) if err != nil { return results, errors.Trace(err) } if len(subnetIds) == 0 { for _, iface := range interfaces { subIdSet[string(iface.ProviderSubnetId)] = false } } for _, iface := range interfaces { _, ok := subIdSet[string(iface.ProviderSubnetId)] if !ok { logger.Tracef("subnet %q not in %v, skipping", iface.ProviderSubnetId, subnetIds) continue } subIdSet[string(iface.ProviderSubnetId)] = true info, err := makeSubnetInfo(iface.CIDR, iface.ProviderSubnetId, iface.ProviderNetworkId, iface.AvailabilityZones) if err != nil { // Error will already have been logged. continue } results = append(results, info) } } else { resp, _, err := e.subnetsForVPC(ctx) if err != nil { return nil, errors.Annotatef(err, "failed to retrieve subnets") } if len(subnetIds) == 0 { for _, subnet := range resp.Subnets { subIdSet[subnet.Id] = false } } for _, subnet := range resp.Subnets { _, ok := subIdSet[subnet.Id] if !ok { logger.Tracef("subnet %q not in %v, skipping", subnet.Id, subnetIds) continue } subIdSet[subnet.Id] = true cidr := subnet.CIDRBlock info, err := makeSubnetInfo(cidr, network.Id(subnet.Id), network.Id(subnet.VPCId), []string{subnet.AvailZone}) if err != nil { // Error will already have been logged. continue } results = append(results, info) } } notFound := []string{} for subId, found := range subIdSet { if !found { notFound = append(notFound, subId) } } if len(notFound) != 0 { return nil, errors.Errorf("failed to find the following subnet ids: %v", notFound) } return results, nil }
go
func (e *environ) Subnets(ctx context.ProviderCallContext, instId instance.Id, subnetIds []network.Id) ([]network.SubnetInfo, error) { var results []network.SubnetInfo subIdSet := make(map[string]bool) for _, subId := range subnetIds { subIdSet[string(subId)] = false } if instId != instance.UnknownId { interfaces, err := e.NetworkInterfaces(ctx, instId) if err != nil { return results, errors.Trace(err) } if len(subnetIds) == 0 { for _, iface := range interfaces { subIdSet[string(iface.ProviderSubnetId)] = false } } for _, iface := range interfaces { _, ok := subIdSet[string(iface.ProviderSubnetId)] if !ok { logger.Tracef("subnet %q not in %v, skipping", iface.ProviderSubnetId, subnetIds) continue } subIdSet[string(iface.ProviderSubnetId)] = true info, err := makeSubnetInfo(iface.CIDR, iface.ProviderSubnetId, iface.ProviderNetworkId, iface.AvailabilityZones) if err != nil { // Error will already have been logged. continue } results = append(results, info) } } else { resp, _, err := e.subnetsForVPC(ctx) if err != nil { return nil, errors.Annotatef(err, "failed to retrieve subnets") } if len(subnetIds) == 0 { for _, subnet := range resp.Subnets { subIdSet[subnet.Id] = false } } for _, subnet := range resp.Subnets { _, ok := subIdSet[subnet.Id] if !ok { logger.Tracef("subnet %q not in %v, skipping", subnet.Id, subnetIds) continue } subIdSet[subnet.Id] = true cidr := subnet.CIDRBlock info, err := makeSubnetInfo(cidr, network.Id(subnet.Id), network.Id(subnet.VPCId), []string{subnet.AvailZone}) if err != nil { // Error will already have been logged. continue } results = append(results, info) } } notFound := []string{} for subId, found := range subIdSet { if !found { notFound = append(notFound, subId) } } if len(notFound) != 0 { return nil, errors.Errorf("failed to find the following subnet ids: %v", notFound) } return results, nil }
[ "func", "(", "e", "*", "environ", ")", "Subnets", "(", "ctx", "context", ".", "ProviderCallContext", ",", "instId", "instance", ".", "Id", ",", "subnetIds", "[", "]", "network", ".", "Id", ")", "(", "[", "]", "network", ".", "SubnetInfo", ",", "error", ")", "{", "var", "results", "[", "]", "network", ".", "SubnetInfo", "\n", "subIdSet", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "_", ",", "subId", ":=", "range", "subnetIds", "{", "subIdSet", "[", "string", "(", "subId", ")", "]", "=", "false", "\n", "}", "\n\n", "if", "instId", "!=", "instance", ".", "UnknownId", "{", "interfaces", ",", "err", ":=", "e", ".", "NetworkInterfaces", "(", "ctx", ",", "instId", ")", "\n", "if", "err", "!=", "nil", "{", "return", "results", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "subnetIds", ")", "==", "0", "{", "for", "_", ",", "iface", ":=", "range", "interfaces", "{", "subIdSet", "[", "string", "(", "iface", ".", "ProviderSubnetId", ")", "]", "=", "false", "\n", "}", "\n", "}", "\n", "for", "_", ",", "iface", ":=", "range", "interfaces", "{", "_", ",", "ok", ":=", "subIdSet", "[", "string", "(", "iface", ".", "ProviderSubnetId", ")", "]", "\n", "if", "!", "ok", "{", "logger", ".", "Tracef", "(", "\"", "\"", ",", "iface", ".", "ProviderSubnetId", ",", "subnetIds", ")", "\n", "continue", "\n", "}", "\n", "subIdSet", "[", "string", "(", "iface", ".", "ProviderSubnetId", ")", "]", "=", "true", "\n", "info", ",", "err", ":=", "makeSubnetInfo", "(", "iface", ".", "CIDR", ",", "iface", ".", "ProviderSubnetId", ",", "iface", ".", "ProviderNetworkId", ",", "iface", ".", "AvailabilityZones", ")", "\n", "if", "err", "!=", "nil", "{", "// Error will already have been logged.", "continue", "\n", "}", "\n", "results", "=", "append", "(", "results", ",", "info", ")", "\n", "}", "\n", "}", "else", "{", "resp", ",", "_", ",", "err", ":=", "e", ".", "subnetsForVPC", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "subnetIds", ")", "==", "0", "{", "for", "_", ",", "subnet", ":=", "range", "resp", ".", "Subnets", "{", "subIdSet", "[", "subnet", ".", "Id", "]", "=", "false", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "subnet", ":=", "range", "resp", ".", "Subnets", "{", "_", ",", "ok", ":=", "subIdSet", "[", "subnet", ".", "Id", "]", "\n", "if", "!", "ok", "{", "logger", ".", "Tracef", "(", "\"", "\"", ",", "subnet", ".", "Id", ",", "subnetIds", ")", "\n", "continue", "\n", "}", "\n", "subIdSet", "[", "subnet", ".", "Id", "]", "=", "true", "\n", "cidr", ":=", "subnet", ".", "CIDRBlock", "\n", "info", ",", "err", ":=", "makeSubnetInfo", "(", "cidr", ",", "network", ".", "Id", "(", "subnet", ".", "Id", ")", ",", "network", ".", "Id", "(", "subnet", ".", "VPCId", ")", ",", "[", "]", "string", "{", "subnet", ".", "AvailZone", "}", ")", "\n", "if", "err", "!=", "nil", "{", "// Error will already have been logged.", "continue", "\n", "}", "\n", "results", "=", "append", "(", "results", ",", "info", ")", "\n\n", "}", "\n", "}", "\n\n", "notFound", ":=", "[", "]", "string", "{", "}", "\n", "for", "subId", ",", "found", ":=", "range", "subIdSet", "{", "if", "!", "found", "{", "notFound", "=", "append", "(", "notFound", ",", "subId", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "notFound", ")", "!=", "0", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "notFound", ")", "\n", "}", "\n\n", "return", "results", ",", "nil", "\n", "}" ]
// Subnets returns basic information about the specified subnets known // by the provider for the specified instance or list of ids. subnetIds can be // empty, in which case all known are returned. Implements // NetworkingEnviron.Subnets.
[ "Subnets", "returns", "basic", "information", "about", "the", "specified", "subnets", "known", "by", "the", "provider", "for", "the", "specified", "instance", "or", "list", "of", "ids", ".", "subnetIds", "can", "be", "empty", "in", "which", "case", "all", "known", "are", "returned", ".", "Implements", "NetworkingEnviron", ".", "Subnets", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/environ.go#L1067-L1138
4,490
juju/juju
provider/ec2/environ.go
AllInstances
func (e *environ) AllInstances(ctx context.ProviderCallContext) ([]instances.Instance, error) { return e.AllInstancesByState(ctx, "pending", "running") }
go
func (e *environ) AllInstances(ctx context.ProviderCallContext) ([]instances.Instance, error) { return e.AllInstancesByState(ctx, "pending", "running") }
[ "func", "(", "e", "*", "environ", ")", "AllInstances", "(", "ctx", "context", ".", "ProviderCallContext", ")", "(", "[", "]", "instances", ".", "Instance", ",", "error", ")", "{", "return", "e", ".", "AllInstancesByState", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}" ]
// AllInstances is part of the environs.InstanceBroker interface.
[ "AllInstances", "is", "part", "of", "the", "environs", ".", "InstanceBroker", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/environ.go#L1184-L1186
4,491
juju/juju
provider/ec2/environ.go
AllInstancesByState
func (e *environ) AllInstancesByState(ctx context.ProviderCallContext, states ...string) ([]instances.Instance, error) { // NOTE(axw) we use security group filtering here because instances // start out untagged. If Juju were to abort after starting an instance, // but before tagging it, it would be leaked. We only need to do this // for AllInstances, as it is the result of AllInstances that is used // in "harvesting" unknown instances by the provisioner. // // One possible alternative is to modify ec2.RunInstances to allow the // caller to specify ClientToken, and then format it like // <controller-uuid>:<model-uuid>:<machine-id> // (with base64-encoding to keep the size under the 64-byte limit) // // It is possible to filter on "client-token", and specify wildcards; // therefore we could use client-token filters everywhere in the ec2 // provider instead of tags or security groups. The only danger is if // we need to make non-idempotent calls to RunInstances for the machine // ID. I don't think this is needed, but I am not confident enough to // change this fundamental right now. // // An EC2 API call is required to resolve the group name to an id, as // VPC enabled accounts do not support name based filtering. groupName := e.jujuGroupName() group, err := e.groupByName(ctx, groupName) if isNotFoundError(err) { // If there's no group, then there cannot be any instances. return nil, nil } else if err != nil { return nil, errors.Trace(maybeConvertCredentialError(err, ctx)) } filter := ec2.NewFilter() filter.Add("instance-state-name", states...) filter.Add("instance.group-id", group.Id) return e.allInstances(ctx, filter) }
go
func (e *environ) AllInstancesByState(ctx context.ProviderCallContext, states ...string) ([]instances.Instance, error) { // NOTE(axw) we use security group filtering here because instances // start out untagged. If Juju were to abort after starting an instance, // but before tagging it, it would be leaked. We only need to do this // for AllInstances, as it is the result of AllInstances that is used // in "harvesting" unknown instances by the provisioner. // // One possible alternative is to modify ec2.RunInstances to allow the // caller to specify ClientToken, and then format it like // <controller-uuid>:<model-uuid>:<machine-id> // (with base64-encoding to keep the size under the 64-byte limit) // // It is possible to filter on "client-token", and specify wildcards; // therefore we could use client-token filters everywhere in the ec2 // provider instead of tags or security groups. The only danger is if // we need to make non-idempotent calls to RunInstances for the machine // ID. I don't think this is needed, but I am not confident enough to // change this fundamental right now. // // An EC2 API call is required to resolve the group name to an id, as // VPC enabled accounts do not support name based filtering. groupName := e.jujuGroupName() group, err := e.groupByName(ctx, groupName) if isNotFoundError(err) { // If there's no group, then there cannot be any instances. return nil, nil } else if err != nil { return nil, errors.Trace(maybeConvertCredentialError(err, ctx)) } filter := ec2.NewFilter() filter.Add("instance-state-name", states...) filter.Add("instance.group-id", group.Id) return e.allInstances(ctx, filter) }
[ "func", "(", "e", "*", "environ", ")", "AllInstancesByState", "(", "ctx", "context", ".", "ProviderCallContext", ",", "states", "...", "string", ")", "(", "[", "]", "instances", ".", "Instance", ",", "error", ")", "{", "// NOTE(axw) we use security group filtering here because instances", "// start out untagged. If Juju were to abort after starting an instance,", "// but before tagging it, it would be leaked. We only need to do this", "// for AllInstances, as it is the result of AllInstances that is used", "// in \"harvesting\" unknown instances by the provisioner.", "//", "// One possible alternative is to modify ec2.RunInstances to allow the", "// caller to specify ClientToken, and then format it like", "// <controller-uuid>:<model-uuid>:<machine-id>", "// (with base64-encoding to keep the size under the 64-byte limit)", "//", "// It is possible to filter on \"client-token\", and specify wildcards;", "// therefore we could use client-token filters everywhere in the ec2", "// provider instead of tags or security groups. The only danger is if", "// we need to make non-idempotent calls to RunInstances for the machine", "// ID. I don't think this is needed, but I am not confident enough to", "// change this fundamental right now.", "//", "// An EC2 API call is required to resolve the group name to an id, as", "// VPC enabled accounts do not support name based filtering.", "groupName", ":=", "e", ".", "jujuGroupName", "(", ")", "\n", "group", ",", "err", ":=", "e", ".", "groupByName", "(", "ctx", ",", "groupName", ")", "\n", "if", "isNotFoundError", "(", "err", ")", "{", "// If there's no group, then there cannot be any instances.", "return", "nil", ",", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "maybeConvertCredentialError", "(", "err", ",", "ctx", ")", ")", "\n", "}", "\n", "filter", ":=", "ec2", ".", "NewFilter", "(", ")", "\n", "filter", ".", "Add", "(", "\"", "\"", ",", "states", "...", ")", "\n", "filter", ".", "Add", "(", "\"", "\"", ",", "group", ".", "Id", ")", "\n", "return", "e", ".", "allInstances", "(", "ctx", ",", "filter", ")", "\n", "}" ]
// AllInstancesByState returns all instances in the environment // with one of the specified instance states.
[ "AllInstancesByState", "returns", "all", "instances", "in", "the", "environment", "with", "one", "of", "the", "specified", "instance", "states", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/environ.go#L1190-L1223
4,492
juju/juju
provider/ec2/environ.go
allControllerManagedInstances
func (e *environ) allControllerManagedInstances(ctx context.ProviderCallContext, controllerUUID string) ([]instance.Id, error) { filter := ec2.NewFilter() filter.Add("instance-state-name", aliveInstanceStates...) e.addControllerFilter(filter, controllerUUID) return e.allInstanceIDs(ctx, filter) }
go
func (e *environ) allControllerManagedInstances(ctx context.ProviderCallContext, controllerUUID string) ([]instance.Id, error) { filter := ec2.NewFilter() filter.Add("instance-state-name", aliveInstanceStates...) e.addControllerFilter(filter, controllerUUID) return e.allInstanceIDs(ctx, filter) }
[ "func", "(", "e", "*", "environ", ")", "allControllerManagedInstances", "(", "ctx", "context", ".", "ProviderCallContext", ",", "controllerUUID", "string", ")", "(", "[", "]", "instance", ".", "Id", ",", "error", ")", "{", "filter", ":=", "ec2", ".", "NewFilter", "(", ")", "\n", "filter", ".", "Add", "(", "\"", "\"", ",", "aliveInstanceStates", "...", ")", "\n", "e", ".", "addControllerFilter", "(", "filter", ",", "controllerUUID", ")", "\n", "return", "e", ".", "allInstanceIDs", "(", "ctx", ",", "filter", ")", "\n", "}" ]
// allControllerManagedInstances returns the IDs of all instances managed by // this environment's controller. // // Note that this requires that all instances are tagged; we cannot filter on // security groups, as we do not know the names of the models.
[ "allControllerManagedInstances", "returns", "the", "IDs", "of", "all", "instances", "managed", "by", "this", "environment", "s", "controller", ".", "Note", "that", "this", "requires", "that", "all", "instances", "are", "tagged", ";", "we", "cannot", "filter", "on", "security", "groups", "as", "we", "do", "not", "know", "the", "names", "of", "the", "models", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/environ.go#L1246-L1251
4,493
juju/juju
provider/ec2/environ.go
destroyControllerManagedEnvirons
func (e *environ) destroyControllerManagedEnvirons(ctx context.ProviderCallContext, controllerUUID string) error { // Terminate all instances managed by the controller. instIds, err := e.allControllerManagedInstances(ctx, controllerUUID) if err != nil { return errors.Annotate(err, "listing instances") } if err := e.terminateInstances(ctx, instIds); err != nil { return errors.Annotate(err, "terminating instances") } // Delete all volumes managed by the controller. (No need to delete root disks manually.) volIds, err := e.allControllerManagedVolumes(ctx, controllerUUID, false) if err != nil { return errors.Annotate(err, "listing volumes") } errs := foreachVolume(e.ec2, ctx, volIds, destroyVolume) for i, err := range errs { if err == nil { continue } // (anastasiamac 2018-03-21) This is strange - we do try // to destroy all volumes but afterwards, if we have encountered any errors, // we will return first one...The same logic happens on detach..?... return errors.Annotatef(err, "destroying volume %q", volIds[i]) } // Delete security groups managed by the controller. groups, err := e.controllerSecurityGroups(ctx, controllerUUID) if err != nil { return errors.Trace(err) } for _, g := range groups { if err := deleteSecurityGroupInsistently(e.ec2, ctx, g, clock.WallClock); err != nil { return errors.Annotatef( err, "cannot delete security group %q (%q)", g.Name, g.Id, ) } } return nil }
go
func (e *environ) destroyControllerManagedEnvirons(ctx context.ProviderCallContext, controllerUUID string) error { // Terminate all instances managed by the controller. instIds, err := e.allControllerManagedInstances(ctx, controllerUUID) if err != nil { return errors.Annotate(err, "listing instances") } if err := e.terminateInstances(ctx, instIds); err != nil { return errors.Annotate(err, "terminating instances") } // Delete all volumes managed by the controller. (No need to delete root disks manually.) volIds, err := e.allControllerManagedVolumes(ctx, controllerUUID, false) if err != nil { return errors.Annotate(err, "listing volumes") } errs := foreachVolume(e.ec2, ctx, volIds, destroyVolume) for i, err := range errs { if err == nil { continue } // (anastasiamac 2018-03-21) This is strange - we do try // to destroy all volumes but afterwards, if we have encountered any errors, // we will return first one...The same logic happens on detach..?... return errors.Annotatef(err, "destroying volume %q", volIds[i]) } // Delete security groups managed by the controller. groups, err := e.controllerSecurityGroups(ctx, controllerUUID) if err != nil { return errors.Trace(err) } for _, g := range groups { if err := deleteSecurityGroupInsistently(e.ec2, ctx, g, clock.WallClock); err != nil { return errors.Annotatef( err, "cannot delete security group %q (%q)", g.Name, g.Id, ) } } return nil }
[ "func", "(", "e", "*", "environ", ")", "destroyControllerManagedEnvirons", "(", "ctx", "context", ".", "ProviderCallContext", ",", "controllerUUID", "string", ")", "error", "{", "// Terminate all instances managed by the controller.", "instIds", ",", "err", ":=", "e", ".", "allControllerManagedInstances", "(", "ctx", ",", "controllerUUID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "e", ".", "terminateInstances", "(", "ctx", ",", "instIds", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Delete all volumes managed by the controller. (No need to delete root disks manually.)", "volIds", ",", "err", ":=", "e", ".", "allControllerManagedVolumes", "(", "ctx", ",", "controllerUUID", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "errs", ":=", "foreachVolume", "(", "e", ".", "ec2", ",", "ctx", ",", "volIds", ",", "destroyVolume", ")", "\n", "for", "i", ",", "err", ":=", "range", "errs", "{", "if", "err", "==", "nil", "{", "continue", "\n", "}", "\n", "// (anastasiamac 2018-03-21) This is strange - we do try", "// to destroy all volumes but afterwards, if we have encountered any errors,", "// we will return first one...The same logic happens on detach..?...", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "volIds", "[", "i", "]", ")", "\n", "}", "\n\n", "// Delete security groups managed by the controller.", "groups", ",", "err", ":=", "e", ".", "controllerSecurityGroups", "(", "ctx", ",", "controllerUUID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "for", "_", ",", "g", ":=", "range", "groups", "{", "if", "err", ":=", "deleteSecurityGroupInsistently", "(", "e", ".", "ec2", ",", "ctx", ",", "g", ",", "clock", ".", "WallClock", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "g", ".", "Name", ",", "g", ".", "Id", ",", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// destroyControllerManagedEnvirons destroys all environments managed by this // environment's controller.
[ "destroyControllerManagedEnvirons", "destroys", "all", "environments", "managed", "by", "this", "environment", "s", "controller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/environ.go#L1305-L1346
4,494
juju/juju
provider/ec2/environ.go
controllerSecurityGroups
func (e *environ) controllerSecurityGroups(ctx context.ProviderCallContext, controllerUUID string) ([]ec2.SecurityGroup, error) { filter := ec2.NewFilter() e.addControllerFilter(filter, controllerUUID) resp, err := e.ec2.SecurityGroups(nil, filter) if err != nil { return nil, errors.Annotate(maybeConvertCredentialError(err, ctx), "listing security groups") } groups := make([]ec2.SecurityGroup, len(resp.Groups)) for i, info := range resp.Groups { groups[i] = ec2.SecurityGroup{Id: info.Id, Name: info.Name} } return groups, nil }
go
func (e *environ) controllerSecurityGroups(ctx context.ProviderCallContext, controllerUUID string) ([]ec2.SecurityGroup, error) { filter := ec2.NewFilter() e.addControllerFilter(filter, controllerUUID) resp, err := e.ec2.SecurityGroups(nil, filter) if err != nil { return nil, errors.Annotate(maybeConvertCredentialError(err, ctx), "listing security groups") } groups := make([]ec2.SecurityGroup, len(resp.Groups)) for i, info := range resp.Groups { groups[i] = ec2.SecurityGroup{Id: info.Id, Name: info.Name} } return groups, nil }
[ "func", "(", "e", "*", "environ", ")", "controllerSecurityGroups", "(", "ctx", "context", ".", "ProviderCallContext", ",", "controllerUUID", "string", ")", "(", "[", "]", "ec2", ".", "SecurityGroup", ",", "error", ")", "{", "filter", ":=", "ec2", ".", "NewFilter", "(", ")", "\n", "e", ".", "addControllerFilter", "(", "filter", ",", "controllerUUID", ")", "\n", "resp", ",", "err", ":=", "e", ".", "ec2", ".", "SecurityGroups", "(", "nil", ",", "filter", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "maybeConvertCredentialError", "(", "err", ",", "ctx", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "groups", ":=", "make", "(", "[", "]", "ec2", ".", "SecurityGroup", ",", "len", "(", "resp", ".", "Groups", ")", ")", "\n", "for", "i", ",", "info", ":=", "range", "resp", ".", "Groups", "{", "groups", "[", "i", "]", "=", "ec2", ".", "SecurityGroup", "{", "Id", ":", "info", ".", "Id", ",", "Name", ":", "info", ".", "Name", "}", "\n", "}", "\n", "return", "groups", ",", "nil", "\n", "}" ]
// controllerSecurityGroups returns the details of all security groups managed // by the environment's controller.
[ "controllerSecurityGroups", "returns", "the", "details", "of", "all", "security", "groups", "managed", "by", "the", "environment", "s", "controller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/environ.go#L1510-L1522
4,495
juju/juju
provider/ec2/environ.go
cleanEnvironmentSecurityGroups
func (e *environ) cleanEnvironmentSecurityGroups(ctx context.ProviderCallContext) error { jujuGroup := e.jujuGroupName() g, err := e.groupByName(ctx, jujuGroup) if isNotFoundError(err) { return nil } if err != nil { return errors.Annotatef(err, "cannot retrieve default security group: %q", jujuGroup) } if err := deleteSecurityGroupInsistently(e.ec2, ctx, g, clock.WallClock); err != nil { return errors.Annotate(err, "cannot delete default security group") } return nil }
go
func (e *environ) cleanEnvironmentSecurityGroups(ctx context.ProviderCallContext) error { jujuGroup := e.jujuGroupName() g, err := e.groupByName(ctx, jujuGroup) if isNotFoundError(err) { return nil } if err != nil { return errors.Annotatef(err, "cannot retrieve default security group: %q", jujuGroup) } if err := deleteSecurityGroupInsistently(e.ec2, ctx, g, clock.WallClock); err != nil { return errors.Annotate(err, "cannot delete default security group") } return nil }
[ "func", "(", "e", "*", "environ", ")", "cleanEnvironmentSecurityGroups", "(", "ctx", "context", ".", "ProviderCallContext", ")", "error", "{", "jujuGroup", ":=", "e", ".", "jujuGroupName", "(", ")", "\n", "g", ",", "err", ":=", "e", ".", "groupByName", "(", "ctx", ",", "jujuGroup", ")", "\n", "if", "isNotFoundError", "(", "err", ")", "{", "return", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "jujuGroup", ")", "\n", "}", "\n", "if", "err", ":=", "deleteSecurityGroupInsistently", "(", "e", ".", "ec2", ",", "ctx", ",", "g", ",", "clock", ".", "WallClock", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// cleanEnvironmentSecurityGroups attempts to delete all security groups owned // by the environment.
[ "cleanEnvironmentSecurityGroups", "attempts", "to", "delete", "all", "security", "groups", "owned", "by", "the", "environment", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/environ.go#L1540-L1553
4,496
juju/juju
provider/ec2/environ.go
setUpGroups
func (e *environ) setUpGroups(ctx context.ProviderCallContext, controllerUUID, machineId string, apiPorts []int) ([]ec2.SecurityGroup, error) { perms := []ec2.IPPerm{{ Protocol: "tcp", FromPort: 22, ToPort: 22, SourceIPs: []string{"0.0.0.0/0"}, }} for _, apiPort := range apiPorts { perms = append(perms, ec2.IPPerm{ Protocol: "tcp", FromPort: apiPort, ToPort: apiPort, SourceIPs: []string{"0.0.0.0/0"}, }) } perms = append(perms, ec2.IPPerm{ Protocol: "tcp", FromPort: 0, ToPort: 65535, }, ec2.IPPerm{ Protocol: "udp", FromPort: 0, ToPort: 65535, }, ec2.IPPerm{ Protocol: "icmp", FromPort: -1, ToPort: -1, }) // Ensure there's a global group for Juju-related traffic. jujuGroup, err := e.ensureGroup(ctx, controllerUUID, e.jujuGroupName(), perms) if err != nil { return nil, err } var machineGroup ec2.SecurityGroup switch e.Config().FirewallMode() { case config.FwInstance: machineGroup, err = e.ensureGroup(ctx, controllerUUID, e.machineGroupName(machineId), nil) case config.FwGlobal: machineGroup, err = e.ensureGroup(ctx, controllerUUID, e.globalGroupName(), nil) } if err != nil { return nil, err } return []ec2.SecurityGroup{jujuGroup, machineGroup}, nil }
go
func (e *environ) setUpGroups(ctx context.ProviderCallContext, controllerUUID, machineId string, apiPorts []int) ([]ec2.SecurityGroup, error) { perms := []ec2.IPPerm{{ Protocol: "tcp", FromPort: 22, ToPort: 22, SourceIPs: []string{"0.0.0.0/0"}, }} for _, apiPort := range apiPorts { perms = append(perms, ec2.IPPerm{ Protocol: "tcp", FromPort: apiPort, ToPort: apiPort, SourceIPs: []string{"0.0.0.0/0"}, }) } perms = append(perms, ec2.IPPerm{ Protocol: "tcp", FromPort: 0, ToPort: 65535, }, ec2.IPPerm{ Protocol: "udp", FromPort: 0, ToPort: 65535, }, ec2.IPPerm{ Protocol: "icmp", FromPort: -1, ToPort: -1, }) // Ensure there's a global group for Juju-related traffic. jujuGroup, err := e.ensureGroup(ctx, controllerUUID, e.jujuGroupName(), perms) if err != nil { return nil, err } var machineGroup ec2.SecurityGroup switch e.Config().FirewallMode() { case config.FwInstance: machineGroup, err = e.ensureGroup(ctx, controllerUUID, e.machineGroupName(machineId), nil) case config.FwGlobal: machineGroup, err = e.ensureGroup(ctx, controllerUUID, e.globalGroupName(), nil) } if err != nil { return nil, err } return []ec2.SecurityGroup{jujuGroup, machineGroup}, nil }
[ "func", "(", "e", "*", "environ", ")", "setUpGroups", "(", "ctx", "context", ".", "ProviderCallContext", ",", "controllerUUID", ",", "machineId", "string", ",", "apiPorts", "[", "]", "int", ")", "(", "[", "]", "ec2", ".", "SecurityGroup", ",", "error", ")", "{", "perms", ":=", "[", "]", "ec2", ".", "IPPerm", "{", "{", "Protocol", ":", "\"", "\"", ",", "FromPort", ":", "22", ",", "ToPort", ":", "22", ",", "SourceIPs", ":", "[", "]", "string", "{", "\"", "\"", "}", ",", "}", "}", "\n", "for", "_", ",", "apiPort", ":=", "range", "apiPorts", "{", "perms", "=", "append", "(", "perms", ",", "ec2", ".", "IPPerm", "{", "Protocol", ":", "\"", "\"", ",", "FromPort", ":", "apiPort", ",", "ToPort", ":", "apiPort", ",", "SourceIPs", ":", "[", "]", "string", "{", "\"", "\"", "}", ",", "}", ")", "\n", "}", "\n", "perms", "=", "append", "(", "perms", ",", "ec2", ".", "IPPerm", "{", "Protocol", ":", "\"", "\"", ",", "FromPort", ":", "0", ",", "ToPort", ":", "65535", ",", "}", ",", "ec2", ".", "IPPerm", "{", "Protocol", ":", "\"", "\"", ",", "FromPort", ":", "0", ",", "ToPort", ":", "65535", ",", "}", ",", "ec2", ".", "IPPerm", "{", "Protocol", ":", "\"", "\"", ",", "FromPort", ":", "-", "1", ",", "ToPort", ":", "-", "1", ",", "}", ")", "\n", "// Ensure there's a global group for Juju-related traffic.", "jujuGroup", ",", "err", ":=", "e", ".", "ensureGroup", "(", "ctx", ",", "controllerUUID", ",", "e", ".", "jujuGroupName", "(", ")", ",", "perms", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "machineGroup", "ec2", ".", "SecurityGroup", "\n", "switch", "e", ".", "Config", "(", ")", ".", "FirewallMode", "(", ")", "{", "case", "config", ".", "FwInstance", ":", "machineGroup", ",", "err", "=", "e", ".", "ensureGroup", "(", "ctx", ",", "controllerUUID", ",", "e", ".", "machineGroupName", "(", "machineId", ")", ",", "nil", ")", "\n", "case", "config", ".", "FwGlobal", ":", "machineGroup", ",", "err", "=", "e", ".", "ensureGroup", "(", "ctx", ",", "controllerUUID", ",", "e", ".", "globalGroupName", "(", ")", ",", "nil", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "[", "]", "ec2", ".", "SecurityGroup", "{", "jujuGroup", ",", "machineGroup", "}", ",", "nil", "\n", "}" ]
// setUpGroups creates the security groups for the new machine, and // returns them. // // Instances are tagged with a group so they can be distinguished from // other instances that might be running on the same EC2 account. In // addition, a specific machine security group is created for each // machine, so that its firewall rules can be configured per machine.
[ "setUpGroups", "creates", "the", "security", "groups", "for", "the", "new", "machine", "and", "returns", "them", ".", "Instances", "are", "tagged", "with", "a", "group", "so", "they", "can", "be", "distinguished", "from", "other", "instances", "that", "might", "be", "running", "on", "the", "same", "EC2", "account", ".", "In", "addition", "a", "specific", "machine", "security", "group", "is", "created", "for", "each", "machine", "so", "that", "its", "firewall", "rules", "can", "be", "configured", "per", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/environ.go#L1721-L1766
4,497
juju/juju
provider/ec2/environ.go
newPermSetForGroup
func newPermSetForGroup(ps []ec2.IPPerm, group ec2.SecurityGroup) permSet { m := make(permSet) for _, p := range ps { k := permKey{ protocol: p.Protocol, fromPort: p.FromPort, toPort: p.ToPort, } if len(p.SourceIPs) > 0 { for _, ip := range p.SourceIPs { k.ipAddr = ip m[k] = true } } else { k.groupId = group.Id m[k] = true } } return m }
go
func newPermSetForGroup(ps []ec2.IPPerm, group ec2.SecurityGroup) permSet { m := make(permSet) for _, p := range ps { k := permKey{ protocol: p.Protocol, fromPort: p.FromPort, toPort: p.ToPort, } if len(p.SourceIPs) > 0 { for _, ip := range p.SourceIPs { k.ipAddr = ip m[k] = true } } else { k.groupId = group.Id m[k] = true } } return m }
[ "func", "newPermSetForGroup", "(", "ps", "[", "]", "ec2", ".", "IPPerm", ",", "group", "ec2", ".", "SecurityGroup", ")", "permSet", "{", "m", ":=", "make", "(", "permSet", ")", "\n", "for", "_", ",", "p", ":=", "range", "ps", "{", "k", ":=", "permKey", "{", "protocol", ":", "p", ".", "Protocol", ",", "fromPort", ":", "p", ".", "FromPort", ",", "toPort", ":", "p", ".", "ToPort", ",", "}", "\n", "if", "len", "(", "p", ".", "SourceIPs", ")", ">", "0", "{", "for", "_", ",", "ip", ":=", "range", "p", ".", "SourceIPs", "{", "k", ".", "ipAddr", "=", "ip", "\n", "m", "[", "k", "]", "=", "true", "\n", "}", "\n", "}", "else", "{", "k", ".", "groupId", "=", "group", ".", "Id", "\n", "m", "[", "k", "]", "=", "true", "\n", "}", "\n", "}", "\n", "return", "m", "\n", "}" ]
// newPermSetForGroup returns a set of all the permissions in the // given slice of IPPerms. It ignores the name and owner // id in source groups, and any entry with no source ips will // be granted for the given group only.
[ "newPermSetForGroup", "returns", "a", "set", "of", "all", "the", "permissions", "in", "the", "given", "slice", "of", "IPPerms", ".", "It", "ignores", "the", "name", "and", "owner", "id", "in", "source", "groups", "and", "any", "entry", "with", "no", "source", "ips", "will", "be", "granted", "for", "the", "given", "group", "only", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/environ.go#L1892-L1911
4,498
juju/juju
provider/ec2/environ.go
ipPerms
func (m permSet) ipPerms() (ps []ec2.IPPerm) { // We could compact the permissions, but it // hardly seems worth it. for p := range m { ipp := ec2.IPPerm{ Protocol: p.protocol, FromPort: p.fromPort, ToPort: p.toPort, } if p.ipAddr != "" { ipp.SourceIPs = []string{p.ipAddr} } else { ipp.SourceGroups = []ec2.UserSecurityGroup{{Id: p.groupId}} } ps = append(ps, ipp) } return }
go
func (m permSet) ipPerms() (ps []ec2.IPPerm) { // We could compact the permissions, but it // hardly seems worth it. for p := range m { ipp := ec2.IPPerm{ Protocol: p.protocol, FromPort: p.fromPort, ToPort: p.toPort, } if p.ipAddr != "" { ipp.SourceIPs = []string{p.ipAddr} } else { ipp.SourceGroups = []ec2.UserSecurityGroup{{Id: p.groupId}} } ps = append(ps, ipp) } return }
[ "func", "(", "m", "permSet", ")", "ipPerms", "(", ")", "(", "ps", "[", "]", "ec2", ".", "IPPerm", ")", "{", "// We could compact the permissions, but it", "// hardly seems worth it.", "for", "p", ":=", "range", "m", "{", "ipp", ":=", "ec2", ".", "IPPerm", "{", "Protocol", ":", "p", ".", "protocol", ",", "FromPort", ":", "p", ".", "fromPort", ",", "ToPort", ":", "p", ".", "toPort", ",", "}", "\n", "if", "p", ".", "ipAddr", "!=", "\"", "\"", "{", "ipp", ".", "SourceIPs", "=", "[", "]", "string", "{", "p", ".", "ipAddr", "}", "\n", "}", "else", "{", "ipp", ".", "SourceGroups", "=", "[", "]", "ec2", ".", "UserSecurityGroup", "{", "{", "Id", ":", "p", ".", "groupId", "}", "}", "\n", "}", "\n", "ps", "=", "append", "(", "ps", ",", "ipp", ")", "\n", "}", "\n", "return", "\n", "}" ]
// ipPerms returns m as a slice of permissions usable // with the ec2 package.
[ "ipPerms", "returns", "m", "as", "a", "slice", "of", "permissions", "usable", "with", "the", "ec2", "package", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/environ.go#L1915-L1932
4,499
juju/juju
provider/ec2/environ.go
isZoneConstrainedError
func isZoneConstrainedError(err error) bool { switch err := errors.Cause(err).(type) { case *ec2.Error: switch err.Code { case "Unsupported", "InsufficientInstanceCapacity": // A big hammer, but we've now seen several different error messages // for constrained zones, and who knows how many more there might // be. If the message contains "Availability Zone", it's a fair // bet that it's constrained or otherwise unusable. return strings.Contains(err.Message, "Availability Zone") case "InvalidInput": // If the region has a default VPC, then we will receive an error // if the AZ does not have a default subnet. Until we have proper // support for networks, we'll skip over these. return strings.HasPrefix(err.Message, "No default subnet for availability zone") case "VolumeTypeNotAvailableInZone": return true } } return false }
go
func isZoneConstrainedError(err error) bool { switch err := errors.Cause(err).(type) { case *ec2.Error: switch err.Code { case "Unsupported", "InsufficientInstanceCapacity": // A big hammer, but we've now seen several different error messages // for constrained zones, and who knows how many more there might // be. If the message contains "Availability Zone", it's a fair // bet that it's constrained or otherwise unusable. return strings.Contains(err.Message, "Availability Zone") case "InvalidInput": // If the region has a default VPC, then we will receive an error // if the AZ does not have a default subnet. Until we have proper // support for networks, we'll skip over these. return strings.HasPrefix(err.Message, "No default subnet for availability zone") case "VolumeTypeNotAvailableInZone": return true } } return false }
[ "func", "isZoneConstrainedError", "(", "err", "error", ")", "bool", "{", "switch", "err", ":=", "errors", ".", "Cause", "(", "err", ")", ".", "(", "type", ")", "{", "case", "*", "ec2", ".", "Error", ":", "switch", "err", ".", "Code", "{", "case", "\"", "\"", ",", "\"", "\"", ":", "// A big hammer, but we've now seen several different error messages", "// for constrained zones, and who knows how many more there might", "// be. If the message contains \"Availability Zone\", it's a fair", "// bet that it's constrained or otherwise unusable.", "return", "strings", ".", "Contains", "(", "err", ".", "Message", ",", "\"", "\"", ")", "\n", "case", "\"", "\"", ":", "// If the region has a default VPC, then we will receive an error", "// if the AZ does not have a default subnet. Until we have proper", "// support for networks, we'll skip over these.", "return", "strings", ".", "HasPrefix", "(", "err", ".", "Message", ",", "\"", "\"", ")", "\n", "case", "\"", "\"", ":", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isZoneConstrainedError reports whether or not the error indicates // RunInstances failed due to the specified availability zone being // constrained for the instance type being provisioned, or is // otherwise unusable for the specific request made.
[ "isZoneConstrainedError", "reports", "whether", "or", "not", "the", "error", "indicates", "RunInstances", "failed", "due", "to", "the", "specified", "availability", "zone", "being", "constrained", "for", "the", "instance", "type", "being", "provisioned", "or", "is", "otherwise", "unusable", "for", "the", "specific", "request", "made", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/environ.go#L1942-L1962