本文整理匯總了Golang中github.com/flynn/flynn/controller/client.GetApp函數的典型用法代碼示例。如果您正苦於以下問題:Golang GetApp函數的具體用法?Golang GetApp怎麽用?Golang GetApp使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了GetApp函數的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: main
func main() {
appName := os.Args[2]
client, err := controller.NewClient("", os.Getenv("CONTROLLER_KEY"))
if err != nil {
log.Fatalln("Unable to connect to controller:", err)
}
app, err := client.GetApp(appName)
if err != nil {
log.Fatalln("Error retrieving app:", err)
}
fmt.Println(app.ID)
}
示例2: main
func main() {
client, err := controller.NewClient("", os.Getenv("CONTROLLER_AUTH_KEY"))
if err != nil {
log.Fatalln("Unable to connect to controller:", err)
}
// TODO: use discoverd http dialer here?
services, err := discoverd.Services("shelf", discoverd.DefaultTimeout)
if err != nil || len(services) < 1 {
log.Fatalf("Unable to discover shelf %q", err)
}
shelfHost := services[0].Addr
app := os.Args[1]
commit := os.Args[2]
_, err = client.GetApp(app)
if err == controller.ErrNotFound {
log.Fatalf("Unknown app %q", app)
} else if err != nil {
log.Fatalln("Error retrieving app:", err)
}
prevRelease, err := client.GetAppRelease(app)
if err == controller.ErrNotFound {
prevRelease = &ct.Release{}
} else if err != nil {
log.Fatalln("Error creating getting current app release:", err)
}
fmt.Printf("-----> Building %s...\n", app)
var output bytes.Buffer
slugURL := fmt.Sprintf("http://%s/%s.tgz", shelfHost, commit)
cmd := exec.Command("flynn/slugbuilder", slugURL)
cmd.Stdout = io.MultiWriter(os.Stdout, &output)
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
if buildpackURL, ok := prevRelease.Env["BUILDPACK_URL"]; ok {
cmd.Env = map[string]string{"BUILDPACK_URL": buildpackURL}
}
if err := cmd.Run(); err != nil {
log.Fatalln("Build failed:", err)
}
var types []string
if match := typesPattern.FindSubmatch(output.Bytes()); match != nil {
types = strings.Split(string(match[1]), ", ")
}
fmt.Printf("-----> Creating release...\n")
artifact := &ct.Artifact{URI: "docker://flynn/slugrunner"}
if err := client.CreateArtifact(artifact); err != nil {
log.Fatalln("Error creating artifact:", err)
}
release := &ct.Release{
ArtifactID: artifact.ID,
Env: prevRelease.Env,
}
procs := make(map[string]ct.ProcessType)
for _, t := range types {
proc := prevRelease.Processes[t]
proc.Cmd = []string{"start", t}
if t == "web" {
proc.Ports.TCP = 1
if proc.Env == nil {
proc.Env = make(map[string]string)
}
proc.Env["SD_NAME"] = app + "-web"
}
procs[t] = proc
}
release.Processes = procs
if release.Env == nil {
release.Env = make(map[string]string)
}
release.Env["SLUG_URL"] = slugURL
if err := client.CreateRelease(release); err != nil {
log.Fatalln("Error creating release:", err)
}
if err := client.SetAppRelease(app, release.ID); err != nil {
log.Fatalln("Error setting app release:", err)
}
fmt.Println("=====> Application deployed")
}
示例3: run
func run() error {
log := log15.New()
if *isTTY {
log.SetHandler(log15.StreamHandler(colorable.NewColorableStdout(), log15.TerminalFormat()))
}
var images map[string]*ct.Artifact
if err := json.NewDecoder(os.Stdin).Decode(&images); err != nil {
log.Error("error decoding images", "err", err)
return err
}
req, err := http.NewRequest("GET", "http://status-web.discoverd", nil)
if err != nil {
return err
}
req.Header = make(http.Header)
req.Header.Set("Accept", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Error("error getting cluster status", "err", err)
return err
}
defer res.Body.Close()
if res.StatusCode != 200 {
log.Error("cluster status is unhealthy", "code", res.StatusCode)
return fmt.Errorf("cluster is unhealthy")
}
var statusWrapper struct {
Data struct {
Detail map[string]status.Status
}
}
if err := json.NewDecoder(res.Body).Decode(&statusWrapper); err != nil {
log.Error("error decoding cluster status JSON", "err", err)
return err
}
statuses := statusWrapper.Data.Detail
instances, err := discoverd.GetInstances("controller", 10*time.Second)
if err != nil {
log.Error("error looking up controller in service discovery", "err", err)
return err
}
client, err := controller.NewClient("", instances[0].Meta["AUTH_KEY"])
if err != nil {
log.Error("error creating controller client", "err", err)
return err
}
log.Info("validating images")
for _, app := range updater.SystemApps {
if v := version.Parse(statuses[app.Name].Version); !v.Dev && app.MinVersion != "" && v.Before(version.Parse(app.MinVersion)) {
log.Info(
"not updating image of system app, can't upgrade from running version",
"app", app.Name,
"version", v,
)
continue
}
if _, ok := images[app.Name]; !ok {
err := fmt.Errorf("missing image: %s", app.Name)
log.Error(err.Error())
return err
}
}
log.Info("creating new image artifacts")
redisImage = images["redis"]
if err := client.CreateArtifact(redisImage); err != nil {
log.Error("error creating redis image artifact", "err", err)
return err
}
slugRunner = images["slugrunner"]
if err := client.CreateArtifact(slugRunner); err != nil {
log.Error("error creating slugrunner image artifact", "err", err)
return err
}
slugBuilder = images["slugbuilder"]
if err := client.CreateArtifact(slugBuilder); err != nil {
log.Error("error creating slugbuilder image artifact", "err", err)
return err
}
// deploy system apps in order first
for _, appInfo := range updater.SystemApps {
if appInfo.ImageOnly {
continue // skip ImageOnly updates
}
log := log.New("name", appInfo.Name)
log.Info("starting deploy of system app")
app, err := client.GetApp(appInfo.Name)
if err == controller.ErrNotFound && appInfo.Optional {
log.Info(
"skipped deploy of system app",
"reason", "optional app not present",
"app", appInfo.Name,
)
continue
//.........這裏部分代碼省略.........
示例4: TestAppDelete
func (s *ControllerSuite) TestAppDelete(t *c.C) {
client := s.controllerClient(t)
type test struct {
desc string
name string
create bool
useName bool
delErr error
}
for _, s := range []test{
{
desc: "delete existing app by name",
name: "app-delete-" + random.String(8),
create: true,
useName: true,
delErr: nil,
},
{
desc: "delete existing app by id",
name: "app-delete-" + random.String(8),
create: true,
useName: false,
delErr: nil,
},
{
desc: "delete existing UUID app by name",
name: random.UUID(),
create: true,
useName: true,
delErr: nil,
},
{
desc: "delete existing UUID app by id",
name: random.UUID(),
create: true,
useName: false,
delErr: nil,
},
{
desc: "delete non-existent app",
name: "i-dont-exist",
create: false,
useName: true,
delErr: controller.ErrNotFound,
},
{
desc: "delete non-existent UUID app",
name: random.UUID(),
create: false,
useName: true,
delErr: controller.ErrNotFound,
},
} {
debugf(t, "TestAppDelete: %s", s.desc)
app := &ct.App{Name: s.name}
if s.create {
t.Assert(client.CreateApp(app), c.IsNil)
}
appID := app.ID
if s.useName {
appID = app.Name
}
_, err := client.DeleteApp(appID)
t.Assert(err, c.Equals, s.delErr)
if s.delErr == nil {
_, err = client.GetApp(appID)
t.Assert(err, c.Equals, controller.ErrNotFound)
}
}
}
示例5: run
func run() error {
log := log15.New()
if *isTTY {
log.SetHandler(log15.StreamHandler(colorable.NewColorableStdout(), log15.TerminalFormat()))
}
var images map[string]string
if err := json.NewDecoder(os.Stdin).Decode(&images); err != nil {
log.Error("error decoding images", "err", err)
return err
}
instances, err := discoverd.GetInstances("flynn-controller", 10*time.Second)
if err != nil {
log.Error("error looking up controller in service discovery", "err", err)
return err
}
client, err := controller.NewClient("", instances[0].Meta["AUTH_KEY"])
if err != nil {
log.Error("error creating controller client", "err", err)
return err
}
log.Info("validating images")
uris := make(map[string]string, len(updater.SystemApps)+2)
for _, name := range append(updater.SystemApps, "slugbuilder", "slugrunner") {
image := "flynn/" + name
if name == "gitreceive" {
image = "flynn/receiver"
} else if name == "postgres" {
image = "flynn/postgresql"
}
uri, ok := images[image]
if !ok {
err := fmt.Errorf("missing image: %s", image)
log.Error(err.Error())
return err
}
uris[name] = uri
}
slugbuilderURI = uris["slugbuilder"]
slugrunnerURI = uris["slugrunner"]
// deploy system apps in order first
for _, name := range updater.SystemApps {
log := log.New("name", name)
log.Info("starting deploy of system app")
app, err := client.GetApp(name)
if err != nil {
log.Error("error getting app", "err", err)
return err
}
if err := deployApp(client, app, uris[name], log); err != nil {
if e, ok := err.(errDeploySkipped); ok {
log.Info("skipped deploy of system app", "reason", e.reason)
continue
}
return err
}
log.Info("finished deploy of system app")
}
// deploy all other apps
apps, err := client.AppList()
if err != nil {
log.Error("error getting apps", "err", err)
return err
}
for _, app := range apps {
if app.System() {
continue
}
log := log.New("name", app.Name)
log.Info("starting deploy of app to update slugrunner")
if err := deployApp(client, app, slugrunnerURI, log); err != nil {
if e, ok := err.(errDeploySkipped); ok {
log.Info("skipped deploy of app", "reason", e.reason)
continue
}
return err
}
log.Info("finished deploy of app")
}
return nil
}
示例6: main
func main() {
client, err := controller.NewClient("", os.Getenv("CONTROLLER_AUTH_KEY"))
if err != nil {
log.Fatalln("Unable to connect to controller:", err)
}
appName := os.Args[1]
app, err := client.GetApp(appName)
if err == controller.ErrNotFound {
log.Fatalf("Unknown app %q", appName)
} else if err != nil {
log.Fatalln("Error retrieving app:", err)
}
prevRelease, err := client.GetAppRelease(app.Name)
if err == controller.ErrNotFound {
prevRelease = &ct.Release{}
} else if err != nil {
log.Fatalln("Error getting current app release:", err)
}
fmt.Printf("-----> Building %s...\n", app.Name)
var output bytes.Buffer
slugURL := fmt.Sprintf("%s/%s.tgz", blobstoreURL, random.UUID())
cmd := exec.Command(exec.DockerImage(os.Getenv("SLUGBUILDER_IMAGE_URI")), slugURL)
cmd.Stdout = io.MultiWriter(os.Stdout, &output)
cmd.Stderr = os.Stderr
if len(prevRelease.Env) > 0 {
stdin, err := cmd.StdinPipe()
if err != nil {
log.Fatalln(err)
}
go appendEnvDir(os.Stdin, stdin, prevRelease.Env)
} else {
cmd.Stdin = os.Stdin
}
cmd.Env = make(map[string]string)
cmd.Env["BUILD_CACHE_URL"] = fmt.Sprintf("%s/%s-cache.tgz", blobstoreURL, app.ID)
if buildpackURL, ok := prevRelease.Env["BUILDPACK_URL"]; ok {
cmd.Env["BUILDPACK_URL"] = buildpackURL
}
if err := cmd.Run(); err != nil {
log.Fatalln("Build failed:", err)
}
var types []string
if match := typesPattern.FindSubmatch(output.Bytes()); match != nil {
types = strings.Split(string(match[1]), ", ")
}
fmt.Printf("-----> Creating release...\n")
artifact := &ct.Artifact{Type: "docker", URI: os.Getenv("SLUGRUNNER_IMAGE_URI")}
if err := client.CreateArtifact(artifact); err != nil {
log.Fatalln("Error creating artifact:", err)
}
release := &ct.Release{
ArtifactID: artifact.ID,
Env: prevRelease.Env,
}
procs := make(map[string]ct.ProcessType)
for _, t := range types {
proc := prevRelease.Processes[t]
proc.Cmd = []string{"start", t}
if t == "web" {
proc.Ports = []ct.Port{{
Port: 8080,
Proto: "tcp",
Service: &host.Service{
Name: app.Name + "-web",
Create: true,
Check: &host.HealthCheck{Type: "tcp"},
},
}}
}
procs[t] = proc
}
release.Processes = procs
if release.Env == nil {
release.Env = make(map[string]string)
}
release.Env["SLUG_URL"] = slugURL
if err := client.CreateRelease(release); err != nil {
log.Fatalln("Error creating release:", err)
}
if err := client.DeployAppRelease(app.Name, release.ID); err != nil {
log.Fatalln("Error deploying app release:", err)
}
fmt.Println("=====> Application deployed")
// If the app is new and the web process type exists,
// it should scale to one process after the release is created.
if _, ok := procs["web"]; ok && prevRelease.ID == "" {
formation := &ct.Formation{
AppID: app.ID,
//.........這裏部分代碼省略.........
示例7: runBootstrapBackup
//.........這裏部分代碼省略.........
}.RunWithState(ch, state)
if err != nil {
return err
}
// ensure the formation is correct in the database
if err := client.PutFormation(data.MongoDB.Formation()); err != nil {
return fmt.Errorf("error updating mongodb formation: %s", err)
}
cmd = exec.JobUsingHost(state.Hosts[0], artifacts["mongodb"], nil)
cmd.Args = []string{"mongorestore", "-h", "leader.mongodb.discoverd", "-u", "flynn", "-p", data.MongoDB.Release.Env["MONGO_PWD"], "--archive"}
cmd.Stdin = mongodb
meta = bootstrap.StepMeta{ID: "restore", Action: "restore-mongodb"}
ch <- &bootstrap.StepInfo{StepMeta: meta, State: "start", Timestamp: time.Now().UTC()}
out, err = cmd.CombinedOutput()
if os.Getenv("DEBUG") != "" {
fmt.Println(string(out))
}
if err != nil {
ch <- &bootstrap.StepInfo{
StepMeta: meta,
State: "error",
Error: fmt.Sprintf("error running mongodb restore: %s - %q", err, string(out)),
Err: err,
Timestamp: time.Now().UTC(),
}
return err
}
ch <- &bootstrap.StepInfo{StepMeta: meta, State: "done", Timestamp: time.Now().UTC()}
}
// get blobstore config
blobstoreRelease, err := client.GetAppRelease("blobstore")
if err != nil {
return fmt.Errorf("error getting blobstore release: %s", err)
}
blobstoreFormation, err := client.GetExpandedFormation("blobstore", blobstoreRelease.ID)
if err != nil {
return fmt.Errorf("error getting blobstore expanded formation: %s", err)
}
state.SetControllerKey(controllerKey)
ch <- &bootstrap.StepInfo{StepMeta: meta, State: "done", Timestamp: time.Now().UTC()}
// start the blobstore
blobstoreFormation.Artifacts = []*ct.Artifact{artifacts["blobstore"]}
_, err = bootstrap.Manifest{
step("blobstore", "run-app", &bootstrap.RunAppAction{
ExpandedFormation: blobstoreFormation,
}),
step("blobstore-wait", "wait", &bootstrap.WaitAction{
URL: "http://blobstore.discoverd",
Status: 200,
}),
}.RunWithState(ch, state)
if err != nil {
return err
}
// now that the controller and blobstore are up and controller
// migrations have run (so we know artifacts have a manifest column),
// migrate all artifacts to Flynn images
jsonb := func(v interface{}) []byte {
data, _ := json.Marshal(v)
return data
}
示例8: main
func main() {
client, err := controller.NewClient("", os.Getenv("CONTROLLER_AUTH_KEY"))
if err != nil {
log.Fatalln("Unable to connect to controller:", err)
}
// TODO: use discoverd http dialer here?
services, err := discoverd.Services("blobstore", discoverd.DefaultTimeout)
if err != nil || len(services) < 1 {
log.Fatalf("Unable to discover blobstore %q", err)
}
blobstoreHost := services[0].Addr
appName := os.Args[1]
app, err := client.GetApp(appName)
if err == controller.ErrNotFound {
log.Fatalf("Unknown app %q", appName)
} else if err != nil {
log.Fatalln("Error retrieving app:", err)
}
prevRelease, err := client.GetAppRelease(app.Name)
if err == controller.ErrNotFound {
prevRelease = &ct.Release{}
} else if err != nil {
log.Fatalln("Error creating getting current app release:", err)
}
fmt.Printf("-----> Building %s...\n", app.Name)
var output bytes.Buffer
slugURL := fmt.Sprintf("http://%s/%s.tgz", blobstoreHost, random.UUID())
cmd := exec.Command(exec.DockerImage("flynn/slugbuilder", os.Getenv("SLUGBUILDER_IMAGE_ID")), slugURL)
cmd.Stdout = io.MultiWriter(os.Stdout, &output)
cmd.Stderr = os.Stderr
stdin, err := cmd.StdinPipe()
if err != nil {
log.Fatalln(err)
}
go appendEnvDir(os.Stdin, stdin, prevRelease.Env)
if buildpackURL, ok := prevRelease.Env["BUILDPACK_URL"]; ok {
cmd.Env = map[string]string{"BUILDPACK_URL": buildpackURL}
}
if err := cmd.Run(); err != nil {
log.Fatalln("Build failed:", err)
}
var types []string
if match := typesPattern.FindSubmatch(output.Bytes()); match != nil {
types = strings.Split(string(match[1]), ", ")
}
fmt.Printf("-----> Creating release...\n")
artifact := &ct.Artifact{Type: "docker", URI: "https://registry.hub.docker.com/flynn/slugrunner?id=" + os.Getenv("SLUGRUNNER_IMAGE_ID")}
if err := client.CreateArtifact(artifact); err != nil {
log.Fatalln("Error creating artifact:", err)
}
release := &ct.Release{
ArtifactID: artifact.ID,
Env: prevRelease.Env,
}
procs := make(map[string]ct.ProcessType)
for _, t := range types {
proc := prevRelease.Processes[t]
proc.Cmd = []string{"start", t}
if t == "web" {
proc.Ports = []ct.Port{{Proto: "tcp"}}
if proc.Env == nil {
proc.Env = make(map[string]string)
}
proc.Env["SD_NAME"] = app.Name + "-web"
}
procs[t] = proc
}
release.Processes = procs
if release.Env == nil {
release.Env = make(map[string]string)
}
release.Env["SLUG_URL"] = slugURL
if err := client.CreateRelease(release); err != nil {
log.Fatalln("Error creating release:", err)
}
if err := client.SetAppRelease(app.Name, release.ID); err != nil {
log.Fatalln("Error setting app release:", err)
}
fmt.Println("=====> Application deployed")
// If the app is new and the web process type exists,
// it should scale to one process after the release is created.
if _, ok := procs["web"]; ok && prevRelease.ID == "" {
formation := &ct.Formation{
AppID: app.ID,
ReleaseID: release.ID,
Processes: map[string]int{"web": 1},
}
if err := client.PutFormation(formation); err != nil {
//.........這裏部分代碼省略.........
示例9: main
func main() {
client, err := controller.NewClient("", os.Getenv("CONTROLLER_KEY"))
if err != nil {
log.Fatalln("Unable to connect to controller:", err)
}
appName := os.Args[1]
app, err := client.GetApp(appName)
if err == controller.ErrNotFound {
log.Fatalf("Unknown app %q", appName)
} else if err != nil {
log.Fatalln("Error retrieving app:", err)
}
prevRelease, err := client.GetAppRelease(app.Name)
if err == controller.ErrNotFound {
prevRelease = &ct.Release{}
} else if err != nil {
log.Fatalln("Error getting current app release:", err)
}
fmt.Printf("-----> Building %s...\n", app.Name)
var output bytes.Buffer
slugURL := fmt.Sprintf("%s/%s.tgz", blobstoreURL, random.UUID())
cmd := exec.Command(exec.DockerImage(os.Getenv("SLUGBUILDER_IMAGE_URI")), slugURL)
cmd.Stdout = io.MultiWriter(os.Stdout, &output)
cmd.Stderr = os.Stderr
cmd.Meta = map[string]string{
"flynn-controller.app": app.ID,
"flynn-controller.app_name": app.Name,
"flynn-controller.release": prevRelease.ID,
"flynn-controller.type": "slugbuilder",
}
if len(prevRelease.Env) > 0 {
stdin, err := cmd.StdinPipe()
if err != nil {
log.Fatalln(err)
}
go appendEnvDir(os.Stdin, stdin, prevRelease.Env)
} else {
cmd.Stdin = os.Stdin
}
cmd.Env = make(map[string]string)
cmd.Env["BUILD_CACHE_URL"] = fmt.Sprintf("%s/%s-cache.tgz", blobstoreURL, app.ID)
if buildpackURL, ok := prevRelease.Env["BUILDPACK_URL"]; ok {
cmd.Env["BUILDPACK_URL"] = buildpackURL
}
for _, k := range []string{"SSH_CLIENT_KEY", "SSH_CLIENT_HOSTS"} {
if v := os.Getenv(k); v != "" {
cmd.Env[k] = v
}
}
if err := cmd.Run(); err != nil {
log.Fatalln("Build failed:", err)
}
var types []string
if match := typesPattern.FindSubmatch(output.Bytes()); match != nil {
types = strings.Split(string(match[1]), ", ")
}
fmt.Printf("-----> Creating release...\n")
artifact := &ct.Artifact{Type: "docker", URI: os.Getenv("SLUGRUNNER_IMAGE_URI")}
if err := client.CreateArtifact(artifact); err != nil {
log.Fatalln("Error creating artifact:", err)
}
release := &ct.Release{
ArtifactID: artifact.ID,
Env: prevRelease.Env,
}
procs := make(map[string]ct.ProcessType)
for _, t := range types {
proc := prevRelease.Processes[t]
proc.Cmd = []string{"start", t}
if t == "web" {
proc.Ports = []ct.Port{{
Port: 8080,
Proto: "tcp",
Service: &host.Service{
Name: app.Name + "-web",
Create: true,
Check: &host.HealthCheck{Type: "tcp"},
},
}}
}
procs[t] = proc
}
release.Processes = procs
if release.Env == nil {
release.Env = make(map[string]string)
}
release.Env["SLUG_URL"] = slugURL
if err := client.CreateRelease(release); err != nil {
log.Fatalln("Error creating release:", err)
}
//.........這裏部分代碼省略.........
示例10: main
func main() {
client, err := controller.NewClient("", os.Getenv("CONTROLLER_KEY"))
if err != nil {
log.Fatalln("Unable to connect to controller:", err)
}
usage := `
Usage: flynn-receiver <app> <rev> [-e <var>=<val>]... [-m <key>=<val>]...
Options:
-e,--env <var>=<val>
-m,--meta <key>=<val>
`[1:]
args, _ := docopt.Parse(usage, nil, true, version.String(), false)
appName := args.String["<app>"]
env, err := parsePairs(args, "--env")
if err != nil {
log.Fatal(err)
}
meta, err := parsePairs(args, "--meta")
if err != nil {
log.Fatal(err)
}
app, err := client.GetApp(appName)
if err == controller.ErrNotFound {
log.Fatalf("Unknown app %q", appName)
} else if err != nil {
log.Fatalln("Error retrieving app:", err)
}
prevRelease, err := client.GetAppRelease(app.Name)
if err == controller.ErrNotFound {
prevRelease = &ct.Release{}
} else if err != nil {
log.Fatalln("Error getting current app release:", err)
}
fmt.Printf("-----> Building %s...\n", app.Name)
jobEnv := make(map[string]string)
jobEnv["BUILD_CACHE_URL"] = fmt.Sprintf("%s/%s-cache.tgz", blobstoreURL, app.ID)
if buildpackURL, ok := env["BUILDPACK_URL"]; ok {
jobEnv["BUILDPACK_URL"] = buildpackURL
} else if buildpackURL, ok := prevRelease.Env["BUILDPACK_URL"]; ok {
jobEnv["BUILDPACK_URL"] = buildpackURL
}
for _, k := range []string{"SSH_CLIENT_KEY", "SSH_CLIENT_HOSTS"} {
if v := os.Getenv(k); v != "" {
jobEnv[k] = v
}
}
slugURL := fmt.Sprintf("%s/%s.tgz", blobstoreURL, random.UUID())
cmd := exec.Job(exec.DockerImage(os.Getenv("SLUGBUILDER_IMAGE_URI")), &host.Job{
Config: host.ContainerConfig{
Cmd: []string{slugURL},
Env: jobEnv,
Stdin: true,
DisableLog: true,
},
Partition: "background",
Metadata: map[string]string{
"flynn-controller.app": app.ID,
"flynn-controller.app_name": app.Name,
"flynn-controller.release": prevRelease.ID,
"flynn-controller.type": "slugbuilder",
},
})
var output bytes.Buffer
cmd.Stdout = io.MultiWriter(os.Stdout, &output)
cmd.Stderr = os.Stderr
if len(prevRelease.Env) > 0 {
stdin, err := cmd.StdinPipe()
if err != nil {
log.Fatalln(err)
}
go appendEnvDir(os.Stdin, stdin, prevRelease.Env)
} else {
cmd.Stdin = os.Stdin
}
if err := cmd.Run(); err != nil {
log.Fatalln("Build failed:", err)
}
var types []string
if match := typesPattern.FindSubmatch(output.Bytes()); match != nil {
types = strings.Split(string(match[1]), ", ")
}
fmt.Printf("-----> Creating release...\n")
artifact := &ct.Artifact{Type: "docker", URI: os.Getenv("SLUGRUNNER_IMAGE_URI")}
if err := client.CreateArtifact(artifact); err != nil {
log.Fatalln("Error creating artifact:", err)
}
release := &ct.Release{
//.........這裏部分代碼省略.........
示例11: run
func run() error {
client, err := controller.NewClient("", os.Getenv("CONTROLLER_KEY"))
if err != nil {
return fmt.Errorf("Unable to connect to controller: %s", err)
}
usage := `
Usage: flynn-receiver <app> <rev> [-e <var>=<val>]... [-m <key>=<val>]...
Options:
-e,--env <var>=<val>
-m,--meta <key>=<val>
`[1:]
args, _ := docopt.Parse(usage, nil, true, version.String(), false)
appName := args.String["<app>"]
env, err := parsePairs(args, "--env")
if err != nil {
return err
}
meta, err := parsePairs(args, "--meta")
if err != nil {
return err
}
slugBuilder, err := client.GetArtifact(os.Getenv("SLUGBUILDER_IMAGE_ID"))
if err != nil {
return fmt.Errorf("Error getting slugbuilder image: %s", err)
}
slugRunnerID := os.Getenv("SLUGRUNNER_IMAGE_ID")
if _, err := client.GetArtifact(slugRunnerID); err != nil {
return fmt.Errorf("Error getting slugrunner image: %s", err)
}
app, err := client.GetApp(appName)
if err == controller.ErrNotFound {
return fmt.Errorf("Unknown app %q", appName)
} else if err != nil {
return fmt.Errorf("Error retrieving app: %s", err)
}
prevRelease, err := client.GetAppRelease(app.Name)
if err == controller.ErrNotFound {
prevRelease = &ct.Release{}
} else if err != nil {
return fmt.Errorf("Error getting current app release: %s", err)
}
fmt.Printf("-----> Building %s...\n", app.Name)
slugImageID := random.UUID()
jobEnv := map[string]string{
"BUILD_CACHE_URL": fmt.Sprintf("%s/%s-cache.tgz", blobstoreURL, app.ID),
"CONTROLLER_KEY": os.Getenv("CONTROLLER_KEY"),
"SLUG_IMAGE_ID": slugImageID,
}
if buildpackURL, ok := env["BUILDPACK_URL"]; ok {
jobEnv["BUILDPACK_URL"] = buildpackURL
} else if buildpackURL, ok := prevRelease.Env["BUILDPACK_URL"]; ok {
jobEnv["BUILDPACK_URL"] = buildpackURL
}
for _, k := range []string{"SSH_CLIENT_KEY", "SSH_CLIENT_HOSTS"} {
if v := os.Getenv(k); v != "" {
jobEnv[k] = v
}
}
job := &host.Job{
Config: host.ContainerConfig{
Args: []string{"/builder/build.sh"},
Env: jobEnv,
Stdin: true,
DisableLog: true,
},
Partition: "background",
Metadata: map[string]string{
"flynn-controller.app": app.ID,
"flynn-controller.app_name": app.Name,
"flynn-controller.release": prevRelease.ID,
"flynn-controller.type": "slugbuilder",
},
Resources: resource.Defaults(),
}
if sb, ok := prevRelease.Processes["slugbuilder"]; ok {
job.Resources = sb.Resources
} else if rawLimit := os.Getenv("SLUGBUILDER_DEFAULT_MEMORY_LIMIT"); rawLimit != "" {
if limit, err := resource.ParseLimit(resource.TypeMemory, rawLimit); err == nil {
job.Resources[resource.TypeMemory] = resource.Spec{Limit: &limit, Request: &limit}
}
}
cmd := exec.Job(slugBuilder, job)
cmd.Volumes = []*ct.VolumeReq{{Path: "/tmp", DeleteOnStop: true}}
var output bytes.Buffer
cmd.Stdout = io.MultiWriter(os.Stdout, &output)
cmd.Stderr = os.Stderr
releaseEnv := make(map[string]string, len(env))
if prevRelease.Env != nil {
for k, v := range prevRelease.Env {
//.........這裏部分代碼省略.........
示例12: runClusterBackup
func runClusterBackup(args *docopt.Args) error {
client, err := getClusterClient()
if err != nil {
return err
}
var bar *pb.ProgressBar
if term.IsTerminal(os.Stderr.Fd()) {
bar = pb.New(0)
bar.SetUnits(pb.U_BYTES)
bar.ShowBar = false
bar.ShowSpeed = true
bar.Output = os.Stderr
bar.Start()
}
var dest io.Writer = os.Stdout
if filename := args.String["--file"]; filename != "" {
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
dest = f
}
fmt.Fprintln(os.Stderr, "Creating cluster backup...")
tw := NewTarWriter("flynn-backup-"+time.Now().UTC().Format("2006-01-02_150405"), dest)
defer tw.Close()
// get app and release details for key apps
data := make(map[string]*ct.ExpandedFormation, 4)
for _, name := range []string{"postgres", "discoverd", "flannel", "controller"} {
app, err := client.GetApp(name)
if err != nil {
return fmt.Errorf("error getting %s app details: %s", name, err)
}
release, err := client.GetAppRelease(app.ID)
if err != nil {
return fmt.Errorf("error getting %s app release: %s", name, err)
}
formation, err := client.GetFormation(app.ID, release.ID)
if err != nil {
return fmt.Errorf("error getting %s app formation: %s", name, err)
}
artifact, err := client.GetArtifact(release.ArtifactID)
if err != nil {
return fmt.Errorf("error getting %s app artifact: %s", name, err)
}
data[name] = &ct.ExpandedFormation{
App: app,
Release: release,
Artifact: artifact,
Processes: formation.Processes,
}
}
if err := tw.WriteJSON("flynn.json", data); err != nil {
return err
}
config := &runConfig{
App: "postgres",
Release: data["postgres"].Release.ID,
Entrypoint: []string{"sh"},
Args: []string{"-c", "pg_dumpall --clean --if-exists | gzip -9"},
Env: map[string]string{
"PGHOST": "leader.postgres.discoverd",
"PGUSER": "flynn",
"PGPASSWORD": data["postgres"].Release.Env["PGPASSWORD"],
},
DisableLog: true,
}
if err := tw.WriteCommandOutput(client, "postgres.sql.gz", config, bar); err != nil {
return fmt.Errorf("error dumping database: %s", err)
}
if bar != nil {
bar.Finish()
}
fmt.Fprintln(os.Stderr, "Backup complete.")
return nil
}
示例13: TestDeployController
func (s *SchedulerSuite) TestDeployController(t *c.C) {
if testCluster == nil {
t.Skip("cannot determine test cluster size")
}
// get the current controller release
client := s.controllerClient(t)
app, err := client.GetApp("controller")
t.Assert(err, c.IsNil)
release, err := client.GetAppRelease(app.ID)
t.Assert(err, c.IsNil)
// create a controller deployment
release.ID = ""
t.Assert(client.CreateRelease(release), c.IsNil)
deployment, err := client.CreateDeployment(app.ID, release.ID)
t.Assert(err, c.IsNil)
// use a function to create the event stream as a new stream will be needed
// after deploying the controller
var events chan *ct.DeploymentEvent
var eventStream stream.Stream
connectStream := func() {
events = make(chan *ct.DeploymentEvent)
err := attempt.Strategy{
Total: 10 * time.Second,
Delay: 500 * time.Millisecond,
}.Run(func() (err error) {
eventStream, err = client.StreamDeployment(deployment.ID, events)
return
})
t.Assert(err, c.IsNil)
}
connectStream()
defer eventStream.Close()
// wait for the deploy to complete (this doesn't wait for specific events
// due to the fact that when the deployer deploys itself, some events will
// not get sent)
loop:
for {
select {
case e, ok := <-events:
if !ok {
// reconnect the stream as it may of been closed
// due to the controller being deployed
debug(t, "reconnecting deployment event stream")
connectStream()
continue
}
debugf(t, "got deployment event: %s %s", e.JobType, e.JobState)
switch e.Status {
case "complete":
break loop
case "failed":
t.Fatal("the deployment failed")
}
case <-time.After(60 * time.Second):
t.Fatal("timed out waiting for the deploy to complete")
}
}
// check the correct controller jobs are running
hosts, err := s.clusterClient(t).ListHosts()
t.Assert(err, c.IsNil)
actual := make(map[string]map[string]int)
for _, host := range hosts {
for _, job := range host.Jobs {
appID := job.Metadata["flynn-controller.app"]
if appID != app.ID {
continue
}
releaseID := job.Metadata["flynn-controller.release"]
if _, ok := actual[releaseID]; !ok {
actual[releaseID] = make(map[string]int)
}
typ := job.Metadata["flynn-controller.type"]
actual[releaseID][typ]++
}
}
expected := map[string]map[string]int{release.ID: {
"web": 2,
"deployer": 2,
"scheduler": testCluster.Size(),
}}
t.Assert(actual, c.DeepEquals, expected)
}