├── discovery ├── .gitempty └── eureka │ ├── testdata │ ├── test_config.yml │ └── test_config.json │ ├── connection.go │ ├── backoff.go │ ├── model │ ├── registration.go │ ├── string.go │ ├── util.go │ ├── config_test.go │ ├── config.go │ └── struct.go │ ├── eureka.go │ ├── app.go │ └── registration.go ├── config ├── testdata │ ├── GET-properties_response.txt │ ├── LOAD-test.json │ └── GET-response.json ├── config_test.go └── config.go ├── README.md ├── Makefile ├── .gitignore └── LICENSE /discovery/.gitempty: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /config/testdata/GET-properties_response.txt: -------------------------------------------------------------------------------- 1 | datasource.user: test 2 | foo: bar -------------------------------------------------------------------------------- /config/testdata/LOAD-test.json: -------------------------------------------------------------------------------- 1 | { 2 | "Name": "test", 3 | "URI": "http://test", 4 | "Context": "/test" 5 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go-springcloud 2 | Go support for Spring Cloud (Configuration, Discovery/Netflix Eureka & More) 3 | -------------------------------------------------------------------------------- /config/testdata/GET-response.json: -------------------------------------------------------------------------------- 1 | { 2 | "foo": "bar", 3 | "datasource": { 4 | "host": "localhost:3306", 5 | "user": "test" 6 | } 7 | } -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | GO_FMT = gofmt -s -w -l . 2 | 3 | all: deps compile 4 | 5 | compile: 6 | go build ./... 7 | 8 | deps: 9 | go get 10 | 11 | format: 12 | $(GO_FMT) 13 | -------------------------------------------------------------------------------- /discovery/eureka/testdata/test_config.yml: -------------------------------------------------------------------------------- 1 | client: 2 | serviceUrls: 3 | - http://1.1.1.1:8761 4 | pollIntervalSeconds: 20 5 | registerWithEureka: true 6 | retries: 4 7 | -------------------------------------------------------------------------------- /discovery/eureka/testdata/test_config.json: -------------------------------------------------------------------------------- 1 | { 2 | "client": { 3 | "serviceUrls": [ 4 | "http://1.1.1.1:8761" 5 | ], 6 | "pollIntervalSeconds": 20, 7 | "registerWithEureka": true, 8 | "retries": 4 9 | } 10 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | 26 | .idea 27 | 28 | main.go 29 | boot.go 30 | test/ 31 | testing 32 | go-springcloud 33 | -------------------------------------------------------------------------------- /discovery/eureka/connection.go: -------------------------------------------------------------------------------- 1 | package eureka 2 | 3 | import ( 4 | "math/rand" 5 | "strings" 6 | "time" 7 | ) 8 | 9 | const ( 10 | pathApps = "apps" 11 | ) 12 | 13 | func init() { 14 | rand.Seed(time.Now().UnixNano()) 15 | } 16 | 17 | func (e *eureka) selectServiceURL() string { 18 | urls := e.config.Client.ServiceUrls 19 | if len(urls) == 0 { 20 | log.Fatal("There are no Eureka Service URLs found") 21 | } 22 | return strings.TrimSuffix(urls[rand.Int()%len(urls)], "/") 23 | } 24 | 25 | func (e *eureka) buildUrl(paths ...string) string { 26 | return strings.Join(append([]string{e.selectServiceURL()}, paths...), "/") 27 | } 28 | -------------------------------------------------------------------------------- /discovery/eureka/backoff.go: -------------------------------------------------------------------------------- 1 | package eureka 2 | 3 | import ( 4 | "github.com/cenkalti/backoff" 5 | "time" 6 | ) 7 | 8 | type MaxAttemptBackoff struct { 9 | Interval time.Duration 10 | Attempts int 11 | count int 12 | } 13 | 14 | func NewMaxAttemptBackoff(interval time.Duration, attempts int) *MaxAttemptBackoff { 15 | return &MaxAttemptBackoff{Interval: interval, Attempts: attempts} 16 | } 17 | 18 | func (b *MaxAttemptBackoff) Reset() { 19 | b.count = 0 20 | } 21 | 22 | func (b *MaxAttemptBackoff) NextBackOff() time.Duration { 23 | if b.count >= (b.Attempts - 1) { 24 | b.Reset() 25 | return backoff.Stop 26 | } 27 | b.count = b.count + 1 28 | return b.Interval 29 | } 30 | -------------------------------------------------------------------------------- /discovery/eureka/model/registration.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | const ( 4 | nonSecureUrlPath = "http://%s:%d/%s" 5 | homePageDefaultPath = "/" 6 | statusPageDefaultPath = "/info" 7 | healthCheckDefaultPath = "health" 8 | ) 9 | 10 | func NewRegistrationFromInstanceConfig(instance EurekaInstanceConfig) *Instance { 11 | i := &Instance{} 12 | i.InstanceId = generateID(instance.AppName) 13 | i.AppName = instance.AppName 14 | i.IpAddr = getLocalIP(instance.IpAddress) 15 | i.HostName = i.IpAddr 16 | i.VipAddr = instance.AppName 17 | i.Status = UP 18 | i.Port = asPort(instance.Port, true) 19 | i.SecurePort = asPort(instance.SecurePort, false) 20 | i.HomePageUrl = toInstanceUrlPathToUrl(i.IpAddr, instance.Port, instance.HomePageUrlPath, homePageDefaultPath) 21 | i.StatusPageUrl = toInstanceUrlPathToUrl(i.IpAddr, instance.Port, instance.StatusPageUrlPath, statusPageDefaultPath) 22 | i.HealthCheckUrl = toInstanceUrlPathToUrl(i.IpAddr, instance.Port, instance.HealthCheckUrlPath, healthCheckDefaultPath) 23 | i.DataCenterInfo = defaultDataCenter 24 | return i 25 | } 26 | 27 | func (i *Instance) WrapInRequest() *RegisrationRequest { 28 | return &RegisrationRequest{Instance: i} 29 | } 30 | -------------------------------------------------------------------------------- /discovery/eureka/model/string.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "bytes" 5 | "strconv" 6 | ) 7 | 8 | func (a *Application) String() string { 9 | b := &FormattedBuffer{} 10 | b.append("") 11 | b.append("Name : ", a.Name) 12 | b.append("Instances : [") 13 | for _, i := range a.Instances { 14 | b.append("") 15 | b.writeInstance(i, " ") 16 | } 17 | b.append("]") 18 | return b.String() 19 | } 20 | 21 | func (i *Instance) String() string { 22 | b := &FormattedBuffer{} 23 | b.writeInstance(i, "") 24 | return b.String() 25 | } 26 | 27 | func (f *FormattedBuffer) writeInstance(i *Instance, indent string) { 28 | f.append(indent, "InstanceId : ", i.InstanceId) 29 | f.append(indent, "Hostname : ", i.HostName) 30 | f.append(indent, "IpAddr : ", i.IpAddr) 31 | f.append(indent, "Port : ", strconv.Itoa(i.Port.Number)) 32 | f.append(indent, "SecurePort : ", strconv.Itoa(i.SecurePort.Number)) 33 | f.append(indent, "Status : ", string(i.Status)) 34 | } 35 | 36 | type FormattedBuffer struct { 37 | bytes.Buffer 38 | } 39 | 40 | func (f *FormattedBuffer) append(elements ...string) { 41 | for _, e := range elements { 42 | f.WriteString(e) 43 | } 44 | f.WriteString("\n") 45 | } 46 | -------------------------------------------------------------------------------- /discovery/eureka/model/util.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "fmt" 5 | "github.com/google/uuid" 6 | "net" 7 | "os" 8 | "strings" 9 | ) 10 | 11 | func asPort(port int, enabled bool) Port { 12 | return Port{ 13 | Number: port, 14 | Enabled: enabled, 15 | } 16 | } 17 | 18 | func toInstanceUrlPathToUrl(host string, port int, path string, defaultPath string) string { 19 | p := path 20 | if len(p) <= 0 { 21 | p = defaultPath 22 | } 23 | p = strings.TrimPrefix(p, "/") 24 | return fmt.Sprintf(nonSecureUrlPath, host, port, p) 25 | } 26 | 27 | func getLocalIP(address string) string { 28 | 29 | if address != "" { 30 | return os.ExpandEnv(address) 31 | } 32 | 33 | addrs, err := net.InterfaceAddrs() 34 | if err != nil { 35 | return "" 36 | } 37 | for _, address := range addrs { 38 | // check the address type and if it is not a loopback the display it 39 | if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { 40 | if ipnet.IP.To4() != nil { 41 | return ipnet.IP.String() 42 | } 43 | } 44 | } 45 | panic("Unable to determine local IP address (non loopback). Exiting.") 46 | } 47 | 48 | func generateID(fields ...string) string { 49 | return strings.Join(append(fields, uuid.New().String()), ":") 50 | } 51 | -------------------------------------------------------------------------------- /discovery/eureka/model/config_test.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | const ( 9 | TestServiceUrl = "http://1.1.1.1:8761" 10 | TestPollInterval = 20 11 | TestRegisterWithEureka = true 12 | TestRetries = 4 13 | ) 14 | 15 | func TestEurekaConfigAsYaml(t *testing.T) { 16 | cfg, err := Read("testdata/test_config.yml") 17 | if assert.NoError(t, err) { 18 | assert.Equal(t, 1, len(cfg.Client.ServiceUrls)) 19 | assert.Equal(t, TestServiceUrl, cfg.Client.ServiceUrls[0]) 20 | assert.Equal(t, TestPollInterval, cfg.Client.PollIntervalSeconds) 21 | assert.Equal(t, TestRegisterWithEureka, cfg.Client.RegisterWithEureka) 22 | assert.Equal(t, TestRetries, cfg.Client.Retries) 23 | assert.Equal(t, true, cfg.Client.HealthCheckEnabled) 24 | } 25 | } 26 | 27 | func TestEurekaConfigAsJson(t *testing.T) { 28 | cfg, err := Read("testdata/test_config.json") 29 | if assert.NoError(t, err) { 30 | assert.Equal(t, 1, len(cfg.Client.ServiceUrls)) 31 | assert.Equal(t, TestServiceUrl, cfg.Client.ServiceUrls[0]) 32 | assert.Equal(t, TestPollInterval, cfg.Client.PollIntervalSeconds) 33 | assert.Equal(t, TestRegisterWithEureka, cfg.Client.RegisterWithEureka) 34 | assert.Equal(t, TestRetries, cfg.Client.Retries) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /config/config_test.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "github.com/ContainX/go-utils/mockrest" 5 | "github.com/stretchr/testify/assert" 6 | "strings" 7 | "testing" 8 | ) 9 | 10 | const ( 11 | FilePropertyResp = "testdata/GET-properties_response.txt" 12 | FileJsonResp = "testdata/GET-response.json" 13 | ) 14 | 15 | type testStruct struct { 16 | Foo string `json:"foo"` 17 | } 18 | 19 | func TestConfigAsMap(t *testing.T) { 20 | server := mockrest.StartNewWithFile(FilePropertyResp) 21 | defer server.Stop() 22 | 23 | // Configure Bootstrap - use dynamic mockrest server host/port 24 | cfg, err := New(Bootstrap{Name: "myapp", URI: server.Start()}) 25 | assert.NoError(t, err) 26 | 27 | // Test fetch remote config as Map 28 | m, err := cfg.FetchAsMap() 29 | assert.NoError(t, err) 30 | assert.Equal(t, "bar", m["foo"]) 31 | } 32 | 33 | func TestConfigAsStruct(t *testing.T) { 34 | server := mockrest.StartNewWithFile(FileJsonResp) 35 | defer server.Stop() 36 | 37 | // Configure Bootstrap - use dynamic mockrest server host/port 38 | cfg, err := New(Bootstrap{Name: "myapp", URI: server.Start()}) 39 | assert.NoError(t, err) 40 | 41 | ts := &testStruct{} 42 | 43 | err = cfg.Fetch(ts) 44 | assert.NoError(t, err) 45 | 46 | assert.Equal(t, "bar", ts.Foo) 47 | } 48 | 49 | func TestConfigAsJSON(t *testing.T) { 50 | server := mockrest.StartNewWithFile(FileJsonResp) 51 | defer server.Stop() 52 | 53 | // Configure Bootstrap - use dynamic mockrest server host/port 54 | cfg, err := New(Bootstrap{Name: "myapp", URI: server.Start()}) 55 | 56 | if assert.NoError(t, err) { 57 | json, _ := cfg.FetchAsJSON() 58 | assert.True(t, strings.Contains(json, `"foo": "bar"`)) 59 | } 60 | } 61 | 62 | func TestLoadFromFile(t *testing.T) { 63 | c, err := LoadFromFile("testdata/LOAD-test.json") 64 | 65 | if assert.NoError(t, err, "") { 66 | assert.Equal(t, "http://test", c.Bootstrap().URI) 67 | assert.Equal(t, "/test", c.Bootstrap().Context) 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /discovery/eureka/eureka.go: -------------------------------------------------------------------------------- 1 | package eureka 2 | 3 | import ( 4 | "github.com/ContainX/go-springcloud/discovery/eureka/model" 5 | "github.com/ContainX/go-utils/logger" 6 | ) 7 | 8 | type EurekaClient interface { 9 | // Register the current application with Eureka and setup client side health checks 10 | // if enabled (default). 11 | // 12 | // If await is true then this call will block until either retries have been exhausted or an successful 13 | // registration. 14 | Register(await bool) error 15 | 16 | // Unregister the current application from Eureka. This is auto triggered during normal exiting or sigterm 17 | // but in some rare cases may be handled manually. 18 | Unregister() 19 | 20 | // GetInstance fetches the current application instance for the specified application name 21 | // and id 22 | GetInstance(name, id string) (*model.Instance, error) 23 | 24 | // GetCurrentInstance fetches the current application instance that has registered within 25 | // the current lifecycle 26 | GetCurrentInstance() (*model.Instance, error) 27 | 28 | // GetApplication returns the information about an application by its name. This also includes 29 | // information about all the available instances. 30 | GetApplication(name string) (*model.Application, error) 31 | 32 | // GetApplications fetches all applications and returns a map keyed by the application 33 | // name and a value of the application containing all available instances 34 | GetApplications() (map[string]*model.Application, error) 35 | } 36 | 37 | type ShutdownChan chan bool 38 | 39 | type eureka struct { 40 | config *model.EurekaConfig 41 | instance *model.Instance 42 | shutdown ShutdownChan 43 | } 44 | 45 | type eurekaResponse struct { 46 | status int 47 | err error 48 | } 49 | 50 | var log = logger.GetLogger("discovery") 51 | 52 | func NewClient(cfg *model.EurekaConfig) EurekaClient { 53 | return &eureka{config: cfg, shutdown: make(ShutdownChan, 2)} 54 | } 55 | 56 | func (e *eurekaResponse) hasError() bool { 57 | return e.err != nil 58 | } 59 | 60 | func isStatus2XX(status int) bool { 61 | return status > 199 && status < 300 62 | } 63 | -------------------------------------------------------------------------------- /discovery/eureka/app.go: -------------------------------------------------------------------------------- 1 | package eureka 2 | 3 | import ( 4 | "fmt" 5 | "github.com/ContainX/go-springcloud/discovery/eureka/model" 6 | "github.com/ContainX/go-utils/httpclient" 7 | "net/http" 8 | ) 9 | 10 | func (e *eureka) GetCurrentInstance() (*model.Instance, error) { 11 | log.Infof("Calling current instance with: %s, %s", e.instance.AppName, e.instance.InstanceId) 12 | return e.GetInstance(e.instance.AppName, e.instance.InstanceId) 13 | } 14 | 15 | func (e *eureka) GetInstance(name, id string) (*model.Instance, error) { 16 | url := e.buildUrl(pathApps, name, id) 17 | 18 | result := &model.RegisrationRequest{} 19 | resp := httpclient.Get(url, result) 20 | 21 | if resp.Error != nil { 22 | return nil, resp.Error 23 | } 24 | return result.Instance, nil 25 | } 26 | 27 | func (e *eureka) GetApplication(name string) (*model.Application, error) { 28 | url := e.buildUrl(pathApps, name) 29 | log.Info(url) 30 | result := &model.ApplicationResponse{} 31 | resp := httpclient.Get(url, result) 32 | 33 | if resp.Error != nil { 34 | return nil, resp.Error 35 | } 36 | 37 | return result.Response, nil 38 | } 39 | 40 | func (e *eureka) GetApplications() (map[string]*model.Application, error) { 41 | url := e.buildUrl(pathApps) 42 | 43 | result := &model.ApplicationsResponse{} 44 | resp := httpclient.Get(url, result) 45 | 46 | if resp.Error != nil { 47 | return nil, resp.Error 48 | } 49 | 50 | apps := map[string]*model.Application{} 51 | 52 | for _, a := range result.Response.Applications { 53 | apps[a.Name] = a 54 | } 55 | 56 | return apps, nil 57 | } 58 | 59 | func (e *eureka) sendHealthCheckUpdate(name, id string) *eurekaResponse { 60 | url := e.buildUrl(pathApps, name, id) 61 | resp := httpclient.Put(url, "{}", nil) 62 | 63 | if resp.Error != nil { 64 | return &eurekaResponse{status: resp.Status, err: resp.Error} 65 | } 66 | 67 | if resp.Status != http.StatusOK { 68 | return &eurekaResponse{ 69 | status: resp.Status, 70 | err: fmt.Errorf("Heartbeat to Eureka for instance: %s returned status code of: %d", id, resp.Status), 71 | } 72 | } 73 | log.Debugf("successful heartbeat: %d", resp.Status) 74 | return &eurekaResponse{status: resp.Status} 75 | } 76 | -------------------------------------------------------------------------------- /discovery/eureka/model/config.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "github.com/ContainX/go-utils/encoding" 5 | "github.com/ContainX/go-utils/logger" 6 | ) 7 | 8 | type EurekaConfig struct { 9 | // Instance - Application Instance Information 10 | Instance EurekaInstanceConfig `json:"instance"` 11 | // Client - Eureka Client Configuration 12 | Client EurekaClientConfig `json:"client"` 13 | } 14 | 15 | type EurekaInstanceConfig struct { 16 | AppName string `json:"app"` 17 | IpAddress string `json:"ipAddress"` 18 | HostName string `json:"hostName"` 19 | Port int `json:"port"` 20 | SecurePort int `json:"securePort"` 21 | PreferIpAddress bool `json:"preferIpAddress"` 22 | HomePageUrlPath string `json:"homePageUrlPath"` 23 | StatusPageUrlPath string `json:"statusPageUrlPath"` 24 | HealthCheckUrlPath string `json:"healthCheckUrlPath"` 25 | } 26 | 27 | type EurekaClientConfig struct { 28 | ServiceUrls []string `json:"serviceUrls"` 29 | PollIntervalSeconds int `json:"pollIntervalSeconds"` 30 | RegisterWithEureka bool `json:"registerWithEureka"` 31 | HealthCheckEnabled bool `json:"healthCheckEnabled"` 32 | Retries int `json:"retries"` 33 | } 34 | 35 | func (c *EurekaConfig) PopulateDefaults() { 36 | c.Client.PollIntervalSeconds = 30 37 | c.Client.Retries = 3 38 | c.Client.RegisterWithEureka = true 39 | c.Client.HealthCheckEnabled = true 40 | } 41 | 42 | var log = logger.GetLogger("discovery.model") 43 | 44 | func NewConfigFromArgs(appName, host string, port int, serviceUrls ...string) *EurekaConfig { 45 | ec := &EurekaConfig{ 46 | Instance: EurekaInstanceConfig{ 47 | AppName: appName, 48 | IpAddress: host, 49 | Port: port, 50 | }, 51 | Client: EurekaClientConfig{ 52 | ServiceUrls: serviceUrls, 53 | }, 54 | } 55 | ec.PopulateDefaults() 56 | return ec 57 | } 58 | 59 | func Read(configFile string) (config EurekaConfig, err error) { 60 | 61 | config.PopulateDefaults() 62 | 63 | encoder, err := encoding.NewEncoderFromFileExt(configFile) 64 | if err != nil { 65 | log.Fatalf("Error reading config: %s - %s", configFile, err.Error()) 66 | return config, err 67 | } 68 | 69 | err = encoder.UnMarshalFile(configFile, &config) 70 | if err != nil { 71 | log.Fatalf("Error reading config: %s - %s", configFile, err.Error()) 72 | return config, err 73 | } 74 | return config, nil 75 | } 76 | -------------------------------------------------------------------------------- /discovery/eureka/registration.go: -------------------------------------------------------------------------------- 1 | package eureka 2 | 3 | import ( 4 | "fmt" 5 | "github.com/ContainX/go-springcloud/discovery/eureka/model" 6 | "github.com/ContainX/go-utils/httpclient" 7 | "github.com/cenkalti/backoff" 8 | "os" 9 | "os/signal" 10 | "syscall" 11 | "time" 12 | ) 13 | 14 | func (e *eureka) Register(await bool) error { 15 | e.instance = model.NewRegistrationFromInstanceConfig(e.config.Instance) 16 | 17 | // If true - we block after retries and start heartbeat if enabled 18 | if await { 19 | if err := e.retryRegistrationFunc(e.reRegister); err != nil { 20 | return err 21 | } 22 | e.heartbeat() 23 | } else { 24 | go func() { 25 | if err := e.retryRegistrationFunc(e.reRegister); err == nil { 26 | e.heartbeat() 27 | } 28 | }() 29 | } 30 | return nil 31 | } 32 | 33 | func (e *eureka) reRegister() error { 34 | url := e.buildUrl(pathApps, e.instance.AppName) 35 | log.Infof("Registering [%s] with instance: %s", url, e.instance.InstanceId) 36 | resp := httpclient.Post(url, e.instance.WrapInRequest(), nil) 37 | 38 | if resp.Error != nil { 39 | return fmt.Errorf("Could not complete registration, error: %s, content: %s", 40 | resp.Error, resp.Content) 41 | } 42 | 43 | if resp.Status != 204 { 44 | return fmt.Errorf("HTTP returned %d registering Instance=%s App=%s Body=\"%s\"", resp.Status, 45 | e.instance.InstanceId, e.instance.AppName, resp.Content) 46 | } 47 | return nil 48 | } 49 | 50 | func (e *eureka) Unregister() { 51 | e.stopHeartbeat() 52 | url := e.buildUrl(pathApps, e.instance.AppName, e.instance.InstanceId) 53 | resp := httpclient.Delete(url, nil, nil) 54 | log.Info("Unregistering application: ", resp.Status) 55 | } 56 | 57 | func (e *eureka) heartbeat() { 58 | e.handleSigterm() 59 | 60 | if e.config.Client.RegisterWithEureka { 61 | go e.startHeartbeat() 62 | } 63 | } 64 | 65 | func (e *eureka) startHeartbeat() { 66 | log.Info("starting heartbeat....") 67 | throttle := time.NewTicker(time.Duration(e.config.Client.PollIntervalSeconds) * time.Second) 68 | stop := false 69 | for { 70 | if stop { 71 | log.Info("shutting down heartbeat service") 72 | break 73 | } 74 | select { 75 | case <-e.shutdown: 76 | stop = true 77 | case <-throttle.C: 78 | log.Info("sending heartbeat...") 79 | resp := e.sendHealthCheckUpdate(e.instance.AppName, e.instance.InstanceId) 80 | if resp.hasError() { 81 | if resp.status == 404 { 82 | log.Info("App not found, re-registering...") 83 | e.reRegister() 84 | } else { 85 | log.Error(resp.err) 86 | } 87 | } 88 | } 89 | } 90 | } 91 | 92 | func (e *eureka) stopHeartbeat() { 93 | e.shutdown <- true 94 | } 95 | 96 | func (e *eureka) retryRegistrationFunc(f func() error) error { 97 | return backoff.RetryNotify(f, NewMaxAttemptBackoff(2*time.Second, 3), e.notifyAttempts) 98 | } 99 | 100 | func (e *eureka) notifyAttempts(err error, i time.Duration) { 101 | log.Error(err.Error()) 102 | } 103 | 104 | func (e *eureka) handleSigterm() { 105 | c := make(chan os.Signal, 1) 106 | signal.Notify(c, syscall.SIGINT) 107 | signal.Notify(c, syscall.SIGTERM) 108 | go func() { 109 | <-c 110 | e.Unregister() 111 | os.Exit(1) 112 | }() 113 | } 114 | -------------------------------------------------------------------------------- /discovery/eureka/model/struct.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "encoding/xml" 5 | ) 6 | 7 | type StatusType string 8 | type DataCenterType uint8 9 | type Metadata map[string]string 10 | 11 | //type PortType map[string]interface{} 12 | type DataCenterInfoType map[string]string 13 | 14 | // Supported statuses 15 | const ( 16 | UP StatusType = "UP" 17 | DOWN StatusType = "DOWN" 18 | STARTING StatusType = "STARTING" 19 | OUTOFSERVICE StatusType = "OUT_OF_SERVICE" 20 | UNKNOWN StatusType = "UNKNOWN" 21 | ) 22 | 23 | // Datacenter names 24 | const ( 25 | Amazon = "Amazon" 26 | MyOwn = "MyOwn" 27 | DataCenterInfoClass = "com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo" 28 | ) 29 | 30 | var defaultDataCenter = DataCenterInfo{ 31 | Name: MyOwn, 32 | ClassName: DataCenterInfoClass, 33 | } 34 | 35 | type ApplicationsResponse struct { 36 | Response *Applications `json:"applications"` 37 | } 38 | 39 | type ApplicationResponse struct { 40 | Response *Application `json:"application"` 41 | } 42 | 43 | type Applications struct { 44 | Applications []*Application `json:"application"` 45 | AppsHashcode string `json:"apps__hashcode"` 46 | VersionsDelta int `json:"versions__delta"` 47 | } 48 | 49 | type Application struct { 50 | XMLName xml.Name `json:"application"` 51 | Name string `json:"name"` 52 | Instances []*Instance `json:"instance"` 53 | } 54 | 55 | type RegisrationRequest struct { 56 | Instance *Instance `json:"instance"` 57 | } 58 | 59 | type Instance struct { 60 | InstanceId string `json:"instanceId"` 61 | HostName string `json:"hostName"` 62 | AppName string `json:"app"` 63 | IpAddr string `json:"ipAddr"` 64 | VipAddr string `json:"vipAddress"` 65 | Status StatusType `json:"status"` 66 | Port Port `json:"port"` 67 | SecurePort Port `json:"securePort"` 68 | HomePageUrl string `json:"homePageUrl"` 69 | StatusPageUrl string `json:"statusPageUrl"` 70 | HealthCheckUrl string `json:"healthCheckUrl"` 71 | DataCenterInfo DataCenterInfo `json:"dataCenterInfo,omitempty"` 72 | Metadata Metadata `json:"metadata,omitempty"` 73 | } 74 | 75 | type Registry struct { 76 | XMLName xml.Name `json:"applications"` 77 | VersionDelta int `json:"versions__delta"` 78 | Hashcode string `json:"apps__hashcode"` 79 | Apps []*Application `json:"application"` 80 | } 81 | 82 | type AmazonMetadata struct { 83 | Hostname string `json:"hostname'` 84 | PublicHostName string `json:"public-hostname"` 85 | LocalHostName string `json:"local-hostname"` 86 | PublicIpv4 string `json:"public-ipv4'` 87 | LocalIpv4 string `json:"local-ipv4"` 88 | AvailabilityZone string `json:"availability-zone"` 89 | InstanceId string `json:"instance-id"` 90 | InstanceType string `json:"instance-type"` 91 | AmiId string `json:"ami-id"` 92 | AmiLaunchIndex string `json:"ami-launch-index"` 93 | AmiManifestPath string `json:"ami-manifest-path"` 94 | } 95 | 96 | type DataCenterInfo struct { 97 | ClassName string `json:"@class"` 98 | Name string `json:"name"` 99 | Metadata *AmazonMetadata `json:"metadata,omitempty"` 100 | } 101 | 102 | type Port struct { 103 | Number int `json:"$"` 104 | Enabled bool `json:"@enabled"` 105 | } 106 | 107 | type LeaseInfo struct { 108 | RenewalIntervalInSecs int32 `json:"renewalIntervalInSecs"` 109 | DurationInSecs int32 `json:"durationInSecs"` 110 | RegistrationTimestamp int64 `json:"registrationTimestamp"` 111 | LastRenewalTimestamp int64 `json:"lastRenewalTimestamp"` 112 | EvictionTimestamp int64 `json:"evictionTimestamp"` 113 | ServiceUpTimestamp int64 `json:"serviceUpTimestamp"` 114 | } 115 | -------------------------------------------------------------------------------- /config/config.go: -------------------------------------------------------------------------------- 1 | // Config client for Spring Cloud Configuration server. 2 | package config 3 | 4 | import ( 5 | "errors" 6 | "fmt" 7 | "github.com/ContainX/go-utils/encoding" 8 | "github.com/ContainX/go-utils/envsubst" 9 | "github.com/ContainX/go-utils/httpclient" 10 | "os" 11 | "strings" 12 | ) 13 | 14 | const ( 15 | // EnvConfigProfile holds the name of the environment variable (CONFIG_PROFILE) 16 | // which is used during runtime lookups 17 | EnvConfigProfile = "CONFIG_PROFILE" 18 | // The configuration server URI environment variable (CONFIG_SERVER_URI) 19 | // ex. http://host:8888 20 | EnvConfigServerURI = "CONFIG_SERVER_URI" 21 | // UriDefault is the default URI to the configuration server 22 | UriDefault = "http://localhost:8888" 23 | // ProfileDefault is the default profile 24 | ProfileDefault = "default" 25 | // LabelDefault is the initial SCM branch 26 | LabelDefault = "master" 27 | // Format is {uri}/{label}/{name}-{profile}.type 28 | configPathFmt = "%s/%s/%s-%s.%s" 29 | extJSON = "json" 30 | extPROP = "properties" 31 | extYAML = "yml" 32 | ) 33 | 34 | var ( 35 | NameNotDeclaredErr = errors.New("Name must be declared") 36 | FileNotDeclaredErr = errors.New("Filename must have a value") 37 | ) 38 | 39 | type ConfigClient interface { 40 | // Fetch queries the remote configuration service and populates the 41 | // target value 42 | Fetch(target interface{}) error 43 | 44 | // FetchWithSubstitution fetches a remote config, substitutes environment variables 45 | // and writes it to the target 46 | FetchWithSubstitution(target interface{}) error 47 | 48 | // Fetch queries the remote configuration service and populates 49 | // a map of kv strings. This call flattens hierarchical values 50 | // into flattened form. Example: datasource.mysql.user 51 | FetchAsMap() (map[string]string, error) 52 | 53 | // Fetch queries the remote configuration service and returns 54 | // the result as a JSON string 55 | FetchAsJSON() (string, error) 56 | 57 | // Fetch queries the remote configuration service and returns 58 | // the result as a YAML string 59 | FetchAsYAML() (string, error) 60 | 61 | // Fetch queries the remote configuration service and returns 62 | // the result as a Properties string 63 | FetchAsProperties() (string, error) 64 | 65 | // Bootstrap returns a reference to the current bootstrap settings 66 | Bootstrap() *Bootstrap 67 | } 68 | 69 | type client struct { 70 | bootstrap *Bootstrap 71 | } 72 | 73 | // Bootstrap is the properties needed to fetch a remote configuration from 74 | // spring cloud configuration server. 75 | type Bootstrap struct { 76 | 77 | // The URI of the remote server (default http://localhost:8888). 78 | URI string `json:"uri"` 79 | 80 | // Context is used as the base URI an optional /refresh endpoint which can by 81 | // exposed to update an anonynmous function when configuration changes 82 | Context string `json:"context"` 83 | 84 | // Profile represents the default to use when fetching remote configuration (comma-separated). 85 | // Default is "default". 86 | // 87 | // Note: During runtime the config client looks for the presence of an environment 88 | // variable called CONFIG_PROFILE. If this is defined it overwrites this value. 89 | Profile string `json:"profile"` 90 | 91 | // Name of application used to fetch remote properties. 92 | Name string `json:"name"` 93 | 94 | // Label name to use to pull remote configuration properties. The default is set 95 | // on the server (generally "master" for a git based server). 96 | Label string `json:"label"` 97 | 98 | // The username to use (HTTP Basic) when contacting the remote server. 99 | Username string `json:"username,omitempty"` 100 | 101 | // The password to use (HTTP Basic) when contacting the remote server. 102 | Password string `json:"password,omitempty"` 103 | } 104 | 105 | // New creates a new ConfigClient based on b Bootstrap 106 | // Error will be thrown if Name is not set 107 | func New(b Bootstrap) (ConfigClient, error) { 108 | if b.Name == "" { 109 | return nil, NameNotDeclaredErr 110 | } 111 | 112 | b.URI = defaultVal(b.URI, UriDefault) 113 | b.Profile = defaultVal(b.Profile, ProfileDefault) 114 | b.Label = defaultVal(b.Label, LabelDefault) 115 | 116 | client := &client{ 117 | bootstrap: &b, 118 | } 119 | return client, nil 120 | } 121 | 122 | func LoadFromFile(filename string) (ConfigClient, error) { 123 | if filename == "" { 124 | return nil, FileNotDeclaredErr 125 | } 126 | 127 | f, err := os.Open(filename) 128 | if err != nil { 129 | return nil, err 130 | } 131 | 132 | defer f.Close() 133 | if encoder, err := encoding.NewEncoderFromFileExt(filename); err == nil { 134 | config := &Bootstrap{} 135 | if e := encoder.UnMarshal(f, config); e != nil { 136 | return nil, e 137 | } 138 | config.PopulateDefaultsIfEmpty() 139 | if config.Name == "" { 140 | return nil, NameNotDeclaredErr 141 | } 142 | client := &client{ 143 | bootstrap: config, 144 | } 145 | return client, nil 146 | } else { 147 | return nil, err 148 | } 149 | } 150 | 151 | func (b *Bootstrap) PopulateDefaultsIfEmpty() { 152 | if b.URI == "" { 153 | b.URI = UriDefault 154 | } 155 | if b.Profile == "" { 156 | b.Profile = ProfileDefault 157 | } 158 | if b.Label == "" { 159 | b.Label = LabelDefault 160 | } 161 | } 162 | 163 | // defaultVal returns "d" if "s" aka source has an empty value 164 | func defaultVal(s, d string) string { 165 | if s == "" { 166 | return d 167 | } 168 | return s 169 | } 170 | 171 | // Profile returns the resolved value of the profile. It will 172 | // either use the CLUSTER_PROFILE env variable or fallback to 173 | // the specified default value as a fallback 174 | func (c *client) resolveProfile() string { 175 | if v := os.Getenv(EnvConfigProfile); v != "" { 176 | return v 177 | } 178 | return c.bootstrap.Profile 179 | } 180 | 181 | // URI returns the resolved value of the config server URI. It will 182 | // either use the CONFIG_SERVER_URI env variable or fallback to 183 | // the specified default value as a fallback 184 | func (c *client) resolveURI() string { 185 | if v := os.Getenv(EnvConfigServerURI); v != "" { 186 | return v 187 | } 188 | return c.bootstrap.URI 189 | } 190 | 191 | // Fetch queries the remote configuration service and populates the 192 | // target value 193 | func (c *client) Fetch(target interface{}) error { 194 | uri := c.buildRequestURI(extJSON) 195 | resp := httpclient.Get(uri, target) 196 | if resp.Error != nil { 197 | return resp.Error 198 | } 199 | return nil 200 | } 201 | 202 | func (c *client) FetchWithSubstitution(target interface{}) error { 203 | content, err := c.FetchAsYAML() 204 | if err != nil { 205 | return err 206 | } 207 | 208 | enc, _ := encoding.NewEncoder(encoding.YAML) 209 | 210 | if err = enc.UnMarshalStr(content, target); err != nil { 211 | return err 212 | } 213 | return nil 214 | } 215 | 216 | func (c *client) FetchAsMap() (map[string]string, error) { 217 | uri := c.buildRequestURI(extPROP) 218 | resp := httpclient.Get(uri, nil) 219 | if resp.Error != nil { 220 | return nil, resp.Error 221 | } 222 | 223 | m := map[string]string{} 224 | for _, line := range strings.Split(resp.Content, "\n") { 225 | kv := strings.Split(line, ":") 226 | if len(kv) == 2 { 227 | m[kv[0]] = strings.TrimSpace(kv[1]) 228 | } 229 | } 230 | return m, nil 231 | } 232 | 233 | func (c *client) FetchAsProperties() (string, error) { 234 | return c.fetchAsString(extPROP) 235 | } 236 | 237 | func (c *client) FetchAsJSON() (string, error) { 238 | return c.fetchAsString(extJSON) 239 | } 240 | 241 | func (c *client) FetchAsYAML() (string, error) { 242 | return c.fetchAsString(extYAML) 243 | } 244 | 245 | func (c *client) fetchAsString(extension string) (string, error) { 246 | uri := c.buildRequestURI(extension) 247 | 248 | resp := httpclient.Get(uri, nil) 249 | content := resp.Content 250 | if resp.Error == nil { 251 | content = envsubst.Substitute(strings.NewReader(content), false, func(s string) string { 252 | return os.Getenv(s) 253 | }) 254 | } 255 | return content, resp.Error 256 | } 257 | 258 | func (c *client) Bootstrap() *Bootstrap { 259 | return c.bootstrap 260 | } 261 | 262 | // Builds the final request URI for fetching a remote configuration. 263 | // The returned URI is in the format of : {uri}/{label}/{name}-{profile}.json 264 | func (c *client) buildRequestURI(t string) string { 265 | return fmt.Sprintf(configPathFmt, c.resolveURI(), c.bootstrap.Label, c.bootstrap.Name, c.resolveProfile(), t) 266 | } 267 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------