[asterisk-commits] dlee: branch dlee/stasis-http r379041 - in /team/dlee/stasis-http: ./ apps/ b...

SVN commits to the Asterisk project asterisk-commits at lists.digium.com
Mon Jan 14 10:40:40 CST 2013


Author: dlee
Date: Mon Jan 14 10:40:35 2013
New Revision: 379041

URL: http://svnview.digium.com/svn/asterisk?view=rev&rev=379041
Log:
Initial proof-of-concept work

Added:
    team/dlee/stasis-http/apps/app_stasis.c   (with props)
    team/dlee/stasis-http/build_tools/make_stasis_http_stubs   (with props)
    team/dlee/stasis-http/cog/
    team/dlee/stasis-http/cog/res_stasis_http.make.cog   (with props)
    team/dlee/stasis-http/cog/stasis_cog.py   (with props)
    team/dlee/stasis-http/cog/stasis_http_resource.c.cog   (with props)
    team/dlee/stasis-http/cog/stasis_http_resource.h.cog   (with props)
    team/dlee/stasis-http/cog/stasis_http_resources.c.cog   (with props)
    team/dlee/stasis-http/include/asterisk/stasis.h   (with props)
    team/dlee/stasis-http/include/asterisk/stasis_http.h   (with props)
    team/dlee/stasis-http/include/asterisk/stasis_http_asterisk.h   (with props)
    team/dlee/stasis-http/include/asterisk/stasis_http_bridges.h   (with props)
    team/dlee/stasis-http/include/asterisk/stasis_http_channels.h   (with props)
    team/dlee/stasis-http/include/asterisk/stasis_http_endpoints.h   (with props)
    team/dlee/stasis-http/include/asterisk/stasis_http_recordings.h   (with props)
    team/dlee/stasis-http/res/res_stasis_core.c   (with props)
    team/dlee/stasis-http/res/res_stasis_core.exports.in   (with props)
    team/dlee/stasis-http/res/res_stasis_facade.c   (with props)
    team/dlee/stasis-http/res/res_stasis_http.c   (with props)
    team/dlee/stasis-http/res/res_stasis_http.make   (with props)
    team/dlee/stasis-http/res/stasis_http_asterisk.c   (with props)
    team/dlee/stasis-http/res/stasis_http_bridges.c   (with props)
    team/dlee/stasis-http/res/stasis_http_channels.c   (with props)
    team/dlee/stasis-http/res/stasis_http_endpoints.c   (with props)
    team/dlee/stasis-http/res/stasis_http_recordings.c   (with props)
    team/dlee/stasis-http/res/stasis_http_resources.c   (with props)
    team/dlee/stasis-http/rest-api/
    team/dlee/stasis-http/rest-api/README.txt   (with props)
    team/dlee/stasis-http/rest-api/asterisk.json   (with props)
    team/dlee/stasis-http/rest-api/bridges.json   (with props)
    team/dlee/stasis-http/rest-api/channels.json   (with props)
    team/dlee/stasis-http/rest-api/endpoints.json   (with props)
    team/dlee/stasis-http/rest-api/recordings.json   (with props)
    team/dlee/stasis-http/rest-api/resources.json   (with props)
Modified:
    team/dlee/stasis-http/Makefile
    team/dlee/stasis-http/include/asterisk/autoconfig.h.in
    team/dlee/stasis-http/include/asterisk/http.h
    team/dlee/stasis-http/include/asterisk/strings.h
    team/dlee/stasis-http/main/http.c
    team/dlee/stasis-http/res/Makefile

Modified: team/dlee/stasis-http/Makefile
URL: http://svnview.digium.com/svn/asterisk/team/dlee/stasis-http/Makefile?view=diff&rev=379041&r1=379040&r2=379041
==============================================================================
--- team/dlee/stasis-http/Makefile (original)
+++ team/dlee/stasis-http/Makefile Mon Jan 14 10:40:35 2013
@@ -462,6 +462,9 @@
 		$(INSTALL) -m 644 $$x "$(DESTDIR)$(ASTDATADIR)/images" ; \
 	done
 	$(MAKE) -C sounds install
