repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/sharedaction/is_logged_in.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/sharedaction/is_logged_in.go#L4-L6
go
train
// IsLoggedIn checks whether a user has authenticated with CF
func (actor Actor) IsLoggedIn() bool
// IsLoggedIn checks whether a user has authenticated with CF func (actor Actor) IsLoggedIn() bool
{ return actor.Config.AccessToken() != "" || actor.Config.RefreshToken() != "" }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/plugin/request.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/plugin/request.go#L7-L23
go
train
// newGETRequest returns a constructed HTTP.Request with some defaults. // Defaults are applied when Request options are not filled in.
func (client *Client) newGETRequest(url string) (*http.Request, error)
// newGETRequest returns a constructed HTTP.Request with some defaults. // Defaults are applied when Request options are not filled in. func (client *Client) newGETRequest(url string) (*http.Request, error)
{ request, err := http.NewRequest( http.MethodGet, url, nil, ) if err != nil { return nil, err } request.Header = http.Header{} request.Header.Set("Accept", "application/json") request.Header.Set("Content-Type", "application/json") request.Header.Set("User-Agent", client.userAgent) return request, nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/minimum_version_check.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/minimum_version_check.go#L10-L33
go
train
// MinimumAPIVersionCheck compares `current` to `minimum`. If `current` is // older than `minimum` then an error is returned; otherwise, nil is returned.
func MinimumAPIVersionCheck(current string, minimum string) error
// MinimumAPIVersionCheck compares `current` to `minimum`. If `current` is // older than `minimum` then an error is returned; otherwise, nil is returned. func MinimumAPIVersionCheck(current string, minimum string) error
{ if minimum == "" { return nil } currentSemver, err := semver.Make(current) if err != nil { return err } minimumSemver, err := semver.Make(minimum) if err != nil { return err } if currentSemver.Compare(minimumSemver) == -1 { return ccerror.MinimumAPIVersionNotMetError{ CurrentVersion: current, MinimumVersion: minimum, } } return nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
util/ui/request_logger_file_writer.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/ui/request_logger_file_writer.go#L142-L144
go
train
// RequestLoggerFileWriter returns a RequestLoggerFileWriter that cannot // overwrite another RequestLoggerFileWriter.
func (ui *UI) RequestLoggerFileWriter(filePaths []string) *RequestLoggerFileWriter
// RequestLoggerFileWriter returns a RequestLoggerFileWriter that cannot // overwrite another RequestLoggerFileWriter. func (ui *UI) RequestLoggerFileWriter(filePaths []string) *RequestLoggerFileWriter
{ return newRequestLoggerFileWriter(ui, ui.fileLock, filePaths) }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/stack.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/stack.go#L22-L39
go
train
// UnmarshalJSON helps unmarshal a Cloud Controller Stack response.
func (stack *Stack) UnmarshalJSON(data []byte) error
// UnmarshalJSON helps unmarshal a Cloud Controller Stack response. func (stack *Stack) UnmarshalJSON(data []byte) error
{ var ccStack struct { Metadata internal.Metadata `json:"metadata"` Entity struct { Name string `json:"name"` Description string `json:"description"` } `json:"entity"` } err := cloudcontroller.DecodeJSON(data, &ccStack) if err != nil { return err } stack.GUID = ccStack.Metadata.GUID stack.Name = ccStack.Entity.Name stack.Description = ccStack.Entity.Description return nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/stack.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/stack.go#L42-L58
go
train
// GetStack returns the requested stack.
func (client *Client) GetStack(guid string) (Stack, Warnings, error)
// GetStack returns the requested stack. func (client *Client) GetStack(guid string) (Stack, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetStackRequest, URIParams: Params{"stack_guid": guid}, }) if err != nil { return Stack{}, nil, err } var stack Stack response := cloudcontroller.Response{ DecodeJSONResponseInto: &stack, } err = client.connection.Make(request, &response) return stack, response.Warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/stack.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/stack.go#L61-L84
go
train
// GetStacks returns a list of Stacks based off of the provided filters.
func (client *Client) GetStacks(filters ...Filter) ([]Stack, Warnings, error)
// GetStacks returns a list of Stacks based off of the provided filters. func (client *Client) GetStacks(filters ...Filter) ([]Stack, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetStacksRequest, Query: ConvertFilterParameters(filters), }) if err != nil { return nil, nil, err } var fullStacksList []Stack warnings, err := client.paginate(request, Stack{}, func(item interface{}) error { if space, ok := item.(Stack); ok { fullStacksList = append(fullStacksList, space) } else { return ccerror.UnknownObjectInListError{ Expected: Stack{}, Unexpected: item, } } return nil }) return fullStacksList, warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/wrapper/uaa_authentication.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/wrapper/uaa_authentication.go#L52-L68
go
train
// Make adds authentication headers to the passed in request and then calls the // wrapped connection's Make. If the client is not set on the wrapper, it will // not add any header or handle any authentication errors.
func (t *UAAAuthentication) Make(request *cloudcontroller.Request, passedResponse *cloudcontroller.Response) error
// Make adds authentication headers to the passed in request and then calls the // wrapped connection's Make. If the client is not set on the wrapper, it will // not add any header or handle any authentication errors. func (t *UAAAuthentication) Make(request *cloudcontroller.Request, passedResponse *cloudcontroller.Response) error
{ if t.client == nil { return t.connection.Make(request, passedResponse) } if t.cache.AccessToken() != "" || t.cache.RefreshToken() != "" { // assert a valid access token for authenticated requests err := t.refreshToken() if nil != err { return err } request.Header.Set("Authorization", t.cache.AccessToken()) } err := t.connection.Make(request, passedResponse) return err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/wrapper/uaa_authentication.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/wrapper/uaa_authentication.go#L76-L79
go
train
// Wrap sets the connection on the UAAAuthentication and returns itself
func (t *UAAAuthentication) Wrap(innerconnection cloudcontroller.Connection) cloudcontroller.Connection
// Wrap sets the connection on the UAAAuthentication and returns itself func (t *UAAAuthentication) Wrap(innerconnection cloudcontroller.Connection) cloudcontroller.Connection
{ t.connection = innerconnection return t }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/wrapper/uaa_authentication.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/wrapper/uaa_authentication.go#L83-L105
go
train
// refreshToken refreshes the JWT access token if it is expired or about to expire. // If the access token is not yet expired, no action is performed.
func (t *UAAAuthentication) refreshToken() error
// refreshToken refreshes the JWT access token if it is expired or about to expire. // If the access token is not yet expired, no action is performed. func (t *UAAAuthentication) refreshToken() error
{ var expiresIn time.Duration tokenStr := strings.TrimPrefix(t.cache.AccessToken(), "bearer ") token, err := jws.ParseJWT([]byte(tokenStr)) if err != nil { // if the JWT could not be parsed, force a refresh expiresIn = 0 } else { expiration, _ := token.Claims().Expiration() expiresIn = time.Until(expiration) } if expiresIn < accessTokenExpirationMargin { tokens, err := t.client.RefreshAccessToken(t.cache.RefreshToken()) if err != nil { return err } t.cache.SetAccessToken(tokens.AuthorizationToken()) t.cache.SetRefreshToken(tokens.RefreshToken) } return nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v2action/service_access.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/service_access.go#L63-L89
go
train
// EnableServiceForOrg enables access for the given service in a specific org.
func (actor Actor) EnableServiceForOrg(serviceName, orgName, brokerName string) (Warnings, error)
// EnableServiceForOrg enables access for the given service in a specific org. func (actor Actor) EnableServiceForOrg(serviceName, orgName, brokerName string) (Warnings, error)
{ servicePlans, allWarnings, err := actor.GetServicePlansForService(serviceName, brokerName) if err != nil { return allWarnings, err } org, orgWarnings, err := actor.GetOrganizationByName(orgName) allWarnings = append(allWarnings, orgWarnings...) if err != nil { return allWarnings, err } for _, plan := range servicePlans { if plan.Public != true { _, warnings, err := actor.CloudControllerClient.CreateServicePlanVisibility(plan.GUID, org.GUID) allWarnings = append(allWarnings, warnings...) if _, alreadyExistsError := err.(ccerror.ServicePlanVisibilityExistsError); alreadyExistsError { return allWarnings, nil } if err != nil { return allWarnings, err } } } return allWarnings, nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v2action/service_access.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/service_access.go#L92-L119
go
train
// EnablePlanForOrg enables access to a specific plan of the given service in a specific org.
func (actor Actor) EnablePlanForOrg(serviceName, servicePlanName, orgName, brokerName string) (Warnings, error)
// EnablePlanForOrg enables access to a specific plan of the given service in a specific org. func (actor Actor) EnablePlanForOrg(serviceName, servicePlanName, orgName, brokerName string) (Warnings, error)
{ servicePlans, allWarnings, err := actor.GetServicePlansForService(serviceName, brokerName) if err != nil { return allWarnings, err } org, orgWarnings, err := actor.GetOrganizationByName(orgName) allWarnings = append(allWarnings, orgWarnings...) if err != nil { return allWarnings, err } for _, plan := range servicePlans { if plan.Name == servicePlanName { if plan.Public { return allWarnings, nil } _, warnings, err := actor.CloudControllerClient.CreateServicePlanVisibility(plan.GUID, org.GUID) allWarnings = append(allWarnings, warnings...) if _, alreadyExistsError := err.(ccerror.ServicePlanVisibilityExistsError); alreadyExistsError { return allWarnings, nil } return allWarnings, err } } return nil, fmt.Errorf("Service plan '%s' not found", servicePlanName) }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v2action/service_access.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/service_access.go#L122-L144
go
train
// DisableServiceForAllOrgs disables access for the given service in all orgs.
func (actor Actor) DisableServiceForAllOrgs(serviceName, brokerName string) (Warnings, error)
// DisableServiceForAllOrgs disables access for the given service in all orgs. func (actor Actor) DisableServiceForAllOrgs(serviceName, brokerName string) (Warnings, error)
{ servicePlans, allWarnings, err := actor.GetServicePlansForService(serviceName, brokerName) if err != nil { return allWarnings, err } for _, plan := range servicePlans { warnings, err := actor.removeOrgLevelServicePlanVisibilities(plan.GUID, "") allWarnings = append(allWarnings, warnings...) if err != nil { return allWarnings, err } if plan.Public == true { warnings, err := actor.CloudControllerClient.UpdateServicePlan(plan.GUID, false) allWarnings = append(allWarnings, warnings...) if err != nil { return allWarnings, err } } } return allWarnings, nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v2action/service_access.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/service_access.go#L147-L176
go
train
// DisablePlanForAllOrgs disables access to a specific plan of the given service, from the given broker in all orgs.
func (actor Actor) DisablePlanForAllOrgs(serviceName, servicePlanName, brokerName string) (Warnings, error)
// DisablePlanForAllOrgs disables access to a specific plan of the given service, from the given broker in all orgs. func (actor Actor) DisablePlanForAllOrgs(serviceName, servicePlanName, brokerName string) (Warnings, error)
{ servicePlans, allWarnings, err := actor.GetServicePlansForService(serviceName, brokerName) if err != nil { return allWarnings, err } planFound := false for _, plan := range servicePlans { if plan.Name == servicePlanName { warnings, err := actor.removeOrgLevelServicePlanVisibilities(plan.GUID, "") allWarnings = append(allWarnings, warnings...) if err != nil { return allWarnings, err } if plan.Public == true { ccv2Warnings, err := actor.CloudControllerClient.UpdateServicePlan(plan.GUID, false) allWarnings = append(allWarnings, ccv2Warnings...) return allWarnings, err } planFound = true break } } if planFound == false { return allWarnings, actionerror.ServicePlanNotFoundError{PlanName: servicePlanName, ServiceName: serviceName} } return allWarnings, nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v2action/service_access.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/service_access.go#L179-L199
go
train
// DisableServiceForOrg disables access for the given service in a specific org.
func (actor Actor) DisableServiceForOrg(serviceName, orgName, brokerName string) (Warnings, error)
// DisableServiceForOrg disables access for the given service in a specific org. func (actor Actor) DisableServiceForOrg(serviceName, orgName, brokerName string) (Warnings, error)
{ servicePlans, allWarnings, err := actor.GetServicePlansForService(serviceName, brokerName) if err != nil { return allWarnings, err } org, orgWarnings, err := actor.GetOrganizationByName(orgName) allWarnings = append(allWarnings, orgWarnings...) if err != nil { return allWarnings, err } for _, plan := range servicePlans { warnings, err := actor.removeOrgLevelServicePlanVisibilities(plan.GUID, org.GUID) allWarnings = append(allWarnings, warnings...) if err != nil { return allWarnings, err } } return allWarnings, nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v2action/service_access.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/service_access.go#L202-L231
go
train
// DisablePlanForOrg disables access to a specific plan of the given service from the given broker in a specific org.
func (actor Actor) DisablePlanForOrg(serviceName, servicePlanName, orgName, brokerName string) (Warnings, error)
// DisablePlanForOrg disables access to a specific plan of the given service from the given broker in a specific org. func (actor Actor) DisablePlanForOrg(serviceName, servicePlanName, orgName, brokerName string) (Warnings, error)
{ servicePlans, allWarnings, err := actor.GetServicePlansForService(serviceName, brokerName) if err != nil { return allWarnings, err } org, orgWarnings, err := actor.GetOrganizationByName(orgName) allWarnings = append(allWarnings, orgWarnings...) if err != nil { return allWarnings, err } planFound := false for _, plan := range servicePlans { if plan.Name == servicePlanName { warnings, err := actor.removeOrgLevelServicePlanVisibilities(plan.GUID, org.GUID) allWarnings = append(allWarnings, warnings...) if err != nil { return allWarnings, err } planFound = true break } } if planFound == false { return allWarnings, actionerror.ServicePlanNotFoundError{PlanName: servicePlanName, ServiceName: serviceName} } return allWarnings, nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
integration/helpers/service_instance.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/integration/helpers/service_instance.go#L21-L33
go
train
// ManagedServiceInstanceGUID returns the GUID for a managed service instance.
func ManagedServiceInstanceGUID(managedServiceInstanceName string) string
// ManagedServiceInstanceGUID returns the GUID for a managed service instance. func ManagedServiceInstanceGUID(managedServiceInstanceName string) string
{ session := CF("curl", fmt.Sprintf("/v2/service_instances?q=name:%s", managedServiceInstanceName)) Eventually(session).Should(Exit(0)) rawJSON := strings.TrimSpace(string(session.Out.Contents())) var serviceInstanceGUID ServiceInstanceGUID err := json.Unmarshal([]byte(rawJSON), &serviceInstanceGUID) Expect(err).NotTo(HaveOccurred()) Expect(serviceInstanceGUID.Resources).To(HaveLen(1)) return serviceInstanceGUID.Resources[0].Metadata.GUID }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/router/wrapper/request_logger.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/router/wrapper/request_logger.go#L64-L67
go
train
// Wrap sets the connection on the RequestLogger and returns itself
func (logger *RequestLogger) Wrap(innerconnection router.Connection) router.Connection
// Wrap sets the connection on the RequestLogger and returns itself func (logger *RequestLogger) Wrap(innerconnection router.Connection) router.Connection
{ logger.connection = innerconnection return logger }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v7action/space.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v7action/space.go#L60-L75
go
train
// GetOrganizationSpaces returns a list of spaces in the specified org
func (actor Actor) GetOrganizationSpaces(orgGUID string) ([]Space, Warnings, error)
// GetOrganizationSpaces returns a list of spaces in the specified org func (actor Actor) GetOrganizationSpaces(orgGUID string) ([]Space, Warnings, error)
{ ccv2Spaces, warnings, err := actor.CloudControllerClient.GetSpaces(ccv3.Query{ Key: ccv3.OrganizationGUIDFilter, Values: []string{orgGUID}, }) if err != nil { return []Space{}, Warnings(warnings), err } spaces := make([]Space, len(ccv2Spaces)) for i, ccv2Space := range ccv2Spaces { spaces[i] = Space(ccv2Space) } return spaces, Warnings(warnings), nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/uaa/wrapper/uaa_authentication.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/uaa/wrapper/uaa_authentication.go#L48-L90
go
train
// Make adds authentication headers to the passed in request and then calls the // wrapped connection's Make
func (t *UAAAuthentication) Make(request *http.Request, passedResponse *uaa.Response) error
// Make adds authentication headers to the passed in request and then calls the // wrapped connection's Make func (t *UAAAuthentication) Make(request *http.Request, passedResponse *uaa.Response) error
{ if t.client == nil { return t.connection.Make(request, passedResponse) } var err error var rawRequestBody []byte if request.Body != nil { rawRequestBody, err = ioutil.ReadAll(request.Body) defer request.Body.Close() if err != nil { return err } request.Body = ioutil.NopCloser(bytes.NewBuffer(rawRequestBody)) if skipAuthenticationHeader(request, rawRequestBody) { return t.connection.Make(request, passedResponse) } } request.Header.Set("Authorization", t.cache.AccessToken()) err = t.connection.Make(request, passedResponse) if _, ok := err.(uaa.InvalidAuthTokenError); ok { tokens, refreshErr := t.client.RefreshAccessToken(t.cache.RefreshToken()) if refreshErr != nil { return refreshErr } t.cache.SetAccessToken(tokens.AuthorizationToken()) t.cache.SetRefreshToken(tokens.RefreshToken) if rawRequestBody != nil { request.Body = ioutil.NopCloser(bytes.NewBuffer(rawRequestBody)) } request.Header.Set("Authorization", t.cache.AccessToken()) return t.connection.Make(request, passedResponse) } return err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/uaa/wrapper/uaa_authentication.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/uaa/wrapper/uaa_authentication.go#L98-L101
go
train
// Wrap sets the connection on the UAAAuthentication and returns itself
func (t *UAAAuthentication) Wrap(innerconnection uaa.Connection) uaa.Connection
// Wrap sets the connection on the UAAAuthentication and returns itself func (t *UAAAuthentication) Wrap(innerconnection uaa.Connection) uaa.Connection
{ t.connection = innerconnection return t }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/uaa/wrapper/uaa_authentication.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/uaa/wrapper/uaa_authentication.go#L105-L113
go
train
// The authentication header is not added to token refresh requests or login // requests.
func skipAuthenticationHeader(request *http.Request, body []byte) bool
// The authentication header is not added to token refresh requests or login // requests. func skipAuthenticationHeader(request *http.Request, body []byte) bool
{ stringBody := string(body) return strings.Contains(request.URL.String(), "/oauth/token") && request.Method == http.MethodPost && (strings.Contains(stringBody, "grant_type=refresh_token") || strings.Contains(stringBody, "grant_type=password") || strings.Contains(stringBody, "grant_type=client_credentials")) }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/plugin/plugin_connection.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/plugin/plugin_connection.go#L25-L40
go
train
// NewConnection returns a new PluginConnection
func NewConnection(skipSSLValidation bool, dialTimeout time.Duration) *PluginConnection
// NewConnection returns a new PluginConnection func NewConnection(skipSSLValidation bool, dialTimeout time.Duration) *PluginConnection
{ tr := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: skipSSLValidation, }, Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ KeepAlive: 30 * time.Second, Timeout: dialTimeout, }).DialContext, } return &PluginConnection{ HTTPClient: &http.Client{Transport: tr}, } }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/plugin/plugin_connection.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/plugin/plugin_connection.go#L43-L62
go
train
// Make performs the request and parses the response.
func (connection *PluginConnection) Make(request *http.Request, passedResponse *Response, proxyReader ProxyReader) error
// Make performs the request and parses the response. func (connection *PluginConnection) Make(request *http.Request, passedResponse *Response, proxyReader ProxyReader) error
{ // In case this function is called from a retry, passedResponse may already // be populated with a previous response. We reset in case there's an HTTP // error and we don't repopulate it in populateResponse. passedResponse.reset() response, err := connection.HTTPClient.Do(request) if err != nil { return connection.processRequestErrors(request, err) } body := response.Body if proxyReader != nil { proxyReader.Start(response.ContentLength) defer proxyReader.Finish() body = proxyReader.Wrap(response.Body) } return connection.populateResponse(response, passedResponse, body) }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/pushaction/apply.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/pushaction/apply.go#L19-L175
go
train
// Apply use the V2 API to create/update the application settings and // eventually uploads the application bits. // // If multiple buildpacks are being applied to the application, the V3 API is // used to set those buildpacks.
func (actor Actor) Apply(config ApplicationConfig, progressBar ProgressBar) (<-chan ApplicationConfig, <-chan Event, <-chan Warnings, <-chan error)
// Apply use the V2 API to create/update the application settings and // eventually uploads the application bits. // // If multiple buildpacks are being applied to the application, the V3 API is // used to set those buildpacks. func (actor Actor) Apply(config ApplicationConfig, progressBar ProgressBar) (<-chan ApplicationConfig, <-chan Event, <-chan Warnings, <-chan error)
{ configStream := make(chan ApplicationConfig) eventStream := make(chan Event) warningsStream := make(chan Warnings) errorStream := make(chan error) go func() { log.Debug("starting apply go routine") defer close(configStream) defer close(eventStream) defer close(warningsStream) defer close(errorStream) var event Event var warnings Warnings var err error eventStream <- SettingUpApplication if config.UpdatingApplication() { config, event, warnings, err = actor.UpdateApplication(config) } else { config, event, warnings, err = actor.CreateApplication(config) } warningsStream <- warnings if err != nil { errorStream <- err return } eventStream <- event log.Debugf("desired application: %#v", config.DesiredApplication) if config.NoRoute { if len(config.CurrentRoutes) > 0 { eventStream <- UnmappingRoutes config, warnings, err = actor.UnmapRoutes(config) warningsStream <- warnings if err != nil { errorStream <- err return } } } else { eventStream <- CreatingAndMappingRoutes var createdRoutes bool config, createdRoutes, warnings, err = actor.CreateRoutes(config) warningsStream <- warnings if err != nil { errorStream <- err return } if createdRoutes { log.Debugf("updated desired routes: %#v", config.DesiredRoutes) eventStream <- CreatedRoutes } var boundRoutes bool config, boundRoutes, warnings, err = actor.MapRoutes(config) warningsStream <- warnings if err != nil { errorStream <- err return } if boundRoutes { log.Debugf("updated desired routes: %#v", config.DesiredRoutes) eventStream <- BoundRoutes } } if len(config.CurrentServices) != len(config.DesiredServices) { eventStream <- ConfiguringServices config, _, warnings, err = actor.BindServices(config) warningsStream <- warnings if err != nil { errorStream <- err return } log.Debugf("bound desired services: %#v", config.DesiredServices) eventStream <- BoundServices } if config.DropletPath != "" { for count := 0; count < PushRetries; count++ { warnings, err = actor.UploadDroplet(config, config.DropletPath, progressBar, eventStream) warningsStream <- warnings if _, ok := err.(ccerror.PipeSeekError); ok { eventStream <- RetryUpload } else { break } } if err != nil { if e, ok := err.(ccerror.PipeSeekError); ok { errorStream <- actionerror.UploadFailedError{Err: e.Err} } else { errorStream <- err } return } } else if config.DesiredApplication.DockerImage == "" { eventStream <- ResourceMatching config, warnings = actor.SetMatchedResources(config) warningsStream <- warnings if len(config.UnmatchedResources) > 0 { var archivePath string archivePath, err = actor.CreateArchive(config) if err != nil { errorStream <- err os.RemoveAll(archivePath) return } eventStream <- CreatingArchive defer os.RemoveAll(archivePath) for count := 0; count < PushRetries; count++ { warnings, err = actor.UploadPackageWithArchive(config, archivePath, progressBar, eventStream) warningsStream <- warnings if _, ok := err.(ccerror.PipeSeekError); ok { eventStream <- RetryUpload } else { break } } if err != nil { if e, ok := err.(ccerror.PipeSeekError); ok { errorStream <- actionerror.UploadFailedError{Err: e.Err} } else { errorStream <- err } return } } else { eventStream <- UploadingApplication warnings, err = actor.UploadPackage(config) warningsStream <- warnings if err != nil { errorStream <- err return } } } else { log.WithField("docker_image", config.DesiredApplication.DockerImage).Debug("skipping file upload") } configStream <- config log.Debug("completed apply") eventStream <- Complete }() return configStream, eventStream, warningsStream, errorStream }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v2action/service.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/service.go#L19-L22
go
train
// GetService fetches a service by GUID.
func (actor Actor) GetService(serviceGUID string) (Service, Warnings, error)
// GetService fetches a service by GUID. func (actor Actor) GetService(serviceGUID string) (Service, Warnings, error)
{ service, warnings, err := actor.CloudControllerClient.GetService(serviceGUID) return Service(service), Warnings(warnings), err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v2action/service.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/service.go#L30-L65
go
train
// GetServiceByNameAndBrokerName returns services based on the name and broker provided. // If a service broker name is provided, only services for that broker will be returned. // If there are no services, a ServiceNotFoundError will be returned. // // NOTE: this will fail for non-admin users if the broker name is specified, as only // admin users are able to view the list of service brokers.
func (actor Actor) GetServiceByNameAndBrokerName(serviceName, serviceBrokerName string) (Service, Warnings, error)
// GetServiceByNameAndBrokerName returns services based on the name and broker provided. // If a service broker name is provided, only services for that broker will be returned. // If there are no services, a ServiceNotFoundError will be returned. // // NOTE: this will fail for non-admin users if the broker name is specified, as only // admin users are able to view the list of service brokers. func (actor Actor) GetServiceByNameAndBrokerName(serviceName, serviceBrokerName string) (Service, Warnings, error)
{ filters := []ccv2.Filter{ccv2.Filter{ Type: constant.LabelFilter, Operator: constant.EqualOperator, Values: []string{serviceName}, }} if serviceBrokerName != "" { serviceBroker, warnings, err := actor.GetServiceBrokerByName(serviceBrokerName) if err != nil { return Service{}, warnings, err } brokerFilter := ccv2.Filter{ Type: constant.ServiceBrokerGUIDFilter, Operator: constant.EqualOperator, Values: []string{serviceBroker.GUID}, } filters = append(filters, brokerFilter) } services, warnings, err := actor.CloudControllerClient.GetServices(filters...) if err != nil { return Service{}, Warnings(warnings), err } if len(services) == 0 { return Service{}, Warnings(warnings), actionerror.ServiceNotFoundError{Name: serviceName} } if len(services) > 1 { return Service{}, Warnings(warnings), actionerror.DuplicateServiceError{Name: serviceName} } return Service(services[0]), Warnings(warnings), nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v2action/service.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/service.go#L93-L128
go
train
// GetServicesWithPlans returns a map of Services to ServicePlans for a particular broker. // A particular service with associated plans from a broker can be fetched by additionally providing // a service label filter.
func (actor Actor) GetServicesWithPlans(filters ...Filter) (ServicesWithPlans, Warnings, error)
// GetServicesWithPlans returns a map of Services to ServicePlans for a particular broker. // A particular service with associated plans from a broker can be fetched by additionally providing // a service label filter. func (actor Actor) GetServicesWithPlans(filters ...Filter) (ServicesWithPlans, Warnings, error)
{ ccv2Filters := []ccv2.Filter{} for _, f := range filters { ccv2Filters = append(ccv2Filters, ccv2.Filter(f)) } var allWarnings Warnings services, warnings, err := actor.CloudControllerClient.GetServices(ccv2Filters...) allWarnings = append(allWarnings, Warnings(warnings)...) if err != nil { return nil, allWarnings, err } servicesWithPlans := ServicesWithPlans{} for _, service := range services { servicePlans, warnings, err := actor.CloudControllerClient.GetServicePlans(ccv2.Filter{ Type: constant.ServiceGUIDFilter, Operator: constant.EqualOperator, Values: []string{service.GUID}, }) allWarnings = append(allWarnings, Warnings(warnings)...) if err != nil { return nil, allWarnings, err } plansToReturn := []ServicePlan{} for _, plan := range servicePlans { plansToReturn = append(plansToReturn, ServicePlan(plan)) } servicesWithPlans[Service(service)] = plansToReturn } return servicesWithPlans, allWarnings, nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v2action/service.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/service.go#L132-L147
go
train
// ServiceExistsWithName returns true if there is an Organization with the // provided name, otherwise false.
func (actor Actor) ServiceExistsWithName(serviceName string) (bool, Warnings, error)
// ServiceExistsWithName returns true if there is an Organization with the // provided name, otherwise false. func (actor Actor) ServiceExistsWithName(serviceName string) (bool, Warnings, error)
{ services, warnings, err := actor.CloudControllerClient.GetServices(ccv2.Filter{ Type: constant.LabelFilter, Operator: constant.EqualOperator, Values: []string{serviceName}, }) if err != nil { return false, Warnings(warnings), err } if len(services) == 0 { return false, Warnings(warnings), nil } return true, Warnings(warnings), nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v3action/ssh.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v3action/ssh.go#L18-L80
go
train
// GetSecureShellConfigurationByApplicationNameSpaceProcessTypeAndIndex returns // back the SSH authentication information for the SSH session.
func (actor Actor) GetSecureShellConfigurationByApplicationNameSpaceProcessTypeAndIndex( appName string, spaceGUID string, processType string, processIndex uint, ) (SSHAuthentication, Warnings, error)
// GetSecureShellConfigurationByApplicationNameSpaceProcessTypeAndIndex returns // back the SSH authentication information for the SSH session. func (actor Actor) GetSecureShellConfigurationByApplicationNameSpaceProcessTypeAndIndex( appName string, spaceGUID string, processType string, processIndex uint, ) (SSHAuthentication, Warnings, error)
{ endpoint := actor.CloudControllerClient.AppSSHEndpoint() if endpoint == "" { return SSHAuthentication{}, nil, actionerror.SSHEndpointNotSetError{} } fingerprint := actor.CloudControllerClient.AppSSHHostKeyFingerprint() if fingerprint == "" { return SSHAuthentication{}, nil, actionerror.SSHHostKeyFingerprintNotSetError{} } passcode, err := actor.UAAClient.GetSSHPasscode(actor.Config.AccessToken(), actor.Config.SSHOAuthClient()) if err != nil { return SSHAuthentication{}, Warnings{}, err } // TODO: don't use Summary object for this appSummary, warnings, err := actor.GetApplicationSummaryByNameAndSpace(appName, spaceGUID, false) if err != nil { return SSHAuthentication{}, warnings, err } var processSummary ProcessSummary for _, appProcessSummary := range appSummary.ProcessSummaries { if appProcessSummary.Type == processType { processSummary = appProcessSummary break } } if processSummary.GUID == "" { return SSHAuthentication{}, warnings, actionerror.ProcessNotFoundError{ProcessType: processType} } if !appSummary.Application.Started() { return SSHAuthentication{}, warnings, actionerror.ApplicationNotStartedError{Name: appName} } var processInstance ProcessInstance for _, instance := range processSummary.InstanceDetails { if uint(instance.Index) == processIndex { processInstance = instance break } } if processInstance == (ProcessInstance{}) { return SSHAuthentication{}, warnings, actionerror.ProcessInstanceNotFoundError{ProcessType: processType, InstanceIndex: processIndex} } if !processInstance.Running() { return SSHAuthentication{}, warnings, actionerror.ProcessInstanceNotRunningError{ProcessType: processType, InstanceIndex: processIndex} } return SSHAuthentication{ Endpoint: endpoint, HostKeyFingerprint: fingerprint, Passcode: passcode, Username: fmt.Sprintf("cf:%s/%d", processSummary.GUID, processIndex), }, warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
util/configv3/load_config.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/load_config.go#L55-L159
go
train
// LoadConfig loads the config from the .cf/config.json and os.ENV. If the // config.json does not exists, it will use a default config in it's place. // Takes in an optional FlagOverride, will only use the first one passed, that // can override the given flag values. // // The '.cf' directory will be read in one of the following locations on UNIX // Systems: // 1. $CF_HOME/.cf if $CF_HOME is set // 2. $HOME/.cf as the default // // The '.cf' directory will be read in one of the following locations on // Windows Systems: // 1. CF_HOME\.cf if CF_HOME is set // 2. HOMEDRIVE\HOMEPATH\.cf if HOMEDRIVE or HOMEPATH is set // 3. USERPROFILE\.cf as the default
func LoadConfig(flags ...FlagOverride) (*Config, error)
// LoadConfig loads the config from the .cf/config.json and os.ENV. If the // config.json does not exists, it will use a default config in it's place. // Takes in an optional FlagOverride, will only use the first one passed, that // can override the given flag values. // // The '.cf' directory will be read in one of the following locations on UNIX // Systems: // 1. $CF_HOME/.cf if $CF_HOME is set // 2. $HOME/.cf as the default // // The '.cf' directory will be read in one of the following locations on // Windows Systems: // 1. CF_HOME\.cf if CF_HOME is set // 2. HOMEDRIVE\HOMEPATH\.cf if HOMEDRIVE or HOMEPATH is set // 3. USERPROFILE\.cf as the default func LoadConfig(flags ...FlagOverride) (*Config, error)
{ err := removeOldTempConfigFiles() if err != nil { return nil, err } configFilePath := ConfigFilePath() config := Config{ ConfigFile: JSONConfig{ ConfigVersion: 3, Target: DefaultTarget, ColorEnabled: DefaultColorEnabled, PluginRepositories: []PluginRepository{{ Name: DefaultPluginRepoName, URL: DefaultPluginRepoURL, }}, }, } var jsonError error if _, err = os.Stat(configFilePath); err == nil || !os.IsNotExist(err) { var file []byte file, err = ioutil.ReadFile(configFilePath) if err != nil { return nil, err } if len(file) == 0 { // TODO: change this to not use translatableerror jsonError = translatableerror.EmptyConfigError{FilePath: configFilePath} } else { var configFile JSONConfig err = json.Unmarshal(file, &configFile) if err != nil { return nil, err } config.ConfigFile = configFile } } if config.ConfigFile.SSHOAuthClient == "" { config.ConfigFile.SSHOAuthClient = DefaultSSHOAuthClient } if config.ConfigFile.UAAOAuthClient == "" { config.ConfigFile.UAAOAuthClient = DefaultUAAOAuthClient config.ConfigFile.UAAOAuthClientSecret = DefaultUAAOAuthClientSecret } config.ENV = EnvOverride{ BinaryName: filepath.Base(os.Args[0]), CFColor: os.Getenv("CF_COLOR"), CFDialTimeout: os.Getenv("CF_DIAL_TIMEOUT"), CFLogLevel: os.Getenv("CF_LOG_LEVEL"), CFPassword: os.Getenv("CF_PASSWORD"), CFPluginHome: os.Getenv("CF_PLUGIN_HOME"), CFStagingTimeout: os.Getenv("CF_STAGING_TIMEOUT"), CFStartupTimeout: os.Getenv("CF_STARTUP_TIMEOUT"), CFTrace: os.Getenv("CF_TRACE"), CFUsername: os.Getenv("CF_USERNAME"), DockerPassword: os.Getenv("CF_DOCKER_PASSWORD"), Experimental: os.Getenv("CF_CLI_EXPERIMENTAL"), ExperimentalLogin: os.Getenv("CF_EXPERIMENTAL_LOGIN"), ForceTTY: os.Getenv("FORCE_TTY"), HTTPSProxy: os.Getenv("https_proxy"), Lang: os.Getenv("LANG"), LCAll: os.Getenv("LC_ALL"), } err = config.loadPluginConfig() if err != nil { return nil, err } if len(flags) > 0 { config.Flags = flags[0] } pwd, err := os.Getwd() if err != nil { return nil, err } // Developer Note: The following is untested! Change at your own risk. isTTY := terminal.IsTerminal(int(os.Stdout.Fd())) terminalWidth := math.MaxInt32 if isTTY { var err error terminalWidth, _, err = terminal.GetSize(int(os.Stdout.Fd())) if err != nil { return nil, err } } config.detectedSettings = detectedSettings{ currentDirectory: pwd, terminalWidth: terminalWidth, tty: isTTY, } return &config, jsonError }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv3/organization.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv3/organization.go#L25-L48
go
train
// GetIsolationSegmentOrganizations lists organizations // entitled to an isolation segment.
func (client *Client) GetIsolationSegmentOrganizations(isolationSegmentGUID string) ([]Organization, Warnings, error)
// GetIsolationSegmentOrganizations lists organizations // entitled to an isolation segment. func (client *Client) GetIsolationSegmentOrganizations(isolationSegmentGUID string) ([]Organization, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetIsolationSegmentOrganizationsRequest, URIParams: map[string]string{"isolation_segment_guid": isolationSegmentGUID}, }) if err != nil { return nil, nil, err } var fullOrgsList []Organization warnings, err := client.paginate(request, Organization{}, func(item interface{}) error { if app, ok := item.(Organization); ok { fullOrgsList = append(fullOrgsList, app) } else { return ccerror.UnknownObjectInListError{ Expected: Organization{}, Unexpected: item, } } return nil }) return fullOrgsList, warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv3/organization.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv3/organization.go#L51-L74
go
train
// GetOrganizations lists organizations with optional filters.
func (client *Client) GetOrganizations(query ...Query) ([]Organization, Warnings, error)
// GetOrganizations lists organizations with optional filters. func (client *Client) GetOrganizations(query ...Query) ([]Organization, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetOrganizationsRequest, Query: query, }) if err != nil { return nil, nil, err } var fullOrgsList []Organization warnings, err := client.paginate(request, Organization{}, func(item interface{}) error { if app, ok := item.(Organization); ok { fullOrgsList = append(fullOrgsList, app) } else { return ccerror.UnknownObjectInListError{ Expected: Organization{}, Unexpected: item, } } return nil }) return fullOrgsList, warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv3/droplet.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv3/droplet.go#L38-L53
go
train
// GetApplicationDropletCurrent returns the current droplet for a given // application.
func (client *Client) GetApplicationDropletCurrent(appGUID string) (Droplet, Warnings, error)
// GetApplicationDropletCurrent returns the current droplet for a given // application. func (client *Client) GetApplicationDropletCurrent(appGUID string) (Droplet, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetApplicationDropletCurrentRequest, URIParams: map[string]string{"app_guid": appGUID}, }) if err != nil { return Droplet{}, nil, err } var responseDroplet Droplet response := cloudcontroller.Response{ DecodeJSONResponseInto: &responseDroplet, } err = client.connection.Make(request, &response) return responseDroplet, response.Warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv3/droplet.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv3/droplet.go#L56-L72
go
train
// GetDroplet returns a droplet with the given GUID.
func (client *Client) GetDroplet(dropletGUID string) (Droplet, Warnings, error)
// GetDroplet returns a droplet with the given GUID. func (client *Client) GetDroplet(dropletGUID string) (Droplet, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetDropletRequest, URIParams: map[string]string{"droplet_guid": dropletGUID}, }) if err != nil { return Droplet{}, nil, err } var responseDroplet Droplet response := cloudcontroller.Response{ DecodeJSONResponseInto: &responseDroplet, } err = client.connection.Make(request, &response) return responseDroplet, response.Warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv3/droplet.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv3/droplet.go#L75-L98
go
train
// GetDroplets lists droplets with optional filters.
func (client *Client) GetDroplets(query ...Query) ([]Droplet, Warnings, error)
// GetDroplets lists droplets with optional filters. func (client *Client) GetDroplets(query ...Query) ([]Droplet, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetDropletsRequest, Query: query, }) if err != nil { return nil, nil, err } var responseDroplets []Droplet warnings, err := client.paginate(request, Droplet{}, func(item interface{}) error { if droplet, ok := item.(Droplet); ok { responseDroplets = append(responseDroplets, droplet) } else { return ccerror.UnknownObjectInListError{ Expected: Droplet{}, Unexpected: item, } } return nil }) return responseDroplets, warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/cfnetworkingaction/actor.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/cfnetworkingaction/actor.go#L14-L19
go
train
// NewActor returns a new actor.
func NewActor(networkingClient NetworkingClient, v3Actor V3Actor) *Actor
// NewActor returns a new actor. func NewActor(networkingClient NetworkingClient, v3Actor V3Actor) *Actor
{ return &Actor{ NetworkingClient: networkingClient, V3Actor: v3Actor, } }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
types/null_int.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/types/null_int.go#L17-L31
go
train
// ParseStringValue is used to parse a user provided flag argument.
func (n *NullInt) ParseStringValue(val string) error
// ParseStringValue is used to parse a user provided flag argument. func (n *NullInt) ParseStringValue(val string) error
{ if val == "" { return nil } intVal, err := strconv.Atoi(val) if err != nil { return err } n.Value = intVal n.IsSet = true return nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
types/null_int.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/types/null_int.go#L34-L37
go
train
// IsValidValue returns an error if the input value is not an integer.
func (n *NullInt) IsValidValue(val string) error
// IsValidValue returns an error if the input value is not an integer. func (n *NullInt) IsValidValue(val string) error
{ _, err := strconv.Atoi(val) return err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
types/null_int.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/types/null_int.go#L40-L49
go
train
// ParseIntValue is used to parse a user provided *int argument.
func (n *NullInt) ParseIntValue(val *int)
// ParseIntValue is used to parse a user provided *int argument. func (n *NullInt) ParseIntValue(val *int)
{ if val == nil { n.IsSet = false n.Value = 0 return } n.Value = *val n.IsSet = true }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv3/service_instance.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv3/service_instance.go#L17-L40
go
train
// GetServiceInstances lists service instances with optional filters.
func (client *Client) GetServiceInstances(query ...Query) ([]ServiceInstance, Warnings, error)
// GetServiceInstances lists service instances with optional filters. func (client *Client) GetServiceInstances(query ...Query) ([]ServiceInstance, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetServiceInstancesRequest, Query: query, }) if err != nil { return nil, nil, err } var fullServiceInstanceList []ServiceInstance warnings, err := client.paginate(request, ServiceInstance{}, func(item interface{}) error { if serviceInstance, ok := item.(ServiceInstance); ok { fullServiceInstanceList = append(fullServiceInstanceList, serviceInstance) } else { return ccerror.UnknownObjectInListError{ Expected: ServiceInstance{}, Unexpected: item, } } return nil }) return fullServiceInstanceList, warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/route_mapping.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/route_mapping.go#L22-L40
go
train
// UnmarshalJSON helps unmarshal a Cloud Controller Route Mapping
func (routeMapping *RouteMapping) UnmarshalJSON(data []byte) error
// UnmarshalJSON helps unmarshal a Cloud Controller Route Mapping func (routeMapping *RouteMapping) UnmarshalJSON(data []byte) error
{ var ccRouteMapping struct { Metadata internal.Metadata `json:"metadata"` Entity struct { AppGUID string `json:"app_guid"` RouteGUID string `json:"route_guid"` } `json:"entity"` } err := cloudcontroller.DecodeJSON(data, &ccRouteMapping) if err != nil { return err } routeMapping.GUID = ccRouteMapping.Metadata.GUID routeMapping.AppGUID = ccRouteMapping.Entity.AppGUID routeMapping.RouteGUID = ccRouteMapping.Entity.RouteGUID return nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/route_mapping.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/route_mapping.go#L43-L59
go
train
// GetRouteMapping returns a route mapping with the provided guid.
func (client *Client) GetRouteMapping(guid string) (RouteMapping, Warnings, error)
// GetRouteMapping returns a route mapping with the provided guid. func (client *Client) GetRouteMapping(guid string) (RouteMapping, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetRouteMappingRequest, URIParams: Params{"route_mapping_guid": guid}, }) if err != nil { return RouteMapping{}, nil, err } var routeMapping RouteMapping response := cloudcontroller.Response{ DecodeJSONResponseInto: &routeMapping, } err = client.connection.Make(request, &response) return routeMapping, response.Warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/route_mapping.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/route_mapping.go#L62-L85
go
train
// GetRouteMappings returns a list of RouteMappings based off of the provided queries.
func (client *Client) GetRouteMappings(filters ...Filter) ([]RouteMapping, Warnings, error)
// GetRouteMappings returns a list of RouteMappings based off of the provided queries. func (client *Client) GetRouteMappings(filters ...Filter) ([]RouteMapping, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetRouteMappingsRequest, Query: ConvertFilterParameters(filters), }) if err != nil { return nil, nil, err } var fullRouteMappingsList []RouteMapping warnings, err := client.paginate(request, RouteMapping{}, func(item interface{}) error { if routeMapping, ok := item.(RouteMapping); ok { fullRouteMappingsList = append(fullRouteMappingsList, routeMapping) } else { return ccerror.UnknownObjectInListError{ Expected: RouteMapping{}, Unexpected: item, } } return nil }) return fullRouteMappingsList, warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
command/v7/target_command.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/command/v7/target_command.go#L121-L133
go
train
// setOrgAndSpace sets organization and space
func (cmd *TargetCommand) setOrgAndSpace() error
// setOrgAndSpace sets organization and space func (cmd *TargetCommand) setOrgAndSpace() error
{ err := cmd.setOrg() if err != nil { return err } err = cmd.setSpace() if err != nil { return err } return nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v2action/target.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/target.go#L21-L43
go
train
// SetTarget targets the Cloud Controller using the client and sets target // information in the actor based on the response.
func (actor Actor) SetTarget(settings TargetSettings) (Warnings, error)
// SetTarget targets the Cloud Controller using the client and sets target // information in the actor based on the response. func (actor Actor) SetTarget(settings TargetSettings) (Warnings, error)
{ if actor.Config.Target() == settings.URL && actor.Config.SkipSSLValidation() == settings.SkipSSLValidation { return nil, nil } warnings, err := actor.CloudControllerClient.TargetCF(ccv2.TargetSettings(settings)) if err != nil { return Warnings(warnings), err } actor.Config.SetTargetInformation( actor.CloudControllerClient.API(), actor.CloudControllerClient.APIVersion(), actor.CloudControllerClient.AuthorizationEndpoint(), actor.CloudControllerClient.MinCLIVersion(), actor.CloudControllerClient.DopplerEndpoint(), actor.CloudControllerClient.RoutingEndpoint(), settings.SkipSSLValidation, ) actor.Config.SetTokenInformation("", "", "") return Warnings(warnings), nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/uaa/refresh_token.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/uaa/refresh_token.go#L21-L23
go
train
// AuthorizationToken returns formatted authorization header.
func (refreshTokenResponse RefreshedTokens) AuthorizationToken() string
// AuthorizationToken returns formatted authorization header. func (refreshTokenResponse RefreshedTokens) AuthorizationToken() string
{ return fmt.Sprintf("%s %s", refreshTokenResponse.Type, refreshTokenResponse.AccessToken) }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/uaa/refresh_token.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/uaa/refresh_token.go#L26-L62
go
train
// RefreshAccessToken refreshes the current access token.
func (client *Client) RefreshAccessToken(refreshToken string) (RefreshedTokens, error)
// RefreshAccessToken refreshes the current access token. func (client *Client) RefreshAccessToken(refreshToken string) (RefreshedTokens, error)
{ var values url.Values switch client.config.UAAGrantType() { case string(constant.GrantTypeClientCredentials): values = client.clientCredentialRefreshBody() case "", string(constant.GrantTypePassword): // CLI used to write empty string for grant type in the case of password; preserve compatibility with old config.json files values = client.refreshTokenBody(refreshToken) } body := strings.NewReader(values.Encode()) request, err := client.newRequest(requestOptions{ RequestName: internal.PostOAuthTokenRequest, Header: http.Header{"Content-Type": {"application/x-www-form-urlencoded"}}, Body: body, }) if err != nil { return RefreshedTokens{}, err } if client.config.UAAGrantType() != string(constant.GrantTypeClientCredentials) { request.SetBasicAuth(client.config.UAAOAuthClient(), client.config.UAAOAuthClientSecret()) } var refreshResponse RefreshedTokens response := Response{ Result: &refreshResponse, } err = client.connection.Make(request, &response) if err != nil { return RefreshedTokens{}, err } return refreshResponse, nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
util/ui/table.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/ui/table.go#L20-L40
go
train
// DisplayKeyValueTable outputs a matrix of strings as a table to UI.Out. // Prefix will be prepended to each row and padding adds the specified number // of spaces between columns. The final columns may wrap to multiple lines but // will still be confined to the last column. Wrapping will occur on word // boundaries.
func (ui *UI) DisplayKeyValueTable(prefix string, table [][]string, padding int)
// DisplayKeyValueTable outputs a matrix of strings as a table to UI.Out. // Prefix will be prepended to each row and padding adds the specified number // of spaces between columns. The final columns may wrap to multiple lines but // will still be confined to the last column. Wrapping will occur on word // boundaries. func (ui *UI) DisplayKeyValueTable(prefix string, table [][]string, padding int)
{ rows := len(table) if rows == 0 { return } var displayTable [][]string for _, row := range table { if len(row) > 0 { displayTable = append(displayTable, row) } } columns := len(displayTable[0]) if columns < 2 || !ui.IsTTY { ui.DisplayNonWrappingTable(prefix, displayTable, padding) return } ui.displayWrappingTableWithWidth(prefix, displayTable, padding) }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
util/ui/table.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/ui/table.go#L45-L79
go
train
// DisplayNonWrappingTable outputs a matrix of strings as a table to UI.Out. // Prefix will be prepended to each row and padding adds the specified number // of spaces between columns.
func (ui *UI) DisplayNonWrappingTable(prefix string, table [][]string, padding int)
// DisplayNonWrappingTable outputs a matrix of strings as a table to UI.Out. // Prefix will be prepended to each row and padding adds the specified number // of spaces between columns. func (ui *UI) DisplayNonWrappingTable(prefix string, table [][]string, padding int)
{ ui.terminalLock.Lock() defer ui.terminalLock.Unlock() if len(table) == 0 { return } var columnPadding []int rows := len(table) columns := len(table[0]) for col := 0; col < columns; col++ { var max int for row := 0; row < rows; row++ { if strLen := wordSize(table[row][col]); max < strLen { max = strLen } } columnPadding = append(columnPadding, max+padding) } for row := 0; row < rows; row++ { fmt.Fprint(ui.Out, prefix) for col := 0; col < columns; col++ { data := table[row][col] var addedPadding int if col+1 != columns { addedPadding = columnPadding[col] - wordSize(data) } fmt.Fprintf(ui.Out, "%s%s", data, strings.Repeat(" ", addedPadding)) } fmt.Fprintf(ui.Out, "\n") } }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
util/ui/table.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/ui/table.go#L83-L92
go
train
// DisplayTableWithHeader outputs a simple non-wrapping table with bolded // headers.
func (ui *UI) DisplayTableWithHeader(prefix string, table [][]string, padding int)
// DisplayTableWithHeader outputs a simple non-wrapping table with bolded // headers. func (ui *UI) DisplayTableWithHeader(prefix string, table [][]string, padding int)
{ if len(table) == 0 { return } for i, str := range table[0] { table[0][i] = ui.modifyColor(str, color.New(color.Bold)) } ui.DisplayNonWrappingTable(prefix, table, padding) }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/application_instance.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/application_instance.go#L29-L45
go
train
// UnmarshalJSON helps unmarshal a Cloud Controller application instance // response.
func (instance *ApplicationInstance) UnmarshalJSON(data []byte) error
// UnmarshalJSON helps unmarshal a Cloud Controller application instance // response. func (instance *ApplicationInstance) UnmarshalJSON(data []byte) error
{ var ccInstance struct { Details string `json:"details"` Since float64 `json:"since"` State string `json:"state"` } err := cloudcontroller.DecodeJSON(data, &ccInstance) if err != nil { return err } instance.Details = ccInstance.Details instance.State = constant.ApplicationInstanceState(ccInstance.State) instance.Since = ccInstance.Since return nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/application_instance.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/application_instance.go#L50-L80
go
train
// GetApplicationApplicationInstances returns a list of ApplicationInstance for // a given application. Depending on the state of an application, it might skip // some application instances.
func (client *Client) GetApplicationApplicationInstances(guid string) (map[int]ApplicationInstance, Warnings, error)
// GetApplicationApplicationInstances returns a list of ApplicationInstance for // a given application. Depending on the state of an application, it might skip // some application instances. func (client *Client) GetApplicationApplicationInstances(guid string) (map[int]ApplicationInstance, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetAppInstancesRequest, URIParams: Params{"app_guid": guid}, }) if err != nil { return nil, nil, err } var instances map[string]ApplicationInstance response := cloudcontroller.Response{ DecodeJSONResponseInto: &instances, } err = client.connection.Make(request, &response) if err != nil { return nil, response.Warnings, err } returnedInstances := map[int]ApplicationInstance{} for instanceID, instance := range instances { id, convertErr := strconv.Atoi(instanceID) if convertErr != nil { return nil, response.Warnings, convertErr } instance.ID = id returnedInstances[id] = instance } return returnedInstances, response.Warnings, nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/errors.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/errors.go#L23-L34
go
train
// Make converts RawHTTPStatusError, which represents responses with 4xx and // 5xx status codes, to specific errors.
func (e *errorWrapper) Make(request *cloudcontroller.Request, passedResponse *cloudcontroller.Response) error
// Make converts RawHTTPStatusError, which represents responses with 4xx and // 5xx status codes, to specific errors. func (e *errorWrapper) Make(request *cloudcontroller.Request, passedResponse *cloudcontroller.Response) error
{ err := e.connection.Make(request, passedResponse) if rawHTTPStatusErr, ok := err.(ccerror.RawHTTPStatusError); ok { if passedResponse.HTTPResponse.StatusCode >= http.StatusInternalServerError { return convert500(rawHTTPStatusErr) } return convert400(rawHTTPStatusErr) } return err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/service_plan_visibility.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/service_plan_visibility.go#L24-L41
go
train
// UnmarshalJSON helps unmarshal a Cloud Controller Service Plan Visibilities // response.
func (servicePlanVisibility *ServicePlanVisibility) UnmarshalJSON(data []byte) error
// UnmarshalJSON helps unmarshal a Cloud Controller Service Plan Visibilities // response. func (servicePlanVisibility *ServicePlanVisibility) UnmarshalJSON(data []byte) error
{ var ccServicePlanVisibility struct { Metadata internal.Metadata Entity struct { ServicePlanGUID string `json:"service_plan_guid"` OrganizationGUID string `json:"organization_guid"` } `json:"entity"` } err := cloudcontroller.DecodeJSON(data, &ccServicePlanVisibility) if err != nil { return err } servicePlanVisibility.GUID = ccServicePlanVisibility.Metadata.GUID servicePlanVisibility.ServicePlanGUID = ccServicePlanVisibility.Entity.ServicePlanGUID servicePlanVisibility.OrganizationGUID = ccServicePlanVisibility.Entity.OrganizationGUID return nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/service_plan_visibility.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/service_plan_visibility.go#L93-L117
go
train
// GetServicePlanVisibilities returns back a list of Service Plan Visibilities // given the provided filters.
func (client *Client) GetServicePlanVisibilities(filters ...Filter) ([]ServicePlanVisibility, Warnings, error)
// GetServicePlanVisibilities returns back a list of Service Plan Visibilities // given the provided filters. func (client *Client) GetServicePlanVisibilities(filters ...Filter) ([]ServicePlanVisibility, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetServicePlanVisibilitiesRequest, Query: ConvertFilterParameters(filters), }) if err != nil { return nil, nil, err } var fullVisibilityList []ServicePlanVisibility warnings, err := client.paginate(request, ServicePlanVisibility{}, func(item interface{}) error { if vis, ok := item.(ServicePlanVisibility); ok { fullVisibilityList = append(fullVisibilityList, vis) } else { return ccerror.UnknownObjectInListError{ Expected: ServicePlanVisibility{}, Unexpected: item, } } return nil }) return fullVisibilityList, warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
cf/api/logs/noaa_logs_repository.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/cf/api/logs/noaa_logs_repository.go#L131-L135
go
train
// newUnstartedTimer returns a *time.Timer that is in an unstarted // state.
func newUnstartedTimer() *time.Timer
// newUnstartedTimer returns a *time.Timer that is in an unstarted // state. func newUnstartedTimer() *time.Timer
{ timer := time.NewTimer(time.Second) timer.Stop() return timer }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/uaa/request.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/uaa/request.go#L36-L71
go
train
// newRequest returns a constructed http.Request with some defaults. The // request will terminate the connection after it is sent (via a 'Connection: // close' header).
func (client *Client) newRequest(passedRequest requestOptions) (*http.Request, error)
// newRequest returns a constructed http.Request with some defaults. The // request will terminate the connection after it is sent (via a 'Connection: // close' header). func (client *Client) newRequest(passedRequest requestOptions) (*http.Request, error)
{ var request *http.Request var err error if passedRequest.URL != "" { request, err = http.NewRequest( passedRequest.Method, passedRequest.URL, passedRequest.Body, ) } else { request, err = client.router.CreateRequest( passedRequest.RequestName, passedRequest.URIParams, passedRequest.Body, ) } if err != nil { return nil, err } if passedRequest.Query != nil { request.URL.RawQuery = passedRequest.Query.Encode() } if passedRequest.Header != nil { request.Header = passedRequest.Header } else { request.Header = http.Header{} } request.Header.Set("Accept", "application/json") request.Header.Set("Connection", "close") request.Header.Set("User-Agent", client.userAgent) return request, nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/uaa/wrapper/request_logger.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/uaa/wrapper/request_logger.go#L44-L60
go
train
// Make records the request and the response to UI
func (logger *RequestLogger) Make(request *http.Request, passedResponse *uaa.Response) error
// Make records the request and the response to UI func (logger *RequestLogger) Make(request *http.Request, passedResponse *uaa.Response) error
{ err := logger.displayRequest(request) if err != nil { logger.output.HandleInternalError(err) } err = logger.connection.Make(request, passedResponse) if passedResponse.HTTPResponse != nil { displayErr := logger.displayResponse(passedResponse) if displayErr != nil { logger.output.HandleInternalError(displayErr) } } return err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/uaa/wrapper/request_logger.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/uaa/wrapper/request_logger.go#L63-L66
go
train
// Wrap sets the connection on the RequestLogger and returns itself
func (logger *RequestLogger) Wrap(innerconnection uaa.Connection) uaa.Connection
// Wrap sets the connection on the RequestLogger and returns itself func (logger *RequestLogger) Wrap(innerconnection uaa.Connection) uaa.Connection
{ logger.connection = innerconnection return logger }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v3action/application_manifest.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v3action/application_manifest.go#L17-L50
go
train
// ApplyApplicationManifest reads in the manifest from the path and provides it // to the cloud controller.
func (actor Actor) ApplyApplicationManifest(parser ManifestParser, spaceGUID string) (Warnings, error)
// ApplyApplicationManifest reads in the manifest from the path and provides it // to the cloud controller. func (actor Actor) ApplyApplicationManifest(parser ManifestParser, spaceGUID string) (Warnings, error)
{ var allWarnings Warnings for _, appName := range parser.AppNames() { rawManifest, err := parser.RawAppManifest(appName) if err != nil { return allWarnings, err } app, getAppWarnings, err := actor.GetApplicationByNameAndSpace(appName, spaceGUID) allWarnings = append(allWarnings, getAppWarnings...) if err != nil { return allWarnings, err } jobURL, applyManifestWarnings, err := actor.CloudControllerClient.UpdateApplicationApplyManifest(app.GUID, rawManifest) allWarnings = append(allWarnings, applyManifestWarnings...) if err != nil { return allWarnings, err } pollWarnings, err := actor.CloudControllerClient.PollJob(jobURL) allWarnings = append(allWarnings, pollWarnings...) if err != nil { if newErr, ok := err.(ccerror.V3JobFailedError); ok { return allWarnings, actionerror.ApplicationManifestError{Message: newErr.Detail} } return allWarnings, err } } return allWarnings, nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/space_quota.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/space_quota.go#L21-L36
go
train
// UnmarshalJSON helps unmarshal a Cloud Controller Space Quota response.
func (spaceQuota *SpaceQuota) UnmarshalJSON(data []byte) error
// UnmarshalJSON helps unmarshal a Cloud Controller Space Quota response. func (spaceQuota *SpaceQuota) UnmarshalJSON(data []byte) error
{ var ccSpaceQuota struct { Metadata internal.Metadata `json:"metadata"` Entity struct { Name string `json:"name"` } `json:"entity"` } err := cloudcontroller.DecodeJSON(data, &ccSpaceQuota) if err != nil { return err } spaceQuota.GUID = ccSpaceQuota.Metadata.GUID spaceQuota.Name = ccSpaceQuota.Entity.Name return nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/space_quota.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/space_quota.go#L39-L55
go
train
// GetSpaceQuotaDefinition returns a Space Quota.
func (client *Client) GetSpaceQuotaDefinition(guid string) (SpaceQuota, Warnings, error)
// GetSpaceQuotaDefinition returns a Space Quota. func (client *Client) GetSpaceQuotaDefinition(guid string) (SpaceQuota, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetSpaceQuotaDefinitionRequest, URIParams: Params{"space_quota_guid": guid}, }) if err != nil { return SpaceQuota{}, nil, err } var spaceQuota SpaceQuota response := cloudcontroller.Response{ DecodeJSONResponseInto: &spaceQuota, } err = client.connection.Make(request, &response) return spaceQuota, response.Warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/space_quota.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/space_quota.go#L58-L82
go
train
// GetSpaceQuotas returns all the space quotas for the org
func (client *Client) GetSpaceQuotas(orgGUID string) ([]SpaceQuota, Warnings, error)
// GetSpaceQuotas returns all the space quotas for the org func (client *Client) GetSpaceQuotas(orgGUID string) ([]SpaceQuota, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetOrganizationSpaceQuotasRequest, URIParams: Params{"organization_guid": orgGUID}, }) if err != nil { return nil, nil, err } var spaceQuotas []SpaceQuota warnings, err := client.paginate(request, SpaceQuota{}, func(item interface{}) error { if spaceQuota, ok := item.(SpaceQuota); ok { spaceQuotas = append(spaceQuotas, spaceQuota) } else { return ccerror.UnknownObjectInListError{ Expected: SpaceQuota{}, Unexpected: item, } } return nil }) return spaceQuotas, warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/space_quota.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/space_quota.go#L85-L99
go
train
// SetSpaceQuota should set the quota for the space and returns the warnings
func (client *Client) SetSpaceQuota(spaceGUID string, quotaGUID string) (Warnings, error)
// SetSpaceQuota should set the quota for the space and returns the warnings func (client *Client) SetSpaceQuota(spaceGUID string, quotaGUID string) (Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.PutSpaceQuotaRequest, URIParams: Params{"space_quota_guid": quotaGUID, "space_guid": spaceGUID}, }) if err != nil { return nil, err } response := cloudcontroller.Response{} err = client.connection.Make(request, &response) return response.Warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
util/configv3/config.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/config.go#L37-L46
go
train
// IsTTY returns true based off of: // - The $FORCE_TTY is set to true/t/1 // - Detected from the STDOUT stream
func (config *Config) IsTTY() bool
// IsTTY returns true based off of: // - The $FORCE_TTY is set to true/t/1 // - Detected from the STDOUT stream func (config *Config) IsTTY() bool
{ if config.ENV.ForceTTY != "" { envVal, err := strconv.ParseBool(config.ENV.ForceTTY) if err == nil { return envVal } } return config.detectedSettings.tty }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
util/configv3/config.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/config.go#L62-L99
go
train
// Verbose returns true if verbose should be displayed to terminal, in addition // a slice of absolute paths in which verbose text will appear. This is based // off of: // - The config file's trace value (true/false/file path) // - The $CF_TRACE environment variable if set (true/false/file path) // - The '-v/--verbose' global flag // - Defaults to false
func (config *Config) Verbose() (bool, []string)
// Verbose returns true if verbose should be displayed to terminal, in addition // a slice of absolute paths in which verbose text will appear. This is based // off of: // - The config file's trace value (true/false/file path) // - The $CF_TRACE environment variable if set (true/false/file path) // - The '-v/--verbose' global flag // - Defaults to false func (config *Config) Verbose() (bool, []string)
{ var ( verbose bool envOverride bool filePath []string ) if config.ENV.CFTrace != "" { envVal, err := strconv.ParseBool(config.ENV.CFTrace) verbose = envVal if err != nil { filePath = []string{config.ENV.CFTrace} } else { envOverride = true } } if config.ConfigFile.Trace != "" { envVal, err := strconv.ParseBool(config.ConfigFile.Trace) if !envOverride { verbose = envVal || verbose } if err != nil { filePath = append(filePath, config.ConfigFile.Trace) } } verbose = config.Flags.Verbose || verbose for i, path := range filePath { if !filepath.IsAbs(path) { filePath[i] = filepath.Join(config.detectedSettings.currentDirectory, path) } resolvedPath, err := filepath.EvalSymlinks(filePath[i]) if err == nil { filePath[i] = resolvedPath } } return verbose, filePath }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v2action/organization.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/organization.go#L15-L23
go
train
// GetOrganization returns an Organization based on the provided guid.
func (actor Actor) GetOrganization(guid string) (Organization, Warnings, error)
// GetOrganization returns an Organization based on the provided guid. func (actor Actor) GetOrganization(guid string) (Organization, Warnings, error)
{ org, warnings, err := actor.CloudControllerClient.GetOrganization(guid) if _, ok := err.(ccerror.ResourceNotFoundError); ok { return Organization{}, Warnings(warnings), actionerror.OrganizationNotFoundError{GUID: guid} } return Organization(org), Warnings(warnings), err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v2action/organization.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/organization.go#L26-L49
go
train
// GetOrganizationByName returns an Organization based off of the name given.
func (actor Actor) GetOrganizationByName(orgName string) (Organization, Warnings, error)
// GetOrganizationByName returns an Organization based off of the name given. func (actor Actor) GetOrganizationByName(orgName string) (Organization, Warnings, error)
{ orgs, warnings, err := actor.CloudControllerClient.GetOrganizations(ccv2.Filter{ Type: constant.NameFilter, Operator: constant.EqualOperator, Values: []string{orgName}, }) if err != nil { return Organization{}, Warnings(warnings), err } if len(orgs) == 0 { return Organization{}, Warnings(warnings), actionerror.OrganizationNotFoundError{Name: orgName} } if len(orgs) > 1 { var guids []string for _, org := range orgs { guids = append(guids, org.GUID) } return Organization{}, Warnings(warnings), actionerror.MultipleOrganizationsFoundError{Name: orgName, GUIDs: guids} } return Organization(orgs[0]), Warnings(warnings), nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v2action/organization.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/organization.go#L52-L63
go
train
// GrantOrgManagerByUsername gives the Org Manager role to the provided user.
func (actor Actor) GrantOrgManagerByUsername(guid string, username string) (Warnings, error)
// GrantOrgManagerByUsername gives the Org Manager role to the provided user. func (actor Actor) GrantOrgManagerByUsername(guid string, username string) (Warnings, error)
{ var warnings ccv2.Warnings var err error if actor.Config.UAAGrantType() != string(uaaconst.GrantTypeClientCredentials) { warnings, err = actor.CloudControllerClient.UpdateOrganizationManagerByUsername(guid, username) } else { warnings, err = actor.CloudControllerClient.UpdateOrganizationManager(guid, username) } return Warnings(warnings), err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v2action/organization.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/organization.go#L66-L91
go
train
// CreateOrganization creates an Organization based on the provided orgName.
func (actor Actor) CreateOrganization(orgName string, quotaName string) (Organization, Warnings, error)
// CreateOrganization creates an Organization based on the provided orgName. func (actor Actor) CreateOrganization(orgName string, quotaName string) (Organization, Warnings, error)
{ var quotaGUID string var allWarnings Warnings if quotaName != "" { quota, warnings, err := actor.GetOrganizationQuotaByName(quotaName) allWarnings = append(allWarnings, warnings...) if err != nil { return Organization{}, allWarnings, err } quotaGUID = quota.GUID } org, warnings, err := actor.CloudControllerClient.CreateOrganization(orgName, quotaGUID) allWarnings = append(allWarnings, warnings...) if _, ok := err.(ccerror.OrganizationNameTakenError); ok { return Organization{}, allWarnings, actionerror.OrganizationNameTakenError{Name: orgName} } if err != nil { return Organization{}, allWarnings, err } return Organization(org), allWarnings, nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v2action/organization.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/organization.go#L96-L117
go
train
// DeleteOrganization deletes the Organization associated with the provided // GUID. Once the deletion request is sent, it polls the deletion job until // it's finished.
func (actor Actor) DeleteOrganization(orgName string) (Warnings, error)
// DeleteOrganization deletes the Organization associated with the provided // GUID. Once the deletion request is sent, it polls the deletion job until // it's finished. func (actor Actor) DeleteOrganization(orgName string) (Warnings, error)
{ var allWarnings Warnings org, warnings, err := actor.GetOrganizationByName(orgName) allWarnings = append(allWarnings, warnings...) if err != nil { return allWarnings, err } job, deleteWarnings, err := actor.CloudControllerClient.DeleteOrganizationJob(org.GUID) allWarnings = append(allWarnings, deleteWarnings...) if err != nil { return allWarnings, err } ccWarnings, err := actor.CloudControllerClient.PollJob(job) for _, warning := range ccWarnings { allWarnings = append(allWarnings, warning) } return allWarnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v2action/organization.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/organization.go#L120-L127
go
train
// GetOrganizations returns all the available organizations.
func (actor Actor) GetOrganizations() ([]Organization, Warnings, error)
// GetOrganizations returns all the available organizations. func (actor Actor) GetOrganizations() ([]Organization, Warnings, error)
{ var returnedOrgs []Organization orgs, warnings, err := actor.CloudControllerClient.GetOrganizations() for _, org := range orgs { returnedOrgs = append(returnedOrgs, Organization(org)) } return returnedOrgs, Warnings(warnings), err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v2action/organization.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2action/organization.go#L131-L146
go
train
// OrganizationExistsWithName returns true if there is an Organization with the // provided name, otherwise false.
func (actor Actor) OrganizationExistsWithName(orgName string) (bool, Warnings, error)
// OrganizationExistsWithName returns true if there is an Organization with the // provided name, otherwise false. func (actor Actor) OrganizationExistsWithName(orgName string) (bool, Warnings, error)
{ orgs, warnings, err := actor.CloudControllerClient.GetOrganizations(ccv2.Filter{ Type: constant.NameFilter, Operator: constant.EqualOperator, Values: []string{orgName}, }) if err != nil { return false, Warnings(warnings), err } if len(orgs) == 0 { return false, Warnings(warnings), nil } return true, Warnings(warnings), nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/client/ncc_client.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/client/ncc_client.go#L159-L176
go
train
// call performs an RPC call to the Seesaw v2 nccClient.
func (nc *nccClient) call(name string, in interface{}, out interface{}) error
// call performs an RPC call to the Seesaw v2 nccClient. func (nc *nccClient) call(name string, in interface{}, out interface{}) error
{ nc.lock.RLock() client := nc.client nc.lock.RUnlock() if client == nil { return fmt.Errorf("Not connected") } ch := make(chan error, 1) go func() { ch <- client.Call(name, in, out) }() select { case err := <-ch: return err case <-time.After(nccRPCTimeout): return fmt.Errorf("RPC call timed out after %v", nccRPCTimeout) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/client/ncc_client.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/client/ncc_client.go#L243-L245
go
train
// TODO(ncope): Use seesaw.VIP here for consistency
func (nc *nccClient) BGPAdvertiseVIP(vip net.IP) error
// TODO(ncope): Use seesaw.VIP here for consistency func (nc *nccClient) BGPAdvertiseVIP(vip net.IP) error
{ return nc.call("SeesawNCC.BGPAdvertiseVIP", vip, nil) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L67-L72
go
train
// String returns the string representation for the given healthcheck state.
func (s State) String() string
// String returns the string representation for the given healthcheck state. func (s State) String() string
{ if name, ok := stateNames[s]; ok { return name } return "<unknown>" }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L91-L97
go
train
// String returns the string representation of a healthcheck target.
func (t Target) String() string
// String returns the string representation of a healthcheck target. func (t Target) String() string
{ var via string if t.Mode == seesaw.HCModeDSR { via = fmt.Sprintf(" (via %s mark %d)", t.Host, t.Mark) } return fmt.Sprintf("%s %s%s", t.addr(), t.Mode, via) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L100-L105
go
train
// addr returns the address string for the healthcheck target.
func (t *Target) addr() string
// addr returns the address string for the healthcheck target. func (t *Target) addr() string
{ if t.IP.To4() != nil { return fmt.Sprintf("%v:%d", t.IP, t.Port) } return fmt.Sprintf("[%v]:%d", t.IP, t.Port) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L108-L129
go
train
// network returns the network name for the healthcheck target.
func (t *Target) network() string
// network returns the network name for the healthcheck target. func (t *Target) network() string
{ version := 4 if t.IP.To4() == nil { version = 6 } var network string switch t.Proto { case seesaw.IPProtoICMP: network = "ip4:icmp" case seesaw.IPProtoICMPv6: network = "ip6:ipv6-icmp" case seesaw.IPProtoTCP: network = fmt.Sprintf("tcp%d", version) case seesaw.IPProtoUDP: network = fmt.Sprintf("udp%d", version) default: return "(unknown)" } return network }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L140-L145
go
train
// String returns the string representation of a healthcheck result.
func (r *Result) String() string
// String returns the string representation of a healthcheck result. func (r *Result) String() string
{ if r.Err != nil { return r.Err.Error() } return r.Message }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L148-L152
go
train
// complete returns a Result for a completed healthcheck.
func complete(start time.Time, msg string, success bool, err error) *Result
// complete returns a Result for a completed healthcheck. func complete(start time.Time, msg string, success bool, err error) *Result
{ // TODO(jsing): Make this clock skew safe. duration := time.Since(start) return &Result{msg, success, duration, err} }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L161-L163
go
train
// String returns the string representation for the given notification.
func (n *Notification) String() string
// String returns the string representation for the given notification. func (n *Notification) String() string
{ return fmt.Sprintf("ID 0x%x %v", n.Id, n.State) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L186-L194
go
train
// NewConfig returns an initialised Config.
func NewConfig(id Id, checker Checker) *Config
// NewConfig returns an initialised Config. func NewConfig(id Id, checker Checker) *Config
{ return &Config{ Id: id, Interval: 5 * time.Second, Timeout: 30 * time.Second, Retries: 0, Checker: checker, } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L225-L232
go
train
// NewCheck returns an initialised Check.
func NewCheck(notify chan<- *Notification) *Check
// NewCheck returns an initialised Check. func NewCheck(notify chan<- *Notification) *Check
{ return &Check{ state: StateUnknown, notify: notify, update: make(chan Config, 1), quit: make(chan bool, 1), } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L235-L249
go
train
// Status returns the current status for this healthcheck instance.
func (hc *Check) Status() Status
// Status returns the current status for this healthcheck instance. func (hc *Check) Status() Status
{ hc.lock.RLock() defer hc.lock.RUnlock() status := Status{ LastCheck: hc.start, Failures: hc.failures, Successes: hc.successes, State: hc.state, } if hc.result != nil { status.Duration = hc.result.Duration status.Message = hc.result.String() } return status }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L258-L298
go
train
// Run invokes a healthcheck. It waits for the initial configuration to be // provided via the configuration channel, after which the configured // healthchecker is invoked at the given interval. If a new configuration // is provided the healthchecker is updated and checks are scheduled at the // new interval. Notifications are generated and sent via the notification // channel whenever a state transition occurs. Run will terminate once a // value is received on the quit channel.
func (hc *Check) Run(start <-chan time.Time)
// Run invokes a healthcheck. It waits for the initial configuration to be // provided via the configuration channel, after which the configured // healthchecker is invoked at the given interval. If a new configuration // is provided the healthchecker is updated and checks are scheduled at the // new interval. Notifications are generated and sent via the notification // channel whenever a state transition occurs. Run will terminate once a // value is received on the quit channel. func (hc *Check) Run(start <-chan time.Time)
{ // Wait for initial configuration. select { case config := <-hc.update: hc.Config = config case <-hc.quit: return } // Wait for a tick to avoid a thundering herd at startup and to // stagger healthchecks that have the same interval. if start != nil { <-start } log.Infof("Starting healthchecker for %d (%s)", hc.Id, hc) ticker := time.NewTicker(hc.Interval) hc.healthcheck() for { select { case <-hc.quit: ticker.Stop() log.Infof("Stopping healthchecker for %d (%s)", hc.Id, hc) return case config := <-hc.update: if hc.Interval != config.Interval { ticker.Stop() if start != nil { <-start } ticker = time.NewTicker(config.Interval) } hc.Config = config case <-ticker.C: hc.healthcheck() } } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L301-L342
go
train
// healthcheck executes the given checker.
func (hc *Check) healthcheck()
// healthcheck executes the given checker. func (hc *Check) healthcheck()
{ if hc.Checker == nil { return } start := time.Now() result := hc.execute() status := "SUCCESS" if !result.Success { status = "FAILURE" } log.Infof("%d: (%s) %s: %v", hc.Id, hc, status, result) hc.lock.Lock() hc.start = start hc.result = result var state State if result.Success { state = StateHealthy hc.failed = 0 hc.successes++ } else { hc.failed++ hc.failures++ state = StateUnhealthy } if hc.state == StateHealthy && hc.failed > 0 && hc.failed <= uint64(hc.Config.Retries) { log.Infof("%d: Failure %d - retrying...", hc.Id, hc.failed) state = StateHealthy } transition := (hc.state != state) hc.state = state hc.lock.Unlock() if transition { hc.Notify() } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L345-L350
go
train
// Notify generates a healthcheck notification for this checker.
func (hc *Check) Notify()
// Notify generates a healthcheck notification for this checker. func (hc *Check) Notify()
{ hc.notify <- &Notification{ Id: hc.Id, Status: hc.Status(), } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L353-L367
go
train
// execute invokes the given healthcheck checker with the configured timeout.
func (hc *Check) execute() *Result
// execute invokes the given healthcheck checker with the configured timeout. func (hc *Check) execute() *Result
{ ch := make(chan *Result, 1) checker := hc.Checker go func() { // TODO(jsing): Determine a way to ensure that this go routine // does not linger. ch <- checker.Check(hc.Timeout) }() select { case result := <-ch: return result case <-time.After(hc.Timeout): return &Result{"Timed out", false, hc.Timeout, nil} } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L378-L385
go
train
// Blocking enables or disables blocking updates for a healthcheck.
func (hc *Check) Blocking(block bool)
// Blocking enables or disables blocking updates for a healthcheck. func (hc *Check) Blocking(block bool)
{ len := 0 if !block { len = 1 } hc.blocking = block hc.update = make(chan Config, len) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L388-L398
go
train
// Update queues a healthcheck configuration update for processing.
func (hc *Check) Update(config *Config)
// Update queues a healthcheck configuration update for processing. func (hc *Check) Update(config *Config)
{ if hc.blocking { hc.update <- *config return } select { case hc.update <- *config: default: log.Warningf("Unable to update %d (%s), last update still queued", hc.Id, hc) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L439-L454
go
train
// NewServer returns an initialised healthcheck server.
func NewServer(cfg *ServerConfig) *Server
// NewServer returns an initialised healthcheck server. func NewServer(cfg *ServerConfig) *Server
{ if cfg == nil { defaultCfg := DefaultServerConfig() cfg = &defaultCfg } return &Server{ config: cfg, healthchecks: make(map[Id]*Check), notify: make(chan *Notification, cfg.ChannelSize), configs: make(chan map[Id]*Config), batch: make([]*Notification, 0, cfg.BatchSize), quit: make(chan bool, 1), } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L465-L471
go
train
// Run runs a healthcheck server.
func (s *Server) Run()
// Run runs a healthcheck server. func (s *Server) Run()
{ go s.updater() go s.notifier() go s.manager() <-s.quit }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L475-L491
go
train
// getHealthchecks attempts to get the current healthcheck configurations from // the Seesaw Engine.
func (s *Server) getHealthchecks() (*Checks, error)
// getHealthchecks attempts to get the current healthcheck configurations from // the Seesaw Engine. func (s *Server) getHealthchecks() (*Checks, error)
{ engineConn, err := net.DialTimeout("unix", s.config.EngineSocket, engineTimeout) if err != nil { return nil, fmt.Errorf("Dial failed: %v", err) } engineConn.SetDeadline(time.Now().Add(engineTimeout)) engine := rpc.NewClient(engineConn) defer engine.Close() var checks Checks ctx := ipc.NewTrustedContext(seesaw.SCHealthcheck) if err := engine.Call("SeesawEngine.Healthchecks", ctx, &checks); err != nil { return nil, fmt.Errorf("SeesawEngine.Healthchecks failed: %v", err) } return &checks, nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L496-L509
go
train
// updater attempts to fetch healthcheck configurations at regular intervals. // When configurations are successfully retrieved they are provided to the // manager via the configs channel.
func (s *Server) updater()
// updater attempts to fetch healthcheck configurations at regular intervals. // When configurations are successfully retrieved they are provided to the // manager via the configs channel. func (s *Server) updater()
{ for { log.Info("Getting healthchecks from engine...") checks, err := s.getHealthchecks() if err != nil { log.Error(err) time.Sleep(5 * time.Second) } else { log.Infof("Engine returned %d healthchecks", len(checks.Configs)) s.configs <- checks.Configs time.Sleep(15 * time.Second) } } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L515-L550
go
train
// manager is responsible for controlling the healthchecks that are currently // running. When healthcheck configurations become available, the manager will // stop and remove deleted healthchecks, spawn new healthchecks and provide // the current configurations to each of the running healthchecks.
func (s *Server) manager()
// manager is responsible for controlling the healthchecks that are currently // running. When healthcheck configurations become available, the manager will // stop and remove deleted healthchecks, spawn new healthchecks and provide // the current configurations to each of the running healthchecks. func (s *Server) manager()
{ checkTicker := time.NewTicker(50 * time.Millisecond) notifyTicker := time.NewTicker(s.config.NotifyInterval) for { select { case configs := <-s.configs: // Remove healthchecks that have been deleted. for id, hc := range s.healthchecks { if configs[id] == nil { hc.Stop() delete(s.healthchecks, id) } } // Spawn new healthchecks. for id := range configs { if s.healthchecks[id] == nil { hc := NewCheck(s.notify) s.healthchecks[id] = hc go hc.Run(checkTicker.C) } } // Update configurations. for id, hc := range s.healthchecks { hc.Update(configs[id]) } case <-notifyTicker.C: // Send status notifications for all healthchecks. for _, hc := range s.healthchecks { hc.Notify() } } } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L554-L578
go
train
// notifier batches healthcheck notifications and sends them to the Seesaw // Engine.
func (s *Server) notifier()
// notifier batches healthcheck notifications and sends them to the Seesaw // Engine. func (s *Server) notifier()
{ var timer <-chan time.Time for { var err error select { case notification := <-s.notify: s.batch = append(s.batch, notification) // Collect until BatchDelay passes, or BatchSize are queued. switch len(s.batch) { case 1: timer = time.After(s.config.BatchDelay) case s.config.BatchSize: err = s.send() timer = nil } case <-timer: err = s.send() } if err != nil { log.Fatal(err) } } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L582-L601
go
train
// send sends a batch of notifications to the Seesaw Engine, retrying on any // error and giving up after MaxFailures.
func (s *Server) send() error
// send sends a batch of notifications to the Seesaw Engine, retrying on any // error and giving up after MaxFailures. func (s *Server) send() error
{ failures := 0 for { err := s.sendBatch(s.batch) if err == nil { break } failures++ log.Errorf("Send failed %d times: %v", failures, err) if failures >= s.config.MaxFailures { return fmt.Errorf("send: %d errors, giving up", failures) } time.Sleep(s.config.RetryDelay) } s.batch = s.batch[:0] return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/core.go#L604-L616
go
train
// sendBatch sends a batch of notifications to the Seesaw Engine.
func (s *Server) sendBatch(batch []*Notification) error
// sendBatch sends a batch of notifications to the Seesaw Engine. func (s *Server) sendBatch(batch []*Notification) error
{ engineConn, err := net.DialTimeout("unix", s.config.EngineSocket, engineTimeout) if err != nil { return err } engineConn.SetDeadline(time.Now().Add(engineTimeout)) engine := rpc.NewClient(engineConn) defer engine.Close() var reply int ctx := ipc.NewTrustedContext(seesaw.SCHealthcheck) return engine.Call("SeesawEngine.HealthState", &HealthState{ctx, batch}, &reply) }