Skip to content

Commit

Permalink
Configuration and logging refactoring
Browse files Browse the repository at this point in the history
* Main config file now in ~/.hahuna directory
* Main configuration is now a singleton
* Loggign level configured in the main configuration file
* Refactored plugins to output debug logs
  • Loading branch information
Ignasi Barrera committed Jan 27, 2012
1 parent 5e4246e commit 28fa291
Show file tree
Hide file tree
Showing 9 changed files with 68 additions and 34 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@ package ready, the *$JYHTONPATH* environment variable needs to be set manually:

export JYTHONPATH=$(YOUR_PROJECT_HOME_DIRECTORY)

You must also copy the **examples/kahuna.conf** file to **/etc/kahuna.conf** and edit
it to configure the connection to your Abiquo Platform. It is also a good choice
You must also copy the **examples/kahuna.conf** file to **$HOME/.kahuna/kahuna.conf**
and edit it to configure the connection to your Abiquo Platform. It is also a good choice
to add the script to your PATH. You could simply create a symlink to the kahuna script
in */usr/local/bin*:

cd <kahuna source directory>
cp examples/kahuna.conf /etc/kahuna.conf # The edit the /etc/kahuna.conf accordingly
cp config/kahuna.conf ~/.kahuna/kahuna.conf # The edit the file accordingly
chmod u+x kahuna.sh
ln -s $(pwd)/kahuna.sh /usr/local/bin/kahuna

Expand Down
10 changes: 10 additions & 0 deletions config/kahuna.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Main configuration file fot Kahuna

[connection]
address = 10.60.1.222
user = admin
pass = xabiquo

[logging]
level = INFO

14 changes: 0 additions & 14 deletions examples/kahuna.conf

This file was deleted.

8 changes: 6 additions & 2 deletions kahuna/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import logging
from config import Config

FORMAT = '%(asctime)-15s %(levelname)s %(message)s'
logging.basicConfig(format=FORMAT)
logger = logging.getLogger("kahuna")
logger.setLevel(logging.DEBUG)

# Load the singleton configuration instance to initialize
# the 'kahuna' logger
Config()

40 changes: 28 additions & 12 deletions kahuna/config.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,47 @@
#!/usr/bin/env jython

import os
import ConfigParser
import logging
import shutil
import ConfigParser
from utils.singleton import singleton

log = logging.getLogger('kahuna')
log.setLevel(logging.INFO)

@singleton
class Config:
""" Main configuration. """
def __init__(self):
config = ConfigParser.SafeConfigParser()
configFound = os.environ['HOME'] + "/tmp/kahuna.conf"
# User config has precedence, then system then /usr/local
files = [os.environ['HOME'] + '/.kahuna.conf', '/etc/kahuna.conf', '/usr/local/etc/kahuna.conf']
config = ConfigParser.SafeConfigParser()
user_dir = os.environ['HOME'] + "/.kahuna"
user_config = user_dir + "/kahuna.conf"
config_found = user_config
# User config has precedence, then system
files = [user_config, '/etc/kahuna.conf']
for file in files:
if os.path.exists(file):
#some debugging
log.debug("Config found in %s" % file)
configFound = file
config_found = file
break

if not os.path.exists(configFound):
log.error("Kahuna config file not found.")
raise IOError("Configuration file not found. " +
"Please, make sure that $HOME/.kahuna.conf or /etc/kahuna.conf exists");
# If no config file exists, copy the default one to the user config
if not os.path.exists(config_found):
log.warn("Kahuna config file not found. Creating the default one to %s" % user_config)
if not os.path.isdir(user_dir):
os.makedirs(user_dir)
shutil.copy('config/kahuna.conf', user_config)
config_found = user_config

config.read(file)
config.read(config_found)
self.address = config.get("connection", "address")
self.user = config.get("connection", "user")
self.password = config.get("connection", "pass")

try:
self.loglevel = config.get("logging", "level")
level = logging._levelNames[self.loglevel]
log.setLevel(level)
except ConfigParser.NoOptionError:
pass

2 changes: 0 additions & 2 deletions kahuna/plugins/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#!/usr/bin/env jython

import os

# Automatically set the __all__ variable with all
Expand Down
6 changes: 6 additions & 0 deletions kahuna/plugins/vm.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/usr/bin/env jython

import logging
from optparse import OptionParser
from kahuna.session import ContextLoader
from kahuna.utils.prettyprint import pprint_vms
Expand All @@ -15,6 +16,8 @@
from org.jclouds.abiquo.domain.exception import AbiquoException
from org.jclouds.rest import AuthorizationException

log = logging.getLogger('kahuna')

class VmPlugin:
""" Virtual machine plugin. """
def __init__(self):
Expand Down Expand Up @@ -157,15 +160,18 @@ def create(self, args):
if not template:
print "No template was found with id %s" % options.template
return
log.debug("Using template: %s" % template.getName())

vdc = helper.find_compatible_virtual_datacenter(context, template)
if not vdc:
print "No virtual datacenter found for: %s" % template.getDiskFormatType()
return
log.debug("Using virtual datacenter: %s" % vdc.getName())

name = "Kahuna-" + context.getIdentity()
vapp = vdc.findVirtualAppliance(VirtualAppliancePredicates.name(name))
if not vapp:
log.debug("Virtual appliance %s not found. Creating it..." % name)
vapp = VirtualAppliance.builder(context, vdc).name(name).build()
vapp.save()

Expand Down
5 changes: 4 additions & 1 deletion kahuna/session.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
#!/usr/bin/env jython

import atexit
import logging

from config import Config
from java.lang import System
from java.util import Properties
from org.jclouds.abiquo import *

log = logging.getLogger('kahuna')

class ContextLoader:
""" Sets the context to call Abiquo's API.
Expand Down Expand Up @@ -40,7 +43,7 @@ def load_context(self):
# Wait at most 2 minutes in Machine discovery
props.put("jclouds.timeouts.InfrastructureClient.discoverSingleMachine", "120000");
props.put("jclouds.timeouts.InfrastructureClient.discoverMultipleMachines", "120000");
print "Connecting to: %s" % endpoint
log.debug("Connecting to: %s" % endpoint)
self.__context = AbiquoContextFactory().createContext(self.__config.user,
self.__config.password, props);
atexit.register(self.__del__) # Close context automatically when exiting
Expand Down
11 changes: 11 additions & 0 deletions kahuna/utils/singleton.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/usr/bin/env jython

def singleton(cls):
""" Singleton decorator. """
instances = {}
def instance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return instance

0 comments on commit 28fa291

Please sign in to comment.