+	find rest-api -name "*.json" | while read x; do \
+		$(INSTALL) -m 644 $$x "$(DESTDIR)$(ASTDATADIR)/rest-api" ; \
+	done
 
 doc/core-en_US.xml: $(foreach dir,$(MOD_SUBDIRS),$(shell $(GREP) -l "language=\"en_US\"" $(dir)/*.c $(dir)/*.cc 2>/dev/null))
 	@printf "Building Documentation For: "
@@ -538,8 +541,8 @@
 	"$(ASTLOGDIR)/cel-custom" "$(ASTDATADIR)" "$(ASTDATADIR)/documentation" \
 	"$(ASTDATADIR)/documentation/thirdparty" "$(ASTDATADIR)/firmware" \
 	"$(ASTDATADIR)/firmware/iax" "$(ASTDATADIR)/images" "$(ASTDATADIR)/keys" \
-	"$(ASTDATADIR)/phoneprov" "$(ASTDATADIR)/static-http" "$(ASTDATADIR)/sounds" \
-	"$(ASTDATADIR)/moh" "$(ASTMANDIR)/man8" "$(AGI_DIR)" "$(ASTDBDIR)"
+	"$(ASTDATADIR)/phoneprov" "$(ASTDATADIR)/rest-api" "$(ASTDATADIR)/static-http" \
+	"$(ASTDATADIR)/sounds" "$(ASTDATADIR)/moh" "$(ASTMANDIR)/man8" "$(AGI_DIR)" "$(ASTDBDIR)"
 
 installdirs:
 	@for i in $(INSTALLDIRS); do \
@@ -959,6 +962,11 @@
 	@cat sounds/sounds.xml >> $@
 	@echo "</menu>" >> $@
 
+# We don't want to require Python or Cog for every build, so this is its own
+# target.
+stasis-stubs:
+	build_tools/make_stasis_http_stubs
+
 .PHONY: menuselect
 .PHONY: main
 .PHONY: sounds
@@ -978,6 +986,7 @@
 .PHONY: installdirs
 .PHONY: validate-docs
 .PHONY: _clean
+.PHONY: stasis-stubs
 .PHONY: $(SUBDIRS_INSTALL)
 .PHONY: $(SUBDIRS_DIST_CLEAN)
 .PHONY: $(SUBDIRS_CLEAN)

Added: team/dlee/stasis-http/apps/app_stasis.c
URL: http://svnview.digium.com/svn/asterisk/team/dlee/stasis-http/apps/app_stasis.c?view=auto&rev=379041
==============================================================================
--- team/dlee/stasis-http/apps/app_stasis.c (added)
+++ team/dlee/stasis-http/apps/app_stasis.c Mon Jan 14 10:40:35 2013
@@ -1,0 +1,101 @@
+/*
+ * Asterisk -- An open source telephony toolkit.
+ *
+ * Copyright (C) 2012, Digium, Inc.
+ *
+ * David M. Lee, II <dlee at digium.com>
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE file
+ * at the top of the source tree.
+ */
+
+/*! \file
+ *
+ * \brief Stasis dialplan application.
+ *
+ * \author David M. Lee, II <dlee at digium.com>
+ */
+
+/*** MODULEINFO
+	<support_level>core</support_level>
+ ***/
+
+#include "asterisk.h"
+
+ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
+
+#include "asterisk/app.h"
+#include "asterisk/module.h"
+#include "asterisk/stasis.h"
+
+/*** DOCUMENTATION
+	<application name="Stasis" language="en_US">
+		<synopsis>Invoke an extenal Stasis application.</synopsis>
+		<syntax>
+			<parameter name="app_name" required="true">
+				<para>Name of the application to invoke.</para>
+			</parameter>
+			<parameter name="args">
+				<para>Optional arguments for the application invocation.</para>
+			</parameter>
+		</syntax>
+		<description>
+			<para>Invoke an extenal Stasis application.</para>
+		</description>
+	</application>
+ ***/
+
+/*! Maximum number of arguments for the Stasis dialplan application */
+#define MAX_ARGS 128
+
+static const char *stasis = "Stasis";
+
+/*! /brief Stasis dialplan application callback */
+static int stasis_exec(struct ast_channel *chan, const char *data)
+{
+	char *parse = NULL;
+
+	AST_DECLARE_APP_ARGS(args,
+		AST_APP_ARG(app_name);
+		AST_APP_ARG(app_argv)[MAX_ARGS];
+	);
+
+	/* parse the arguments */
+	parse = ast_strdupa(data);
+	AST_STANDARD_APP_ARGS(args, parse);
+
+	if (args.argc < 1) {
+		ast_log(LOG_WARNING, "Stasis app_name argument missing\n");
+		return -1;
+	}
+
+	return stasis_app_invoke(args.app_name, chan, args.argc - 1, args.app_argv);
+}
+
+static int load_module(void)
+{
+	int r = 0;
+	r |= ast_register_application_xml(stasis, stasis_exec);
+	return r;
+}
+
+static int unload_module(void)
+{
+	int r = 0;
+	r |= ast_unregister_application(stasis);
+	return r;
+}
+
+AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Stasis dialplan application",
+		.load = load_module,
+		.unload = unload_module,
+		.load_pri = AST_MODPRI_DEFAULT,
+		.nonoptreq = "res_stasis_core"
+	);

Propchange: team/dlee/stasis-http/apps/app_stasis.c
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: team/dlee/stasis-http/apps/app_stasis.c
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Rev URL

Propchange: team/dlee/stasis-http/apps/app_stasis.c
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: team/dlee/stasis-http/build_tools/make_stasis_http_stubs
URL: http://svnview.digium.com/svn/asterisk/team/dlee/stasis-http/build_tools/make_stasis_http_stubs?view=auto&rev=379041
==============================================================================
--- team/dlee/stasis-http/build_tools/make_stasis_http_stubs (added)
+++ team/dlee/stasis-http/build_tools/make_stasis_http_stubs Mon Jan 14 10:40:35 2013
@@ -1,0 +1,43 @@
+#!/bin/sh
+
+#
+# Wrapper script to run cog on stasis_http templates.
+#
+
+TOPDIR=$(cd $(dirname $0)/.. && pwd)
+PROGNAME=$(basename $0)
+
+: ${COG:=cog.py}
+
+# Exit on error
+set -e
+
+if ! which ${COG} > /dev/null 2>&1; then
+    echo "${PROGNAME}: Cannot execute ${COG}" >&2
+    echo "  You probably need to run sudo pip install cogapp" >&2
+    exit 1
+fi
+
+cd ${TOPDIR}
+
+sources=""
+
+for json in rest-api/*.json; do
+    echo "Cogging ${json}"
+    name=$(basename ${json} .json)
+    sources="${sources} stasis_http_${name}.o"
+    if test ${name} = resources; then
+        ${COG} -z -I cog/ -D RESOURCES=${json} -d -o res/stasis_http_resources.c cog/stasis_http_resources.c.cog
+    else
+        ${COG} -z -I cog/ -D RESOURCE=${json} -d -o include/asterisk/stasis_http_${name}.h cog/stasis_http_resource.h.cog
+	if ! test -e res/stasis_http_${name}.c; then
+	    # Only write the file if it doesn't exist; otherwise you'll overwrite someone's hard work.
+	    echo "  Generating source stubs"
+            ${COG} -z -I cog/ -D RESOURCE=${json} -d -o res/stasis_http_${name}.c cog/stasis_http_resource.c.cog
+	fi
+    fi
+done
+
+# Generate the makefile for the dependencies
+echo "Cogging res_stasis_http.make"
+${COG} -z -I cog/ -D SOURCES="${sources}" -D TARGET="res_stasis_http.so" -d -o res/res_stasis_http.make cog/res_stasis_http.make.cog

Propchange: team/dlee/stasis-http/build_tools/make_stasis_http_stubs
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: team/dlee/stasis-http/build_tools/make_stasis_http_stubs
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Rev URL

Propchange: team/dlee/stasis-http/build_tools/make_stasis_http_stubs
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: team/dlee/stasis-http/cog/res_stasis_http.make.cog
URL: http://svnview.digium.com/svn/asterisk/team/dlee/stasis-http/cog/res_stasis_http.make.cog?view=auto&rev=379041
==============================================================================
--- team/dlee/stasis-http/cog/res_stasis_http.make.cog (added)
+++ team/dlee/stasis-http/cog/res_stasis_http.make.cog Mon Jan 14 10:40:35 2013
@@ -1,0 +1,14 @@
+# -*- Makefile -*-
+
+#
+# Asterisk -- A telephony toolkit for Linux.
+#
+# Generated Makefile for res_stasis_http dependencies.
+#
+# Copyright (C) 2012, Digium, Inc.
+#
+# This program is free software, distributed under the terms of
+# the GNU General Public License
+#
+
+# [[[cog import cog, stasis_cog; stasis_cog.do_not_edit('#'); cog.outl('%s: %s' % (TARGET, SOURCES))]]]

Propchange: team/dlee/stasis-http/cog/res_stasis_http.make.cog
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: team/dlee/stasis-http/cog/res_stasis_http.make.cog
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Rev URL

Propchange: team/dlee/stasis-http/cog/res_stasis_http.make.cog
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: team/dlee/stasis-http/cog/stasis_cog.py
URL: http://svnview.digium.com/svn/asterisk/team/dlee/stasis-http/cog/stasis_cog.py?view=auto&rev=379041
==============================================================================
--- team/dlee/stasis-http/cog/stasis_cog.py (added)
+++ team/dlee/stasis-http/cog/stasis_cog.py Mon Jan 14 10:40:35 2013
@@ -1,0 +1,369 @@
+#
+# Asterisk -- An open source telephony toolkit.
+#
+# Copyright (C) 2012, Digium, Inc.
+#
+# David M. Lee, II <dlee at digium.com>
+#
+# See http://www.asterisk.org for more information about
+# the Asterisk project. Please do not directly contact
+# any of the maintainers of this project for assistance;
+# the project provides a web site, mailing lists and IRC
+# channels for your use.
+#
+# This program is free software, distributed under the terms of
+# the GNU General Public License Version 2. See the LICENSE file
+# at the top of the source tree.
+#
+
+"""Swagger code generator for Asterisk.
+
+This file reads in Swagger API documentation and generates a series of
+implemenation stubs for the Asterisk HTTP server. Using swagger-codegen
+was a bit too heavyweight, and adding Java as a dependency for developers
+would engender much unnecessary hate.
+"""
+
+import cog
+import json
+import os
+import os.path
+import re
+from collections import OrderedDict
+
+class ResourcesSourceWriter(object):
+    """Writes the resources.c file from Swagger API docs."""
+
+    def __init__(self, root):
+	self.root = root
+
+    def write(self):
+	"""Write source code for this resource, and all decendants."""
+	self.write_includes()
+	# Callbacks are referenced by handlers, so write them first
+	self.write_callbacks(self.root)
+	self.write_handlers(self.root)
+
+    def write_includes(self):
+	"""Write the #includes for resources.c"""
+	for include in self.root.includes:
+	    cog.outl('#include "%s"' % include)
+	cog.outl("#include <inttypes.h>")
+	cog.outl("#include <strings.h>")
+	cog.outl()
+
+    def write_callbacks(self, resource):
+	"""Write the callback functions for the resource"""
+	# Children first, for consistency with handler order
+	for child in resource.children.itervalues():
+	    self.write_callbacks(child)
+
+ 	for operation in resource.operations.itervalues():
+	    self.write_callback(operation)
+
+    def write_callback(self, operation):
+	"""Writes the Operations's callback function definition"""
+	cog.outl('static void %s(struct ast_variable *get_params, struct ast_variable *path_vars, struct ast_variable *headers, struct stasis_http_response *response) {' % operation.get_callback_name())
+	if operation.path_parameters or operation.query_parameters:
+	    cog.outl('\tstruct ast_variable *i;');
+	cog.outl('\t%s args = {};' % operation.get_args_name())
+	cog.outl('')
+	if operation.path_parameters:
+	    cog.outl('\tfor (i = path_vars; i; i = i->next) {')
+	    for param in operation.path_parameters.itervalues():
+		cog.outl('\t\tif (strcmp(i->name, "%s") == 0) {' % param.name)
+		cog.outl('\t\t\targs.%s = i->value;' % param.c_name)
+		cog.outl('\t\t}')
+	    cog.outl('\t}')
+	if operation.query_parameters:
+	    cog.outl('\tfor (i = get_params; i; i = i->next) {')
+	    for param in operation.query_parameters.itervalues():
+		cog.outl('\t\tif (strcmp(i->name, "%s") == 0) {' % param.name)
+		cog.outl('\t\t\targs.%s = %s;' % (param.c_name, param.decoder("i->value")))
+		cog.outl('\t\t}')
+	    cog.outl('\t}')
+	cog.outl('\t%s(headers, &args, response);' % operation.get_impl_name())
+	cog.outl('}')
+	cog.outl()
+
+    def write_handlers(self, resource):
+	"""Write the stasis_rest_handlers for the resource"""
+	# Children are referred to by handler, so write them first
+	for child in resource.children.itervalues():
+	    self.write_handlers(child)
+
+	cog.outl('static struct stasis_rest_handlers %s = {' % resource.get_name())
+	cog.outl('\t.path_segment = "%s",' % resource.path_element)
+	if resource.is_wildcard:
+	    cog.outl('\t.is_wildcard = 1,')
+	cog.outl('\t.callbacks = {')
+	for operation in resource.operations.itervalues():
+	    cog.outl('\t\t[AST_HTTP_%s] = %s,' % (operation.http_method, operation.get_callback_name()))
+	cog.outl('\t},')
+	cog.outl('\t.num_children = %d,' % len(resource.children))
+	cog.out('\t.children = { ')
+	for child in resource.children.itervalues():
+	    cog.out('&%s, ' % child.get_name())
+	cog.outl('},')
+	cog.outl('};')
+	cog.outl()
+
+class ResourceHeaderWriter(object):
+    """Writes a resource.h file from Swagger API docs."""
+
+    def __init__(self, root):
+	self.root = root
+
+    def write(self):
+	"""Writes the corresponding header file for this resource's operations."""
+	(name, ext) = os.path.splitext(os.path.basename(cog.outFile))
+	incl_guard = '_ASTERISK_%s_H' % name.upper()
+	cog.outl('#ifndef %s' % incl_guard)
+	cog.outl('#define %s' % incl_guard)
+	# args structures first, so the prototypes can easily be copy/pasted in one blob
+	self.write_structs(self.root)
+	self.write_impl_prototypes(self.root)
+	cog.outl('#endif /* %s */' % incl_guard)
+
+    def write_structs(self, resource):
+	"""Write the args structs for the resource's operations."""
+	# Children first, so we're in the same order as resources.c
+	for child in resource.children.itervalues():
+	    self.write_structs(child)
+
+	for operation in resource.operations.itervalues():
+	    cog.outl('%s {' % operation.get_args_name())
+	    for param in operation.get_all_parameters().itervalues():
+		cog.out('\t%s' % param.c_type)
+		if not param.c_type.endswith('*'):
+		    cog.out(' ')
+		cog.outl('%s;' % param.c_name)
+	    cog.outl('};')
+
+    def write_impl_prototypes(self, resource):
+	"""Write the prototypes for all the implementation functions in the given resource's operations."""
+	# Children first, so we're in the same order as resources.c
+	for child in resource.children.itervalues():
+	    self.write_impl_prototypes(child)
+
+ 	for operation in resource.operations.itervalues():
+	    cog.outl('void %s(struct ast_variable *headers, %s *args, struct stasis_http_response *response);' % (operation.get_impl_name(), operation.get_args_name()))
+
+class ResourceSourceWriter(object):
+    """Writes a resource.c file from Swagger API docs."""
+
+    def __init__(self, root):
+	self.root = root
+
+    def write(self):
+	"""Writes the corresponding source stubs file for this resource's operations."""
+	(name, ext) = os.path.splitext(os.path.basename(cog.outFile))
+	cog.outl('#include "asterisk/%s.h"' % name)
+	cog.outl()
+	self.write_impl_stubs(self.root)
+
+    def write_impl_stubs(self, resource):
+	"""Write the stubs for all the implementation functions in the given resource's operations."""
+	# Children first, so we're in the same order as the header file
+	for child in resource.children.itervalues():
+	    self.write_impl_stubs(child)
+
+ 	for operation in resource.operations.itervalues():
+	    cog.outl('void %s(struct ast_variable *headers, %s *args, struct stasis_http_response *response) {' % (operation.get_impl_name(), operation.get_args_name()))
+	    cog.outl('\tast_log(LOG_ERROR, "TODO: %s\\n");' % operation.get_impl_name())
+	    cog.outl('}')
+
+class Resource(object):
+    """Swagger resource"""
+    def __init__(self, parent_name, path_element):
+	self.parent_name = parent_name
+	if path_element.startswith('{') and path_element.endswith('}'):
+	    self.is_wildcard = True
+	    self.path_element = path_element[1:-1]
+	else:
+	    self.is_wildcard = False
+	    self.path_element = path_element
+	# It's important to maintain order of the children
+	# Otherwise, search order won't match the .json files
+	self.children = OrderedDict()
+	self.operations = OrderedDict()
+	self.includes = []
+
+	if not is_identifier(self.get_name()):
+	    raise ValueError("Invalid path name: %s" % path_element)
+
+    def load_resources(self, resources_file):
+	"""Loads resources from a Swagger resources.json file.
+	"""
+	assert not self.children, "Should not reload existing resource"
+	assert not self.operations, "Should not reload existing resource"
+
+	resources_dir = os.path.dirname(resources_file)
+	with open(resources_file) as fp:
+	    resources = json.load(fp)
+
+	for api in resources['apis']:
+	    # Path in json is URI relative, so we need to drop the initial /api/
+	    path = api['path'].replace('/api/', '', 1)
+	    resource_file = os.path.abspath(os.path.join(resources_dir, path)).format(format = 'json')
+	    (basename, ext) = os.path.splitext(os.path.basename(resource_file))
+	    self.includes.append('asterisk/stasis_http_%s.h' % basename)
+	    self.load_resource(resource_file)
+
+    def load_resource(self, resource_file):
+	"""Loads a resource from a single Swagger resource.json file.
+	"""
+	with open(resource_file) as fp:
+	    resource = json.load(fp)
+
+	for api in resource['apis']:
+	    resource_path = api['path'].split('/')
+	    # remove empty strings from resource_path
+	    resource_path = filter(lambda x: x, resource_path)
+	    resource = self.get_child(resource_path)
+	    for operation in api['operations']:
+		op = resource.add_operation(operation['httpMethod'], operation['nickname'])
+		for param in operation.get('parameters') or []:
+		    op.add_parameter(name = param['name'],
+				     param_type = param['paramType'],
+				     required = param.get('required'),
+				     allowMultiple = param.get('allowMultiple'),
+				     dataType = param.get('dataType'),
+				     defaultValue = param.get('defaultValue'))
+
+    def get_name(self):
+	"""Returns the fully qualified name of this Resource."""
+	if self.parent_name:
+	    return '%s_%s' % (self.parent_name, self.path_element)
+	else:
+	    return self.path_element
+
+    def get_child(self, path_list):
+	"""Finds the decendent specified by path_list.
+
+	This method will create any missing decendants along the way, if needed.
+	"""
+	if not path_list:
+	    return self
+
+	path_element = path_list[0]
+	r = self.children.get(path_element)
+	if r is None:
+	    r = Resource(self.get_name(), path_element)
+	    self.children[path_element] = r
+	return r.get_child(path_list[1:])
+
+    def add_operation(self, http_method, nickname):
+	"""Add an operation to this resource"""
+	op = Operation(http_method, nickname)
+	self.operations[http_method] = op
+	return op
+
+class Operation(object):
+    """Swagger operation"""
+    def __init__(self, http_method, nickname):
+	self.http_method = http_method
+	self.nickname = snakify(nickname)
+	self.query_parameters = OrderedDict()
+	self.path_parameters = OrderedDict()
+
+	if not is_identifier(self.get_callback_name()) or not is_identifier(self.nickname):
+	    raise ValueError("Invalid operation nickname: %s" % nickname)
+
+    def add_parameter(self, name, param_type, required, allowMultiple, dataType, defaultValue):
+	if param_type == 'path':
+	    p = self.path_parameters
+	elif param_type == 'query':
+	    p = self.query_parameters
+	else:
+	    raise ValueError("Invalid param_type: %s" % param_type)
+	p[name] = Parameter(name, required, allowMultiple, dataType, defaultValue)
+
+    def get_all_parameters(self):
+	return OrderedDict(self.path_parameters.items() + self.query_parameters.items())
+
+    def get_callback_name(self):
+	"""Returns the name of this Operation's callback function"""
+	return "%s_cb" % self.get_impl_name()
+
+    def get_impl_name(self):
+	"""Returns the name of this Operation's callback function"""
+	return "stasis_http_%s" % self.nickname
+
+    def get_args_name(self):
+	"""Returns the name of impl's args struct"""
+	return "struct ast_%s_args" % self.nickname
+
+class Parameter(object):
+    """Swagger operation parameter"""
+    def __init__(self, name, required, allowMultiple, dataType, defaultValue):
+	self.name = name
+	self.required = required
+	self.allowMultiple = allowMultiple
+	self.dataType = dataType
+	self.defaultValue = defaultValue
+	self.c_name = snakify(self.name)
+
+	if dataType == 'string':
+	    self.c_type = 'const char *'
+	elif dataType == 'boolean':
+	    self.c_type = 'int'
+	elif dataType == 'number':
+	    self.c_type = 'int'
+	else:
+	    raise ValueError("Invalid dataType: %s" % dataType)
+
+	if not is_identifier(self.c_name):
+	    raise ValueError("Invalid paramater name: %s" % name)
+
+    def decoder(self, char_pointer):
+	"""Returns the C code for decoding this param from a string."""
+	if self.dataType == 'string':
+	    return char_pointer
+	elif self.dataType == 'boolean':
+	    return 'ast_true(%s)' % char_pointer
+	elif self.dataType == 'number':
+	    return 'strtol(%s, NULL, 0)' % char_pointer
+	else:
+	    assert False, "Someone forgot to update the decoder"
+	    return char_pointer
+
+def snakify(name):
+    """Helper to take a camelCase or dash-seperated name and make it snake_case"""
+    r = ''
+    prior_lower = False
+    for c in name:
+	if c.isupper() and prior_lower:
+	    r += "_"
+	if c is '-':
+	    c = '_'
+	prior_lower = c.islower()
+	r += c.lower()
+    return r
+
+def is_identifier(str):
+    """Returns True if given string is a valid C identifier; False otherwise"""
+    return re.match('^[_A-Za-z][_A-Za-z0-9]*$', str) is not None
+
+def do_not_edit(comment_style = 'C'):
+    """Write the do not edit warning.
+
+    Note that this doesn't apply to this file, just the generated output. But I
+    hope that you knew that already. Right?
+    """
+    msg = """~
+~ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+~ !!!!!                               DO NOT EDIT                        !!!!!
+~ !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+~ This file is generated by a Cog template. Please see the original template
+~ at %s
+~""" % cog.inFile
+    if comment_style == 'C':
+	msg = msg.replace('~', '/*', 1)
+	msg = msg.replace('~', ' *')
+	msg += '/'
+    elif comment_style == '#':
+	msg = msg.replace('~', '#')
+    else:
+	raise ValueError("Invalid comment style: %s" % comment_style)
+    cog.outl(msg)

Propchange: team/dlee/stasis-http/cog/stasis_cog.py
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: team/dlee/stasis-http/cog/stasis_cog.py
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Rev URL

Propchange: team/dlee/stasis-http/cog/stasis_cog.py
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: team/dlee/stasis-http/cog/stasis_http_resource.c.cog
URL: http://svnview.digium.com/svn/asterisk/team/dlee/stasis-http/cog/stasis_http_resource.c.cog?view=auto&rev=379041
==============================================================================
--- team/dlee/stasis-http/cog/stasis_http_resource.c.cog (added)
+++ team/dlee/stasis-http/cog/stasis_http_resource.c.cog Mon Jan 14 10:40:35 2013
@@ -1,0 +1,41 @@
+/* -*- C -*-
+ * Asterisk -- An open source telephony toolkit.
+ *
+ * Copyright (C) 2012, Digium, Inc.
+ *
+ * David M. Lee, II <dlee at digium.com>
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE file
+ * at the top of the source tree.
+ */
+
+/*! \file
+ *
+ * \brief Implementation
+ *
+ * \author David M. Lee, II <dlee at digium.com>
+ */
+
+/*** MODULEINFO
+	<support_level>core</support_level>
+ ***/
+
+#include "asterisk.h"
+
+ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
+
+/* [[[cog
+import stasis_cog
+
+root = stasis_cog.Resource('', 'stasis')
+root.load_resource(RESOURCE)
+stasis_cog.ResourceSourceWriter(root).write()
+]]] */
+/*[[[end]]]*/

Propchange: team/dlee/stasis-http/cog/stasis_http_resource.c.cog
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: team/dlee/stasis-http/cog/stasis_http_resource.c.cog
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Rev URL

Propchange: team/dlee/stasis-http/cog/stasis_http_resource.c.cog
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: team/dlee/stasis-http/cog/stasis_http_resource.h.cog
URL: http://svnview.digium.com/svn/asterisk/team/dlee/stasis-http/cog/stasis_http_resource.h.cog?view=auto&rev=379041
==============================================================================
--- team/dlee/stasis-http/cog/stasis_http_resource.h.cog (added)
+++ team/dlee/stasis-http/cog/stasis_http_resource.h.cog Mon Jan 14 10:40:35 2013
@@ -1,0 +1,36 @@
+/* -*- C -*-
+ * Asterisk -- An open source telephony toolkit.
+ *
+ * Copyright (C) 2012, Digium, Inc.
+ *
+ * David M. Lee, II <dlee at digium.com>
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE file
+ * at the top of the source tree.
+ */
+
+/*! \file
+ *
+ * \brief Generated file - declares stubs to be implemented for stasis_http
+ *
+ * \author David M. Lee, II <dlee at digium.com>
+ */
+
+#include "asterisk/stasis_http.h"
+
+/* [[[cog
+import stasis_cog
+
+stasis_cog.do_not_edit()
+root = stasis_cog.Resource('', 'stasis')
+root.load_resource(RESOURCE)
+stasis_cog.ResourceHeaderWriter(root).write()
+]]] */
+/*[[[end]]]*/

Propchange: team/dlee/stasis-http/cog/stasis_http_resource.h.cog
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: team/dlee/stasis-http/cog/stasis_http_resource.h.cog
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Rev URL

Propchange: team/dlee/stasis-http/cog/stasis_http_resource.h.cog
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: team/dlee/stasis-http/cog/stasis_http_resources.c.cog
URL: http://svnview.digium.com/svn/asterisk/team/dlee/stasis-http/cog/stasis_http_resources.c.cog?view=auto&rev=379041
==============================================================================
--- team/dlee/stasis-http/cog/stasis_http_resources.c.cog (added)
+++ team/dlee/stasis-http/cog/stasis_http_resources.c.cog Mon Jan 14 10:40:35 2013
@@ -1,0 +1,50 @@
+/* -*- C -*-
+ * Asterisk -- An open source telephony toolkit.
+ *
+ * Copyright (C) 2012, Digium, Inc.
+ *
+ * David M. Lee, II <dlee at digium.com>
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE file
+ * at the top of the source tree.
+ */
+
+/*! \file
+ *
+ * \brief Generated file - provides Stasis API HTTP entry points
+ *
+ * \author David M. Lee, II <dlee at digium.com>
+ */
+
+/*** MODULEINFO
+	<support_level>core</support_level>
+ ***/
+
+#include "asterisk.h"
+
+ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
+
+#include "asterisk/stasis_http.h"
+#include "asterisk/strings.h"
+
+/* [[[cog
+import stasis_cog
+
+stasis_cog.do_not_edit()
+
+root = stasis_cog.Resource('', 'stasis')
+root.load_resources(RESOURCES)
+stasis_cog.ResourcesSourceWriter(root).write()
+]]] */
+/*[[[end]]]*/
+
+struct stasis_rest_handlers *stasis_root_handler(void) {
+	return &stasis;
+}

Propchange: team/dlee/stasis-http/cog/stasis_http_resources.c.cog
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: team/dlee/stasis-http/cog/stasis_http_resources.c.cog
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Rev URL

Propchange: team/dlee/stasis-http/cog/stasis_http_resources.c.cog
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Modified: team/dlee/stasis-http/include/asterisk/autoconfig.h.in
URL: http://svnview.digium.com/svn/asterisk/team/dlee/stasis-http/include/asterisk/autoconfig.h.in?view=diff&rev=379041&r1=379040&r2=379041
==============================================================================
--- team/dlee/stasis-http/include/asterisk/autoconfig.h.in (original)
+++ team/dlee/stasis-http/include/asterisk/autoconfig.h.in Mon Jan 14 10:40:35 2013
@@ -1144,6 +1144,9 @@
 /* Define to the version of this package. */
 #undef PACKAGE_VERSION
 
+/* Define to 1 if the C compiler supports function prototypes. */
+#undef PROTOTYPES
+
 /* Define to necessary symbol if this constant uses a non-standard name on
    your system. */
 #undef PTHREAD_CREATE_JOINABLE
@@ -1162,6 +1165,11 @@
 
 /* Define to the type of arg 5 for `select'. */
 #undef SELECT_TYPE_ARG5
+
+/* Define to 1 if the `setvbuf' function takes the buffering type as its
+   second argument and the buffer pointer as the third, as on System V before
+   release 3. */
+#undef SETVBUF_REVERSED
 
 /* The size of `char *', as computed by sizeof. */
 #undef SIZEOF_CHAR_P
@@ -1198,54 +1206,58 @@
 /* Define to a type of the same size as fd_set.fds_bits[[0]] */
 #undef TYPEOF_FD_SET_FDS_BITS
 
-/* Enable extensions on AIX 3, Interix.  */
+/* Define to 1 if on AIX 3.
+   System headers sometimes define this.
+   We just want to avoid a redefinition error message.  */
 #ifndef _ALL_SOURCE
 # undef _ALL_SOURCE
 #endif
+
+/* Define to 1 if running on Darwin. */
+#undef _DARWIN_UNLIMITED_SELECT
+
+/* Enable large inode numbers on Mac OS X 10.5.  */
+#ifndef _DARWIN_USE_64_BIT_INODE
+# define _DARWIN_USE_64_BIT_INODE 1
+#endif
+
+/* Number of bits in a file offset, on hosts where this is settable. */
+#undef _FILE_OFFSET_BITS
+
 /* Enable GNU extensions on systems that have them.  */
 #ifndef _GNU_SOURCE
 # undef _GNU_SOURCE
 #endif
-/* Enable threading extensions on Solaris.  */
+
+/* Define to 1 to make fseeko visible on some hosts (e.g. glibc 2.2). */
+#undef _LARGEFILE_SOURCE
+
+/* Define for large files, on AIX-style hosts. */
+#undef _LARGE_FILES
+
+/* Define to 1 if on MINIX. */
+#undef _MINIX
+
+/* Define to 2 if the system does not provide POSIX.1 features except with
+   this defined. */
+#undef _POSIX_1_SOURCE
+
+/* Define to 1 if you need to in order for `stat' and other things to work. */
+#undef _POSIX_SOURCE
+
+/* Enable extensions on Solaris.  */
+#ifndef __EXTENSIONS__
+# undef __EXTENSIONS__
+#endif
 #ifndef _POSIX_PTHREAD_SEMANTICS
 # undef _POSIX_PTHREAD_SEMANTICS
 #endif
-/* Enable extensions on HP NonStop.  */
 #ifndef _TANDEM_SOURCE
 # undef _TANDEM_SOURCE
 #endif
-/* Enable general extensions on Solaris.  */
-#ifndef __EXTENSIONS__
-# undef __EXTENSIONS__
-#endif
-
-
-/* Define to 1 if running on Darwin. */
-#undef _DARWIN_UNLIMITED_SELECT
-
-/* Enable large inode numbers on Mac OS X 10.5.  */
-#ifndef _DARWIN_USE_64_BIT_INODE
-# define _DARWIN_USE_64_BIT_INODE 1
-#endif
-
-/* Number of bits in a file offset, on hosts where this is settable. */
-#undef _FILE_OFFSET_BITS
-
-/* Define to 1 to make fseeko visible on some hosts (e.g. glibc 2.2). */
-#undef _LARGEFILE_SOURCE
-
-/* Define for large files, on AIX-style hosts. */
-#undef _LARGE_FILES
-
-/* Define to 1 if on MINIX. */
-#undef _MINIX
-
-/* Define to 2 if the system does not provide POSIX.1 features except with
-   this defined. */
-#undef _POSIX_1_SOURCE
-
-/* Define to 1 if you need to in order for `stat' and other things to work. */
-#undef _POSIX_SOURCE
+
+/* Define like PROTOTYPES; this can be used by system headers. */
+#undef __PROTOTYPES
 
 /* Define to empty if `const' does not conform to ANSI C. */
 #undef const

Modified: team/dlee/stasis-http/include/asterisk/http.h
URL: http://svnview.digium.com/svn/asterisk/team/dlee/stasis-http/include/asterisk/http.h?view=diff&rev=379041&r1=379040&r2=379041
==============================================================================
--- team/dlee/stasis-http/include/asterisk/http.h (original)
+++ team/dlee/stasis-http/include/asterisk/http.h Mon Jan 14 10:40:35 2013
@@ -58,7 +58,9 @@
 	AST_HTTP_GET = 0,
 	AST_HTTP_POST,
 	AST_HTTP_HEAD,
-	AST_HTTP_PUT,            /*!< Not supported in Asterisk */
+	AST_HTTP_PUT,
+	AST_HTTP_DELETE,
+	AST_HTTP_MAX_METHOD, /*!< Last entry in ast_http_method enum */
 };
 
 struct ast_http_uri;

