Repository: docker/go-healthcheck Branch: master Commit: a4f20681d8a1 Files: 11 Total size: 42.8 KB Directory structure: gitextract_cyo82iev/ ├── CONTRIBUTING.md ├── LICENSE ├── MAINTAINERS ├── README.md ├── api/ │ ├── api.go │ └── api_test.go ├── checks/ │ ├── checks.go │ └── checks_test.go ├── doc.go ├── health.go └── health_test.go ================================================ FILE CONTENTS ================================================ ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing to Docker open source projects Want to hack on this project? Awesome! Here are instructions to get you started. This project is a part of the [Docker](https://www.docker.com) project, and follows the same rules and principles. If you're already familiar with the way Docker does things, you'll feel right at home. Otherwise, go read Docker's [contributions guidelines](https://github.com/docker/docker/blob/master/CONTRIBUTING.md), [issue triaging](https://github.com/docker/docker/blob/master/project/ISSUE-TRIAGE.md), [review process](https://github.com/docker/docker/blob/master/project/REVIEWING.md) and [branches and tags](https://github.com/docker/docker/blob/master/project/BRANCHES-AND-TAGS.md). For an in-depth description of our contribution process, visit the contributors guide: [Understand how to contribute](https://docs.docker.com/opensource/workflow/make-a-contribution/) ### Sign your work The sign-off is a simple line at the end of the explanation for the patch. Your signature certifies that you wrote the patch or otherwise have the right to pass it on as an open-source patch. The rules are pretty simple: if you can certify the below (from [developercertificate.org](http://developercertificate.org/)): ``` Developer Certificate of Origin Version 1.1 Copyright (C) 2004, 2006 The Linux Foundation and its contributors. 1 Letterman Drive Suite D4700 San Francisco, CA, 94129 Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Developer's Certificate of Origin 1.1 By making a contribution to this project, I certify that: (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. ``` Then you just add a line to every git commit message: Signed-off-by: Joe Smith Use your real name (sorry, no pseudonyms or anonymous contributions.) If you set your `user.name` and `user.email` git configs, you can sign your commit automatically with `git commit -s`. ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: MAINTAINERS ================================================ # Project maintainers file # # This file describes who runs the docker/go-healthcheck project and how. # This is a living document - if you see something out of date or missing, speak up! # # It is structured to be consumable by both humans and programs. # To extract its contents programmatically, use any TOML-compliant parser. # # This file is compiled into the MAINTAINERS file in docker/opensource. # [Org] [Org."Core maintainers"] people = [ "diogomonica", "nathanmccauley", "stevvooe", ] [people] # A reference list of all people associated with the project. # All other sections should refer to people by their canonical key # in the people section. # ADD YOURSELF HERE IN ALPHABETICAL ORDER [people.diogomonica] Name = "Diogo Monica" Email = "diogo@docker.com" GitHub = "diogomonica" [people.nathanmccauley] Name = "Nathan McCauley" Email = "nathan.mccauley@docker.com" GitHub = "nathanmccauley" [people.stevvooe] Name = "Stephen Day" Email = "stephen.day@docker.com" GitHub = "stevvooe" ================================================ FILE: README.md ================================================ # go-healthcheck Go Healthcheck provides a generic health checking framework. The health package works expvar style. By importing the package the debug server is getting a `/debug/health` endpoint that returns the current status of the application. If there are no errors, `/debug/health` will return a HTTP 200 status, together with an empty JSON reply `{}`. If there are any checks with errors, the JSON reply will include all the failed checks, and the response will be have a HTTP 500 status. A Check can either be run synchronously, or asynchronously. We recommend that most checks are registered as an asynchronous check, so a call to the `/debug/health` endpoint always returns immediately. This pattern is particularly useful for checks that verify upstream connectivity or database status, since they might take a long time to return/timeout. ## Installing To install go-healthcheck, just import it in your application: `import "github.com/docker/go-healthcheck/health"` You can also (optionally) import `health/api` that will add two convenience endpoints: `/debug/health/down` and `/debug/health/up`. These endpoints add "manual" checks that allow the service to quickly be brought in/out of rotation. `import _ "github.com/docker/go-healthcheck/health/api"` ```bash # curl localhost:5001/debug/health {} # curl -X POST localhost:5001/debug/health/down # curl localhost:5001/debug/health {"manual_http_status":"Manual Check"} ``` After importing these packages to your main application, you can start registering checks. ## Registering Checks The recommended way of registering checks is using a periodic Check. PeriodicChecks run on a certain schedule and asynchronously update the status of the check. This allows `CheckStatus()` to return without blocking on an expensive check. A trivial example of a check that runs every 5 seconds and shuts down our server if the current minute is even, could be added as follows: ```go func currentMinuteEvenCheck() error { m := time.Now().Minute() if m%2 == 0 { return errors.New("Current minute is even!") } return nil } health.RegisterPeriodicFunc("minute_even", currentMinuteEvenCheck, time.Second*5) ``` Alternatively, you can also make use of `RegisterPeriodicThresholdFunc` to implement the exact same check, but add a threshold of failures after which the check will be unhealthy. This is particularly useful for flaky Checks, ensuring some stability of the service when handling them. ```go health.RegisterPeriodicThresholdFunc("minute_even", currentMinuteEvenCheck, time.Second*5, 4) ``` The lowest-level way to interact with the health package is calling `Register` directly. Register allows you to pass in an arbitrary string and something that implements `Checker` and runs your check. If your method returns an error with nil, it is considered a healthy check, otherwise it will make the health check endpoint `/debug/health` start returning a 500 and list the specific check that failed. Assuming you wish to register a method called `currentMinuteEvenCheck() error` you could do that by doing: ```go health.Register("even_minute", health.CheckFunc(currentMinuteEvenCheck)) ``` CheckFunc is a convenience type that implements Checker. Another way of registering a check could be by using an anonymous function and the convenience method RegisterFunc. An example that makes the status endpoint always return an error: ```go health.RegisterFunc("my_check", func() error { return Errors.new("This is an error!") })) ``` ## Examples You could also use the health checker mechanism to ensure your application only comes up if certain conditions are met, or to allow the developer to take the service out of rotation immediately. An example that checks database connectivity and immediately takes the server out of rotation on err: ```go updater = health.NewStatusUpdater() health.RegisterFunc("database_check", func() error { return updater.Check() })) conn, err := Connect(...) // database call here if err != nil { updater.Update(errors.New("Error connecting to the database: " + err.Error())) } ``` You can also use the predefined Checkers that come included with the health package. First, import the checks: `import "github.com/docker/distribution/health/checks` After that you can make use of any of the provided checks. An example of using a `FileChecker` to take the application out of rotation if a certain file exists can be done as follows: ```go health.Register("fileChecker", health.PeriodicChecker(checks.FileChecker("/tmp/disable"), time.Second*5)) ``` After registering the check, it is trivial to take an application out of rotation from the console: ```bash # curl localhost:5001/debug/health {} # touch /tmp/disable # curl localhost:5001/debug/health {"fileChecker":"file exists"} ``` You could also test the connectivity to a downstream service by using a `HTTPChecker`, but ensure that you only mark the test unhealthy if there are a minimum of two failures in a row: ```go health.Register("httpChecker", health.PeriodicThresholdChecker(checks.HTTPChecker("https://www.google.pt"), time.Second*5, 2)) ``` ## Reporting security issues The maintainers take security seriously. If you discover a security issue, please bring it to their attention right away! Please **DO NOT** file a public issue, instead send your report privately to [security@docker.com](mailto:security@docker.com). Security reports are greatly appreciated and we will publicly thank you for it. We also like to send gifts—if you're into Docker schwag, make sure to let us know. We currently do not offer a paid security bounty program, but are not ruling it out in the future. ## Copyright and license Copyright © 2015 Docker, Inc. Licensed under the [Apache License, Version 2.0](LICENSE). ================================================ FILE: api/api.go ================================================ package api import ( "errors" "net/http" "github.com/docker/distribution/health" ) var ( updater = health.NewStatusUpdater() ) // DownHandler registers a manual_http_status that always returns an Error func DownHandler(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { updater.Update(errors.New("Manual Check")) } else { w.WriteHeader(http.StatusNotFound) } } // UpHandler registers a manual_http_status that always returns nil func UpHandler(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { updater.Update(nil) } else { w.WriteHeader(http.StatusNotFound) } } // init sets up the two endpoints to bring the service up and down func init() { health.Register("manual_http_status", updater) http.HandleFunc("/debug/health/down", DownHandler) http.HandleFunc("/debug/health/up", UpHandler) } ================================================ FILE: api/api_test.go ================================================ package api import ( "net/http" "net/http/httptest" "testing" "github.com/docker/distribution/health" ) // TestGETDownHandlerDoesNotChangeStatus ensures that calling the endpoint // /debug/health/down with METHOD GET returns a 404 func TestGETDownHandlerDoesNotChangeStatus(t *testing.T) { recorder := httptest.NewRecorder() req, err := http.NewRequest("GET", "https://fakeurl.com/debug/health/down", nil) if err != nil { t.Errorf("Failed to create request.") } DownHandler(recorder, req) if recorder.Code != 404 { t.Errorf("Did not get a 404.") } } // TestGETUpHandlerDoesNotChangeStatus ensures that calling the endpoint // /debug/health/down with METHOD GET returns a 404 func TestGETUpHandlerDoesNotChangeStatus(t *testing.T) { recorder := httptest.NewRecorder() req, err := http.NewRequest("GET", "https://fakeurl.com/debug/health/up", nil) if err != nil { t.Errorf("Failed to create request.") } DownHandler(recorder, req) if recorder.Code != 404 { t.Errorf("Did not get a 404.") } } // TestPOSTDownHandlerChangeStatus ensures the endpoint /debug/health/down changes // the status code of the response to 503 // This test is order dependent, and should come before TestPOSTUpHandlerChangeStatus func TestPOSTDownHandlerChangeStatus(t *testing.T) { recorder := httptest.NewRecorder() req, err := http.NewRequest("POST", "https://fakeurl.com/debug/health/down", nil) if err != nil { t.Errorf("Failed to create request.") } DownHandler(recorder, req) if recorder.Code != 200 { t.Errorf("Did not get a 200.") } if len(health.CheckStatus()) != 1 { t.Errorf("DownHandler didn't add an error check.") } } // TestPOSTUpHandlerChangeStatus ensures the endpoint /debug/health/up changes // the status code of the response to 200 func TestPOSTUpHandlerChangeStatus(t *testing.T) { recorder := httptest.NewRecorder() req, err := http.NewRequest("POST", "https://fakeurl.com/debug/health/up", nil) if err != nil { t.Errorf("Failed to create request.") } UpHandler(recorder, req) if recorder.Code != 200 { t.Errorf("Did not get a 200.") } if len(health.CheckStatus()) != 0 { t.Errorf("UpHandler didn't remove the error check.") } } ================================================ FILE: checks/checks.go ================================================ package checks import ( "errors" "net" "net/http" "os" "strconv" "time" "github.com/docker/distribution/health" ) // FileChecker checks the existence of a file and returns an error // if the file exists. func FileChecker(f string) health.Checker { return health.CheckFunc(func() error { if _, err := os.Stat(f); err == nil { return errors.New("file exists") } return nil }) } // HTTPChecker does a HEAD request and verifies that the HTTP status code // returned matches statusCode. func HTTPChecker(r string, statusCode int, timeout time.Duration, headers http.Header) health.Checker { return health.CheckFunc(func() error { client := http.Client{ Timeout: timeout, } req, err := http.NewRequest("HEAD", r, nil) if err != nil { return errors.New("error creating request: " + r) } for headerName, headerValues := range headers { for _, headerValue := range headerValues { req.Header.Add(headerName, headerValue) } } response, err := client.Do(req) if err != nil { return errors.New("error while checking: " + r) } if response.StatusCode != statusCode { return errors.New("downstream service returned unexpected status: " + strconv.Itoa(response.StatusCode)) } return nil }) } // TCPChecker attempts to open a TCP connection. func TCPChecker(addr string, timeout time.Duration) health.Checker { return health.CheckFunc(func() error { conn, err := net.DialTimeout("tcp", addr, timeout) if err != nil { return errors.New("connection to " + addr + " failed") } conn.Close() return nil }) } ================================================ FILE: checks/checks_test.go ================================================ package checks import ( "testing" ) func TestFileChecker(t *testing.T) { if err := FileChecker("/tmp").Check(); err == nil { t.Errorf("/tmp was expected as exists") } if err := FileChecker("NoSuchFileFromMoon").Check(); err != nil { t.Errorf("NoSuchFileFromMoon was expected as not exists, error:%v", err) } } func TestHTTPChecker(t *testing.T) { if err := HTTPChecker("https://www.google.cybertron", 200, 0, nil).Check(); err == nil { t.Errorf("Google on Cybertron was expected as not exists") } if err := HTTPChecker("https://www.google.pt", 200, 0, nil).Check(); err != nil { t.Errorf("Google at Portugal was expected as exists, error:%v", err) } } ================================================ FILE: doc.go ================================================ // Package health provides a generic health checking framework. // The health package works expvar style. By importing the package the debug // server is getting a "/debug/health" endpoint that returns the current // status of the application. // If there are no errors, "/debug/health" will return a HTTP 200 status, // together with an empty JSON reply "{}". If there are any checks // with errors, the JSON reply will include all the failed checks, and the // response will be have an HTTP 503 status. // // A Check can either be run synchronously, or asynchronously. We recommend // that most checks are registered as an asynchronous check, so a call to the // "/debug/health" endpoint always returns immediately. This pattern is // particularly useful for checks that verify upstream connectivity or // database status, since they might take a long time to return/timeout. // // Installing // // To install health, just import it in your application: // // import "github.com/docker/distribution/health" // // You can also (optionally) import "health/api" that will add two convenience // endpoints: "/debug/health/down" and "/debug/health/up". These endpoints add // "manual" checks that allow the service to quickly be brought in/out of // rotation. // // import _ "github.com/docker/distribution/registry/health/api" // // # curl localhost:5001/debug/health // {} // # curl -X POST localhost:5001/debug/health/down // # curl localhost:5001/debug/health // {"manual_http_status":"Manual Check"} // // After importing these packages to your main application, you can start // registering checks. // // Registering Checks // // The recommended way of registering checks is using a periodic Check. // PeriodicChecks run on a certain schedule and asynchronously update the // status of the check. This allows CheckStatus to return without blocking // on an expensive check. // // A trivial example of a check that runs every 5 seconds and shuts down our // server if the current minute is even, could be added as follows: // // func currentMinuteEvenCheck() error { // m := time.Now().Minute() // if m%2 == 0 { // return errors.New("Current minute is even!") // } // return nil // } // // health.RegisterPeriodicFunc("minute_even", currentMinuteEvenCheck, time.Second*5) // // Alternatively, you can also make use of "RegisterPeriodicThresholdFunc" to // implement the exact same check, but add a threshold of failures after which // the check will be unhealthy. This is particularly useful for flaky Checks, // ensuring some stability of the service when handling them. // // health.RegisterPeriodicThresholdFunc("minute_even", currentMinuteEvenCheck, time.Second*5, 4) // // The lowest-level way to interact with the health package is calling // "Register" directly. Register allows you to pass in an arbitrary string and // something that implements "Checker" and runs your check. If your method // returns an error with nil, it is considered a healthy check, otherwise it // will make the health check endpoint "/debug/health" start returning a 503 // and list the specific check that failed. // // Assuming you wish to register a method called "currentMinuteEvenCheck() // error" you could do that by doing: // // health.Register("even_minute", health.CheckFunc(currentMinuteEvenCheck)) // // CheckFunc is a convenience type that implements Checker. // // Another way of registering a check could be by using an anonymous function // and the convenience method RegisterFunc. An example that makes the status // endpoint always return an error: // // health.RegisterFunc("my_check", func() error { // return Errors.new("This is an error!") // })) // // Examples // // You could also use the health checker mechanism to ensure your application // only comes up if certain conditions are met, or to allow the developer to // take the service out of rotation immediately. An example that checks // database connectivity and immediately takes the server out of rotation on // err: // // updater = health.NewStatusUpdater() // health.RegisterFunc("database_check", func() error { // return updater.Check() // })) // // conn, err := Connect(...) // database call here // if err != nil { // updater.Update(errors.New("Error connecting to the database: " + err.Error())) // } // // You can also use the predefined Checkers that come included with the health // package. First, import the checks: // // import "github.com/docker/distribution/health/checks // // After that you can make use of any of the provided checks. An example of // using a `FileChecker` to take the application out of rotation if a certain // file exists can be done as follows: // // health.Register("fileChecker", health.PeriodicChecker(checks.FileChecker("/tmp/disable"), time.Second*5)) // // After registering the check, it is trivial to take an application out of // rotation from the console: // // # curl localhost:5001/debug/health // {} // # touch /tmp/disable // # curl localhost:5001/debug/health // {"fileChecker":"file exists"} // // You could also test the connectivity to a downstream service by using a // "HTTPChecker", but ensure that you only mark the test unhealthy if there // are a minimum of two failures in a row: // // health.Register("httpChecker", health.PeriodicThresholdChecker(checks.HTTPChecker("https://www.google.pt"), time.Second*5, 2)) package health ================================================ FILE: health.go ================================================ package health import ( "encoding/json" "fmt" "net/http" "sync" "time" "github.com/docker/distribution/context" "github.com/docker/distribution/registry/api/errcode" ) // A Registry is a collection of checks. Most applications will use the global // registry defined in DefaultRegistry. However, unit tests may need to create // separate registries to isolate themselves from other tests. type Registry struct { mu sync.RWMutex registeredChecks map[string]Checker } // NewRegistry creates a new registry. This isn't necessary for normal use of // the package, but may be useful for unit tests so individual tests have their // own set of checks. func NewRegistry() *Registry { return &Registry{ registeredChecks: make(map[string]Checker), } } // DefaultRegistry is the default registry where checks are registered. It is // the registry used by the HTTP handler. var DefaultRegistry *Registry // Checker is the interface for a Health Checker type Checker interface { // Check returns nil if the service is okay. Check() error } // CheckFunc is a convenience type to create functions that implement // the Checker interface type CheckFunc func() error // Check Implements the Checker interface to allow for any func() error method // to be passed as a Checker func (cf CheckFunc) Check() error { return cf() } // Updater implements a health check that is explicitly set. type Updater interface { Checker // Update updates the current status of the health check. Update(status error) } // updater implements Checker and Updater, providing an asynchronous Update // method. // This allows us to have a Checker that returns the Check() call immediately // not blocking on a potentially expensive check. type updater struct { mu sync.Mutex status error } // Check implements the Checker interface func (u *updater) Check() error { u.mu.Lock() defer u.mu.Unlock() return u.status } // Update implements the Updater interface, allowing asynchronous access to // the status of a Checker. func (u *updater) Update(status error) { u.mu.Lock() defer u.mu.Unlock() u.status = status } // NewStatusUpdater returns a new updater func NewStatusUpdater() Updater { return &updater{} } // thresholdUpdater implements Checker and Updater, providing an asynchronous Update // method. // This allows us to have a Checker that returns the Check() call immediately // not blocking on a potentially expensive check. type thresholdUpdater struct { mu sync.Mutex status error threshold int count int } // Check implements the Checker interface func (tu *thresholdUpdater) Check() error { tu.mu.Lock() defer tu.mu.Unlock() if tu.count >= tu.threshold { return tu.status } return nil } // thresholdUpdater implements the Updater interface, allowing asynchronous // access to the status of a Checker. func (tu *thresholdUpdater) Update(status error) { tu.mu.Lock() defer tu.mu.Unlock() if status == nil { tu.count = 0 } else if tu.count < tu.threshold { tu.count++ } tu.status = status } // NewThresholdStatusUpdater returns a new thresholdUpdater func NewThresholdStatusUpdater(t int) Updater { return &thresholdUpdater{threshold: t} } // PeriodicChecker wraps an updater to provide a periodic checker func PeriodicChecker(check Checker, period time.Duration) Checker { u := NewStatusUpdater() go func() { t := time.NewTicker(period) for { <-t.C u.Update(check.Check()) } }() return u } // PeriodicThresholdChecker wraps an updater to provide a periodic checker that // uses a threshold before it changes status func PeriodicThresholdChecker(check Checker, period time.Duration, threshold int) Checker { tu := NewThresholdStatusUpdater(threshold) go func() { t := time.NewTicker(period) for { <-t.C tu.Update(check.Check()) } }() return tu } // CheckStatus returns a map with all the current health check errors func (registry *Registry) CheckStatus() map[string]string { // TODO(stevvooe) this needs a proper type registry.mu.RLock() defer registry.mu.RUnlock() statusKeys := make(map[string]string) for k, v := range registry.registeredChecks { err := v.Check() if err != nil { statusKeys[k] = err.Error() } } return statusKeys } // CheckStatus returns a map with all the current health check errors from the // default registry. func CheckStatus() map[string]string { return DefaultRegistry.CheckStatus() } // Register associates the checker with the provided name. func (registry *Registry) Register(name string, check Checker) { if registry == nil { registry = DefaultRegistry } registry.mu.Lock() defer registry.mu.Unlock() _, ok := registry.registeredChecks[name] if ok { panic("Check already exists: " + name) } registry.registeredChecks[name] = check } // Register associates the checker with the provided name in the default // registry. func Register(name string, check Checker) { DefaultRegistry.Register(name, check) } // RegisterFunc allows the convenience of registering a checker directly from // an arbitrary func() error. func (registry *Registry) RegisterFunc(name string, check func() error) { registry.Register(name, CheckFunc(check)) } // RegisterFunc allows the convenience of registering a checker in the default // registry directly from an arbitrary func() error. func RegisterFunc(name string, check func() error) { DefaultRegistry.RegisterFunc(name, check) } // RegisterPeriodicFunc allows the convenience of registering a PeriodicChecker // from an arbitrary func() error. func (registry *Registry) RegisterPeriodicFunc(name string, period time.Duration, check CheckFunc) { registry.Register(name, PeriodicChecker(CheckFunc(check), period)) } // RegisterPeriodicFunc allows the convenience of registering a PeriodicChecker // in the default registry from an arbitrary func() error. func RegisterPeriodicFunc(name string, period time.Duration, check CheckFunc) { DefaultRegistry.RegisterPeriodicFunc(name, period, check) } // RegisterPeriodicThresholdFunc allows the convenience of registering a // PeriodicChecker from an arbitrary func() error. func (registry *Registry) RegisterPeriodicThresholdFunc(name string, period time.Duration, threshold int, check CheckFunc) { registry.Register(name, PeriodicThresholdChecker(CheckFunc(check), period, threshold)) } // RegisterPeriodicThresholdFunc allows the convenience of registering a // PeriodicChecker in the default registry from an arbitrary func() error. func RegisterPeriodicThresholdFunc(name string, period time.Duration, threshold int, check CheckFunc) { DefaultRegistry.RegisterPeriodicThresholdFunc(name, period, threshold, check) } // StatusHandler returns a JSON blob with all the currently registered Health Checks // and their corresponding status. // Returns 503 if any Error status exists, 200 otherwise func StatusHandler(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { checks := CheckStatus() status := http.StatusOK // If there is an error, return 503 if len(checks) != 0 { status = http.StatusServiceUnavailable } statusResponse(w, r, status, checks) } else { http.NotFound(w, r) } } // Handler returns a handler that will return 503 response code if the health // checks have failed. If everything is okay with the health checks, the // handler will pass through to the provided handler. Use this handler to // disable a web application when the health checks fail. func Handler(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { checks := CheckStatus() if len(checks) != 0 { errcode.ServeJSON(w, errcode.ErrorCodeUnavailable. WithDetail("health check failed: please see /debug/health")) return } handler.ServeHTTP(w, r) // pass through }) } // statusResponse completes the request with a response describing the health // of the service. func statusResponse(w http.ResponseWriter, r *http.Request, status int, checks map[string]string) { p, err := json.Marshal(checks) if err != nil { context.GetLogger(context.Background()).Errorf("error serializing health status: %v", err) p, err = json.Marshal(struct { ServerError string `json:"server_error"` }{ ServerError: "Could not parse error message", }) status = http.StatusInternalServerError if err != nil { context.GetLogger(context.Background()).Errorf("error serializing health status failure message: %v", err) return } } w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Header().Set("Content-Length", fmt.Sprint(len(p))) w.WriteHeader(status) if _, err := w.Write(p); err != nil { context.GetLogger(context.Background()).Errorf("error writing health status response body: %v", err) } } // Registers global /debug/health api endpoint, creates default registry func init() { DefaultRegistry = NewRegistry() http.HandleFunc("/debug/health", StatusHandler) } ================================================ FILE: health_test.go ================================================ package health import ( "errors" "fmt" "net/http" "net/http/httptest" "testing" ) // TestReturns200IfThereAreNoChecks ensures that the result code of the health // endpoint is 200 if there are not currently registered checks. func TestReturns200IfThereAreNoChecks(t *testing.T) { recorder := httptest.NewRecorder() req, err := http.NewRequest("GET", "https://fakeurl.com/debug/health", nil) if err != nil { t.Errorf("Failed to create request.") } StatusHandler(recorder, req) if recorder.Code != 200 { t.Errorf("Did not get a 200.") } } // TestReturns500IfThereAreErrorChecks ensures that the result code of the // health endpoint is 500 if there are health checks with errors func TestReturns503IfThereAreErrorChecks(t *testing.T) { recorder := httptest.NewRecorder() req, err := http.NewRequest("GET", "https://fakeurl.com/debug/health", nil) if err != nil { t.Errorf("Failed to create request.") } // Create a manual error Register("some_check", CheckFunc(func() error { return errors.New("This Check did not succeed") })) StatusHandler(recorder, req) if recorder.Code != 503 { t.Errorf("Did not get a 503.") } } // TestHealthHandler ensures that our handler implementation correct protects // the web application when things aren't so healthy. func TestHealthHandler(t *testing.T) { // clear out existing checks. DefaultRegistry = NewRegistry() // protect an http server handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) })) // wrap it in our health handler handler = Handler(handler) // use this swap check status updater := NewStatusUpdater() Register("test_check", updater) // now, create a test server server := httptest.NewServer(handler) checkUp := func(t *testing.T, message string) { resp, err := http.Get(server.URL) if err != nil { t.Fatalf("error getting success status: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusNoContent { t.Fatalf("unexpected response code from server when %s: %d != %d", message, resp.StatusCode, http.StatusNoContent) } // NOTE(stevvooe): we really don't care about the body -- the format is // not standardized or supported, yet. } checkDown := func(t *testing.T, message string) { resp, err := http.Get(server.URL) if err != nil { t.Fatalf("error getting down status: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusServiceUnavailable { t.Fatalf("unexpected response code from server when %s: %d != %d", message, resp.StatusCode, http.StatusServiceUnavailable) } } // server should be up checkUp(t, "initial health check") // now, we fail the health check updater.Update(fmt.Errorf("the server is now out of commission")) checkDown(t, "server should be down") // should be down // bring server back up updater.Update(nil) checkUp(t, "when server is back up") // now we should be back up. }