code
stringlengths
11
335k
docstring
stringlengths
20
11.8k
func_name
stringlengths
1
100
language
stringclasses
1 value
repo
stringclasses
245 values
path
stringlengths
4
144
url
stringlengths
43
214
license
stringclasses
4 values
func newClient(key string, url string, http *http.Client) *v1controller.Client { c := &v1controller.Client{ Client: &httpclient.Client{ ErrNotFound: ErrNotFound, Key: key, URL: url, HTTP: http, }, } return c }
newClient creates a generic Client object, additional attributes must be set by the caller
newClient
go
flynn/flynn
controller/client/client.go
https://github.com/flynn/flynn/blob/master/controller/client/client.go
BSD-3-Clause
func NewClient(uri, key string) (Client, error) { return NewClientWithHTTP(uri, key, httphelper.RetryClient) }
NewClient creates a new Client pointing at uri and using key for authentication.
NewClient
go
flynn/flynn
controller/client/client.go
https://github.com/flynn/flynn/blob/master/controller/client/client.go
BSD-3-Clause
func NewClientWithConfig(uri, key string, config Config) (Client, error) { if config.Pin == nil { return NewClient(uri, key) } d := &pinned.Config{Pin: config.Pin} if config.Domain != "" { d.Config = &tls.Config{ServerName: config.Domain} } httpClient := &http.Client{Transport: &http.Transport{DialTLS: d.Dial}} c := newClient(key, uri, httpClient) c.Host = config.Domain c.HijackDial = d.Dial return c, nil }
NewClientWithConfig acts like NewClient, but supports custom configuration.
NewClientWithConfig
go
flynn/flynn
controller/client/client.go
https://github.com/flynn/flynn/blob/master/controller/client/client.go
BSD-3-Clause
func (c *Client) GetCACert() ([]byte, error) { var cert bytes.Buffer res, err := c.RawReq("GET", "/ca-cert", nil, nil, nil) if err != nil { return nil, err } defer res.Body.Close() if _, err := io.Copy(&cert, res.Body); err != nil { return nil, err } return cert.Bytes(), nil }
GetCACert returns the CA cert for the controller
GetCACert
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) StreamFormations(since *time.Time, output chan<- *ct.ExpandedFormation) (stream.Stream, error) { if since == nil { s := time.Unix(0, 0) since = &s } t := since.UTC().Format(time.RFC3339Nano) return c.Stream("GET", "/formations?since="+t, nil, output) }
StreamFormations yields a series of ExpandedFormation into the provided channel. If since is not nil, only retrieves formation updates since the specified time.
StreamFormations
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) PutDomain(dm *ct.DomainMigration) error { if dm.Domain == "" { return errors.New("controller: missing domain") } if dm.OldDomain == "" { return errors.New("controller: missing old domain") } return c.Put("/domain", dm, dm) }
PutDomain migrates the cluster domain
PutDomain
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) CreateArtifact(artifact *ct.Artifact) error { return c.Post("/artifacts", artifact, artifact) }
CreateArtifact creates a new artifact.
CreateArtifact
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) CreateRelease(appID string, release *ct.Release) error { release.AppID = appID return c.Post("/releases", release, release) }
CreateRelease creates a new release.
CreateRelease
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) CreateApp(app *ct.App) error { return c.Post("/apps", app, app) }
CreateApp creates a new app.
CreateApp
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) UpdateApp(app *ct.App) error { if app.ID == "" { return errors.New("controller: missing id") } return c.Post(fmt.Sprintf("/apps/%s", app.ID), app, app) }
UpdateApp updates the meta and strategy using app.ID.
UpdateApp
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) UpdateAppMeta(app *ct.App) error { if app.ID == "" { return errors.New("controller: missing id") } return c.Post(fmt.Sprintf("/apps/%s/meta", app.ID), app, app) }
UpdateAppMeta updates the meta using app.ID, allowing empty meta to be set explicitly.
UpdateAppMeta
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) DeleteApp(appID string) (*ct.AppDeletion, error) { events := make(chan *ct.Event) stream, err := c.StreamEvents(ct.StreamEventsOptions{ AppID: appID, ObjectTypes: []ct.EventType{ct.EventTypeAppDeletion}, }, events) if err != nil { return nil, err } defer stream.Close() if err := c.Delete(fmt.Sprintf("/apps/%s", appID), nil); err != nil { return nil, err } select { case event, ok := <-events: if !ok { return nil, stream.Err() } var e ct.AppDeletionEvent if err := json.Unmarshal(event.Data, &e); err != nil { return nil, err } if e.Error != "" { return nil, errors.New(e.Error) } return e.AppDeletion, nil case <-time.After(60 * time.Second): return nil, errors.New("timed out waiting for app deletion") } }
DeleteApp deletes an app.
DeleteApp
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) CreateProvider(provider *ct.Provider) error { return c.Post("/providers", provider, provider) }
CreateProvider creates a new provider.
CreateProvider
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) GetProvider(providerID string) (*ct.Provider, error) { provider := &ct.Provider{} return provider, c.Get(fmt.Sprintf("/providers/%s", providerID), provider) }
GetProvider returns the provider identified by providerID.
GetProvider
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) ProvisionResource(req *ct.ResourceReq) (*ct.Resource, error) { if req.ProviderID == "" { return nil, errors.New("controller: missing provider id") } res := &ct.Resource{} err := c.Post(fmt.Sprintf("/providers/%s/resources", req.ProviderID), req, res) return res, err }
ProvisionResource uses a provider to provision a new resource for the application. Returns details about the resource.
ProvisionResource
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) GetResource(providerID, resourceID string) (*ct.Resource, error) { res := &ct.Resource{} err := c.Get(fmt.Sprintf("/providers/%s/resources/%s", providerID, resourceID), res) return res, err }
GetResource returns the resource identified by resourceID under providerID.
GetResource
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) ResourceListAll() ([]*ct.Resource, error) { var resources []*ct.Resource return resources, c.Get("/resources", &resources) }
ResourceListAll returns all resources.
ResourceListAll
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) ResourceList(providerID string) ([]*ct.Resource, error) { var resources []*ct.Resource return resources, c.Get(fmt.Sprintf("/providers/%s/resources", providerID), &resources) }
ResourceList returns all resources under providerID.
ResourceList
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) AddResourceApp(providerID, resourceID, appID string) (*ct.Resource, error) { var resource *ct.Resource return resource, c.Put(fmt.Sprintf("/providers/%s/resources/%s/apps/%s", providerID, resourceID, appID), nil, &resource) }
AddResourceApp adds appID to the resource identified by resourceID and returns the resource
AddResourceApp
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) DeleteResourceApp(providerID, resourceID, appID string) (*ct.Resource, error) { var resource *ct.Resource return resource, c.Delete(fmt.Sprintf("/providers/%s/resources/%s/apps/%s", providerID, resourceID, appID), &resource) }
DeleteResourceApp removes appID from the resource identified by resourceID and returns the resource
DeleteResourceApp
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) AppResourceList(appID string) ([]*ct.Resource, error) { var resources []*ct.Resource return resources, c.Get(fmt.Sprintf("/apps/%s/resources", appID), &resources) }
AppResourceList returns a list of all resources under appID.
AppResourceList
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) PutResource(resource *ct.Resource) error { if resource.ID == "" || resource.ProviderID == "" { return errors.New("controller: missing id and/or provider id") } return c.Put(fmt.Sprintf("/providers/%s/resources/%s", resource.ProviderID, resource.ID), resource, resource) }
PutResource updates a resource.
PutResource
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) DeleteResource(providerID, resourceID string) (*ct.Resource, error) { res := &ct.Resource{} err := c.Delete(fmt.Sprintf("/providers/%s/resources/%s", providerID, resourceID), res) return res, err }
DeleteResource deprovisions and deletes the resource identified by resourceID under providerID.
DeleteResource
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) PutFormation(formation *ct.Formation) error { if formation.AppID == "" || formation.ReleaseID == "" { return errors.New("controller: missing app id and/or release id") } return c.Put(fmt.Sprintf("/apps/%s/formations/%s", formation.AppID, formation.ReleaseID), formation, formation) }
PutFormation updates an existing formation.
PutFormation
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) PutJob(job *ct.Job) error { if job.UUID == "" || job.AppID == "" { return errors.New("controller: missing job uuid and/or app id") } return c.Put(fmt.Sprintf("/apps/%s/jobs/%s", job.AppID, job.UUID), job, job) }
PutJob updates an existing job.
PutJob
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) DeleteJob(appID, jobID string) error { return c.Delete(fmt.Sprintf("/apps/%s/jobs/%s", appID, jobID), nil) }
DeleteJob kills a specific job id under the specified app.
DeleteJob
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) SetAppRelease(appID, releaseID string) error { return c.Put(fmt.Sprintf("/apps/%s/release", appID), &ct.Release{ID: releaseID}, nil) }
SetAppRelease sets the specified release as the current release for an app.
SetAppRelease
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) GetAppRelease(appID string) (*ct.Release, error) { release := &ct.Release{} return release, c.Get(fmt.Sprintf("/apps/%s/release", appID), release) }
GetAppRelease returns the current release of an app.
GetAppRelease
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) RouteList() ([]*router.Route, error) { var routes []*router.Route return routes, c.Get("/routes", &routes) }
RouteList returns all routes.
RouteList
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) AppRouteList(appID string) ([]*router.Route, error) { var routes []*router.Route return routes, c.Get(fmt.Sprintf("/apps/%s/routes", appID), &routes) }
AppRouteList returns all routes for an app.
AppRouteList
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) GetRoute(appID string, routeID string) (*router.Route, error) { route := &router.Route{} return route, c.Get(fmt.Sprintf("/apps/%s/routes/%s", appID, routeID), route) }
GetRoute returns details for the routeID under the specified app.
GetRoute
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) CreateRoute(appID string, route *router.Route) error { return c.Post(fmt.Sprintf("/apps/%s/routes", appID), route, route) }
CreateRoute creates a new route for the specified app.
CreateRoute
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) UpdateRoute(appID string, routeID string, route *router.Route) error { return c.Put(fmt.Sprintf("/apps/%s/routes/%s", appID, routeID), route, route) }
UpdateRoute updates details for the routeID under the specified app.
UpdateRoute
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) DeleteRoute(appID string, routeID string) error { return c.Delete(fmt.Sprintf("/apps/%s/routes/%s", appID, routeID), nil) }
DeleteRoute deletes a route under the specified app.
DeleteRoute
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) GetFormation(appID, releaseID string) (*ct.Formation, error) { formation := &ct.Formation{} return formation, c.Get(fmt.Sprintf("/apps/%s/formations/%s", appID, releaseID), formation) }
GetFormation returns details for the specified formation under app and release.
GetFormation
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) GetExpandedFormation(appID, releaseID string) (*ct.ExpandedFormation, error) { formation := &ct.ExpandedFormation{} return formation, c.Get(fmt.Sprintf("/apps/%s/formations/%s?expand=true", appID, releaseID), formation) }
GetExpandedFormation returns expanded details for the specified formation under app and release.
GetExpandedFormation
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) FormationList(appID string) ([]*ct.Formation, error) { var formations []*ct.Formation return formations, c.Get(fmt.Sprintf("/apps/%s/formations", appID), &formations) }
FormationList returns a list of all formations under appID.
FormationList
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) FormationListActive() ([]*ct.ExpandedFormation, error) { var formations []*ct.ExpandedFormation return formations, c.Get("/formations?active=true", &formations) }
FormationListActive returns a list of all active formations (i.e. formations whose process count is greater than zero).
FormationListActive
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) DeleteFormation(appID, releaseID string) error { return c.Delete(fmt.Sprintf("/apps/%s/formations/%s", appID, releaseID), nil) }
DeleteFormation deletes the formation matching appID and releaseID.
DeleteFormation
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) GetRelease(releaseID string) (*ct.Release, error) { release := &ct.Release{} return release, c.Get(fmt.Sprintf("/releases/%s", releaseID), release) }
GetRelease returns details for the specified release.
GetRelease
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) GetArtifact(artifactID string) (*ct.Artifact, error) { artifact := &ct.Artifact{} return artifact, c.Get(fmt.Sprintf("/artifacts/%s", artifactID), artifact) }
GetArtifact returns details for the specified artifact.
GetArtifact
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) GetApp(appID string) (*ct.App, error) { app := &ct.App{} return app, c.Get(fmt.Sprintf("/apps/%s", appID), app) }
GetApp returns details for the specified app.
GetApp
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) GetAppLog(appID string, opts *logagg.LogOpts) (io.ReadCloser, error) { path := fmt.Sprintf("/apps/%s/log", appID) if opts != nil { if encodedQuery := opts.EncodedQuery(); encodedQuery != "" { path = fmt.Sprintf("%s?%s", path, encodedQuery) } } res, err := c.RawReq("GET", path, nil, nil, nil) if err != nil { return nil, err } return res.Body, nil }
GetAppLog returns a ReadCloser log stream of the app with ID appID. If lines is zero or above, the number of lines returned will be capped at that value. Otherwise, all available logs are returned. If follow is true, new log lines are streamed after the buffered log.
GetAppLog
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) StreamAppLog(appID string, opts *logagg.LogOpts, output chan<- *ct.SSELogChunk) (stream.Stream, error) { path := fmt.Sprintf("/apps/%s/log", appID) if opts != nil { if encodedQuery := opts.EncodedQuery(); encodedQuery != "" { path = fmt.Sprintf("%s?%s", path, encodedQuery) } } return c.Stream("GET", path, nil, output) }
StreamAppLog is the same as GetAppLog but returns log lines via an SSE stream
StreamAppLog
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) GetDeployment(deploymentID string) (*ct.Deployment, error) { res := &ct.Deployment{} return res, c.Get(fmt.Sprintf("/deployments/%s", deploymentID), res) }
GetDeployment returns a deployment queued on the deployer.
GetDeployment
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) DeploymentList(appID string) ([]*ct.Deployment, error) { var deployments []*ct.Deployment return deployments, c.Get(fmt.Sprintf("/apps/%s/deployments", appID), &deployments) }
DeploymentList returns a list of all deployments.
DeploymentList
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) StreamJobEvents(appID string, output chan *ct.Job) (stream.Stream, error) { appEvents := make(chan *ct.Event) go convertEvents(appEvents, output) return c.StreamEvents(ct.StreamEventsOptions{ AppID: appID, ObjectTypes: []ct.EventType{ct.EventTypeJob}, }, appEvents) }
StreamJobEvents streams job events to the output channel.
StreamJobEvents
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) RunJobAttached(appID string, job *ct.NewJob) (httpclient.ReadWriteCloser, error) { return c.Hijack("POST", fmt.Sprintf("/apps/%s/jobs", appID), http.Header{"Upgrade": {"flynn-attach/0"}}, job) }
RunJobAttached runs a new job under the specified app, attaching to the job and returning a ReadWriteCloser stream, which can then be used for communicating with the job.
RunJobAttached
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) RunJobDetached(appID string, req *ct.NewJob) (*ct.Job, error) { job := &ct.Job{} return job, c.Post(fmt.Sprintf("/apps/%s/jobs", appID), req, job) }
RunJobDetached runs a new job under the specified app, returning the job's details.
RunJobDetached
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) GetJob(appID, jobID string) (*ct.Job, error) { job := &ct.Job{} return job, c.Get(fmt.Sprintf("/apps/%s/jobs/%s", appID, jobID), job) }
GetJob returns a Job for the given app and job ID
GetJob
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) JobList(appID string) ([]*ct.Job, error) { var jobs []*ct.Job return jobs, c.Get(fmt.Sprintf("/apps/%s/jobs", appID), &jobs) }
JobList returns a list of all jobs.
JobList
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) JobListActive() ([]*ct.Job, error) { var jobs []*ct.Job return jobs, c.Get("/active-jobs", &jobs) }
JobListActive returns a list of all active jobs.
JobListActive
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) AppList() ([]*ct.App, error) { var apps []*ct.App return apps, c.Get("/apps", &apps) }
AppList returns a list of all apps.
AppList
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) ArtifactList() ([]*ct.Artifact, error) { var artifacts []*ct.Artifact return artifacts, c.Get("/artifacts", &artifacts) }
ArtifactList returns a list of all artifacts
ArtifactList
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) ReleaseList() ([]*ct.Release, error) { var releases []*ct.Release return releases, c.Get("/releases", &releases) }
ReleaseList returns a list of all releases
ReleaseList
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) AppReleaseList(appID string) ([]*ct.Release, error) { var releases []*ct.Release return releases, c.Get(fmt.Sprintf("/apps/%s/releases", appID), &releases) }
AppReleaseList returns a list of all releases under appID.
AppReleaseList
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) ProviderList() ([]*ct.Provider, error) { var providers []*ct.Provider return providers, c.Get("/providers", &providers) }
ProviderList returns a list of all providers.
ProviderList
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) GetVolume(appID, id string) (*ct.Volume, error) { if appID == "" { return nil, errors.New("controller: missing app ID") } if id == "" { return nil, errors.New("controller: missing id") } vol := &ct.Volume{} return vol, c.Get(fmt.Sprintf("/apps/%s/volumes/%s", appID, id), vol) }
GetVolume returns a Volume for the given volume ID
GetVolume
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) PutVolume(vol *ct.Volume) error { if vol.ID == "" { return errors.New("controller: missing id") } return c.Put(fmt.Sprintf("/volumes/%s", vol.ID), vol, vol) }
PutVolume updates an existing volume.
PutVolume
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) VolumeList() ([]*ct.Volume, error) { var volumes []*ct.Volume return volumes, c.Get("/volumes", &volumes) }
VolumeList returns a list of all volumes.
VolumeList
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) AppVolumeList(appID string) ([]*ct.Volume, error) { if appID == "" { return nil, errors.New("controller: missing app ID") } var volumes []*ct.Volume return volumes, c.Get(fmt.Sprintf("/apps/%s/volumes", appID), &volumes) }
AppVolumeList returns a list of all volumes for an app.
AppVolumeList
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) DecommissionVolume(appID string, vol *ct.Volume) error { if appID == "" { return errors.New("controller: missing app ID") } if vol.ID == "" { return errors.New("controller: missing id") } return c.Put(fmt.Sprintf("/apps/%s/volumes/%s/decommission", appID, vol.ID), &vol, &vol) }
DecommissionVolume decommissions a volume
DecommissionVolume
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) StreamVolumes(since *time.Time, output chan *ct.Volume) (stream.Stream, error) { if since == nil { s := time.Unix(0, 0) since = &s } t := since.UTC().Format(time.RFC3339Nano) return c.Stream("GET", "/volumes?since="+t, nil, output) }
StreamVolumes sends a series of Volume into the provided channel. If since is not nil, only retrieves volume updates since the specified time.
StreamVolumes
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) Backup() (io.ReadCloser, error) { res, err := c.RawReq("GET", "/backup", nil, nil, nil) if err != nil { return nil, err } return res.Body, nil }
Backup takes a backup of the cluster
Backup
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) GetBackupMeta() (*ct.ClusterBackup, error) { b := &ct.ClusterBackup{} return b, c.Get("/backup", b) }
GetBackupMeta returns metadata for latest backup
GetBackupMeta
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) DeleteRelease(appID, releaseID string) (*ct.ReleaseDeletion, error) { events := make(chan *ct.Event) stream, err := c.StreamEvents(ct.StreamEventsOptions{ AppID: appID, ObjectID: releaseID, ObjectTypes: []ct.EventType{ct.EventTypeReleaseDeletion}, }, events) if err != nil { return nil, err } defer stream.Close() if err := c.Delete(fmt.Sprintf("/apps/%s/releases/%s", appID, releaseID), nil); err != nil { return nil, err } select { case event, ok := <-events: if !ok { return nil, stream.Err() } var e ct.ReleaseDeletionEvent if err := json.Unmarshal(event.Data, &e); err != nil { return nil, err } if e.Error != "" { return nil, errors.New(e.Error) } return e.ReleaseDeletion, nil case <-time.After(60 * time.Second): return nil, errors.New("timed out waiting for release deletion") } }
DeleteRelease deletes a release and any associated file artifacts.
DeleteRelease
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) ScheduleAppGarbageCollection(appID string) error { return c.Post(fmt.Sprintf("/apps/%s/gc", appID), nil, nil) }
ScheduleAppGarbageCollection schedules a garbage collection cycle for the app
ScheduleAppGarbageCollection
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) Status() (*status.Status, error) { type statusResponse struct { Data status.Status `json:"data"` } s := &statusResponse{} if err := c.Get(status.Path, s); err != nil { return nil, err } return &s.Data, nil }
Status gets the controller status
Status
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) CreateSink(sink *ct.Sink) error { return c.Post("/sinks", sink, sink) }
CreateSink creates a new log sink
CreateSink
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) GetSink(sinkID string) (*ct.Sink, error) { sink := &ct.Sink{} return sink, c.Get(fmt.Sprintf("/sinks/%s", sinkID), sink) }
GetSink gets a log sink
GetSink
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) DeleteSink(sinkID string) (*ct.Sink, error) { sink := &ct.Sink{} return sink, c.Delete(fmt.Sprintf("/sinks/%s", sinkID), sink) }
DeleteSink removes a log sink
DeleteSink
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) ListSinks() ([]*ct.Sink, error) { var sinks []*ct.Sink return sinks, c.Get("/sinks", &sinks) }
ListSink returns all log sinks
ListSinks
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func (c *Client) StreamSinks(since *time.Time, output chan *ct.Sink) (stream.Stream, error) { if since == nil { s := time.Unix(0, 0) since = &s } t := since.UTC().Format(time.RFC3339Nano) return c.Stream("GET", "/sinks?since="+t, nil, output) }
StreamSinks yields a series of Sink into the provided channel. If since is not nil, only retrieves sink updates since the specified time.
StreamSinks
go
flynn/flynn
controller/client/v1/client.go
https://github.com/flynn/flynn/blob/master/controller/client/v1/client.go
BSD-3-Clause
func GetEntrypoint(artifacts []*ct.Artifact, typ string) *ct.ImageEntrypoint { for i := len(artifacts) - 1; i >= 0; i-- { artifact := artifacts[i] if artifact.Type != ct.ArtifactTypeFlynn { continue } if e, ok := artifact.Manifest().Entrypoints[typ]; ok { return e } } for i := len(artifacts) - 1; i >= 0; i-- { artifact := artifacts[i] if artifact.Type != ct.ArtifactTypeFlynn { continue } if e := artifact.Manifest().DefaultEntrypoint(); e != nil { return e } } return nil }
GetEntrypoint returns an image entrypoint for a process type from a list of artifacts, first iterating through them and returning any entrypoint having the exact type, then iterating through them and returning the artifact's default entrypoint if it has one. The artifacts are traversed in reverse order so that entrypoints in the image being overlayed at the top are considered first.
GetEntrypoint
go
flynn/flynn
controller/utils/utils.go
https://github.com/flynn/flynn/blob/master/controller/utils/utils.go
BSD-3-Clause
func SetupMountspecs(job *host.Job, artifacts []*ct.Artifact) { for _, artifact := range artifacts { if artifact.Type != ct.ArtifactTypeFlynn { continue } if len(artifact.Manifest().Rootfs) != 1 { continue } rootfs := artifact.Manifest().Rootfs[0] for _, layer := range rootfs.Layers { if layer.Type != ct.ImageLayerTypeSquashfs { continue } job.Mountspecs = append(job.Mountspecs, &host.Mountspec{ Type: host.MountspecTypeSquashfs, ID: layer.ID, URL: artifact.LayerURL(layer), Size: layer.Length, Hashes: layer.Hashes, Meta: artifact.Meta, }) } } }
SetupMountspecs populates job.Mountspecs using the layers from a list of Flynn image artifacts, expecting each artifact to have a single rootfs entry containing squashfs layers
SetupMountspecs
go
flynn/flynn
controller/utils/utils.go
https://github.com/flynn/flynn/blob/master/controller/utils/utils.go
BSD-3-Clause
func updateImageIDs(env map[string]string) bool { updated := false for prefix, newID := range map[string]string{ "REDIS": redisImage.ID, "SLUGBUILDER": slugBuilder.ID, "SLUGRUNNER": slugRunner.ID, } { idKey := prefix + "_IMAGE_ID" if id, ok := env[idKey]; ok && id != newID { env[idKey] = newID updated = true } uriKey := prefix + "_IMAGE_URI" if _, ok := env[uriKey]; ok { delete(env, uriKey) env[idKey] = newID updated = true } } return updated }
updateImageIDs updates REDIS_IMAGE_ID, SLUGBUILDER_IMAGE_ID and SLUGRUNNER_IMAGE_ID if they are set and have an old ID, and also replaces the legacy REDIS_IMAGE_URI, SLUGBUILDER_IMAGE_URI and SLUGRUNNER_IMAGE_URI
updateImageIDs
go
flynn/flynn
updater/updater.go
https://github.com/flynn/flynn/blob/master/updater/updater.go
BSD-3-Clause
func (l *LibcontainerBackend) ConfigureNetworking(config *host.NetworkConfig) error { log := l.Logger.New("fn", "ConfigureNetworking") var err error l.bridgeAddr, l.bridgeNet, err = net.ParseCIDR(config.Subnet) if err != nil { return err } l.ipalloc.RequestIP(l.bridgeNet, l.bridgeAddr) la := netlink.NewLinkAttrs() la.Name = l.BridgeName bridge := netlink.Link(&netlink.Bridge{LinkAttrs: la}) err = netlink.LinkAdd(bridge) bridgeExists := os.IsExist(err) if err != nil && !bridgeExists { return err } bridge, err = netlink.LinkByName(l.BridgeName) if err != nil { return err } if !bridgeExists { // We need to explicitly assign the MAC address to avoid it changing to a lower value // See: https://github.com/flynn/flynn/issues/223 mac := random.Bytes(5) if err := netlink.LinkSetHardwareAddr(bridge, append([]byte{0xfe}, mac...)); err != nil { return err } } currAddrs, err := netlink.AddrList(bridge, netlink.FAMILY_ALL) if err != nil { return err } setIP := true for _, addr := range currAddrs { if addr.IPNet.IP.Equal(l.bridgeAddr) && bytes.Equal(addr.IPNet.Mask, l.bridgeNet.Mask) { setIP = false } else { if err := netlink.AddrDel(bridge, &addr); err != nil { return err } } } if setIP { if err := netlink.AddrAdd(bridge, &netlink.Addr{IPNet: &net.IPNet{IP: l.bridgeAddr, Mask: l.bridgeNet.Mask}}); err != nil { return err } } // Workaround for a kernel bug that results in a unregister_netdevice error // in dmesg and hang of netlink, requiring a reboot. // // Remove when the kernel bug is fixed. // // https://github.com/moby/moby/issues/5618 // https://github.com/kubernetes/kubernetes/issues/20096 if err := netlink.SetPromiscOn(bridge); err != nil { return err } if err := netlink.LinkSetUp(bridge); err != nil { return err } // enable IP forwarding ipFwd := "/proc/sys/net/ipv4/ip_forward" data, err := ioutil.ReadFile(ipFwd) if err != nil { return err } if !bytes.HasPrefix(data, []byte("1")) { if err := ioutil.WriteFile(ipFwd, []byte("1\n"), 0644); err != nil { return err } } // Set up iptables for outbound traffic masquerading from containers to the // rest of the network. if err := iptables.EnableOutboundNAT(l.BridgeName, l.bridgeNet.String()); err != nil { return err } // Read DNS config, discoverd uses the nameservers dnsConf, err := dns.ClientConfigFromFile("/etc/resolv.conf") if err != nil { return err } config.Resolvers = dnsConf.Servers // Write a resolv.conf to be bind-mounted into containers pointing at the // future discoverd DNS listener if err := os.MkdirAll("/etc/flynn", 0755); err != nil { return err } var resolvSearch string if len(dnsConf.Search) > 0 { resolvSearch = fmt.Sprintf("search %s\n", strings.Join(dnsConf.Search, " ")) } if err := ioutil.WriteFile("/etc/flynn/resolv.conf", []byte(fmt.Sprintf("%snameserver %s\n", resolvSearch, l.bridgeAddr.String())), 0644); err != nil { return err } l.resolvConf = "/etc/flynn/resolv.conf" // Allocate IPs for running jobs l.containersMtx.Lock() defer l.containersMtx.Unlock() for _, container := range l.containers { if !container.job.Config.HostNetwork { b := random.Bytes(5) container.MAC = fmt.Sprintf("fe:%02x:%02x:%02x:%02x:%02x", b[0], b[1], b[2], b[3], b[4]) if _, err := l.ipalloc.RequestIP(l.bridgeNet, container.IP); err != nil { log.Error("error requesting ip", "job.id", container.job.ID, "err", err) } } } if l.EnableDHCP { go func() { if err := dhcp.ListenAndServeIf(l.BridgeName, l); err != nil { shutdown.Fatal(err) } }() } close(l.networkConfigured) return nil }
ConfigureNetworking is called once during host startup and sets up the local bridge and forwarding rules for containers.
ConfigureNetworking
go
flynn/flynn
host/libcontainer_backend.go
https://github.com/flynn/flynn/blob/master/host/libcontainer_backend.go
BSD-3-Clause
func (l *LibcontainerBackend) discoverdDial(network, addr string) (net.Conn, error) { host, _, err := net.SplitHostPort(addr) if err != nil { return nil, err } if strings.HasSuffix(host, ".discoverd") { // ensure discoverd is configured <-l.discoverdConfigured // lookup the service and pick a random address service := strings.TrimSuffix(host, ".discoverd") addrs, err := l.discoverdClient.Service(service).Addrs() if err != nil { return nil, err } else if len(addrs) == 0 { return nil, fmt.Errorf("lookup %s: no such host", host) } addr = addrs[random.Math.Intn(len(addrs))] } return dialer.Default.Dial(network, addr) }
discoverdDial is a discoverd aware dialer which resolves a discoverd host to an address using the configured discoverd client as the host is likely not using discoverd to resolve DNS queries
discoverdDial
go
flynn/flynn
host/libcontainer_backend.go
https://github.com/flynn/flynn/blob/master/host/libcontainer_backend.go
BSD-3-Clause
func milliCPUToShares(milliCPU uint64) uint64 { // Taken from lmctfy https://github.com/google/lmctfy/blob/master/lmctfy/controllers/cpu_controller.cc const ( minShares = 2 sharesPerCPU = 1024 milliCPUToCPU = 1000 ) if milliCPU == 0 { // zero shares is invalid, 2 is the minimum return minShares } // Conceptually (milliCPU / milliCPUToCPU) * sharesPerCPU, but factored to improve rounding. shares := (milliCPU * sharesPerCPU) / milliCPUToCPU if shares < minShares { return minShares } return shares }
Taken from Kubernetes: https://github.com/kubernetes/kubernetes/blob/d66ae29587e746c40390d61a1253a1bfa7aebd8a/pkg/kubelet/dockertools/docker.go#L323-L336
milliCPUToShares
go
flynn/flynn
host/libcontainer_backend.go
https://github.com/flynn/flynn/blob/master/host/libcontainer_backend.go
BSD-3-Clause
func (d *discoverdWrapper) LeaderCh() chan bool { return d.leader }
Only one receiver can consume from this channel at a time.
LeaderCh
go
flynn/flynn
host/discoverd_wrapper.go
https://github.com/flynn/flynn/blob/master/host/discoverd_wrapper.go
BSD-3-Clause
func (h *Host) Update(cmd *host.Command) error { log := h.log.New("fn", "Update") // dup the listener so we can close the current listener but still be // able continue serving requests if the child exits by using the dup'd // listener. log.Info("duplicating HTTP listener") file, err := h.listener.(interface { File() (*os.File, error) }).File() if err != nil { log.Error("error duplicating HTTP listener", "err", err) return err } defer file.Close() // exec a child, passing the listener and control socket as extra files log.Info("creating child process") child, err := h.exec(cmd, file) if err != nil { log.Error("error creating child process", "err", err) return err } defer child.CloseSock() // close our listener and state DBs log.Info("closing HTTP listener") h.listener.Close() log.Info("closing state databases") if err := h.CloseDBs(); err != nil { log.Error("error closing state databases", "err", err) return err } log.Info("closing logs") buffers, err := h.CloseLogs() if err != nil { log.Error("error closing logs", "err", err) return err } log.Info("resuming child process") if resumeErr := child.Resume(buffers); resumeErr != nil { log.Error("error resuming child process", "err", resumeErr) // The child failed to resume, kill it and resume ourselves. // // If anything fails here, exit rather than returning an error // so a new host process can be started (rather than this // process sitting around not serving requests). log.Info("killing child process") child.Kill() log.Info("reopening logs") if err := h.OpenLogs(buffers); err != nil { shutdown.Fatalf("error reopening logs after failed update: %s", err) } log.Error("recreating HTTP listener") l, err := net.FileListener(file) if err != nil { shutdown.Fatalf("error recreating HTTP listener after failed update: %s", err) } h.listener = l log.Info("reopening state databases") if err := h.OpenDBs(); err != nil { shutdown.Fatalf("error reopening state databases after failed update: %s", err) } log.Info("serving HTTP requests") h.ServeHTTP() return resumeErr } return nil }
Update performs a zero-downtime update of the flynn-host daemon, replacing the current daemon with an instance of the given command. The HTTP API listener is passed from the parent to the child, but due to the state DBs being process exclusive and requiring initialisation, further syncronisation is required to manage opening and closing them, which is done using a control socket. Any partial log lines read by the parent are also passed to the child to avoid dropping logs or sending partial logs over two lines. An outline of the process: * parent receives a request to exec a new daemon * parent creates a control socket pair (via socketpair(2)) * parent starts a child process, passing the API listener as FD 3, and a control socket as FD 4 * parent closes its API listener FD, state DBs and log followers. * parent signals the child to resume by sending "resume" message to control socket, followed by any partial log buffers. * child receives resume request, opens state DBs, seeds the log followers with the partial buffers and starts serving API requests * child signals parent it is now serving requests by sending "ok" message to control socket * parent sends response to client and shuts down seconds later
Update
go
flynn/flynn
host/update.go
https://github.com/flynn/flynn/blob/master/host/update.go
BSD-3-Clause
func setEnv(cmd *exec.Cmd, envs map[string]string) { env := os.Environ() cmd.Env = make([]string, 0, len(env)+len(envs)) outer: for _, e := range env { for k := range envs { if strings.HasPrefix(e, k+"=") { continue outer } } cmd.Env = append(cmd.Env, e) } for k, v := range envs { cmd.Env = append(cmd.Env, k+"="+v) } }
setEnv sets the given environment variables for the command, ensuring they are only set once.
setEnv
go
flynn/flynn
host/update.go
https://github.com/flynn/flynn/blob/master/host/update.go
BSD-3-Clause
func (c *Child) Resume(buffers host.LogBuffers) error { if buffers == nil { buffers = host.LogBuffers{} } data, err := json.Marshal(buffers) if err != nil { return err } if _, err := syscall.Write(c.sock, append(ControlMsgResume, data...)); err != nil { return err } msg := make([]byte, len(ControlMsgOK)) if _, err := syscall.Read(c.sock, msg); err != nil { return err } if !bytes.Equal(msg, ControlMsgOK) { return fmt.Errorf("unexpected resume message from child: %s", msg) } return nil }
Resume writes ControlMsgResume to the control socket and waits for a ControlMsgOK response
Resume
go
flynn/flynn
host/update.go
https://github.com/flynn/flynn/blob/master/host/update.go
BSD-3-Clause
func (s *State) OpenDB() error { s.dbCond.L.Lock() defer s.dbCond.L.Unlock() if s.stateDB != nil { return nil } // open/initialize db if err := os.MkdirAll(filepath.Dir(s.stateFilePath), 0755); err != nil { return fmt.Errorf("could not not mkdir for db: %s", err) } stateDB, err := bolt.Open(s.stateFilePath, 0600, &bolt.Options{Timeout: 5 * time.Second}) if err != nil { return fmt.Errorf("could not open db: %s", err) } s.stateDB = stateDB if err := s.stateDB.Update(func(tx *bolt.Tx) error { // idempotently create buckets. (errors ignored because they're all compile-time impossible args checks.) tx.CreateBucketIfNotExists([]byte("jobs")) tx.CreateBucketIfNotExists([]byte("gc-jobs")) tx.CreateBucketIfNotExists([]byte("backend-jobs")) tx.CreateBucketIfNotExists([]byte("backend-global")) tx.CreateBucketIfNotExists([]byte("persistent-jobs")) return nil }); err != nil { return fmt.Errorf("could not initialize host persistence db: %s", err) } return nil }
OpenDB opens and initialises the persistence DB, if not already open.
OpenDB
go
flynn/flynn
host/state.go
https://github.com/flynn/flynn/blob/master/host/state.go
BSD-3-Clause
func (s *State) CloseDB() error { s.dbCond.L.Lock() defer s.dbCond.L.Unlock() if s.stateDB == nil { return nil } for s.dbUsers > 0 { s.dbCond.Wait() } if err := s.stateDB.Close(); err != nil { return err } s.stateDB = nil return nil }
CloseDB closes the persistence DB, waiting for the state to be fully released first.
CloseDB
go
flynn/flynn
host/state.go
https://github.com/flynn/flynn/blob/master/host/state.go
BSD-3-Clause
func (s *State) Acquire() error { s.dbCond.L.Lock() defer s.dbCond.L.Unlock() if s.stateDB == nil { return ErrDBClosed } s.dbUsers++ return nil }
Acquire acquires the state for use by incrementing s.dbUsers, which prevents the state DB being closed until the caller has finished performing actions which will lead to changes being persisted to the DB. For example, running a job starts the job and then persists the change of state, but if the DB is closed in that time then the state of the running job will be lost. ErrDBClosed is returned if the DB is already closed so API requests will fail before any actions are performed.
Acquire
go
flynn/flynn
host/state.go
https://github.com/flynn/flynn/blob/master/host/state.go
BSD-3-Clause
func (s *State) Release() { s.dbCond.L.Lock() defer s.dbCond.L.Unlock() s.dbUsers-- if s.dbUsers == 0 { s.dbCond.Broadcast() } }
Release releases the state by decrementing s.dbUsers, broadcasting the condition variable if no users are left to wake CloseDB.
Release
go
flynn/flynn
host/state.go
https://github.com/flynn/flynn/blob/master/host/state.go
BSD-3-Clause
func (r *RateLimitBucket) Take() bool { select { case r.ch <- struct{}{}: return true default: return false } }
Take attempts to take a token from the bucket, returning whether or not a token was taken
Take
go
flynn/flynn
host/http.go
https://github.com/flynn/flynn/blob/master/host/http.go
BSD-3-Clause
func (r *RateLimitBucket) Wait() { r.ch <- struct{}{} }
Wait takes the next available token
Wait
go
flynn/flynn
host/http.go
https://github.com/flynn/flynn/blob/master/host/http.go
BSD-3-Clause
func (r *RateLimitBucket) Put() { <-r.ch }
Put returns a token to the bucket
Put
go
flynn/flynn
host/http.go
https://github.com/flynn/flynn/blob/master/host/http.go
BSD-3-Clause
func (m *Mux) Follow(r io.ReadCloser, buffer string, msgID logagg.MsgID, config *Config) *LogStream { hdr := &rfc5424.Header{ Hostname: []byte(config.HostID), AppName: []byte(config.AppID), MsgID: []byte(msgID), Severity: 6, // Info Facility: 23, // local7 } if config.JobType != "" { hdr.ProcID = []byte(config.JobType + "." + config.JobID) } else { hdr.ProcID = []byte(config.JobID) } s := &LogStream{ m: m, log: r, done: make(chan struct{}), } s.closed.Store(false) m.jobsMtx.Lock() defer m.jobsMtx.Unlock() // set up the WaitGroup so that subscribers can track when the job fds have closed wg, ok := m.jobWaits[config.JobID] if !ok { wg = &sync.WaitGroup{} m.jobWaits[config.JobID] = wg } wg.Add(1) if !ok { // we created the wg, so create a goroutine to clean up go func() { wg.Wait() m.jobsMtx.Lock() defer m.jobsMtx.Unlock() delete(m.jobWaits, config.JobID) }() } // if there is a jobStart channel, a subscriber is waiting for the WaitGroup // to be created, signal it. if ch, ok := m.jobStarts[config.JobID]; ok { close(ch) delete(m.jobStarts, config.JobID) } go s.follow(r, buffer, config.AppID, hdr, wg) return s }
Follow starts a goroutine that reads log lines from the reader into the mux. It runs until the reader is closed or an error occurs. If an error occurs, the reader may still be open.
Follow
go
flynn/flynn
host/logmux/logmux.go
https://github.com/flynn/flynn/blob/master/host/logmux/logmux.go
BSD-3-Clause
func (m *Mux) logFiles(app string) (map[string][]string, error) { files, err := ioutil.ReadDir(m.logDir) if err != nil { return nil, err } res := make(map[string][]string) for _, f := range files { n := f.Name() if f.IsDir() || !strings.HasSuffix(n, ".log") || !appIDPrefixPattern.MatchString(n) || !strings.HasPrefix(n, app) { continue } appID := n[:36] res[appID] = append(res[appID], filepath.Join(m.logDir, n)) } return res, nil }
logFiles returns a list of app IDs and the list of log file names associated with them, from oldest to newest. There is always at least one file, the current log for the app.
logFiles
go
flynn/flynn
host/logmux/logmux.go
https://github.com/flynn/flynn/blob/master/host/logmux/logmux.go
BSD-3-Clause
func (l *appLog) Release() { l.mtx.Lock() defer l.mtx.Unlock() l.refs-- if l.refs == 0 { // we're the last user, clean it up l.l.Close() l.m.appLogsMtx.Lock() delete(l.m.appLogs, l.appID) l.m.appLogsMtx.Unlock() } }
Release releases the app log, when the last job releases an app log, it is closed.
Release
go
flynn/flynn
host/logmux/logmux.go
https://github.com/flynn/flynn/blob/master/host/logmux/logmux.go
BSD-3-Clause
func parseProcID(procID []byte) (string, string) { procTypeID := strings.SplitN(string(procID), ".", 2) if len(procTypeID) == 2 { return procTypeID[1], procTypeID[0] } return procTypeID[0], "" }
Parses JobID and ProcType from header ProcID field Always returns JobID, returns ProcType if available
parseProcID
go
flynn/flynn
host/logmux/sink.go
https://github.com/flynn/flynn/blob/master/host/logmux/sink.go
BSD-3-Clause
func (x ContainerConfig) Merge(y ContainerConfig) ContainerConfig { x.TTY = x.TTY || y.TTY x.Stdin = x.Stdin || y.Stdin x.Data = x.Data || y.Data if y.Args != nil { x.Args = y.Args } env := make(map[string]string, len(x.Env)+len(y.Env)) for k, v := range x.Env { env[k] = v } for k, v := range y.Env { env[k] = v } x.Env = env mounts := make([]Mount, 0, len(x.Mounts)+len(y.Mounts)) mounts = append(mounts, x.Mounts...) mounts = append(mounts, y.Mounts...) x.Mounts = mounts volumes := make([]VolumeBinding, 0, len(x.Volumes)+len(y.Volumes)) volumes = append(volumes, x.Volumes...) volumes = append(volumes, y.Volumes...) x.Volumes = volumes ports := make([]Port, 0, len(x.Ports)+len(y.Ports)) ports = append(ports, x.Ports...) ports = append(ports, y.Ports...) x.Ports = ports if y.WorkingDir != "" { x.WorkingDir = y.WorkingDir } if y.Uid != nil { x.Uid = y.Uid } if y.Gid != nil { x.Gid = y.Gid } x.HostNetwork = x.HostNetwork || y.HostNetwork x.HostPIDNamespace = x.HostPIDNamespace || y.HostPIDNamespace return x }
Apply 'y' to 'x', returning a new structure. 'y' trumps.
Merge
go
flynn/flynn
host/types/types.go
https://github.com/flynn/flynn/blob/master/host/types/types.go
BSD-3-Clause
func routerMigrateScript(controllerEnv map[string]string) ([]byte, error) { tmpl, err := template.New("script").Parse(` set -e set -o pipefail main() { # get the controller db version local controller_version="$(controller_psql "COPY (SELECT MAX(id) FROM schema_migrations) TO STDOUT")" if [[ -z "${controller_version}" ]]; then fail "error getting controller db version" fi # only proceed if the controller database hasn't run the router # related migrations if [[ $controller_version -ge {{ .RouterMigrationStart }} ]]; then return fi # get the router db version local router_version="$(router_psql "COPY (SELECT MAX(id) FROM schema_migrations) TO STDOUT")" if [[ -z "${router_version}" ]]; then fail "error getting router db version" fi # dump the router db into the controller db router_dump | controller_restore # populate the controller schema_migrations table with the equivalent # migrations we just imported from the router controller_psql "INSERT INTO schema_migrations (id) SELECT generate_series({{ .RouterMigrationStart }}, $(({{ .RouterMigrationStart }} + $router_version - 1)))" } controller_psql() { local sql=$1 env {{ .ControllerEnv }} psql -c "${sql}" } controller_restore() { env {{ .ControllerEnv }} pg_restore -d "{{ .ControllerDB }}" -n public --no-owner --no-acl } router_psql() { local sql=$1 env $(router_env) psql -c "${sql}" } router_dump() { env $(router_env) pg_dump --format=custom --exclude-table schema_migrations --no-owner --no-acl } # router_env pulls the router PG* env vars from the controller db router_env() { controller_psql "COPY (SELECT string_agg(key || '=' || (value #>> '{}'), ' ') FROM releases, jsonb_each(env) WHERE release_id = (SELECT release_id FROM apps WHERE name = 'router' AND deleted_at IS NULL) AND key IN ('PGUSER', 'PGPASSWORD', 'PGDATABASE')) TO STDOUT" } fail() { echo $@ >&2 exit 1 } main "$@" `) if err != nil { return nil, err } data := struct { ControllerDB string ControllerEnv string RouterMigrationStart int64 }{ ControllerDB: controllerEnv["PGDATABASE"], ControllerEnv: fmt.Sprintf( "PGDATABASE=%q PGUSER=%q PGPASSWORD=%q", controllerEnv["PGDATABASE"], controllerEnv["PGUSER"], controllerEnv["PGPASSWORD"], ), RouterMigrationStart: controllerdata.RouterMigrationStart, } var buf bytes.Buffer if err := tmpl.Execute(&buf, &data); err != nil { return nil, err } return buf.Bytes(), nil }
routerMigrateScript renders a bash script to migrate the router database over to the controller database
routerMigrateScript
go
flynn/flynn
host/cli/bootstrap.go
https://github.com/flynn/flynn/blob/master/host/cli/bootstrap.go
BSD-3-Clause
func updateTUFClient(client *tuf.Client) error { _, err := client.Update() if err == nil || tuf.IsLatestSnapshot(err) { return nil } if err == tuf.ErrNoRootKeys { if err := client.Init(tufconfig.RootKeys, len(tufconfig.RootKeys)); err != nil { return err } return updateTUFClient(client) } return err }
updateTUFClient updates the given client, initializing and re-running the update if ErrNoRootKeys is returned.
updateTUFClient
go
flynn/flynn
host/cli/download.go
https://github.com/flynn/flynn/blob/master/host/cli/download.go
BSD-3-Clause
func getChannelVersion(configDir string, client *tuf.Client, log log15.Logger) (string, error) { log.Info("getting configured release channel") data, err := ioutil.ReadFile(filepath.Join(configDir, "channel.txt")) if err != nil { log.Error("error getting configured release channel", "err", err) return "", err } channel := strings.TrimSpace(string(data)) log.Info(fmt.Sprintf("determining latest version of %s release channel", channel)) version, err := tufutil.DownloadString(client, path.Join("channels", channel)) if err != nil { log.Error("error determining latest version", "err", err) return "", err } version = strings.TrimSpace(version) log.Info(fmt.Sprintf("latest %s version is %s", channel, version)) return version, nil }
getChannelVersion reads the locally configured release channel from <configDir>/channel.txt then gets the latest version for that channel using the TUF client.
getChannelVersion
go
flynn/flynn
host/cli/download.go
https://github.com/flynn/flynn/blob/master/host/cli/download.go
BSD-3-Clause
func updateAndExecLatest(configDir string, client *tuf.Client, log log15.Logger) error { log.Info("updating TUF data") if _, err := client.Update(); err != nil && !tuf.IsLatestSnapshot(err) { log.Error("error updating TUF client", "err", err) return err } version, err := getChannelVersion(configDir, client, log) if err != nil { return err } log.Info(fmt.Sprintf("downloading %s flynn-host binary", version)) gzTmp, err := tufutil.Download(client, path.Join(version, "flynn-host.gz")) if err != nil { log.Error("error downloading latest flynn-host binary", "err", err) return err } defer gzTmp.Close() gz, err := gzip.NewReader(gzTmp) if err != nil { log.Error("error creating gzip reader", "err", err) return err } defer gz.Close() tmp, err := ioutil.TempFile("", "flynn-host") if err != nil { log.Error("error creating temp file", "err", err) return err } _, err = io.Copy(tmp, gz) tmp.Close() if err != nil { log.Error("error decompressing gzipped flynn-host binary", "err", err) return err } if err := os.Chmod(tmp.Name(), 0755); err != nil { log.Error("error setting executable bit on tmp file", "err", err) return err } log.Info("executing latest flynn-host binary") argv := []string{tmp.Name()} argv = append(argv, os.Args[1:]...) argv = append(argv, "--is-latest") argv = append(argv, "--is-tempfile") return syscall.Exec(tmp.Name(), argv, os.Environ()) }
updateAndExecLatest updates the tuf DB, downloads the latest flynn-host binary to a temp file and execs it. Latest snapshot errors are ignored because, even though we may have the latest snapshot, the cluster may not be fully up to date (a previous update may have failed).
updateAndExecLatest
go
flynn/flynn
host/cli/update.go
https://github.com/flynn/flynn/blob/master/host/cli/update.go
BSD-3-Clause
func (d *Downloader) DownloadBinaries(dir string) (map[string]string, error) { if err := os.MkdirAll(dir, 0755); err != nil { return nil, fmt.Errorf("error creating bin dir: %s", err) } paths := make(map[string]string, len(binaries)) for _, bin := range binaries { path, err := d.downloadGzippedFile(bin, dir, true) if err != nil { return nil, err } if err := os.Chmod(path, 0755); err != nil { return nil, err } paths[bin] = path } // symlink flynn to flynn-linux-amd64 if err := symlink("flynn-linux-amd64", filepath.Join(dir, "flynn")); err != nil { return nil, err } return paths, nil }
DownloadBinaries downloads the Flynn binaries using the tuf client to the given dir with the version suffixed (e.g. /usr/local/bin/flynn-host.v20150726.0) and updates non-versioned symlinks.
DownloadBinaries
go
flynn/flynn
host/downloader/downloader.go
https://github.com/flynn/flynn/blob/master/host/downloader/downloader.go
BSD-3-Clause