Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

First take #1

Merged
merged 3 commits into from
Oct 22, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
*.project
*.pydev*
.DS_Store
*.pyc
dropin.cache
12 changes: 12 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
Copyright 2012-2013 Rackspace, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
Empty file added mimic/__init__.py
Empty file.
Empty file.
66 changes: 66 additions & 0 deletions mimic/canned_responses/auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"""
Canned response for get auth token
"""
from datetime import datetime, timedelta


get_token = {
"access": {
"token": {
"id": "fff73937db5047b8b12fc9691ea5b9e8",
"expires": ((datetime.now() + timedelta(1)).
strftime(('%Y-%m-%dT%H:%M:%S.999-05:00'))),
"tenant": {
"id": "851153",
"name": "851153"},
"RAX-AUTH:authenticatedBy": ["PASSWORD"]},
"serviceCatalog": [
{"name": "cloudServersOpenStack",
"endpoints": [{"region": "ORD",
"tenantId": "851153",
"publicURL": "http://10.20.76.72:8909/v2/851153/servers"}],
"type": "compute"},
{"name": "cloudLoadBalancers",
"endpoints": [{"region": "ORD",
"tenantId": "851153",
"publicURL": "http://10.20.76.72:8909/v2/851153/loadbalancers"}],
"type": "rax:load-balancer"}]}}


def get_user():
return {'user': {'id': 'autoscaleprod'}}


def get_user_token(expires_in):
return {
"access":
{"token":
{"id": "sample12auth12token12f0r12otter",
"expires": ((datetime.now() + timedelta(seconds=int(expires_in))).
strftime(('%Y-%m-%dT%H:%M:%S.999-05:00')))}
}
}


def get_endpoints():
return {"endpoints": [{"tenantId": "851153",
"region": "ORD",
"id": 19,
"publicURL": "http://10.20.76.72:8909/v2/851153",
"name": "cloudLoadBalancers",
"type": "rax:load-balancer"},
{"tenantId": "851153",
"region": "ORD",
"id": 86,
"publicURL": "http://10.20.76.72:8909/v2/851153",
"name": "autoscale",
"type": "rax:autoscale"},
{"tenantId": "851153",
"region": "ORD",
"id": 303,
"publicURL": "http://10.20.76.72:8909/v2/851153/",
"versionInfo": "http://10.20.76.72:8909/v2",
"versionList": "http://10.20.76.72:8909/",
"name": "cloudServersOpenStack",
"versionId": "2",
"type": "compute"}]}
84 changes: 84 additions & 0 deletions mimic/canned_responses/nova.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
from random import randrange


def get_server(tenant_id, server_id):
"""
Canned response for get server.
The server id provided is substituted in the response
"""
return {"server": {"status": "ACTIVE",
"id": server_id,
"name": 'server-from-above',
"addresses": {
"public": [
{"version": 6,
"addr": "2401:1801:7800:0101:7271:929b:ff18:06de"},
{"version": 4,
"addr": "119.9.41.136"}],
"private": [
{"version": 4,
"addr": "10.176.8.186"}]},
"links": [{
"href": "http://localhost:8909/v2/{0}/servers/{1}".format(tenant_id,
server_id),
"rel": "self"},
{"href": "http://localhost:8909/v2/{0}/servers/{1}".format(tenant_id,
server_id),
"rel": "bookmark"}]}}


def create_server_example(tenant_id):
"""
Canned response for create server
"""
server_id = 'test-server{0}-id-{0}'.format(str(randrange(9999999999)))
return {'server':
{'OS-DCF:diskConfig': 'AUTO',
'id': server_id,
'links': [{'href': 'http://localhost:8909/v2/{0}/servers/{1}'.format(tenant_id, server_id),
'rel': 'self'},
{'href': 'http://localhost:8909/v2/{0}/servers/{1}'.format(tenant_id, server_id),
'rel': 'bookmark'}],
'adminPass': 'testpassword'}}


def get_image(image_id):
"""
Canned response for get image.
The image id provided is substituted in the response
"""
return {'image': {'status': 'ACTIVE', 'id': image_id}}


def get_flavor(flavor_id):
"""
Canned response for get flavor.
The flavor id provided is substituted in the response
"""
return {'flavor': {'name': '512MB Standard Instance',
'id': flavor_id}}


def get_limit():
"""
Canned response for limits for servers. Returns only the absolute limits
"""
return {"limits":
{"absolute": {"maxServerMeta": 40,
"maxPersonality": 5,
"totalPrivateNetworksUsed": 0,
"maxImageMeta": 40,
"maxPersonalitySize": 1000,
"maxSecurityGroupRules": -1,
"maxTotalKeypairs": 100,
"totalCoresUsed": 5,
"totalRAMUsed": 2560,
"totalInstancesUsed": 5,
"maxSecurityGroups": -1,
"totalFloatingIpsUsed": 0,
"maxTotalCores": -1,
"totalSecurityGroupsUsed": 0,
"maxTotalPrivateNetworks": 3,
"maxTotalFloatingIps": -1,
"maxTotalInstances": 200,
"maxTotalRAMSize": 256000}}}
Empty file added mimic/rest/__init__.py
Empty file.
17 changes: 17 additions & 0 deletions mimic/rest/mimicapp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"""
Contains the base Klein app for Mimic.
"""