Added: team/dlee/stasis-http/include/asterisk/stasis.h
URL: http://svnview.digium.com/svn/asterisk/team/dlee/stasis-http/include/asterisk/stasis.h?view=auto&rev=379041
==============================================================================
--- team/dlee/stasis-http/include/asterisk/stasis.h (added)
+++ team/dlee/stasis-http/include/asterisk/stasis.h Mon Jan 14 10:40:35 2013
@@ -1,0 +1,41 @@
+/*
+ * Asterisk -- An open source telephony toolkit.
+ *
+ * Copyright (C) 2012, Digium, Inc.
+ *
+ * David M. Lee, II <dlee at digium.com>
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE file
+ * at the top of the source tree.
+ */
+
+#ifndef _ASTERISK_STASIS_H
+#define _ASTERISK_STASIS_H
+
+/*! \file
+ *
+ * \brief Stasis message bus.
+ *
+ * \author David M. Lee, II <dlee at digium.com>
+ */
+
+/*!
+ * Invoke stasis application for a given channel, with the given arguments.
+ *
+ * \param app_name Name of the application to invoke
+ * \param chan Channel to invoke application upon
+ * \param argc Number of arguments to pass into the application
+ * \param argv Argument array.
+ * \return 0 for success; -1 for error.
+ */
+int stasis_app_invoke(const char *app_name, struct ast_channel *chan, int argc, char *argv[]);
+
+
+#endif /* _ASTERISK_STASIS_H */

