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

Initialized gcloud dns. #71

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
16 changes: 16 additions & 0 deletions gcloud/dns/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
__version__ = '0.1'

# TODO: Allow specific scopes and authorization levels.
SCOPE = ('https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/ndev.clouddns.readonly',
'https://www.googleapis.com/auth/ndev.clouddns.readwrite')
"""The scope required for authenticating as a Cloud DNS consumer."""


def get_connection(project_name, client_email, private_key_path):
from gcloud.credentials import Credentials
from gcloud.dns.connection import Connection

credentials = Credentials.get_for_service_account(
client_email, private_key_path, scope=SCOPE)
return Connection(project_name=project_name, credentials=credentials)
10 changes: 10 additions & 0 deletions gcloud/dns/changes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
class Changes(object):

This comment was marked as spam.

This comment was marked as spam.


def __init__(self, connection=None, additions=None, deletions=None, id=None,
kind=None, status=None):
self.connection = connection
self.additions = additions
self.deletions = deletions
self.id = id
self.kind = kind
self.status = status
148 changes: 148 additions & 0 deletions gcloud/dns/connection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import json
import urllib

from gcloud import connection
from gcloud.dns import exceptions
from gcloud.dns.project import Project
from gcloud.dns.managed_zone import ManagedZone


class Connection(connection.Connection):

This comment was marked as spam.


API_BASE_URL = 'https://www.googleapis.com'
"""The base of the API call URL."""

API_VERSION = 'v1beta1'
"""The version of the API, used in building the API call's URL."""

API_URL_TEMPLATE = ('{api_base_url}/dns/{api_version}/projects/{path}')
"""A template used to craft the URL pointing toward a particular API call."""

_EMPTY = object()
"""A pointer to represent an empty value for default arguments."""

def __init__(self, project_name=None, *args, **kwargs):

This comment was marked as spam.


super(Connection, self).__init__(*args, **kwargs)

self.project_name = project_name

def build_api_url(self, path, query_params=None, api_base_url=None,
api_version=None):

url = self.API_URL_TEMPLATE.format(
api_base_url=(api_base_url or self.API_BASE_URL),
api_version=(api_version or self.API_VERSION),
path=path)

query_params = query_params or {}
query_params.update({'project': self.project_name})
url += '?' + urllib.urlencode(query_params)

return url

def make_request(self, method, url, data=None, content_type=None,
headers=None):

headers = headers or {}
headers['Accept-Encoding'] = 'gzip'

if data:
content_length = len(str(data))
else:
content_length = 0

headers['Content-Length'] = content_length

if content_type:
headers['Content-Type'] = content_type

return self.http.request(uri=url, method=method, headers=headers,
body=data)

def api_request(self, method, path=None, query_params=None,
data=None, content_type=None,
api_base_url=None, api_version=None,
expect_json=True):

url = self.build_api_url(path=path, query_params=query_params,
api_base_url=api_base_url,
api_version=api_version)
print url
# Making the executive decision that any dictionary
# data will be sent properly as JSON.
if data and isinstance(data, dict):
data = json.dumps(data)
content_type = 'application/json'

response, content = self.make_request(
method=method, url=url, data=data, content_type=content_type)

# TODO: Add better error handling.
if response.status == 404:
raise exceptions.NotFoundError(response, content)
elif not 200 <= response.status < 300:
raise exceptions.ConnectionError(response, content)

if content and expect_json:
# TODO: Better checking on this header for JSON.
content_type = response.get('content-type', '')
if not content_type.startswith('application/json'):
raise TypeError('Expected JSON, got %s' % content_type)
return json.loads(content)

return content

def get_project(self, project):

This comment was marked as spam.

project = self.new_project(project)
response = self.api_request(method='GET', path=project.path)
return Project.from_dict(response, connection=self)

def new_project(self, project):
if isinstance(project, Project):
return project

# Support Python 2 and 3.
try:
string_type = basestring
except NameError:
string_type = str

if isinstance(project, string_type):
return Project(connection=self)

def create_managed_zone(self, data):

This comment was marked as spam.

managed_zone = self.new_managed_zone(data['name'])
response = self.api_request(method='POST', path=managed_zone.path,
data=data)
return ManagedZone.from_dict(response, connection=self)

def delete_managed_zone(self, managed_zone):
managed_zone = self.new_managed_zone(managed_zone)
self.api_request(method='DELETE', path=managed_zone.path +
managed_zone.name)
return True

def get_managed_zone(self, managed_zone):
managed_zone = self.new_managed_zone(managed_zone)
response = self.api_request(method='GET', path=managed_zone.path)
return ManagedZone.from_dict(response['managedZones'][0],
connection=self)

def list_managed_zones(self):
managed_zone = self.new_managed_zone('test')
response = self.api_request(method='GET', path=managed_zone.path)
print json.dumps(response, indent=2)

