func createBackend(vs, rs string, b gdc.APIPort) error { log.Infof("creating [%s] with %s:%d -> %d", path.Join(vs, rs), b.IP, b.PublicPort, b.PrivatePort) if _, exists := exposed[vs]; !exists { r, err := http.Get( fmt.Sprintf("http://%s", path.Join(*remote, "service", vs))) if err != nil { return err } if r.StatusCode == 200 { // Service was pre-exposed earlier. exposed[vs] = struct{}{} } else if err := createService(vs, b.PrivatePort, b.Type); err != nil { return err } } opts := core.BackendOptions{Host: b.IP, Port: uint16(b.PublicPort)} data := bytes.NewBuffer(util.MustMarshal(opts, util.JSONOptions{})) rqst, _ := http.NewRequest( "PUT", fmt.Sprintf("http://%s", path.Join(*remote, "service", vs, rs)), data) return roundtrip(rqst, map[int]func() error{ http.StatusConflict: func() error { return fmt.Errorf("backend [%s] was already created", path.Join(vs, rs)) }, http.StatusNotFound: func() error { return fmt.Errorf("service parent [%s] cannot be found", vs) }}) }
func (h backendStatusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) if opts, err := h.ctx.GetBackend(vars["vsID"], vars["rsID"]); err != nil { writeError(w, err) } else { w.Write(util.MustMarshal(opts, util.JSONOptions{Indent: true})) } }
func createService(vs string, n int64, proto string) error { log.Infof("creating service [%s] on port %d/%s", vs, n, proto) opts := core.ServiceOptions{Port: uint16(n), Protocol: proto} data := bytes.NewBuffer(util.MustMarshal(opts, util.JSONOptions{})) rqst, _ := http.NewRequest( "PUT", fmt.Sprintf("http://%s", path.Join(*remote, "service", vs)), data) return roundtrip(rqst, map[int]func() error{ http.StatusConflict: func() error { exposed[vs] = struct{}{} return nil // not actually an error. }}) }
func writeError(w http.ResponseWriter, err error) { code := http.StatusOK switch err { case core.ErrIpvsSyscallFailed: code = http.StatusInternalServerError case core.ErrObjectExists: code = http.StatusConflict case core.ErrObjectNotFound: code = http.StatusNotFound default: code = http.StatusBadRequest } w.WriteHeader(code) w.Write(util.MustMarshal(&errorResponse{err.Error()}, util.JSONOptions{Indent: true})) }
func (c *consulDisco) Expose(name, host string, port uint16) error { u := *c.consul u.Path = "v1/agent/service/register" r, err := c.client.Post( u.String(), "application/json", bytes.NewBuffer(util.MustMarshal(exposeRequest{ Name: name, Host: host, Port: port, }, util.JSONOptions{}))) if err != nil { return err } if r.StatusCode != http.StatusOK { return errConsulError } return nil }
func writeJSON(w http.ResponseWriter, obj interface{}) { w.Header().Add("Content-Type", "application/json") w.Write(util.MustMarshal(obj, util.JSONOptions{Indent: true})) }