Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | # ex:ts=4:sw=4:sts=4:et |
| 3 | # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- |
| 4 | # |
| 5 | # BitBake Toaster Implementation |
| 6 | # |
| 7 | # Copyright (C) 2015 Intel Corporation |
| 8 | # |
| 9 | # This program is free software; you can redistribute it and/or modify |
| 10 | # it under the terms of the GNU General Public License version 2 as |
| 11 | # published by the Free Software Foundation. |
| 12 | # |
| 13 | # This program is distributed in the hope that it will be useful, |
| 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 16 | # GNU General Public License for more details. |
| 17 | # |
| 18 | # You should have received a copy of the GNU General Public License along |
| 19 | # with this program; if not, write to the Free Software Foundation, Inc., |
| 20 | # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. |
| 21 | |
| 22 | """Custom management command checksocket.""" |
| 23 | |
| 24 | import errno |
| 25 | import socket |
| 26 | |
| 27 | from django.core.management.base import BaseCommand, CommandError |
| 28 | from django.utils.encoding import force_text |
| 29 | |
| 30 | DEFAULT_ADDRPORT = "0.0.0.0:8000" |
| 31 | |
| 32 | class Command(BaseCommand): |
| 33 | """Custom management command.""" |
| 34 | |
| 35 | help = 'Check if Toaster can listen on address:port' |
| 36 | |
| 37 | def add_arguments(self, parser): |
| 38 | parser.add_argument('addrport', nargs='?', default=DEFAULT_ADDRPORT, |
| 39 | help='ipaddr:port to check, %s by default' % \ |
| 40 | DEFAULT_ADDRPORT) |
| 41 | |
| 42 | def handle(self, *args, **options): |
| 43 | addrport = options['addrport'] |
| 44 | if ':' not in addrport: |
| 45 | raise CommandError('Invalid addr:port specified: %s' % addrport) |
| 46 | splitted = addrport.split(':') |
| 47 | try: |
| 48 | splitted[1] = int(splitted[1]) |
| 49 | except ValueError: |
| 50 | raise CommandError('Invalid port specified: %s' % splitted[1]) |
| 51 | self.stdout.write('Check if toaster can listen on %s' % addrport) |
| 52 | try: |
| 53 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 54 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 55 | sock.bind(tuple(splitted)) |
| 56 | except (socket.error, OverflowError) as err: |
| 57 | errors = { |
| 58 | errno.EACCES: 'You don\'t have permission to access port %s' \ |
| 59 | % splitted[1], |
| 60 | errno.EADDRINUSE: 'Port %s is already in use' % splitted[1], |
| 61 | errno.EADDRNOTAVAIL: 'IP address can\'t be assigned to', |
| 62 | } |
| 63 | if hasattr(err, 'errno') and err.errno in errors: |
| 64 | errtext = errors[err.errno] |
| 65 | else: |
| 66 | errtext = force_text(err) |
| 67 | raise CommandError(errtext) |
| 68 | |
| 69 | self.stdout.write("OK") |