def new_managed_zone(self, managed_zone):
if isinstance(managed_zone, ManagedZone):
return managed_zone

# Support Python 2 and 3.
try:
string_type = basestring
except NameError:
string_type = str

if isinstance(managed_zone, string_type):
return ManagedZone(connection=self, name=managed_zone)
15 changes: 15 additions & 0 deletions gcloud/dns/demo/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import os
from gcloud import dns


__all__ = ['get_connection', 'CLIENT_EMAIL', 'PRIVATE_KEY_PATH',
'PROJECT_NAME']


CLIENT_EMAIL = '524635209885-rda26ks46309o10e0nc8rb7d33rn0hlm@developer.gserviceaccount.com'

This comment was marked as spam.

PRIVATE_KEY_PATH = os.path.join(os.path.dirname(__file__), 'demo.key')
PROJECT_NAME = 'gceremote'


def get_connection():
return dns.get_connection(PROJECT_NAME, CLIENT_EMAIL, PRIVATE_KEY_PATH)

This comment was marked as spam.

Binary file added gcloud/dns/demo/demo.key
Binary file not shown.
8 changes: 8 additions & 0 deletions gcloud/dns/demo/demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Welcome to the gCloud DNS Demo! (hit enter)

# We're going to walk through some of the basics...,
# Don't worry though. You don't need to do anything, just keep hitting enter...

# Let's start by importing the demo module and getting a connection:
from gcloud.dns import demo
connection = demo.get_connection()
18 changes: 18 additions & 0 deletions gcloud/dns/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# TODO: Make these super useful.


class DNSError(Exception):

This comment was marked as spam.

pass


class ConnectionError(DNSError):

def __init__(self, response, content):
message = str(response) + content
super(ConnectionError, self).__init__(message)


class NotFoundError(DNSError):

def __init__(self, response, content):
self.message = 'GET %s returned a 404.' % (response.url)
21 changes: 21 additions & 0 deletions gcloud/dns/extras
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
def create_change(self, project, managed_zone):
response = self.api_request(method='POST',
path='%s/managedZones/%s/changes'
% (project, managed_zone))
print json.dumps(response, indent=2)

def get_change(self, project, managed_zone, change_id):
response = self.api_request(method='GET',
path='%s/managedZones/%s/changes/%s'
% (project, managed_zone, change_id))
print json.dumps(response, indent=2)

def list_change(self, project, managed_zone):
response = self.api_request(method='GET', path='%s/managedZones/%s/changes'
% (project, managed_zone))
print json.dumps(response, indent=2)

def list_resource_record_sets(self, project, managed_zone):
response = self.api_request(method='GET', path='%s/managedZones/%s/rrsets'
% (project, managed_zone))
print json.dumps(response, indent=2)
39 changes: 39 additions & 0 deletions gcloud/dns/managed_zone.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
class ManagedZone(object):

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.


def __init__(self, connection=None, creationTime=None, description=None,
dnsName=None, id=None, kind=None, name=None, nameServers=None):

self.connection = connection
self.creationTime = creationTime
self.description = description
self.dnsName = dnsName
self.id = id
self.kind = kind
self.name = name
self.nameServers = nameServers

This comment was marked as spam.


@property
def path(self):
"""The URL path to this managed zone."""

if not self.connection.project_name:
raise ValueError('Cannot determine path without project name.')

return self.connection.project_name + '/managedZones/'

@classmethod
def from_dict(cls, managed_zone_dict, connection=None):

return cls(connection=connection,
creationTime=managed_zone_dict['creationTime'],
description=managed_zone_dict['description'],
dnsName=managed_zone_dict['dnsName'],
id=managed_zone_dict['id'],
kind=managed_zone_dict['kind'], name=managed_zone_dict['name'],
nameServers=managed_zone_dict['nameServers'])

def delete(self):
return self.connection.delete_managed_zone(self)

def get(self):
return self.connection.get_managed_zone(self)
29 changes: 29 additions & 0 deletions gcloud/dns/project.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class Project(object):

This comment was marked as spam.


def __init__(self, connection=None, id=None, kind=None, number=None,
quota=None):

self.connection = connection
self.id = id
self.kind = kind
self.number = number
self.quota = quota

@property
def path(self):
"""The URL path to this instances."""

if not self.connection.project_name:
raise ValueError('Cannot determine path without project name.')

return self.connection.project_name

@classmethod
def from_dict(cls, project_dict, connection=None):

return cls(connection=connection, id=project_dict['id'],
kind=project_dict['kind'], number=project_dict['number'],
quota=project_dict['quota'])

def get(self):
return self.connection.get_project(self)
6 changes: 6 additions & 0 deletions gcloud/dns/resource_record_sets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
class ResourceRecordSets(object):

This comment was marked as spam.


def __init__(self, connection=None, kind=None, name=None, rrdatas=None,
ttl=None, type=None):

self.connection = connection