Propchange: team/dlee/stasis-http/include/asterisk/stasis.h
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: team/dlee/stasis-http/include/asterisk/stasis.h
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Rev URL

Propchange: team/dlee/stasis-http/include/asterisk/stasis.h
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: team/dlee/stasis-http/include/asterisk/stasis_http.h
URL: http://svnview.digium.com/svn/asterisk/team/dlee/stasis-http/include/asterisk/stasis_http.h?view=auto&rev=379041
==============================================================================
--- team/dlee/stasis-http/include/asterisk/stasis_http.h (added)
+++ team/dlee/stasis-http/include/asterisk/stasis_http.h Mon Jan 14 10:40:35 2013
@@ -1,0 +1,53 @@
+/*
+ * Asterisk -- An open source telephony toolkit.
+ *
+ * Copyright (C) 2012, Digium, Inc.
+ *
+ * David M. Lee, II <dlee at digium.com>
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE file
+ * at the top of the source tree.
+ */
+
+#ifndef _ASTERISK_STASIS_HTTP_H
+#define _ASTERISK_STASIS_HTTP_H
+
+/*! \file
+ *
+ * \brief Stasis RESTful API hooks.
+ *
+ * \author David M. Lee, II <dlee at digium.com>
+ */
+
+#include "asterisk/http.h"
+#include "asterisk/json.h"
+
+struct stasis_http_response {

[... 3255 lines stripped ...]



More information about the asterisk-commits mailing list