本文整理汇总了Golang中github.com/wercker/wercker/core.EmitterFromContext函数的典型用法代码示例。如果您正苦于以下问题:Golang EmitterFromContext函数的具体用法?Golang EmitterFromContext怎么用?Golang EmitterFromContext使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了EmitterFromContext函数的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: Fetch
// Fetch an image (or update the local)
func (b *DockerBox) Fetch(ctx context.Context, env *util.Environment) (*docker.Image, error) {
// TODO(termie): maybe move the container manipulation outside of here?
client := b.client
e, err := core.EmitterFromContext(ctx)
if err != nil {
return nil, err
}
authenticator := b.config.Auth.ToAuthenticator(env)
b.repository = authenticator.Repository(env.Interpolate(b.repository))
b.Name = fmt.Sprintf("%s:%s", b.repository, b.tag)
// Shortcut to speed up local dev
if b.dockerOptions.DockerLocal {
image, err := client.InspectImage(env.Interpolate(b.Name))
if err != nil {
return nil, err
}
b.image = image
return image, nil
}
check, err := authenticator.CheckAccess(env.Interpolate(b.repository), auth.Pull)
if err != nil {
return nil, fmt.Errorf("Error interacting with this repository: %s %v", env.Interpolate(b.repository), err)
}
if !check {
return nil, fmt.Errorf("Not allowed to interact with this repository: %s:", env.Interpolate(b.repository))
}
// Create a pipe since we want a io.Reader but Docker expects a io.Writer
r, w := io.Pipe()
defer w.Close()
// emitStatusses in a different go routine
go EmitStatus(e, r, b.options)
options := docker.PullImageOptions{
// changeme if we have a private registry
// Registry: "docker.tsuru.io",
OutputStream: w,
RawJSONStream: true,
Repository: b.repository,
Tag: env.Interpolate(b.tag),
}
authConfig := docker.AuthConfiguration{
Username: authenticator.Username(),
Password: authenticator.Password(),
}
err = client.PullImage(options, authConfig)
if err != nil {
return nil, err
}
image, err := client.InspectImage(env.Interpolate(b.Name))
if err != nil {
return nil, err
}
b.image = image
return nil, err
}
开发者ID:wercker,项目名称:wercker,代码行数:60,代码来源:box.go
示例2: NewRunner
// NewRunner from global options
func NewRunner(ctx context.Context, options *core.PipelineOptions, dockerOptions *dockerlocal.DockerOptions, getPipeline pipelineGetter) (*Runner, error) {
e, err := core.EmitterFromContext(ctx)
if err != nil {
return nil, err
}
logger := util.RootLogger().WithField("Logger", "Runner")
// h, err := NewLogHandler()
// if err != nil {
// p.logger.WithField("Error", err).Panic("Unable to LogHandler")
// }
// h.ListenTo(e)
if options.Debug {
dh := core.NewDebugHandler()
dh.ListenTo(e)
}
l, err := event.NewLiteralLogHandler(options)
if err != nil {
logger.WithField("Error", err).Panic("Unable to event.LiteralLogHandler")
}
l.ListenTo(e)
var mh *event.MetricsEventHandler
if options.ShouldKeenMetrics {
mh, err = event.NewMetricsHandler(options)
if err != nil {
logger.WithField("Error", err).Panic("Unable to MetricsHandler")
}
mh.ListenTo(e)
}
var r *event.ReportHandler
if options.ShouldReport {
r, err := event.NewReportHandler(options.ReporterHost, options.ReporterKey)
if err != nil {
logger.WithField("Error", err).Panic("Unable to event.ReportHandler")
}
r.ListenTo(e)
}
return &Runner{
options: options,
dockerOptions: dockerOptions,
literalLogger: l,
metrics: mh,
reporter: r,
getPipeline: getPipeline,
logger: logger,
emitter: e,
formatter: &util.Formatter{options.GlobalOptions.ShowColors},
}, nil
}
开发者ID:sgoings,项目名称:wercker,代码行数:54,代码来源:runner.go
示例3: Run
// Run executes the service
func (b *InternalServiceBox) Run(ctx context.Context, env *util.Environment, links []string) (*docker.Container, error) {
e, err := core.EmitterFromContext(ctx)
if err != nil {
return nil, err
}
f := &util.Formatter{}
client, err := NewDockerClient(b.dockerOptions)
if err != nil {
return nil, err
}
// Import the environment and command
myEnv := dockerEnv(b.config.Env, env)
origEntrypoint := b.image.Config.Entrypoint
origCmd := b.image.Config.Cmd
cmdInfo := []string{}
var entrypoint []string
if b.entrypoint != "" {
entrypoint, err = shlex.Split(b.entrypoint)
if err != nil {
return nil, err
}
cmdInfo = append(cmdInfo, entrypoint...)
} else {
cmdInfo = append(cmdInfo, origEntrypoint...)
}
var cmd []string
if b.config.Cmd != "" {
cmd, err = shlex.Split(b.config.Cmd)
if err != nil {
return nil, err
}
cmdInfo = append(cmdInfo, cmd...)
} else {
cmdInfo = append(cmdInfo, origCmd...)
}
container, err := client.CreateContainer(
docker.CreateContainerOptions{
Name: b.getContainerName(),
Config: &docker.Config{
Image: b.Name,
Cmd: cmd,
Env: myEnv,
NetworkDisabled: b.networkDisabled,
DNS: b.dockerOptions.DockerDNS,
Entrypoint: entrypoint,
},
})
if err != nil {
return nil, err
}
out := []string{}
for _, part := range cmdInfo {
if strings.Contains(part, " ") {
out = append(out, fmt.Sprintf("%q", part))
} else {
out = append(out, part)
}
}
if b.options.Verbose {
b.logger.Println(f.Info(fmt.Sprintf("Starting service %s", b.ShortName), strings.Join(out, " ")))
}
client.StartContainer(container.ID, &docker.HostConfig{
DNS: b.dockerOptions.DockerDNS,
Links: links,
})
b.container = container
go func() {
status, err := client.WaitContainer(container.ID)
if err != nil {
b.logger.Errorln("Error waiting", err)
}
b.logger.Debugln("Service container finished with status code:", status, container.ID)
if status != 0 {
var errstream bytes.Buffer
var outstream bytes.Buffer
// recv := make(chan string)
// outputStream := NewReceiver(recv)
opts := docker.LogsOptions{
Container: container.ID,
Stdout: true,
Stderr: true,
ErrorStream: &errstream,
OutputStream: &outstream,
RawTerminal: false,
}
err = client.Logs(opts)
if err != nil {
b.logger.Panicln(err)
//.........这里部分代码省略.........
开发者ID:hughker,项目名称:wercker,代码行数:101,代码来源:service.go
示例4: Execute
// Execute commits the current container and pushes it to the configured
// registry
func (s *DockerPushStep) Execute(ctx context.Context, sess *core.Session) (int, error) {
// TODO(termie): could probably re-use the tansport's client
client, err := NewDockerClient(s.dockerOptions)
if err != nil {
return 1, err
}
e, err := core.EmitterFromContext(ctx)
if err != nil {
return 1, err
}
s.logger.WithFields(util.LogFields{
"Registry": s.registry,
"Repository": s.repository,
"Tags": s.tags,
"Message": s.message,
}).Debug("Push to registry")
// This is clearly only relevant to docker so we're going to dig into the
// transport internals a little bit to get the container ID
dt := sess.Transport().(*DockerTransport)
containerID := dt.containerID
auth := docker.AuthConfiguration{
Username: s.username,
Password: s.password,
Email: s.email,
ServerAddress: s.authServer,
}
if !s.dockerOptions.DockerLocal {
checkOpts := CheckAccessOptions{
Auth: auth,
Access: "write",
Repository: s.repository,
Registry: s.registry,
}
check, err := client.CheckAccess(checkOpts)
if err != nil {
s.logger.Errorln("Error during check access", err)
return -1, err
}
if !check {
s.logger.Errorln("Not allowed to interact with this repository:", s.repository)
return -1, fmt.Errorf("Not allowed to interact with this repository: %s", s.repository)
}
}
s.logger.Debugln("Init env:", s.data)
config := docker.Config{
Cmd: s.cmd,
Entrypoint: s.entrypoint,
WorkingDir: s.workingDir,
User: s.user,
Env: s.env,
StopSignal: s.stopSignal,
Labels: s.labels,
ExposedPorts: s.ports,
Volumes: s.volumes,
}
if len(s.tags) == 0 {
s.tags = []string{"latest"}
}
commitOpts := docker.CommitContainerOptions{
Container: containerID,
Repository: s.repository,
Author: s.author,
Message: s.message,
Run: &config,
Tag: s.tags[0],
}
s.logger.Debugln("Commit container:", containerID)
i, err := client.CommitContainer(commitOpts)
if err != nil {
return -1, err
}
s.logger.WithField("Image", i).Debug("Commit completed")
return s.tagAndPush(i.ID, e, client, auth)
}
开发者ID:rlugojr,项目名称:wercker,代码行数:86,代码来源:docker.go
示例5: executePipeline
func executePipeline(cmdCtx context.Context, options *core.PipelineOptions, dockerOptions *dockerlocal.DockerOptions, getter pipelineGetter) (*RunnerShared, error) {
// Boilerplate
soft := NewSoftExit(options.GlobalOptions)
logger := util.RootLogger().WithField("Logger", "Main")
e, err := core.EmitterFromContext(cmdCtx)
if err != nil {
return nil, err
}
f := &util.Formatter{options.GlobalOptions.ShowColors}
// Set up the runner
r, err := NewRunner(cmdCtx, options, dockerOptions, getter)
if err != nil {
return nil, err
}
// Main timer
mainTimer := util.NewTimer()
timer := util.NewTimer()
// These will be emitted at the end of the execution, we're going to be
// pessimistic and report that we failed, unless overridden at the end of the
// execution.
fullPipelineFinisher := r.StartFullPipeline(options)
pipelineArgs := &core.FullPipelineFinishedArgs{}
defer fullPipelineFinisher.Finish(pipelineArgs)
buildFinisher := r.StartBuild(options)
buildFinishedArgs := &core.BuildFinishedArgs{Box: nil, Result: "failed"}
defer buildFinisher.Finish(buildFinishedArgs)
// Debug information
DumpOptions(options)
// Do some sanity checks before starting
err = dockerlocal.RequireDockerEndpoint(dockerOptions)
if err != nil {
return nil, soft.Exit(err)
}
// Start copying code
logger.Println(f.Info("Executing pipeline"))
timer.Reset()
_, err = r.EnsureCode()
if err != nil {
e.Emit(core.Logs, &core.LogsArgs{
Stream: "stderr",
Logs: err.Error() + "\n",
})
return nil, soft.Exit(err)
}
err = r.CleanupOldBuilds()
if err != nil {
e.Emit(core.Logs, &core.LogsArgs{
Stream: "stderr",
Logs: err.Error() + "\n",
})
}
if options.Verbose {
logger.Printf(f.Success("Copied working dir", timer.String()))
}
// Setup environment is still a fairly special step, it needs
// to start our boxes and get everything set up
logger.Println(f.Info("Running step", "setup environment"))
timer.Reset()
shared, err := r.SetupEnvironment(cmdCtx)
if shared.box != nil {
if options.ShouldRemove {
defer shared.box.Clean()
}
defer shared.box.Stop()
}
if err != nil {
logger.Errorln(f.Fail("Step failed", "setup environment", timer.String()))
e.Emit(core.Logs, &core.LogsArgs{
Stream: "stderr",
Logs: err.Error() + "\n",
})
return nil, soft.Exit(err)
}
if options.Verbose {
logger.Printf(f.Success("Step passed", "setup environment", timer.String()))
}
// Expand our context object
box := shared.box
buildFinishedArgs.Box = box
pipeline := shared.pipeline
repoName := pipeline.DockerRepo()
tag := pipeline.DockerTag()
message := pipeline.DockerMessage()
shouldStore := options.ShouldArtifacts
// TODO(termie): hack for now, probably can be made into a naive class
var storeStep core.Step
if shouldStore {
storeStep = &core.ExternalStep{
//.........这里部分代码省略.........
开发者ID:rlugojr,项目名称:wercker,代码行数:101,代码来源:main.go
示例6: Fetch
// Fetch an image (or update the local)
func (b *DockerBox) Fetch(ctx context.Context, env *util.Environment) (*docker.Image, error) {
// TODO(termie): maybe move the container manipulation outside of here?
client := b.client
e, err := core.EmitterFromContext(ctx)
if err != nil {
return nil, err
}
// Shortcut to speed up local dev
if b.dockerOptions.DockerLocal {
image, err := client.InspectImage(env.Interpolate(b.Name))
if err != nil {
return nil, err
}
b.image = image
return image, nil
}
// Check for access to this image
auth := docker.AuthConfiguration{
Username: env.Interpolate(b.config.Username),
Password: env.Interpolate(b.config.Password),
}
checkOpts := CheckAccessOptions{
Auth: auth,
Access: "read",
Repository: env.Interpolate(b.repository),
Registry: env.Interpolate(b.config.Registry),
}
check, err := client.CheckAccess(checkOpts)
if err != nil {
b.logger.Errorln("Error during check access")
return nil, err
}
if !check {
b.logger.Errorln("Not allowed to interact with this repository:", b.repository)
return nil, fmt.Errorf("Not allowed to interact with this repository: %s", b.repository)
}
// Create a pipe since we want a io.Reader but Docker expects a io.Writer
r, w := io.Pipe()
defer w.Close()
// emitStatusses in a different go routine
go EmitStatus(e, r, b.options)
options := docker.PullImageOptions{
// changeme if we have a private registry
// Registry: "docker.tsuru.io",
OutputStream: w,
RawJSONStream: true,
Repository: env.Interpolate(b.repository),
Tag: env.Interpolate(b.tag),
}
err = client.PullImage(options, auth)
if err != nil {
return nil, err
}
image, err := client.InspectImage(env.Interpolate(b.Name))
if err != nil {
return nil, err
}
b.image = image
return nil, err
}
开发者ID:umcodemonkey,项目名称:wercker,代码行数:73,代码来源:box.go
示例7: Execute
// Execute does the actual export and upload of the container
func (s *StoreContainerStep) Execute(ctx context.Context, sess *core.Session) (int, error) {
e, err := core.EmitterFromContext(ctx)
if err != nil {
return -1, err
}
// TODO(termie): could probably re-use the tansport's client
client, err := NewDockerClient(s.dockerOptions)
if err != nil {
return -1, err
}
// This is clearly only relevant to docker so we're going to dig into the
// transport internals a little bit to get the container ID
dt := sess.Transport().(*DockerTransport)
containerID := dt.containerID
repoName := s.DockerRepo()
tag := s.DockerTag()
message := s.DockerMessage()
commitOpts := docker.CommitContainerOptions{
Container: containerID,
Repository: repoName,
Tag: tag,
Author: "wercker",
Message: message,
}
s.logger.Debugln("Commit container:", containerID)
i, err := client.CommitContainer(commitOpts)
if err != nil {
return -1, err
}
s.logger.WithField("Image", i).Debug("Commit completed")
e.Emit(core.Logs, &core.LogsArgs{
Logs: "Exporting container\n",
})
file, err := ioutil.TempFile(s.options.BuildPath(), "export-image-")
if err != nil {
s.logger.WithField("Error", err).Error("Unable to create temporary file")
return -1, err
}
hash := sha256.New()
w := snappystream.NewWriter(io.MultiWriter(file, hash))
exportImageOptions := docker.ExportImageOptions{
Name: repoName,
OutputStream: w,
}
err = client.ExportImage(exportImageOptions)
if err != nil {
s.logger.WithField("Error", err).Error("Unable to export image")
return -1, err
}
// Copy is done now, so close temporary file and set the calculatedHash
file.Close()
calculatedHash := hex.EncodeToString(hash.Sum(nil))
s.logger.WithFields(util.LogFields{
"SHA256": calculatedHash,
"TemporaryLocation": file.Name(),
}).Println("Export image successful")
key := core.GenerateBaseKey(s.options)
key = fmt.Sprintf("%s/%s", key, "docker.tar.sz")
s.artifact = &core.Artifact{
HostPath: file.Name(),
Key: key,
Bucket: s.options.S3Bucket,
ContentType: "application/x-snappy-framed",
Meta: map[string]*string{
"Sha256": &calculatedHash,
},
}
return 0, nil
}
开发者ID:hughker,项目名称:wercker,代码行数:82,代码来源:store.go
示例8: Execute
//.........这里部分代码省略.........
defer jsonFile.Close()
_, err = jsonFile.Write(js)
if err != nil {
return -1, err
}
err = jsonFile.Sync()
if err != nil {
return -1, err
}
// repositories file
repositoriesFile, err := os.OpenFile(s.options.HostPath("scratch", "repositories"), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return -1, err
}
defer repositoriesFile.Close()
_, err = repositoriesFile.Write([]byte(fmt.Sprintf(`{"%s":{`, s.authenticator.Repository(s.repository))))
if err != nil {
return -1, err
}
if len(s.tags) == 0 {
s.tags = []string{"latest"}
}
for i, tag := range s.tags {
_, err = repositoriesFile.Write([]byte(fmt.Sprintf(`"%s":"%s"`, tag, layerID)))
if err != nil {
return -1, err
}
if i != len(s.tags)-1 {
_, err = repositoriesFile.Write([]byte{','})
if err != nil {
return -1, err
}
}
}
_, err = repositoriesFile.Write([]byte{'}', '}'})
err = repositoriesFile.Sync()
if err != nil {
return -1, err
}
// Build our output tarball and start writing to it
imageFile, err := os.Create(s.options.HostPath("scratch.tar"))
if err != nil {
return -1, err
}
defer imageFile.Close()
err = util.TarPath(imageFile, s.options.HostPath("scratch"))
if err != nil {
return -1, err
}
imageFile.Close()
client, err := NewDockerClient(s.dockerOptions)
if err != nil {
return 1, err
}
// Check the auth
if !s.dockerOptions.DockerLocal {
check, err := s.authenticator.CheckAccess(s.repository, auth.Push)
if !check || err != nil {
s.logger.Errorln("Not allowed to interact with this repository:", s.repository)
return -1, fmt.Errorf("Not allowed to interact with this repository: %s", s.repository)
}
}
s.repository = s.authenticator.Repository(s.repository)
s.logger.WithFields(util.LogFields{
"Repository": s.repository,
"Tags": s.tags,
"Message": s.message,
}).Debug("Scratch push to registry")
// Okay, we can access it, do a docker load to import the image then push it
loadFile, err := os.Open(s.options.HostPath("scratch.tar"))
if err != nil {
return -1, err
}
defer loadFile.Close()
e, err := core.EmitterFromContext(ctx)
if err != nil {
return 1, err
}
err = client.LoadImage(docker.LoadImageOptions{InputStream: loadFile})
if err != nil {
return 1, err
}
return s.tagAndPush(layerID, e, client)
}
开发者ID:wercker,项目名称:wercker,代码行数:101,代码来源:docker.go
示例9: Execute
// Execute runs a command and optionally reloads it
func (s *WatchStep) Execute(ctx context.Context, sess *core.Session) (int, error) {
e, err := core.EmitterFromContext(ctx)
if err != nil {
return -1, err
}
// TODO(termie): PACKAGING make this a feature of session and remove
// the calls into its struct
// Start watching our stdout
stopListening := make(chan struct{})
defer func() { stopListening <- struct{}{} }()
go func() {
for {
select {
case line := <-sess.Recv():
e.Emit(core.Logs, &core.LogsArgs{
// Hidden: sess.logsHidden,
Logs: line,
})
// We need to make sure we stop eating the stdout from the container
// promiscuously when we finish out step
case <-stopListening:
return
}
}
}()
// cheating to get containerID
// TODO(termie): we should deal with this eventually
dt := sess.Transport().(*DockerTransport)
containerID := dt.containerID
// Set up a signal handler to end our step.
finishedStep := make(chan struct{})
stopWatchHandler := &util.SignalHandler{
ID: "stop-watch",
// Signal our stuff to stop and finish the step, return false to
// signify that we've handled the signal and don't process further
F: func() bool {
s.logger.Println("Keyboard interrupt detected, finishing step")
finishedStep <- struct{}{}
return false
},
}
util.GlobalSigint().Add(stopWatchHandler)
// NOTE(termie): I think the only way to exit this code is via this
// signal handler and the signal monkey removes handlers
// after it processes them, so this may be superfluous
defer util.GlobalSigint().Remove(stopWatchHandler)
// If we're not going to reload just run the thing once, synchronously
if !s.reload {
err := sess.Send(ctx, false, "set +e", s.Code)
if err != nil {
return 0, err
}
<-finishedStep
// ignoring errors
s.killProcesses(containerID, "INT")
return 0, nil
}
f := &util.Formatter{s.options.GlobalOptions.ShowColors}
s.logger.Info(f.Info("Reloading on file changes"))
doCmd := func() {
err := sess.Send(ctx, false, "set +e", s.Code)
if err != nil {
s.logger.Errorln(err)
return
}
open, err := exposedPortMaps(s.dockerOptions.DockerHost, s.options.PublishPorts)
if err != nil {
s.logger.Warnf(f.Info("There was a problem parsing your docker host."), err)
return
}
for _, uri := range open {
s.logger.Infof(f.Info("Forwarding %s to %s on the container."), uri.HostURI, uri.ContainerPort)
}
}
// Otherwise set up a watcher and do some magic
watcher, err := s.watch(s.options.ProjectPath)
if err != nil {
return -1, err
}
debounce := util.NewDebouncer(2 * time.Second)
done := make(chan struct{})
go func() {
for {
select {
case event := <-watcher.Events:
s.logger.Debugln("fsnotify event", event.String())
if event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Create == fsnotify.Create || event.Op&fsnotify.Remove == fsnotify.Remove {
if !strings.HasPrefix(filepath.Base(event.Name), ".") {
s.logger.Debug(f.Info("Modified file", event.Name))
debounce.Trigger()
}
}
case <-debounce.C:
//.........这里部分代码省略.........
开发者ID:wercker,项目名称:wercker,代码行数:101,代码来源:watchstep.go
注:本文中的github.com/wercker/wercker/core.EmitterFromContext函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论