[
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2015 Johannes Schickling\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n"
  },
  {
    "path": "README.md",
    "content": "# docker-hook\n\n> Automatic Docker Deployment via [Webhooks](https://docs.docker.com/docker-hub/repos/#webhooks)\n\n`docker-hook` listens to incoming HTTP requests and triggers your specified command.\n\n## Features\n\n* No dependencies\n* Super lightweight\n* Dead **simple setup process**\n* Authentification support\n\n## Setup\n\n### 1. Prepare Your Server\n\n#### Download `docker-hook`\n\nNo worries - it just downloads a Python script. There won't be anything installed or written elsewhere.\n\n```sh\n$ curl https://raw.githubusercontent.com/schickling/docker-hook/master/docker-hook > /usr/local/bin/docker-hook; chmod +x /usr/local/bin/docker-hook\n```\n\n#### Start `docker-hook`\n\n```sh\n$ docker-hook -t <auth-token> -c <command>\n```\n\n##### Auth-Token\n\nPlease choose a secure `auth-token` string or generate one with `$ uuidgen`. Keep it safe or otherwise other people might be able to trigger the specified command. You can pass the `auth-token` as a command line argument, or set it as an environment variable.\n\n##### Command\n\nThe `command` can be any bash command of your choice. See the following [example](#example). This command will be triggered each time someone makes a HTTP request.\n\n### 2. Configuration On Docker Hub\n\nAdd a webhook like on the following image. `example.com` can be the domain of your server or its ip address. `docker-hook` listens to port `8555`. Please replace `my-super-safe-token` with your `auth-token`.\n\n![](http://i.imgur.com/B6QyfmC.png)\n\n## Example\n\nThis example will stop the current running `yourname/app` container, pull the newest version and start a new container.\n\n```sh\n$ docker-hook -t my-super-safe-token -c sh ./deploy.sh\n```\n\nIf you want to store the authentication token as an environment variable, then run\n```sh\n# Make sure there is no space before or after the `=` sign\n$ export DOCKER_AUTH_TOKEN=<my-super-safe-token>\n$ docker-hook -c sh ./deploy.sh\n```\n#### `deploy.sh`\n\n```sh\n#! /bin/bash\n\nIMAGE=\"yourname/app\"\ndocker ps | grep $IMAGE | awk '{print $1}' | xargs docker stop\ndocker pull $IMAGE\ndocker run -d $IMAGE\n```\n\nYou can now test it by pushing something to `yourname/app` or by running the following command where `yourdomain.com` is either a domain pointing to your server or just its ip address.\n\n```sh\n$ curl -X POST yourdomain.com:8555/my-super-safe-token\n```\n\n## How it works\n\n`docker-hook` is written in plain Python and does have **no further dependencies**. It uses `BaseHTTPRequestHandler` to listen for incoming HTTP requests from Docker Hub and then executes the provided [command](#command) if the [authentification](#auth-token) was successful.\n\n## Caveat\n\nThis tool was built as a proof-of-concept and might not be completly secure. If you have any improvement suggestions please open up an issue.\n\n## License\n\n[MIT License](http://opensource.org/licenses/MIT)\n"
  },
  {
    "path": "docker-hook",
    "content": "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Automatic Docker Deployment via Webhooks.\"\"\"\n\nimport json\nimport os\nfrom subprocess import Popen\nfrom argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\ntry:\n    # For Python 3.0 and later\n    from http.server import HTTPServer\n    from http.server import BaseHTTPRequestHandler\nexcept ImportError:\n    # Fall back to Python 2\n    from BaseHTTPServer import BaseHTTPRequestHandler\n    from BaseHTTPServer import HTTPServer as HTTPServer\nimport sys\nimport logging\nimport requests\n\nlogging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',\n                    level=logging.DEBUG,\n                    stream=sys.stdout)\n\nclass RequestHandler(BaseHTTPRequestHandler):\n    \"\"\"A POST request handler which expects a token in its path.\"\"\"\n\n    def do_POST(self):\n        logging.info(\"Path: %s\", self.path)\n        header_length = int(self.headers.getheader('content-length', \"0\"))\n        json_payload = self.rfile.read(header_length)\n        env = dict(os.environ)\n        json_params = {}\n        if len(json_payload) > 0:\n            json_params = json.loads(json_payload)\n            env.update(('REPOSITORY_' + var.upper(), str(val))\n                       for var, val in json_params['repository'].items())\n\n        # Check if the secret URL was called\n        token = args.token or os.environ.get(\"DOCKER_AUTH_TOKEN\")\n        if token == self.path[1:]:\n            logging.info(\"Start executing '%s'\" % args.cmd)\n            try:\n                Popen(args.cmd, env=env).wait()\n                self.send_response(200, \"OK\")\n                if 'callback_url' in json_params:\n                    # Make a callback to Docker Hub\n                    data = {'state': 'success'}\n                    headers = {'Content-type': 'application/json',\n                               'Accept': 'text/plain'}\n                    requests.post(json_params['callback_url'],\n                                  data=json.dumps(data),\n                                  headers=headers)\n            except OSError as err:\n                self.send_response(500, \"OSError\")\n                logging.error(\"You probably didn't use 'sh ./script.sh'.\")\n                logging.error(err)\n                if 'callback_url' in json_params:\n                    # Make a callback to Docker Hub\n                    data = {'state': 'failure',\n                            'description': str(err)}\n                    headers = {'Content-type': 'application/json',\n                               'Accept': 'text/plain'}\n                    requests.post(json_params['callback_url'],\n                                  data=json.dumps(data),\n                                  headers=headers)\n        else:\n            self.send_response(401, \"Not authorized\")\n        self.end_headers()\n\n\ndef get_parser():\n    \"\"\"Get a command line parser for docker-hook.\"\"\"\n    parser = ArgumentParser(description=__doc__,\n                            formatter_class=ArgumentDefaultsHelpFormatter)\n\n    parser.add_argument(\"-t\", \"--token\",\n                        dest=\"token\",\n                        required=False,\n                        help=(\"Secure auth token (can be choosen \"\n                              \"arbitrarily)\"))\n    parser.add_argument(\"-c\", \"--cmd\",\n                        dest=\"cmd\",\n                        required=True,\n                        nargs=\"*\",\n                        help=\"Command to execute when triggered\")\n    parser.add_argument(\"--addr\",\n                        dest=\"addr\",\n                        default=\"0.0.0.0\",\n                        help=\"address where it listens\")\n    parser.add_argument(\"--port\",\n                        dest=\"port\",\n                        type=int,\n                        default=8555,\n                        metavar=\"PORT\",\n                        help=\"port where it listens\")\n    return parser\n\n\ndef main(addr, port):\n    \"\"\"Start a HTTPServer which waits for requests.\"\"\"\n    httpd = HTTPServer((addr, port), RequestHandler)\n    httpd.serve_forever()\n\nif __name__ == '__main__':\n    parser = get_parser()\n    if len(sys.argv) == 1:\n        parser.print_help()\n        sys.exit(1)\n    args = parser.parse_args()\n    main(args.addr, args.port)\n"
  }
]