本文整理汇总了Golang中github.com/openshift/geard/jobs.Response类的典型用法代码示例。如果您正苦于以下问题:Golang Response类的具体用法?Golang Response怎么用?Golang Response使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Response类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Execute
func (j *PatchEnvironmentRequest) Execute(resp jobs.Response) {
if err := j.Write(true); err != nil {
resp.Failure(ErrEnvironmentUpdateFailed)
return
}
resp.Success(jobs.ResponseOk)
}
示例2: Execute
func (j *ListContainersRequest) Execute(resp jobs.Response) {
r := &ListContainersResponse{make(ContainerUnitResponses, 0)}
if err := unitsMatching(reContainerUnits, func(name string, unit *dbus.UnitStatus) {
if unit.LoadState == "not-found" || unit.LoadState == "masked" {
return
}
r.Containers = append(r.Containers, ContainerUnitResponse{
UnitResponse{
name,
unit.ActiveState,
unit.SubState,
},
unit.LoadState,
unit.JobType,
"",
})
}); err != nil {
log.Printf("list_units: Unable to list units from systemd: %v", err)
resp.Failure(ErrListContainersFailed)
return
}
r.Sort()
resp.SuccessWithData(jobs.ResponseOk, r)
}
示例3: Execute
func (j *CreateKeysRequest) Execute(resp jobs.Response) {
failedKeys := []KeyFailure{}
for i := range j.Keys {
key := j.Keys[i]
locator, err := key.Create()
if err != nil {
failedKeys = append(failedKeys, KeyFailure{i, &key, err})
continue
}
for k := range j.Permissions {
if err := j.Permissions[k].Create(locator); err != nil {
failedKeys = append(failedKeys, KeyFailure{i, &key, err})
continue
}
}
}
if len(failedKeys) > 0 {
data := make([]KeyStructuredFailure, len(failedKeys))
for i := range failedKeys {
data[i] = KeyStructuredFailure{failedKeys[i].Index, failedKeys[i].Reason.Error()}
log.Printf("Failure %d: %+v", failedKeys[i].Index, failedKeys[i].Reason)
}
resp.Failure(jobs.StructuredJobError{jobs.SimpleError{jobs.ResponseError, "Not all keys were completed"}, data})
} else {
resp.Success(jobs.ResponseOk)
}
}
示例4: Execute
func (j AddAliasRequest) Execute(resp jobs.Response) {
value, ok := router.GlobalRoutes[j.Frontend]
if ok {
router.AddAlias(j.Alias, value.Name)
} else {
router.CreateFrontend(j.Frontend, j.Alias)
}
resp.Success(jobs.ResponseOk)
}
示例5: Execute
func (j *LinkContainersRequest) Execute(resp jobs.Response) {
for i := range j.Links {
if errw := j.Links[i].NetworkLinks.Write(j.Links[i].Id.NetworkLinksPathFor(), false); errw != nil {
resp.Failure(ErrLinkContainersFailed)
return
}
}
resp.Success(jobs.ResponseOk)
}
示例6: Execute
func (j *ContainerPortsRequest) Execute(resp jobs.Response) {
portPairs, err := containers.GetExistingPorts(j.Id)
if err != nil {
log.Printf("job_container_ports_log: Unable to find unit: %s\n", err.Error())
resp.Failure(ErrContainerNotFound)
return
}
resp.SuccessWithData(jobs.ResponseAccepted, ContainerPortsResponse{portPairs})
}
示例7: Execute
func (j *ContainerLogRequest) Execute(resp jobs.Response) {
if _, err := os.Stat(j.Id.UnitPathFor()); err != nil {
resp.Failure(ErrContainerNotFound)
return
}
w := resp.SuccessWithWrite(jobs.ResponseOk, true, false)
err := systemd.WriteLogsTo(w, j.Id.UnitNameFor(), 30, time.After(30*time.Second))
if err != nil {
log.Printf("job_container_log: Unable to fetch journal logs: %s\n", err.Error())
}
}
示例8: Execute
func (j *ContainerStatusRequest) Execute(resp jobs.Response) {
if _, err := os.Stat(j.Id.UnitPathFor()); err != nil {
//log.Printf("container_status: Can't stat unit: %v", err)
resp.Failure(ErrContainerNotFound)
return
}
w := resp.SuccessWithWrite(jobs.ResponseOk, true, false)
err := systemd.WriteStatusTo(w, j.Id.UnitNameFor())
if err != nil {
log.Printf("container_status: Unable to fetch container status logs: %s\n", err.Error())
}
}
示例9: Execute
func (j UpdateFrontendRequest) Execute(resp jobs.Response) {
// detach empty frontends
for _, frontend := range j.Frontends {
if frontend.BackendId == "" {
frontend.Remove()
}
}
errs := []backendError{}
for _, backend := range j.Backends {
if err := utils.WriteToPathExclusive(backend.Id.BackendPathFor(), 0554, backend); err != nil {
errs = append(errs, backendError{backend.Id, err})
}
}
if len(errs) != 0 {
log.Printf("Unable to persist some backends: %+v", errs)
resp.Failure(ErrBackendWriteFailed)
return
}
resp.Success(jobs.ResponseOk)
}
示例10: Execute
func (j *ContentRequest) Execute(resp jobs.Response) {
switch j.Type {
case ContentTypeEnvironment:
id, errr := containers.NewIdentifier(j.Locator)
if errr != nil {
resp.Failure(jobs.SimpleError{jobs.ResponseInvalidRequest, fmt.Sprintf("Invalid environment identifier: %s", errr.Error())})
return
}
file, erro := os.Open(id.EnvironmentPathFor())
if erro != nil {
resp.Failure(ErrEnvironmentNotFound)
return
}
defer file.Close()
w := resp.SuccessWithWrite(jobs.ResponseOk, false, false)
if _, err := io.Copy(w, file); err != nil {
log.Printf("job_content: Unable to write environment file: %+v", err)
return
}
}
}
示例11: Execute
func (j *ListImagesRequest) Execute(resp jobs.Response) {
// TODO: config item for docker port
dockerClient, err := docker.NewClient(j.DockerSocket)
if err != nil {
log.Printf("job_list_images: Couldn't connect to docker: %+v", err)
resp.Failure(ErrListImagesFailed)
return
}
imgs, err := dockerClient.ListImages(false)
if err != nil {
log.Printf("job_list_images: Couldn't connect to docker: %+v", err)
resp.Failure(ErrListImagesFailed)
return
}
w := resp.SuccessWithWrite(jobs.ResponseAccepted, true, false)
for _, img := range imgs {
fmt.Fprintf(w, "%+v\n", img.RepoTags[0])
}
}
示例12: Execute
func (req *InstallContainerRequest) Execute(resp jobs.Response) {
id := req.Id
unitName := id.UnitNameFor()
unitPath := id.UnitPathFor()
unitVersionPath := id.VersionedUnitPathFor(req.RequestIdentifier.String())
socketUnitName := id.SocketUnitNameFor()
socketUnitPath := id.SocketUnitPathFor()
var socketActivationType string
if req.SocketActivation {
socketActivationType = "enabled"
if !req.SkipSocketProxy {
socketActivationType = "proxied"
}
}
// attempt to download the environment if it is remote
env := req.Environment
if env != nil {
if err := env.Fetch(100 * 1024); err != nil {
resp.Failure(ErrContainerCreateFailed)
return
}
if env.Empty() {
env = nil
}
}
// open and lock the base path (to prevent simultaneous updates)
state, exists, err := utils.OpenFileExclusive(unitPath, 0664)
if err != nil {
log.Print("install_container: Unable to lock unit file: ", err)
resp.Failure(ErrContainerCreateFailed)
}
defer state.Close()
// write a new file to disk that describes the new service
unit, err := utils.CreateFileExclusive(unitVersionPath, 0664)
if err != nil {
log.Print("install_container: Unable to open unit file definition: ", err)
resp.Failure(ErrContainerCreateFailed)
return
}
defer unit.Close()
// if this is an existing container, read the currently reserved ports
existingPorts := port.PortPairs{}
if exists {
existingPorts, err = containers.GetExistingPorts(id)
if err != nil {
if _, ok := err.(*os.PathError); !ok {
log.Print("install_container: Unable to read existing ports from file: ", err)
resp.Failure(ErrContainerCreateFailed)
return
}
}
}
// allocate and reserve ports for this container
reserved, erra := port.AtomicReserveExternalPorts(unitVersionPath, req.Ports, existingPorts)
if erra != nil {
log.Printf("install_container: Unable to reserve external ports: %+v", erra)
resp.Failure(ErrContainerCreateFailedPortsReserved)
return
}
if len(reserved) > 0 {
resp.WritePendingSuccess(PendingPortMappingName, reserved)
}
var portSpec string
if req.Simple && len(reserved) == 0 {
portSpec = "-P"
} else {
portSpec = dockerPortSpec(reserved)
}
// write the environment to disk
var environmentPath string
if env != nil {
if errw := env.Write(false); errw != nil {
resp.Failure(ErrContainerCreateFailed)
return
}
environmentPath = env.Id.EnvironmentPathFor()
}
// write the network links (if any) to disk
if req.NetworkLinks != nil {
if errw := req.NetworkLinks.Write(id.NetworkLinksPathFor(), false); errw != nil {
resp.Failure(ErrContainerCreateFailed)
return
}
}
slice := "container-small"
// write the definition unit file
args := csystemd.ContainerUnit{
Id: id,
Image: req.Image,
//.........这里部分代码省略.........
示例13: Execute
func (j CreateRepositoryRequest) Execute(resp jobs.Response) {
unitName := fmt.Sprintf("job-create-repo-%s.service", j.RequestId.String())
path := j.Id.HomePath()
if _, err := os.Stat(path); err == nil || !os.IsNotExist(err) {
resp.Failure(ErrRepositoryAlreadyExists)
return
}
conn, errc := systemd.NewConnection()
if errc != nil {
log.Print("create_repository:", errc)
return
}
if err := conn.Subscribe(); err != nil {
log.Print("create_repository:", err)
return
}
defer conn.Unsubscribe()
// make subscription global for efficiency
changes, errch := conn.SubscribeUnitsCustom(1*time.Second, 2,
func(s1 *dbus.UnitStatus, s2 *dbus.UnitStatus) bool {
return true
},
func(unit string) bool {
return unit != unitName
})
stdout, err := systemd.ProcessLogsForUnit(unitName)
if err != nil {
stdout = utils.EmptyReader
log.Printf("create_repository: Unable to fetch build logs: %+v", err)
}
defer stdout.Close()
startCmd := []string{
filepath.Join("/", "usr", "bin", "gear"),
"init-repo",
string(j.Id),
}
if j.CloneUrl != "" {
startCmd = append(startCmd, j.CloneUrl)
}
status, err := conn.StartTransientUnit(
unitName,
"fail",
dbus.PropExecStart(startCmd, true),
dbus.PropDescription(fmt.Sprintf("Create repository %s", j.Id)),
dbus.PropRemainAfterExit(true),
dbus.PropSlice("githost.slice"),
)
if err != nil {
log.Printf("create_repository: Could not start unit %s: %s", unitName, systemd.SprintSystemdError(err))
resp.Failure(ErrRepositoryCreateFailed)
return
} else if status != "done" {
log.Printf("create_repository: Unit did not return 'done'")
resp.Failure(ErrRepositoryCreateFailed)
return
}
w := resp.SuccessWithWrite(jobs.ResponseAccepted, true, false)
go io.Copy(w, stdout)
wait:
for {
select {
case c := <-changes:
if changed, ok := c[unitName]; ok {
if changed.SubState != "running" {
fmt.Fprintf(w, "Repository created succesfully\n")
break wait
}
}
case err := <-errch:
fmt.Fprintf(w, "Error %+v\n", err)
case <-time.After(10 * time.Second):
log.Print("create_repository:", "timeout")
break wait
}
}
stdout.Close()
}
示例14: Execute
func (j GitArchiveContentRequest) Execute(resp jobs.Response) {
w := resp.SuccessWithWrite(jobs.ResponseOk, false, false)
if err := writeGitRepositoryArchive(w, j.RepositoryId.RepositoryPathFor(), j.Ref); err != nil {
log.Printf("job_content: Invalid git repository stream: %v", err)
}
}
示例15: ExecuteRemote
func (h *HttpTransport) ExecuteRemote(baseUrl *url.URL, job RemoteExecutable, res jobs.Response) error {
reader, writer := io.Pipe()
httpreq, errn := http.NewRequest(job.HttpMethod(), baseUrl.String(), reader)
if errn != nil {
return errn
}
id := job.MarshalRequestIdentifier()
if len(id) == 0 {
id = jobs.NewRequestIdentifier()
}
query := &url.Values{}
job.MarshalUrlQuery(query)
req := httpreq
req.Header.Set("X-Request-Id", id.String())
req.Header.Set("If-Match", "api="+ApiVersion())
req.Header.Set("Content-Type", "application/json")
//TODO: introduce API version per job
//TODO: content request signing for GETs
req.URL.Path = job.HttpPath()
req.URL.RawQuery = query.Encode()
go func() {
if err := job.MarshalHttpRequestBody(writer); err != nil {
log.Printf("http_remote: Error when writing to http: %v", err)
writer.CloseWithError(err)
} else {
writer.Close()
}
}()
resp, err := h.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
isJson := resp.Header.Get("Content-Type") == "application/json"
switch code := resp.StatusCode; {
case code == 202:
if isJson {
return errors.New("Decoding of streaming JSON has not been implemented")
}
data, err := job.UnmarshalHttpResponse(resp.Header, nil, ResponseTable)
if err != nil {
return err
}
if pending, ok := data.(map[string]interface{}); ok {
for k := range pending {
res.WritePendingSuccess(k, pending[k])
}
}
w := res.SuccessWithWrite(jobs.ResponseOk, false, false)
if _, err := io.Copy(w, resp.Body); err != nil {
return err
}
case code == 204:
data, err := job.UnmarshalHttpResponse(resp.Header, nil, ResponseTable)
if err != nil {
return err
}
if pending, ok := data.(map[string]interface{}); ok {
for k := range pending {
res.WritePendingSuccess(k, pending[k])
}
}
res.Success(jobs.ResponseOk)
case code >= 200 && code < 300:
if !isJson {
return errors.New(fmt.Sprintf("remote: Response with %d status code had content type %s (should be application/json)", code, resp.Header.Get("Content-Type")))
}
data, err := job.UnmarshalHttpResponse(nil, resp.Body, ResponseJson)
if err != nil {
return err
}
res.SuccessWithData(jobs.ResponseOk, data)
default:
if isJson {
decoder := json.NewDecoder(resp.Body)
data := httpFailureResponse{}
if err := decoder.Decode(&data); err != nil {
return err
}
res.Failure(jobs.SimpleError{jobs.ResponseError, data.Message})
return nil
}
io.Copy(os.Stderr, resp.Body)
res.Failure(jobs.SimpleError{jobs.ResponseError, "Unable to decode response."})
}
return nil
}