k8s-wrapper (empty) → 0.1.0.0
raw patch · 7 files changed
+1110/−0 lines, 7 filesdep +asyncdep +basedep +http-client
Dependencies added: async, base, http-client, http-types, k8s-wrapper, lens, stm, tasty, tasty-hunit, text, wai, wai-middleware-prometheus, warp
Files
- CHANGELOG.md +5/−0
- LICENSE +373/−0
- Readme.md +75/−0
- k8s-wrapper.cabal +67/−0
- spec.yaml +124/−0
- src/Network/K8s/Application.hs +326/−0
- test/unit.hs +140/−0
+ CHANGELOG.md view
@@ -0,0 +1,5 @@+# Revision history for k8s-wrapper++## 0.1.0.0 -- 2022-03-13++* First version.
+ LICENSE view
@@ -0,0 +1,373 @@+Mozilla Public License Version 2.0+==================================++1. Definitions+--------------++1.1. "Contributor"+ means each individual or legal entity that creates, contributes to+ the creation of, or owns Covered Software.++1.2. "Contributor Version"+ means the combination of the Contributions of others (if any) used+ by a Contributor and that particular Contributor's Contribution.++1.3. "Contribution"+ means Covered Software of a particular Contributor.++1.4. "Covered Software"+ means Source Code Form to which the initial Contributor has attached+ the notice in Exhibit A, the Executable Form of such Source Code+ Form, and Modifications of such Source Code Form, in each case+ including portions thereof.++1.5. "Incompatible With Secondary Licenses"+ means++ (a) that the initial Contributor has attached the notice described+ in Exhibit B to the Covered Software; or++ (b) that the Covered Software was made available under the terms of+ version 1.1 or earlier of the License, but not also under the+ terms of a Secondary License.++1.6. "Executable Form"+ means any form of the work other than Source Code Form.++1.7. "Larger Work"+ means a work that combines Covered Software with other material, in+ a separate file or files, that is not Covered Software.++1.8. "License"+ means this document.++1.9. "Licensable"+ means having the right to grant, to the maximum extent possible,+ whether at the time of the initial grant or subsequently, any and+ all of the rights conveyed by this License.++1.10. "Modifications"+ means any of the following:++ (a) any file in Source Code Form that results from an addition to,+ deletion from, or modification of the contents of Covered+ Software; or++ (b) any new file in Source Code Form that contains any Covered+ Software.++1.11. "Patent Claims" of a Contributor+ means any patent claim(s), including without limitation, method,+ process, and apparatus claims, in any patent Licensable by such+ Contributor that would be infringed, but for the grant of the+ License, by the making, using, selling, offering for sale, having+ made, import, or transfer of either its Contributions or its+ Contributor Version.++1.12. "Secondary License"+ means either the GNU General Public License, Version 2.0, the GNU+ Lesser General Public License, Version 2.1, the GNU Affero General+ Public License, Version 3.0, or any later versions of those+ licenses.++1.13. "Source Code Form"+ means the form of the work preferred for making modifications.++1.14. "You" (or "Your")+ means an individual or a legal entity exercising rights under this+ License. For legal entities, "You" includes any entity that+ controls, is controlled by, or is under common control with You. For+ purposes of this definition, "control" means (a) the power, direct+ or indirect, to cause the direction or management of such entity,+ whether by contract or otherwise, or (b) ownership of more than+ fifty percent (50%) of the outstanding shares or beneficial+ ownership of such entity.++2. License Grants and Conditions+--------------------------------++2.1. Grants++Each Contributor hereby grants You a world-wide, royalty-free,+non-exclusive license:++(a) under intellectual property rights (other than patent or trademark)+ Licensable by such Contributor to use, reproduce, make available,+ modify, display, perform, distribute, and otherwise exploit its+ Contributions, either on an unmodified basis, with Modifications, or+ as part of a Larger Work; and++(b) under Patent Claims of such Contributor to make, use, sell, offer+ for sale, have made, import, and otherwise transfer either its+ Contributions or its Contributor Version.++2.2. Effective Date++The licenses granted in Section 2.1 with respect to any Contribution+become effective for each Contribution on the date the Contributor first+distributes such Contribution.++2.3. Limitations on Grant Scope++The licenses granted in this Section 2 are the only rights granted under+this License. No additional rights or licenses will be implied from the+distribution or licensing of Covered Software under this License.+Notwithstanding Section 2.1(b) above, no patent license is granted by a+Contributor:++(a) for any code that a Contributor has removed from Covered Software;+ or++(b) for infringements caused by: (i) Your and any other third party's+ modifications of Covered Software, or (ii) the combination of its+ Contributions with other software (except as part of its Contributor+ Version); or++(c) under Patent Claims infringed by Covered Software in the absence of+ its Contributions.++This License does not grant any rights in the trademarks, service marks,+or logos of any Contributor (except as may be necessary to comply with+the notice requirements in Section 3.4).++2.4. Subsequent Licenses++No Contributor makes additional grants as a result of Your choice to+distribute the Covered Software under a subsequent version of this+License (see Section 10.2) or under the terms of a Secondary License (if+permitted under the terms of Section 3.3).++2.5. Representation++Each Contributor represents that the Contributor believes its+Contributions are its original creation(s) or it has sufficient rights+to grant the rights to its Contributions conveyed by this License.++2.6. Fair Use++This License is not intended to limit any rights You have under+applicable copyright doctrines of fair use, fair dealing, or other+equivalents.++2.7. Conditions++Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted+in Section 2.1.++3. Responsibilities+-------------------++3.1. Distribution of Source Form++All distribution of Covered Software in Source Code Form, including any+Modifications that You create or to which You contribute, must be under+the terms of this License. You must inform recipients that the Source+Code Form of the Covered Software is governed by the terms of this+License, and how they can obtain a copy of this License. You may not+attempt to alter or restrict the recipients' rights in the Source Code+Form.++3.2. Distribution of Executable Form++If You distribute Covered Software in Executable Form then:++(a) such Covered Software must also be made available in Source Code+ Form, as described in Section 3.1, and You must inform recipients of+ the Executable Form how they can obtain a copy of such Source Code+ Form by reasonable means in a timely manner, at a charge no more+ than the cost of distribution to the recipient; and++(b) You may distribute such Executable Form under the terms of this+ License, or sublicense it under different terms, provided that the+ license for the Executable Form does not attempt to limit or alter+ the recipients' rights in the Source Code Form under this License.++3.3. Distribution of a Larger Work++You may create and distribute a Larger Work under terms of Your choice,+provided that You also comply with the requirements of this License for+the Covered Software. If the Larger Work is a combination of Covered+Software with a work governed by one or more Secondary Licenses, and the+Covered Software is not Incompatible With Secondary Licenses, this+License permits You to additionally distribute such Covered Software+under the terms of such Secondary License(s), so that the recipient of+the Larger Work may, at their option, further distribute the Covered+Software under the terms of either this License or such Secondary+License(s).++3.4. Notices++You may not remove or alter the substance of any license notices+(including copyright notices, patent notices, disclaimers of warranty,+or limitations of liability) contained within the Source Code Form of+the Covered Software, except that You may alter any license notices to+the extent required to remedy known factual inaccuracies.++3.5. Application of Additional Terms++You may choose to offer, and to charge a fee for, warranty, support,+indemnity or liability obligations to one or more recipients of Covered+Software. However, You may do so only on Your own behalf, and not on+behalf of any Contributor. You must make it absolutely clear that any+such warranty, support, indemnity, or liability obligation is offered by+You alone, and You hereby agree to indemnify every Contributor for any+liability incurred by such Contributor as a result of warranty, support,+indemnity or liability terms You offer. You may include additional+disclaimers of warranty and limitations of liability specific to any+jurisdiction.++4. Inability to Comply Due to Statute or Regulation+---------------------------------------------------++If it is impossible for You to comply with any of the terms of this+License with respect to some or all of the Covered Software due to+statute, judicial order, or regulation then You must: (a) comply with+the terms of this License to the maximum extent possible; and (b)+describe the limitations and the code they affect. Such description must+be placed in a text file included with all distributions of the Covered+Software under this License. Except to the extent prohibited by statute+or regulation, such description must be sufficiently detailed for a+recipient of ordinary skill to be able to understand it.++5. Termination+--------------++5.1. The rights granted under this License will terminate automatically+if You fail to comply with any of its terms. However, if You become+compliant, then the rights granted under this License from a particular+Contributor are reinstated (a) provisionally, unless and until such+Contributor explicitly and finally terminates Your grants, and (b) on an+ongoing basis, if such Contributor fails to notify You of the+non-compliance by some reasonable means prior to 60 days after You have+come back into compliance. Moreover, Your grants from a particular+Contributor are reinstated on an ongoing basis if such Contributor+notifies You of the non-compliance by some reasonable means, this is the+first time You have received notice of non-compliance with this License+from such Contributor, and You become compliant prior to 30 days after+Your receipt of the notice.++5.2. If You initiate litigation against any entity by asserting a patent+infringement claim (excluding declaratory judgment actions,+counter-claims, and cross-claims) alleging that a Contributor Version+directly or indirectly infringes any patent, then the rights granted to+You by any and all Contributors for the Covered Software under Section+2.1 of this License shall terminate.++5.3. In the event of termination under Sections 5.1 or 5.2 above, all+end user license agreements (excluding distributors and resellers) which+have been validly granted by You or Your distributors under this License+prior to termination shall survive termination.++************************************************************************+* *+* 6. Disclaimer of Warranty *+* ------------------------- *+* *+* Covered Software is provided under this License on an "as is" *+* basis, without warranty of any kind, either expressed, implied, or *+* statutory, including, without limitation, warranties that the *+* Covered Software is free of defects, merchantable, fit for a *+* particular purpose or non-infringing. The entire risk as to the *+* quality and performance of the Covered Software is with You. *+* Should any Covered Software prove defective in any respect, You *+* (not any Contributor) assume the cost of any necessary servicing, *+* repair, or correction. This disclaimer of warranty constitutes an *+* essential part of this License. No use of any Covered Software is *+* authorized under this License except under this disclaimer. *+* *+************************************************************************++************************************************************************+* *+* 7. Limitation of Liability *+* -------------------------- *+* *+* Under no circumstances and under no legal theory, whether tort *+* (including negligence), contract, or otherwise, shall any *+* Contributor, or anyone who distributes Covered Software as *+* permitted above, be liable to You for any direct, indirect, *+* special, incidental, or consequential damages of any character *+* including, without limitation, damages for lost profits, loss of *+* goodwill, work stoppage, computer failure or malfunction, or any *+* and all other commercial damages or losses, even if such party *+* shall have been informed of the possibility of such damages. This *+* limitation of liability shall not apply to liability for death or *+* personal injury resulting from such party's negligence to the *+* extent applicable law prohibits such limitation. Some *+* jurisdictions do not allow the exclusion or limitation of *+* incidental or consequential damages, so this exclusion and *+* limitation may not apply to You. *+* *+************************************************************************++8. Litigation+-------------++Any litigation relating to this License may be brought only in the+courts of a jurisdiction where the defendant maintains its principal+place of business and such litigation shall be governed by laws of that+jurisdiction, without reference to its conflict-of-law provisions.+Nothing in this Section shall prevent a party's ability to bring+cross-claims or counter-claims.++9. Miscellaneous+----------------++This License represents the complete agreement concerning the subject+matter hereof. If any provision of this License is held to be+unenforceable, such provision shall be reformed only to the extent+necessary to make it enforceable. Any law or regulation which provides+that the language of a contract shall be construed against the drafter+shall not be used to construe this License against a Contributor.++10. Versions of the License+---------------------------++10.1. New Versions++Mozilla Foundation is the license steward. Except as provided in Section+10.3, no one other than the license steward has the right to modify or+publish new versions of this License. Each version will be given a+distinguishing version number.++10.2. Effect of New Versions++You may distribute the Covered Software under the terms of the version+of the License under which You originally received the Covered Software,+or under the terms of any subsequent version published by the license+steward.++10.3. Modified Versions++If you create software not governed by this License, and you want to+create a new license for such software, you may create and use a+modified version of this License if you rename the license and remove+any references to the name of the license steward (except to note that+such modified license differs from this License).++10.4. Distributing Source Code Form that is Incompatible With Secondary+Licenses++If You choose to distribute Source Code Form that is Incompatible With+Secondary Licenses under the terms of this version of the License, the+notice described in Exhibit B of this License must be attached.++Exhibit A - Source Code Form License Notice+-------------------------------------------++ This Source Code Form is subject to the terms of the Mozilla Public+ License, v. 2.0. If a copy of the MPL was not distributed with this+ file, You can obtain one at http://mozilla.org/MPL/2.0/.++If it is not possible or desirable to put the notice in a particular+file, then You may include the notice in a location (such as a LICENSE+file in a relevant directory) where a recipient would be likely to look+for such a notice.++You may add additional accurate notices of copyright ownership.++Exhibit B - "Incompatible With Secondary Licenses" Notice+---------------------------------------------------------++ This Source Code Form is "Incompatible With Secondary Licenses", as+ defined by the Mozilla Public License, v. 2.0.
+ Readme.md view
@@ -0,0 +1,75 @@+k8s-wrapper is a [wai](https://hackage.haskell.org/package/wai) application that is designed to wrap your service running in a k8s+environment and provide the additional functionality needed for a fully-featured application+to operate. It accomplishes it in several ways:++ 1. **Health and liveness Endpoints** — the feature provides information on the current state+ of the application, allowing k8s to control execution, restart application, manage rollouts+ and route traffic+ 2. **Startup and Teardown Control** — the application's statup and teardown processes are managed+ by `k8s-wrapper`, ensuring that your service operates smoothly+ 3. **Graceful Shutdown Endpoint** — This feature enables graceful shutdown of your service.+ 4. **Metrics Enpoint** — Metrics are exposed on a dedicated endpoint, allowing for easy monitoring+ of your application's performance++By utilizing k8s-wrapper, you can simplify the management of your service and ensure that it runs+reliably in a k8s environment++# Get Started++In order to use k8s application you should do:++1. All k8s-wrapper to the list of dependencies in the cabal file:++```cabal+executable mega-service+ build-depends: base >= 4.4,+ k8s-wrapper,+ ...+ ...+```++2. In the main file use:++```haskell+import Network.K8s.Application as K8s++main :: IO ()+main = do+ let runReadynessCheck = do + -- In this function we check if the traffic can be routed to the+ -- application. If this function returns False traffic will not+ -- be routed to the application.+ pure True+ let runLivenessCheck = do+ -- Check if the application is in a workable state. If returns `False`+ -- then k8s based on it's rules may restart the application.+ pure True+ let initializeServer = do+ -- This function is used to initialize the service, for example+ -- setup connection to the databases, check config files, register metrics+ _ <- register ghcMetrics+ -- While this function is executing k8s-wrapper replies the+ -- status on it's interface.+ + -- This function returns created resources that may be needed for the+ -- application.+ pure ()+ withK8sEndpoint+ K8s.defConfig -- Default configuration+ K8sChecks{ runReadynessCheck, runLivenessCheck }+ initializeServer+ (\resources -> Warp.run application_port (yourApp resources)) +```++After settings k8s-wrapper will start the interface on the port 10120 (can be redefinen in the config),+that provides endpoints:++ - **/started** — provides information if application is started+ - **/ready** — provides information if application can accept the traffic+ - **/health** — provides information if application is healthy+ - **/stop** — preStop hook — requests application teardown+ - `/_metrics` - output metrics for the application+ +For the machine readable format you can check `spec.yaml` file provided with the package+that provides openapi v3 definition of the endpoints.+
+ k8s-wrapper.cabal view
@@ -0,0 +1,67 @@+cabal-version: 2.4+name: k8s-wrapper+version: 0.1.0.0+synopsis: Application wrapper for the k8s environment+description: A wrapper for the k8s environment. It provides the logic that+ can automate the communication with k8s and easily provide proper+ run in the application.++ For more details see documentation in the "Network.K8s.Application"+ module++homepage: https://github.com/cheopslab/k8s-wrapper++bug-reports: https://github.com/cheopslab/k8s-wrapper/issues+license: MPL-2.0+license-file: LICENSE+author: Alexander Vershilov+maintainer: alexander.vershilov@sirius.online, backend-dev@sirius.online+category: Network+extra-source-files:+ CHANGELOG.md+ spec.yaml+ Readme.md+tested-with: GHC==9.2.2, GHC==9.0.2, GHC==8.10.7++library+ exposed-modules: + Network.K8s.Application+ default-extensions:+ ImportQualifiedPost+ LambdaCase+ NumericUnderscores+ OverloadedStrings+ RecordWildCards+ ScopedTypeVariables+ build-depends:+ base >=4.14.3.0 && <5.0,+ async ^>= 2.2.4,+ stm >=2.4 && <3.0,+ text ^>=1.2.4.1,+ http-types ^>=0.12.3,+ wai,+ wai-middleware-prometheus,+ warp+ hs-source-dirs: src+ default-language: Haskell2010+ ghc-options: -Wall -Wextra++test-suite k8s-wrapper-test+ default-language: Haskell2010+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ default-extensions:+ ImportQualifiedPost+ main-is: unit.hs+ ghc-options: -threaded+ build-depends:+ base >=4.14.3.0 && <5.0,+ async ^>=2.2.4,+ stm >=2.4 && <3.0,+ text ^>=1.2.4.1,+ tasty ^>=1.4.2.1,+ tasty-hunit ^>=0.10.0.3,+ lens ^>=5.1,+ k8s-wrapper,+ http-client,+ http-types
+ spec.yaml view
@@ -0,0 +1,124 @@+openapi: 3.0.3+info:+ title: Management control interface+ description: Service management interface+ version: 0.0.1+paths:+ /started:+ get:+ summary: Application startup state.+ description: |-+ Returns information if the application is already started or not.+ responses:+ '200':+ description: Application is in an operating state+ content:+ text/plain:+ schema: + oneOf:+ - $ref: "#/components/schemas/Ok"+ - $ref: "#/components/schemas/TearingDown"+ '400':+ description: Application is in a starting state+ content:+ text/plain:+ schema: + oneOf:+ - $ref: "#/components/schemas/Starting"++ /ready:+ get:+ summary: Application readiness state.+ description: |-+ Tells if the k8s can route the traffic to this application. K8s periodically checks this+ endpoint in order to understand if it can route traffic there.+ responses:+ '200':+ description: Application is in an operating state+ content:+ text/plain:+ schema: + oneOf:+ - $ref: "#/components/schemas/Running"+ '400':+ description: Application is in a starting state+ content:+ text/plain:+ schema: + oneOf:+ - $ref: "#/components/schemas/Starting"+ - $ref: "#/components/schemas/NotRunning"+ - $ref: "#/components/schemas/TearingDown"+ /health:+ get:+ summary: Application liveness state.+ description: |-+ Tells if the application is alive, if not k8s can restart this instance.+ responses:+ '200':+ description: Application is in an operating state+ content:+ text/plain:+ schema: + oneOf:+ - $ref: "#/components/schemas/Running"+ '400':+ description: Application is in a starting state+ content:+ text/plain:+ schema: + oneOf:+ - $ref: "#/components/schemas/Starting" + - $ref: "#/components/schemas/Unhealthy"+ /stop:+ get:+ summary: Request application teardown.+ description: |-+ Tells if to gracefully teardown, after being called the ready endpoint starts returning 400,+ and no new traffic is accepted. All current requestes are processed.+ + If users' appliction does not exit withing allowed timeout it's killed forcefully.+ responses:+ '200':+ description: Application has accepted the teardown request + content:+ text/plain:+ schema:+ oneOf:+ - $ref: "#/components/schemas/TearingDown"+ /_metrics:+ get:+ summary: Output metrics in prometheus format+ description: |-+ Output all the metrics provided by the application+ responses:+ '200':+ description: Metrics for the application+ content:+ text/plain:+ schema:+ type: string++components:+ schemas:+ Ok:+ type: string+ enum: ["ok"]+ description: Application is working+ Running:+ type: string+ enum: ["running"]+ description: Application is running+ NotRunning:+ type: string+ enum: ["not running"]+ description: Application is not running+ TearingDown:+ enum: ["tearing down"]+ description: Application is tearing down+ Starting:+ enum: ["starting"]+ description: Application is starting+ Unhealthy:+ enum: ["unhealthy"]+ description: Application is unhealthy
+ src/Network/K8s/Application.hs view
@@ -0,0 +1,326 @@+-- | +-- = k8s-wrapper+--+-- The k8s Wrapper is a module designed to provide an interface for running+-- applications in the Kubernetes system. This wrapper spawns the server on an+-- internal protocol, providing endpoints for startup, liveness, and+-- readiness checks, as well as optional metrics support.+--+-- There are some restrictions to be aware of when using this module.+-- First, the **server must be running in the main thread** in order to exit properly.+-- If this guarantee is not met, application and k8s will still function, but rollout+-- update procedures may take much longer.+-- +-- Second, the user's application must be able to tear down upon receiving+-- `AsyncCancelled` or `ThreadKilled` signals. While it's acceptable to implement+-- graceful teardowns, these should be time-bound. In general, applications that use+-- Warp handles this automatically.+--+-- To use the k8s Wrapper, include the following configuration snippet in your pod:+--+-- == __pod.yaml__+-- @+-- ...+-- spec:+-- metadata:+-- annotations:+-- prometheus.io/port: "9121"+-- prometheus.io/scrape: "true"+-- prometheus.io\/path: "\/_metrics"+-- containers:+-- - lifecycle:+-- preStop:+-- httpGet:+-- path: /stop+-- port: ${config.port}+-- # Period when after which the pod will be terminated+-- # even if the stop hook has not returned.+-- terminationGracePeriodSeconds: 30+-- # When the service is considered started+-- # if the startup probe will not return success in+-- # `initialDealySeconds + periodSeconds * failureThreshold` seconds+-- # the service will be restarted+-- startupProbe:+-- httpGet:+-- path: /ready+-- port: ${config.port}+-- failureThreshold: 12+-- initialDelaySeconds: 1+-- periodSeconds: 5+-- successThreshold: 1+-- timeoutSeconds: 2 +-- # When the service is considered alive, if it's not alive it will be+-- # restarted according to it's policy +-- # initialDealySeconds + periodSeconds * failureThreshold+-- livenessProbe:+-- httpGet:+-- path: /health+-- port: ${config.health}+-- failureThreshold: 2+-- initialDelaySeconds: 1+-- periodSeconds: 10+-- successThreshold: 1+-- timeoutSeconds: 2+-- readinessProbe:+-- httpGet:+-- path: /ready+-- port:${config.port}+-- failureThreshold: 2+-- initialDelaySeconds: 1+-- periodSeconds: 10+-- successThreshold: 1+-- timeoutSeconds: 2+-- @+--+module Network.K8s.Application+ ( withK8sEndpoint+ , Config(..)+ , defConfig+ -- * Checks+ -- $k8s-checks+ , K8sChecks(..)+ ) where++import Control.Concurrent (killThread, threadDelay, forkIO)+import Control.Concurrent.Async+import Control.Concurrent.STM+import Control.Exception (finally, AsyncException, throwIO, fromException)+import Control.Monad+import Data.Foldable+import Network.HTTP.Types+import Network.Wai as Wai+import Network.Wai.Handler.Warp qualified as Warp+import Network.Wai.Middleware.Prometheus as Prometheus++-- | Server configuration.+data Config = Config+ { port :: Int -- ^ Port where control interface is statred.+ , maxTearDownPeriodSeconds :: Int -- ^ How much time to wait before forceful teardown.+ } deriving (Show)++-- | Default configuration variables.+defConfig :: Config+defConfig = Config 10120 30++-- $k8s-checks+-- +-- There are two types of health checks that can be used:+--+-- 1. __Deep check__ - this verifies not only basic startup but also that the services+-- the application communicates with are up and running. It is more precise, but it increases+-- the risk of marking services as unavailable and causing cascading errors. Therefore,+-- it is recommended to use deep checks for the `startupCheck`, but use shallow checks for the `livenessCheck`.+-- As for the `readinessCheck`, it is up to the user to decide which type of check to use.+-- 2. __Shallow check__ - this provides only the basic tests to ensure the application is running.+--+-- The suggested approach for implementing the health checks is as follows:+-- +-- 1. The `startupCheck` should return @True@ after the server is started, configs were checked,+-- and communication with other services was established. Once it has returned @True@, the+-- function should always return @True@.+-- 2. The `readinessCheck` should return @True@ after the startup check has passed and after+-- population of the caches, preparing of the internal structures, etc. The function may+-- switch back to @False@ if the structures need repopulation and the application+-- can't serve the users. It's important to ensure that all the services in the cluster will+-- not switch to not ready state at the same time to avoid cascading failures.+-- 3. The `livenessCheck` performs a shallow check of the service and returns the state accordingly.+-- Generally, the `livenessCheck` should return @False@ only in the case where the server needs to be restarted.++-- | Callbacks that the wrapper can use in order to understand the state of+-- the application and react accordingly.+data K8sChecks = K8sChecks+ { runReadynessCheck :: IO Bool -- ^ Checks that application can receive requests+ , runLivenessCheck :: IO Bool -- ^ Checks that application running (should not be restarted)+ }++-- | Application state.+data ApplicationState+ = ApplicationStarting (Async ())+ | ApplicationRunning+ | ApplicationTeardownConfirm (TVar Bool)+ | ApplicationTearingDown+ ++-- | Wrap a server that allows controlling business logic server.+-- The server can be communicated by the k8s services and can monitor the application livecycle.+--+-- In the application run the following logic:+--+-- @+-- k8s_wrapper_server user code+-- +----------------++-- ready=false | initialization | +-- started=false | |+-- alive=false +----------------++-- |+-- started=true <-------------------++-- |+-- +---------------++-- | start server |+-- +---------------++-- |+-- ready? ---> check user thread, run callback+-- alive? ---> check user thread, run callback+-- @+-- +-- +-- The server wrapper also provides additional logic:+-- 1. When checking liveness, the code checks if the thread running the server is still+-- alive and returns @False@ if it is not, regardless of what liveness check returns.+-- 2. When the `stop` action is called, the server starts to return @False@ in the readiness check.+-- Once it is asked by the server, it sends an Exception to the client code.+-- This ensures that no new requests will be sent to the server.+--+-- In case of an asynchronous exception, we expect that we want to terminate the program.+-- Thus, we want to ensure a similar set of actions as a call to the @/stop@ hook:+--+-- 1. Put the application in the tearing down state.+-- 2. Start replying with @ready=False@ replies.+-- 3. Once we replied with @ready=false@ at least once (or after a timeout), we trigger server stop.+-- In this place, we expect the server to stop accepting new connections and exit once all+-- current connections will be processed. This is the responsibility of the function provided by the user,+-- but servers like Warp already handle that properly.+--+-- In case of an exception in the initialization function, it will be rethrown, and the function will exit with the same exception.+-- The k8s endpoint will be torn down.+--+-- In case if the user code exists with an exception, it will be rethrown. Otherwise, the code exits properly.+withK8sEndpoint+ :: Config -- ^ Static configuration of the endpoint.+ -> K8sChecks -- ^ K8s hooks+ -> IO a -- ^ Initialization procedure+ -> (a -> IO b) -- ^ User supplied logic, see requirements for the server to work properly.+ -> IO ()+withK8sEndpoint Config{..} k8s startup action = do+ startup_handle <- async startup+ state_box <- atomically $ newTVar $ ApplicationStarting (fmap (const ()) startup_handle)+ -- We start the server in the background, this is done synchronously+ -- with running initialization procedure.+ withAsync (do+ x <- wait startup_handle+ atomically (switchToRunning state_box)+ action x) $ \server -> do+ k8s_server <- async $ runK8sServiceEndpoint port maxTearDownPeriodSeconds k8s state_box server+ (do result <- atomically $ asum+ [ fmap void $ waitCatchSTM server+ , readTVar state_box >>= \case+ ApplicationTearingDown -> pure $ Right ()+ _ -> retry+ ]+ case result of+ Left se+ | Just (_ :: AsyncCancelled) <- fromException se -> pure ()+ | Just (_ :: AsyncException) <- fromException se -> pure ()+ | otherwise -> throwIO se+ Right{} -> pure ()+ ) `finally`+ (let half_interval = maxTearDownPeriodSeconds * 1_000_000 `div` 2+ in race_ (threadDelay half_interval) (cancel server))+ `finally`+ (forkIO (cancel k8s_server))++-- | Run server with k8s endpoint.+--+-- This endpoint provides k8s hooks:+-- 1. start+-- 2. liveness+-- 3. readyness+-- 4. pre_stop handler+-- +-- All other endpoints returns 404.+runK8sServiceEndpoint+ :: Int -- ^ Port+ -> Int -- ^ Shutdown interval+ -> K8sChecks -- ^ K8s hooks+ -> TVar ApplicationState -- ^ Projection of the application state+ -> Async void -- ^ Handle of the running user code+ -> IO ()+runK8sServiceEndpoint port teardown_time_seconds K8sChecks{..} state_box server = Warp.run port $ \req resp -> do+ case Wai.pathInfo req of+ ["started"] -> do+ readTVarIO state_box >>= \case+ ApplicationStarting{} ->+ resp $ responseLBS status400 [(hContentType, "text/plain")] "starting"+ ApplicationRunning{} ->+ resp $ responseLBS status200 [(hContentType, "text/plain")] "ok"+ _ -> + resp $ responseLBS status200 [(hContentType, "text/plain")] "tearing down"+ ["ready"] -> do+ readTVarIO state_box >>= \case+ ApplicationStarting{} -> + resp $ responseLBS status400 [(hContentType, "text/plain")] "starting"+ ApplicationRunning{} -> do+ isReady <- runReadynessCheck+ if isReady+ then resp $ responseLBS status200 [(hContentType, "text/plain")] "running"+ else resp $ responseLBS status400 [(hContentType, "text/plain")] "not running"+ ApplicationTeardownConfirm confirmed -> do+ atomically $ writeTVar confirmed True+ resp $ responseLBS status400 [(hContentType, "text/plain")] "tearing down"+ ApplicationTearingDown{} ->+ resp $ responseLBS status400 [(hContentType, "text/plain")] "tearing down"+ ["health"] -> do+ readTVarIO state_box >>= \case+ ApplicationStarting{} -> + resp $ responseLBS status400 [(hContentType, "text/plain")] "starting"+ _ -> do+ isAlive <- runLivenessCheck + -- TODO: is thread ok?+ if isAlive+ then resp $ responseLBS status200 [(hContentType, "text/plain")] "running"+ else resp $ responseLBS status400 [(hContentType, "text/plain")] "unhealthy"+ ["stop"] -> do+ _ <- async $ do+ d <- registerDelay (teardown_time_seconds * 1_000_000)+ join $ atomically $ switchToTeardown d state_box+ -- this is interruptible, and waits until user thread will receive an+ -- exception, but does not wait for the tearing down.+ killThread $ asyncThreadId server+ resp $ responseLBS status200 [(hContentType, "text/plain")] "tearing down"+ ["_metrics"] -> metricsApp req resp+ -- If it's any other path then we simply return 404+ _ -> resp $ Wai.responseLBS status404 [(hContentType, "text/plain")] "Not found"+ +-- | Switches the application to the tearing down state.+-- +-- In case if the application was running it injects the confirmation+-- variable that is switched when the k8s system has seen that the+-- application is not ready.+--+-- Returns an action that once finished tells that the application+-- can be teared down. The action does not wait longer that max+-- timeout period+switchToTeardown :: TVar Bool -> TVar ApplicationState -> STM (IO ())+switchToTeardown timeout state = readTVar state >>= \case+ ApplicationStarting init_thread -> do+ writeTVar state ApplicationTearingDown+ pure $ cancel init_thread + ApplicationRunning{} -> do+ confirmed <- newTVar False+ writeTVar state $ ApplicationTeardownConfirm confirmed+ pure $ do+ atomically $ asum+ [ readTVar confirmed >>= check+ , readTVar timeout >>= check+ ]+ atomically $ writeTVar state ApplicationTearingDown+ ApplicationTeardownConfirm confirmed -> do+ pure $ do+ atomically $ asum+ [ readTVar confirmed >>= check+ , readTVar timeout >>= check+ ]+ atomically $ writeTVar state ApplicationTearingDown+ ApplicationTearingDown -> + pure $ pure ()+++-- | Switch the state to the running in case if it was started.+-- Otherwise this is a noop.+switchToRunning :: TVar ApplicationState -> STM ()+switchToRunning state = readTVar state >>= \case+ ApplicationStarting{} -> do+ writeTVar state ApplicationRunning+ ApplicationRunning{} -> pure ()+ ApplicationTeardownConfirm{} -> pure ()+ ApplicationTearingDown -> pure ()
+ test/unit.hs view
@@ -0,0 +1,140 @@+{-# LANGUAGE OverloadedStrings #-}+module Main (main) where++import Control.Lens+import Control.Concurrent+import Control.Concurrent.Async+import Control.Exception+import Control.Monad+import Data.IORef+import Test.Tasty+import Test.Tasty.HUnit+import Network.K8s.Application qualified as K8s+import Network.HTTP.Client+import Network.HTTP.Types++main :: IO ()+main = defaultMain tests++isAlive, isReady, isStarted :: Manager -> IO Bool+isAlive manager =+ let req = "http://localhost:10120/health"+ in httpNoBody req manager <&> (==200) . statusCode . responseStatus +isReady manager = + let req = "http://localhost:10120/ready"+ in httpNoBody req manager <&> (==200) . statusCode . responseStatus +isStarted manager =+ let req = "http://localhost:10120/started"+ in httpNoBody req manager <&> (==200) . statusCode . responseStatus +stopIt :: Manager -> IO ()+stopIt manager =+ let req = "http://localhost:10120/stop"+ in void $ httpNoBody req manager++tests :: TestTree+tests = testGroup "unit"+ [ testGroup "startup"+ [ testCaseSteps "Normal startup" $ \step -> do+ manager <- newManager defaultManagerSettings+ step "Preparing.."+ lock <- newEmptyMVar+ finished <- newEmptyMVar+ closed <- newEmptyMVar+ ready_var <- newIORef True+ alive_var <- newIORef True+ k8s <- async $ K8s.withK8sEndpoint+ K8s.defConfig{K8s.maxTearDownPeriodSeconds=1}+ K8s.K8sChecks+ { K8s.runReadynessCheck = readIORef ready_var+ , K8s.runLivenessCheck = readIORef alive_var+ }+ (takeMVar lock)+ (\x -> putMVar finished x >> takeMVar closed)+ assertBool "appication should not be started" . not =<< isStarted manager+ assertBool "appication should not be ready" . not =<< isReady manager+ assertBool "appication should not be alive" . not =<< isAlive manager+ step "initialization has finished"+ writeIORef ready_var False+ writeIORef alive_var False+ putMVar lock () >> yield+ assertBool "appication should be started" =<< isStarted manager+ assertBool "appication should not be ready" . not =<< isReady manager+ assertBool "appication should not be alive" . not =<< isAlive manager+ step "application is alive now"+ writeIORef alive_var True+ assertBool "appication should be started" =<< isStarted manager+ assertBool "appication should not be ready" . not =<< isReady manager+ assertBool "appication should be alive" =<< isAlive manager+ writeIORef ready_var True+ step "application is ready now"+ assertBool "appication should be started" =<< isStarted manager+ assertBool "appication should be ready" =<< isReady manager+ assertBool "appication should be alive" =<< isAlive manager+ step "teardown"+ cancel k8s+ , testCase "Exception on startup" $ do+ e <- try $ K8s.withK8sEndpoint+ K8s.defConfig{K8s.maxTearDownPeriodSeconds=1}+ (K8s.K8sChecks (pure True) (pure True))+ (throwIO (userError "foo") :: IO ())+ (pure)+ assertEqual "Should be exception" (Left (userError "foo")) e+ , testCase "Exits on application exit" $ do+ K8s.withK8sEndpoint+ K8s.defConfig{K8s.maxTearDownPeriodSeconds=1}+ (K8s.K8sChecks (pure True) (pure True)) (pure ())+ pure+ ] + , testGroup "teardown"+ [ testCaseSteps "Kills application after /stop and /ready" $ \step -> do+ manager <- newManager defaultManagerSettings+ lock <- newEmptyMVar+ received_exception <- newIORef False+ x <- async $ K8s.withK8sEndpoint+ K8s.defConfig{K8s.maxTearDownPeriodSeconds=1}+ (K8s.K8sChecks (pure True) (pure True))+ (pure ())+ (\() -> do+ takeMVar lock `finally` (writeIORef received_exception True))+ step "Stopping the application"+ stopIt manager+ replicateM_ 100 yield -- Hack :(+ step "Check that it's still running"+ assertBool "should not receive exception" . not =<< readIORef received_exception+ step "Check ready"+ assertBool "appication should not be ready" . not =<< isReady manager+ step "Check that application is closing"+ assertBool "should receive exception" =<< readIORef received_exception+ wait x+ putMVar lock ()+ , testCaseSteps "Kills application after /stop and timeout" $ \step -> do+ manager <- newManager defaultManagerSettings+ lock <- newEmptyMVar+ received_exception <- newIORef False+ x <- async $ K8s.withK8sEndpoint+ K8s.defConfig{K8s.maxTearDownPeriodSeconds=1}+ (K8s.K8sChecks (pure True) (pure True))+ (pure ())+ (\() -> do+ takeMVar lock `finally` (writeIORef received_exception True))+ step "Stopping the application"+ stopIt manager+ replicateM_ 100 yield -- Hack :(+ step "Check that it's still running"+ assertBool "should not receive exception" . not =<< readIORef received_exception+ wait x+ putMVar lock ()+ , testCase "Exits if application is terminating for too long" $ do+ manager <- newManager defaultManagerSettings+ lock <- newEmptyMVar+ x <- async $ K8s.withK8sEndpoint+ K8s.defConfig{K8s.maxTearDownPeriodSeconds=1}+ (K8s.K8sChecks (pure True) (pure True))+ (pure ())+ (\() -> do+ takeMVar lock `finally` (takeMVar lock))+ stopIt manager+ wait x+ putMVar lock ()+ ]+ ]