from klein import Klein


class MimicApp(Klein):
"""
Base app that extends Klein to override route.
"""
def route(self, *args, **kwargs):
"""
Default strict_slashes to False
"""
kwargs['strict_slashes'] = False
return super(MimicApp, self).route(*args, **kwargs)
110 changes: 110 additions & 0 deletions mimic/rest/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
"""
Defines get token from Auth and create, delete, get servers and get images and flavors.
"""
import json
from twisted.web.server import Request

from mimic.canned_responses.auth import (get_token, get_user,
get_user_token, get_endpoints)
from mimic.canned_responses.nova import (get_server, get_limit,
create_server_example,
get_image, get_flavor)
from mimic.rest.mimicapp import MimicApp

Request.defaultContentType = 'application/json'


class Mimic(object):

"""
Rest endpoints for mocked Auth.
"""
app = MimicApp()
cache = {}

@app.route('/v2.0/tokens', methods=['POST'])
def get_service_catalog_and_token(self, request):
"""
Return a service catalog consisting of nova and load balancer mocked
endpoints and an api token.
"""
request.setResponseCode(200)
return json.dumps(get_token)

@app.route('/v1.1/mosso/<string:tenant_id>', methods=['GET'])
def get_username(self, request, tenant_id):
"""
Returns response with username 'autoscaleprod.
"""
request.setResponseCode(301)
return json.dumps(get_user())

@app.route('/v2.0/RAX-AUTH/impersonation-tokens', methods=['POST'])
def get_user_token(self, request):
"""
Return a token id with expiration.
"""
request.setResponseCode(200)
content = json.loads(request.content.read())
expires_in = content['RAX-AUTH:impersonation']['expire-in-seconds']
return json.dumps(get_user_token(expires_in))

@app.route('/v2.0/tokens/<string:token_id>/endpoints', methods=['GET'])
def get_service_catalog(self, request, token_id):
"""
Return a service catalog consisting of nova and load balancer mocked
endpoints.
"""
request.setResponseCode(200)
return json.dumps(get_endpoints())

@app.route('/v2/<string:tenant_id>/servers', methods=['POST'])
def create_server(self, request, tenant_id):
"""
Returns a generic get server response, with status 'ACTIVE'
"""
request.setResponseCode(202)
return json.dumps(create_server_example(tenant_id))

@app.route('/v2/<string:tenant_id>/servers/<string:server_id>', methods=['GET'])
def get_server(self, request, tenant_id, server_id):
"""
Returns a generic get server response, with status 'ACTIVE'
"""
if self.cache.get(server_id):
return request.setResponseCode(404)
else:
self.cache[server_id] = server_id
request.setResponseCode(200)
return json.dumps(get_server(tenant_id, server_id))

@app.route('/v2/<string:tenant_id>/servers/<string:server_id>', methods=['DELETE'])
def delete_server(self, request, tenant_id, server_id):
"""
Returns a 204 response code, for any server id'
"""
return request.setResponseCode(204)

@app.route('/v2/<string:tenant_id>/images/<string:image_id>', methods=['GET'])
def get_image(self, request, tenant_id, image_id):
"""
Returns a get image response, for any given imageid
"""
request.setResponseCode(200)
return json.dumps(get_image(image_id))

@app.route('/v2/<string:tenant_id>/flavors/<string:flavor_id>', methods=['GET'])
def get_flavor(self, request, tenant_id, flavor_id):
"""
Returns a get flavor response, for any given flavorid
"""
request.setResponseCode(200)
return json.dumps(get_flavor(flavor_id))

@app.route('/v2/<string:tenant_id>/limits', methods=['GET'])
def get_limit(self, request, tenant_id):
"""
Returns a get flavor response, for any given flavorid
"""
request.setResponseCode(200)
return json.dumps(get_limit())
22 changes: 22 additions & 0 deletions mimic/tap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from twisted.application.strports import service
from twisted.application.service import MultiService
from twisted.web.server import Site
from mimic.rest.views import Mimic
from twisted.python import usage


class Options(usage.Options):
pass


def makeService(config):
"""
Set up the otter-api service.
"""
s = MultiService()
m = Mimic()
site = Site(m.app.resource())
api_service = service(str(8909), site)
api_service.setServiceParent(s)
site.displayTracebacks = False
return s
5 changes: 5 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
klein==0.2.1
twisted
jsonschema==2.0
treq==0.2.0
unittest2==0.5.1
16 changes: 16 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
Setup file for mimic
"""

from setuptools import setup, find_packages

setup(
name='mimic',
version='0.0.0',
description='Mocks for Autoscale',
packages=find_packages(exclude=[]),
package_data={'': ['LICENSE']},
package_dir={'mimic': 'mimic'},
include_package_data=True,
license=open('LICENSE').read()
)
8 changes: 8 additions & 0 deletions twisted/plugins/mimic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from twisted.application.service import ServiceMaker


mimicService = ServiceMaker(
"mimic Service/",
"mimic.tap",
"Mocks for Autoscale.",
"mimic")