Skip to content

Commit

Permalink
Pushing early version of pdfcd framework
Browse files Browse the repository at this point in the history
But this doesn't work properly right now, there is an import issue.
  • Loading branch information
dalefwillis committed Jun 22, 2015
1 parent 8f031db commit 12cc46f
Show file tree
Hide file tree
Showing 9 changed files with 474 additions and 24 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,7 @@ docs/_build
docs/_static
docs/_templates

bin/*.pex
bin/*.pex
*.img
*.swp
*.pyc
7 changes: 2 additions & 5 deletions docs/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
Flask==0.10.1
itsdangerous==0.24
Jinja2==2.7.3
MarkupSafe==0.23
Werkzeug==0.10.4
Twisted==15.2.1
wheel==0.24.0
zope.interface==4.1.2
82 changes: 82 additions & 0 deletions paradrop/paradrop/backend/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
'''
Core module. Contains the entry point into Paradrop and establishes all other modules.
Does not implement any behavior itself.
'''

import sys, argparse, signal

# Need to fully import the output module so we can toggle verbose mode at runtime
from lib.utils import output

from lib import settings
from lib.utils.output import out, logPrefix
from pdfcd import server


#################################################################################################################
# Support Functions
#################################################################################################################
def setupArgParse():
"""
Sets up arguments if backend is called directly for testing.
"""
p = argparse.ArgumentParser(description='Paradrop API server running on client')
p.add_argument('-s', '--settings', help='Overwrite settings, format is "KEY:VALUE"',
action='append', type=str, default=[])
p.add_argument('--development', help='Enable the development environment variables',
action='store_true')
p.add_argument('--unittest', help="Run the server in unittest mode", action='store_true')
p.add_argument('--verbose', '-v', help='Enable verbose',
action='store_true')
return p

def caughtSIGUSR1(signum, frame):
"""
Catches SIGUSR1 calls and toggles verbose output
"""
if(isinstance(PD.out.verbose, PD.FakeOutput)):
output.out.header("== %s Activating verbose mode\n" % logPrefix())
output.out.verbose = PD.Stdout(PD.Colors.VERBOSE)
output.verbose = True
else:
output.out.header("== %s Deactivating verbose mode\n" % logPrefix())
output.verbose = False
output.out.verbose = PD.FakeOutput()

#################################################################################################################
# Main Function
#################################################################################################################
def main():
"""
This function does something. Right now what its doing is demonstrating
a docstring with sphinxy additions.
:param name: The name to use.
:type name: str.
:param state: Current state to be in.
:type state: bool.
:returns: int -- the return code.
:raises: AttributeError, KeyError
"""
# Setup the signal handler for verbose
signal.signal(signal.SIGUSR1, caughtSIGUSR1)

# Setup args if called directly (testing)
p = setupArgParse()
args = p.parse_args()
out.asdf('asdf')
# Check for settings to overwrite
settings.updateSettings(args.settings)

if(args.verbose):
caughtSIGUSR1(signal.SIGUSR1, None)

# Before we setup anything make sure we have generated a UUID for our instance
# TODO
out.info('-- {} Test\n'.format(logPrefix()))

# Now setup the RESTful API server for Paradrop
server.setup(args)

if __name__ == "__main__":
main()
Empty file.
51 changes: 51 additions & 0 deletions paradrop/paradrop/backend/pdfcd/apichute.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Import ParaDrop related stuff
from lib.utils.output import out, logPrefix
from lib.utils.pdutils import json2str, str2json, timeint, urlDecodeMe

from lib.api.pdrest import APIDecorator
from lib.api import pdapi


#########################################################################################################################
# DB API AP module
#########################################################################################################################

class ChuteAPI:
def __init__(self, rest):
self.rest = rest
self.rest.register('POST', '^/v1/chute/create$', self.POST_createChute)



@APIDecorator(requiredArgs=["sessionToken"])
def POST_createChute(self, apiPackage):
"""
Description:
Get the network config of all chutes under an AP from the vnet_network table
Arguments:
POST request:
@sessionToken
@apid
Returns:
On success:
List of:
* radioid: INT
* isprimary: 0/1
* config: JSON
On failure: A string explain the reason of failure
"""
#token, apid = pdutils.explode(apiPackage.inputArgs, "sessionToken", "apid")

out.info('-- {} Creating chute...\n'.format(logPrefix()))

# TODO implement
result = dict(success=True, message='Successfully launched chute')

if(result is None):
apiPackage.setFailure(errType=pdapi.ERR_BADAUTH, countFailure=False)
else:
apiPackage.setSuccess(json2str(result))




65 changes: 65 additions & 0 deletions paradrop/paradrop/backend/pdfcd/apiutils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
####################################################################
# Copyright 2013-2015 All Rights Reserved
# Authors: The Paradrop Team
###################################################################

'''
backend.pdfcd.apiutils.
Contains helper functions specific to the backend API code.
'''

def getIP(req):
"""
Returns the str IP addr from the request.
NOTE: This is required because when we use nginx servers
it is used as a proxy, so the REAL IP addr is stored in a HTTP header
called 'X-Real-IP', so we need to check for this first, otherwise the
request.getClientIP() is always going to return 'localhost' to us.
"""
ip = req.received_headers.get('X-Real-IP')
if(ip is None):
return req.getClientIP()
else:
return ip

def addressInNetwork(ipaddr, netTuple):
"""
This function allows you to check if on IP belongs to a Network.
Arguments:
unpacked IP address (use unpackIPAddr())
tuple of unpacked (addr, netmask) (use unpackIPAddrWithSlash())
Returns:
True if in network
False otherwise
"""
network, netmask = netTuple
return (ipaddr & netmask) == (network & netmask)

def calcDottedNetmask(mask):
"""Returns quad dot format of IP address."""
bits = 0
for i in xrange(32-mask,32):
bits |= (1 << i)
return "%d.%d.%d.%d" % ((bits & 0xff000000) >> 24, (bits & 0xff0000) >> 16, (bits & 0xff00) >> 8 , (bits & 0xff))

def unpackIPAddrWithSlash(net):
"""
Unpacks the 'IP/bitmask' str.
Returns a tuple of binary forms of both the ipaddr and netmask such that (ipaddr & netmask) will work.
"""
# Take "0.0.0.0/16" and split into 2 components
netaddr, bits = net.split('/')
# Get the quad dot addr of netmask
netmask = struct.unpack('=L',socket.inet_aton(calcDottedNetmask(int(bits))))[0]
# Get the unpacked addr of the IP
network = struct.unpack('=L',socket.inet_aton(netaddr))[0]
return (network, netmask)

def unpackIPAddr(ip):
"""
Unpacks the 'IP' str.
Returns a binary form of the ipaddr such that (ipaddr & netmask) will work.
"""
return struct.unpack('=L',socket.inet_aton(ip))[0]


0 comments on commit 12cc46f

Please sign in to comment.