code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class ArticleFavourite(AuthenticatedHandler):
def execute(self):
article = model.Article.get(self.get_param('key'))
user = self.values['user']
if not article or article.draft or article.deletion_date:
self.not_found()
return
if not self.auth():
return
favourite = model.Favourite.gql('WHERE user=:1 AND article=:2', user, article).get()
if not favourite:
favourite = model.Favourite(article=article,
user=user,
article_author_nickname=article.author_nickname,
article_title=article.title,
article_url_path=article.url_path,
user_nickname=user.nickname)
favourite.put()
user.favourites += 1
user.put()
followers = list(self.get_followers(user=user))
followers.append(user.nickname)
followers.extend(self.get_followers(article=article))
followers = list(set(followers))
self.create_event(event_type='article.favourite', followers=followers, user=user, article=article)
if self.get_param('x'):
self.render_json({ 'action': 'added' })
else:
self.redirect('/module/article/%s' % article.url_path)
else:
favourite.delete()
user.favourites -= 1
user.put()
if self.get_param('x'):
self.render_json({ 'action': 'deleted' })
else:
self.redirect('/module/article/%s' % article.url_path)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class ArticleVote(AuthenticatedHandler):
def execute(self):
article = model.Article.get(self.get_param('key'))
if not article or article.draft or article.deletion_date:
self.not_found()
return
if not self.auth():
return
memcache.delete(str(article.key().id()) + '_article')
rating = int(self.get_param('rating'))
if rating < 0:
rating = 0
elif rating > 5:
rating = 5
user = self.values['user']
avg = article.rating_average
if article and article.author.nickname != user.nickname:
vote = model.Vote.gql('WHERE user=:1 and article=:2', user, article).get()
if not vote:
vote = model.Vote(user=user,rating=rating,article=article)
vote.put()
article.rating_count += 1
article.rating_total += rating
article.rating_average = int(article.rating_total / article.rating_count)
article.put()
author = article.author
author.rating_count += 1
author.rating_total += rating
author.rating_average = int(author.rating_total / author.rating_count)
author.put()
avg = article.rating_average
memcache.add(str(article.key().id()) + '_article', article, 0)
if self.get_param('x'):
self.render_json({ 'average': avg, 'votes': article.rating_count })
else:
self.redirect('/module/article/%s' % article.url_path)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
class Dispatcher(BaseHandler):
def execute(self):
referer = self.request.path.split('/', 1)[1]
# if referer.startswith('module'):
# referer = self.request.path.split('/',2)[2]
self.add_tag_cloud()
self.values['tab'] = self.request.path
self.render('templates/%s.html' % referer) | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import re
import model
import datetime
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError
from utilities import Constant
from utilities.AppProperties import AppProperties
class BaseHandler(webapp.RequestHandler):
#########################
### Handler functions ###
#########################
def get(self):
if self.request.url.split('/')[2] == AppProperties().getAppDic().get(Constant.domain):#'vikuit.com':
self.redirect(self.get_application().url + self.request.url.split('/', 3)[3], permanent=True)# 'http://www.vikuit.com/'
return
try:
self.common_stuff()
self.pre_execute()
except CapabilityDisabledError:
self.values = {}
self.render('templates/maintenace.html')
return
def post(self):
self.common_stuff()
self.pre_execute()
def pre_execute(self):
self.execute()
def common_stuff(self):
self.values = {}
self.user = None
import session
#app = model.Application.all().get()
app = self.get_application()
if app:
self.sess = session.Session(app.session_seed)
if self.sess.load():
self.user = self.get_current_user()
elif self.is_google_account():
#google account users.get_current_user()
#user only arrives here 1 time per session
self.user = self.get_current_user()
if self.user:
redirect, self.user = self.store_google_account()
self.sess.store(str(self.user.key()), 7200)
if redirect:
# redirect to preferences page
self.redirect("/module/user.edit")
if self.user.banned_date is not None:
msg = self.getLocale("User '%s' was blocked. Contact with an administrator.") % self.user.nickname()
self.show_error( msg )
else:
self.sess = None
redirect = '%s?%s' % (self.request.path, self.request.query)
self.values['sess'] = self.sess
self.values['redirect'] = redirect
self.values['app'] = self.get_application()
self.values['activity_communities'] = self.communities_by_activity()
#self.values['all_user_communities'] = self.all_user_communities()
if self.user:
self.values['auth'] = self.sess.auth
self.values['logout'] = '/module/user.logout?redirect_to=%s&auth=%s' % (self.quote(redirect), self.sess.auth)
"""
user_data = model.UserData.gql('WHERE email=:1', user.email()).get()
if not user_data:
user_data = model.UserData(email=user.email(),
nickname=user.nickname(),
articles=0,
draft_articles=0,
messages=0,
draft_messages=0,
comments=0,
rating_count=0,
rating_total=0,
rating_average=0,
threads=0,
responses=0,
communities=0,
favourites=0,
public=False)
user_data.put()
self.values['user'] = user_data
"""
# TODO deprecated, use self.user instead
self.values['user'] = self.user
else:
self.user = None
self.values['user'] = None
self.values['login'] = '/module/user.login?redirect_to=%s' % self.quote(redirect) # users.create_login_url(self.values['redirect'])
self.values['glogin'] = users.create_login_url(self.values['redirect'])
#################################################
### Authentication and Autorization functions ###
#################################################
def hash(self, login, p, times=100):
import sha
p = p.encode('ascii', 'ignore')
p = '%s:%s' % (login, p)
for i in range(0, times):
p = sha.new(p).hexdigest()
return p
def can_write(self, community):
if community.all_users is None or community.all_users:
return True
user = self.values['user']
if not user:
return False
if model.CommunityUser.all().filter('community', community).filter('user', user).get():
return True
return False
def check_password(self, user, password):
times = 100
user_password = user.password
s = user.password.split(':')
if len(s) > 1:
times = int(s[0])
user_password = s[1]
return self.hash(user.nickname, password, times) == user_password
def hash_password(self, nickname, password):
times = 1
return '%d:%s' % (times, self.hash(nickname, password, times))
def auth(self):
token = self.values['auth']
b = token == self.get_param('auth')
if not b:
self.forbidden()
return b
def get_current_user(self):
if self.sess.user:##first
return db.get(self.sess.user)
user = users.get_current_user()#login with google account
# if user:
# user = model.UserData.gql('WHERE email=:1', user.email()).get()
return user
def is_google_account(self):
user = users.get_current_user()
if user:
return True
else:
return False
def store_google_account(self):
googleAcc = users.get_current_user()
user = model.UserData.gql('WHERE email=:1', googleAcc.email()).get()
redirectPreferences = False
if user is None:
redirectPreferences = True
nick = self.getNickname(googleAcc.nickname())
user = model.UserData(nickname=nick,
email=googleAcc.email(),
password=None,#Change to optional
articles=0,
draft_articles=0,
messages=0,
draft_messages=0,
comments=0,
rating_count=0,
rating_total=0,
rating_average=0,
threads=0,
responses=0,
communities=0,
favourites=0,
public=False,
contacts=0)
user.registrationType = 1 #Google identifier
user.last_login = datetime.datetime.now()
user.put()
if redirectPreferences:
# Is new user
app = model.Application.all().get()
if app:
app.users += 1
app.put()
memcache.delete('app')
return redirectPreferences, user
def getNickname(self, nick, isMail=True):
if isMail:
return nick.split('@')[0]
else:
return nick
###########################
### Bussiness functions ###
###########################
def add_user_subscription(self, user, subscription_type, subscription_id):
user_subscription = model.UserSubscription(user=user,
user_nickname=user.nickname,
user_email=user.email,
subscription_type=subscription_type,
subscription_id=subscription_id,
creation_date = datetime.datetime.now())
subscription = model.UserSubscription.all().filter('user', user).filter('subscription_type', subscription_type).filter('subscription_id', subscription_id).get()
if subscription is None:
user_subscription.put()
def remove_user_subscription(self, user, subscription_type, subscription_id):
user_subscription = model.UserSubscription.all().filter('user', user).filter('subscription_type', subscription_type).filter('subscription_id', subscription_id).get()
if user_subscription is not None:
user_subscription.delete()
def add_follower(self, community=None, user=None, article=None, thread=None, nickname=None):
object_type = None
obj = None
if user is not None:
object_type = 'user'
obj = user
elif community is not None:
object_type = 'community'
obj = community
elif thread is not None:
object_type = 'thread'
obj = thread
elif article is not None:
object_type = 'article'
obj = article
if object_type is None:
return None
follower = model.Follower.all().filter('object_type', object_type).filter('object_id', obj.key().id()).get()
if follower:
if nickname not in follower.followers:
follower.followers.append(nickname)
follower.put()
else:
follower = model.Follower(object_type=object_type,
object_id=obj.key().id(),
followers=[nickname])
follower.put()
def remove_follower(self, community=None, user=None, article=None, thread=None, nickname=None):
object_type = None
obj = None
if user is not None:
object_type = 'user'
obj = user
elif community is not None:
object_type = 'community'
obj = community
elif thread is not None:
object_type = 'thread'
obj = thread
elif article is not None:
object_type = 'article'
obj = article
if object_type is None:
return None
follower = model.Follower.all().filter('object_type', object_type).filter('object_id', obj.key().id()).get()
if follower:
if nickname in follower.followers:
follower.followers.remove(nickname)
follower.put()
def create_event(self, event_type, followers,
user, user_to=None, community=None, article=None, thread=None, creation_date=None,
response_number=0):
event = model.Event(event_type=event_type,
followers=followers,
user=user,
user_nickname=user.nickname,
response_number=response_number)
if user_to is not None:
event.user_to = user_to
event.user_to_nickname = user_to.nickname
if community is not None:
event.community = community
event.community_title = community.title
event.community_url_path = community.url_path
if article is not None:
event.article = article
event.article_title = article.title
event.article_author_nickname = article.author_nickname
event.article_url_path = article.url_path
if thread is not None:
event.thread = thread
event.thread_title = thread.title
event.thread_url_path = thread.url_path
if creation_date is None:
event.creation_date = datetime.datetime.now()
else:
event.creation_date = creation_date
event.put()
def get_followers(self, user=None, community=None, thread=None, article=None):
object_type = None
obj = None
if user is not None:
object_type = 'user'
obj = user
elif community is not None:
object_type = 'community'
obj = community
elif thread is not None:
object_type = 'thread'
obj = thread
elif article is not None:
object_type = 'article'
obj = article
if object_type is None:
return None
object_id = obj.key().id()
follower = model.Follower.all().filter('object_type', object_type).filter('object_id', object_id).get()
if not follower:
follower = model.Follower(object_type=object_type, object_id=object_id, followers=[])
follower.put()
return follower.followers
def create_task(self, task_type, priority, data):
import simplejson
t = model.Task(task_type=task_type, priority=priority, data=simplejson.dumps(data))
t.put()
def is_contact(self, this_user):
user = self.values['user']
if not user:
return False
if model.Contact.all().filter('user_from', user).filter('user_to', this_user).get():
return True
return False
def create_community_subscribers(self, community):
if not community.subscribers:
com = [g.user.email for g in model.CommunityUser.all().filter('community', community).fetch(1000) ]
community.subscribers = list(set(com))
# I use strings in order to distinguish three values into the templates
# 'True', 'False', and None
def joined(self, community):
gu = model.CommunityUser.gql('WHERE community=:1 and user=:2', community, self.values['user']).get()
if gu is not None:
return 'True'
return 'False'
def communities_by_activity(self):
key = 'activity_communities'
g = memcache.get(key)
if g is not None:
return g
else:
communities = model.Community.all().order('-activity').fetch(15)
memcache.add(key, communities, 3600)
return communities
def all_user_communities(self):
key = 'all_user_communities'
g = memcache.get(key)
if g is not None:
return g
else:
all_user_communities = model.Community.all()
memcache.add(key, all_user_communities, 3600)
return all_user_communities
def add_categories(self):
cats = model.Category.all().order('title').fetch(50)
categories = {}
for category in cats:
# legacy code
if not category.url_path:
category.url_path = self.to_url_path(category.title)
category.put()
# end
if category.parent_category is None:
categories[str(category.key())] = category
for category in cats:
if category.parent_category is not None:
parent_category = categories[str(category.parent_category.key())]
if not parent_category.subcategories:
parent_category.subcategories = []
parent_category.subcategories.append(category)
ret = [categories[key] for key in categories]
ret.sort()
self.values['categories'] = ret
def add_tag_cloud(self):
self.values['tag_cloud'] = self.cache('tag_cloud', self.get_tag_cloud)
def get_tag_cloud(self):
return self.tag_list(model.Tag.all().order('-count').fetch(30))
def parse_tags(self, tag_string):
tags = [self.to_url_path(t) for t in tag_string.split(',')]
return list(set(tags))
def delete_tags(self, tags):
tags=set(tags)
for tag in tags:
t = model.Tag.gql('WHERE tag=:1', tag).get()
if t:
if t.count == 1:
t.delete()
else:
t.count = t.count - 1
t.put()
def update_tags(self, tags):
tags=set(tags)
for tag in tags:
t = model.Tag.gql('WHERE tag=:1', tag).get()
if not t:
tg = model.Tag(tag=tag,count=1)
tg.put()
else:
t.count = t.count + 1
t.put()
def tag_list(self, tags):
tagdict={}
for t in tags:
tagdict[t.tag] = t.count
if not tagdict:
return []
maxcount = max(t.count for t in tags)
taglist = [(tag, 6*tagdict[tag]/maxcount, tagdict[tag]) for tag in tagdict.keys()]
taglist.sort()
return taglist
###############################
### Evnironment And Renders ###
###############################
def create_jinja_environment(self):
env = AppProperties().getJinjaEnv()
env.filters['relativize'] = self.relativize
env.filters['markdown'] = self.markdown
env.filters['smiley'] = self.smiley
env.filters['pagination'] = self.pagination
env.filters['media'] = self.media_content
env.filters['quote'] = self.quote
return env
def get_template(self, env, f):
p = f.split('/')
if p[0] == 'templates':
f = '/'.join(p[1:])
t = env.get_template(f)
return t
def render_chunk(self, f, params):
env = self.create_jinja_environment()
t = self.get_template(env, f)
return t.render(params)
def render(self, f):
self.response.headers['Content-Type'] = 'text/html;charset=UTF-8'
self.response.headers['Pragma'] = 'no-cache'
self.response.headers['Cache-Control'] = 'no-cache'
self.response.headers['Expires'] = 'Wed, 27 Aug 2008 18:00:00 GMT'
self.response.out.write(self.render_chunk(f, self.values))
def render_json(self, data):
import simplejson
self.response.headers['Content-Type'] = 'application/json;charset=UTF-8'
self.response.headers['Pragma'] = 'no-cache'
self.response.headers['Cache-Control'] = 'no-cache'
self.response.headers['Expires'] = 'Wed, 27 Aug 2008 18:00:00 GMT'
self.response.out.write(simplejson.dumps(data))
def relativize(self, value):
now = datetime.datetime.now()
try:
diff = now - value
except TypeError:
return ''
days = diff.days
seconds = diff.seconds
if days > 365:
return self.getLocale("%d years") % (days / 365, ) #u"%d años" % (days / 365, )
if days > 30:
return self.getLocale("%d months") % (days / 30, ) #u"%d meses" % (days / 30, )
if days > 0:
return self.getLocale("%d days") % (days, ) # u"%d días" % (days, )
if seconds > 3600:
return self.getLocale("%d hours") % (seconds / 3600, ) # u"%d horas" % (seconds / 3600, )
if seconds > 60:
return self.getLocale("%d minutes") % (seconds / 60, ) # u"%d minutos" % (seconds / 60, )
return self.getLocale("%d seconds") % (seconds, ) # u"%d segundos" % (seconds, )
def smiley(self, value):
return value
def markdown(self, value):
try:
import markdown
except ImportError:
return "error"
else:
return markdown.markdown(value, [], safe_mode='escape')
def quote(self, value):
import urllib
value = self.get_unicode(value)
return urllib.quote((value).encode('UTF-8'))
def media_content(self,value):
import MediaContentFilters as contents
value=contents.media_content(value)
return value
###########################
### Utilities functions ###
###########################
def mail(self, subject, body, to=[], bcc=[]):
app = self.get_application()
subject = "%s %s" % (app.mail_subject_prefix, subject)
body = """
%s
%s
""" % (body,app.mail_footer)
queue = model.MailQueue(subject=subject, body=body, to=to, bcc=bcc)
queue.put()
def show_error(self, message):
self.values['message'] = message
self.render('templates/error.html')
"""
def handle_exception(self, exception):
self.response.clear()
self.response.set_status(500)
self.render('templates/error500.html')
"""
def not_found(self):
self.response.clear()
self.response.set_status(404)
self.render('templates/error404.html')
def forbidden(self):
self.response.clear()
self.response.set_status(403)
self.render('templates/error403.html')
def getLocale(self, label):
return self.render_chunk("/translator-util.html", {"label": label})
def get_application(self):
return self.cache('app', self.fetch_application)
def fetch_application(self):
return model.Application.all().get()
def value(self, key):
try:
return self.values[key]
except KeyError:
return None
def not_none(self, value):
if not value:
return ''
return value
def get_param(self, key):
return self.get_unicode(self.request.get(key))
def get_unicode(self, value):
try:
value = unicode(value, "utf-8")
except TypeError:
return value
return value
def cache(self, key, function, timeout=0):
# import logging
# logging.debug('looking for %s in the cache' % key)
data = memcache.get(key)
if data is not None:
# logging.debug('%s is already in the cache' % key)
return data
else:
data = function.__call__()
# logging.debug('inserting %s in the cache' % key)
memcache.add(key, data, timeout)
return data
"""
def cache_this(self, function, timeout=600):
key = '%s?%s' % (self.request.path, self.request.query)
return self.cache(key, function, timeout)
def pre_pag(self, query, max, default_order=None):
try:
p = int(self.get_param('p'))
except ValueError:
p = 1
offset = (p-1)*max
o = self.get_param('o')
if o:
query = query.order(o)
self.values['o'] = o
elif default_order:
query = query.order(default_order)
return [obj for obj in query.fetch(max+1, offset)]
def post_pag(self, a, max):
try:
p = int(self.get_param('p'))
except ValueError:
p = 1
self.values['p'] = p
if p > 1:
self.values['prev'] = p-1
l = len(a)
if l > max:
self.values['len'] = max
self.values['next'] = p+1
return a[:max]
self.values['len'] = l
o = self.get_param('o')
if o:
self.values['o'] = o
return a
"""
def paging(self, query, max, default_order=None, total=-1, accepted_orderings=[], key=None, timeout=300):
if total > 0:
pages = total / max
if total % max > 0:
pages += 1
self.values['pages'] = pages
i = 1
pagesList = []
while i <= pages:
pagesList.append(i)
i += 1
self.values['pagesList'] = pagesList
try:
p = int(self.get_param('p'))
if p < 1:
p = 1
except ValueError:
p = 1
self.values['p'] = p
offset = (p-1)*max
#if offset > 1000:
# return None
o = self.get_param('o')
if o and o in accepted_orderings:
query = query.order(o)
self.values['o'] = o
elif default_order:
query = query.order(default_order)
# caching
if not key is None:
a = memcache.get(key)
if a is None:
a = [obj for obj in query.fetch(max+1, offset)]
memcache.add(key, a, timeout)
else:
a = [obj for obj in query.fetch(max+1, offset)]
#
if p > 1:
self.values['prev'] = p-1
l = len(a)
if l > max:
self.values['len'] = max
self.values['next'] = p+1
return a[:max]
self.values['len'] = l
return a
def pagination(self, value):
##Pagination
if self.value('prev') or self.value('next'):
params = []
p = self.value('p')
q = self.value('q')
a = self.value('a')
t = self.value('t')
o = self.value('o')
cat = self.value('cat')
pages = self.value('pages')
# order
if cat:
params.append('cat=%s' % cat)
# query string
if q:
params.append('q=%s' % q)
# type
if t:
params.append('t=%s' % t)
# order
if o:
params.append('o=%s' % o)
# anchor
if a:
a = '#%s' % str(a)
else:
a = ''
self.values['p'] = p
self.values['common'] = '%s%s' % ('&'.join(params), a)
return ''
def to_url_path(self, value):
value = value.lower()
# table = maketrans(u'áéíóúÁÉÍÓÚñÑ', u'aeiouAEIOUnN')
# value = value.translate(table)
value = value.replace(u'á', 'a')
value = value.replace(u'é', 'e')
value = value.replace(u'í', 'i')
value = value.replace(u'ó', 'o')
value = value.replace(u'ú', 'u')
value = value.replace(u'Á', 'A')
value = value.replace(u'É', 'E')
value = value.replace(u'Í', 'I')
value = value.replace(u'Ó', 'O')
value = value.replace(u'Ú', 'U')
value = value.replace(u'ñ', 'n')
value = value.replace(u'Ñ', 'N') # TODO improve + review URL path allowed chars
value = '-'.join(re.findall('[a-zA-Z0-9]+', value))
return value
def clean_ascii(self, value):
# table = maketrans(u'áéíóúÁÉÍÓÚñÑ', u'aeiouAEIOUnN')
# value = value.translate(table)
value = value.replace(u'á', 'a')
value = value.replace(u'é', 'e')
value = value.replace(u'í', 'i')
value = value.replace(u'ó', 'o')
value = value.replace(u'ú', 'u')
value = value.replace(u'Á', 'A')
value = value.replace(u'É', 'E')
value = value.replace(u'Í', 'I')
value = value.replace(u'Ó', 'O')
value = value.replace(u'Ú', 'U')
value = value.replace(u'ñ', 'n')
value = value.replace(u'Ñ', 'N') # TODO improve + review URL path allowed chars
value = ' '.join(re.findall('[a-zA-Z0-9()_\.:;-]+', value))
return value
def unique_url_path(self, model, url_path):
c = 1
url_path_base = url_path
while True:
query = db.Query(model)
query.filter('url_path =', url_path)
count = query.count(1)
if count > 0:
url_path = '%s-%d' % (url_path_base, c)
c = c + 1
continue
break
return url_path | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.MainPage import *
### MODULES ###
# Admin
from handlers.module.admin.Admin import *
from handlers.module.admin.AdminCategories import *
from handlers.module.admin.AdminCategoryEdit import *
from handlers.module.admin.AdminApplication import *
from handlers.module.admin.AdminCommunityAddRelated import *
from handlers.module.admin.AdminUsers import *
from handlers.module.admin.AdminModules import *
from handlers.module.admin.AdminLookAndFeel import *
from handlers.module.admin.AdminGoogle import *
from handlers.module.admin.AdminMail import *
from handlers.module.admin.AdminCache import *
from handlers.module.admin.AdminStats import *
# Articles
from handlers.module.article.ArticleList import *
from handlers.module.article.ArticleEdit import *
from handlers.module.article.ArticleView import *
from handlers.module.article.ArticleTTS import *
from handlers.module.article.ArticleVote import *
from handlers.module.article.ArticleDelete import *
from handlers.module.article.ArticleComment import *
from handlers.module.article.ArticleFavourite import *
from handlers.module.article.ArticleCommentSubscribe import *
from handlers.module.article.ArticleCommentDelete import *
from handlers.module.article.ArticleAddCommunities import *
from handlers.module.article.ArticleCommentEdit import *
from handlers.module.article.ArticleVisit import *
# Communities
from handlers.module.community.CommunityList import *
from handlers.module.community.CommunityEdit import *
from handlers.module.community.CommunityView import *
from handlers.module.community.CommunityMove import *
from handlers.module.community.CommunityDelete import *
# community forums
from handlers.module.community.CommunityForumList import *
from handlers.module.community.CommunityForumEdit import *
from handlers.module.community.CommunityForumView import *
from handlers.module.community.CommunityForumReply import *
from handlers.module.community.CommunityForumSubscribe import *
from handlers.module.community.CommunityForumDelete import *
from handlers.module.community.CommunityThreadEdit import *
from handlers.module.community.CommunityForumMove import *
from handlers.module.community.CommunityForumVisit import *
# community articles
from handlers.module.community.CommunityArticleList import *
from handlers.module.community.CommunityNewArticle import *
from handlers.module.community.CommunityArticleDelete import *
# community users
from handlers.module.community.CommunityUserList import *
from handlers.module.community.CommunityUserUnjoin import *
from handlers.module.community.CommunityUserJoin import *
# Users
from handlers.module.user.UserList import *
from handlers.module.user.UserView import *
from handlers.module.user.UserEdit import *
from handlers.module.user.UserArticles import *
from handlers.module.user.UserLogin import *
from handlers.module.user.UserCommunities import *
from handlers.module.user.UserLogout import *
from handlers.module.user.UserRegister import *
from handlers.module.user.UserChangePassword import *
from handlers.module.user.UserForgotPassword import *
from handlers.module.user.UserResetPassword import *
from handlers.module.user.UserDrafts import *
from handlers.module.user.UserContact import *
from handlers.module.user.UserFavourites import *
from handlers.module.user.UserContacts import *
from handlers.module.user.UserPromote import *
from handlers.module.user.UserEvents import *
from handlers.module.user.UserForums import *
# Blogging
from handlers.module.mblog.MBlogEdit import *
# Messages
from handlers.module.message.MessageEdit import *
from handlers.module.message.MessageSent import *
from handlers.module.message.MessageInbox import *
from handlers.module.message.MessageRead import *
from handlers.module.message.MessageDelete import *
### Common handlers / Other Handlers ###
# forums
from handlers.ForumList import *
#search
from handlers.SearchResult import *
# inviting contacts
from handlers.Invite import *
# feed RSS
from handlers.Feed import *
# images
from handlers.ImageDisplayer import *
from handlers.editor.ImageBrowser import *
from handlers.editor.ImageUploader import *
#Queue
from handlers.MailQueue import *
from handlers.TaskQueue import *
from handlers.Tag import *
from handlers.Search import *
from handlers.Dispatcher import *
from handlers.Initialization import *
from handlers.NotFound import *
from handlers.BaseRest import *
from handlers.Static import *
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
class MainPage(BaseHandler):
def execute(self):
self.values['tab'] = '/'
# memcache.delete('index_articles')
# memcache.delete('index_communities')
# memcache.delete('index_threads')
self.values['articles'] = self.cache('index_articles', self.get_articles)
# self.values['communities'] = self.cache('index_communities', self.get_communities)
self.values['threads'] = self.cache('index_threads', self.get_threads)
self.add_tag_cloud()
# self.add_categories()
self.render('templates/index.html')
def get_articles(self):
return model.Article.all().filter('draft', False).filter('deletion_date', None).order('-creation_date').fetch(5)
# return self.render_chunk('templates/index-articles.html', {'articles': articles})
def get_communities(self):
return model.Community.all().order('-members').fetch(5)
# return self.render_chunk('templates/index-communities.html', {'communities': communities})
def get_threads(self):
return model.Thread.all().filter('parent_thread', None).order('-last_response_date').fetch(5)
# return self.render_chunk('templates/index-threads.html', {'threads': threads})
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Alberto Gimeno <gimenete at gmail dot com>
# (C) Copyright 2008 Ignacio Andreu <plunchete at gmail dot com>
# (C) Copyright 2008 Néstor Salceda <nestor.salceda at gmail dot com>
#
# This file is part of "debug_mode_on".
#
# "debug_mode_on" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "debug_mode_on" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>.
#
from handlers.BaseHandler import *
class Search(BaseHandler):
def execute(self):
q = self.get_param('q')
typ = self.get_param('t')
if typ == 'articles':
query = model.Article.all().filter('draft', False).filter('deletion_date', None).search(q)
self.values['articles'] = self.paging(query, 10)
self.add_tag_cloud()
elif typ == 'forums':
query = model.Thread.all().search(q)
threads = self.paging(query, 10)
# migration
for t in threads:
if not t.url_path:
t.url_path = t.parent_thread.url_path
t.put()
# end migration
self.values['threads'] = threads
else:
query = model.Community.all().search(q)
self.values['communities'] = self.paging(query, 10)
self.values['q'] = q
self.values['t'] = typ
self.render('templates/search.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Juan Luis Belmonte <jlbelmonte at gmail dot com>
#
# This file is part of "debug_mode_on".
#
# "debug_mode_on" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "debug_mode_on" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>.
#
import re
#main method to apply all filters
def media_content(value):
if re.search('youtube',value):
value=youtube(value)
if re.search('vimeo', value):
value=vimeo(value)
# if re.search('slideshare', value):
# value=slideshare(value)
if re.search('veoh', value):
value=veoh(value)
if re.search('metacafe', value):
value=metacafe(value)
if re.search('video\.yahoo', value):
value=yahoovideo(value)
# if re.search('show\.zoho', value):
# value=sohoshow(value)
# if re.search('teachertube', value):
# value=teachertube(value)
return value
# specific methods for the different services
def youtube(text):
targets = re.findall('media=http://\S+.youtube.com/watch\?v=\S+;', text)
for i in targets:
match= re.match('(.*)watch\?v=(\S+);',i)
html = '<p><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/%s"&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/%s"=es&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object></p>' % ( match.community(2), match.community(2))
text=text.replace(i,html)
return text
def vimeo(text):
targets = re.findall('media=\S*vimeo.com/\S+;',text)
for i in targets:
match = re.match('(\S*)vimeo.com/(\S+)',i)
html='<p><object width="400" height="300"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=%s&server=vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=%s&server=vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="400" height="300"></embed></object></p>' % ( match.community(2), match.community(2))
text=text.replace(i,html)
return text
def slideshare(text):
targets = re.findall('(media=\[.*\];)', text)
for i in targets:
match = re.search('id=(.*)&doc=(.*)&w=(.*)',i)
html = '<p><div style="width:425px;text-align:left" id="__ss_%s"><object style="margin:0px" width="%s" height="355"><param name="movie" value="http://static.slideshare.net/swf/ssplayer2.swf?doc=%s"/><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slideshare.net/swf/ssplayer2.swf?doc=%s" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="%s" height="355"/></object></div></p>' %(match.community(1),match.community(3),match.community(2),match.community(2),match.community(3))
text=text.replace(i,html)
return text
def metacafe(text):
targets = re.findall('media=\S+/watch/\d+/\S+/;', text)
for i in targets:
match = re.search('http://www.metacafe.com/watch/(\d+)/(\S+)/', i)
html = '<p><embed src="http://www.metacafe.com/fplayer/%s/%s.swf" width="400" height="345" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"> </embed></p>' %(match.community(1), match.community(2))
text=text.replace(i,html)
return text
def veoh(text):
targets = re.findall('media=\S+veoh.com/videos/\S+;', text)
for i in targets:
match = re.search('http://www.veoh.com/videos/(\S+);',i)
html = '<p><embed src="http://www.veoh.com/veohplayer.swf?permalinkId=%s&id=anonymous&player=videodetailsembedded&videoAutoPlay=0" allowFullScreen="true" width="410" height="341" bgcolor="#FFFFFF" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed></p>' % match.community(1)
text = text.replace(i, html)
return text
def yahoovideo(text):
targets = re.findall('media=\S+video.yahoo.com/\S+/\d+\S+\d+;', text)
for i in targets:
match = re.search('video.yahoo.com/\S+/(\d+)/(\d+);', i)
html='<p><div><object width="512" height="322"><param name="movie" value="http://d.yimg.com/static.video.yahoo.com/yep/YV_YEP.swf?ver=2.2.30" /><param name="allowFullScreen" value="true" /><param name="AllowScriptAccess" VALUE="always" /><param name="bgcolor" value="#000000" /><param name="flashVars" value="id=%s&vid=%s&lang=en-us&intl=us&embed=1" /><embed src="http://d.yimg.com/static.video.yahoo.com/yep/YV_YEP.swf?ver=2.2.30" type="application/x-shockwave-flash" width="512" height="322" allowFullScreen="true" AllowScriptAccess="always" bgcolor="#000000" flashVars="id=%s&vid=%s&lang=en-us&intl=us&embed=1" ></embed></object></div></p>' % (match.community(2),match.community(1),match.community(2),match.community(2))
text = text.replace(i, html)
return text
def teachertube(text):
targets = re.findall('media=\S+/view_video.php\?viewkey=\S+;', text)
for i in targets:
match = re.search('viewkey=(\S+)',i)
url_atom='%3'
html='<embed src="http://www.teachertube.com/skin-p/mediaplayer.swf" width="425" height="350" type="application/x-shockwave-flash" allowfullscreen="true" menu="false" flashvars="height=350&width=425&file=http://www.teachertube.com/flvideo/64252.flv&location=http://www.teachertube.com/skin-p/mediaplayer.swf&logo=http://www.teachertube.com/images/greylogo.swf&searchlink=http://teachertube.com/search_result.php%sFsearch_id%sD&frontcolor=0xffffff&backcolor=0x000000&lightcolor=0xFF0000&screencolor=0xffffff&autostart=false&volume=80&overstretch=fit&link=http://www.teachertube.com/view_video.php?viewkey=%s&linkfromdisplay=true></embed>' % (url_atom, url_atom, match.community(1))
text = text.replace(i, text)
return text
def sohoshow(text):
targets = re.findall('media=\S+show.zoho.com/public/\S+;', text)
for i in targets:
match = re.search('show.zoho.com/public/(\S+)/(\S+);',i)
html='<p><embed height="335" width="450" name="Welcome3" style="border:1px solid #AABBCC" scrolling="no" src="http://show.zoho.com/embed?USER=%s&DOC=%s&IFRAME=yes" frameBorder="0"></embed></p>' % (match.community(1), match.community(2))
text = text.replace(i, text)
return text
def dummy(text):
return text
### skeleton
#def teacherstube(text):
# targets = re.findall('', text)
# for i in targets:
# match = re.search('',text)
# html=
# text = text.replace(i, text)
# return text
| Python |
"""Beautiful Soup
Elixir and Tonic
"The Screen-Scraper's Friend"
http://www.crummy.com/software/BeautifulSoup/
Beautiful Soup parses a (possibly invalid) XML or HTML document into a
tree representation. It provides methods and Pythonic idioms that make
it easy to navigate, search, and modify the tree.
A well-formed XML/HTML document yields a well-formed data
structure. An ill-formed XML/HTML document yields a correspondingly
ill-formed data structure. If your document is only locally
well-formed, you can use this library to find and process the
well-formed part of it.
Beautiful Soup works with Python 2.2 and up. It has no external
dependencies, but you'll have more success at converting data to UTF-8
if you also install these three packages:
* chardet, for auto-detecting character encodings
http://chardet.feedparser.org/
* cjkcodecs and iconv_codec, which add more encodings to the ones supported
by stock Python.
http://cjkpython.i18n.org/
Beautiful Soup defines classes for two main parsing strategies:
* BeautifulStoneSoup, for parsing XML, SGML, or your domain-specific
language that kind of looks like XML.
* BeautifulSoup, for parsing run-of-the-mill HTML code, be it valid
or invalid. This class has web browser-like heuristics for
obtaining a sensible parse tree in the face of common HTML errors.
Beautiful Soup also defines a class (UnicodeDammit) for autodetecting
the encoding of an HTML or XML document, and converting it to
Unicode. Much of this code is taken from Mark Pilgrim's Universal Feed Parser.
For more than you ever wanted to know about Beautiful Soup, see the
documentation:
http://www.crummy.com/software/BeautifulSoup/documentation.html
Here, have some legalese:
Copyright (c) 2004-2010, Leonard Richardson
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the the Beautiful Soup Consortium and All
Night Kosher Bakery nor the names of its contributors may be
used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE, DAMMIT.
"""
from __future__ import generators
__author__ = "Leonard Richardson (leonardr@segfault.org)"
__version__ = "3.2.0"
__copyright__ = "Copyright (c) 2004-2010 Leonard Richardson"
__license__ = "New-style BSD"
from sgmllib import SGMLParser, SGMLParseError
import codecs
import markupbase
import types
import re
import sgmllib
try:
from htmlentitydefs import name2codepoint
except ImportError:
name2codepoint = {}
try:
set
except NameError:
from sets import Set as set
#These hacks make Beautiful Soup able to parse XML with namespaces
sgmllib.tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*')
markupbase._declname_match = re.compile(r'[a-zA-Z][-_.:a-zA-Z0-9]*\s*').match
DEFAULT_OUTPUT_ENCODING = "utf-8"
def _match_css_class(str):
"""Build a RE to match the given CSS class."""
return re.compile(r"(^|.*\s)%s($|\s)" % str)
# First, the classes that represent markup elements.
class PageElement(object):
"""Contains the navigational information for some part of the page
(either a tag or a piece of text)"""
def setup(self, parent=None, previous=None):
"""Sets up the initial relations between this element and
other elements."""
self.parent = parent
self.previous = previous
self.next = None
self.previousSibling = None
self.nextSibling = None
if self.parent and self.parent.contents:
self.previousSibling = self.parent.contents[-1]
self.previousSibling.nextSibling = self
def replaceWith(self, replaceWith):
oldParent = self.parent
myIndex = self.parent.index(self)
if hasattr(replaceWith, "parent")\
and replaceWith.parent is self.parent:
# We're replacing this element with one of its siblings.
index = replaceWith.parent.index(replaceWith)
if index and index < myIndex:
# Furthermore, it comes before this element. That
# means that when we extract it, the index of this
# element will change.
myIndex = myIndex - 1
self.extract()
oldParent.insert(myIndex, replaceWith)
def replaceWithChildren(self):
myParent = self.parent
myIndex = self.parent.index(self)
self.extract()
reversedChildren = list(self.contents)
reversedChildren.reverse()
for child in reversedChildren:
myParent.insert(myIndex, child)
def extract(self):
"""Destructively rips this element out of the tree."""
if self.parent:
try:
del self.parent.contents[self.parent.index(self)]
except ValueError:
pass
#Find the two elements that would be next to each other if
#this element (and any children) hadn't been parsed. Connect
#the two.
lastChild = self._lastRecursiveChild()
nextElement = lastChild.next
if self.previous:
self.previous.next = nextElement
if nextElement:
nextElement.previous = self.previous
self.previous = None
lastChild.next = None
self.parent = None
if self.previousSibling:
self.previousSibling.nextSibling = self.nextSibling
if self.nextSibling:
self.nextSibling.previousSibling = self.previousSibling
self.previousSibling = self.nextSibling = None
return self
def _lastRecursiveChild(self):
"Finds the last element beneath this object to be parsed."
lastChild = self
while hasattr(lastChild, 'contents') and lastChild.contents:
lastChild = lastChild.contents[-1]
return lastChild
def insert(self, position, newChild):
if isinstance(newChild, basestring) \
and not isinstance(newChild, NavigableString):
newChild = NavigableString(newChild)
position = min(position, len(self.contents))
if hasattr(newChild, 'parent') and newChild.parent is not None:
# We're 'inserting' an element that's already one
# of this object's children.
if newChild.parent is self:
index = self.index(newChild)
if index > position:
# Furthermore we're moving it further down the
# list of this object's children. That means that
# when we extract this element, our target index
# will jump down one.
position = position - 1
newChild.extract()
newChild.parent = self
previousChild = None
if position == 0:
newChild.previousSibling = None
newChild.previous = self
else:
previousChild = self.contents[position-1]
newChild.previousSibling = previousChild
newChild.previousSibling.nextSibling = newChild
newChild.previous = previousChild._lastRecursiveChild()
if newChild.previous:
newChild.previous.next = newChild
newChildsLastElement = newChild._lastRecursiveChild()
if position >= len(self.contents):
newChild.nextSibling = None
parent = self
parentsNextSibling = None
while not parentsNextSibling:
parentsNextSibling = parent.nextSibling
parent = parent.parent
if not parent: # This is the last element in the document.
break
if parentsNextSibling:
newChildsLastElement.next = parentsNextSibling
else:
newChildsLastElement.next = None
else:
nextChild = self.contents[position]
newChild.nextSibling = nextChild
if newChild.nextSibling:
newChild.nextSibling.previousSibling = newChild
newChildsLastElement.next = nextChild
if newChildsLastElement.next:
newChildsLastElement.next.previous = newChildsLastElement
self.contents.insert(position, newChild)
def append(self, tag):
"""Appends the given tag to the contents of this tag."""
self.insert(len(self.contents), tag)
def findNext(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the first item that matches the given criteria and
appears after this Tag in the document."""
return self._findOne(self.findAllNext, name, attrs, text, **kwargs)
def findAllNext(self, name=None, attrs={}, text=None, limit=None,
**kwargs):
"""Returns all items that match the given criteria and appear
after this Tag in the document."""
return self._findAll(name, attrs, text, limit, self.nextGenerator,
**kwargs)
def findNextSibling(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the closest sibling to this Tag that matches the
given criteria and appears after this Tag in the document."""
return self._findOne(self.findNextSiblings, name, attrs, text,
**kwargs)
def findNextSiblings(self, name=None, attrs={}, text=None, limit=None,
**kwargs):
"""Returns the siblings of this Tag that match the given
criteria and appear after this Tag in the document."""
return self._findAll(name, attrs, text, limit,
self.nextSiblingGenerator, **kwargs)
fetchNextSiblings = findNextSiblings # Compatibility with pre-3.x
def findPrevious(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the first item that matches the given criteria and
appears before this Tag in the document."""
return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs)
def findAllPrevious(self, name=None, attrs={}, text=None, limit=None,
**kwargs):
"""Returns all items that match the given criteria and appear
before this Tag in the document."""
return self._findAll(name, attrs, text, limit, self.previousGenerator,
**kwargs)
fetchPrevious = findAllPrevious # Compatibility with pre-3.x
def findPreviousSibling(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the closest sibling to this Tag that matches the
given criteria and appears before this Tag in the document."""
return self._findOne(self.findPreviousSiblings, name, attrs, text,
**kwargs)
def findPreviousSiblings(self, name=None, attrs={}, text=None,
limit=None, **kwargs):
"""Returns the siblings of this Tag that match the given
criteria and appear before this Tag in the document."""
return self._findAll(name, attrs, text, limit,
self.previousSiblingGenerator, **kwargs)
fetchPreviousSiblings = findPreviousSiblings # Compatibility with pre-3.x
def findParent(self, name=None, attrs={}, **kwargs):
"""Returns the closest parent of this Tag that matches the given
criteria."""
# NOTE: We can't use _findOne because findParents takes a different
# set of arguments.
r = None
l = self.findParents(name, attrs, 1)
if l:
r = l[0]
return r
def findParents(self, name=None, attrs={}, limit=None, **kwargs):
"""Returns the parents of this Tag that match the given
criteria."""
return self._findAll(name, attrs, None, limit, self.parentGenerator,
**kwargs)
fetchParents = findParents # Compatibility with pre-3.x
#These methods do the real heavy lifting.
def _findOne(self, method, name, attrs, text, **kwargs):
r = None
l = method(name, attrs, text, 1, **kwargs)
if l:
r = l[0]
return r
def _findAll(self, name, attrs, text, limit, generator, **kwargs):
"Iterates over a generator looking for things that match."
if isinstance(name, SoupStrainer):
strainer = name
# (Possibly) special case some findAll*(...) searches
elif text is None and not limit and not attrs and not kwargs:
# findAll*(True)
if name is True:
return [element for element in generator()
if isinstance(element, Tag)]
# findAll*('tag-name')
elif isinstance(name, basestring):
return [element for element in generator()
if isinstance(element, Tag) and
element.name == name]
else:
strainer = SoupStrainer(name, attrs, text, **kwargs)
# Build a SoupStrainer
else:
strainer = SoupStrainer(name, attrs, text, **kwargs)
results = ResultSet(strainer)
g = generator()
while True:
try:
i = g.next()
except StopIteration:
break
if i:
found = strainer.search(i)
if found:
results.append(found)
if limit and len(results) >= limit:
break
return results
#These Generators can be used to navigate starting from both
#NavigableStrings and Tags.
def nextGenerator(self):
i = self
while i is not None:
i = i.next
yield i
def nextSiblingGenerator(self):
i = self
while i is not None:
i = i.nextSibling
yield i
def previousGenerator(self):
i = self
while i is not None:
i = i.previous
yield i
def previousSiblingGenerator(self):
i = self
while i is not None:
i = i.previousSibling
yield i
def parentGenerator(self):
i = self
while i is not None:
i = i.parent
yield i
# Utility methods
def substituteEncoding(self, str, encoding=None):
encoding = encoding or "utf-8"
return str.replace("%SOUP-ENCODING%", encoding)
def toEncoding(self, s, encoding=None):
"""Encodes an object to a string in some encoding, or to Unicode.
."""
if isinstance(s, unicode):
if encoding:
s = s.encode(encoding)
elif isinstance(s, str):
if encoding:
s = s.encode(encoding)
else:
s = unicode(s)
else:
if encoding:
s = self.toEncoding(str(s), encoding)
else:
s = unicode(s)
return s
class NavigableString(unicode, PageElement):
def __new__(cls, value):
"""Create a new NavigableString.
When unpickling a NavigableString, this method is called with
the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be
passed in to the superclass's __new__ or the superclass won't know
how to handle non-ASCII characters.
"""
if isinstance(value, unicode):
return unicode.__new__(cls, value)
return unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING)
def __getnewargs__(self):
return (NavigableString.__str__(self),)
def __getattr__(self, attr):
"""text.string gives you text. This is for backwards
compatibility for Navigable*String, but for CData* it lets you
get the string without the CData wrapper."""
if attr == 'string':
return self
else:
raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr)
def __unicode__(self):
return str(self).decode(DEFAULT_OUTPUT_ENCODING)
def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING):
if encoding:
return self.encode(encoding)
else:
return self
class CData(NavigableString):
def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING):
return "<![CDATA[%s]]>" % NavigableString.__str__(self, encoding)
class ProcessingInstruction(NavigableString):
def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING):
output = self
if "%SOUP-ENCODING%" in output:
output = self.substituteEncoding(output, encoding)
return "<?%s?>" % self.toEncoding(output, encoding)
class Comment(NavigableString):
def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING):
return "<!--%s-->" % NavigableString.__str__(self, encoding)
class Declaration(NavigableString):
def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING):
return "<!%s>" % NavigableString.__str__(self, encoding)
class Tag(PageElement):
"""Represents a found HTML tag with its attributes and contents."""
def _invert(h):
"Cheap function to invert a hash."
i = {}
for k,v in h.items():
i[v] = k
return i
XML_ENTITIES_TO_SPECIAL_CHARS = { "apos" : "'",
"quot" : '"',
"amp" : "&",
"lt" : "<",
"gt" : ">" }
XML_SPECIAL_CHARS_TO_ENTITIES = _invert(XML_ENTITIES_TO_SPECIAL_CHARS)
def _convertEntities(self, match):
"""Used in a call to re.sub to replace HTML, XML, and numeric
entities with the appropriate Unicode characters. If HTML
entities are being converted, any unrecognized entities are
escaped."""
x = match.group(1)
if self.convertHTMLEntities and x in name2codepoint:
return unichr(name2codepoint[x])
elif x in self.XML_ENTITIES_TO_SPECIAL_CHARS:
if self.convertXMLEntities:
return self.XML_ENTITIES_TO_SPECIAL_CHARS[x]
else:
return u'&%s;' % x
elif len(x) > 0 and x[0] == '#':
# Handle numeric entities
if len(x) > 1 and x[1] == 'x':
return unichr(int(x[2:], 16))
else:
return unichr(int(x[1:]))
elif self.escapeUnrecognizedEntities:
return u'&%s;' % x
else:
return u'&%s;' % x
def __init__(self, parser, name, attrs=None, parent=None,
previous=None):
"Basic constructor."
# We don't actually store the parser object: that lets extracted
# chunks be garbage-collected
self.parserClass = parser.__class__
self.isSelfClosing = parser.isSelfClosingTag(name)
self.name = name
if attrs is None:
attrs = []
elif isinstance(attrs, dict):
attrs = attrs.items()
self.attrs = attrs
self.contents = []
self.setup(parent, previous)
self.hidden = False
self.containsSubstitutions = False
self.convertHTMLEntities = parser.convertHTMLEntities
self.convertXMLEntities = parser.convertXMLEntities
self.escapeUnrecognizedEntities = parser.escapeUnrecognizedEntities
# Convert any HTML, XML, or numeric entities in the attribute values.
convert = lambda(k, val): (k,
re.sub("&(#\d+|#x[0-9a-fA-F]+|\w+);",
self._convertEntities,
val))
self.attrs = map(convert, self.attrs)
def getString(self):
if (len(self.contents) == 1
and isinstance(self.contents[0], NavigableString)):
return self.contents[0]
def setString(self, string):
"""Replace the contents of the tag with a string"""
self.clear()
self.append(string)
string = property(getString, setString)
def getText(self, separator=u""):
if not len(self.contents):
return u""
stopNode = self._lastRecursiveChild().next
strings = []
current = self.contents[0]
while current is not stopNode:
if isinstance(current, NavigableString):
strings.append(current.strip())
current = current.next
return separator.join(strings)
text = property(getText)
def get(self, key, default=None):
"""Returns the value of the 'key' attribute for the tag, or
the value given for 'default' if it doesn't have that
attribute."""
return self._getAttrMap().get(key, default)
def clear(self):
"""Extract all children."""
for child in self.contents[:]:
child.extract()
def index(self, element):
for i, child in enumerate(self.contents):
if child is element:
return i
raise ValueError("Tag.index: element not in tag")
def has_key(self, key):
return self._getAttrMap().has_key(key)
def __getitem__(self, key):
"""tag[key] returns the value of the 'key' attribute for the tag,
and throws an exception if it's not there."""
return self._getAttrMap()[key]
def __iter__(self):
"Iterating over a tag iterates over its contents."
return iter(self.contents)
def __len__(self):
"The length of a tag is the length of its list of contents."
return len(self.contents)
def __contains__(self, x):
return x in self.contents
def __nonzero__(self):
"A tag is non-None even if it has no contents."
return True
def __setitem__(self, key, value):
"""Setting tag[key] sets the value of the 'key' attribute for the
tag."""
self._getAttrMap()
self.attrMap[key] = value
found = False
for i in range(0, len(self.attrs)):
if self.attrs[i][0] == key:
self.attrs[i] = (key, value)
found = True
if not found:
self.attrs.append((key, value))
self._getAttrMap()[key] = value
def __delitem__(self, key):
"Deleting tag[key] deletes all 'key' attributes for the tag."
for item in self.attrs:
if item[0] == key:
self.attrs.remove(item)
#We don't break because bad HTML can define the same
#attribute multiple times.
self._getAttrMap()
if self.attrMap.has_key(key):
del self.attrMap[key]
def __call__(self, *args, **kwargs):
"""Calling a tag like a function is the same as calling its
findAll() method. Eg. tag('a') returns a list of all the A tags
found within this tag."""
return apply(self.findAll, args, kwargs)
def __getattr__(self, tag):
#print "Getattr %s.%s" % (self.__class__, tag)
if len(tag) > 3 and tag.rfind('Tag') == len(tag)-3:
return self.find(tag[:-3])
elif tag.find('__') != 0:
return self.find(tag)
raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__, tag)
def __eq__(self, other):
"""Returns true iff this tag has the same name, the same attributes,
and the same contents (recursively) as the given tag.
NOTE: right now this will return false if two tags have the
same attributes in a different order. Should this be fixed?"""
if other is self:
return True
if not hasattr(other, 'name') or not hasattr(other, 'attrs') or not hasattr(other, 'contents') or self.name != other.name or self.attrs != other.attrs or len(self) != len(other):
return False
for i in range(0, len(self.contents)):
if self.contents[i] != other.contents[i]:
return False
return True
def __ne__(self, other):
"""Returns true iff this tag is not identical to the other tag,
as defined in __eq__."""
return not self == other
def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING):
"""Renders this tag as a string."""
return self.__str__(encoding)
def __unicode__(self):
return self.__str__(None)
BARE_AMPERSAND_OR_BRACKET = re.compile("([<>]|"
+ "&(?!#\d+;|#x[0-9a-fA-F]+;|\w+;)"
+ ")")
def _sub_entity(self, x):
"""Used with a regular expression to substitute the
appropriate XML entity for an XML special character."""
return "&" + self.XML_SPECIAL_CHARS_TO_ENTITIES[x.group(0)[0]] + ";"
def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING,
prettyPrint=False, indentLevel=0):
"""Returns a string or Unicode representation of this tag and
its contents. To get Unicode, pass None for encoding.
NOTE: since Python's HTML parser consumes whitespace, this
method is not certain to reproduce the whitespace present in
the original string."""
encodedName = self.toEncoding(self.name, encoding)
attrs = []
if self.attrs:
for key, val in self.attrs:
fmt = '%s="%s"'
if isinstance(val, basestring):
if self.containsSubstitutions and '%SOUP-ENCODING%' in val:
val = self.substituteEncoding(val, encoding)
# The attribute value either:
#
# * Contains no embedded double quotes or single quotes.
# No problem: we enclose it in double quotes.
# * Contains embedded single quotes. No problem:
# double quotes work here too.
# * Contains embedded double quotes. No problem:
# we enclose it in single quotes.
# * Embeds both single _and_ double quotes. This
# can't happen naturally, but it can happen if
# you modify an attribute value after parsing
# the document. Now we have a bit of a
# problem. We solve it by enclosing the
# attribute in single quotes, and escaping any
# embedded single quotes to XML entities.
if '"' in val:
fmt = "%s='%s'"
if "'" in val:
# TODO: replace with apos when
# appropriate.
val = val.replace("'", "&squot;")
# Now we're okay w/r/t quotes. But the attribute
# value might also contain angle brackets, or
# ampersands that aren't part of entities. We need
# to escape those to XML entities too.
val = self.BARE_AMPERSAND_OR_BRACKET.sub(self._sub_entity, val)
attrs.append(fmt % (self.toEncoding(key, encoding),
self.toEncoding(val, encoding)))
close = ''
closeTag = ''
if self.isSelfClosing:
close = ' /'
else:
closeTag = '</%s>' % encodedName
indentTag, indentContents = 0, 0
if prettyPrint:
indentTag = indentLevel
space = (' ' * (indentTag-1))
indentContents = indentTag + 1
contents = self.renderContents(encoding, prettyPrint, indentContents)
if self.hidden:
s = contents
else:
s = []
attributeString = ''
if attrs:
attributeString = ' ' + ' '.join(attrs)
if prettyPrint:
s.append(space)
s.append('<%s%s%s>' % (encodedName, attributeString, close))
if prettyPrint:
s.append("\n")
s.append(contents)
if prettyPrint and contents and contents[-1] != "\n":
s.append("\n")
if prettyPrint and closeTag:
s.append(space)
s.append(closeTag)
if prettyPrint and closeTag and self.nextSibling:
s.append("\n")
s = ''.join(s)
return s
def decompose(self):
"""Recursively destroys the contents of this tree."""
self.extract()
if len(self.contents) == 0:
return
current = self.contents[0]
while current is not None:
next = current.next
if isinstance(current, Tag):
del current.contents[:]
current.parent = None
current.previous = None
current.previousSibling = None
current.next = None
current.nextSibling = None
current = next
def prettify(self, encoding=DEFAULT_OUTPUT_ENCODING):
return self.__str__(encoding, True)
def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING,
prettyPrint=False, indentLevel=0):
"""Renders the contents of this tag as a string in the given
encoding. If encoding is None, returns a Unicode string.."""
s=[]
for c in self:
text = None
if isinstance(c, NavigableString):
text = c.__str__(encoding)
elif isinstance(c, Tag):
s.append(c.__str__(encoding, prettyPrint, indentLevel))
if text and prettyPrint:
text = text.strip()
if text:
if prettyPrint:
s.append(" " * (indentLevel-1))
s.append(text)
if prettyPrint:
s.append("\n")
return ''.join(s)
#Soup methods
def find(self, name=None, attrs={}, recursive=True, text=None,
**kwargs):
"""Return only the first child of this Tag matching the given
criteria."""
r = None
l = self.findAll(name, attrs, recursive, text, 1, **kwargs)
if l:
r = l[0]
return r
findChild = find
def findAll(self, name=None, attrs={}, recursive=True, text=None,
limit=None, **kwargs):
"""Extracts a list of Tag objects that match the given
criteria. You can specify the name of the Tag and any
attributes you want the Tag to have.
The value of a key-value pair in the 'attrs' map can be a
string, a list of strings, a regular expression object, or a
callable that takes a string and returns whether or not the
string matches for some custom definition of 'matches'. The
same is true of the tag name."""
generator = self.recursiveChildGenerator
if not recursive:
generator = self.childGenerator
return self._findAll(name, attrs, text, limit, generator, **kwargs)
findChildren = findAll
# Pre-3.x compatibility methods
first = find
fetch = findAll
def fetchText(self, text=None, recursive=True, limit=None):
return self.findAll(text=text, recursive=recursive, limit=limit)
def firstText(self, text=None, recursive=True):
return self.find(text=text, recursive=recursive)
#Private methods
def _getAttrMap(self):
"""Initializes a map representation of this tag's attributes,
if not already initialized."""
if not getattr(self, 'attrMap'):
self.attrMap = {}
for (key, value) in self.attrs:
self.attrMap[key] = value
return self.attrMap
#Generator methods
def childGenerator(self):
# Just use the iterator from the contents
return iter(self.contents)
def recursiveChildGenerator(self):
if not len(self.contents):
raise StopIteration
stopNode = self._lastRecursiveChild().next
current = self.contents[0]
while current is not stopNode:
yield current
current = current.next
# Next, a couple classes to represent queries and their results.
class SoupStrainer:
"""Encapsulates a number of ways of matching a markup element (tag or
text)."""
def __init__(self, name=None, attrs={}, text=None, **kwargs):
self.name = name
if isinstance(attrs, basestring):
kwargs['class'] = _match_css_class(attrs)
attrs = None
if kwargs:
if attrs:
attrs = attrs.copy()
attrs.update(kwargs)
else:
attrs = kwargs
self.attrs = attrs
self.text = text
def __str__(self):
if self.text:
return self.text
else:
return "%s|%s" % (self.name, self.attrs)
def searchTag(self, markupName=None, markupAttrs={}):
found = None
markup = None
if isinstance(markupName, Tag):
markup = markupName
markupAttrs = markup
callFunctionWithTagData = callable(self.name) \
and not isinstance(markupName, Tag)
if (not self.name) \
or callFunctionWithTagData \
or (markup and self._matches(markup, self.name)) \
or (not markup and self._matches(markupName, self.name)):
if callFunctionWithTagData:
match = self.name(markupName, markupAttrs)
else:
match = True
markupAttrMap = None
for attr, matchAgainst in self.attrs.items():
if not markupAttrMap:
if hasattr(markupAttrs, 'get'):
markupAttrMap = markupAttrs
else:
markupAttrMap = {}
for k,v in markupAttrs:
markupAttrMap[k] = v
attrValue = markupAttrMap.get(attr)
if not self._matches(attrValue, matchAgainst):
match = False
break
if match:
if markup:
found = markup
else:
found = markupName
return found
def search(self, markup):
#print 'looking for %s in %s' % (self, markup)
found = None
# If given a list of items, scan it for a text element that
# matches.
if hasattr(markup, "__iter__") \
and not isinstance(markup, Tag):
for element in markup:
if isinstance(element, NavigableString) \
and self.search(element):
found = element
break
# If it's a Tag, make sure its name or attributes match.
# Don't bother with Tags if we're searching for text.
elif isinstance(markup, Tag):
if not self.text:
found = self.searchTag(markup)
# If it's text, make sure the text matches.
elif isinstance(markup, NavigableString) or \
isinstance(markup, basestring):
if self._matches(markup, self.text):
found = markup
else:
raise Exception, "I don't know how to match against a %s" \
% markup.__class__
return found
def _matches(self, markup, matchAgainst):
#print "Matching %s against %s" % (markup, matchAgainst)
result = False
if matchAgainst is True:
result = markup is not None
elif callable(matchAgainst):
result = matchAgainst(markup)
else:
#Custom match methods take the tag as an argument, but all
#other ways of matching match the tag name as a string.
if isinstance(markup, Tag):
markup = markup.name
if markup and not isinstance(markup, basestring):
markup = unicode(markup)
#Now we know that chunk is either a string, or None.
if hasattr(matchAgainst, 'match'):
# It's a regexp object.
result = markup and matchAgainst.search(markup)
elif hasattr(matchAgainst, '__iter__'): # list-like
result = markup in matchAgainst
elif hasattr(matchAgainst, 'items'):
result = markup.has_key(matchAgainst)
elif matchAgainst and isinstance(markup, basestring):
if isinstance(markup, unicode):
matchAgainst = unicode(matchAgainst)
else:
matchAgainst = str(matchAgainst)
if not result:
result = matchAgainst == markup
return result
class ResultSet(list):
"""A ResultSet is just a list that keeps track of the SoupStrainer
that created it."""
def __init__(self, source):
list.__init__([])
self.source = source
# Now, some helper functions.
def buildTagMap(default, *args):
"""Turns a list of maps, lists, or scalars into a single map.
Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and
NESTING_RESET_TAGS maps out of lists and partial maps."""
built = {}
for portion in args:
if hasattr(portion, 'items'):
#It's a map. Merge it.
for k,v in portion.items():
built[k] = v
elif hasattr(portion, '__iter__'): # is a list
#It's a list. Map each item to the default.
for k in portion:
built[k] = default
else:
#It's a scalar. Map it to the default.
built[portion] = default
return built
# Now, the parser classes.
class BeautifulStoneSoup(Tag, SGMLParser):
"""This class contains the basic parser and search code. It defines
a parser that knows nothing about tag behavior except for the
following:
You can't close a tag without closing all the tags it encloses.
That is, "<foo><bar></foo>" actually means
"<foo><bar></bar></foo>".
[Another possible explanation is "<foo><bar /></foo>", but since
this class defines no SELF_CLOSING_TAGS, it will never use that
explanation.]
This class is useful for parsing XML or made-up markup languages,
or when BeautifulSoup makes an assumption counter to what you were
expecting."""
SELF_CLOSING_TAGS = {}
NESTABLE_TAGS = {}
RESET_NESTING_TAGS = {}
QUOTE_TAGS = {}
PRESERVE_WHITESPACE_TAGS = []
MARKUP_MASSAGE = [(re.compile('(<[^<>]*)/>'),
lambda x: x.group(1) + ' />'),
(re.compile('<!\s+([^<>]*)>'),
lambda x: '<!' + x.group(1) + '>')
]
ROOT_TAG_NAME = u'[document]'
HTML_ENTITIES = "html"
XML_ENTITIES = "xml"
XHTML_ENTITIES = "xhtml"
# TODO: This only exists for backwards-compatibility
ALL_ENTITIES = XHTML_ENTITIES
# Used when determining whether a text node is all whitespace and
# can be replaced with a single space. A text node that contains
# fancy Unicode spaces (usually non-breaking) should be left
# alone.
STRIP_ASCII_SPACES = { 9: None, 10: None, 12: None, 13: None, 32: None, }
def __init__(self, markup="", parseOnlyThese=None, fromEncoding=None,
markupMassage=True, smartQuotesTo=XML_ENTITIES,
convertEntities=None, selfClosingTags=None, isHTML=False):
"""The Soup object is initialized as the 'root tag', and the
provided markup (which can be a string or a file-like object)
is fed into the underlying parser.
sgmllib will process most bad HTML, and the BeautifulSoup
class has some tricks for dealing with some HTML that kills
sgmllib, but Beautiful Soup can nonetheless choke or lose data
if your data uses self-closing tags or declarations
incorrectly.
By default, Beautiful Soup uses regexes to sanitize input,
avoiding the vast majority of these problems. If the problems
don't apply to you, pass in False for markupMassage, and
you'll get better performance.
The default parser massage techniques fix the two most common
instances of invalid HTML that choke sgmllib:
<br/> (No space between name of closing tag and tag close)
<! --Comment--> (Extraneous whitespace in declaration)
You can pass in a custom list of (RE object, replace method)
tuples to get Beautiful Soup to scrub your input the way you
want."""
self.parseOnlyThese = parseOnlyThese
self.fromEncoding = fromEncoding
self.smartQuotesTo = smartQuotesTo
self.convertEntities = convertEntities
# Set the rules for how we'll deal with the entities we
# encounter
if self.convertEntities:
# It doesn't make sense to convert encoded characters to
# entities even while you're converting entities to Unicode.
# Just convert it all to Unicode.
self.smartQuotesTo = None
if convertEntities == self.HTML_ENTITIES:
self.convertXMLEntities = False
self.convertHTMLEntities = True
self.escapeUnrecognizedEntities = True
elif convertEntities == self.XHTML_ENTITIES:
self.convertXMLEntities = True
self.convertHTMLEntities = True
self.escapeUnrecognizedEntities = False
elif convertEntities == self.XML_ENTITIES:
self.convertXMLEntities = True
self.convertHTMLEntities = False
self.escapeUnrecognizedEntities = False
else:
self.convertXMLEntities = False
self.convertHTMLEntities = False
self.escapeUnrecognizedEntities = False
self.instanceSelfClosingTags = buildTagMap(None, selfClosingTags)
SGMLParser.__init__(self)
if hasattr(markup, 'read'): # It's a file-type object.
markup = markup.read()
self.markup = markup
self.markupMassage = markupMassage
try:
self._feed(isHTML=isHTML)
except StopParsing:
pass
self.markup = None # The markup can now be GCed
def convert_charref(self, name):
"""This method fixes a bug in Python's SGMLParser."""
try:
n = int(name)
except ValueError:
return
if not 0 <= n <= 127 : # ASCII ends at 127, not 255
return
return self.convert_codepoint(n)
def _feed(self, inDocumentEncoding=None, isHTML=False):
# Convert the document to Unicode.
markup = self.markup
if isinstance(markup, unicode):
if not hasattr(self, 'originalEncoding'):
self.originalEncoding = None
else:
dammit = UnicodeDammit\
(markup, [self.fromEncoding, inDocumentEncoding],
smartQuotesTo=self.smartQuotesTo, isHTML=isHTML)
markup = dammit.unicode
self.originalEncoding = dammit.originalEncoding
self.declaredHTMLEncoding = dammit.declaredHTMLEncoding
if markup:
if self.markupMassage:
if not hasattr(self.markupMassage, "__iter__"):
self.markupMassage = self.MARKUP_MASSAGE
for fix, m in self.markupMassage:
markup = fix.sub(m, markup)
# TODO: We get rid of markupMassage so that the
# soup object can be deepcopied later on. Some
# Python installations can't copy regexes. If anyone
# was relying on the existence of markupMassage, this
# might cause problems.
del(self.markupMassage)
self.reset()
SGMLParser.feed(self, markup)
# Close out any unfinished strings and close all the open tags.
self.endData()
while self.currentTag.name != self.ROOT_TAG_NAME:
self.popTag()
def __getattr__(self, methodName):
"""This method routes method call requests to either the SGMLParser
superclass or the Tag superclass, depending on the method name."""
#print "__getattr__ called on %s.%s" % (self.__class__, methodName)
if methodName.startswith('start_') or methodName.startswith('end_') \
or methodName.startswith('do_'):
return SGMLParser.__getattr__(self, methodName)
elif not methodName.startswith('__'):
return Tag.__getattr__(self, methodName)
else:
raise AttributeError
def isSelfClosingTag(self, name):
"""Returns true iff the given string is the name of a
self-closing tag according to this parser."""
return self.SELF_CLOSING_TAGS.has_key(name) \
or self.instanceSelfClosingTags.has_key(name)
def reset(self):
Tag.__init__(self, self, self.ROOT_TAG_NAME)
self.hidden = 1
SGMLParser.reset(self)
self.currentData = []
self.currentTag = None
self.tagStack = []
self.quoteStack = []
self.pushTag(self)
def popTag(self):
tag = self.tagStack.pop()
#print "Pop", tag.name
if self.tagStack:
self.currentTag = self.tagStack[-1]
return self.currentTag
def pushTag(self, tag):
#print "Push", tag.name
if self.currentTag:
self.currentTag.contents.append(tag)
self.tagStack.append(tag)
self.currentTag = self.tagStack[-1]
def endData(self, containerClass=NavigableString):
if self.currentData:
currentData = u''.join(self.currentData)
if (currentData.translate(self.STRIP_ASCII_SPACES) == '' and
not set([tag.name for tag in self.tagStack]).intersection(
self.PRESERVE_WHITESPACE_TAGS)):
if '\n' in currentData:
currentData = '\n'
else:
currentData = ' '
self.currentData = []
if self.parseOnlyThese and len(self.tagStack) <= 1 and \
(not self.parseOnlyThese.text or \
not self.parseOnlyThese.search(currentData)):
return
o = containerClass(currentData)
o.setup(self.currentTag, self.previous)
if self.previous:
self.previous.next = o
self.previous = o
self.currentTag.contents.append(o)
def _popToTag(self, name, inclusivePop=True):
"""Pops the tag stack up to and including the most recent
instance of the given tag. If inclusivePop is false, pops the tag
stack up to but *not* including the most recent instqance of
the given tag."""
#print "Popping to %s" % name
if name == self.ROOT_TAG_NAME:
return
numPops = 0
mostRecentTag = None
for i in range(len(self.tagStack)-1, 0, -1):
if name == self.tagStack[i].name:
numPops = len(self.tagStack)-i
break
if not inclusivePop:
numPops = numPops - 1
for i in range(0, numPops):
mostRecentTag = self.popTag()
return mostRecentTag
def _smartPop(self, name):
"""We need to pop up to the previous tag of this type, unless
one of this tag's nesting reset triggers comes between this
tag and the previous tag of this type, OR unless this tag is a
generic nesting trigger and another generic nesting trigger
comes between this tag and the previous tag of this type.
Examples:
<p>Foo<b>Bar *<p>* should pop to 'p', not 'b'.
<p>Foo<table>Bar *<p>* should pop to 'table', not 'p'.
<p>Foo<table><tr>Bar *<p>* should pop to 'tr', not 'p'.
<li><ul><li> *<li>* should pop to 'ul', not the first 'li'.
<tr><table><tr> *<tr>* should pop to 'table', not the first 'tr'
<td><tr><td> *<td>* should pop to 'tr', not the first 'td'
"""
nestingResetTriggers = self.NESTABLE_TAGS.get(name)
isNestable = nestingResetTriggers != None
isResetNesting = self.RESET_NESTING_TAGS.has_key(name)
popTo = None
inclusive = True
for i in range(len(self.tagStack)-1, 0, -1):
p = self.tagStack[i]
if (not p or p.name == name) and not isNestable:
#Non-nestable tags get popped to the top or to their
#last occurance.
popTo = name
break
if (nestingResetTriggers is not None
and p.name in nestingResetTriggers) \
or (nestingResetTriggers is None and isResetNesting
and self.RESET_NESTING_TAGS.has_key(p.name)):
#If we encounter one of the nesting reset triggers
#peculiar to this tag, or we encounter another tag
#that causes nesting to reset, pop up to but not
#including that tag.
popTo = p.name
inclusive = False
break
p = p.parent
if popTo:
self._popToTag(popTo, inclusive)
def unknown_starttag(self, name, attrs, selfClosing=0):
#print "Start tag %s: %s" % (name, attrs)
if self.quoteStack:
#This is not a real tag.
#print "<%s> is not real!" % name
attrs = ''.join([' %s="%s"' % (x, y) for x, y in attrs])
self.handle_data('<%s%s>' % (name, attrs))
return
self.endData()
if not self.isSelfClosingTag(name) and not selfClosing:
self._smartPop(name)
if self.parseOnlyThese and len(self.tagStack) <= 1 \
and (self.parseOnlyThese.text or not self.parseOnlyThese.searchTag(name, attrs)):
return
tag = Tag(self, name, attrs, self.currentTag, self.previous)
if self.previous:
self.previous.next = tag
self.previous = tag
self.pushTag(tag)
if selfClosing or self.isSelfClosingTag(name):
self.popTag()
if name in self.QUOTE_TAGS:
#print "Beginning quote (%s)" % name
self.quoteStack.append(name)
self.literal = 1
return tag
def unknown_endtag(self, name):
#print "End tag %s" % name
if self.quoteStack and self.quoteStack[-1] != name:
#This is not a real end tag.
#print "</%s> is not real!" % name
self.handle_data('</%s>' % name)
return
self.endData()
self._popToTag(name)
if self.quoteStack and self.quoteStack[-1] == name:
self.quoteStack.pop()
self.literal = (len(self.quoteStack) > 0)
def handle_data(self, data):
self.currentData.append(data)
def _toStringSubclass(self, text, subclass):
"""Adds a certain piece of text to the tree as a NavigableString
subclass."""
self.endData()
self.handle_data(text)
self.endData(subclass)
def handle_pi(self, text):
"""Handle a processing instruction as a ProcessingInstruction
object, possibly one with a %SOUP-ENCODING% slot into which an
encoding will be plugged later."""
if text[:3] == "xml":
text = u"xml version='1.0' encoding='%SOUP-ENCODING%'"
self._toStringSubclass(text, ProcessingInstruction)
def handle_comment(self, text):
"Handle comments as Comment objects."
self._toStringSubclass(text, Comment)
def handle_charref(self, ref):
"Handle character references as data."
if self.convertEntities:
data = unichr(int(ref))
else:
data = '&#%s;' % ref
self.handle_data(data)
def handle_entityref(self, ref):
"""Handle entity references as data, possibly converting known
HTML and/or XML entity references to the corresponding Unicode
characters."""
data = None
if self.convertHTMLEntities:
try:
data = unichr(name2codepoint[ref])
except KeyError:
pass
if not data and self.convertXMLEntities:
data = self.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref)
if not data and self.convertHTMLEntities and \
not self.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref):
# TODO: We've got a problem here. We're told this is
# an entity reference, but it's not an XML entity
# reference or an HTML entity reference. Nonetheless,
# the logical thing to do is to pass it through as an
# unrecognized entity reference.
#
# Except: when the input is "&carol;" this function
# will be called with input "carol". When the input is
# "AT&T", this function will be called with input
# "T". We have no way of knowing whether a semicolon
# was present originally, so we don't know whether
# this is an unknown entity or just a misplaced
# ampersand.
#
# The more common case is a misplaced ampersand, so I
# escape the ampersand and omit the trailing semicolon.
data = "&%s" % ref
if not data:
# This case is different from the one above, because we
# haven't already gone through a supposedly comprehensive
# mapping of entities to Unicode characters. We might not
# have gone through any mapping at all. So the chances are
# very high that this is a real entity, and not a
# misplaced ampersand.
data = "&%s;" % ref
self.handle_data(data)
def handle_decl(self, data):
"Handle DOCTYPEs and the like as Declaration objects."
self._toStringSubclass(data, Declaration)
def parse_declaration(self, i):
"""Treat a bogus SGML declaration as raw data. Treat a CDATA
declaration as a CData object."""
j = None
if self.rawdata[i:i+9] == '<![CDATA[':
k = self.rawdata.find(']]>', i)
if k == -1:
k = len(self.rawdata)
data = self.rawdata[i+9:k]
j = k+3
self._toStringSubclass(data, CData)
else:
try:
j = SGMLParser.parse_declaration(self, i)
except SGMLParseError:
toHandle = self.rawdata[i:]
self.handle_data(toHandle)
j = i + len(toHandle)
return j
class BeautifulSoup(BeautifulStoneSoup):
"""This parser knows the following facts about HTML:
* Some tags have no closing tag and should be interpreted as being
closed as soon as they are encountered.
* The text inside some tags (ie. 'script') may contain tags which
are not really part of the document and which should be parsed
as text, not tags. If you want to parse the text as tags, you can
always fetch it and parse it explicitly.
* Tag nesting rules:
Most tags can't be nested at all. For instance, the occurance of
a <p> tag should implicitly close the previous <p> tag.
<p>Para1<p>Para2
should be transformed into:
<p>Para1</p><p>Para2
Some tags can be nested arbitrarily. For instance, the occurance
of a <blockquote> tag should _not_ implicitly close the previous
<blockquote> tag.
Alice said: <blockquote>Bob said: <blockquote>Blah
should NOT be transformed into:
Alice said: <blockquote>Bob said: </blockquote><blockquote>Blah
Some tags can be nested, but the nesting is reset by the
interposition of other tags. For instance, a <tr> tag should
implicitly close the previous <tr> tag within the same <table>,
but not close a <tr> tag in another table.
<table><tr>Blah<tr>Blah
should be transformed into:
<table><tr>Blah</tr><tr>Blah
but,
<tr>Blah<table><tr>Blah
should NOT be transformed into
<tr>Blah<table></tr><tr>Blah
Differing assumptions about tag nesting rules are a major source
of problems with the BeautifulSoup class. If BeautifulSoup is not
treating as nestable a tag your page author treats as nestable,
try ICantBelieveItsBeautifulSoup, MinimalSoup, or
BeautifulStoneSoup before writing your own subclass."""
def __init__(self, *args, **kwargs):
if not kwargs.has_key('smartQuotesTo'):
kwargs['smartQuotesTo'] = self.HTML_ENTITIES
kwargs['isHTML'] = True
BeautifulStoneSoup.__init__(self, *args, **kwargs)
SELF_CLOSING_TAGS = buildTagMap(None,
('br' , 'hr', 'input', 'img', 'meta',
'spacer', 'link', 'frame', 'base', 'col'))
PRESERVE_WHITESPACE_TAGS = set(['pre', 'textarea'])
QUOTE_TAGS = {'script' : None, 'textarea' : None}
#According to the HTML standard, each of these inline tags can
#contain another tag of the same type. Furthermore, it's common
#to actually use these tags this way.
NESTABLE_INLINE_TAGS = ('span', 'font', 'q', 'object', 'bdo', 'sub', 'sup',
'center')
#According to the HTML standard, these block tags can contain
#another tag of the same type. Furthermore, it's common
#to actually use these tags this way.
NESTABLE_BLOCK_TAGS = ('blockquote', 'div', 'fieldset', 'ins', 'del')
#Lists can contain other lists, but there are restrictions.
NESTABLE_LIST_TAGS = { 'ol' : [],
'ul' : [],
'li' : ['ul', 'ol'],
'dl' : [],
'dd' : ['dl'],
'dt' : ['dl'] }
#Tables can contain other tables, but there are restrictions.
NESTABLE_TABLE_TAGS = {'table' : [],
'tr' : ['table', 'tbody', 'tfoot', 'thead'],
'td' : ['tr'],
'th' : ['tr'],
'thead' : ['table'],
'tbody' : ['table'],
'tfoot' : ['table'],
}
NON_NESTABLE_BLOCK_TAGS = ('address', 'form', 'p', 'pre')
#If one of these tags is encountered, all tags up to the next tag of
#this type are popped.
RESET_NESTING_TAGS = buildTagMap(None, NESTABLE_BLOCK_TAGS, 'noscript',
NON_NESTABLE_BLOCK_TAGS,
NESTABLE_LIST_TAGS,
NESTABLE_TABLE_TAGS)
NESTABLE_TAGS = buildTagMap([], NESTABLE_INLINE_TAGS, NESTABLE_BLOCK_TAGS,
NESTABLE_LIST_TAGS, NESTABLE_TABLE_TAGS)
# Used to detect the charset in a META tag; see start_meta
CHARSET_RE = re.compile("((^|;)\s*charset=)([^;]*)", re.M)
def start_meta(self, attrs):
"""Beautiful Soup can detect a charset included in a META tag,
try to convert the document to that charset, and re-parse the
document from the beginning."""
httpEquiv = None
contentType = None
contentTypeIndex = None
tagNeedsEncodingSubstitution = False
for i in range(0, len(attrs)):
key, value = attrs[i]
key = key.lower()
if key == 'http-equiv':
httpEquiv = value
elif key == 'content':
contentType = value
contentTypeIndex = i
if httpEquiv and contentType: # It's an interesting meta tag.
match = self.CHARSET_RE.search(contentType)
if match:
if (self.declaredHTMLEncoding is not None or
self.originalEncoding == self.fromEncoding):
# An HTML encoding was sniffed while converting
# the document to Unicode, or an HTML encoding was
# sniffed during a previous pass through the
# document, or an encoding was specified
# explicitly and it worked. Rewrite the meta tag.
def rewrite(match):
return match.group(1) + "%SOUP-ENCODING%"
newAttr = self.CHARSET_RE.sub(rewrite, contentType)
attrs[contentTypeIndex] = (attrs[contentTypeIndex][0],
newAttr)
tagNeedsEncodingSubstitution = True
else:
# This is our first pass through the document.
# Go through it again with the encoding information.
newCharset = match.group(3)
if newCharset and newCharset != self.originalEncoding:
self.declaredHTMLEncoding = newCharset
self._feed(self.declaredHTMLEncoding)
raise StopParsing
pass
tag = self.unknown_starttag("meta", attrs)
if tag and tagNeedsEncodingSubstitution:
tag.containsSubstitutions = True
class StopParsing(Exception):
pass
class ICantBelieveItsBeautifulSoup(BeautifulSoup):
"""The BeautifulSoup class is oriented towards skipping over
common HTML errors like unclosed tags. However, sometimes it makes
errors of its own. For instance, consider this fragment:
<b>Foo<b>Bar</b></b>
This is perfectly valid (if bizarre) HTML. However, the
BeautifulSoup class will implicitly close the first b tag when it
encounters the second 'b'. It will think the author wrote
"<b>Foo<b>Bar", and didn't close the first 'b' tag, because
there's no real-world reason to bold something that's already
bold. When it encounters '</b></b>' it will close two more 'b'
tags, for a grand total of three tags closed instead of two. This
can throw off the rest of your document structure. The same is
true of a number of other tags, listed below.
It's much more common for someone to forget to close a 'b' tag
than to actually use nested 'b' tags, and the BeautifulSoup class
handles the common case. This class handles the not-co-common
case: where you can't believe someone wrote what they did, but
it's valid HTML and BeautifulSoup screwed up by assuming it
wouldn't be."""
I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS = \
('em', 'big', 'i', 'small', 'tt', 'abbr', 'acronym', 'strong',
'cite', 'code', 'dfn', 'kbd', 'samp', 'strong', 'var', 'b',
'big')
I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS = ('noscript',)
NESTABLE_TAGS = buildTagMap([], BeautifulSoup.NESTABLE_TAGS,
I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS,
I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS)
class MinimalSoup(BeautifulSoup):
"""The MinimalSoup class is for parsing HTML that contains
pathologically bad markup. It makes no assumptions about tag
nesting, but it does know which tags are self-closing, that
<script> tags contain Javascript and should not be parsed, that
META tags may contain encoding information, and so on.
This also makes it better for subclassing than BeautifulStoneSoup
or BeautifulSoup."""
RESET_NESTING_TAGS = buildTagMap('noscript')
NESTABLE_TAGS = {}
class BeautifulSOAP(BeautifulStoneSoup):
"""This class will push a tag with only a single string child into
the tag's parent as an attribute. The attribute's name is the tag
name, and the value is the string child. An example should give
the flavor of the change:
<foo><bar>baz</bar></foo>
=>
<foo bar="baz"><bar>baz</bar></foo>
You can then access fooTag['bar'] instead of fooTag.barTag.string.
This is, of course, useful for scraping structures that tend to
use subelements instead of attributes, such as SOAP messages. Note
that it modifies its input, so don't print the modified version
out.
I'm not sure how many people really want to use this class; let me
know if you do. Mainly I like the name."""
def popTag(self):
if len(self.tagStack) > 1:
tag = self.tagStack[-1]
parent = self.tagStack[-2]
parent._getAttrMap()
if (isinstance(tag, Tag) and len(tag.contents) == 1 and
isinstance(tag.contents[0], NavigableString) and
not parent.attrMap.has_key(tag.name)):
parent[tag.name] = tag.contents[0]
BeautifulStoneSoup.popTag(self)
#Enterprise class names! It has come to our attention that some people
#think the names of the Beautiful Soup parser classes are too silly
#and "unprofessional" for use in enterprise screen-scraping. We feel
#your pain! For such-minded folk, the Beautiful Soup Consortium And
#All-Night Kosher Bakery recommends renaming this file to
#"RobustParser.py" (or, in cases of extreme enterprisiness,
#"RobustParserBeanInterface.class") and using the following
#enterprise-friendly class aliases:
class RobustXMLParser(BeautifulStoneSoup):
pass
class RobustHTMLParser(BeautifulSoup):
pass
class RobustWackAssHTMLParser(ICantBelieveItsBeautifulSoup):
pass
class RobustInsanelyWackAssHTMLParser(MinimalSoup):
pass
class SimplifyingSOAPParser(BeautifulSOAP):
pass
######################################################
#
# Bonus library: Unicode, Dammit
#
# This class forces XML data into a standard format (usually to UTF-8
# or Unicode). It is heavily based on code from Mark Pilgrim's
# Universal Feed Parser. It does not rewrite the XML or HTML to
# reflect a new encoding: that happens in BeautifulStoneSoup.handle_pi
# (XML) and BeautifulSoup.start_meta (HTML).
# Autodetects character encodings.
# Download from http://chardet.feedparser.org/
try:
import chardet
# import chardet.constants
# chardet.constants._debug = 1
except ImportError:
chardet = None
# cjkcodecs and iconv_codec make Python know about more character encodings.
# Both are available from http://cjkpython.i18n.org/
# They're built in if you use Python 2.4.
try:
import cjkcodecs.aliases
except ImportError:
pass
try:
import iconv_codec
except ImportError:
pass
class UnicodeDammit:
"""A class for detecting the encoding of a *ML document and
converting it to a Unicode string. If the source encoding is
windows-1252, can replace MS smart quotes with their HTML or XML
equivalents."""
# This dictionary maps commonly seen values for "charset" in HTML
# meta tags to the corresponding Python codec names. It only covers
# values that aren't in Python's aliases and can't be determined
# by the heuristics in find_codec.
CHARSET_ALIASES = { "macintosh" : "mac-roman",
"x-sjis" : "shift-jis" }
def __init__(self, markup, overrideEncodings=[],
smartQuotesTo='xml', isHTML=False):
self.declaredHTMLEncoding = None
self.markup, documentEncoding, sniffedEncoding = \
self._detectEncoding(markup, isHTML)
self.smartQuotesTo = smartQuotesTo
self.triedEncodings = []
if markup == '' or isinstance(markup, unicode):
self.originalEncoding = None
self.unicode = unicode(markup)
return
u = None
for proposedEncoding in overrideEncodings:
u = self._convertFrom(proposedEncoding)
if u: break
if not u:
for proposedEncoding in (documentEncoding, sniffedEncoding):
u = self._convertFrom(proposedEncoding)
if u: break
# If no luck and we have auto-detection library, try that:
if not u and chardet and not isinstance(self.markup, unicode):
u = self._convertFrom(chardet.detect(self.markup)['encoding'])
# As a last resort, try utf-8 and windows-1252:
if not u:
for proposed_encoding in ("utf-8", "windows-1252"):
u = self._convertFrom(proposed_encoding)
if u: break
self.unicode = u
if not u: self.originalEncoding = None
def _subMSChar(self, orig):
"""Changes a MS smart quote character to an XML or HTML
entity."""
sub = self.MS_CHARS.get(orig)
if isinstance(sub, tuple):
if self.smartQuotesTo == 'xml':
sub = '&#x%s;' % sub[1]
else:
sub = '&%s;' % sub[0]
return sub
def _convertFrom(self, proposed):
proposed = self.find_codec(proposed)
if not proposed or proposed in self.triedEncodings:
return None
self.triedEncodings.append(proposed)
markup = self.markup
# Convert smart quotes to HTML if coming from an encoding
# that might have them.
if self.smartQuotesTo and proposed.lower() in("windows-1252",
"iso-8859-1",
"iso-8859-2"):
markup = re.compile("([\x80-\x9f])").sub \
(lambda(x): self._subMSChar(x.group(1)),
markup)
try:
# print "Trying to convert document to %s" % proposed
u = self._toUnicode(markup, proposed)
self.markup = u
self.originalEncoding = proposed
except Exception, e:
# print "That didn't work!"
# print e
return None
#print "Correct encoding: %s" % proposed
return self.markup
def _toUnicode(self, data, encoding):
'''Given a string and its encoding, decodes the string into Unicode.
%encoding is a string recognized by encodings.aliases'''
# strip Byte Order Mark (if present)
if (len(data) >= 4) and (data[:2] == '\xfe\xff') \
and (data[2:4] != '\x00\x00'):
encoding = 'utf-16be'
data = data[2:]
elif (len(data) >= 4) and (data[:2] == '\xff\xfe') \
and (data[2:4] != '\x00\x00'):
encoding = 'utf-16le'
data = data[2:]
elif data[:3] == '\xef\xbb\xbf':
encoding = 'utf-8'
data = data[3:]
elif data[:4] == '\x00\x00\xfe\xff':
encoding = 'utf-32be'
data = data[4:]
elif data[:4] == '\xff\xfe\x00\x00':
encoding = 'utf-32le'
data = data[4:]
newdata = unicode(data, encoding)
return newdata
def _detectEncoding(self, xml_data, isHTML=False):
"""Given a document, tries to detect its XML encoding."""
xml_encoding = sniffed_xml_encoding = None
try:
if xml_data[:4] == '\x4c\x6f\xa7\x94':
# EBCDIC
xml_data = self._ebcdic_to_ascii(xml_data)
elif xml_data[:4] == '\x00\x3c\x00\x3f':
# UTF-16BE
sniffed_xml_encoding = 'utf-16be'
xml_data = unicode(xml_data, 'utf-16be').encode('utf-8')
elif (len(xml_data) >= 4) and (xml_data[:2] == '\xfe\xff') \
and (xml_data[2:4] != '\x00\x00'):
# UTF-16BE with BOM
sniffed_xml_encoding = 'utf-16be'
xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8')
elif xml_data[:4] == '\x3c\x00\x3f\x00':
# UTF-16LE
sniffed_xml_encoding = 'utf-16le'
xml_data = unicode(xml_data, 'utf-16le').encode('utf-8')
elif (len(xml_data) >= 4) and (xml_data[:2] == '\xff\xfe') and \
(xml_data[2:4] != '\x00\x00'):
# UTF-16LE with BOM
sniffed_xml_encoding = 'utf-16le'
xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8')
elif xml_data[:4] == '\x00\x00\x00\x3c':
# UTF-32BE
sniffed_xml_encoding = 'utf-32be'
xml_data = unicode(xml_data, 'utf-32be').encode('utf-8')
elif xml_data[:4] == '\x3c\x00\x00\x00':
# UTF-32LE
sniffed_xml_encoding = 'utf-32le'
xml_data = unicode(xml_data, 'utf-32le').encode('utf-8')
elif xml_data[:4] == '\x00\x00\xfe\xff':
# UTF-32BE with BOM
sniffed_xml_encoding = 'utf-32be'
xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8')
elif xml_data[:4] == '\xff\xfe\x00\x00':
# UTF-32LE with BOM
sniffed_xml_encoding = 'utf-32le'
xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8')
elif xml_data[:3] == '\xef\xbb\xbf':
# UTF-8 with BOM
sniffed_xml_encoding = 'utf-8'
xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8')
else:
sniffed_xml_encoding = 'ascii'
pass
except:
xml_encoding_match = None
xml_encoding_match = re.compile(
'^<\?.*encoding=[\'"](.*?)[\'"].*\?>').match(xml_data)
if not xml_encoding_match and isHTML:
regexp = re.compile('<\s*meta[^>]+charset=([^>]*?)[;\'">]', re.I)
xml_encoding_match = regexp.search(xml_data)
if xml_encoding_match is not None:
xml_encoding = xml_encoding_match.groups()[0].lower()
if isHTML:
self.declaredHTMLEncoding = xml_encoding
if sniffed_xml_encoding and \
(xml_encoding in ('iso-10646-ucs-2', 'ucs-2', 'csunicode',
'iso-10646-ucs-4', 'ucs-4', 'csucs4',
'utf-16', 'utf-32', 'utf_16', 'utf_32',
'utf16', 'u16')):
xml_encoding = sniffed_xml_encoding
return xml_data, xml_encoding, sniffed_xml_encoding
def find_codec(self, charset):
return self._codec(self.CHARSET_ALIASES.get(charset, charset)) \
or (charset and self._codec(charset.replace("-", ""))) \
or (charset and self._codec(charset.replace("-", "_"))) \
or charset
def _codec(self, charset):
if not charset: return charset
codec = None
try:
codecs.lookup(charset)
codec = charset
except (LookupError, ValueError):
pass
return codec
EBCDIC_TO_ASCII_MAP = None
def _ebcdic_to_ascii(self, s):
c = self.__class__
if not c.EBCDIC_TO_ASCII_MAP:
emap = (0,1,2,3,156,9,134,127,151,141,142,11,12,13,14,15,
16,17,18,19,157,133,8,135,24,25,146,143,28,29,30,31,
128,129,130,131,132,10,23,27,136,137,138,139,140,5,6,7,
144,145,22,147,148,149,150,4,152,153,154,155,20,21,158,26,
32,160,161,162,163,164,165,166,167,168,91,46,60,40,43,33,
38,169,170,171,172,173,174,175,176,177,93,36,42,41,59,94,
45,47,178,179,180,181,182,183,184,185,124,44,37,95,62,63,
186,187,188,189,190,191,192,193,194,96,58,35,64,39,61,34,
195,97,98,99,100,101,102,103,104,105,196,197,198,199,200,
201,202,106,107,108,109,110,111,112,113,114,203,204,205,
206,207,208,209,126,115,116,117,118,119,120,121,122,210,
211,212,213,214,215,216,217,218,219,220,221,222,223,224,
225,226,227,228,229,230,231,123,65,66,67,68,69,70,71,72,
73,232,233,234,235,236,237,125,74,75,76,77,78,79,80,81,
82,238,239,240,241,242,243,92,159,83,84,85,86,87,88,89,
90,244,245,246,247,248,249,48,49,50,51,52,53,54,55,56,57,
250,251,252,253,254,255)
import string
c.EBCDIC_TO_ASCII_MAP = string.maketrans( \
''.join(map(chr, range(256))), ''.join(map(chr, emap)))
return s.translate(c.EBCDIC_TO_ASCII_MAP)
MS_CHARS = { '\x80' : ('euro', '20AC'),
'\x81' : ' ',
'\x82' : ('sbquo', '201A'),
'\x83' : ('fnof', '192'),
'\x84' : ('bdquo', '201E'),
'\x85' : ('hellip', '2026'),
'\x86' : ('dagger', '2020'),
'\x87' : ('Dagger', '2021'),
'\x88' : ('circ', '2C6'),
'\x89' : ('permil', '2030'),
'\x8A' : ('Scaron', '160'),
'\x8B' : ('lsaquo', '2039'),
'\x8C' : ('OElig', '152'),
'\x8D' : '?',
'\x8E' : ('#x17D', '17D'),
'\x8F' : '?',
'\x90' : '?',
'\x91' : ('lsquo', '2018'),
'\x92' : ('rsquo', '2019'),
'\x93' : ('ldquo', '201C'),
'\x94' : ('rdquo', '201D'),
'\x95' : ('bull', '2022'),
'\x96' : ('ndash', '2013'),
'\x97' : ('mdash', '2014'),
'\x98' : ('tilde', '2DC'),
'\x99' : ('trade', '2122'),
'\x9a' : ('scaron', '161'),
'\x9b' : ('rsaquo', '203A'),
'\x9c' : ('oelig', '153'),
'\x9d' : '?',
'\x9e' : ('#x17E', '17E'),
'\x9f' : ('Yuml', ''),}
#######################################################################
#By default, act as an HTML pretty-printer.
if __name__ == '__main__':
import sys
soup = BeautifulSoup(sys.stdin)
print soup.prettify()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import model
import PropertiesUtil
import Constant
from google.appengine.api import memcache
class AppProperties (object):
__instance = None
__appDic = None
__env = None
def __new__(cls, *args, **kargs):
if cls.__instance is None:
cls.__instance = object.__new__(cls, *args, **kargs)
return cls.__instance
'''
Gets application properties
'''
def getAppDic(self):
if self.__appDic is None:
self.__appDic = PropertiesUtil.loadProperties(r"conf/application.properties")
return self.__appDic
'''
Gets Jinja Environment
'''
def getJinjaEnv(self):
import os
import jinja2
import gettext
if self.__env is None:
self.__env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), '..', 'templates' )), extensions=['jinja2.ext.i18n'])##MOD
'''self.__env.filters['relativize'] = self.relativize
self.__env.filters['markdown'] = self.markdown
self.__env.filters['smiley'] = self.smiley
self.__env.filters['pagination'] = self.pagination
self.__env.filters['media'] = self.media_content
self.__env.filters['quote'] = self.quote'''
######################################################################################
# i18n configuration
# Added: mo and po files
# Mdofied: handlers and templates
######################################################################################
locale = ''
try :
locale = self.get_application().locale
if locale is None or locale == "" :
locale = Constant.DEFAULT_LOCALE
except:
locale = Constant.DEFAULT_LOCALE
domain = 'django'
localeDir = 'conf/locale'
localeCodeset = 'UTF-8'
langs=[locale]#, 'ca_ES', 'es']#'es',
#os.environ["LANGUAGE"] = "en"
translations = gettext.translation(domain, localeDir, languages=langs) #GNUTranslations
#env = Environment(extensions=['jinja2.ext.i18n'])
self.__env.install_gettext_translations(translations)
gettext.textdomain(domain)
gettext.bindtextdomain(gettext._current_domain, localeDir)
gettext.bind_textdomain_codeset(gettext._current_domain, localeCodeset)
#self.__env.shared = True
return self.__env
def updateJinjaEnv(self):
self.__env = None
self.getJinjaEnv()
def getAccountProvider(self, regType = 0):
if regType is None or regType == 0:# Local
return self.get_application().name
elif regType == 1:
return "Google"
return ""
#Dup
def get_application(self):
app = memcache.get('app')
if app is not None:
# logging.debug('%s is already in the cache' % key)
return app
else:
app = model.Application.all().get()
# logging.debug('inserting %s in the cache' % key)
memcache.add('app', app, 0)
return app
| Python |
"""
Copyright (c) 2008, appengine-utilities project
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of the appengine-utilities project nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
# main python imports
import os
import time
import datetime
import random
import sha
import Cookie
import pickle
# google appengine imports
from google.appengine.ext import db
from google.appengine.api import memcache
# settings, if you have these set elsewhere, such as your django settings file,
# you'll need to adjust the values to pull from there.
COOKIE_NAME = 'appengine-utilities-session-sid'
DEFAULT_COOKIE_PATH = '/'
SESSION_EXPIRE_TIME = 7200 # sessions are valid for 7200 seconds (2 hours)
CLEAN_CHECK_PERCENT = 15 # 15% of all requests will clean the database
INTEGRATE_FLASH = True # integrate functionality from flash module?
CHECK_IP = True # validate sessions by IP
CHECK_USER_AGENT = True # validate sessions by user agent
SET_COOKIE_EXPIRES = True # Set to True to add expiration field to cookie
SESSION_TOKEN_TTL = 5 # Number of seconds a session token is valid for.
class _AppEngineUtilities_Session(db.Model):
"""
Model for the sessions in the datastore. This contains the identifier and
validation information for the session.
"""
sid = db.StringListProperty()
ip = db.StringProperty()
ua = db.StringProperty()
last_activity = db.DateTimeProperty(auto_now=True)
class _AppEngineUtilities_SessionData(db.Model):
"""
Model for the session data in the datastore.
"""
session = db.ReferenceProperty(_AppEngineUtilities_Session)
keyname = db.StringProperty()
content = db.BlobProperty()
class Session(object):
"""
Sessions used to maintain user presence between requests.
Sessions store a unique id as a cookie in the browser and
referenced in a datastore object. This maintains user presence
by validating requests as visits from the same browser.
You can add extra data to the session object by using it
as a dictionary object. Values can be any python object that
can be pickled.
For extra performance, session objects are also store in
memcache and kept consistent with the datastore. This
increases the performance of read requests to session
data.
"""
def __init__(self, cookie_path=DEFAULT_COOKIE_PATH,
cookie_name=COOKIE_NAME, session_expire_time=SESSION_EXPIRE_TIME,
clean_check_percent=CLEAN_CHECK_PERCENT,
integrate_flash=INTEGRATE_FLASH, check_ip=CHECK_IP,
check_user_agent=CHECK_USER_AGENT,
set_cookie_expires=SET_COOKIE_EXPIRES,
session_token_ttl=SESSION_TOKEN_TTL):
"""
Initializer
Args:
cookie_name: The name for the session cookie stored in the browser.
session_expire_time: The amount of time between requests before the
session expires.
clean_check_percent: The percentage of requests the will fire off a
cleaning routine that deletes stale session data.
integrate_flash: If appengine-utilities flash utility should be
integrated into the session object.
check_ip: If browser IP should be used for session validation
check_user_agent: If the browser user agent should be used for
sessoin validation.
set_cookie_expires: True adds an expires field to the cookie so
it saves even if the browser is closed.
session_token_ttl: Number of sessions a session token is valid
for before it should be regenerated.
"""
self.cookie_path = cookie_path
self.cookie_name = cookie_name
self.session_expire_time = session_expire_time
self.clean_check_percent = clean_check_percent
self.integrate_flash = integrate_flash
self.check_user_agent = check_user_agent
self.check_ip = check_ip
self.set_cookie_expires = set_cookie_expires
self.session_token_ttl = session_token_ttl
"""
Check the cookie and, if necessary, create a new one.
"""
self.cache = {}
self.sid = None
string_cookie = os.environ.get('HTTP_COOKIE', '')
self.cookie = Cookie.SimpleCookie()
self.cookie.load(string_cookie)
# check for existing cookie
if self.cookie.get(cookie_name):
self.sid = self.cookie[cookie_name].value
# If there isn't a valid session for the cookie sid,
# start a new session.
self.session = self._get_session()
if self.session is None:
self.sid = self.new_sid()
self.session = _AppEngineUtilities_Session()
self.session.ua = os.environ['HTTP_USER_AGENT']
self.session.ip = os.environ['REMOTE_ADDR']
self.session.sid = [self.sid]
self.cookie[cookie_name] = self.sid
self.cookie[cookie_name]['path'] = cookie_path
if set_cookie_expires:
self.cookie[cookie_name]['expires'] = \
self.session_expire_time
else:
# check the age of the token to determine if a new one
# is required
duration = datetime.timedelta(seconds=self.session_token_ttl)
session_age_limit = datetime.datetime.now() - duration
if self.session.last_activity < session_age_limit:
self.sid = self.new_sid()
if len(self.session.sid) > 2:
self.session.sid.remove(self.session.sid[0])
self.session.sid.append(self.sid)
else:
self.sid = self.session.sid[-1]
self.cookie[cookie_name] = self.sid
self.cookie[cookie_name]['path'] = cookie_path
if set_cookie_expires:
self.cookie[cookie_name]['expires'] = \
self.session_expire_time
else:
self.sid = self.new_sid()
self.session = _AppEngineUtilities_Session()
self.session.ua = os.environ['HTTP_USER_AGENT']
self.session.ip = os.environ['REMOTE_ADDR']
self.session.sid = [self.sid]
self.cookie[cookie_name] = self.sid
self.cookie[cookie_name]['path'] = cookie_path
if set_cookie_expires:
self.cookie[cookie_name]['expires'] = self.session_expire_time
self.cache['sid'] = pickle.dumps(self.sid)
# update the last_activity field in the datastore every time that
# the session is accessed. This also handles the write for all
# session data above.
self.session.put()
print self.cookie
# fire up a Flash object if integration is enabled
if self.integrate_flash:
import flash
self.flash = flash.Flash(cookie=self.cookie)
# randomly delete old stale sessions in the datastore (see
# CLEAN_CHECK_PERCENT variable)
if random.randint(1, 100) < CLEAN_CHECK_PERCENT:
self._clean_old_sessions()
def new_sid(self):
"""
Create a new session id.
"""
sid = sha.new(repr(time.time()) + os.environ['REMOTE_ADDR'] + \
str(random.random())).hexdigest()
return sid
def _get_session(self):
"""
Get the user's session from the datastore
"""
query = _AppEngineUtilities_Session.all()
query.filter('sid', self.sid)
if self.check_user_agent:
query.filter('ua', os.environ['HTTP_USER_AGENT'])
if self.check_ip:
query.filter('ip', os.environ['REMOTE_ADDR'])
results = query.fetch(1)
if len(results) is 0:
return None
else:
sessionAge = datetime.datetime.now() - results[0].last_activity
if sessionAge.seconds > self.session_expire_time:
results[0].delete()
return None
return results[0]
def _get(self, keyname=None):
"""
Return all of the SessionData object unless keyname is specified, in
which case only that instance of SessionData is returned.
Important: This does not interact with memcache and pulls directly
from the datastore.
Args:
keyname: The keyname of the value you are trying to retrieve.
"""
query = _AppEngineUtilities_SessionData.all()
query.filter('session', self.session)
if keyname != None:
query.filter('keyname =', keyname)
results = query.fetch(1000)
if len(results) is 0:
return None
if keyname != None:
return results[0]
return results
def _validate_key(self, keyname):
"""
Validate the keyname, making sure it is set and not a reserved name.
"""
if keyname is None:
raise ValueError('You must pass a keyname for the session' + \
' data content.')
elif keyname in ('sid', 'flash'):
raise ValueError(keyname + ' is a reserved keyname.')
if type(keyname) != type([str, unicode]):
return str(keyname)
return keyname
def _put(self, keyname, value):
"""
Insert a keyname/value pair into the datastore for the session.
Args:
keyname: The keyname of the mapping.
value: The value of the mapping.
"""
keyname = self._validate_key(keyname)
if value is None:
raise ValueError('You must pass a value to put.')
sessdata = self._get(keyname=keyname)
if sessdata is None:
sessdata = _AppEngineUtilities_SessionData()
sessdata.session = self.session
sessdata.keyname = keyname
sessdata.content = pickle.dumps(value)
self.cache[keyname] = pickle.dumps(value)
sessdata.put()
self._set_memcache()
def _delete_session(self):
"""
Delete the session and all session data for the sid passed.
"""
sessiondata = self._get()
# delete from datastore
if sessiondata is not None:
for sd in sessiondata:
sd.delete()
# delete from memcache
memcache.delete('sid-'+str(self.session.key()))
# delete the session now that all items that reference it are deleted.
self.session.delete()
# if the event class has been loaded, fire off the sessionDeleted event
if 'AEU_Events' in __main__.__dict__:
__main__.AEU_Events.fire_event('sessionDelete')
def delete(self):
"""
Delete the current session and start a new one.
This is useful for when you need to get rid of all data tied to a
current session, such as when you are logging out a user.
"""
self._delete_session()
def delete_all_sessions(self):
"""
Deletes all sessions and session data from the data store and memcache.
"""
all_sessions_deleted = False
all_data_deleted = False
while not all_sessions_deleted:
query = _AppEngineUtilities_Session.all()
results = query.fetch(1000)
if len(results) is 0:
all_sessions_deleted = True
else:
for result in results:
result.delete()
while not all_data_deleted:
query = _AppEngineUtilities_SessionData.all()
results = query.fetch(1000)
if len(results) is 0:
all_data_deleted = True
else:
for result in results:
result.delete()
def _clean_old_sessions(self):
"""
Delete expired sessions from the datastore.
This is only called for CLEAN_CHECK_PERCENT percent of requests because
it could be rather intensive.
"""
duration = datetime.timedelta(seconds=self.session_expire_time)
session_age = datetime.datetime.now() - duration
query = _AppEngineUtilities_Session.all()
query.filter('last_activity <', session_age)
results = query.fetch(1000)
for result in results:
data_query = _AppEngineUtilities_SessionData.all()
query.filter('session', result)
data_results = data_query.fetch(1000)
for data_result in data_results:
data_result.delete()
memcache.delete('sid-'+str(result.key()))
result.delete()
# Implement Python container methods
def __getitem__(self, keyname):
"""
Get item from session data.
keyname: The keyname of the mapping.
"""
# flash messages don't go in the datastore
if self.integrate_flash and (keyname == 'flash'):
return self.flash.msg
if keyname in self.cache:
return pickle.loads(str(self.cache[keyname]))
mc = memcache.get('sid-'+str(self.session.key()))
if mc is not None:
if keyname in mc:
return mc[keyname]
data = self._get(keyname)
if data:
self.cache[keyname] = data.content
self._set_memcache()
return pickle.loads(data.content)
else:
raise KeyError(str(keyname))
def __setitem__(self, keyname, value):
"""
Set item in session data.
Args:
keyname: They keyname of the mapping.
value: The value of mapping.
"""
# if type(keyname) is type(''):
# flash messages don't go in the datastore
if self.integrate_flash and (keyname == 'flash'):
self.flash.msg = value
else:
keyname = self._validate_key(keyname)
self.cache[keyname] = value
self._set_memcache()
return self._put(keyname, value)
# else:
# raise TypeError('Session data objects are only accessible by' + \
# ' string keys, not numerical indexes.')
def __delitem__(self, keyname):
"""
Delete item from session data.
Args:
keyname: The keyname of the object to delete.
"""
sessdata = self._get(keyname = keyname)
if sessdata is None:
raise KeyError(str(keyname))
sessdata.delete()
if keyname in self.cache:
del self.cache[keyname]
self._set_memcache()
def __len__(self):
"""
Return size of session.
"""
# check memcache first
mc = memcache.get('sid-'+str(self.session.key()))
if mc is not None:
return len(mc)
results = self._get()
return len(results)
def __contains__(self, keyname):
"""
Check if an item is in the session data.
Args:
keyname: The keyname being searched.
"""
try:
r = self.__getitem__(keyname)
except KeyError:
return False
return True
def __iter__(self):
"""
Iterate over the keys in the session data.
"""
# try memcache first
mc = memcache.get('sid-'+str(self.session.key()))
if mc is not None:
for k in mc:
yield k
else:
for k in self._get():
yield k.keyname
def __str__(self):
"""
Return string representation.
"""
return ', '.join(['("%s" = "%s")' % (k, self[k]) for k in self])
def _set_memcache(self):
"""
Set a memcache object with all the session date. Optionally you can
add a key and value to the memcache for put operations.
"""
# Pull directly from the datastore in order to ensure that the
# information is as up to date as possible.
data = {}
sessiondata = self._get()
if sessiondata is not None:
for sd in sessiondata:
data[sd.keyname] = pickle.loads(sd.content)
memcache.set('sid-'+str(self.session.key()), data, \
self.session_expire_time)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 John Cube <jonh.cube[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.api import urlfetch
from utilities.BeautifulSoup import *
import urllib
import sys
class TTSUtil (object):
__instance = None
__appDic = None
__env = None
def get_tts_stream_from_tts_urs(self,tts_urls):
content=""
for tts_url in tts_urls:
url = "http://translate.google.com/translate_tts?tl=es&q=" + tts_url
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
try:
result = urlfetch.fetch(url,
payload=' ',
method=urlfetch.GET,
headers={'Content-Type': 'text/xml;charset=UTF-8', 'User-Agent' : user_agent})
if result.status_code == 200:
content=content+result.content
except:
sys.__stdout__.write("Unexpected error:"+ str(sys.exc_info()[0]))
#return the content
return content
def get_tts_url_from_html(self,html=None):
# Constants (moove up)
TTS_MAX_CHARACTERS=130
# TTS mp3 urls
tts_urls=[];
# convert HTML to parsed text
hexentityMassage = [(re.compile('&#x([^;]+);'), lambda m: '&#%d;' % int(m.group(1), 16))]
soup=BeautifulSoup(html,convertEntities=BeautifulSoup.HTML_ENTITIES,markupMassage=hexentityMassage)
# remove all tags
text=''.join(soup.findAll(text=True))
# remove %0A characters
tokens=text.strip('%0A').split('.')
# iterate over the tokens (base on dot)
for token in tokens:
commatokens=token.split(',')
# iterate over the tokens (base on comma)
for commatoken in commatokens:
# encode as url params
params=urllib.quote(commatoken.encode('utf-8'),'')
previous_index=0
while (previous_index<len(params)):
last_index=params.rfind('%20',previous_index,previous_index+TTS_MAX_CHARACTERS)
if (len(params)-previous_index)<=TTS_MAX_CHARACTERS: last_index=len(params)
tts_urls.append(params[previous_index:last_index])
previous_index=last_index
return tts_urls
| Python |
"""
Copyright (c) 2008, appengine-utilities project
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of the appengine-utilities project nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import __main__
class Event(object):
"""
Event is a simple publish/subscribe based event dispatcher
It sets itself to the __main__ function. In order to use it,
you must import it and __main__
"""
def __init__(self):
self.events = []
def subscribe(self, event, callback, args = None):
"""
This method will subscribe a callback function to an event name.
"""
if not {"event": event, "callback": callback, "args": args, } \
in self.events:
self.events.append({"event": event, "callback": callback, \
"args": args, })
def unsubscribe(self, event, callback, args = None):
"""
This method will unsubscribe a callback from an event.
"""
if {"event": event, "callback": callback, "args": args, }\
in self.events:
self.events.remove({"event": event, "callback": callback,\
"args": args, })
def fire_event(self, event = None):
"""
This method is what a method uses to fire an event,
initiating all registered callbacks
"""
for e in self.events:
if e["event"] == event:
if type(e["args"]) == type([]):
e["callback"](*e["args"])
elif type(e["args"]) == type({}):
e["callback"](**e["args"])
elif e["args"] == None:
e["callback"]()
else:
e["callback"](e["args"])
"""
Assign to the event class to __main__
"""
__main__.AEU_Events = Event()
| Python |
"""
Copyright (c) 2008, appengine-utilities project
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of the appengine-utilities project nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import os
import Cookie
import pickle
COOKIE_NAME = 'appengine-utilities-flash'
class Flash(object):
"""
Send messages to the user between pages.
When you instantiate the class, the attribute 'msg' will be set from the
cookie, and the cookie will be deleted. If there is no flash cookie, 'msg'
will default to None.
To set a flash message for the next page, simply set the 'msg' attribute.
Example psuedocode:
if new_entity.put():
flash = Flash()
flash.msg = 'Your new entity has been created!'
return redirect_to_entity_list()
Then in the template on the next page:
{% if flash.msg %}
<div class="flash-msg">{{ flash.msg }}</div>
{% endif %}
"""
def __init__(self, cookie=None):
"""
Load the flash message and clear the cookie.
"""
# load cookie
if cookie is None:
browser_cookie = os.environ.get('HTTP_COOKIE', '')
self.cookie = Cookie.SimpleCookie()
self.cookie.load(browser_cookie)
else:
self.cookie = cookie
# check for flash data
if self.cookie.get(COOKIE_NAME):
# set 'msg' attribute
cookie_val = self.cookie[COOKIE_NAME].value
# we don't want to trigger __setattr__(), which creates a cookie
self.__dict__['msg'] = pickle.loads(cookie_val)
# clear the cookie
self.cookie[COOKIE_NAME] = ''
self.cookie[COOKIE_NAME]['path'] = '/'
self.cookie[COOKIE_NAME]['expires'] = 0
print self.cookie
else:
# default 'msg' attribute to None
self.__dict__['msg'] = None
def __setattr__(self, name, value):
"""
Create a cookie when setting the 'msg' attribute.
"""
if name == 'cookie':
self.__dict__['cookie'] = value
elif name == 'msg':
self.__dict__['msg'] = value
self.__dict__['cookie'][COOKIE_NAME] = pickle.dumps(value)
self.__dict__['cookie'][COOKIE_NAME]['path'] = '/'
print self.cookie
else:
raise ValueError('You can only set the "msg" attribute.')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
def loadProperties(fileName):
propFile = file(fileName, "rU" )
propDict = dict()
for propLine in propFile:
propDef = propLine.strip()
if len(propDef) == 0:
continue
if propDef[0] in ( '!', '#' ):
continue
punctuation = [ propDef.find(c) for c in ':= ' ] + [ len(propDef) ]
found = min( [ pos for pos in punctuation if pos != -1 ] )
name = propDef[:found].rstrip()
value = propDef[found:].lstrip(":= ").rstrip()
propDict[name] = value
propFile.close()
return propDict | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
# Global properties
DEFAULT_LOCALE = "en"
locale = "locale"
appName = "app_name"
appSubject = "app_subject"
domain = "domain"
| Python |
"""
Copyright (c) 2008, appengine-utilities project
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of the appengine-utilities project nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
# main python imports
import datetime
import pickle
import random
import __main__
# google appengine import
from google.appengine.ext import db
from google.appengine.api import memcache
# settings
DEFAULT_TIMEOUT = 3600 # cache expires after one hour (3600 sec)
CLEAN_CHECK_PERCENT = 15 # 15% of all requests will clean the database
MAX_HITS_TO_CLEAN = 1000 # the maximum number of cache hits to clean on attempt
class _AppEngineUtilities_Cache(db.Model):
# It's up to the application to determine the format of their keys
cachekey = db.StringProperty()
createTime = db.DateTimeProperty(auto_now_add=True)
timeout = db.DateTimeProperty()
value = db.BlobProperty()
class Cache(object):
"""
Cache is used for storing pregenerated output and/or objects in the Big
Table datastore to minimize the amount of queries needed for page
displays. The idea is that complex queries that generate the same
results really should only be run once. Cache can be used to store
pregenerated value made from queries (or other calls such as
urlFetch()), or the query objects themselves.
"""
def __init__(self, clean_check_percent = CLEAN_CHECK_PERCENT,
max_hits_to_clean = MAX_HITS_TO_CLEAN,
default_timeout = DEFAULT_TIMEOUT):
"""
Initializer
Args:
clean_check_percent: how often cache initialization should
run the cache cleanup
max_hits_to_clean: maximum number of stale hits to clean
default_timeout: default length a cache article is good for
"""
self.clean_check_percent = clean_check_percent
self.max_hits_to_clean = max_hits_to_clean
self.default_timeout = default_timeout
if random.randint(1, 100) < self.clean_check_percent:
self._clean_cache()
if 'AEU_Events' in __main__.__dict__:
__main__.AEU_Events.fire_event('cacheInitialized')
def _clean_cache(self):
"""
_clean_cache is a routine that is run to find and delete cache
articles that are old. This helps keep the size of your over all
datastore down.
"""
query = _AppEngineUtilities_Cache.all()
query.filter('expires < ', datetime.datetime.now())
results = query.fetch(self.max_hits_to_clean)
for result in results:
result.delete()
def _validate_key(self, key):
if key == None:
raise KeyError
def _validate_value(self, value):
if value == None:
raise ValueError
def _validate_timeout(self, timeout):
if timeout == None:
timeout = datetime.datetime.now() +\
datetime.timedelta(seconds=DEFAULT_TIMEOUT)
if type(timeout) == type(1):
timeout = datetime.datetime.now() + \
datetime.timedelta(seconds = timeout)
if type(timeout) != datetime.datetime:
raise TypeError
if timeout < datetime.datetime.now():
raise ValueError
return timeout
def add(self, key = None, value = None, timeout = None):
"""
add adds an entry to the cache, if one does not already
exist.
"""
self._validate_key(key)
self._validate_value(value)
timeout = self._validate_timeout(timeout)
if key in self:
raise KeyError
cacheEntry = _AppEngineUtilities_Cache()
cacheEntry.cachekey = key
cacheEntry.value = pickle.dumps(value)
cacheEntry.timeout = timeout
cacheEntry.put()
memcache_timeout = timeout - datetime.datetime.now()
memcache.set('cache-'+key, value, int(memcache_timeout.seconds))
if 'AEU_Events' in __main__.__dict__:
__main__.AEU_Events.fire_event('cacheAdded')
def set(self, key = None, value = None, timeout = None):
"""
add adds an entry to the cache, overwriting an existing value
if one already exists.
"""
self._validate_key(key)
self._validate_value(value)
timeout = self._validate_timeout(timeout)
cacheEntry = self._read(key)
if not cacheEntry:
cacheEntry = _AppEngineUtilities_Cache()
cacheEntry.cachekey = key
cacheEntry.value = pickle.dumps(value)
cacheEntry.timeout = timeout
cacheEntry.put()
memcache_timeout = timeout - datetime.datetime.now()
memcache.set('cache-'+key, value, int(memcache_timeout.seconds))
if 'AEU_Events' in __main__.__dict__:
__main__.AEU_Events.fire_event('cacheSet')
def _read(self, key = None):
"""
_read returns a cache object determined by the key. It's set
to private because it returns a db.Model object, and also
does not handle the unpickling of objects making it not the
best candidate for use. The special method __getarticle__ is the
preferred access method for cache data.
"""
query = _AppEngineUtilities_Cache.all()
query.filter('cachekey', key)
query.filter('timeout > ', datetime.datetime.now())
results = query.fetch(1)
if len(results) is 0:
return None
return results[0]
if 'AEU_Events' in __main__.__dict__:
__main__.AEU_Events.fire_event('cacheReadFromDatastore')
if 'AEU_Events' in __main__.__dict__:
__main__.AEU_Events.fire_event('cacheRead')
def delete(self, key = None):
"""
Deletes a cache object determined by the key.
"""
memcache.delete('cache-'+key)
result = self._read(key)
if result:
if 'AEU_Events' in __main__.__dict__:
__main__.AEU_Events.fire_event('cacheDeleted')
result.delete()
def get(self, key):
"""
get is used to return the cache value associated with the key passed.
"""
mc = memcache.get('cache-'+key)
if mc:
if 'AEU_Events' in __main__.__dict__:
__main__.AEU_Events.fire_event('cacheReadFromMemcache')
if 'AEU_Events' in __main__.__dict__:
__main__.AEU_Events.fire_event('cacheRead')
return mc
result = self._read(key)
if result:
timeout = result.timeout - datetime.datetime.now()
# print timeout.seconds
memcache.set('cache-'+key, pickle.loads(result.value),
int(timeout.seconds))
return pickle.loads(result.value)
else:
raise KeyError
def get_many(self, keys):
"""
Returns a dict mapping each key in keys to its value. If the given
key is missing, it will be missing from the response dict.
"""
dict = {}
for key in keys:
value = self.get(key)
if value is not None:
dict[key] = val
return dict
def __getarticle__(self, key):
"""
__getarticle__ is necessary for this object to emulate a container.
"""
return self.get(key)
def __setarticle__(self, key, value):
"""
__setarticle__ is necessary for this object to emulate a container.
"""
return self.set(key, value)
def __delarticle__(self, key):
"""
Implement the 'del' keyword
"""
return self.delete(key)
def __contains__(self, key):
"""
Implements "in" operator
"""
try:
r = self.__getarticle__(key)
except KeyError:
return False
return True
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import search
class UserData(search.SearchableModel):
nickname = db.StringProperty(required=True)
personal_message = db.StringProperty()
email = db.StringProperty(required=True)
avatar = db.BlobProperty()
thumbnail = db.BlobProperty()
image_version = db.IntegerProperty()
list_urls = db.StringListProperty()
im_addresses = db.StringListProperty()
about_user = db.TextProperty()
password = db.StringProperty(required=False)#mod to accept Google account
registrationType = db.IntegerProperty()#0 -local, 1 - google
rol = db.StringProperty()
google_adsense = db.StringProperty()
google_adsense_channel = db.StringProperty()
token = db.StringProperty()
checked = db.BooleanProperty()
# articles
articles = db.IntegerProperty(required=True)
draft_articles = db.IntegerProperty(required=True)
# messages
messages = db.IntegerProperty(required=True)
draft_messages = db.IntegerProperty(required=True)
unread_messages = db.IntegerProperty()
sent_messages = db.IntegerProperty()
# comments
comments = db.IntegerProperty(required=True)
# rating
rating_count = db.IntegerProperty(required=True)
rating_total = db.IntegerProperty(required=True)
rating_average = db.IntegerProperty(required=True)
# forums
threads = db.IntegerProperty(required=True)
responses = db.IntegerProperty(required=True)
# communities
communities = db.IntegerProperty(required=True)
# favourites
favourites = db.IntegerProperty(required=True)
# others
real_name = db.StringProperty()
country = db.StringProperty()
city = db.StringProperty()
public = db.BooleanProperty(required=True)
contacts = db.IntegerProperty()
last_update = db.DateTimeProperty(auto_now=True)
creation_date = db.DateTimeProperty(auto_now_add=True)
deletion_date = db.DateTimeProperty()
last_login = db.DateTimeProperty()
banned_date = db.DateTimeProperty()
not_full_rss = db.BooleanProperty()
class ArticleHtml(db.Model):
content = db.TextProperty(required=True)
class ArticleTTS(db.Model):
tts_stream = db.TextProperty(required=True)
tts_urls = db.StringListProperty()
class Article(search.SearchableModel):
author = db.ReferenceProperty(UserData,required=True)
author_nickname = db.StringProperty()
title = db.StringProperty(required=True)
description = db.StringProperty(required=True)
content = db.TextProperty(required=True)
content_html = db.ReferenceProperty(ArticleHtml)
content_tts = db.ReferenceProperty(ArticleTTS)
lic = db.StringProperty(required=True)
views = db.IntegerProperty(required=True)
rating_count = db.IntegerProperty(required=True)
rating_total = db.IntegerProperty(required=True)
rating_average = db.IntegerProperty()
url_path = db.StringProperty(required=True)
responses = db.IntegerProperty(required=True)
tags = db.StringListProperty()
favourites = db.IntegerProperty(required=True)
draft = db.BooleanProperty(required=True)
article_type = db.StringProperty(required=True)
subscribers = db.StringListProperty()
last_update = db.DateTimeProperty(auto_now=True)
creation_date = db.DateTimeProperty(auto_now_add=True)
deletion_date = db.DateTimeProperty()
deletion_message = db.StringProperty()
deletion_user = db.ReferenceProperty(UserData,collection_name='du')
class Mblog(search.SearchableModel):
author = db.ReferenceProperty(UserData,required=True)
author_nickname = db.StringProperty()
content = db.TextProperty(required=True)
responses = db.IntegerProperty(required=True)
creation_date = db.DateTimeProperty(auto_now_add=True)
deletion_date = db.DateTimeProperty()
deletion_user_nick = db.StringProperty()
class Module(db.Model):
name = db.TextProperty(required=True)
active = db.BooleanProperty()
class Comment(db.Model):
content = db.TextProperty(required=True)
article = db.ReferenceProperty(Article,required=True)
author = db.ReferenceProperty(UserData,required=True)
author_nickname = db.StringProperty()
response_number = db.IntegerProperty()
last_update = db.DateTimeProperty(auto_now=True)
creation_date = db.DateTimeProperty(auto_now_add=True)
deletion_date = db.DateTimeProperty()
editions = db.IntegerProperty()
last_edition = db.DateTimeProperty()
class Vote(db.Model):
user = db.ReferenceProperty(UserData,required=True)
article = db.ReferenceProperty(Article,required=True)
rating = db.IntegerProperty(required=True)
class Tag(db.Model):
tag = db.StringProperty(required=True)
count = db.IntegerProperty(required=True)
class Category(db.Model):
parent_category = db.SelfReferenceProperty()
title = db.StringProperty(required=True)
url_path = db.StringProperty()
description = db.StringProperty(required=True)
communities = db.IntegerProperty(required=True)
articles = db.IntegerProperty(required=True)
subcategories = None
class Community(search.SearchableModel):
owner = db.ReferenceProperty(UserData,required=True)
owner_nickname = db.StringProperty()
title = db.StringProperty(required=True)
description = db.StringProperty(required=True, multiline=True)
url_path = db.StringProperty(required=True)
old_url_path = db.StringProperty()
subscribers = db.StringListProperty()
members = db.IntegerProperty(required=True)
articles = db.IntegerProperty(required=True)
threads = db.IntegerProperty(required=True)
responses = db.IntegerProperty(required=True)
last_update = db.DateTimeProperty(auto_now=True)
creation_date = db.DateTimeProperty(auto_now_add=True)
deletion_date = db.DateTimeProperty()
avatar = db.BlobProperty()
thumbnail = db.BlobProperty()
image_version = db.IntegerProperty()
all_users = db.BooleanProperty()
category = db.ReferenceProperty(Category, collection_name='communities_set')
activity = db.IntegerProperty()
class CommunityUser(db.Model):
user = db.ReferenceProperty(UserData,required=True)
community = db.ReferenceProperty(Community,required=True)
creation_date = db.DateTimeProperty(auto_now_add=True)
# denormalizationzation
user_nickname = db.StringProperty()
community_title = db.StringProperty()
community_url_path = db.StringProperty()
class CommunityArticle(db.Model):
article = db.ReferenceProperty(Article,required=True)
community = db.ReferenceProperty(Community,required=True)
creation_date = db.DateTimeProperty(auto_now_add=True)
# denormalization
article_author_nickname = db.StringProperty()
article_title = db.StringProperty()
article_url_path = db.StringProperty()
community_title = db.StringProperty()
community_url_path = db.StringProperty()
class Thread(search.SearchableModel):
community = db.ReferenceProperty(Community,required=True)
community_title = db.StringProperty()
community_url_path = db.StringProperty()
author = db.ReferenceProperty(UserData,required=True)
author_nickname = db.StringProperty()
title = db.StringProperty(required=True)
url_path = db.StringProperty()
content = db.TextProperty(required=True)
subscribers = db.StringListProperty()
last_response_date = db.DateTimeProperty()
response_number = db.IntegerProperty()
editions = db.IntegerProperty()
last_edition = db.DateTimeProperty()
# responses
parent_thread = db.SelfReferenceProperty()
responses = db.IntegerProperty(required=True)
latest_response = db.DateTimeProperty()
last_update = db.DateTimeProperty(auto_now=True)
creation_date = db.DateTimeProperty(auto_now_add=True)
deletion_date = db.DateTimeProperty()
deletion_message = db.StringProperty()
views = db.IntegerProperty()
class Favourite(db.Model):
article = db.ReferenceProperty(Article,required=True)
user = db.ReferenceProperty(UserData,required=True)
creation_date = db.DateTimeProperty(auto_now_add=True)
# denormalize
article_author_nickname = db.StringProperty()
article_title = db.StringProperty()
article_url_path = db.StringProperty()
user_nickname = db.StringProperty()
class Contact(db.Model):
user_from = db.ReferenceProperty(UserData,required=True,collection_name='cf')
user_to = db.ReferenceProperty(UserData,required=True,collection_name='ct')
creation_date = db.DateTimeProperty(auto_now_add=True)
# denormalize
user_from_nickname = db.StringProperty()
user_to_nickname = db.StringProperty()
class Application(db.Model):
name = db.StringProperty()
logo = db.BlobProperty()
theme = db.StringProperty()
subject = db.StringProperty()
locale = db.StringProperty()
users = db.IntegerProperty()
communities = db.IntegerProperty()
articles = db.IntegerProperty()
threads = db.IntegerProperty()
url = db.StringProperty()
mail_contact = db.StringProperty()
mail_subject_prefix = db.StringProperty()
mail_sender = db.StringProperty()
mail_footer = db.StringProperty()
recaptcha_public_key = db.StringProperty()
recaptcha_private_key = db.StringProperty()
google_adsense = db.StringProperty()
google_adsense_channel = db.StringProperty()
google_analytics = db.StringProperty()
max_results = db.IntegerProperty()
max_results_sublist = db.IntegerProperty()
session_seed = db.StringProperty()
version = db.StringProperty()
class Message(db.Model):
user_from = db.ReferenceProperty(UserData,required=True,collection_name='mf')
user_to = db.ReferenceProperty(UserData,required=True,collection_name='mt')
creation_date = db.DateTimeProperty(auto_now_add=True)
title = db.StringProperty(required=True)
url_path = db.StringProperty(required=True)
content = db.TextProperty(required=True)
read = db.BooleanProperty(required=True)
from_deletion_date = db.DateTimeProperty()
to_deletion_date = db.DateTimeProperty()
user_from_nickname = db.StringProperty()
user_to_nickname = db.StringProperty()
class RelatedCommunity(db.Model):
community_from = db.ReferenceProperty(Community,required=True,collection_name='gf')
community_to = db.ReferenceProperty(Community,required=True,collection_name='gt')
creation_date = db.DateTimeProperty(auto_now_add=True)
# denormalization
community_from_title = db.StringProperty(required=True)
community_from_url_path = db.StringProperty(required=True)
community_to_title = db.StringProperty(required=True)
community_to_url_path = db.StringProperty(required=True)
class UserSubscription(db.Model):
user = db.ReferenceProperty(UserData,required=True)
user_email = db.StringProperty(required=True)
user_nickname = db.StringProperty(required=True)
subscription_type = db.StringProperty(required=True)
subscription_id = db.IntegerProperty(required=True)
creation_date = db.DateTimeProperty()
class Follower(db.Model):
object_type = db.StringProperty(required=True)
object_id = db.IntegerProperty(required=True)
followers = db.StringListProperty()
class Event(db.Model):
event_type = db.StringProperty(required=True)
followers = db.StringListProperty()
user = db.ReferenceProperty(UserData,required=True)
user_nickname = db.StringProperty(required=True)
user_to = db.ReferenceProperty(UserData,collection_name='events_user_to')
user_to_nickname = db.StringProperty()
community = db.ReferenceProperty(Community)
community_title = db.StringProperty()
community_url_path = db.StringProperty()
article = db.ReferenceProperty(Article)
article_author_nickname = db.StringProperty()
article_title = db.StringProperty()
article_url_path = db.StringProperty()
thread = db.ReferenceProperty(Thread)
thread_title = db.StringProperty()
thread_url_path = db.StringProperty()
response_number = db.IntegerProperty()
creation_date = db.DateTimeProperty(auto_now_add=True)
class MailQueue(db.Model):
subject = db.StringProperty(required=True)
body = db.TextProperty(required=True)
to = db.StringListProperty()
bcc = db.StringListProperty()
class Recommendation(db.Model):
article_from = db.ReferenceProperty(Article,collection_name='recommendations_from')
article_to = db.ReferenceProperty(Article,collection_name='recommendations_to')
value = db.FloatProperty()
article_from_title = db.StringProperty(required=True)
article_to_title = db.StringProperty(required=True)
article_from_author_nickname = db.StringProperty(required=True)
article_to_author_nickname = db.StringProperty(required=True)
article_from_url_path = db.StringProperty(required=True)
article_to_url_path = db.StringProperty(required=True)
class Task(db.Model):
task_type = db.StringProperty(required=True)
priority = db.IntegerProperty(required=True)
data = db.StringProperty(required=True, multiline=True)
creation_date = db.DateTimeProperty(auto_now_add=True)
class Image(db.Model):
# No restrictions by community or user
# All files are public, but only owner or admin can browse them
# Due image size, those must be deleted.
author = db.ReferenceProperty(UserData,required=True)
author_nickname = db.StringProperty(required=True)
thumbnail = db.BlobProperty(required=True)
url_path = db.StringProperty(required=True)#Unique
image_version = db.IntegerProperty()
creation_date = db.DateTimeProperty(auto_now_add=True)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from django import template
from google.appengine.ext import webapp
from utilities.AppProperties import AppProperties
register = webapp.template.create_template_register()
import datetime
def relativize(value):
now = datetime.datetime.now()
diff = now - value
days = diff.days
seconds = diff.seconds
if days > 365:
return getLocale("%d years") % (days / 365, )
if days > 30:
return getLocale("%d months") % (days / 30, )
if days > 0:
return getLocale("%d days") % (days, )
if seconds > 3600:
return getLocale("%d hours") % (seconds / 3600, )
if seconds > 60:
return getLocale("%d minutes") % (seconds / 60, )
return getLocale("%d seconds") % (seconds, )
register.filter(relativize)
def nolinebreaks(value):
return ' '.join(str(value).splitlines())
register.filter(nolinebreaks)
def markdown(value, arg=''):
try:
import markdown
except ImportError:
return "error"
else:
extensions=arg.split(",")
return markdown.markdown(value, extensions, safe_mode=True)
register.filter(markdown)
def smiley(value):
value = value.replace(' :)', ' <img src="/static/images/smileys/smile.png" class="icon" alt=":)" />')
value = value.replace(' :-)', ' <img src="/static/images/smileys/smile.png" class="icon" alt=":-)" />')
value = value.replace(' :D', ' <img src="/static/images/smileys/jokingly.png" class="icon" alt=":D" />')
value = value.replace(' :-D', ' <img src="/static/images/smileys/jokingly.png" class="icon" alt=":-D" />')
value = value.replace(' :(', ' <img src="/static/images/smileys/sad.png" class="icon" alt=":(" />')
value = value.replace(' :-(', ' <img src="/static/images/smileys/sad.png" class="icon" alt=":-(" />')
value = value.replace(' :|', ' <img src="/static/images/smileys/indifference.png" class="icon" alt=":|" />')
value = value.replace(' :-|', ' <img src="/static/images/smileys/indifference.png" class="icon" alt=":-|" />')
value = value.replace(' :O', ' <img src="/static/images/smileys/surprised.png" class="icon" alt=":O" />')
value = value.replace(' :/', ' <img src="/static/images/smileys/think.png" class="icon" alt=":/" />')
value = value.replace(' :P', ' <img src="/static/images/smileys/tongue.png" class="icon" alt=":P" />')
value = value.replace(' :-P', ' <img src="/static/images/smileys/tongue.png" class="icon" alt=":-P" />')
value = value.replace(' ;)', ' <img src="/static/images/smileys/wink.png" class="icon" alt=";)" />')
value = value.replace(' ;-)', ' <img src="/static/images/smileys/wink.png" class="icon" alt=";-)" />')
value = value.replace(' :*)', ' <img src="/static/images/smileys/embarrassed.png" class="icon" alt=":*)" />')
value = value.replace(' 8-)', ' <img src="/static/images/smileys/cool.png" class="icon" alt="8-)" />')
# value = value.replace(' :'(', ' <img src="/static/images/smileys/cry.png" class="icon" alt=":'(" />')
value = value.replace(' :_(', ' <img src="/static/images/smileys/cry.png" class="icon" alt=":_(" />')
value = value.replace(' :-X', ' <img src="/static/images/smileys/crossedlips.png" class="icon" alt=":-X" />')
return value
register.filter(smiley)
#This Pagination is deprecated
class Pagination(template.Node):
def render(self,context):
prev = self.get('prev', context)
next = self.get('next', context)
params = []
p = self.get('p', context)
q = self.get('q', context)
a = self.get('a', context)
t = self.get('article_type', context)
if a:
a = '#%s' % str(a)
else:
a = ''
if t:
t = '&article_type=%s' % str(t)
else:
t = ''
s = ''
if prev or next:
s = '<p class="paginator">'
if prev:
if prev == 1:
if q:
qp = 'q=%s' % str(q)
else:
qp = ''
s = '%s<a href="?%s%s%s">« %s</a> |' % (s, qp, t, a, getLocale("Previous"))
else:
if q:
qp = '&q=%s' % str(q)
else:
qp = ''
s = '%s<a href="?p=%d%s%s%s">« %s</a> |' % (s, prev, qp, t, a, getLocale("Previous"))
s = '%s '+getLocale("Page")+' %d ' % (s, p)
if next:
if q:
q = '&q=%s' % str(q)
else:
q = ''
s = '%s| <a href="?p=%d%s%s%s">%s »</a>' % (s, next, q, t, a, getLocale("Next"))
s = '%s</p>' % s
return s
def get(self, key, context):
try:
return template.resolve_variable(key, context)
except template.VariableDoesNotExist:
return None
### i18n
def getLocale(label):
env = AppProperties().getJinjaEnv()
t = env.get_template("/translator-util.html")
return t.render({"label": label})
@register.tag
def pagination(parser, token):
return Pagination() | Python |
"""
Implementation of JSONEncoder
"""
import re
try:
from simplejson import _speedups
except ImportError:
_speedups = None
ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
ESCAPE_ASCII = re.compile(r'([\\"/]|[^\ -~])')
ESCAPE_DCT = {
'\\': '\\\\',
'"': '\\"',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
}
for i in range(0x20):
ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
# assume this produces an infinity on all machines (probably not guaranteed)
INFINITY = float('1e66666')
FLOAT_REPR = repr
def floatstr(o, allow_nan=True):
# Check for specials. Note that this type of test is processor- and/or
# platform-specific, so do tests which don't depend on the internals.
if o != o:
text = 'NaN'
elif o == INFINITY:
text = 'Infinity'
elif o == -INFINITY:
text = '-Infinity'
else:
return FLOAT_REPR(o)
if not allow_nan:
raise ValueError("Out of range float values are not JSON compliant: %r"
% (o,))
return text
def encode_basestring(s):
"""
Return a JSON representation of a Python string
"""
def replace(match):
return ESCAPE_DCT[match.group(0)]
return '"' + ESCAPE.sub(replace, s) + '"'
def encode_basestring_ascii(s):
def replace(match):
s = match.group(0)
try:
return ESCAPE_DCT[s]
except KeyError:
n = ord(s)
if n < 0x10000:
return '\\u%04x' % (n,)
else:
# surrogate pair
n -= 0x10000
s1 = 0xd800 | ((n >> 10) & 0x3ff)
s2 = 0xdc00 | (n & 0x3ff)
return '\\u%04x\\u%04x' % (s1, s2)
return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"'
try:
encode_basestring_ascii = _speedups.encode_basestring_ascii
_need_utf8 = True
except AttributeError:
_need_utf8 = False
class JSONEncoder(object):
"""
Extensible JSON <http://json.org> encoder for Python data structures.
Supports the following objects and types by default:
+-------------------+---------------+
| Python | JSON |
+===================+===============+
| dict | object |
+-------------------+---------------+
| list, tuple | array |
+-------------------+---------------+
| str, unicode | string |
+-------------------+---------------+
| int, long, float | number |
+-------------------+---------------+
| True | true |
+-------------------+---------------+
| False | false |
+-------------------+---------------+
| None | null |
+-------------------+---------------+
To extend this to recognize other objects, subclass and implement a
``.default()`` method with another method that returns a serializable
object for ``o`` if possible, otherwise it should call the superclass
implementation (to raise ``TypeError``).
"""
__all__ = ['__init__', 'default', 'encode', 'iterencode']
item_separator = ', '
key_separator = ': '
def __init__(self, skipkeys=False, ensure_ascii=True,
check_circular=True, allow_nan=True, sort_keys=False,
indent=None, separators=None, encoding='utf-8', default=None):
"""
Constructor for JSONEncoder, with sensible defaults.
If skipkeys is False, then it is a TypeError to attempt
encoding of keys that are not str, int, long, float or None. If
skipkeys is True, such items are simply skipped.
If ensure_ascii is True, the output is guaranteed to be str
objects with all incoming unicode characters escaped. If
ensure_ascii is false, the output will be unicode object.
If check_circular is True, then lists, dicts, and custom encoded
objects will be checked for circular references during encoding to
prevent an infinite recursion (which would cause an OverflowError).
Otherwise, no such check takes place.
If allow_nan is True, then NaN, Infinity, and -Infinity will be
encoded as such. This behavior is not JSON specification compliant,
but is consistent with most JavaScript based encoders and decoders.
Otherwise, it will be a ValueError to encode such floats.
If sort_keys is True, then the output of dictionaries will be
sorted by key; this is useful for regression tests to ensure
that JSON serializations can be compared on a day-to-day basis.
If indent is a non-negative integer, then JSON array
elements and object members will be pretty-printed with that
indent level. An indent level of 0 will only insert newlines.
None is the most compact representation.
If specified, separators should be a (item_separator, key_separator)
tuple. The default is (', ', ': '). To get the most compact JSON
representation you should specify (',', ':') to eliminate whitespace.
If specified, default is a function that gets called for objects
that can't otherwise be serialized. It should return a JSON encodable
version of the object or raise a ``TypeError``.
If encoding is not None, then all input strings will be
transformed into unicode using that encoding prior to JSON-encoding.
The default is UTF-8.
"""
self.skipkeys = skipkeys
self.ensure_ascii = ensure_ascii
self.check_circular = check_circular
self.allow_nan = allow_nan
self.sort_keys = sort_keys
self.indent = indent
self.current_indent_level = 0
if separators is not None:
self.item_separator, self.key_separator = separators
if default is not None:
self.default = default
self.encoding = encoding
def _newline_indent(self):
return '\n' + (' ' * (self.indent * self.current_indent_level))
def _iterencode_list(self, lst, markers=None):
if not lst:
yield '[]'
return
if markers is not None:
markerid = id(lst)
if markerid in markers:
raise ValueError("Circular reference detected")
markers[markerid] = lst
yield '['
if self.indent is not None:
self.current_indent_level += 1
newline_indent = self._newline_indent()
separator = self.item_separator + newline_indent
yield newline_indent
else:
newline_indent = None
separator = self.item_separator
first = True
for value in lst:
if first:
first = False
else:
yield separator
for chunk in self._iterencode(value, markers):
yield chunk
if newline_indent is not None:
self.current_indent_level -= 1
yield self._newline_indent()
yield ']'
if markers is not None:
del markers[markerid]
def _iterencode_dict(self, dct, markers=None):
if not dct:
yield '{}'
return
if markers is not None:
markerid = id(dct)
if markerid in markers:
raise ValueError("Circular reference detected")
markers[markerid] = dct
yield '{'
key_separator = self.key_separator
if self.indent is not None:
self.current_indent_level += 1
newline_indent = self._newline_indent()
item_separator = self.item_separator + newline_indent
yield newline_indent
else:
newline_indent = None
item_separator = self.item_separator
first = True
if self.ensure_ascii:
encoder = encode_basestring_ascii
else:
encoder = encode_basestring
allow_nan = self.allow_nan
if self.sort_keys:
keys = dct.keys()
keys.sort()
items = [(k, dct[k]) for k in keys]
else:
items = dct.iteritems()
_encoding = self.encoding
_do_decode = (_encoding is not None
and not (_need_utf8 and _encoding == 'utf-8'))
for key, value in items:
if isinstance(key, str):
if _do_decode:
key = key.decode(_encoding)
elif isinstance(key, basestring):
pass
# JavaScript is weakly typed for these, so it makes sense to
# also allow them. Many encoders seem to do something like this.
elif isinstance(key, float):
key = floatstr(key, allow_nan)
elif isinstance(key, (int, long)):
key = str(key)
elif key is True:
key = 'true'
elif key is False:
key = 'false'
elif key is None:
key = 'null'
elif self.skipkeys:
continue
else:
raise TypeError("key %r is not a string" % (key,))
if first:
first = False
else:
yield item_separator
yield encoder(key)
yield key_separator
for chunk in self._iterencode(value, markers):
yield chunk
if newline_indent is not None:
self.current_indent_level -= 1
yield self._newline_indent()
yield '}'
if markers is not None:
del markers[markerid]
def _iterencode(self, o, markers=None):
if isinstance(o, basestring):
if self.ensure_ascii:
encoder = encode_basestring_ascii
else:
encoder = encode_basestring
_encoding = self.encoding
if (_encoding is not None and isinstance(o, str)
and not (_need_utf8 and _encoding == 'utf-8')):
o = o.decode(_encoding)
yield encoder(o)
elif o is None:
yield 'null'
elif o is True:
yield 'true'
elif o is False:
yield 'false'
elif isinstance(o, (int, long)):
yield str(o)
elif isinstance(o, float):
yield floatstr(o, self.allow_nan)
elif isinstance(o, (list, tuple)):
for chunk in self._iterencode_list(o, markers):
yield chunk
elif isinstance(o, dict):
for chunk in self._iterencode_dict(o, markers):
yield chunk
else:
if markers is not None:
markerid = id(o)
if markerid in markers:
raise ValueError("Circular reference detected")
markers[markerid] = o
for chunk in self._iterencode_default(o, markers):
yield chunk
if markers is not None:
del markers[markerid]
def _iterencode_default(self, o, markers=None):
newobj = self.default(o)
return self._iterencode(newobj, markers)
def default(self, o):
"""
Implement this method in a subclass such that it returns
a serializable object for ``o``, or calls the base implementation
(to raise a ``TypeError``).
For example, to support arbitrary iterators, you could
implement default like this::
def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
return JSONEncoder.default(self, o)
"""
raise TypeError("%r is not JSON serializable" % (o,))
def encode(self, o):
"""
Return a JSON string representation of a Python data structure.
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
"""
# This is for extremely simple cases and benchmarks...
if isinstance(o, basestring):
if isinstance(o, str):
_encoding = self.encoding
if (_encoding is not None
and not (_encoding == 'utf-8' and _need_utf8)):
o = o.decode(_encoding)
return encode_basestring_ascii(o)
# This doesn't pass the iterator directly to ''.join() because it
# sucks at reporting exceptions. It's going to do this internally
# anyway because it uses PySequence_Fast or similar.
chunks = list(self.iterencode(o))
return ''.join(chunks)
def iterencode(self, o):
"""
Encode the given object and yield each string
representation as available.
For example::
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)
"""
if self.check_circular:
markers = {}
else:
markers = None
return self._iterencode(o, markers)
__all__ = ['JSONEncoder']
| Python |
import simplejson
import cgi
class JSONFilter(object):
def __init__(self, app, mime_type='text/x-json'):
self.app = app
self.mime_type = mime_type
def __call__(self, environ, start_response):
# Read JSON POST input to jsonfilter.json if matching mime type
response = {'status': '200 OK', 'headers': []}
def json_start_response(status, headers):
response['status'] = status
response['headers'].extend(headers)
environ['jsonfilter.mime_type'] = self.mime_type
if environ.get('REQUEST_METHOD', '') == 'POST':
if environ.get('CONTENT_TYPE', '') == self.mime_type:
args = [_ for _ in [environ.get('CONTENT_LENGTH')] if _]
data = environ['wsgi.input'].read(*map(int, args))
environ['jsonfilter.json'] = simplejson.loads(data)
res = simplejson.dumps(self.app(environ, json_start_response))
jsonp = cgi.parse_qs(environ.get('QUERY_STRING', '')).get('jsonp')
if jsonp:
content_type = 'text/javascript'
res = ''.join(jsonp + ['(', res, ')'])
elif 'Opera' in environ.get('HTTP_USER_AGENT', ''):
# Opera has bunk XMLHttpRequest support for most mime types
content_type = 'text/plain'
else:
content_type = self.mime_type
headers = [
('Content-type', content_type),
('Content-length', len(res)),
]
headers.extend(response['headers'])
start_response(response['status'], headers)
return [res]
def factory(app, global_conf, **kw):
return JSONFilter(app, **kw)
| Python |
"""
Implementation of JSONDecoder
"""
import re
import sys
from simplejson.scanner import Scanner, pattern
try:
from simplejson import _speedups
except:
_speedups = None
FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
def _floatconstants():
import struct
import sys
_BYTES = '7FF80000000000007FF0000000000000'.decode('hex')
if sys.byteorder != 'big':
_BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1]
nan, inf = struct.unpack('dd', _BYTES)
return nan, inf, -inf
NaN, PosInf, NegInf = _floatconstants()
def linecol(doc, pos):
lineno = doc.count('\n', 0, pos) + 1
if lineno == 1:
colno = pos
else:
colno = pos - doc.rindex('\n', 0, pos)
return lineno, colno
def errmsg(msg, doc, pos, end=None):
lineno, colno = linecol(doc, pos)
if end is None:
return '%s: line %d column %d (char %d)' % (msg, lineno, colno, pos)
endlineno, endcolno = linecol(doc, end)
return '%s: line %d column %d - line %d column %d (char %d - %d)' % (
msg, lineno, colno, endlineno, endcolno, pos, end)
_CONSTANTS = {
'-Infinity': NegInf,
'Infinity': PosInf,
'NaN': NaN,
'true': True,
'false': False,
'null': None,
}
def JSONConstant(match, context, c=_CONSTANTS):
s = match.group(0)
fn = getattr(context, 'parse_constant', None)
if fn is None:
rval = c[s]
else:
rval = fn(s)
return rval, None
pattern('(-?Infinity|NaN|true|false|null)')(JSONConstant)
def JSONNumber(match, context):
match = JSONNumber.regex.match(match.string, *match.span())
integer, frac, exp = match.groups()
if frac or exp:
fn = getattr(context, 'parse_float', None) or float
res = fn(integer + (frac or '') + (exp or ''))
else:
fn = getattr(context, 'parse_int', None) or int
res = fn(integer)
return res, None
pattern(r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?')(JSONNumber)
STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS)
BACKSLASH = {
'"': u'"', '\\': u'\\', '/': u'/',
'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t',
}
DEFAULT_ENCODING = "utf-8"
def scanstring(s, end, encoding=None, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match):
if encoding is None:
encoding = DEFAULT_ENCODING
chunks = []
_append = chunks.append
begin = end - 1
while 1:
chunk = _m(s, end)
if chunk is None:
raise ValueError(
errmsg("Unterminated string starting at", s, begin))
end = chunk.end()
content, terminator = chunk.groups()
if content:
if not isinstance(content, unicode):
content = unicode(content, encoding)
_append(content)
if terminator == '"':
break
elif terminator != '\\':
if strict:
raise ValueError(errmsg("Invalid control character %r at", s, end))
else:
_append(terminator)
continue
try:
esc = s[end]
except IndexError:
raise ValueError(
errmsg("Unterminated string starting at", s, begin))
if esc != 'u':
try:
m = _b[esc]
except KeyError:
raise ValueError(
errmsg("Invalid \\escape: %r" % (esc,), s, end))
end += 1
else:
esc = s[end + 1:end + 5]
next_end = end + 5
msg = "Invalid \\uXXXX escape"
try:
if len(esc) != 4:
raise ValueError
uni = int(esc, 16)
if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535:
msg = "Invalid \\uXXXX\\uXXXX surrogate pair"
if not s[end + 5:end + 7] == '\\u':
raise ValueError
esc2 = s[end + 7:end + 11]
if len(esc2) != 4:
raise ValueError
uni2 = int(esc2, 16)
uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00))
next_end += 6
m = unichr(uni)
except ValueError:
raise ValueError(errmsg(msg, s, end))
end = next_end
_append(m)
return u''.join(chunks), end
# Use speedup
if _speedups is not None:
scanstring = _speedups.scanstring
def JSONString(match, context):
encoding = getattr(context, 'encoding', None)
strict = getattr(context, 'strict', True)
return scanstring(match.string, match.end(), encoding, strict)
pattern(r'"')(JSONString)
WHITESPACE = re.compile(r'\s*', FLAGS)
def JSONObject(match, context, _w=WHITESPACE.match):
pairs = {}
s = match.string
end = _w(s, match.end()).end()
nextchar = s[end:end + 1]
# trivial empty object
if nextchar == '}':
return pairs, end + 1
if nextchar != '"':
raise ValueError(errmsg("Expecting property name", s, end))
end += 1
encoding = getattr(context, 'encoding', None)
strict = getattr(context, 'strict', True)
iterscan = JSONScanner.iterscan
while True:
key, end = scanstring(s, end, encoding, strict)
end = _w(s, end).end()
if s[end:end + 1] != ':':
raise ValueError(errmsg("Expecting : delimiter", s, end))
end = _w(s, end + 1).end()
try:
value, end = iterscan(s, idx=end, context=context).next()
except StopIteration:
raise ValueError(errmsg("Expecting object", s, end))
pairs[key] = value
end = _w(s, end).end()
nextchar = s[end:end + 1]
end += 1
if nextchar == '}':
break
if nextchar != ',':
raise ValueError(errmsg("Expecting , delimiter", s, end - 1))
end = _w(s, end).end()
nextchar = s[end:end + 1]
end += 1
if nextchar != '"':
raise ValueError(errmsg("Expecting property name", s, end - 1))
object_hook = getattr(context, 'object_hook', None)
if object_hook is not None:
pairs = object_hook(pairs)
return pairs, end
pattern(r'{')(JSONObject)
def JSONArray(match, context, _w=WHITESPACE.match):
values = []
s = match.string
end = _w(s, match.end()).end()
# look-ahead for trivial empty array
nextchar = s[end:end + 1]
if nextchar == ']':
return values, end + 1
iterscan = JSONScanner.iterscan
while True:
try:
value, end = iterscan(s, idx=end, context=context).next()
except StopIteration:
raise ValueError(errmsg("Expecting object", s, end))
values.append(value)
end = _w(s, end).end()
nextchar = s[end:end + 1]
end += 1
if nextchar == ']':
break
if nextchar != ',':
raise ValueError(errmsg("Expecting , delimiter", s, end))
end = _w(s, end).end()
return values, end
pattern(r'\[')(JSONArray)
ANYTHING = [
JSONObject,
JSONArray,
JSONString,
JSONConstant,
JSONNumber,
]
JSONScanner = Scanner(ANYTHING)
class JSONDecoder(object):
"""
Simple JSON <http://json.org> decoder
Performs the following translations in decoding by default:
+---------------+-------------------+
| JSON | Python |
+===============+===================+
| object | dict |
+---------------+-------------------+
| array | list |
+---------------+-------------------+
| string | unicode |
+---------------+-------------------+
| number (int) | int, long |
+---------------+-------------------+
| number (real) | float |
+---------------+-------------------+
| true | True |
+---------------+-------------------+
| false | False |
+---------------+-------------------+
| null | None |
+---------------+-------------------+
It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as
their corresponding ``float`` values, which is outside the JSON spec.
"""
_scanner = Scanner(ANYTHING)
__all__ = ['__init__', 'decode', 'raw_decode']
def __init__(self, encoding=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, strict=True):
"""
``encoding`` determines the encoding used to interpret any ``str``
objects decoded by this instance (utf-8 by default). It has no
effect when decoding ``unicode`` objects.
Note that currently only encodings that are a superset of ASCII work,
strings of other encodings should be passed in as ``unicode``.
``object_hook``, if specified, will be called with the result
of every JSON object decoded and its return value will be used in
place of the given ``dict``. This can be used to provide custom
deserializations (e.g. to support JSON-RPC class hinting).
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
``parse_int``, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
``parse_constant``, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN, null, true, false.
This can be used to raise an exception if invalid JSON numbers
are encountered.
"""
self.encoding = encoding
self.object_hook = object_hook
self.parse_float = parse_float
self.parse_int = parse_int
self.parse_constant = parse_constant
self.strict = strict
def decode(self, s, _w=WHITESPACE.match):
"""
Return the Python representation of ``s`` (a ``str`` or ``unicode``
instance containing a JSON document)
"""
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
end = _w(s, end).end()
if end != len(s):
raise ValueError(errmsg("Extra data", s, end, len(s)))
return obj
def raw_decode(self, s, **kw):
"""
Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning
with a JSON document) and return a 2-tuple of the Python
representation and the index in ``s`` where the document ended.
This can be used to decode a JSON document from a string that may
have extraneous data at the end.
"""
kw.setdefault('context', self)
try:
obj, end = self._scanner.iterscan(s, **kw).next()
except StopIteration:
raise ValueError("No JSON object could be decoded")
return obj, end
__all__ = ['JSONDecoder']
| Python |
r"""
A simple, fast, extensible JSON encoder and decoder
JSON (JavaScript Object Notation) <http://json.org> is a subset of
JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
interchange format.
simplejson exposes an API familiar to uses of the standard library
marshal and pickle modules.
Encoding basic Python object hierarchies::
>>> import simplejson
>>> simplejson.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print simplejson.dumps("\"foo\bar")
"\"foo\bar"
>>> print simplejson.dumps(u'\u1234')
"\u1234"
>>> print simplejson.dumps('\\')
"\\"
>>> print simplejson.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
{"a": 0, "b": 0, "c": 0}
>>> from StringIO import StringIO
>>> io = StringIO()
>>> simplejson.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'
Compact encoding::
>>> import simplejson
>>> simplejson.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
'[1,2,3,{"4":5,"6":7}]'
Pretty printing::
>>> import simplejson
>>> print simplejson.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
{
"4": 5,
"6": 7
}
Decoding JSON::
>>> import simplejson
>>> simplejson.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
>>> simplejson.loads('"\\"foo\\bar"')
u'"foo\x08ar'
>>> from StringIO import StringIO
>>> io = StringIO('["streaming API"]')
>>> simplejson.load(io)
[u'streaming API']
Specializing JSON object decoding::
>>> import simplejson
>>> def as_complex(dct):
... if '__complex__' in dct:
... return complex(dct['real'], dct['imag'])
... return dct
...
>>> simplejson.loads('{"__complex__": true, "real": 1, "imag": 2}',
... object_hook=as_complex)
(1+2j)
>>> import decimal
>>> simplejson.loads('1.1', parse_float=decimal.Decimal)
decimal.Decimal(1.1)
Extending JSONEncoder::
>>> import simplejson
>>> class ComplexEncoder(simplejson.JSONEncoder):
... def default(self, obj):
... if isinstance(obj, complex):
... return [obj.real, obj.imag]
... return simplejson.JSONEncoder.default(self, obj)
...
>>> dumps(2 + 1j, cls=ComplexEncoder)
'[2.0, 1.0]'
>>> ComplexEncoder().encode(2 + 1j)
'[2.0, 1.0]'
>>> list(ComplexEncoder().iterencode(2 + 1j))
['[', '2.0', ', ', '1.0', ']']
Using simplejson from the shell to validate and
pretty-print::
$ echo '{"json":"obj"}' | python -msimplejson
{
"json": "obj"
}
$ echo '{ 1.2:3.4}' | python -msimplejson
Expecting property name: line 1 column 2 (char 2)
Note that the JSON produced by this module's default settings
is a subset of YAML, so it may be used as a serializer for that as well.
"""
__version__ = '1.8.2'
__all__ = [
'dump', 'dumps', 'load', 'loads',
'JSONDecoder', 'JSONEncoder',
]
if __name__ == '__main__':
from simplejson.decoder import JSONDecoder
from simplejson.encoder import JSONEncoder
else:
from decoder import JSONDecoder
from encoder import JSONEncoder
_default_encoder = JSONEncoder(
skipkeys=False,
ensure_ascii=True,
check_circular=True,
allow_nan=True,
indent=None,
separators=None,
encoding='utf-8',
default=None,
)
def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, **kw):
"""
Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp``
may be ``unicode`` instances, subject to normal Python ``str`` to
``unicode`` coercion rules. Unless ``fp.write()`` explicitly
understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
to cause an error.
If ``check_circular`` is ``False``, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
in strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a non-negative integer, then JSON array elements and object
members will be pretty-printed with that indent level. An indent level
of 0 will only insert newlines. ``None`` is the most compact representation.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(', ', ': ')`` separators.
``(',', ':')`` is the most compact JSON representation.
``encoding`` is the character encoding for str instances, default is UTF-8.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg.
"""
# cached encoder
if (skipkeys is False and ensure_ascii is True and
check_circular is True and allow_nan is True and
cls is None and indent is None and separators is None and
encoding == 'utf-8' and default is None and not kw):
iterable = _default_encoder.iterencode(obj)
else:
if cls is None:
cls = JSONEncoder
iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
check_circular=check_circular, allow_nan=allow_nan, indent=indent,
separators=separators, encoding=encoding,
default=default, **kw).iterencode(obj)
# could accelerate with writelines in some versions of Python, at
# a debuggability cost
for chunk in iterable:
fp.write(chunk)
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, **kw):
"""
Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is ``False``, then the return value will be a
``unicode`` instance subject to normal Python ``str`` to ``unicode``
coercion rules instead of being escaped to an ASCII ``str``.
If ``check_circular`` is ``False``, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. ``None`` is the most compact
representation.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(', ', ': ')`` separators.
``(',', ':')`` is the most compact JSON representation.
``encoding`` is the character encoding for str instances, default is UTF-8.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg.
"""
# cached encoder
if (skipkeys is False and ensure_ascii is True and
check_circular is True and allow_nan is True and
cls is None and indent is None and separators is None and
encoding == 'utf-8' and default is None and not kw):
return _default_encoder.encode(obj)
if cls is None:
cls = JSONEncoder
return cls(
skipkeys=skipkeys, ensure_ascii=ensure_ascii,
check_circular=check_circular, allow_nan=allow_nan, indent=indent,
separators=separators, encoding=encoding, default=default,
**kw).encode(obj)
_default_decoder = JSONDecoder(encoding=None, object_hook=None)
def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, **kw):
"""
Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
a JSON document) to a Python object.
If the contents of ``fp`` is encoded with an ASCII based encoding other
than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
be specified. Encodings that are not ASCII based (such as UCS-2) are
not allowed, and should be wrapped with
``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``
object and passed to ``loads()``
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg.
"""
return loads(fp.read(),
encoding=encoding, cls=cls, object_hook=object_hook,
parse_float=parse_float, parse_int=parse_int,
parse_constant=parse_constant, **kw)
def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, **kw):
"""
Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
must be specified. Encodings that are not ASCII based (such as UCS-2)
are not allowed and should be decoded to ``unicode`` first.
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
``parse_int``, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
``parse_constant``, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN, null, true, false.
This can be used to raise an exception if invalid JSON numbers
are encountered.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg.
"""
if (cls is None and encoding is None and object_hook is None and
parse_int is None and parse_float is None and
parse_constant is None and not kw):
return _default_decoder.decode(s)
if cls is None:
cls = JSONDecoder
if object_hook is not None:
kw['object_hook'] = object_hook
if parse_float is not None:
kw['parse_float'] = parse_float
if parse_int is not None:
kw['parse_int'] = parse_int
if parse_constant is not None:
kw['parse_constant'] = parse_constant
return cls(encoding=encoding, **kw).decode(s)
#
# Compatibility cruft from other libraries
#
def decode(s):
"""
demjson, python-cjson API compatibility hook. Use loads(s) instead.
"""
import warnings
warnings.warn("simplejson.loads(s) should be used instead of decode(s)",
DeprecationWarning)
return loads(s)
def encode(obj):
"""
demjson, python-cjson compatibility hook. Use dumps(s) instead.
"""
import warnings
warnings.warn("simplejson.dumps(s) should be used instead of encode(s)",
DeprecationWarning)
return dumps(obj)
def read(s):
"""
jsonlib, JsonUtils, python-json, json-py API compatibility hook.
Use loads(s) instead.
"""
import warnings
warnings.warn("simplejson.loads(s) should be used instead of read(s)",
DeprecationWarning)
return loads(s)
def write(obj):
"""
jsonlib, JsonUtils, python-json, json-py API compatibility hook.
Use dumps(s) instead.
"""
import warnings
warnings.warn("simplejson.dumps(s) should be used instead of write(s)",
DeprecationWarning)
return dumps(obj)
#
# Pretty printer:
# curl http://mochikit.com/examples/ajax_tables/domains.json | python -msimplejson
#
def main():
import sys
if len(sys.argv) == 1:
infile = sys.stdin
outfile = sys.stdout
elif len(sys.argv) == 2:
infile = open(sys.argv[1], 'rb')
outfile = sys.stdout
elif len(sys.argv) == 3:
infile = open(sys.argv[1], 'rb')
outfile = open(sys.argv[2], 'wb')
else:
raise SystemExit("%s [infile [outfile]]" % (sys.argv[0],))
try:
obj = load(infile)
except ValueError, e:
raise SystemExit(e)
dump(obj, outfile, sort_keys=True, indent=4)
outfile.write('\n')
if __name__ == '__main__':
main()
| Python |
"""
Iterator based sre token scanner
"""
import sre_parse, sre_compile, sre_constants
from sre_constants import BRANCH, SUBPATTERN
from re import VERBOSE, MULTILINE, DOTALL
import re
__all__ = ['Scanner', 'pattern']
FLAGS = (VERBOSE | MULTILINE | DOTALL)
class Scanner(object):
def __init__(self, lexicon, flags=FLAGS):
self.actions = [None]
# combine phrases into a compound pattern
s = sre_parse.Pattern()
s.flags = flags
p = []
for idx, token in enumerate(lexicon):
phrase = token.pattern
try:
subpattern = sre_parse.SubPattern(s,
[(SUBPATTERN, (idx + 1, sre_parse.parse(phrase, flags)))])
except sre_constants.error:
raise
p.append(subpattern)
self.actions.append(token)
s.groups = len(p)+1 # NOTE(guido): Added to make SRE validation work
p = sre_parse.SubPattern(s, [(BRANCH, (None, p))])
self.scanner = sre_compile.compile(p)
def iterscan(self, string, idx=0, context=None):
"""
Yield match, end_idx for each match
"""
match = self.scanner.scanner(string, idx).match
actions = self.actions
lastend = idx
end = len(string)
while True:
m = match()
if m is None:
break
matchbegin, matchend = m.span()
if lastend == matchend:
break
action = actions[m.lastindex]
if action is not None:
rval, next_pos = action(m, context)
if next_pos is not None and next_pos != matchend:
# "fast forward" the scanner
matchend = next_pos
match = self.scanner.scanner(string, matchend).match
yield rval, matchend
lastend = matchend
def pattern(pattern, flags=FLAGS):
def decorator(fn):
fn.pattern = pattern
fn.regex = re.compile(pattern, flags)
return fn
return decorator
| Python |
#!/usr/bin/env python
import struct
from StringIO import StringIO
from google.appengine.api import images
def resize(image, maxwidth, maxheight):
imageinfo = getimageinfo(image)
width = float(imageinfo[1])
height = float(imageinfo[2])
ratio = width / height
dwidth = maxheight * ratio
dheight = maxheight
if dwidth > maxwidth:
dwidth = maxwidth
dheight = maxwidth / ratio
return images.resize(image, int(dwidth), int(dheight))
def getimageinfo(data):
data = str(data)
size = len(data)
height = -1
width = -1
content_type = ''
# handle GIFs
if (size >= 10) and data[:6] in ('GIF87a', 'GIF89a'):
# Check to see if content_type is correct
content_type = 'image/gif'
w, h = struct.unpack("<HH", data[6:10])
width = int(w)
height = int(h)
# See PNG 2. Edition spec (http://www.w3.org/TR/PNG/)
# Bytes 0-7 are below, 4-byte chunk length, then 'IHDR'
# and finally the 4-byte width, height
elif ((size >= 24) and data.startswith('\211PNG\r\n\032\n')
and (data[12:16] == 'IHDR')):
content_type = 'image/png'
w, h = struct.unpack(">LL", data[16:24])
width = int(w)
height = int(h)
# Maybe this is for an older PNG version.
elif (size >= 16) and data.startswith('\211PNG\r\n\032\n'):
# Check to see if we have the right content type
content_type = 'image/png'
w, h = struct.unpack(">LL", data[8:16])
width = int(w)
height = int(h)
# handle JPEGs
elif (size >= 2) and data.startswith('\377\330'):
content_type = 'image/jpeg'
jpeg = StringIO(data)
jpeg.read(2)
b = jpeg.read(1)
try:
while (b and ord(b) != 0xDA):
while (ord(b) != 0xFF): b = jpeg.read
while (ord(b) == 0xFF): b = jpeg.read(1)
if (ord(b) >= 0xC0 and ord(b) <= 0xC3):
jpeg.read(3)
h, w = struct.unpack(">HH", jpeg.read(4))
break
else:
jpeg.read(int(struct.unpack(">H", jpeg.read(2))[0])-2)
b = jpeg.read(1)
width = int(w)
height = int(h)
except struct.error:
pass
except ValueError:
pass
return content_type, width, height | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import wsgiref.handlers
import os
from handlers import *
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
class NotAvailable(webapp.RequestHandler):
def get(self):
self.response.clear()
self.response.set_status(501)
self.response.headers['Content-Type'] = 'text/html;charset=UTF-8'
self.response.headers['Pragma'] = 'no-cache'
self.response.headers['Cache-Control'] = 'no-cache'
self.response.headers['Expires'] = 'Sat, 1 Jan 2011 00:00:00 GMT'
self.response.out.write(template.render('static/sorry.html', {}))
def main():
application = webapp.WSGIApplication(
[('/.*', NotAvailable)],
debug=True)
wsgiref.handlers.CGIHandler().run(application)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import wsgiref.handlers
from handlers import *
from handlers import Updater
#Updater.update() # TODO updater must be mooved from here
app = webapp.WSGIApplication(
[('/', MainPage),
# Module articles
('/module/article.list', ArticleList),
('/module/article.edit', ArticleEdit),
('/module/article.favourite', ArticleFavourite),
('/module/article.vote', ArticleVote),
('/module/article.tts/.*', ArticleTTS),
('/module/article/.*', ArticleView),
('/module/article.comment.subscribe',ArticleCommentSubscribe),
('/module/article.comment', ArticleComment),
('/module/article.delete', ArticleDelete),
('/module/article.comment.delete', ArticleCommentDelete),
('/module/article.add.communities', ArticleAddCommunities),
('/module/article.comment.edit', ArticleCommentEdit),
('/module/article.visit', ArticleVisit),
# Module users
('/module/user.list', UserList),
('/module/user/.*', UserView),
('/module/user.edit', UserEdit),
('/module/user.register', UserRegister),
('/module/user.login', UserLogin),
('/module/user.logout', UserLogout),
('/module/user.changepassword', UserChangePassword),
('/module/user.forgotpassword', UserForgotPassword),
('/module/user.resetpassword', UserResetPassword),
('/module/user.drafts', UserDrafts),
('/module/user.articles/.*', UserArticles),
('/module/user.communities/.*', UserCommunities),
('/module/user.favourites/.*', UserFavourites),
('/module/user.contacts/.*', UserContacts),
('/module/user.contact', UserContact),
('/module/user.promote', UserPromote),
('/module/user.events', UserEvents),
('/module/user.forums/.*', UserForums),
# Module Community
('/module/community.list', CommunityList),
('/module/community.edit', CommunityEdit),
('/module/community.move', CommunityMove),
('/module/community.delete', CommunityDelete),
('/module/community/.*', CommunityView),
# Community forums
('/module/community.forum.list/.*', CommunityForumList),
('/module/community.forum.edit', CommunityForumEdit),
('/module/community.forum/.*', CommunityForumView),
('/module/community.forum.reply', CommunityForumReply),
('/module/community.forum.subscribe',CommunityForumSubscribe),
('/module/community.forum.delete', CommunityForumDelete),
('/module/community.thread.edit', CommunityThreadEdit),
('/module/community.forum.move', CommunityForumMove),
('/module/community.forum.visit', CommunityForumVisit),
# Community articles
('/module/community.article.list/.*',CommunityArticleList),
('/module/community.article.add', CommunityNewArticle),
('/module/community.article.delete', CommunityArticleDelete),
# Community users
('/module/community.user.list/.*', CommunityUserList),
('/module/community.user.unjoin', CommunityUserUnjoin),
('/module/community.user.join', CommunityUserJoin),
# messages
('/message.edit', MessageEdit),
('/message.sent', MessageSent),
('/message.inbox', MessageInbox),
('/message.read/.*', MessageRead),
('/message.delete', MessageDelete),
# forums,
('/forum.list', ForumList),
# inviting contacts
('/invite', Invite),
# rss
('/feed/.*', Feed),
('/module/mblog.edit', MBlogEdit),
('/module/mblog/mblog.list', Dispatcher),
('/tag/.*', Tag),
('/search', Search),
('/search.result', SearchResult),
# images
('/images/upload', ImageUploader),
('/images/browse', ImageBrowser),
('/images/.*', ImageDisplayer),
# module admin
('/admin', Admin),
('/module/admin.application', AdminApplication),
('/module/admin.categories', AdminCategories),
('/module/admin.category.edit', AdminCategoryEdit),
('/module/admin.users', AdminUsers),
('/module/admin.lookandfeel', AdminLookAndFeel),
('/module/admin.modules', AdminModules),
('/module/admin.mail', AdminMail),
('/module/admin.google', AdminGoogle),
('/module/admin.stats', AdminStats),
('/module/admin.cache', AdminCache),
('/module/admin.community.add.related', AdminCommunityAddRelated),
# Ohters
('/mail.queue', MailQueue),
('/task.queue', TaskQueue),
#General
('/about', Dispatcher),
#('/initialization', Initialization),
('/html/.*', Static),
('/.*', NotFound)],
debug=True)
| Python |
import urllib
from google.appengine.api import urlfetch
"""
Adapted from http://pypi.python.org/pypi/recaptcha-client
to use with Google App Engine
by Joscha Feth <joscha@feth.com>
Version 0.1
"""
API_SSL_SERVER ="https://api-secure.recaptcha.net"
API_SERVER ="http://api.recaptcha.net"
VERIFY_SERVER ="api-verify.recaptcha.net"
class RecaptchaResponse(object):
def __init__(self, is_valid, error_code=None):
self.is_valid = is_valid
self.error_code = error_code
def displayhtml (public_key,
use_ssl = False,
error = None):
"""Gets the HTML to display for reCAPTCHA
public_key -- The public api key
use_ssl -- Should the request be sent over ssl?
error -- An error message to display (from RecaptchaResponse.error_code)"""
error_param = ''
if error:
error_param = '&error=%s' % error
if use_ssl:
server = API_SSL_SERVER
else:
server = API_SERVER
return """<script type="text/javascript" src="%(ApiServer)s/challenge?k=%(PublicKey)s%(ErrorParam)s"></script>
<noscript>
<iframe src="%(ApiServer)s/noscript?k=%(PublicKey)s%(ErrorParam)s" height="300" width="500" frameborder="0"></iframe><br />
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input type='hidden' name='recaptcha_response_field' value='manual_challenge' />
</noscript>
""" % {
'ApiServer' : server,
'PublicKey' : public_key,
'ErrorParam' : error_param,
}
def submit (recaptcha_challenge_field,
recaptcha_response_field,
private_key,
remoteip):
"""
Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
for the request
recaptcha_challenge_field -- The value of recaptcha_challenge_field from the form
recaptcha_response_field -- The value of recaptcha_response_field from the form
private_key -- your reCAPTCHA private key
remoteip -- the user's ip address
"""
if not (recaptcha_response_field and recaptcha_challenge_field and
len (recaptcha_response_field) and len (recaptcha_challenge_field)):
return RecaptchaResponse (is_valid = False, error_code = 'incorrect-captcha-sol')
headers = {
'Content-type': 'application/x-www-form-urlencoded',
"User-agent" : "reCAPTCHA GAE Python"
}
params = urllib.urlencode ({
'privatekey': private_key,
'remoteip' : remoteip,
'challenge': recaptcha_challenge_field,
'response' : recaptcha_response_field,
})
httpresp = urlfetch.fetch(
url = "http://%s/verify" % VERIFY_SERVER,
payload = params,
method = urlfetch.POST,
headers = headers
)
if httpresp.status_code == 200:
# response was fine
# get the return values
return_values = httpresp.content.splitlines();
# get the return code (true/false)
return_code = return_values[0]
if return_code == "true":
# yep, filled perfectly
return RecaptchaResponse (is_valid=True)
else:
# nope, something went wrong
return RecaptchaResponse (is_valid=False, error_code = return_values [1])
else:
# recaptcha server was not reachable
return RecaptchaResponse (is_valid=False, error_code = "recaptcha-not-reachable") | Python |
#!/usr/bin/env python
version = "1.7"
version_info = (1,7,0,"rc-2")
__revision__ = "$Rev: 72 $"
"""
Python-Markdown
===============
Converts Markdown to HTML. Basic usage as a module:
import markdown
md = Markdown()
html = md.convert(your_text_string)
See http://www.freewisdom.org/projects/python-markdown/ for more
information and instructions on how to extend the functionality of the
script. (You might want to read that before you try modifying this
file.)
Started by [Manfred Stienstra](http://www.dwerg.net/). Continued and
maintained by [Yuri Takhteyev](http://www.freewisdom.org) and [Waylan
Limberg](http://achinghead.com/).
Contact: yuri [at] freewisdom.org
waylan [at] gmail.com
License: GPL 2 (http://www.gnu.org/copyleft/gpl.html) or BSD
"""
import re, sys, codecs
from logging import getLogger, StreamHandler, Formatter, \
DEBUG, INFO, WARN, ERROR, CRITICAL
MESSAGE_THRESHOLD = CRITICAL
# Configure debug message logger (the hard way - to support python 2.3)
logger = getLogger('MARKDOWN')
logger.setLevel(DEBUG) # This is restricted by handlers later
console_hndlr = StreamHandler()
formatter = Formatter('%(name)s-%(levelname)s: "%(message)s"')
console_hndlr.setFormatter(formatter)
console_hndlr.setLevel(MESSAGE_THRESHOLD)
logger.addHandler(console_hndlr)
def message(level, text):
''' A wrapper method for logging debug messages. '''
# logger.log(level, text)
foo = ''
# --------------- CONSTANTS YOU MIGHT WANT TO MODIFY -----------------
TAB_LENGTH = 4 # expand tabs to this many spaces
ENABLE_ATTRIBUTES = True # @id = xyz -> <... id="xyz">
SMART_EMPHASIS = 1 # this_or_that does not become this<i>or</i>that
HTML_REMOVED_TEXT = "[HTML_REMOVED]" # text used instead of HTML in safe mode
RTL_BIDI_RANGES = ( (u'\u0590', u'\u07FF'),
# from Hebrew to Nko (includes Arabic, Syriac and Thaana)
(u'\u2D30', u'\u2D7F'),
# Tifinagh
)
# Unicode Reference Table:
# 0590-05FF - Hebrew
# 0600-06FF - Arabic
# 0700-074F - Syriac
# 0750-077F - Arabic Supplement
# 0780-07BF - Thaana
# 07C0-07FF - Nko
BOMS = { 'utf-8': (codecs.BOM_UTF8, ),
'utf-16': (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE),
#'utf-32': (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)
}
def removeBOM(text, encoding):
convert = isinstance(text, unicode)
for bom in BOMS[encoding]:
bom = convert and bom.decode(encoding) or bom
if text.startswith(bom):
return text.lstrip(bom)
return text
# The following constant specifies the name used in the usage
# statement displayed for python versions lower than 2.3. (With
# python2.3 and higher the usage statement is generated by optparse
# and uses the actual name of the executable called.)
EXECUTABLE_NAME_FOR_USAGE = "python markdown.py"
# --------------- CONSTANTS YOU _SHOULD NOT_ HAVE TO CHANGE ----------
# a template for html placeholders
HTML_PLACEHOLDER_PREFIX = "qaodmasdkwaspemas"
HTML_PLACEHOLDER = HTML_PLACEHOLDER_PREFIX + "%dajkqlsmdqpakldnzsdfls"
BLOCK_LEVEL_ELEMENTS = ['p', 'div', 'blockquote', 'pre', 'table',
'dl', 'ol', 'ul', 'script', 'noscript',
'form', 'fieldset', 'iframe', 'math', 'ins',
'del', 'hr', 'hr/', 'style']
def isBlockLevel (tag):
return ( (tag in BLOCK_LEVEL_ELEMENTS) or
(tag[0] == 'h' and tag[1] in "0123456789") )
"""
======================================================================
========================== NANODOM ===================================
======================================================================
The three classes below implement some of the most basic DOM
methods. I use this instead of minidom because I need a simpler
functionality and do not want to require additional libraries.
Importantly, NanoDom does not do normalization, which is what we
want. It also adds extra white space when converting DOM to string
"""
ENTITY_NORMALIZATION_EXPRESSIONS = [ (re.compile("&"), "&"),
(re.compile("<"), "<"),
(re.compile(">"), ">")]
ENTITY_NORMALIZATION_EXPRESSIONS_SOFT = [ (re.compile("&(?!\#)"), "&"),
(re.compile("<"), "<"),
(re.compile(">"), ">"),
(re.compile("\""), """)]
def getBidiType(text):
if not text: return None
ch = text[0]
if not isinstance(ch, unicode) or not ch.isalpha():
return None
else:
for min, max in RTL_BIDI_RANGES:
if ( ch >= min and ch <= max ):
return "rtl"
else:
return "ltr"
class Document:
def __init__ (self):
self.bidi = "ltr"
def appendChild(self, child):
self.documentElement = child
child.isDocumentElement = True
child.parent = self
self.entities = {}
def setBidi(self, bidi):
if bidi:
self.bidi = bidi
def createElement(self, tag, textNode=None):
el = Element(tag)
el.doc = self
if textNode:
el.appendChild(self.createTextNode(textNode))
return el
def createTextNode(self, text):
node = TextNode(text)
node.doc = self
return node
def createEntityReference(self, entity):
if entity not in self.entities:
self.entities[entity] = EntityReference(entity)
return self.entities[entity]
def createCDATA(self, text):
node = CDATA(text)
node.doc = self
return node
def toxml (self):
return self.documentElement.toxml()
def normalizeEntities(self, text, avoidDoubleNormalizing=False):
if avoidDoubleNormalizing:
regexps = ENTITY_NORMALIZATION_EXPRESSIONS_SOFT
else:
regexps = ENTITY_NORMALIZATION_EXPRESSIONS
for regexp, substitution in regexps:
text = regexp.sub(substitution, text)
return text
def find(self, test):
return self.documentElement.find(test)
def unlink(self):
self.documentElement.unlink()
self.documentElement = None
class CDATA:
type = "cdata"
def __init__ (self, text):
self.text = text
def handleAttributes(self):
pass
def toxml (self):
return "<![CDATA[" + self.text + "]]>"
class Element:
type = "element"
def __init__ (self, tag):
self.nodeName = tag
self.attributes = []
self.attribute_values = {}
self.childNodes = []
self.bidi = None
self.isDocumentElement = False
def setBidi(self, bidi):
if bidi:
orig_bidi = self.bidi
if not self.bidi or self.isDocumentElement:
# Once the bidi is set don't change it (except for doc element)
self.bidi = bidi
self.parent.setBidi(bidi)
def unlink(self):
for child in self.childNodes:
if child.type == "element":
child.unlink()
self.childNodes = None
def setAttribute(self, attr, value):
if not attr in self.attributes:
self.attributes.append(attr)
self.attribute_values[attr] = value
def insertChild(self, position, child):
self.childNodes.insert(position, child)
child.parent = self
def removeChild(self, child):
self.childNodes.remove(child)
def replaceChild(self, oldChild, newChild):
position = self.childNodes.index(oldChild)
self.removeChild(oldChild)
self.insertChild(position, newChild)
def appendChild(self, child):
self.childNodes.append(child)
child.parent = self
def handleAttributes(self):
pass
def find(self, test, depth=0):
""" Returns a list of descendants that pass the test function """
matched_nodes = []
for child in self.childNodes:
if test(child):
matched_nodes.append(child)
if child.type == "element":
matched_nodes += child.find(test, depth+1)
return matched_nodes
def toxml(self):
if ENABLE_ATTRIBUTES:
for child in self.childNodes:
child.handleAttributes()
buffer = ""
if self.nodeName in ['h1', 'h2', 'h3', 'h4']:
buffer += "\n"
elif self.nodeName in ['li']:
buffer += "\n "
# Process children FIRST, then do the attributes
childBuffer = ""
if self.childNodes or self.nodeName in ['blockquote']:
childBuffer += ">"
for child in self.childNodes:
childBuffer += child.toxml()
if self.nodeName == 'p':
childBuffer += "\n"
elif self.nodeName == 'li':
childBuffer += "\n "
childBuffer += "</%s>" % self.nodeName
else:
childBuffer += "/>"
buffer += "<" + self.nodeName
if self.nodeName in ['p', 'li', 'ul', 'ol',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6']:
if not self.attribute_values.has_key("dir"):
if self.bidi:
bidi = self.bidi
else:
bidi = self.doc.bidi
if bidi=="rtl":
self.setAttribute("dir", "rtl")
for attr in self.attributes:
value = self.attribute_values[attr]
value = self.doc.normalizeEntities(value,
avoidDoubleNormalizing=True)
buffer += ' %s="%s"' % (attr, value)
# Now let's actually append the children
buffer += childBuffer
if self.nodeName in ['p', 'br ', 'li', 'ul', 'ol',
'h1', 'h2', 'h3', 'h4'] :
buffer += "\n"
return buffer
class TextNode:
type = "text"
attrRegExp = re.compile(r'\{@([^\}]*)=([^\}]*)}') # {@id=123}
def __init__ (self, text):
self.value = text
def attributeCallback(self, match):
self.parent.setAttribute(match.community(1), match.community(2))
def handleAttributes(self):
self.value = self.attrRegExp.sub(self.attributeCallback, self.value)
def toxml(self):
text = self.value
self.parent.setBidi(getBidiType(text))
if not text.startswith(HTML_PLACEHOLDER_PREFIX):
if self.parent.nodeName == "p":
text = text.replace("\n", "\n ")
elif (self.parent.nodeName == "li"
and self.parent.childNodes[0]==self):
text = "\n " + text.replace("\n", "\n ")
text = self.doc.normalizeEntities(text)
return text
class EntityReference:
type = "entity_ref"
def __init__(self, entity):
self.entity = entity
def handleAttributes(self):
pass
def toxml(self):
return "&" + self.entity + ";"
"""
======================================================================
========================== PRE-PROCESSORS ============================
======================================================================
Preprocessors munge source text before we start doing anything too
complicated.
There are two types of preprocessors: TextPreprocessor and Preprocessor.
"""
class TextPreprocessor:
'''
TextPreprocessors are run before the text is broken into lines.
Each TextPreprocessor implements a "run" method that takes a pointer to a
text string of the document, modifies it as necessary and returns
either the same pointer or a pointer to a new string.
TextPreprocessors must extend markdown.TextPreprocessor.
'''
def run(self, text):
pass
class Preprocessor:
'''
Preprocessors are run after the text is broken into lines.
Each preprocessor implements a "run" method that takes a pointer to a
list of lines of the document, modifies it as necessary and returns
either the same pointer or a pointer to a new list.
Preprocessors must extend markdown.Preprocessor.
'''
def run(self, lines):
pass
class HtmlBlockPreprocessor(TextPreprocessor):
"""Removes html blocks from the source text and stores it."""
def _get_left_tag(self, block):
return block[1:].replace(">", " ", 1).split()[0].lower()
def _get_right_tag(self, left_tag, block):
return block.rstrip()[-len(left_tag)-2:-1].lower()
def _equal_tags(self, left_tag, right_tag):
if left_tag == 'div' or left_tag[0] in ['?', '@', '%']: # handle PHP, etc.
return True
if ("/" + left_tag) == right_tag:
return True
if (right_tag == "--" and left_tag == "--"):
return True
elif left_tag == right_tag[1:] \
and right_tag[0] != "<":
return True
else:
return False
def _is_oneliner(self, tag):
return (tag in ['hr', 'hr/'])
def run(self, text):
new_blocks = []
text = text.split("\n\n")
articles = []
left_tag = ''
right_tag = ''
in_tag = False # flag
for block in text:
if block.startswith("\n"):
block = block[1:]
if not in_tag:
if block.startswith("<"):
left_tag = self._get_left_tag(block)
right_tag = self._get_right_tag(left_tag, block)
if not (isBlockLevel(left_tag) \
or block[1] in ["!", "?", "@", "%"]):
new_blocks.append(block)
continue
if self._is_oneliner(left_tag):
new_blocks.append(block.strip())
continue
if block[1] == "!":
# is a comment block
left_tag = "--"
right_tag = self._get_right_tag(left_tag, block)
# keep checking conditions below and maybe just append
if block.rstrip().endswith(">") \
and self._equal_tags(left_tag, right_tag):
new_blocks.append(
self.stash.store(block.strip()))
continue
else: #if not block[1] == "!":
# if is block level tag and is not complete
articles.append(block.strip())
in_tag = True
continue
new_blocks.append(block)
else:
articles.append(block.strip())
right_tag = self._get_right_tag(left_tag, block)
if self._equal_tags(left_tag, right_tag):
# if find closing tag
in_tag = False
new_blocks.append(
self.stash.store('\n\n'.join(articles)))
articles = []
if articles:
new_blocks.append(self.stash.store('\n\n'.join(articles)))
new_blocks.append('\n')
return "\n\n".join(new_blocks)
HTML_BLOCK_PREPROCESSOR = HtmlBlockPreprocessor()
class HeaderPreprocessor(Preprocessor):
"""
Replaces underlined headers with hashed headers to avoid
the nead for lookahead later.
"""
def run (self, lines):
i = -1
while i+1 < len(lines):
i = i+1
if not lines[i].strip():
continue
if lines[i].startswith("#"):
lines.insert(i+1, "\n")
if (i+1 <= len(lines)
and lines[i+1]
and lines[i+1][0] in ['-', '=']):
underline = lines[i+1].strip()
if underline == "="*len(underline):
lines[i] = "# " + lines[i].strip()
lines[i+1] = ""
elif underline == "-"*len(underline):
lines[i] = "## " + lines[i].strip()
lines[i+1] = ""
return lines
HEADER_PREPROCESSOR = HeaderPreprocessor()
class LinePreprocessor(Preprocessor):
"""Deals with HR lines (needs to be done before processing lists)"""
blockquote_re = re.compile(r'^(> )+')
def run (self, lines):
for i in range(len(lines)):
prefix = ''
m = self.blockquote_re.search(lines[i])
if m : prefix = m.community(0)
if self._isLine(lines[i][len(prefix):]):
lines[i] = prefix + self.stash.store("<hr />", safe=True)
return lines
def _isLine(self, block):
"""Determines if a block should be replaced with an <HR>"""
if block.startswith(" "): return 0 # a code block
text = "".join([x for x in block if not x.isspace()])
if len(text) <= 2:
return 0
for pattern in ['isline1', 'isline2', 'isline3']:
m = RE.regExp[pattern].match(text)
if (m and m.community(1)):
return 1
else:
return 0
LINE_PREPROCESSOR = LinePreprocessor()
class ReferencePreprocessor(Preprocessor):
'''
Removes reference definitions from the text and stores them for later use.
'''
def run (self, lines):
new_text = [];
for line in lines:
m = RE.regExp['reference-def'].match(line)
if m:
id = m.community(2).strip().lower()
t = m.community(4).strip() # potential title
if not t:
self.references[id] = (m.community(3), t)
elif (len(t) >= 2
and (t[0] == t[-1] == "\""
or t[0] == t[-1] == "\'"
or (t[0] == "(" and t[-1] == ")") ) ):
self.references[id] = (m.community(3), t[1:-1])
else:
new_text.append(line)
else:
new_text.append(line)
return new_text #+ "\n"
REFERENCE_PREPROCESSOR = ReferencePreprocessor()
"""
======================================================================
========================== INLINE PATTERNS ===========================
======================================================================
Inline patterns such as *emphasis* are handled by means of auxiliary
objects, one per pattern. Pattern objects must be instances of classes
that extend markdown.Pattern. Each pattern object uses a single regular
expression and needs support the following methods:
pattern.getCompiledRegExp() - returns a regular expression
pattern.handleMatch(m, doc) - takes a match object and returns
a NanoDom node (as a part of the provided
doc) or None
All of python markdown's built-in patterns subclass from Patter,
but you can add additional patterns that don't.
Also note that all the regular expressions used by inline must
capture the whole block. For this reason, they all start with
'^(.*)' and end with '(.*)!'. In case with built-in expression
Pattern takes care of adding the "^(.*)" and "(.*)!".
Finally, the order in which regular expressions are applied is very
important - e.g. if we first replace http://.../ links with <a> tags
and _then_ try to replace inline html, we would end up with a mess.
So, we apply the expressions in the following order:
* escape and backticks have to go before everything else, so
that we can preempt any markdown patterns by escaping them.
* then we handle auto-links (must be done before inline html)
* then we handle inline HTML. At this point we will simply
replace all inline HTML strings with a placeholder and add
the actual HTML to a hash.
* then inline images (must be done before links)
* then bracketed links, first regular then reference-style
* finally we apply strong and emphasis
"""
NOBRACKET = r'[^\]\[]*'
BRK = ( r'\[('
+ (NOBRACKET + r'(\[')*6
+ (NOBRACKET+ r'\])*')*6
+ NOBRACKET + r')\]' )
NOIMG = r'(?<!\!)'
BACKTICK_RE = r'\`([^\`]*)\`' # `e= m*c^2`
DOUBLE_BACKTICK_RE = r'\`\`(.*)\`\`' # ``e=f("`")``
ESCAPE_RE = r'\\(.)' # \<
EMPHASIS_RE = r'\*([^\*]*)\*' # *emphasis*
STRONG_RE = r'\*\*(.*)\*\*' # **strong**
STRONG_EM_RE = r'\*\*\*([^_]*)\*\*\*' # ***strong***
if SMART_EMPHASIS:
EMPHASIS_2_RE = r'(?<!\S)_(\S[^_]*)_' # _emphasis_
else:
EMPHASIS_2_RE = r'_([^_]*)_' # _emphasis_
STRONG_2_RE = r'__([^_]*)__' # __strong__
STRONG_EM_2_RE = r'___([^_]*)___' # ___strong___
LINK_RE = NOIMG + BRK + r'\s*\(([^\)]*)\)' # [text](url)
LINK_ANGLED_RE = NOIMG + BRK + r'\s*\(<([^\)]*)>\)' # [text](<url>)
IMAGE_LINK_RE = r'\!' + BRK + r'\s*\(([^\)]*)\)' # 
REFERENCE_RE = NOIMG + BRK+ r'\s*\[([^\]]*)\]' # [Google][3]
IMAGE_REFERENCE_RE = r'\!' + BRK + '\s*\[([^\]]*)\]' # ![alt text][2]
NOT_STRONG_RE = r'( \* )' # stand-alone * or _
AUTOLINK_RE = r'<(http://[^>]*)>' # <http://www.123.com>
AUTOMAIL_RE = r'<([^> \!]*@[^> ]*)>' # <me@example.com>
#HTML_RE = r'(\<[^\>]*\>)' # <...>
HTML_RE = r'(\<[a-zA-Z/][^\>]*\>)' # <...>
ENTITY_RE = r'(&[\#a-zA-Z0-9]*;)' # &
LINE_BREAK_RE = r' \n' # two spaces at end of line
LINE_BREAK_2_RE = r' $' # two spaces at end of text
class Pattern:
def __init__ (self, pattern):
self.pattern = pattern
self.compiled_re = re.compile("^(.*)%s(.*)$" % pattern, re.DOTALL)
def getCompiledRegExp (self):
return self.compiled_re
BasePattern = Pattern # for backward compatibility
class SimpleTextPattern (Pattern):
def handleMatch(self, m, doc):
return doc.createTextNode(m.community(2))
class SimpleTagPattern (Pattern):
def __init__ (self, pattern, tag):
Pattern.__init__(self, pattern)
self.tag = tag
def handleMatch(self, m, doc):
el = doc.createElement(self.tag)
el.appendChild(doc.createTextNode(m.community(2)))
return el
class SubstituteTagPattern (SimpleTagPattern):
def handleMatch (self, m, doc):
return doc.createElement(self.tag)
class BacktickPattern (Pattern):
def __init__ (self, pattern):
Pattern.__init__(self, pattern)
self.tag = "code"
def handleMatch(self, m, doc):
el = doc.createElement(self.tag)
text = m.community(2).strip()
#text = text.replace("&", "&")
el.appendChild(doc.createTextNode(text))
return el
class DoubleTagPattern (SimpleTagPattern):
def handleMatch(self, m, doc):
tag1, tag2 = self.tag.split(",")
el1 = doc.createElement(tag1)
el2 = doc.createElement(tag2)
el1.appendChild(el2)
el2.appendChild(doc.createTextNode(m.community(2)))
return el1
class HtmlPattern (Pattern):
def handleMatch (self, m, doc):
rawhtml = m.community(2)
inline = True
place_holder = self.stash.store(rawhtml)
return doc.createTextNode(place_holder)
class LinkPattern (Pattern):
def handleMatch(self, m, doc):
el = doc.createElement('a')
el.appendChild(doc.createTextNode(m.community(2)))
parts = m.community(9).split('"')
# We should now have [], [href], or [href, title]
if parts:
el.setAttribute('href', parts[0].strip())
else:
el.setAttribute('href', "")
if len(parts) > 1:
# we also got a title
title = '"' + '"'.join(parts[1:]).strip()
title = dequote(title) #.replace('"', """)
el.setAttribute('title', title)
return el
class ImagePattern (Pattern):
def handleMatch(self, m, doc):
el = doc.createElement('img')
src_parts = m.community(9).split()
if src_parts:
el.setAttribute('src', src_parts[0])
else:
el.setAttribute('src', "")
if len(src_parts) > 1:
el.setAttribute('title', dequote(" ".join(src_parts[1:])))
if ENABLE_ATTRIBUTES:
text = doc.createTextNode(m.community(2))
el.appendChild(text)
text.handleAttributes()
truealt = text.value
el.childNodes.remove(text)
else:
truealt = m.community(2)
el.setAttribute('alt', truealt)
return el
class ReferencePattern (Pattern):
def handleMatch(self, m, doc):
if m.community(9):
id = m.community(9).lower()
else:
# if we got something like "[Google][]"
# we'll use "google" as the id
id = m.community(2).lower()
if not self.references.has_key(id): # ignore undefined refs
return None
href, title = self.references[id]
text = m.community(2)
return self.makeTag(href, title, text, doc)
def makeTag(self, href, title, text, doc):
el = doc.createElement('a')
el.setAttribute('href', href)
if title:
el.setAttribute('title', title)
el.appendChild(doc.createTextNode(text))
return el
class ImageReferencePattern (ReferencePattern):
def makeTag(self, href, title, text, doc):
el = doc.createElement('img')
el.setAttribute('src', href)
if title:
el.setAttribute('title', title)
el.setAttribute('alt', text)
return el
class AutolinkPattern (Pattern):
def handleMatch(self, m, doc):
el = doc.createElement('a')
el.setAttribute('href', m.community(2))
el.appendChild(doc.createTextNode(m.community(2)))
return el
class AutomailPattern (Pattern):
def handleMatch(self, m, doc):
el = doc.createElement('a')
email = m.community(2)
if email.startswith("mailto:"):
email = email[len("mailto:"):]
for letter in email:
entity = doc.createEntityReference("#%d" % ord(letter))
el.appendChild(entity)
mailto = "mailto:" + email
mailto = "".join(['&#%d;' % ord(letter) for letter in mailto])
el.setAttribute('href', mailto)
return el
ESCAPE_PATTERN = SimpleTextPattern(ESCAPE_RE)
NOT_STRONG_PATTERN = SimpleTextPattern(NOT_STRONG_RE)
BACKTICK_PATTERN = BacktickPattern(BACKTICK_RE)
DOUBLE_BACKTICK_PATTERN = BacktickPattern(DOUBLE_BACKTICK_RE)
STRONG_PATTERN = SimpleTagPattern(STRONG_RE, 'strong')
STRONG_PATTERN_2 = SimpleTagPattern(STRONG_2_RE, 'strong')
EMPHASIS_PATTERN = SimpleTagPattern(EMPHASIS_RE, 'em')
EMPHASIS_PATTERN_2 = SimpleTagPattern(EMPHASIS_2_RE, 'em')
STRONG_EM_PATTERN = DoubleTagPattern(STRONG_EM_RE, 'strong,em')
STRONG_EM_PATTERN_2 = DoubleTagPattern(STRONG_EM_2_RE, 'strong,em')
LINE_BREAK_PATTERN = SubstituteTagPattern(LINE_BREAK_RE, 'br ')
LINE_BREAK_PATTERN_2 = SubstituteTagPattern(LINE_BREAK_2_RE, 'br ')
LINK_PATTERN = LinkPattern(LINK_RE)
LINK_ANGLED_PATTERN = LinkPattern(LINK_ANGLED_RE)
IMAGE_LINK_PATTERN = ImagePattern(IMAGE_LINK_RE)
IMAGE_REFERENCE_PATTERN = ImageReferencePattern(IMAGE_REFERENCE_RE)
REFERENCE_PATTERN = ReferencePattern(REFERENCE_RE)
HTML_PATTERN = HtmlPattern(HTML_RE)
ENTITY_PATTERN = HtmlPattern(ENTITY_RE)
AUTOLINK_PATTERN = AutolinkPattern(AUTOLINK_RE)
AUTOMAIL_PATTERN = AutomailPattern(AUTOMAIL_RE)
"""
======================================================================
========================== POST-PROCESSORS ===========================
======================================================================
Markdown also allows post-processors, which are similar to
preprocessors in that they need to implement a "run" method. However,
they are run after core processing.
There are two types of post-processors: Postprocessor and TextPostprocessor
"""
class Postprocessor:
'''
Postprocessors are run before the dom it converted back into text.
Each Postprocessor implements a "run" method that takes a pointer to a
NanoDom document, modifies it as necessary and returns a NanoDom
document.
Postprocessors must extend markdown.Postprocessor.
There are currently no standard post-processors, but the footnote
extension uses one.
'''
def run(self, dom):
pass
class TextPostprocessor:
'''
TextPostprocessors are run after the dom it converted back into text.
Each TextPostprocessor implements a "run" method that takes a pointer to a
text string, modifies it as necessary and returns a text string.
TextPostprocessors must extend markdown.TextPostprocessor.
'''
def run(self, text):
pass
class RawHtmlTextPostprocessor(TextPostprocessor):
def __init__(self):
pass
def run(self, text):
for i in range(self.stash.html_counter):
html, safe = self.stash.rawHtmlBlocks[i]
if self.safeMode and not safe:
if str(self.safeMode).lower() == 'escape':
html = self.escape(html)
elif str(self.safeMode).lower() == 'remove':
html = ''
else:
html = HTML_REMOVED_TEXT
text = text.replace("<p>%s\n</p>" % (HTML_PLACEHOLDER % i),
html + "\n")
text = text.replace(HTML_PLACEHOLDER % i, html)
return text
def escape(self, html):
''' Basic html escaping '''
html = html.replace('&', '&')
html = html.replace('<', '<')
html = html.replace('>', '>')
return html.replace('"', '"')
RAWHTMLTEXTPOSTPROCESSOR = RawHtmlTextPostprocessor()
"""
======================================================================
========================== MISC AUXILIARY CLASSES ====================
======================================================================
"""
class HtmlStash:
"""This class is used for stashing HTML objects that we extract
in the beginning and replace with place-holders."""
def __init__ (self):
self.html_counter = 0 # for counting inline html segments
self.rawHtmlBlocks=[]
def store(self, html, safe=False):
"""Saves an HTML segment for later reinsertion. Returns a
placeholder string that needs to be inserted into the
document.
@param html: an html segment
@param safe: label an html segment as safe for safemode
@param inline: label a segmant as inline html
@returns : a placeholder string """
self.rawHtmlBlocks.append((html, safe))
placeholder = HTML_PLACEHOLDER % self.html_counter
self.html_counter += 1
return placeholder
class BlockGuru:
def _findHead(self, lines, fn, allowBlank=0):
"""Functional magic to help determine boundaries of indented
blocks.
@param lines: an array of strings
@param fn: a function that returns a substring of a string
if the string matches the necessary criteria
@param allowBlank: specifies whether it's ok to have blank
lines between matching functions
@returns: a list of post processes articles and the unused
remainder of the original list"""
articles = []
article = -1
i = 0 # to keep track of where we are
for line in lines:
if not line.strip() and not allowBlank:
return articles, lines[i:]
if not line.strip() and allowBlank:
# If we see a blank line, this _might_ be the end
i += 1
# Find the next non-blank line
for j in range(i, len(lines)):
if lines[j].strip():
next = lines[j]
break
else:
# There is no more text => this is the end
break
# Check if the next non-blank line is still a part of the list
part = fn(next)
if part:
articles.append("")
continue
else:
break # found end of the list
part = fn(line)
if part:
articles.append(part)
i += 1
continue
else:
return articles, lines[i:]
else:
i += 1
return articles, lines[i:]
def detabbed_fn(self, line):
""" An auxiliary method to be passed to _findHead """
m = RE.regExp['tabbed'].match(line)
if m:
return m.community(4)
else:
return None
def detectTabbed(self, lines):
return self._findHead(lines, self.detabbed_fn,
allowBlank = 1)
def print_error(string):
"""Print an error string to stderr"""
sys.stderr.write(string +'\n')
def dequote(string):
""" Removes quotes from around a string """
if ( ( string.startswith('"') and string.endswith('"'))
or (string.startswith("'") and string.endswith("'")) ):
return string[1:-1]
else:
return string
"""
======================================================================
========================== CORE MARKDOWN =============================
======================================================================
This stuff is ugly, so if you are thinking of extending the syntax,
see first if you can do it via pre-processors, post-processors,
inline patterns or a combination of the three.
"""
class CorePatterns:
"""This class is scheduled for removal as part of a refactoring
effort."""
patterns = {
'header': r'(#*)([^#]*)(#*)', # # A title
'reference-def': r'(\ ?\ ?\ ?)\[([^\]]*)\]:\s*([^ ]*)(.*)',
# [Google]: http://www.google.com/
'containsline': r'([-]*)$|^([=]*)', # -----, =====, etc.
'ol': r'[ ]{0,3}[\d]*\.\s+(.*)', # 1. text
'ul': r'[ ]{0,3}[*+-]\s+(.*)', # "* text"
'isline1': r'(\**)', # ***
'isline2': r'(\-*)', # ---
'isline3': r'(\_*)', # ___
'tabbed': r'((\t)|( ))(.*)', # an indented line
'quoted': r'> ?(.*)', # a quoted block ("> ...")
}
def __init__ (self):
self.regExp = {}
for key in self.patterns.keys():
self.regExp[key] = re.compile("^%s$" % self.patterns[key],
re.DOTALL)
self.regExp['containsline'] = re.compile(r'^([-]*)$|^([=]*)$', re.M)
RE = CorePatterns()
class Markdown:
""" Markdown formatter class for creating an html document from
Markdown text """
def __init__(self, source=None, # depreciated
extensions=[],
extension_configs=None,
safe_mode = False):
"""Creates a new Markdown instance.
@param source: The text in Markdown format. Depreciated!
@param extensions: A list if extensions.
@param extension-configs: Configuration setting for extensions.
@param safe_mode: Disallow raw html. """
self.source = source
if source is not None:
message(WARN, "The `source` arg of Markdown.__init__() is depreciated and will be removed in the future. Use `instance.convert(source)` instead.")
self.safeMode = safe_mode
self.blockGuru = BlockGuru()
self.registeredExtensions = []
self.stripTopLevelTags = 1
self.docType = ""
self.textPreprocessors = [HTML_BLOCK_PREPROCESSOR]
self.preprocessors = [HEADER_PREPROCESSOR,
LINE_PREPROCESSOR,
# A footnote preprocessor will
# get inserted here
REFERENCE_PREPROCESSOR]
self.postprocessors = [] # a footnote postprocessor will get
# inserted later
self.textPostprocessors = [# a footnote postprocessor will get
# inserted here
RAWHTMLTEXTPOSTPROCESSOR]
self.prePatterns = []
self.inlinePatterns = [DOUBLE_BACKTICK_PATTERN,
BACKTICK_PATTERN,
ESCAPE_PATTERN,
REFERENCE_PATTERN,
LINK_ANGLED_PATTERN,
LINK_PATTERN,
IMAGE_LINK_PATTERN,
IMAGE_REFERENCE_PATTERN,
AUTOLINK_PATTERN,
AUTOMAIL_PATTERN,
LINE_BREAK_PATTERN_2,
LINE_BREAK_PATTERN,
HTML_PATTERN,
ENTITY_PATTERN,
NOT_STRONG_PATTERN,
STRONG_EM_PATTERN,
STRONG_EM_PATTERN_2,
STRONG_PATTERN,
STRONG_PATTERN_2,
EMPHASIS_PATTERN,
EMPHASIS_PATTERN_2
# The order of the handlers matters!!!
]
self.registerExtensions(extensions = extensions,
configs = extension_configs)
self.reset()
def registerExtensions(self, extensions, configs):
if not configs:
configs = {}
for ext in extensions:
extension_module_name = "mdx_" + ext
try:
module = __import__(extension_module_name)
except:
message(CRITICAL,
"couldn't load extension %s (looking for %s module)"
% (ext, extension_module_name) )
else:
if configs.has_key(ext):
configs_for_ext = configs[ext]
else:
configs_for_ext = []
extension = module.makeExtension(configs_for_ext)
extension.extendMarkdown(self, globals())
def registerExtension(self, extension):
""" This gets called by the extension """
self.registeredExtensions.append(extension)
def reset(self):
"""Resets all state variables so that we can start
with a new text."""
self.references={}
self.htmlStash = HtmlStash()
HTML_BLOCK_PREPROCESSOR.stash = self.htmlStash
LINE_PREPROCESSOR.stash = self.htmlStash
REFERENCE_PREPROCESSOR.references = self.references
HTML_PATTERN.stash = self.htmlStash
ENTITY_PATTERN.stash = self.htmlStash
REFERENCE_PATTERN.references = self.references
IMAGE_REFERENCE_PATTERN.references = self.references
RAWHTMLTEXTPOSTPROCESSOR.stash = self.htmlStash
RAWHTMLTEXTPOSTPROCESSOR.safeMode = self.safeMode
for extension in self.registeredExtensions:
extension.reset()
def _transform(self):
"""Transforms the Markdown text into a XHTML body document
@returns: A NanoDom Document """
# Setup the document
self.doc = Document()
self.top_element = self.doc.createElement("span")
self.top_element.appendChild(self.doc.createTextNode('\n'))
self.top_element.setAttribute('class', 'markdown')
self.doc.appendChild(self.top_element)
# Fixup the source text
text = self.source
text = text.replace("\r\n", "\n").replace("\r", "\n")
text += "\n\n"
text = text.expandtabs(TAB_LENGTH)
# Split into lines and run the preprocessors that will work with
# self.lines
self.lines = text.split("\n")
# Run the pre-processors on the lines
for prep in self.preprocessors :
self.lines = prep.run(self.lines)
# Create a NanoDom tree from the lines and attach it to Document
buffer = []
for line in self.lines:
if line.startswith("#"):
self._processSection(self.top_element, buffer)
buffer = [line]
else:
buffer.append(line)
self._processSection(self.top_element, buffer)
#self._processSection(self.top_element, self.lines)
# Not sure why I put this in but let's leave it for now.
self.top_element.appendChild(self.doc.createTextNode('\n'))
# Run the post-processors
for postprocessor in self.postprocessors:
postprocessor.run(self.doc)
return self.doc
def _processSection(self, parent_elem, lines,
inList = 0, looseList = 0):
"""Process a section of a source document, looking for high
level structural elements like lists, block quotes, code
segments, html blocks, etc. Some those then get stripped
of their high level markup (e.g. get unindented) and the
lower-level markup is processed recursively.
@param parent_elem: A NanoDom element to which the content
will be added
@param lines: a list of lines
@param inList: a level
@returns: None"""
# Loop through lines until none left.
while lines:
# Check if this section starts with a list, a blockquote or
# a code block
processFn = { 'ul': self._processUList,
'ol': self._processOList,
'quoted': self._processQuote,
'tabbed': self._processCodeBlock}
for regexp in ['ul', 'ol', 'quoted', 'tabbed']:
m = RE.regExp[regexp].match(lines[0])
if m:
processFn[regexp](parent_elem, lines, inList)
return
# We are NOT looking at one of the high-level structures like
# lists or blockquotes. So, it's just a regular paragraph
# (though perhaps nested inside a list or something else). If
# we are NOT inside a list, we just need to look for a blank
# line to find the end of the block. If we ARE inside a
# list, however, we need to consider that a sublist does not
# need to be separated by a blank line. Rather, the following
# markup is legal:
#
# * The top level list article
#
# Another paragraph of the list. This is where we are now.
# * Underneath we might have a sublist.
#
if inList:
start, lines = self._linesUntil(lines, (lambda line:
RE.regExp['ul'].match(line)
or RE.regExp['ol'].match(line)
or not line.strip()))
self._processSection(parent_elem, start,
inList - 1, looseList = looseList)
inList = inList-1
else: # Ok, so it's just a simple block
paragraph, lines = self._linesUntil(lines, lambda line:
not line.strip())
if len(paragraph) and paragraph[0].startswith('#'):
self._processHeader(parent_elem, paragraph)
elif paragraph:
self._processParagraph(parent_elem, paragraph,
inList, looseList)
if lines and not lines[0].strip():
lines = lines[1:] # skip the first (blank) line
def _processHeader(self, parent_elem, paragraph):
m = RE.regExp['header'].match(paragraph[0])
if m:
level = len(m.community(1))
h = self.doc.createElement("h%d" % level)
parent_elem.appendChild(h)
for article in self._handleInline(m.community(2).strip()):
h.appendChild(article)
else:
message(CRITICAL, "We've got a problem header!")
def _processParagraph(self, parent_elem, paragraph, inList, looseList):
list = self._handleInline("\n".join(paragraph))
if ( parent_elem.nodeName == 'li'
and not (looseList or parent_elem.childNodes)):
# If this is the first paragraph inside "li", don't
# put <p> around it - append the paragraph bits directly
# onto parent_elem
el = parent_elem
else:
# Otherwise make a "p" element
el = self.doc.createElement("p")
parent_elem.appendChild(el)
for article in list:
el.appendChild(article)
def _processUList(self, parent_elem, lines, inList):
self._processList(parent_elem, lines, inList,
listexpr='ul', tag = 'ul')
def _processOList(self, parent_elem, lines, inList):
self._processList(parent_elem, lines, inList,
listexpr='ol', tag = 'ol')
def _processList(self, parent_elem, lines, inList, listexpr, tag):
"""Given a list of document lines starting with a list article,
finds the end of the list, breaks it up, and recursively
processes each list article and the remainder of the text file.
@param parent_elem: A dom element to which the content will be added
@param lines: a list of lines
@param inList: a level
@returns: None"""
ul = self.doc.createElement(tag) # ul might actually be '<ol>'
parent_elem.appendChild(ul)
looseList = 0
# Make a list of list articles
articles = []
article = -1
i = 0 # a counter to keep track of where we are
for line in lines:
loose = 0
if not line.strip():
# If we see a blank line, this _might_ be the end of the list
i += 1
loose = 1
# Find the next non-blank line
for j in range(i, len(lines)):
if lines[j].strip():
next = lines[j]
break
else:
# There is no more text => end of the list
break
# Check if the next non-blank line is still a part of the list
if ( RE.regExp['ul'].match(next) or
RE.regExp['ol'].match(next) or
RE.regExp['tabbed'].match(next) ):
# get rid of any white space in the line
articles[article].append(line.strip())
looseList = loose or looseList
continue
else:
break # found end of the list
# Now we need to detect list articles (at the current level)
# while also detabing child elements if necessary
for expr in ['ul', 'ol', 'tabbed']:
m = RE.regExp[expr].match(line)
if m:
if expr in ['ul', 'ol']: # We are looking at a new article
#if m.community(1) :
# Removed the check to allow for a blank line
# at the beginning of the list article
articles.append([m.community(1)])
article += 1
elif expr == 'tabbed': # This line needs to be detabbed
articles[article].append(m.community(4)) #after the 'tab'
i += 1
break
else:
articles[article].append(line) # Just regular continuation
i += 1 # added on 2006.02.25
else:
i += 1
# Add the dom elements
for article in articles:
li = self.doc.createElement("li")
ul.appendChild(li)
self._processSection(li, article, inList + 1, looseList = looseList)
# Process the remaining part of the section
self._processSection(parent_elem, lines[i:], inList)
def _linesUntil(self, lines, condition):
""" A utility function to break a list of lines upon the
first line that satisfied a condition. The condition
argument should be a predicate function.
"""
i = -1
for line in lines:
i += 1
if condition(line): break
else:
i += 1
return lines[:i], lines[i:]
def _processQuote(self, parent_elem, lines, inList):
"""Given a list of document lines starting with a quote finds
the end of the quote, unindents it and recursively
processes the body of the quote and the remainder of the
text file.
@param parent_elem: DOM element to which the content will be added
@param lines: a list of lines
@param inList: a level
@returns: None """
dequoted = []
i = 0
blank_line = False # allow one blank line between paragraphs
for line in lines:
m = RE.regExp['quoted'].match(line)
if m:
dequoted.append(m.community(1))
i += 1
blank_line = False
elif not blank_line and line.strip() != '':
dequoted.append(line)
i += 1
elif not blank_line and line.strip() == '':
dequoted.append(line)
i += 1
blank_line = True
else:
break
blockquote = self.doc.createElement('blockquote')
parent_elem.appendChild(blockquote)
self._processSection(blockquote, dequoted, inList)
self._processSection(parent_elem, lines[i:], inList)
def _processCodeBlock(self, parent_elem, lines, inList):
"""Given a list of document lines starting with a code block
finds the end of the block, puts it into the dom verbatim
wrapped in ("<pre><code>") and recursively processes the
the remainder of the text file.
@param parent_elem: DOM element to which the content will be added
@param lines: a list of lines
@param inList: a level
@returns: None"""
detabbed, theRest = self.blockGuru.detectTabbed(lines)
pre = self.doc.createElement('pre')
code = self.doc.createElement('code')
parent_elem.appendChild(pre)
pre.appendChild(code)
text = "\n".join(detabbed).rstrip()+"\n"
#text = text.replace("&", "&")
code.appendChild(self.doc.createTextNode(text))
self._processSection(parent_elem, theRest, inList)
def _handleInline (self, line, patternIndex=0):
"""Transform a Markdown line with inline elements to an XHTML
fragment.
This function uses auxiliary objects called inline patterns.
See notes on inline patterns above.
@param line: A line of Markdown text
@param patternIndex: The index of the inlinePattern to start with
@return: A list of NanoDom nodes """
parts = [line]
while patternIndex < len(self.inlinePatterns):
i = 0
while i < len(parts):
x = parts[i]
if isinstance(x, (str, unicode)):
result = self._applyPattern(x, \
self.inlinePatterns[patternIndex], \
patternIndex)
if result:
i -= 1
parts.remove(x)
for y in result:
parts.insert(i+1,y)
i += 1
patternIndex += 1
for i in range(len(parts)):
x = parts[i]
if isinstance(x, (str, unicode)):
parts[i] = self.doc.createTextNode(x)
return parts
def _applyPattern(self, line, pattern, patternIndex):
""" Given a pattern name, this function checks if the line
fits the pattern, creates the necessary elements, and returns
back a list consisting of NanoDom elements and/or strings.
@param line: the text to be processed
@param pattern: the pattern to be checked
@returns: the appropriate newly created NanoDom element if the
pattern matches, None otherwise.
"""
# match the line to pattern's pre-compiled reg exp.
# if no match, move on.
m = pattern.getCompiledRegExp().match(line)
if not m:
return None
# if we got a match let the pattern make us a NanoDom node
# if it doesn't, move on
node = pattern.handleMatch(m, self.doc)
# check if any of this nodes have children that need processing
if isinstance(node, Element):
if not node.nodeName in ["code", "pre"]:
for child in node.childNodes:
if isinstance(child, TextNode):
result = self._handleInline(child.value, patternIndex+1)
if result:
if result == [child]:
continue
result.reverse()
#to make insertion easier
position = node.childNodes.index(child)
node.removeChild(child)
for article in result:
if isinstance(article, (str, unicode)):
if len(article) > 0:
node.insertChild(position,
self.doc.createTextNode(article))
else:
node.insertChild(position, article)
if node:
# Those are in the reverse order!
return ( m.communities()[-1], # the string to the left
node, # the new node
m.community(1)) # the string to the right of the match
else:
return None
def convert (self, source = None):
"""Return the document in XHTML format.
@returns: A serialized XHTML body."""
if source is not None: #Allow blank string
self.source = source
if not self.source:
return u""
try:
self.source = unicode(self.source)
except UnicodeDecodeError:
message(CRITICAL, 'UnicodeDecodeError: Markdown only accepts unicode or ascii input.')
return u""
for pp in self.textPreprocessors:
self.source = pp.run(self.source)
doc = self._transform()
xml = doc.toxml()
# Return everything but the top level tag
if self.stripTopLevelTags:
xml = xml.strip()[23:-7] + "\n"
for pp in self.textPostprocessors:
xml = pp.run(xml)
return (self.docType + xml).strip()
def __str__(self):
''' Report info about instance. Markdown always returns unicode. '''
if self.source is None:
status = 'in which no source text has been assinged.'
else:
status = 'which contains %d chars and %d line(s) of source.'%\
(len(self.source), self.source.count('\n')+1)
return 'An instance of "%s" %s'% (self.__class__, status)
__unicode__ = convert # markdown should always return a unicode string
# ====================================================================
def markdownFromFile(input = None,
output = None,
extensions = [],
encoding = None,
message_threshold = CRITICAL,
safe = False):
global console_hndlr
console_hndlr.setLevel(message_threshold)
message(DEBUG, "input file: %s" % input)
if not encoding:
encoding = "utf-8"
input_file = codecs.open(input, mode="r", encoding=encoding)
text = input_file.read()
input_file.close()
text = removeBOM(text, encoding)
new_text = markdown(text, extensions, safe_mode = safe)
if output:
output_file = codecs.open(output, "w", encoding=encoding)
output_file.write(new_text)
output_file.close()
else:
sys.stdout.write(new_text.encode(encoding))
def markdown(text,
extensions = [],
safe_mode = False):
message(DEBUG, "in markdown.markdown(), received text:\n%s" % text)
extension_names = []
extension_configs = {}
for ext in extensions:
pos = ext.find("(")
if pos == -1:
extension_names.append(ext)
else:
name = ext[:pos]
extension_names.append(name)
pairs = [x.split("=") for x in ext[pos+1:-1].split(",")]
configs = [(x.strip(), y.strip()) for (x, y) in pairs]
extension_configs[name] = configs
md = Markdown(extensions=extension_names,
extension_configs=extension_configs,
safe_mode = safe_mode)
return md.convert(text)
class Extension:
def __init__(self, configs = {}):
self.config = configs
def getConfig(self, key):
if self.config.has_key(key):
return self.config[key][0]
else:
return ""
def getConfigInfo(self):
return [(key, self.config[key][1]) for key in self.config.keys()]
def setConfig(self, key, value):
self.config[key][0] = value
OPTPARSE_WARNING = """
Python 2.3 or higher required for advanced command line options.
For lower versions of Python use:
%s INPUT_FILE > OUTPUT_FILE
""" % EXECUTABLE_NAME_FOR_USAGE
def parse_options():
try:
optparse = __import__("optparse")
except:
if len(sys.argv) == 2:
return {'input': sys.argv[1],
'output': None,
'message_threshold': CRITICAL,
'safe': False,
'extensions': [],
'encoding': None }
else:
print OPTPARSE_WARNING
return None
parser = optparse.OptionParser(usage="%prog INPUTFILE [options]")
parser.add_option("-f", "--file", dest="filename",
help="write output to OUTPUT_FILE",
metavar="OUTPUT_FILE")
parser.add_option("-e", "--encoding", dest="encoding",
help="encoding for input and output files",)
parser.add_option("-q", "--quiet", default = CRITICAL,
action="store_const", const=60, dest="verbose",
help="suppress all messages")
parser.add_option("-v", "--verbose",
action="store_const", const=INFO, dest="verbose",
help="print info messages")
parser.add_option("-s", "--safe", dest="safe", default=False,
metavar="SAFE_MODE",
help="same mode ('replace', 'remove' or 'escape' user's HTML tag)")
parser.add_option("--noisy",
action="store_const", const=DEBUG, dest="verbose",
help="print debug messages")
parser.add_option("-x", "--extension", action="append", dest="extensions",
help = "load extension EXTENSION", metavar="EXTENSION")
(options, args) = parser.parse_args()
if not len(args) == 1:
parser.print_help()
return None
else:
input_file = args[0]
if not options.extensions:
options.extensions = []
return {'input': input_file,
'output': options.filename,
'message_threshold': options.verbose,
'safe': options.safe,
'extensions': options.extensions,
'encoding': options.encoding }
if __name__ == '__main__':
""" Run Markdown from the command line. """
options = parse_options()
#if os.access(inFile, os.R_OK):
if not options:
sys.exit(0)
markdownFromFile(**options)
| Python |
# setup.py build bdist_wininst
from distutils.core import setup, Extension
# get src root info
import os
p = '/'.join(os.path.abspath('.').split(os.path.sep))
p = p[:p.rfind('/wrapper/python')]
# extract version info from dicom.i
v = [l for l in file('dicom.i').readlines() if 'DICOMSDL_VER' in l]
# compiler's option
extra_compile_args = []
if os.name == "nt":
extra_compile_args += ["/EHsc"]
ext = Extension(
"_dicom",
sources=["dicom.i"],
swig_opts=['-c++', '-I%s/lib'%(p)],
include_dirs=['%s/lib'%(p)],
library_dirs=[p],
libraries=['dicomsdl'],
extra_compile_args = extra_compile_args,
language='c++'
)
setup(
name='dicomsdl',
version=v[0].split()[-1] if v else 'UNKNOWN',
description='DICOM Software Development Library',
author='Kim, Tae-Sung',
author_email='taesung.angel@gmail.com',
url='http://code.google.com/p/dicomsdl/',
py_modules=['dicom'],
ext_modules=[ext]
)
| Python |
# GET DICOMSDL VERSION
import re
version = 'UNKNOWN'
for l in file('../../CMakeLists.txt').readlines():
version = re.findall(r'\(dicomsdl_version (\S+)\)', l)
if version:
version = version[0].strip()
break
release = version
print >>file('Doxyfile', 'w'), r'''
DOXYFILE_ENCODING = UTF-8
PROJECT_NAME = DICOMSDL
PROJECT_NUMBER = {0}
PROJECT_BRIEF = DICOM Software Development Library
PROJECT_LOGO =
OUTPUT_DIRECTORY =
CREATE_SUBDIRS = NO
OUTPUT_LANGUAGE = English
BRIEF_MEMBER_DESC = YES
REPEAT_BRIEF = YES
ABBREVIATE_BRIEF =
ALWAYS_DETAILED_SEC = NO
INLINE_INHERITED_MEMB = NO
FULL_PATH_NAMES = YES
STRIP_FROM_PATH =
STRIP_FROM_INC_PATH =
SHORT_NAMES = NO
JAVADOC_AUTOBRIEF = NO
QT_AUTOBRIEF = NO
MULTILINE_CPP_IS_BRIEF = NO
INHERIT_DOCS = YES
SEPARATE_MEMBER_PAGES = NO
TAB_SIZE = 8
ALIASES =
OPTIMIZE_OUTPUT_FOR_C = NO
OPTIMIZE_OUTPUT_JAVA = NO
OPTIMIZE_FOR_FORTRAN = NO
OPTIMIZE_OUTPUT_VHDL = NO
EXTENSION_MAPPING =
BUILTIN_STL_SUPPORT = NO
CPP_CLI_SUPPORT = NO
SIP_SUPPORT = NO
IDL_PROPERTY_SUPPORT = YES
DISTRIBUTE_GROUP_DOC = NO
SUBGROUPING = YES
TYPEDEF_HIDES_STRUCT = NO
SYMBOL_CACHE_SIZE = 0
EXTRACT_ALL = YES
EXTRACT_PRIVATE = NO
EXTRACT_STATIC = NO
EXTRACT_LOCAL_CLASSES = NO
EXTRACT_LOCAL_METHODS = NO
EXTRACT_ANON_NSPACES = NO
HIDE_UNDOC_MEMBERS = YES
HIDE_UNDOC_CLASSES = YES
HIDE_FRIEND_COMPOUNDS = YES
HIDE_IN_BODY_DOCS = YES
INTERNAL_DOCS = NO
CASE_SENSE_NAMES = NO
HIDE_SCOPE_NAMES = NO
SHOW_INCLUDE_FILES = YES
FORCE_LOCAL_INCLUDES = NO
INLINE_INFO = YES
SORT_MEMBER_DOCS = YES
SORT_BRIEF_DOCS = NO
SORT_MEMBERS_CTORS_1ST = NO
SORT_GROUP_NAMES = NO
SORT_BY_SCOPE_NAME = NO
STRICT_PROTO_MATCHING = NO
GENERATE_TODOLIST = YES
GENERATE_TESTLIST = YES
GENERATE_BUGLIST = YES
GENERATE_DEPRECATEDLIST= YES
ENABLED_SECTIONS =
MAX_INITIALIZER_LINES = 30
SHOW_USED_FILES = YES
SHOW_DIRECTORIES = NO
SHOW_FILES = YES
SHOW_NAMESPACES = YES
FILE_VERSION_FILTER =
LAYOUT_FILE =
QUIET = NO
WARNINGS = YES
WARN_IF_UNDOCUMENTED = YES
WARN_IF_DOC_ERROR = YES
WARN_NO_PARAMDOC = NO
WARN_FORMAT = "$file:$line: $text"
WARN_LOGFILE =
INPUT = . ../lib
INPUT_ENCODING = UTF-8
FILE_PATTERNS = *.doc dicom.h
RECURSIVE = NO
EXCLUDE =
EXCLUDE_SYMLINKS = NO
EXCLUDE_PATTERNS =
EXCLUDE_SYMBOLS =
EXAMPLE_PATH =
EXAMPLE_PATTERNS =
EXAMPLE_RECURSIVE = NO
IMAGE_PATH =
INPUT_FILTER =
FILTER_PATTERNS =
FILTER_SOURCE_FILES = NO
FILTER_SOURCE_PATTERNS =
SOURCE_BROWSER = NO
INLINE_SOURCES = NO
STRIP_CODE_COMMENTS = YES
REFERENCED_BY_RELATION = NO
REFERENCES_RELATION = NO
REFERENCES_LINK_SOURCE = YES
USE_HTAGS = NO
VERBATIM_HEADERS = YES
ALPHABETICAL_INDEX = YES
COLS_IN_ALPHA_INDEX = 5
IGNORE_PREFIX =
GENERATE_HTML = YES
HTML_OUTPUT = html
HTML_FILE_EXTENSION = .html
HTML_HEADER =
HTML_FOOTER =
HTML_STYLESHEET =
HTML_COLORSTYLE_HUE = 220
HTML_COLORSTYLE_SAT = 100
HTML_COLORSTYLE_GAMMA = 80
HTML_TIMESTAMP = YES
HTML_ALIGN_MEMBERS = YES
HTML_DYNAMIC_SECTIONS = NO
GENERATE_DOCSET = NO
DOCSET_FEEDNAME = "Doxygen generated docs"
DOCSET_BUNDLE_ID = org.doxygen.Project
DOCSET_PUBLISHER_ID = org.doxygen.Publisher
DOCSET_PUBLISHER_NAME = Publisher
GENERATE_HTMLHELP = YES
CHM_FILE = dicomsdl-{0}-doc.chm
HHC_LOCATION =
GENERATE_CHI = NO
CHM_INDEX_ENCODING =
BINARY_TOC = NO
TOC_EXPAND = NO
GENERATE_QHP = NO
QCH_FILE =
QHP_NAMESPACE = org.doxygen.Project
QHP_VIRTUAL_FOLDER = doc
QHP_CUST_FILTER_NAME =
QHP_CUST_FILTER_ATTRS =
QHP_SECT_FILTER_ATTRS =
QHG_LOCATION =
GENERATE_ECLIPSEHELP = NO
ECLIPSE_DOC_ID = org.doxygen.Project
DISABLE_INDEX = NO
ENUM_VALUES_PER_LINE = 4
GENERATE_TREEVIEW = NO
USE_INLINE_TREES = NO
TREEVIEW_WIDTH = 250
EXT_LINKS_IN_WINDOW = NO
FORMULA_FONTSIZE = 10
FORMULA_TRANSPARENT = YES
USE_MATHJAX = NO
MATHJAX_RELPATH = http://www.mathjax.org/mathjax
SEARCHENGINE = YES
SERVER_BASED_SEARCH = NO
GENERATE_LATEX = YES
LATEX_OUTPUT = latex
LATEX_CMD_NAME = latex
MAKEINDEX_CMD_NAME = makeindex
COMPACT_LATEX = NO
PAPER_TYPE = a4
EXTRA_PACKAGES =
LATEX_HEADER =
PDF_HYPERLINKS = YES
USE_PDFLATEX = YES
LATEX_BATCHMODE = NO
LATEX_HIDE_INDICES = NO
LATEX_SOURCE_CODE = YES
GENERATE_RTF = NO
RTF_OUTPUT = rtf
COMPACT_RTF = NO
RTF_HYPERLINKS = NO
RTF_STYLESHEET_FILE =
RTF_EXTENSIONS_FILE =
GENERATE_MAN = NO
MAN_OUTPUT = man
MAN_EXTENSION = .3
MAN_LINKS = NO
GENERATE_XML = NO
XML_OUTPUT = xml
XML_SCHEMA =
XML_DTD =
XML_PROGRAMLISTING = YES
GENERATE_AUTOGEN_DEF = NO
GENERATE_PERLMOD = NO
PERLMOD_LATEX = NO
PERLMOD_PRETTY = YES
PERLMOD_MAKEVAR_PREFIX =
ENABLE_PREPROCESSING = YES
MACRO_EXPANSION = NO
EXPAND_ONLY_PREDEF = NO
SEARCH_INCLUDES = YES
INCLUDE_PATH =
INCLUDE_FILE_PATTERNS =
PREDEFINED =
EXPAND_AS_DEFINED =
SKIP_FUNCTION_MACROS = YES
TAGFILES =
GENERATE_TAGFILE =
ALLEXTERNALS = NO
EXTERNAL_GROUPS = YES
PERL_PATH = /usr/bin/perl
CLASS_DIAGRAMS = YES
MSCGEN_PATH =
HIDE_UNDOC_RELATIONS = YES
HAVE_DOT = NO
DOT_NUM_THREADS = 0
DOT_FONTNAME = Helvetica
DOT_FONTSIZE = 10
DOT_FONTPATH =
CLASS_GRAPH = YES
COLLABORATION_GRAPH = YES
GROUP_GRAPHS = YES
UML_LOOK = NO
TEMPLATE_RELATIONS = NO
INCLUDE_GRAPH = YES
INCLUDED_BY_GRAPH = YES
CALL_GRAPH = NO
CALLER_GRAPH = NO
GRAPHICAL_HIERARCHY = YES
DIRECTORY_GRAPH = YES
DOT_IMAGE_FORMAT = png
DOT_PATH =
DOTFILE_DIRS =
MSCFILE_DIRS =
DOT_GRAPH_MAX_NODES = 50
MAX_DOT_GRAPH_DEPTH = 0
DOT_TRANSPARENT = NO
DOT_MULTI_TARGETS = NO
GENERATE_LEGEND = YES
DOT_CLEANUP = YES
'''.format(release) | Python |
import re, csv
#
#
# Annex E Command Dictionary ---------------------------------------------
#
#
chunku = []
commands = r'''0001H C-STORE-RQ
8001H C-STORE-RSP
0010H C-GET-RQ
8010H C-GET-RSP
0020H C-FIND-RQ
8020H C-FIND-RSP
0021H C-MOVE-RQ
8021H C-MOVE-RSP
0030H C-ECHO-RQ
8030H C-ECHO-RSP
0100H N-EVENT-REPORT-RQ
8100H N-EVENT-REPORT-RSP
0110H N-GET-RQ
8110H N-GET-RSP
0120H N-SET-RQ
8120H N-SET-RSP
0130H N-ACTION-RQ
8130H N-ACTION-RSP
0140H N-CREATE-RQ
8140H N-CREATE-RSP
0150H N-DELETE-RQ
8150H N-DELETE-RSP
0FFFH C-CANCEL-RQ'''
chunku.append('''/* -----------------------------------------------------------------------
*
* Converted from Part 7: Message Exchange (2009)
* Annex E Command Dictionary, E.1 REGISTRY OF DICOM COMMAND ELEMENTS
*
*/
typedef enum {''')
for line in commands.splitlines():
cmdval, cmdname = line.split()
cmdname = cmdname.replace('-', '_')
cmdval = '0x'+cmdval[:4]
chunku.append('\t%s \t= %s,'%(cmdname, cmdval))
chunku.append('} commandtype;\n\n')
#
#
# uid registry -----------------------------------------------------------
#
#
# build uid list -------------------------------
uidlist = []
for r in [r[:4] for r in csv.reader(open('uid.csv'))]:
uid_value, uid_name, uid_type, uid_part = r
uid_value = uid_value.strip()
uid_name = uid_name.strip()
uid_type = uid_type.strip()
uid_part = uid_part.strip()
uid = uid_name.upper().replace(' & ', 'AND')
uid = re.sub('['+re.escape(',-@/()')+']', ' ', uid)
uid = uid.split(':')[0]
uid = uid.split('[')[0]
uid = '_'.join(uid.split())
uid = 'UID_'+uid
if 'RETIRED' in uid: uid = None
uid_type = uid_type.strip()
if uid_type == 'Transfer': uid_type = 'Transfer Syntax'
if uid_type not in ['Application Context Name',
'Coding Scheme',
'DICOM UIDs as a Coding Scheme',
'Meta SOP Class',
'Query/Retrieve',
'SOP Class',
'Service Class',
'Transfer Syntax',
'']:
uid = None
uidlist.append([uid_value, uid, uid_name, uid_type, uid_part])
uidlist.append(['', 'UID_UNKNOWN', '', '', ''])
for u in uidlist:
if u[3] == '': u[3] = '00'+u[3]
if u[3] == 'Transfer Syntax': u[3] = '01'+u[3]
if u[3] == 'SOP Class': u[3] = '02'+u[3]
if u[3] == 'Meta SOP Class': u[3] = '03'+u[3]
if u[3] == 'Query/Retrieve': u[3] = '04'+u[3]
uidlist.sort(key=lambda x: x[3])
# write to 'dicomdict.hxx' -------------------------------
chunku.append('''/* -----------------------------------------------------------------------
*
* Converted from DICOM Part 6: Data Dictionary (2009)
*
* Python codelet that converts uid name into 'uid variable name'.
*
uid = uid_name.upper().replace(' & ', 'AND')
uid = re.sub('['+re.escape(',-@/()')+']', ' ', uid)
uid = uid.split(':')[0]
uid = uid.split('[')[0]
uid = '_'.join(uid.split())
uid = 'UID_'+uid
if 'RETIRED' in uid: uid = None
*/
typedef enum {
\tUID_UNKNOWN = 0,''')
uid_a = []
for u in uidlist:
if u[1]:
uid_a.append(u[1])
if u[1] != 'UID_UNKNOWN':
chunku.append('\t%s,'%(u[1]))
chunku[-1] = chunku[-1][:-1]
chunku.append('} uidtype;')
# dump!!
file('dicomdict.hxx', 'wb').write('\n'.join(chunku))
# -------------------------------
chunku = []
chunku.append('''static const struct _uid_registry_struct_ uid_registry[] =
{''')
uid_b = []
uidlist.sort()
for u in uidlist:
if u[3].startswith('0'): u[3] = u[3][2:]
chunku.append('\t{\t"%s",\n\t\t%s,'%(u[0], u[1] if u[1] else 'UID_UNKNOWN'))
chunku.append('\t\t"%s", "%s", "%s"},'%(u[2], u[3], u[4]))
uid_b.append(u[1])
chunku[-1] = chunku[-1][:-1]
chunku.append('''};
static const char *uidvalue_registry[] = {''')
for u in uid_a:
chunku.append('\tuid_registry[{0}].uidvalue,'
'\tuid_registry[{0}].uid_name,'.format(uid_b.index(u)))
chunku[-1] = chunku[-1][:-1]
chunku.append('''};''')
#
#
# data element registry --------------------------------------------------
#
#
chunke = []
chunke.append(r'''/* -----------------------------------------------------------------------
*
* Converted from DICOM Part 6: Data Dictionary (2009)
* and DICOM Part 7: Message Exchange (2009)
*
*/
static const struct _element_registry_struct_ element_registry[] =
{''')
keyword2tag = []
for r in [r[:6] for r in csv.reader(open('elements.csv'))]:
tagstr, name, keyword, vrstr, vm, retire = r
tagstr = tagstr.strip()
name = name.strip()
keyword = keyword.strip()
vrstr = vrstr.strip()
vm = vm.strip()
retire = retire.strip()
tag = tagstr.replace('x', '0').strip()
tag = '0x'+''.join(tag[1:-1].split(','))
if vrstr:
vr = vrstr.split()[0]
else:
vr = 'NULL'
if keyword:
keyword2tag.append([keyword, tag])
chunke.append(
'\t{%s, "%s", "%s", "%s", VR_%s, "%s", "%s", %d},'%
(tag, tagstr, name, keyword, vr, vrstr, vm, retire=="RET") )
chunke[-1] = chunke[-1][:-1]
chunke.append('''};
static const struct _element_keyword_struct_ element_keyword[] =
{''')
keyword2tag.sort()
for r in keyword2tag:
chunke.append('\t{%s, "%s"},'%(r[1], r[0]))
chunke[-1] = chunke[-1][:-1]
chunke.append('};');
# dump!!
file('dicomdict.inc.cxx', 'wb').write('\n'.join(chunke+chunku))
| Python |
#-*- coding: MS949 -*-
'''
Copyright 2010, Kim, Tae-Sung. All rights reserved.
See copyright.txt for details
'''
__author__ = 'Kim Tae-Sung'
__id__ = '$Id$'
import sys
import glob
import dicom
def extractimage():
pass
#def extractimage(filename, outputfilename):
# dcmfile = dicom.file(filename)
# imgelement = dcmfile.elementAt('0x7fe00010')
# if not imgelement.isvalid():
# imgelement = dcmfile.elementAt('00540410.0.7fe00010')
# if not imgelement.isvalid():
# print "NO IMAGE DATA IS FOUND "\
# "- I.E. NO ELEMENT WITH 0x7FE00010 or 00540410.0.7FE00010 TAG"
# return
#
# if imgelement.vr == dicom.VR_PX:
# img = imgelement.asImageSequence().itemAt(1)
# else:
# img = imgelement.asString()
#
# fout = file(outputfilename, 'wb')
# fout.write(img)
# fout.close()
#
# print "WRITE IMAGE ELEMENT VALUE IN (%s) TO (%s)"\
# %(filename,outputfilename)
def extract_image(fn, dfo):
imgelement = dfo.get_dataelement(0x7fe00010)
if not imgelement.is_valid():
imgelement = dfo.get_dataelement('00540410.0.7fe00010')
if not imgelement.is_valid():
print fn+" : NO IMAGE DATA ELEMENT IS FOUND; "\
"I.E. NO ELEMENT WITH 0x7FE00010 OR 00540410.0.7FE00010 TAG"
return
if imgelement.vr == 'PX':
print 'PXXXXXXXXXXXXXXXX'
pass
else:
pass
def processfile_3(fn, opt):
dfo = dicom.open_dicomfile(fn, dicom.OPT_LOAD_CONTINUE_ON_ERROR)
if opt['opt_ignore']:
if dfo and not dicom.get_error_message():
print dfo.dump_string(fn+' : ').rstrip()
else:
if dfo:
if not opt['opt_quite']:
print dfo.dump_string(fn+' : ').rstrip()
errmsg = dicom.get_error_message()
if errmsg:
print fn+' : ** ERROR IN LOADING A DICOM FILE; '+errmsg
else:
print fn+' : ** NOT A DICOM FILE'
if dfo and opt['opt_extract']:
extract_image(fn, dfo)
def processfile_2(fn, opt):
# expand filenames in zipped file
if fn.endswith('zip'): # .dicomzip or .zip
s = dicom.zipfile_get_list(fn)
if s:
for zfn in s.splitlines():
processfile_3('zip:///'+fn+':'+zfn, opt)
else:
processfile_3(fn, opt)
def processfile_1(fn, opt):
# expand filenames containing wild card
if '*' in fn or '?' in fn:
for f in glob.glob(fn):
processfile_2(f, opt)
else:
processfile_2(fn, opt)
if len(sys.argv) == 1:
print 'USAGE: %s [dicomfile.dcm or zipped dicomfile.zip] [-q] [-e] [-w]'%(sys.argv[0])
print ' -i - ignore damaged files and non-DICOM formatted files'
print ' -e - extract image data in dicom file into [filename+.raw].'
print ' -q - don\'t display dump.'
else:
opt = {}
opt['opt_ignore'] = True if '-i' in sys.argv else False
if opt['opt_ignore']: sys.argv.remove('-i')
opt['opt_extract'] = True if '-e' in sys.argv else False
if opt['opt_extract']: sys.argv.remove('-e')
opt['opt_quite'] = True if '-q' in sys.argv else False
if opt['opt_quite']: sys.argv.remove('-q')
for f in sys.argv[1:]:
processfile_1(f, opt)
# for fn in fnlist:
# if ':::' in fn:
# zipfn, entry = fn.split(':::')[:2]
# zf = zipfile.ZipFile(zipfn)
# dcmstr = zf.read(entry)
# zf.close()
# try:
# dcm = dicom.file(len(dcmstr), dcmstr)
# except RuntimeError, e:
# print 'ERROR IN {0}: {1}'.format(fn, e)
# continue
# else:
# try:
# dcm = dicom.file(fn)
# except RuntimeError, e:
# print 'ERROR IN {0}: {1}'.format(fn, e)
# continue
#
# if not opt_quite:
# if opt_multifile:
# dummy, _fn = os.path.split(fn)
# for l in dcm.dump().splitlines():
# print _fn, ':', l
# else:
# print dcm.dump()
# if opt_extract:
# extractimage(fn, fn+'.raw')
#
| Python |
import dicom
def ex_dicom_to_pil(fn):
dfo = dicom.dicomfile(fn)
im = dfo.to_pil_image()
im.show()
def ex_dicom_to_numpy(fn):
dfo = dicom.dicomfile(fn)
a = dfo.to_numpy_array()
| Python |
'''
/* -----------------------------------------------------------------------
*
* $Id$
*
* Copyright 2010, Kim, Tae-Sung. All rights reserved.
* See copyright.txt for details
*
* -------------------------------------------------------------------- */
'''
import sys
import dicom
def example_01_longform(df):
print "Example 01 Long Form"
# Get a data element that holds study date (0008,0020).
de = df.get_dataelement(0x00080020)
# check existence of the data element.
if de.is_valid():
# retrieve value
value = de.to_string();
else:
# set value for 'non-exist' data element.
value = "N/A"
print " Value of 0x00080020 = '{0}'".format(value)
def example_01_shortform(df):
print "Example 01 Short Form"
# to_string() will return "N/A" string if get_dataelement() returns
# 'invalid' or 'non-exist' dataelement.
value = df.get_dataelement(0x00080020).to_string("N/A")
print " Value of 0x00080020 = '{0}'".format(value)
# get value 'non-exist' dataelement without default value
value = df.get_dataelement(0x0008FFFF).to_string();
print " Value of 0x00080020 = '{0}'".format(value)
# get value 'non-exist' dataelement with default value
value = df.get_dataelement(0x0008FFFF).to_string("N/A");
print " Value of 0x00080020 = '{0}'".format(value)
# get a value in 'int' form
def example_02_get_int(df):
print "Example 02 Get Integer Values"
number_of_slices = df.get_dataelement(0x00540081).to_int(0)
print " Int Value of (0054,0081) = {0}".format(number_of_slices)
# another equivalent form
number_of_slices = df.get_dataelement(0x00540081).get_value(0)
print " Int Value of (0054,0081) = {0}".format(number_of_slices)
# yet another equivalent form
number_of_slices = df[0x00540081]
print " Int Value of (0054,0081) = {0}".format(number_of_slices)
# get a value in 'double' form
def example_03_get_double(df):
print "Example 03 Get Double Values"
slice_thickeness = df.get_dataelement(0x00180050).to_double(0.0)
# or
slice_thickeness = df.get_dataelement(0x00180050).get_value()
# or
slice_thickeness = df.get_dataelement(0x00180050).get_value(0.0)
# or
slice_thickeness = df[0x00180050]
print " Double Value of (0018,0050) = {0}".format(slice_thickeness)
# get multiple 'double' values
def example_04_get_double_values(df):
print "Example 04 Get Double Values"
image_position = df.get_dataelement("ImagePositionPatient").to_double_values()
# or
image_position = df.get_dataelement("ImagePositionPatient").get_value()
# or
image_position = df["ImagePositionPatient"]
print " Image Patient Position", image_position
# get string value
def example_05_get_string(df):
print "Example 05 Get String Values"
patient_name = df.get_dataelement("PatientName").to_string("N/A")
# or
patient_name = df.get_dataelement("PatientName").get_value("N/A")
print " Patient name = {0}".format(patient_name)
patient_name = df.get_dataelement("PatientName").to_string()
# or
patient_name = df.get_dataelement("PatientName").get_value()
# or
patient_name = df["PatientName"]
if patient_name:
print " Patient name = {0}".format(patient_name)
else:
print " Patient name is not available"
# get binary dat
def example_06_get_binary_data(df):
print "Example 06 Get Binary Data"
pixeldata = df.get_dataelement(0x7fe00010).raw_value()
if pixeldata:
print " Length of pixel data is {0} bytes.".format(len(pixeldata))
else:
print " Pixel data is not available.\n"
if __name__=="__main__":
df = dicom.open_dicomfile("img001.dcm")
if not df:
print dicom.get_error_message()
sys.exit(-1)
example_01_longform(df)
example_01_shortform(df)
example_02_get_int(df)
example_03_get_double(df)
example_04_get_double_values(df)
example_05_get_string(df)
example_06_get_binary_data(df)
del df # if you need to destroy dicomfile object explicitly
| Python |
import dicom
#zipfn = r'E:\StorageA\Program.Free\zip\zip30.zip'
#fnlist = dicom.zipfile_get_list(zipfn).split()
#print '-'*80
#print fnlist[4]
#print '-'*80
#print dicom.zipfile_extract_file(zipfn, fnlist[4])
dr = dicom.dicomdir()
import os
basepath = r'\lab\img\images\PET'
basepath = r'\lab\sample'
basepath = os.path.abspath(basepath)
for root, dns, fns in os.walk(basepath):
for fn in fns:
dr.add_dicomfile(root+'\\'+fn, root[len(basepath)+1:]+'\\'+fn)
#dr.add_dicomfile(r'c:\lab\sample\img001.dcm', 'img001.dcm')
dr.write_to_file('test.dcm') | Python |
import dicom
def ex_dicom_to_pil(fn):
dfo = dicom.dicomfile(fn)
im = dfo.to_pil_image()
im.show()
def ex_dicom_to_numpy(fn):
dfo = dicom.dicomfile(fn)
a = dfo.to_numpy_array()
| Python |
#-*- coding: MS949 -*-
'''
Copyright 2010, Kim, Tae-Sung. All rights reserved.
See copyright.txt for details
'''
__author__ = 'Kim Tae-Sung'
__id__ = '$Id$'
import sys
import dicom
if len(sys.argv) < 3:
print 'python makedicomdir.py basedirpath dicomdir_name'
sys.exit()
try:
ddobj = dicom.dicomfile()
dicom.build_dicomdir(ddobj, sys.argv[1])
ddobj.write_to_file(sys.argv[2])
print "DICOMDIR file is successfully built and "\
"is written to '%s'."%(sys.argv[2])
except RuntimeError, e:
print 'Error in build DICOMDIR'
print e | Python |
#-*- coding: MS949 -*-
'''
Copyright 2010, Kim, Tae-Sung. All rights reserved.
See copyright.txt for details
'''
__author__ = 'Kim Tae-Sung'
__id__ = '$Id$'
import dicom
import os, sys
import re, glob
_NCCNMUIDROOT_ = '1.2.826.0.1.3680043.8.417'
if len(sys.argv) == 1:
print 'USAGE: %s /write [elmod.def] [dicomfile ...]'%(sys.argv[0])
print \
r''' [elmod.def] Definition file define how elements should be modified
/write -- Write modified dicom file name with fn+'.mod'
Example of .def file
'0020000d' <= UI, 1.2.826.0.1.3680043.8.417.1000['00080020']1['00080030']1
'00100020' <= LO, string value # string
'00181130' <= DS, 78 # decimal value
'00200032' <= DS, [-175.0, -175.0, -175.0] # value list
Remark:
['TAG'] string will be replaced by actual value of element with given tag
1.2.826.0.1.3680043.8.417.700000 - root uid value for angel lab
'''
sys.exit(-1)
opt_write = True if '/write' in sys.argv else False
if opt_write: sys.argv.remove('/write')
moddeffn = sys.argv[1]
fnlist = sys.argv[2:]
if not moddeffn.endswith('.def'):
print 'Element modification definition file should have extension ".def"'
# PROCESS DEF FILE
kvlist = []
with file(moddeffn, 'r') as f:
for l in f.readlines():
if not l: continue
k, dummy, v = l.partition('<=')
if dummy != '<=':
print 'ERROR IN PARSING LINE', l
continue
vr,dummy,v = v.partition(',')
vr = vr.strip()
if dummy != ',' or len(vr) != 2:
print 'ERROR IN PARSING LINE', l
continue
try:
vr = eval('dicom.VR_'+vr)
except:
print 'ERROR IN PARSING LINE', l
continue
kvlist.append([k.strip(' "\' '), vr, v.split('#')[0].strip()])
# PROCESS FILE LIST ARG
morefnlist = []
for fn in fnlist[:]:
if '*' in fn or '?' in fn:
morefnlist += glob.glob(fn)
fnlist.remove(fn)
fnlist += morefnlist
# PROCESS EACH FILES
replacer = re.compile(r'\[\'[0-9a-fA-F\.]*\'\]')
for fn in fnlist:
try:
df = dicom.dicomfile(fn)
except:
print 'Error while loading '+fn
continue
for tag, vr, v in kvlist:
print fn+':'+tag+' =',
v = replacer.sub(lambda m: df.get_dataelement(m.group()[2:-2]).to_string(), v)
el = df.get_dataelement(tag)
print el.to_string(),'=>',
el = df.add_dataelement(tag)
if vr in [dicom.VR_SL, dicom.VR_SS, dicom.VR_UL, dicom.VR_US,
dicom.VR_AT, dicom.VR_IS]:
if v[0] == '[' and v[-1] == ']': # this is list
v = map(int, v[1:-1].split(','))
el.from_long_values(v)
else: # a single int value
v = int(v)
el.from_long(v)
elif vr in [dicom.VR_FL, dicom.VR_FD, dicom.VR_DS]:
if v[0] == '[' and v[-1] == ']': # this is list
v = map(float, v[1:-1].split(','))
el.from_double_values(v)
else: # a single int value
v = float(v)
el.from_double(v)
else: # string
el.from_string(v)
print el.to_string()
if opt_write:
_path, _fn = os.path.split(fn)
if not os.path.isdir(_path+'.mod'):
os.makedirs(_path+'.mod')
print 'WRITING TO ', _path+'.mod\\'+_fn
df.write_to_file(_path+'.mod\\'+_fn)
| Python |
#-*- coding: MS949 -*-
'''
Copyright 2010, Kim, Tae-Sung. All rights reserved.
See copyright.txt for details
'''
__author__ = 'Kim Tae-Sung'
__id__ = '$Id$'
import sys
import dicom
if len(sys.argv) < 2:
print 'python dumpdicomdir.py dicomdir_name'
sys.exit()
dfo = dicom.dicomfile(sys.argv[1])
ds = dfo['OffsetOfTheFirstDirectoryRecordOfTheRootDirectoryEntity'].to_dataset()
def proc_branch(ds, prefix=''):
while True:
print prefix, #'%04XH'%(ds['RecordInUseFlag'].get_value()), # retired!
print ds['DirectoryRecordType'].get_value().__repr__(),
if ds['DirectoryRecordType'].get_value() == 'PATIENT':
print ds['PatientName'].get_value().__repr__(),
print ds['PatientID'].get_value().__repr__(),
elif ds['DirectoryRecordType'].get_value() == 'STUDY':
print ds['StudyDate'].get_value().__repr__(),
print ds['StudyTime'].get_value().__repr__(),
print ds['StudyID'].get_value().__repr__(),
print ds['StudyDescription'].get_value().__repr__(), # optional
elif ds['DirectoryRecordType'].get_value() == 'SERIES':
print ds['Modality'].get_value().__repr__(),
print ds['SeriesNumber'].get_value().__repr__(),
elif ds['DirectoryRecordType'].get_value() in ['IMAGE','DATASET']:
print ds['ReferencedFileID'].get_value().__repr__(),
print ds['InstanceNumber'].get_value().__repr__(),
print
leafds = ds['OffsetOfReferencedLowerLevelDirectoryEntity'].to_dataset()
if leafds:
proc_branch(leafds, prefix+' ')
ds = ds['OffsetOfTheNextDirectoryRecord'].to_dataset()
if not ds: break
proc_branch(ds) | Python |
# Python script to get both the data and resource fork from a BinHex encoded
# file.
# Author: MURAOKA Taro <koron.kaoriya@gmail.com>
# Last Change: 2012 Jun 29
#
# Copyright (C) 2003,12 MURAOKA Taro <koron.kaoriya@gmail.com>
# THIS FILE IS DISTRIBUTED UNDER THE VIM LICENSE.
import sys
import binhex
input = sys.argv[1]
conv = binhex.HexBin(input)
info = conv.FInfo
out = conv.FName
out_data = out
out_rsrc = out + '.rsrcfork'
#print 'out_rsrc=' + out_rsrc
print 'In file: ' + input
outfile = open(out_data, 'wb')
print ' Out data fork: ' + out_data
while 1:
d = conv.read(128000)
if not d: break
outfile.write(d)
outfile.close()
conv.close_data()
d = conv.read_rsrc(128000)
if d:
print ' Out rsrc fork: ' + out_rsrc
outfile = open(out_rsrc, 'wb')
outfile.write(d)
while 1:
d = conv.read_rsrc(128000)
if not d: break
outfile.write(d)
outfile.close()
conv.close()
# vim:set ts=8 sts=4 sw=4 et:
| Python |
dir = "before"
| Python |
# empty file
| Python |
# empty file
| Python |
import before_2
dir = "after"
| Python |
import before_1
dir = '3'
| Python |
import before_1
dir = '2'
| Python |
dir = 'x'
| Python |
raise ImportError
| Python |
raise NotImplementedError
| Python |
#
| Python |
#
| Python |
#
| Python |
#
| Python |
ddir = 'xx'
| Python |
'''Copyright 2011 Google Inc. All Rights Reserved.
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.'''
from google.appengine.api import backends
from google.appengine.ext import ndb
import json
import logging
import os
from client import shared
_IS_DEVELOPMENT = os.environ['SERVER_SOFTWARE'].startswith('Development/')
class Config(ndb.Model):
# Client ID for web applications
client_id = ndb.StringProperty(indexed=False)
client_secret = ndb.StringProperty(indexed=False)
# Simple API Access
api_key = ndb.StringProperty(indexed=False)
class User(ndb.Model):
displayName = ndb.StringProperty(indexed=False)
createDate = ndb.DateTimeProperty(indexed=False)
credits = ndb.IntegerProperty(indexed=False)
numWins = ndb.IntegerProperty(indexed=False)
numLoss = ndb.IntegerProperty(indexed=False)
virtualItems = ndb.StringProperty(repeated=True, indexed=False)
def getConfig(origin):
if _IS_DEVELOPMENT:
c = json.loads(open('build/keys-localhost.json').read())
setConfig(origin, c['client_id'], c['client_secret'], c['api_key'])
return Config.get_by_id(str(origin))
def setConfig(origin, client_id, client_secret, api_key):
config = Config(id=str(origin), client_id=client_id, client_secret=client_secret, api_key=api_key)
config.put()
def getUser(userID):
return User.get_by_id(str(userID))
def newUser(userID, displayName):
usr = User(id=str(userID))
usr.displayName = displayName
usr.credits = 1000
usr.numWins = 3
usr.numLosses = 5
usr.put()
return usr
#NOTE what are we doing here, really?
#the goal is to have virtual currency, but also allow for purchacing item combos
#called when client asks to unlock an item with credits
def unlockItemForUser(userID, itemID):
usr = getUser(userID)
if not usr:
return None
vi = shared.getVirtualItem(itemID)
if not vi:
return None
#Do this the hacky way and jusr push it to the end.
usr.virtualItems.append(itemID)
usr.credits -= vi.priceInCredits
usr.push()
return True
#called during a postback call from the IAP server
def purchaseItemForUser(userID, itemID):
usr = getUser(userID)
if not usr:
return None
vi = shared.getVirtualItem(itemID)
if not vi:
return None
if vi.itemType == "credits":
usr.credits += vi.itemData0
return True
return None
def userAttemptToBuy(userID, itemID):
assert userID
assert itemID
result = ""
usr = getUser(userID)
if not usr:
return {'result': False, 'message': 'User not found'}
vi = shared.getVirtualItem(itemID)
if not vi:
return {'result': False, 'message': 'Item not found; please check with the admin'}
#if the user has enough credits for the item, unlock the item
if usr.credits >= vi['priceInCredits']:
usr.virtualItems.append(itemID)
usr.credits -= vi['priceInCredits']
usr.put()
return {'result': True, 'itemID': itemID, 'userCredits': usr.credits}
return {'result': False, 'itemID': itemID, 'userCredits': usr.credits}
| Python |
'''Copyright 2011 Google Inc. All Rights Reserved.
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.'''
from client import db_api
from client import matcher
from google.appengine.api import app_identity
from google.appengine.api import backends
from google.appengine.api import oauth
from google.appengine.api import urlfetch
from google.appengine.api import users
from google.appengine.api.urlfetch import fetch
import cgi
import datetime
import json
import logging
import os
import pprint as pp
import random
import sys
import traceback
import urllib
import webapp2
# constants
_DEBUG = True
_JSON_ENCODER = json.JSONEncoder()
if _DEBUG:
_JSON_ENCODER.indent = 4
_JSON_ENCODER.sort_keys = True
if backends.get_backend() == 'matcher':
_match_maker = matcher.MatchMaker()
_EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email"
_IS_DEVELOPMENT = os.environ['SERVER_SOFTWARE'].startswith('Development/')
#######################################################################
# common functions
#######################################################################
def tojson(python_object):
"""Helper function to output and optionally pretty print JSON."""
return _JSON_ENCODER.encode(python_object)
def fromjson(msg):
"""Helper function to ingest JSON."""
try:
return json.loads(msg)
except Exception, e:
raise Exception('Unable to parse as JSON: %s' % msg)
_PAIRING_KEY = fromjson(open('shared/pairing-key.json').read())['key']
def fetchjson(url, deadline, payload=None):
"""Fetch a remote JSON payload."""
method = "GET"
headers = {}
if payload:
method = "POST"
headers['Content-Type'] = 'application/json'
result = fetch(url, method=method, payload=payload, headers=headers, deadline=deadline).content
return fromjson(result)
def json_by_default_dispatcher(router, request, response):
"""WSGI router which defaults to 'application/json'."""
response.content_type = 'application/json'
return router.default_dispatcher(request, response)
def e(msg):
"""Convient method to raise an exception."""
raise Exception(repr(msg))
def w(msg):
"""Log a warning message."""
logging.warning('##### %s' % repr(msg))
#######################################################################
# frontend related stuff
#######################################################################
# frontend handler
class FrontendHandler(webapp2.RequestHandler):
def determine_user(self):
userID = self.request.get('userID')
if userID:
if _IS_DEVELOPMENT:
return userID, self.request.get('displayName', userID)
if userID.startswith('bot*'):
# we'll use the userID as the displayName
return userID, userID
try:
# TODO avoid http://en.wikipedia.org/wiki/Confused_deputy_problem
user = oauth.get_current_user(_EMAIL_SCOPE)
# TODO instead get a suitable displayName from https://www.googleapis.com/auth/userinfo.profile
return user.user_id(), user.nickname() # '0', 'example@example.com' in dev_appserver
except oauth.OAuthRequestError:
raise Exception("""OAuth2 credentials -or- a valid 'bot*...' userID must be provided""")
# frontend handler
class LoginHandler(FrontendHandler):
def post(self):
# for the admin only auth form
self.get()
def get(self):
config = db_api.getConfig(self.request.host_url)
if not config:
self.request_init()
return
redirectUri = '%s/logup.html' % self.request.host_url
authScope = 'https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/plus.me+https://www.googleapis.com/auth/plus.people.recommended';
returnto = self.request.get('redirect_uri')
authUri = 'http://accounts.google.com/o/oauth2/auth'
authUri += '?scope=' + authScope
authUri += '&redirect_uri=' + redirectUri
authUri += '&response_type=token'
authUri += '&client_id=' + str(config.client_id)
#authUri += '&state=' + returnto
self.response.headers['Access-Control-Allow-Origin'] = '*'
logging.debug('authUri=%s' % authUri)
self.redirect(authUri)
def request_init(self):
user = users.get_current_user()
if user:
if users.is_current_user_admin():
client_id = self.request.get('client_id')
client_secret = self.request.get('client_secret')
api_key = self.request.get('api_key')
if client_id and client_secret and api_key:
db_api.setConfig(self.request.host_url, client_id, client_secret, api_key)
body = 'Thank you! You may now <a href="javascript:window.location.reload();">reload</a> this page.'
else:
body = """Please enter the following information from the
<a href="https://developers.google.com/console" target="_blank">Developer Console<a> <b>%s</b> project:<br><br>
<form method="post">
<h3>Client ID for web applications<h3>
client_id:<input name="client_id"><br>
client_secret:<input name="client_secret"><br>
<h3>Simple API Access<h3>
api_key:<input name="api_key"><br>
<input type="submit">
</form>""" % self.request.host_url
else:
body = 'You (%s) are not an admin. Please <a href="%s">logout</a>.' % (user.email(), users.create_logout_url(self.request.path))
else:
body = 'Please <a href="%s">login</a> as an admin.' % users.create_login_url(self.request.path)
self.response.headers['Content-Type'] = 'text/html'
self.response.write('<html><body><h1>Datastore configuration</h1>%s</body></html>' % body)
# frontend handler
class Login(FrontendHandler):
def post(self):
self.response.headers['Access-Control-Allow-Origin'] = '*'
userID, displayName = self.determine_user()
usr = db_api.getUser(userID)
if not usr:
usr = db_api.newUser(userID, displayName)
r = {'userID': userID, 'displayName': displayName}
self.response.write(tojson(r) + '\n')
# frontend handler
class GritsService(FrontendHandler):
# TODO per client (userID) throttling to limit abuse
def post(self, fcn):
logging.info('%s ...' % self.request.url)
if not fcn:
fcn = self.request.get('fcn')
if fnc:
# TODO remove once there are no more uses of ?fcn=... in our code
logging.warning('Please use /grits/%s/?foo=... instead of /grits/?fcn=%s&foo=...' % (fnc, fnc))
self.response.headers['Access-Control-Allow-Origin'] = '*'
userID, displayName = self.determine_user()
usr = db_api.getUser(userID)
if not usr:
if userID.startswith('bot*'):
usr = db_api.newUser(userID, displayName)
else:
self.response.set_status(404)
self.response.write('Grits userID not found: ' + userID)
return
if fcn == 'getProfile':
r = {'userID': userID, 'credits': str(usr.credits), 'numWins': str(usr.numWins), 'virtualItems': usr.virtualItems}
self.response.write(tojson(r))
elif fcn == 'getFriends':
self.getFriends(userID)
elif fcn == 'buyItem':
itemID = self.request.get('itemID')
if not itemID:
self.response.set_status(400)
self.response.write('Grits itemID is required')
return
r = db_api.userAttemptToBuy(userID, itemID)
self.response.write(tojson(r))
elif fcn == 'findGame':
self.findGame(userID)
else:
self.response.set_status(400)
self.response.write('Bad grits request.')
def findGame(self, userID):
# forward the request to the matcher backend
url = '%s/find-game/%s' % (backends.get_url(backend='matcher', instance=None, protocol='HTTP'), userID)
payload = '{}'
resp = urlfetch.fetch(url=url,
payload=payload,
method=urlfetch.POST,
headers={'Content-Type': 'application/json'})
self.response.set_status(resp.status_code)
self.response.headers.update(resp.headers)
self.response.write(resp.content)
logging.info('%s -> %s -> %s' % (repr(payload), url, resp.content))
def getFriends(self, userID):
config = db_api.getConfig(self.request.host_url)
assert config.api_key
token = self.request.get('accessToken')
reqUri = 'https://www.googleapis.com/plus/v1games/people/me/people/recommended';
reqUri += '?key=' + config.api_key;
reqUri += '&access_token=' + token;
result = fetchjson(reqUri, None)
self.response.write(tojson(result))
#self.response.headers['Content-Type'] = 'application/json'
#self.response.headers['Access-Control-Allow-Origin'] = '*'
#self.redirect(reqUri)
# frontend handler
class PurchaseService(FrontendHandler):
def get(self):
iap.serverPurchasePostback(self)
# frontend handler
class SharedJsonAssets(FrontendHandler):
def get(self, filename):
f = open(filename, 'r')
self.response.write(f.read())
f.close()
#######################################################################
# 'matcher' backend related stuff
#######################################################################
# 'matcher' backend handler
class JsonHandler(webapp2.RequestHandler):
"""Convenience class for handling JSON requests."""
def handle(self, params, *args):
raise Exception('subclasses must implement this method')
def post(self, *args):
logging.info('%s <- %s' % (self.request.path, self.request.body))
try:
if not self.request.body:
raise Exception('Empty request')
params = fromjson(self.request.body)
r = self.handle(params, *args)
if not r:
raise Exception('Unexpected empty response from subclass')
self.response.write(tojson(r))
except:
# clients must already be prepared to deal with non-JSON responses,
# so a raw, human readable, stack trace is fine here
self.response.set_status(500)
tb = traceback.format_exc()
logging.warn(tb)
self.response.write(tb)
# 'matcher' backend handler
class FindGame(JsonHandler):
def handle(self, params, userID):
pingAll()
return self.get_game(userID)
def get_game(self, userID):
# previously matched / player re-entering?
player_game = _match_maker.lookup_player_game(userID)
if player_game:
return player_game
# look for a new available game
result = self._get_player_game(userID)
# found a game?
if result and 'game' in result:
player_game = result
usr = db_api.getUser(userID)
addPlayers(player_game, userID, usr.displayName)
return result
# more players needed to start game?
if result.get('players_needed_for_next_game', None) > 0:
return result
# start a new game
game = startGame()
if 'game_state' not in game:
logging.info('RETURNING RESULT FROM startGame(): %s' % game)
return game
logging.info('RETURNING RESULT: %s' % result)
return result
def _get_player_game(self, userID):
player_game = _match_maker.find_player_game(userID)
return player_game
# 'matcher' backend handler
class UpdateGameState(JsonHandler):
def handle(self, params, *args):
serverid = params['serverid']
new_game_state = params['game_state']
game_name = new_game_state['name']
_match_maker.update_player_names(serverid, game_name, new_game_state)
return {'success': True,
'backend': backends.get_backend()}
# 'matcher' backend handler
class RegisterController(JsonHandler):
def handle(self, params, *args):
if _PAIRING_KEY != params['pairing_key']:
return {'success': False,
'exception': 'bad pairing key'}
controller_port = params['controller_port']
ip = self.request.remote_addr
controller_host = '%s:%d' % (ip, controller_port)
params['controller_host'] = controller_host
_match_maker.update_server_info(params)
return {'success': True,
'backend': backends.get_backend(),
'controller_host': controller_host}
# 'matcher' backend handler
class ListGames(webapp2.RequestHandler):
def get(self):
self.response.write(tojson(pingAll()))
# 'matcher' backend handler
class Debug(webapp2.RequestHandler):
def get(self):
state = _match_maker.get_state()
self.response.write(tojson(state))
# 'matcher' backend handler
class StartGame(webapp2.RequestHandler):
def get(self):
self.response.write(tojson(startGame()))
# 'matcher' backend handler
class LogFiles(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/html'
self.response.write('<html><body><h1>Log Files</h1>')
for serverid in _match_maker.get_game_servers():
server_info = _match_maker.get_game_server_info(serverid)
self.response.write('<p>%(id)s: '
'<a href="http://%(svr)s/forever.log">error</a> '
'<a href="http://%(svr)s/log">console</a> '
'<a href="http://%(svr)s/ping">ping</a> '
'<a href="http://%(svr)s/enable-dedup">enable-dedup</a> '
'<a href="http://%(svr)s/disable-dedup">disable-dedup</a> '
'</p>' %
{'id':serverid,
'svr':server_info['controller_host']})
self.response.write('</body></html>')
# 'matcher' backend handler
class GameOver(JsonHandler):
def handle(self, params, *args):
_match_maker.del_game(params['serverid'], params['name'])
return {'success': True, 'backend': backends.get_backend()}
# 'matcher' backend helper function
def pingAll():
removeserver = []
# TODO use async urlfetch to parallelize url fetch calls
for serverid in _match_maker.get_game_servers():
server_info = _match_maker.get_game_server_info(serverid)
url = 'http://%s/ping' % server_info['controller_host']
try:
r = fetchjson(url, 2)
logging.debug('pingAll(): %s -> %s' % (url, r))
except:
logging.warn('pingAll(): EXCEPTION %s' % traceback.format_exc())
removeserver.append(serverid)
if r['serverid'] != serverid:
removeserver.append(serverid)
continue
# check for games which have ended without our knowledge
remotegameinfo = r['gameinfo']
server_struct = _match_maker.get_game_server_struct(serverid)
games = server_struct['games']
removegame = []
for name, game in games.iteritems():
if name not in remotegameinfo:
# the game is unexpectedly gone
logging.warn('serverid %s unexpectedly lost game %s (did we miss a /game-over callback?)' % (serverid, name))
removegame.append(name)
for name in removegame:
_match_maker.del_game(serverid, name)
for serverid in removeserver:
_match_maker.del_game_server(serverid)
return _match_maker.get_game_servers()
# 'matcher' backend helper function
def rateUsage(r):
return max(int(r['cpu']), int(r['mem']))
# 'matcher' backend helper function
def startGame():
logging.debug('startGame()')
best = None
bestServer = None
for serverid, server_struct in pingAll().iteritems():
if not best or rateUsage(best) > rateUsage(r):
server_info = server_struct['server_info']
best = server_info
bestServer = best['controller_host']
if bestServer:
url = 'http://%s/start-game?p=%s' % (bestServer, _PAIRING_KEY)
game = fetchjson(url, 20)
logging.debug('startGame(): %s -> %s' % (url, tojson(game)))
if game.get('success', False):
ip = bestServer.split(':')[0]
game['gameURL'] = 'http://%s:%s/%s' % (ip, game['port'], game['name'])
game['controller_host'] = bestServer
game['serverid'] = best['serverid']
_match_maker.update_game(game)
return game
else:
return {'result': 'no-available-servers'}
def addPlayers(player_game, userID, displayName):
logging.info('addPlayers(player_game=%s, userID=%s, displayName=%s)' % (player_game, userID, displayName))
game = player_game['game']
url = 'http://%s/add-players?p=%s' % (game['controller_host'], _PAIRING_KEY)
player_game_key = player_game['player_game_key']
msg = {
'userID': userID,
'displayName': displayName,
'game_name' : game['name'],
'player_game_key': player_game_key,
}
try:
result = fetchjson(url, 20, payload=tojson(msg))
logging.info('addPlayers(): %s -> %s -> %s' % (tojson(msg), url, tojson(result)))
return {
'game': game,
'player_game_key': player_game_key,
'success': True,
}
except:
exc = traceback.format_exc()
logging.info('addPlayers(): %s -> %s -> %s' % (tojson(msg), url, exc))
return {
'success' : False,
'exception': exc,
}
#######################################################################
# handler common to frontends and backends
handlers = [
]
if not backends.get_backend():
# frontend specific handlers
handlers.extend([
('/login', Login),
('/loginoauth', LoginHandler),
('/grits/(.*)', GritsService),
('/(shared/.*\.json)', SharedJsonAssets),
])
elif backends.get_backend() == 'matcher':
# 'matcher' backend specific handlers
handlers.extend([
('/find-game/(.*)', FindGame),
('/update-game-state', UpdateGameState),
('/register-controller', RegisterController),
('/list-games', ListGames),
('/debug', Debug),
('/start-game', StartGame),
('/game-over', GameOver),
('/log-files', LogFiles),
])
app = webapp2.WSGIApplication(handlers, debug=True)
app.router.set_dispatcher(json_by_default_dispatcher)
| Python |
'''Copyright 2011 Google Inc. All Rights Reserved.
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.'''
import json
import logging
import os
with open('shared/weapons/Weapons.json', 'r') as f:
_WEAPONS = json.loads(f.read())
def getVirtualItem(itemID):
assert itemID
for item in _WEAPONS['weapons']:
if item['itemID'] == itemID:
return item
raise Exception('itemID "%s" does not exist' % itemID)
| Python |
'''Copyright 2011 Google Inc. All Rights Reserved.
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.'''
from google.appengine.api import apiproxy_stub_map
from google.appengine.api import backends
from google.appengine.api import runtime
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import cgi
import datetime
import logging
import os
import urllib
from client import db_api
#my_name = '%s.%s (%s)' % (backends.get_backend(), backends.get_instance(), backends.get_url())
logging.info('registering shutdown hook')
def my_shutdown_hook():
logging.warning('shutdown hook called')
apiproxy_stub_map.apiproxy.CancelApiCalls()
# save_state()
# May want to raise an exception
# register our shutdown hook, which is not guaranteed to be called
runtime.set_shutdown_hook(my_shutdown_hook)
| Python |
#!/usr/bin/env python
import optparse
import jwt
import sys
import json
import time
__prog__ = 'jwt'
__version__ = '0.1'
""" JSON Web Token implementation
Minimum implementation based on this spec:
http://self-issued.info/docs/draft-jones-json-web-token-01.html
"""
import base64
import hashlib
import hmac
try:
import json
except ImportError:
import simplejson as json
__all__ = ['encode', 'decode', 'DecodeError']
class DecodeError(Exception): pass
signing_methods = {
'HS256': lambda msg, key: hmac.new(key, msg, hashlib.sha256).digest(),
'HS384': lambda msg, key: hmac.new(key, msg, hashlib.sha384).digest(),
'HS512': lambda msg, key: hmac.new(key, msg, hashlib.sha512).digest(),
}
def base64url_decode(input):
input += '=' * (4 - (len(input) % 4))
return base64.urlsafe_b64decode(input)
def base64url_encode(input):
return base64.urlsafe_b64encode(input).replace('=', '')
def header(jwt):
header_segment = jwt.split('.', 1)[0]
try:
return json.loads(base64url_decode(header_segment))
except (ValueError, TypeError):
raise DecodeError("Invalid header encoding")
def encode(payload, key, algorithm='HS256'):
segments = []
header = {"typ": "JWT", "alg": algorithm}
segments.append(base64url_encode(json.dumps(header)))
segments.append(base64url_encode(json.dumps(payload)))
signing_input = '.'.join(segments)
try:
if isinstance(key, unicode):
key = key.encode('utf-8')
signature = signing_methods[algorithm](signing_input, key)
except KeyError:
raise NotImplementedError("Algorithm not supported")
segments.append(base64url_encode(signature))
return '.'.join(segments)
def decode(jwt, key='', verify=True):
try:
signing_input, crypto_segment = jwt.rsplit('.', 1)
header_segment, payload_segment = signing_input.split('.', 1)
except ValueError:
raise DecodeError("Not enough segments")
try:
header = json.loads(base64url_decode(header_segment))
payload = json.loads(base64url_decode(payload_segment))
signature = base64url_decode(crypto_segment)
except (ValueError, TypeError):
raise DecodeError("Invalid segment encoding")
if verify:
try:
if isinstance(key, unicode):
key = key.encode('utf-8')
if not signature == signing_methods[header['alg']](signing_input, key):
raise DecodeError("Signature verification failed")
except KeyError:
raise DecodeError("Algorithm not supported")
return payload
def fix_optionparser_whitespace(input):
"""Hacks around whitespace Nazi-ism in OptionParser"""
newline = ' ' * 80
doublespace = '\033[8m.\033[0m' * 2
return input.replace(' ', doublespace).replace('\n', newline)
def main():
"""Encodes or decodes JSON Web Tokens based on input
Decoding examples:
%prog --key=secret json.web.token
%prog --no-verify json.web.token
Encoding requires the key option and takes space separated key/value pairs
separated by equals (=) as input. Examples:
%prog --key=secret iss=me exp=1302049071
%prog --key=secret foo=bar exp=+10
The exp key is special and can take an offset to current Unix time.
"""
p = optparse.OptionParser(description=fix_optionparser_whitespace(main.__doc__),
prog=__prog__,
version='%s %s' % (__prog__, __version__),
usage='%prog [options] input')
p.add_option('-n', '--no-verify', action='store_false', dest='verify', default=True,
help='ignore signature verification on decode')
p.add_option('--key', dest='key', metavar='KEY', default=None,
help='set the secret key to sign with')
p.add_option('--alg', dest='algorithm', metavar='ALG', default='HS256',
help='set crypto algorithm to sign with. default=HS256')
options, arguments = p.parse_args()
if len(arguments) > 0 or not sys.stdin.isatty():
# Try to decode
try:
if not sys.stdin.isatty():
token = sys.stdin.read()
else:
token = arguments[0]
valid_jwt = jwt.header(token)
if valid_jwt:
try:
print json.dumps(jwt.decode(token, key=options.key, verify=options.verify))
sys.exit(0)
except jwt.DecodeError, e:
print e
sys.exit(1)
except jwt.DecodeError:
pass
# Try to encode
if options.key is None:
print "Key is required when encoding. See --help for usage."
sys.exit(1)
# Build payload object to encode
payload = {}
for arg in arguments:
try:
k,v = arg.split('=', 1)
# exp +offset special case?
if k == 'exp' and v[0] == '+' and len(v) > 1:
v = str(int(time.time()+int(v[1:])))
# Cast to integer?
if v.isdigit():
v = int(v)
else:
# Cast to float?
try:
v = float(v)
except ValueError:
pass
# Cast to true, false, or null?
constants = {'true': True, 'false': False, 'null': None}
if v in constants:
v = constants[v]
payload[k] = v
except ValueError:
print "Invalid encoding input at %s" % arg
sys.exit(1)
try:
print jwt.encode(payload, key=options.key, algorithm=options.algorithm)
sys.exit(0)
except Exception, e:
print e
sys.exit(1)
else:
p.print_help()
if __name__ == '__main__':
main()
| Python |
'''Copyright 2011 Google Inc. All Rights Reserved.
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.'''
from google.appengine.api import backends
from google.appengine.api import users
import copy
import logging
import pprint as pp
import random
import sys
from client import db_api
def e(msg):
"""Convient method to raise an exception."""
raise Exception(repr(msg))
def w(msg):
"""Log a warning message."""
logging.warning('##### %s' % repr(msg))
class MatchMaker:
"""
Multiple player match making service, allowing players
to come together in an arena to show off their skills.
_game_servers =
{ serverid1: <server_struct>,
serverid2: <server_struct>,
}
<server_struct> =
{ 'server_info': <server_info>,
'games': { name1: <game>,
name2: <game>,
},
}
<server_info> =
{ 'serverid': ...,
'uptime': ...,
}
<game> =
{ serverid': ...,
'name': 'mPdn',
'gameURL': 'http://127.0.0.1:8081/mPdn',
'port': 8081,
'controller_host': '127.0.0.1:12345',
'game_state': {'players': {'324324382934982374823748923': '!1'}, 'min_players': 2, 'max_players': 8},
}
"""
_EMPTY_SERVER = { 'games' : {} }
def __init__(self):
self._game_servers = {}
self._players_waiting = []
self._players_playing = {}
def get_game_server_struct(self, serverid):
assert serverid
return self._game_servers.get(serverid, None)
def get_game_server_info(self, serverid):
assert serverid
server_struct = self.get_game_server_struct(serverid)
return server_struct['server_info']
def _set_game_server_struct(self, serverid, server_struct):
self._game_servers[serverid] = server_struct
def _set_game_server_info(self, serverid, server_info):
assert serverid
assert server_info
server_struct = self.get_game_server_struct(serverid)
if not server_struct:
server_struct = copy.deepcopy(MatchMaker._EMPTY_SERVER)
self._set_game_server_struct(serverid, server_struct)
server_struct['server_info'] = server_info
def get_state(self):
return {
'game_servers': self._game_servers,
'players_waiting': self._players_waiting,
'players_playing': self._players_playing,
}
def get_game_servers(self):
return self._game_servers
def del_game_server(self, serverid):
del self._game_servers[serverid]
remove = []
for player, player_game in self._players_playing.iteritems():
game = player_game['game']
if game['serverid'] == serverid:
remove.append(player)
for r in remove:
self._players_playing.pop(r)
def update_player_names(self, serverid, game_name, new_game_state):
server_struct = self.get_game_server_struct(serverid)
games = server_struct['games']
game = games[game_name]
game_state = game['game_state']
players = game_state['players']
new_players = new_game_state['players']
logging.info('Updating %s with %s' % (repr(players), repr(new_players)))
assert isinstance(players, dict)
assert isinstance(new_players, dict)
players.update(new_players)
def update_server_info(self, server_info):
serverid = server_info['serverid']
self._set_game_server_info(serverid, server_info)
def update_game(self, game):
serverid = game['serverid']
name = game['name']
assert serverid in self._game_servers
server_struct = self.get_game_server_struct(serverid)
games = server_struct['games']
games[name] = game
def del_game(self, serverid, game_name):
server_struct = self.get_game_server_struct(serverid)
games = server_struct['games']
game = games[game_name]
game_state = game['game_state']
players = game_state['players']
for p in players:
self._players_playing.pop(p)
del games[game_name]
def _add_player(self, userID, game):
assert isinstance(userID, str)
game_state = game['game_state']
min_players = int(game_state['min_players'])
max_players = int(game_state['max_players'])
players = game_state['players']
assert max_players >= min_players
assert len(players) < max_players
assert userID not in game_state['players']
players[userID] = 'TBD'
self._players_playing[userID] = {
'game': game,
'player_game_key': str(random.randint(-sys.maxint, sys.maxint)),
'userID': userID, # used by Android client
}
def make_matches(self):
if not self._players_waiting:
return
# TODO match based on skills instead of capacity
players_needed_for_next_game = self.make_matches_min_players()
if self._players_waiting:
self.make_matches_max_players()
return players_needed_for_next_game
def make_matches_min_players(self):
players_needed_for_next_game = -1
for server_struct in self._game_servers.itervalues():
for game in server_struct['games'].itervalues():
game_state = game['game_state']
players_in_game = game_state['players']
player_goal = int(game_state['min_players'])
players_needed = player_goal - len(players_in_game)
if not players_needed:
continue
if len(self._players_waiting) >= players_needed:
# let's get this party started
while len(players_in_game) < player_goal:
self._add_player(self._players_waiting.pop(0), game)
elif (players_needed_for_next_game == -1
or players_needed < players_needed_for_next_game):
players_needed_for_next_game = players_needed
return players_needed_for_next_game
def make_matches_max_players(self):
for server_struct in self._game_servers.itervalues():
for game in server_struct['games'].itervalues():
game_state = game['game_state']
players_in_game = game_state['players']
if len(players_in_game) < int(game_state['min_players']):
continue
player_goal = int(game_state['max_players'])
if len(players_in_game) == player_goal:
continue
while self._players_waiting and len(players_in_game) < player_goal:
self._add_player(self._players_waiting.pop(0), game)
def lookup_player_game(self, userID):
assert isinstance(userID, str)
return self._players_playing.get(userID, None)
def find_player_game(self, userID):
assert isinstance(userID, str)
if userID not in self._players_waiting:
self._players_waiting.append(userID)
players_needed_for_next_game = self.make_matches()
if userID in self._players_waiting:
#logging.info('find_player_game: %s must wait a little bit longer' % userID)
return {'result': 'wait', 'players_needed_for_next_game': players_needed_for_next_game}
player_game = self._players_playing.get(userID, None)
if not player_game:
raise Exception('userID %s is not in self._players_playing' % userID)
return player_game
| Python |
'''Copyright 2011 Google Inc. All Rights Reserved.
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.''' | Python |
import logging
# Change default log level to debug in dev_appserver to match production
logging.getLogger().setLevel(logging.DEBUG)
# but leave the default for App Engine APIs
logging.getLogger('google.appengine').setLevel(logging.INFO)
| Python |
#!/usr/bin/env python2.7
import json
import logging
import os
import pprint as pp
import sys
import unittest
import urllib2
try:
from webtest import TestApp
except:
print """Please install webtest from http://webtest.pythonpaste.org/"""
sys.exit(1)
# Attempt to locate the App Engine SDK based on the system PATH
for d in sorted(os.environ['PATH'].split(os.path.pathsep)):
path = os.path.join(d, 'dev_appserver.py')
if not os.path.isfile(path):
continue
print 'Found the App Engine SDK directory: %s' % d
sys.path.insert(0, d)
# The App Engine SDK root is now expected to be in sys.path (possibly provided via PYTHONPATH)
try:
import dev_appserver
except ImportError:
error_msg = ('The path to the App Engine Python SDK must be in the '
'PYTHONPATH environment variable to run unittests.')
# The app engine SDK isn't in sys.path. If we're on Windows, we can try to
# guess where it is.
import platform
if platform.system() == 'Windows':
sys.path = sys.path + ['C:\\Program Files\\Google\\google_appengine']
try:
import dev_appserver # pylint: disable-msg=C6204
except ImportError:
print error_msg
raise
else:
print error_msg
raise
# add App Engine libraries
sys.path += dev_appserver.EXTRA_PATHS
from google.appengine.ext import testbed
from google.appengine.api import backends
def make_state(serverid, extras=None):
"""Create test game server state."""
# something pseudo predictable / stable
uptime = hash(serverid) / 1e16
result = { 'serverid': serverid, 'uptime': uptime }
if extras:
result.update(extras)
return result
def make_game(serverid, name, extras=None):
"""Create test game instance."""
result = {
'serverid': serverid,
'name': name,
'game_state': {'players': {}, 'min_players': 2, 'max_players': 4},
}
if extras:
result.update(extras)
return result
class MatchMakerTest(unittest.TestCase):
def setUp(self):
# see testbed docs https://developers.google.com/appengine/docs/python/tools/localunittesting
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_memcache_stub()
self.testbed.init_datastore_v3_stub()
self.testbed.init_urlfetch_stub()
# import matcher now that testbed has been activated
from client import matcher
# instatiate a new matcher
self.mm = matcher.MatchMaker()
# no maximum length for diffs
self.maxDiff = None
def tearDown(self):
self.testbed.deactivate()
def assertGameServers(self, expected_game_servers):
"""Assert the global game servers state."""
if expected_game_servers != self.mm._game_servers:
self.fail('Unexpected game servers state:\n----------\nEXPECTED:\n%s\n\nACTUAL:\n%s\n----------' % (expected_game_servers, self.mm._game_servers))
#self.assertEquals(expected_game_servers, self.mm._game_servers)
def assertPlayerGameState(self, expected_game, player_game):
"""Assert a specifc game state."""
self.assertIn('game', player_game)
self.assertIn('player_game_key', player_game)
self.assertEquals(expected_game, player_game['game'])
def assertGameServerWait(self, players_needed_for_next_game, pg):
"""Assert that the player is being asked to wait."""
self.assertEquals({'result': 'wait', 'players_needed_for_next_game': players_needed_for_next_game}, pg)
#######################################################################
# tests to verify server and game updates
#######################################################################
def test_initialized_state(self):
self.assertGameServers({})
def test_update_server_info(self):
self.assertGameServers({})
state_foo = make_state('foo')
expected = { 'foo':
{ 'server_info': state_foo,
'games': {},
}
}
self.mm.update_server_info(state_foo)
self.assertGameServers(expected)
def test_update_server_info_twice(self):
state_foo = make_state('foo')
state_bar = make_state('bar')
expected = { 'foo':
{ 'server_info': state_foo,
'games': {},
},
'bar':
{ 'server_info': state_bar,
'games': {},
},
}
self.assertGameServers({})
self.mm.update_server_info(state_foo)
self.mm.update_server_info(state_bar)
self.assertGameServers(expected)
def test_update_server_info_thrice(self):
state_foo1 = make_state('foo', {'update': 17} )
state_foo2 = make_state('foo', {'update': 42} )
state_bar = make_state('bar')
expected = { 'foo':
{ 'server_info': state_foo2,
'games': {},
},
'bar':
{ 'server_info': state_bar,
'games': {},
},
}
self.assertGameServers({})
self.mm.update_server_info(state_foo1)
self.mm.update_server_info(state_bar)
self.mm.update_server_info(state_foo2)
self.assertGameServers(expected)
def test_del_server_info(self):
state_foo = make_state('foo')
state_bar = make_state('bar')
expected = { 'bar':
{ 'server_info': state_bar,
'games': {},
},
}
self.assertGameServers({})
self.mm.update_server_info(state_foo)
self.mm.update_server_info(state_bar)
self.mm.del_game_server('foo')
self.assertGameServers(expected)
def test_update_game(self):
state_foo = make_state('foo')
game_abcd = make_game('foo', 'abcd')
expected = { 'foo':
{ 'server_info': state_foo,
'games': { 'abcd' : game_abcd,
}
}
}
self.assertGameServers({})
self.mm.update_server_info(state_foo)
self.mm.update_game(game_abcd)
self.assertGameServers(expected)
#######################################################################
# tests to verify match making
#######################################################################
def test_do_not_find_full_game(self):
state_foo = make_state('foo')
game_abcd = make_game('foo', 'abcd', {'game_state': {'players': {}, 'min_players': 0, 'max_players': 0}})
self.mm.update_server_info(state_foo)
# we have a game, but no players are needed
self.mm.update_game(game_abcd)
# do not find full game
pg = self.mm.find_player_game('fred')
self.assertGameServerWait(-1, pg)
def test_find_single_player_game(self):
state_foo = make_state('foo')
game_abcd = make_game('foo', 'abcd', {'game_state': {'players': {}, 'min_players': 1, 'max_players': 1}})
self.mm.update_server_info(state_foo)
# no available game yet
pg = self.mm.find_player_game('fred')
self.assertGameServerWait(-1, pg)
# game_abcd becomes available
self.mm.update_game(game_abcd)
# we should find it
pg = self.mm.find_player_game('fred')
self.assertPlayerGameState(game_abcd, pg)
# we should find it again
pg = self.mm.lookup_player_game('fred')
self.assertPlayerGameState(game_abcd, pg)
def test_wait_for_enough_players(self):
state_foo = make_state('foo')
# only 3 game slots remaining
game_abcd = make_game('foo', 'abcd', {'game_state': {'players': {}, 'min_players': 1, 'max_players': 1}})
game_efgh = make_game('foo', 'efgh', {'game_state': {'players': {}, 'min_players': 2, 'max_players': 2}})
self.mm.update_server_info(state_foo)
self.mm.update_game(game_abcd)
self.mm.update_game(game_efgh)
# player1 enters game_abcd
pg = self.mm.find_player_game('player1')
self.assertPlayerGameState(game_abcd, pg)
# player2 waits for a second player
pg = self.mm.find_player_game('player2')
self.assertGameServerWait(2, pg)
# player3 enters game_efgh
pg = self.mm.find_player_game('player3')
self.assertPlayerGameState(game_efgh, pg)
# player4 does not get in
pg = self.mm.find_player_game('player4')
self.assertGameServerWait(-1, pg)
# player2 finally enter game_efgh
pg = self.mm.lookup_player_game('player2')
self.assertPlayerGameState(game_efgh, pg)
def test_honor_max_players(self):
state_foo = make_state('foo')
# only 3 game slots remaining
game_abcd = make_game('foo', 'abcd', {'game_state': {'players': {}, 'min_players': 2, 'max_players': 4}})
self.mm.update_server_info(state_foo)
# player1 is told that a new game needs to be spun up
pg = self.mm.find_player_game('player1')
self.assertGameServerWait(-1, pg)
# a new game is made available
self.mm.update_game(game_abcd)
# player1 is told 2 players are required
pg = self.mm.find_player_game('player1')
self.assertGameServerWait(2, pg)
# player2 allows the game to start
pg = self.mm.find_player_game('player2')
self.assertPlayerGameState(game_abcd, pg)
# player3 drops in
pg = self.mm.find_player_game('player3')
self.assertPlayerGameState(game_abcd, pg)
# player4 drops in
pg = self.mm.find_player_game('player4')
self.assertPlayerGameState(game_abcd, pg)
# player5 does not get in
pg = self.mm.find_player_game('player5')
self.assertGameServerWait(-1, pg)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python2.7
import json
import logging
import os
import pprint as pp
import sys
import unittest
import urllib2
try:
from webtest import TestApp
except:
print """Please install webtest from http://webtest.pythonpaste.org/"""
sys.exit(1)
# Attempt to locate the App Engine SDK based on the system PATH
for d in sorted(os.environ['PATH'].split(os.path.pathsep)):
path = os.path.join(d, 'dev_appserver.py')
if not os.path.isfile(path):
continue
print 'Found the App Engine SDK directory: %s' % d
sys.path.insert(0, d)
# The App Engine SDK root is now expected to be in sys.path (possibly provided via PYTHONPATH)
try:
import dev_appserver
except ImportError:
error_msg = ('The path to the App Engine Python SDK must be in the '
'PYTHONPATH environment variable to run unittests.')
# The app engine SDK isn't in sys.path. If we're on Windows, we can try to
# guess where it is.
import platform
if platform.system() == 'Windows':
sys.path = sys.path + ['C:\\Program Files\\Google\\google_appengine']
try:
import dev_appserver # pylint: disable-msg=C6204
except ImportError:
print error_msg
raise
else:
print error_msg
raise
# add App Engine libraries
sys.path += dev_appserver.EXTRA_PATHS
from google.appengine.ext import testbed
from google.appengine.api import backends
class HttpMatcherTest(unittest.TestCase):
def verifyNodeJsServerRunning(self):
url = 'http://127.0.0.1:12345/ping'
try:
result = urllib2.urlopen(url)
r = json.loads(result.read())
logging.debug('%s -> %s' % (url, r))
self._serverid = r['serverid']
except urllib2.URLError, e:
self.fail('Node.js games-server must be running. Could not connect to %s\n%s' % (url, e))
def get(self, *args, **kwargs):
result = self.app.get(*args, **kwargs)
logging.debug('self.app.get %s %s -> %s' % (args, kwargs, result.body))
return result
def post(self, *args, **kwargs):
result = self.app.post(*args, **kwargs)
logging.debug('self.app.post %s %s -> %s' % (args, kwargs, result.body ))
return result
def setUp(self):
# see testbed docs https://developers.google.com/appengine/docs/python/tools/localunittesting
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_memcache_stub()
self.testbed.init_datastore_v3_stub()
self.testbed.init_urlfetch_stub()
# Pretend we're a matcher backend
self.assertEquals(None, backends.get_backend())
self.save_get_backend = backends.get_backend
backends.get_backend = lambda: 'matcher'
self.assertEquals('matcher', backends.get_backend())
# create TestApp wrapper around client.main.app
from client import main
main._JSON_ENCODER.indent = None
self.app = TestApp(main.app)
#
self.verifyNodeJsServerRunning()
# no maximum length for diffs
self.maxDiff = None
def tearDown(self):
# restore patched methods
backends.get_backend = self.save_get_backend
self.testbed.deactivate()
def test_list_games_starts_emtpy(self):
res = self.get('/list-games')
self.assertEquals('{}', res.body)
def test_start_game(self):
res = self.get('/start-game')
r = json.loads(res.body)
self.assertIn('no-available-servers' , r.get('result'))
def test_start_game2(self):
self.assertTrue(self._serverid)
expected_req = { 'controller_port': 12345, 'serverid': self._serverid, 'pairing_key': 'XXXXXXXXXXXXXXXXXXXXXX' }
expected_res = { 'backend': 'matcher', 'controller_host': '127.0.0.1:12345', 'success': True }
# TODO ensure that in this post, self.request.remote_addr = 127.0.0.1
res = self.post('/register-controller', json.dumps(expected_req), extra_environ={'REMOTE_ADDR': '127.0.0.1'})
r = res.json
self.assertEquals(True, r.get('success'))
self.assertEquals(expected_res, r)
self.verifyNodeJsServerRunning()
res = self.get('/start-game')
r = res.json
self.assertEquals(True, r.get('success'))
name = r.get('name')
self.assertTrue(len(name))
time = r.get('time')
self.assertTrue(time > 0)
game_state = r.get(u'game_state')
self.assertEquals(8, game_state.get(u'max_players'))
self.assertEquals(1, game_state.get(u'min_players'))
self.assertEquals({}, game_state.get(u'players'))
self.assertEquals(name, r.get(u'name'))
self.assertTrue(r.get(u'success'))
self.assertEquals(time, r.get(u'time'))
self.assertEquals(self._serverid, r.get(u'serverid'))
self.assertEquals(u'127.0.0.1:12345', r.get(u'controller_host'))
self.assertEquals(u'http://127.0.0.1:8081/%s' % name, r.get(u'gameURL'))
self.assertEquals(8081, r.get(u'port'))
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python
import sys, getopt, time, os
import pexpect, re
import telnetlib
import atexit
import __main__
## do not add code here.
#BEGIN_VERSION_GENERATION
RELEASE_VERSION="3.0.17"
BUILD_DATE="(built Thu Oct 7 07:06:21 UTC 2010)"
REDHAT_COPYRIGHT="Copyright (C) Red Hat, Inc. 2004-2010 All rights reserved."
#END_VERSION_GENERATION
LOG_MODE_VERBOSE = 100
LOG_MODE_QUIET = 0
EC_GENERIC_ERROR = 1
EC_BAD_ARGS = 2
EC_LOGIN_DENIED = 3
EC_CONNECTION_LOST = 4
EC_TIMED_OUT = 5
EC_WAITING_ON = 6
EC_WAITING_OFF = 7
EC_STATUS = 8
EC_STATUS_HMC = 9
TELNET_PATH = "/usr/bin/telnet"
SSH_PATH = "/usr/bin/ssh"
SSL_PATH = "/usr/sbin/fence_nss_wrapper"
all_opt = {
"help" : {
"getopt" : "h",
"longopt" : "help",
"help" : "-h, --help Display this help and exit",
"required" : "0",
"shortdesc" : "Display help and exit",
"order" : 54 },
"version" : {
"getopt" : "V",
"longopt" : "version",
"help" : "-V, --version Output version information and exit",
"required" : "0",
"shortdesc" : "Display version information and exit",
"order" : 53 },
"quiet" : {
"getopt" : "q",
"help" : "",
"order" : 50 },
"verbose" : {
"getopt" : "v",
"longopt" : "verbose",
"help" : "-v, --verbose Verbose mode",
"required" : "0",
"shortdesc" : "Verbose mode",
"order" : 51 },
"debug" : {
"getopt" : "D:",
"longopt" : "debug-file",
"help" : "-D, --debug-file=<debugfile> Debugging to output file",
"required" : "0",
"shortdesc" : "Write debug information to given file",
"order" : 52 },
"delay" : {
"getopt" : "f:",
"longopt" : "delay",
"help" : "--delay <seconds> Wait X seconds before fencing is started",
"required" : "0",
"shortdesc" : "Wait X seconds before fencing is started",
"default" : "0",
"order" : 200 },
"agent" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"web" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"action" : {
"getopt" : "o:",
"longopt" : "action",
"help" : "-o, --action=<action> Action: status, reboot (default), off or on",
"required" : "1",
"shortdesc" : "Fencing Action",
"default" : "reboot",
"order" : 1 },
"io_fencing" : {
"getopt" : "o:",
"longopt" : "action",
"help" : "-o, --action=<action> Action: status, enable or disable",
"required" : "1",
"shortdesc" : "Fencing Action",
"default" : "disable",
"order" : 1 },
"ipaddr" : {
"getopt" : "a:",
"longopt" : "ip",
"help" : "-a, --ip=<ip> IP address or hostname of fencing device",
"required" : "1",
"shortdesc" : "IP Address or Hostname",
"order" : 1 },
"ipport" : {
"getopt" : "u:",
"longopt" : "ipport",
"help" : "-u, --ipport=<port> TCP port to use",
"required" : "0",
"shortdesc" : "TCP port to use for connection with device",
"order" : 1 },
"login" : {
"getopt" : "l:",
"longopt" : "username",
"help" : "-l, --username=<name> Login name",
"required" : "?",
"shortdesc" : "Login Name",
"order" : 1 },
"no_login" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"no_password" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"passwd" : {
"getopt" : "p:",
"longopt" : "password",
"help" : "-p, --password=<password> Login password or passphrase",
"required" : "0",
"shortdesc" : "Login password or passphrase",
"order" : 1 },
"passwd_script" : {
"getopt" : "S:",
"longopt" : "password-script=",
"help" : "-S, --password-script=<script> Script to run to retrieve password",
"required" : "0",
"shortdesc" : "Script to retrieve password",
"order" : 1 },
"identity_file" : {
"getopt" : "k:",
"longopt" : "identity-file",
"help" : "-k, --identity-file=<filename> Identity file (private key) for ssh ",
"required" : "0",
"shortdesc" : "Identity file for ssh",
"order" : 1 },
"module_name" : {
"getopt" : "m:",
"longopt" : "module-name",
"help" : "-m, --module-name=<module> DRAC/MC module name",
"required" : "0",
"shortdesc" : "DRAC/MC module name",
"order" : 1 },
"drac_version" : {
"getopt" : "d:",
"longopt" : "drac-version",
"help" : "-d, --drac-version=<version> Force DRAC version to use",
"required" : "0",
"shortdesc" : "Force DRAC version to use",
"order" : 1 },
"hmc_version" : {
"getopt" : "H:",
"longopt" : "hmc-version",
"help" : "-H, --hmc-version=<version> Force HMC version to use: 3, 4 (default)",
"required" : "0",
"shortdesc" : "Force HMC version to use (3 or 4)",
"default" : "4",
"order" : 1 },
"ribcl" : {
"getopt" : "r:",
"longopt" : "ribcl-version",
"help" : "-r, --ribcl-version=<version> Force ribcl version to use",
"required" : "0",
"shortdesc" : "Force ribcl version to use",
"order" : 1 },
"login_eol_lf" : {
"getopt" : "",
"help" : "",
"order" : 1
},
"cmd_prompt" : {
"getopt" : "c:",
"longopt" : "command-prompt",
"help" : "-c, --command-prompt=<prompt> Force command prompt",
"shortdesc" : "Force command prompt",
"required" : "0",
"order" : 1 },
"secure" : {
"getopt" : "x",
"longopt" : "ssh",
"help" : "-x, --ssh Use ssh connection",
"shortdesc" : "SSH connection",
"required" : "0",
"order" : 1 },
"ssl" : {
"getopt" : "z",
"longopt" : "ssl",
"help" : "-z, --ssl Use ssl connection",
"required" : "0",
"shortdesc" : "SSL connection",
"order" : 1 },
"port" : {
"getopt" : "n:",
"longopt" : "plug",
"help" : "-n, --plug=<id> Physical plug number on device or\n" +
" name of virtual machine",
"required" : "1",
"shortdesc" : "Physical plug number or name of virtual machine",
"order" : 1 },
"switch" : {
"getopt" : "s:",
"longopt" : "switch",
"help" : "-s, --switch=<id> Physical switch number on device",
"required" : "0",
"shortdesc" : "Physical switch number on device",
"order" : 1 },
"partition" : {
"getopt" : "n:",
"help" : "-n <id> Name of the partition",
"required" : "0",
"shortdesc" : "Partition name",
"order" : 1 },
"managed" : {
"getopt" : "s:",
"help" : "-s <id> Name of the managed system",
"required" : "0",
"shortdesc" : "Managed system name",
"order" : 1 },
"test" : {
"getopt" : "T",
"help" : "",
"order" : 1,
"obsolete" : "use -o status instead" },
"exec" : {
"getopt" : "e:",
"longopt" : "exec",
"help" : "-e, --exec=<command> Command to execute",
"required" : "0",
"shortdesc" : "Command to execute",
"order" : 1 },
"vmware_type" : {
"getopt" : "d:",
"longopt" : "vmware_type",
"help" : "-d, --vmware_type=<type> Type of VMware to connect",
"required" : "0",
"shortdesc" : "Type of VMware to connect",
"order" : 1 },
"vmware_datacenter" : {
"getopt" : "s:",
"longopt" : "vmware-datacenter",
"help" : "-s, --vmware-datacenter=<dc> VMWare datacenter filter",
"required" : "0",
"shortdesc" : "Show only machines in specified datacenter",
"order" : 2 },
"snmp_version" : {
"getopt" : "d:",
"longopt" : "snmp-version",
"help" : "-d, --snmp-version=<ver> Specifies SNMP version to use",
"required" : "0",
"shortdesc" : "Specifies SNMP version to use (1,2c,3)",
"order" : 1 },
"community" : {
"getopt" : "c:",
"longopt" : "community",
"help" : "-c, --community=<community> Set the community string",
"required" : "0",
"shortdesc" : "Set the community string",
"order" : 1},
"snmp_auth_prot" : {
"getopt" : "b:",
"longopt" : "snmp-auth-prot",
"help" : "-b, --snmp-auth-prot=<prot> Set authentication protocol (MD5|SHA)",
"required" : "0",
"shortdesc" : "Set authentication protocol (MD5|SHA)",
"order" : 1},
"snmp_sec_level" : {
"getopt" : "E:",
"longopt" : "snmp-sec-level",
"help" : "-E, --snmp-sec-level=<level> Set security level\n"+
" (noAuthNoPriv|authNoPriv|authPriv)",
"required" : "0",
"shortdesc" : "Set security level (noAuthNoPriv|authNoPriv|authPriv)",
"order" : 1},
"snmp_priv_prot" : {
"getopt" : "B:",
"longopt" : "snmp-priv-prot",
"help" : "-B, --snmp-priv-prot=<prot> Set privacy protocol (DES|AES)",
"required" : "0",
"shortdesc" : "Set privacy protocol (DES|AES)",
"order" : 1},
"snmp_priv_passwd" : {
"getopt" : "P:",
"longopt" : "snmp-priv-passwd",
"help" : "-P, --snmp-priv-passwd=<pass> Set privacy protocol password",
"required" : "0",
"shortdesc" : "Set privacy protocol password",
"order" : 1},
"snmp_priv_passwd_script" : {
"getopt" : "R:",
"longopt" : "snmp-priv-passwd-script",
"help" : "-R, --snmp-priv-passwd-script Script to run to retrieve privacy password",
"required" : "0",
"shortdesc" : "Script to run to retrieve privacy password",
"order" : 1},
"inet4_only" : {
"getopt" : "4",
"longopt" : "inet4-only",
"help" : "-4, --inet4-only Forces agent to use IPv4 addresses only",
"required" : "0",
"shortdesc" : "Forces agent to use IPv4 addresses only",
"order" : 1 },
"inet6_only" : {
"getopt" : "6",
"longopt" : "inet6-only",
"help" : "-6, --inet6-only Forces agent to use IPv6 addresses only",
"required" : "0",
"shortdesc" : "Forces agent to use IPv6 addresses only",
"order" : 1 },
"udpport" : {
"getopt" : "u:",
"longopt" : "udpport",
"help" : "-u, --udpport UDP/TCP port to use",
"required" : "0",
"shortdesc" : "UDP/TCP port to use for connection with device",
"order" : 1},
"separator" : {
"getopt" : "C:",
"longopt" : "separator",
"help" : "-C, --separator=<char> Separator for CSV created by 'list' operation",
"default" : ",",
"required" : "0",
"shortdesc" : "Separator for CSV created by operation list",
"order" : 100 },
"login_timeout" : {
"getopt" : "y:",
"longopt" : "login-timeout",
"help" : "--login-timeout <seconds> Wait X seconds for cmd prompt after login",
"default" : "5",
"required" : "0",
"shortdesc" : "Wait X seconds for cmd prompt after login",
"order" : 200 },
"shell_timeout" : {
"getopt" : "Y:",
"longopt" : "shell-timeout",
"help" : "--shell-timeout <seconds> Wait X seconds for cmd prompt after issuing command",
"default" : "3",
"required" : "0",
"shortdesc" : "Wait X seconds for cmd prompt after issuing command",
"order" : 200 },
"power_timeout" : {
"getopt" : "g:",
"longopt" : "power-timeout",
"help" : "--power-timeout <seconds> Test X seconds for status change after ON/OFF",
"default" : "20",
"required" : "0",
"shortdesc" : "Test X seconds for status change after ON/OFF",
"order" : 200 },
"power_wait" : {
"getopt" : "G:",
"longopt" : "power-wait",
"help" : "--power-wait <seconds> Wait X seconds after issuing ON/OFF",
"default" : "0",
"required" : "0",
"shortdesc" : "Wait X seconds after issuing ON/OFF",
"order" : 200 },
"missing_as_off" : {
"getopt" : "M",
"longopt" : "missing-as-off",
"help" : "--missing-as-off Missing port returns OFF instead of failure",
"required" : "0",
"shortdesc" : "Missing port returns OFF instead of failure",
"order" : 200 },
"retry_on" : {
"getopt" : "F:",
"longopt" : "retry-on",
"help" : "--retry-on <attempts> Count of attempts to retry power on",
"default" : "1",
"required" : "0",
"shortdesc" : "Count of attempts to retry power on",
"order" : 200 },
"session_url" : {
"getopt" : "s:",
"longopt" : "session-url",
"help" : "-s, --session-url URL to connect to XenServer on.",
"required" : "1",
"shortdesc" : "The URL of the XenServer host.",
"order" : 1},
"vm_name" : {
"getopt" : "n:",
"longopt" : "vm-name",
"help" : "-n, --vm-name Name of the VM to fence.",
"required" : "0",
"shortdesc" : "The name of the virual machine to fence.",
"order" : 1},
"uuid" : {
"getopt" : "U:",
"longopt" : "uuid",
"help" : "-U, --uuid UUID of the VM to fence.",
"required" : "0",
"shortdesc" : "The UUID of the virtual machine to fence.",
"order" : 1}
}
common_opt = [ "retry_on", "delay" ]
class fspawn(pexpect.spawn):
def log_expect(self, options, pattern, timeout):
result = self.expect(pattern, timeout)
if options["log"] >= LOG_MODE_VERBOSE:
options["debug_fh"].write(self.before + self.after)
return result
def atexit_handler():
try:
sys.stdout.close()
os.close(1)
except IOError:
sys.stderr.write("%s failed to close standard output\n"%(sys.argv[0]))
sys.exit(EC_GENERIC_ERROR)
def version(command, release, build_date, copyright_notice):
print command, " ", release, " ", build_date
if len(copyright_notice) > 0:
print copyright_notice
def fail_usage(message = ""):
if len(message) > 0:
sys.stderr.write(message+"\n")
sys.stderr.write("Please use '-h' for usage\n")
sys.exit(EC_GENERIC_ERROR)
def fail(error_code):
message = {
EC_LOGIN_DENIED : "Unable to connect/login to fencing device",
EC_CONNECTION_LOST : "Connection lost",
EC_TIMED_OUT : "Connection timed out",
EC_WAITING_ON : "Failed: Timed out waiting to power ON",
EC_WAITING_OFF : "Failed: Timed out waiting to power OFF",
EC_STATUS : "Failed: Unable to obtain correct plug status or plug is not available",
EC_STATUS_HMC : "Failed: Either unable to obtaion correct plug status, partition is not available or incorrect HMC version used"
}[error_code] + "\n"
sys.stderr.write(message)
sys.exit(EC_GENERIC_ERROR)
def usage(avail_opt):
global all_opt
print "Usage:"
print "\t" + os.path.basename(sys.argv[0]) + " [options]"
print "Options:"
sorted_list = [ (key, all_opt[key]) for key in avail_opt ]
sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"]))
for key, value in sorted_list:
if len(value["help"]) != 0:
print " " + value["help"]
def metadata(avail_opt, options, docs):
global all_opt
sorted_list = [ (key, all_opt[key]) for key in avail_opt ]
sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"]))
print "<?xml version=\"1.0\" ?>"
print "<resource-agent name=\"" + os.path.basename(sys.argv[0]) + "\" shortdesc=\"" + docs["shortdesc"] + "\" >"
print "<longdesc>" + docs["longdesc"] + "</longdesc>"
if docs.has_key("vendorurl"):
print "<vendor-url>" + docs["vendorurl"] + "</vendor-url>"
print "<parameters>"
for option, value in sorted_list:
if all_opt[option].has_key("shortdesc"):
print "\t<parameter name=\"" + option + "\" unique=\"1\" required=\"" + all_opt[option]["required"] + "\">"
default = ""
if all_opt[option].has_key("default"):
default = "default=\""+str(all_opt[option]["default"])+"\""
elif options.has_key("-" + all_opt[option]["getopt"][:-1]):
if options["-" + all_opt[option]["getopt"][:-1]]:
try:
default = "default=\"" + options["-" + all_opt[option]["getopt"][:-1]] + "\""
except TypeError:
## @todo/@note: Currently there is no clean way how to handle lists
## we can create a string from it but we can't set it on command line
default = "default=\"" + str(options["-" + all_opt[option]["getopt"][:-1]]) +"\""
elif options.has_key("-" + all_opt[option]["getopt"]):
default = "default=\"true\" "
mixed = all_opt[option]["help"]
## split it between option and help text
res = re.compile("^(.*--\S+)\s+", re.IGNORECASE | re.S).search(mixed)
if (None != res):
mixed = res.group(1)
mixed = mixed.replace("<", "<").replace(">", ">")
print "\t\t<getopt mixed=\"" + mixed + "\" />"
if all_opt[option]["getopt"].count(":") > 0:
print "\t\t<content type=\"string\" "+default+" />"
else:
print "\t\t<content type=\"boolean\" "+default+" />"
print "\t\t<shortdesc lang=\"en\">" + all_opt[option]["shortdesc"] + "</shortdesc>"
print "\t</parameter>"
print "</parameters>"
print "<actions>"
print "\t<action name=\"on\" />"
print "\t<action name=\"off\" />"
print "\t<action name=\"reboot\" />"
print "\t<action name=\"status\" />"
print "\t<action name=\"list\" />"
print "\t<action name=\"monitor\" />"
print "\t<action name=\"metadata\" />"
print "</actions>"
print "</resource-agent>"
def process_input(avail_opt):
global all_opt
global common_opt
##
## Add options which are available for every fence agent
#####
avail_opt.extend(common_opt)
##
## Set standard environment
#####
os.putenv("LANG", "C")
os.putenv("LC_ALL", "C")
##
## Prepare list of options for getopt
#####
getopt_string = ""
longopt_list = [ ]
for k in avail_opt:
if all_opt.has_key(k):
getopt_string += all_opt[k]["getopt"]
else:
fail_usage("Parse error: unknown option '"+k+"'")
if all_opt.has_key(k) and all_opt[k].has_key("longopt"):
if all_opt[k]["getopt"].endswith(":"):
longopt_list.append(all_opt[k]["longopt"] + "=")
else:
longopt_list.append(all_opt[k]["longopt"])
## Compatibility layer
if avail_opt.count("module_name") == 1:
getopt_string += "n:"
longopt_list.append("plug=")
##
## Read options from command line or standard input
#####
if len(sys.argv) > 1:
try:
opt, args = getopt.gnu_getopt(sys.argv[1:], getopt_string, longopt_list)
except getopt.GetoptError, error:
fail_usage("Parse error: " + error.msg)
## Transform longopt to short one which are used in fencing agents
#####
old_opt = opt
opt = { }
for o in dict(old_opt).keys():
if o.startswith("--"):
for x in all_opt.keys():
if all_opt[x].has_key("longopt") and "--" + all_opt[x]["longopt"] == o:
opt["-" + all_opt[x]["getopt"].rstrip(":")] = dict(old_opt)[o]
else:
opt[o] = dict(old_opt)[o]
## Compatibility Layer
#####
z = dict(opt)
if z.has_key("-T") == 1:
z["-o"] = "status"
if z.has_key("-n") == 1:
z["-m"] = z["-n"]
opt = z
##
#####
else:
opt = { }
name = ""
for line in sys.stdin.readlines():
line = line.strip()
if ((line.startswith("#")) or (len(line) == 0)):
continue
(name, value) = (line + "=").split("=", 1)
value = value[:-1]
## Compatibility Layer
######
if name == "blade":
name = "port"
elif name == "option":
name = "action"
elif name == "fm":
name = "port"
elif name == "hostname":
name = "ipaddr"
elif name == "modulename":
name = "module_name"
elif name == "action" and 1 == avail_opt.count("io_fencing"):
name = "io_fencing"
elif name == "port" and 1 == avail_opt.count("drac_version"):
name = "module_name"
##
######
if avail_opt.count(name) == 0:
sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n")
continue
if all_opt[name]["getopt"].endswith(":"):
opt["-"+all_opt[name]["getopt"].rstrip(":")] = value
elif ((value == "1") or (value.lower() == "yes")):
opt["-"+all_opt[name]["getopt"]] = "1"
return opt
##
## This function checks input and answers if we want to have same answers
## in each of the fencing agents. It looks for possible errors and run
## password script to set a correct password
######
def check_input(device_opt, opt):
global all_opt
global common_opt
##
## Add options which are available for every fence agent
#####
device_opt.extend([x for x in common_opt if device_opt.count(x) == 0])
options = dict(opt)
options["device_opt"] = device_opt
## Set requirements that should be included in metadata
#####
if device_opt.count("login") and device_opt.count("no_login") == 0:
all_opt["login"]["required"] = "1"
else:
all_opt["login"]["required"] = "0"
## In special cases (show help, metadata or version) we don't need to check anything
#####
if options.has_key("-h") or options.has_key("-V") or (options.has_key("-o") and options["-o"].lower() == "metadata"):
return options;
## Set default values
#####
for opt in device_opt:
if all_opt[opt].has_key("default"):
getopt = "-" + all_opt[opt]["getopt"].rstrip(":")
if 0 == options.has_key(getopt):
options[getopt] = all_opt[opt]["default"]
options["-o"]=options["-o"].lower()
if options.has_key("-v"):
options["log"] = LOG_MODE_VERBOSE
else:
options["log"] = LOG_MODE_QUIET
if 0 == device_opt.count("io_fencing"):
if 0 == ["on", "off", "reboot", "status", "list", "monitor"].count(options["-o"].lower()):
fail_usage("Failed: Unrecognised action '" + options["-o"] + "'")
else:
if 0 == ["enable", "disable", "status", "list", "monitor"].count(options["-o"].lower()):
fail_usage("Failed: Unrecognised action '" + options["-o"] + "'")
if (0 == options.has_key("-l")) and device_opt.count("login") and (device_opt.count("no_login") == 0):
fail_usage("Failed: You have to set login name")
if 0 == options.has_key("-a") and 0 == options.has_key("-s"):
fail_usage("Failed: You have to enter fence address")
if (0 == ["list", "monitor"].count(options["-o"].lower())) and device_opt.count("vm_name") and device_opt.count("uuid"):
if 0 == options.has_key("-n") and 0 == options.has_key("-U"):
fail_usage("Failed: You must specify either UUID or VM name")
if (device_opt.count("no_password") == 0):
if 0 == device_opt.count("identity_file"):
if 0 == (options.has_key("-p") or options.has_key("-S")):
fail_usage("Failed: You have to enter password or password script")
else:
if 0 == (options.has_key("-p") or options.has_key("-S") or options.has_key("-k")):
fail_usage("Failed: You have to enter password, password script or identity file")
if 0 == options.has_key("-x") and 1 == options.has_key("-k"):
fail_usage("Failed: You have to use identity file together with ssh connection (-x)")
if 1 == options.has_key("-k"):
if 0 == os.path.isfile(options["-k"]):
fail_usage("Failed: Identity file " + options["-k"] + " does not exist")
if (0 == ["list", "monitor"].count(options["-o"].lower())) and (0 == options.has_key("-n")) and (device_opt.count("port")):
fail_usage("Failed: You have to enter plug number")
if options.has_key("-S"):
options["-p"] = os.popen(options["-S"]).read().rstrip()
if options.has_key("-D"):
try:
options["debug_fh"] = file (options["-D"], "w")
except IOError:
fail_usage("Failed: Unable to create file "+options["-D"])
if options.has_key("-v") and options.has_key("debug_fh") == 0:
options["debug_fh"] = sys.stderr
if options.has_key("-R"):
options["-P"] = os.popen(options["-R"]).read().rstrip()
if options.has_key("-u") == False:
if options.has_key("-x"):
options["-u"] = 22
elif options.has_key("-z"):
options["-u"] = 443
elif device_opt.count("web"):
options["-u"] = 80
else:
options["-u"] = 23
return options
def wait_power_status(tn, options, get_power_fn):
for dummy in xrange(int(options["-g"])):
if get_power_fn(tn, options) != options["-o"]:
time.sleep(1)
else:
return 1
return 0
def show_docs(options, docs = None):
device_opt = options["device_opt"]
if docs == None:
docs = { }
docs["shortdesc"] = "Fence agent"
docs["longdesc"] = ""
## Process special options (and exit)
#####
if options.has_key("-h"):
usage(device_opt)
sys.exit(0)
if options.has_key("-o") and options["-o"].lower() == "metadata":
metadata(device_opt, options, docs)
sys.exit(0)
if options.has_key("-V"):
print __main__.RELEASE_VERSION, __main__.BUILD_DATE
print __main__.REDHAT_COPYRIGHT
sys.exit(0)
def fence_action(tn, options, set_power_fn, get_power_fn, get_outlet_list = None):
result = 0
## Process options that manipulate fencing device
#####
if (options["-o"] == "list") and (0 == options["device_opt"].count("port")) and (0 == options["device_opt"].count("partition")) and (0 == options["device_opt"].count("uuid")):
print "N/A"
return
elif (options["-o"] == "list" and get_outlet_list == None):
## @todo: exception?
## This is just temporal solution, we will remove default value
## None as soon as all existing agent will support this operation
print "NOTICE: List option is not working on this device yet"
return
elif (options["-o"] == "list") or ((options["-o"] == "monitor") and 1 == options["device_opt"].count("port")):
outlets = get_outlet_list(tn, options)
## keys can be numbers (port numbers) or strings (names of VM)
for o in outlets.keys():
(alias, status) = outlets[o]
if options["-o"] != "monitor":
print o + options["-C"] + alias
return
if options["-o"] in ["off", "reboot"]:
time.sleep(int(options["-f"]))
status = get_power_fn(tn, options)
if status != "on" and status != "off":
fail(EC_STATUS)
if options["-o"] == "enable":
options["-o"] = "on"
if options["-o"] == "disable":
options["-o"] = "off"
if options["-o"] == "on":
if status == "on":
print "Success: Already ON"
else:
power_on = False
for i in range(1,1 + int(options["-F"])):
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn):
power_on = True
break
if power_on:
print "Success: Powered ON"
else:
fail(EC_WAITING_ON)
elif options["-o"] == "off":
if status == "off":
print "Success: Already OFF"
else:
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn):
print "Success: Powered OFF"
else:
fail(EC_WAITING_OFF)
elif options["-o"] == "reboot":
if status != "off":
options["-o"] = "off"
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn) == 0:
fail(EC_WAITING_OFF)
options["-o"] = "on"
power_on = False
for i in range(1,1 + int(options["-F"])):
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn) == 1:
power_on = True
break
if power_on == False:
# this should not fail as not was fenced succesfully
sys.stderr.write('Timed out waiting to power ON\n')
print "Success: Rebooted"
elif options["-o"] == "status":
print "Status: " + status.upper()
if status.upper() == "OFF":
result = 2
elif options["-o"] == "monitor":
1
return result
def fence_login(options):
force_ipvx=""
if (options.has_key("-6")):
force_ipvx="-6 "
if (options.has_key("-4")):
force_ipvx="-4 "
if (options["device_opt"].count("login_eol_lf")):
login_eol = "\n"
else:
login_eol = "\r\n"
try:
re_login = re.compile("(login\s*: )|(Login Name: )|(username: )|(User Name :)", re.IGNORECASE)
re_pass = re.compile("password", re.IGNORECASE)
if options.has_key("-z"):
command = '%s %s %s %s' % (SSL_PATH, force_ipvx, options["-a"], options["-u"])
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
## SSL telnet is part of the fencing package
sys.stderr.write(str(ex) + "\n")
sys.exit(EC_GENERIC_ERROR)
elif options.has_key("-x") and 0 == options.has_key("-k"):
command = '%s %s %s@%s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-u"])
if options.has_key("ssh_options"):
command += ' ' + options["ssh_options"]
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
if options.has_key("telnet_over_ssh"):
#This is for stupid ssh servers (like ALOM) which behave more like telnet (ignore name and display login prompt)
result = conn.log_expect(options, [ re_login, "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"]))
if result == 1:
conn.sendline("yes") # Host identity confirm
conn.log_expect(options, re_login, int(options["-y"]))
conn.sendline(options["-l"])
conn.log_expect(options, re_pass, int(options["-y"]))
else:
result = conn.log_expect(options, [ "ssword:", "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"]))
if result == 1:
conn.sendline("yes")
conn.log_expect(options, "ssword:", int(options["-y"]))
conn.sendline(options["-p"])
conn.log_expect(options, options["-c"], int(options["-y"]))
elif options.has_key("-x") and 1 == options.has_key("-k"):
command = '%s %s %s@%s -i %s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-k"], options["-u"])
if options.has_key("ssh_options"):
command += ' ' + options["ssh_options"]
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
result = conn.log_expect(options, [ options["-c"], "Are you sure you want to continue connecting (yes/no)?", "Enter passphrase for key '"+options["-k"]+"':" ], int(options["-y"]))
if result == 1:
conn.sendline("yes")
conn.log_expect(options, [ options["-c"], "Enter passphrase for key '"+options["-k"]+"':"] , int(options["-y"]))
if result != 0:
if options.has_key("-p"):
conn.sendline(options["-p"])
conn.log_expect(options, options["-c"], int(options["-y"]))
else:
fail_usage("Failed: You have to enter passphrase (-p) for identity file")
else:
try:
conn = fspawn(TELNET_PATH)
conn.send("set binary\n")
conn.send("open %s -%s\n"%(options["-a"], options["-u"]))
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
conn.log_expect(options, re_login, int(options["-y"]))
conn.send(options["-l"] + login_eol)
conn.log_expect(options, re_pass, int(options["-Y"]))
conn.send(options["-p"] + login_eol)
conn.log_expect(options, options["-c"], int(options["-Y"]))
except pexpect.EOF:
fail(EC_LOGIN_DENIED)
except pexpect.TIMEOUT:
fail(EC_LOGIN_DENIED)
return conn
| Python |
#!/usr/bin/python
#
#############################################################################
# Copyright 2011 Matt Clark
# This file is part of fence-xenserver
#
# fence-xenserver is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# fence-xenserver is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
#############################################################################
#############################################################################
# It's only just begun...
# Current status: completely usable. This script is now working well and,
# has a lot of functionality as a result of the fencing.py library and the
# XenAPI libary.
#############################################################################
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
import sys
sys.path.append("/usr/lib/fence")
from fencing import *
import XenAPI
EC_BAD_SESSION = 1
# Find the status of the port given in the -U flag of options.
def get_power_fn(session, options):
if options.has_key("-v"):
verbose = True
else:
verbose = False
try:
# Get a reference to the vm specified in the UUID or vm_name parameter
vm = return_vm_reference(session, options)
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm);
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
status = record["power_state"]
if verbose: print "UUID:", record["uuid"], "NAME:", record["name_label"], "POWER STATUS:", record["power_state"]
# Note that the VM can be in the following states (from the XenAPI document)
# Halted: VM is offline and not using any resources.
# Paused: All resources have been allocated but the VM itself is paused and its vCPUs are not running
# Running: Running
# Paused: VM state has been saved to disk and it is nolonger running. Note that disks remain in-Use while
# We want to make sure that we only return the status "off" if the machine is actually halted as the status
# is checked before a fencing action. Only when the machine is Halted is it not consuming resources which
# may include whatever you are trying to protect with this fencing action.
return (status=="Halted" and "off" or "on")
except Exception, exn:
print str(exn)
return "Error"
# Set the state of the port given in the -U flag of options.
def set_power_fn(session, options):
action = options["-o"].lower()
if options.has_key("-v"):
verbose = True
else:
verbose = False
try:
# Get a reference to the vm specified in the UUID or vm_name parameter
vm = return_vm_reference(session, options)
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm)
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
# Start the VM
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
# Force shutdown the VM
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
# Force reboot the VM
session.xenapi.VM.hard_reboot(vm)
except Exception, exn:
print str(exn);
# Function to populate an array of virtual machines and their status
def get_outlet_list(session, options):
result = {}
if options.has_key("-v"):
verbose = True
else:
verbose = False
try:
# Return an array of all the VM's on the host
vms = session.xenapi.VM.get_all()
for vm in vms:
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm);
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
uuid = record["uuid"]
status = record["power_state"]
result[uuid] = (name, status)
if verbose: print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
return result
# Function to initiate the XenServer session via the XenAPI library.
def connect_and_login(options):
url = options["-s"]
username = options["-l"]
password = options["-p"]
try:
# Create the XML RPC session to the specified URL.
session = XenAPI.Session(url);
# Login using the supplied credentials.
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
# http://sources.redhat.com/cluster/wiki/FenceAgentAPI says that for no connectivity
# the exit value should be 1. It doesn't say anything about failed logins, so
# until I hear otherwise it is best to keep this exit the same to make sure that
# anything calling this script (that uses the same information in the web page
# above) knows that this is an error condition, not a msg signifying a down port.
sys.exit(EC_BAD_SESSION);
return session;
# return a reference to the VM by either using the UUID or the vm_name. If the UUID is set then
# this is tried first as this is the only properly unique identifier.
# Exceptions are not handled in this function, code that calls this must be ready to handle them.
def return_vm_reference(session, options):
if options.has_key("-v"):
verbose = True
else:
verbose = False
# Case where the UUID has been specified
if options.has_key("-U"):
uuid = options["-U"].lower()
# When using the -n parameter for name, we get an error message (in verbose
# mode) that tells us that we didn't find a VM. To immitate that here we
# need to catch and re-raise the exception produced by get_by_uuid.
try:
return session.xenapi.VM.get_by_uuid(uuid)
except Exception,exn:
if verbose: print "No VM's found with a UUID of \"%s\"" %uuid
raise
# Case where the vm_name has been specified
if options.has_key("-n"):
vm_name = options["-n"]
vm_arr = session.xenapi.VM.get_by_name_label(vm_name)
# Need to make sure that we only have one result as the vm_name may
# not be unique. Average case, so do it first.
if len(vm_arr) == 1:
return vm_arr[0]
else:
if len(vm_arr) == 0:
if verbose: print "No VM's found with a name of \"%s\"" %vm_name
# NAME_INVALID used as the XenAPI throws a UUID_INVALID if it can't find
# a VM with the specified UUID. This should make the output look fairly
# consistent.
raise Exception("NAME_INVALID")
else:
if verbose: print "Multiple VM's have the name \"%s\", use UUID instead" %vm_name
raise Exception("MULTIPLE_VMS_FOUND")
# We should never get to this case as the input processing checks that either the UUID or
# the name parameter is set. Regardless of whether or not a VM is found the above if
# statements will return to the calling function (either by exception or by a reference
# to the VM).
raise Exception("VM_LOGIC_ERROR")
def main():
device_opt = [ "help", "version", "agent", "quiet", "verbose", "debug", "action",
"login", "passwd", "passwd_script", "vm_name", "test", "separator",
"no_login", "no_password", "power_timeout", "shell_timeout",
"login_timeout", "power_wait", "session_url", "uuid" ]
atexit.register(atexit_handler)
options=process_input(device_opt)
options = check_input(device_opt, options)
docs = { }
docs["shortdesc"] = "XenAPI based fencing for the Citrix XenServer virtual machines."
docs["longdesc"] = "\
fence_cxs is an I/O Fencing agent used on Citrix XenServer hosts. \
It uses the XenAPI, supplied by Citrix, to establish an XML-RPC sesssion \
to a XenServer host. Once the session is established, further XML-RPC \
commands are issued in order to switch on, switch off, restart and query \
the status of virtual machines running on the host."
show_docs(options, docs)
xenSession = connect_and_login(options)
# Operate the fencing device
result = fence_action(xenSession, options, set_power_fn, get_power_fn, get_outlet_list)
sys.exit(result)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
import sys, getopt, time, os
import pexpect, re
import telnetlib
import atexit
import __main__
## do not add code here.
#BEGIN_VERSION_GENERATION
RELEASE_VERSION="3.0.17"
BUILD_DATE="(built Thu Oct 7 07:06:21 UTC 2010)"
REDHAT_COPYRIGHT="Copyright (C) Red Hat, Inc. 2004-2010 All rights reserved."
#END_VERSION_GENERATION
LOG_MODE_VERBOSE = 100
LOG_MODE_QUIET = 0
EC_GENERIC_ERROR = 1
EC_BAD_ARGS = 2
EC_LOGIN_DENIED = 3
EC_CONNECTION_LOST = 4
EC_TIMED_OUT = 5
EC_WAITING_ON = 6
EC_WAITING_OFF = 7
EC_STATUS = 8
EC_STATUS_HMC = 9
TELNET_PATH = "/usr/bin/telnet"
SSH_PATH = "/usr/bin/ssh"
SSL_PATH = "/usr/sbin/fence_nss_wrapper"
all_opt = {
"help" : {
"getopt" : "h",
"longopt" : "help",
"help" : "-h, --help Display this help and exit",
"required" : "0",
"shortdesc" : "Display help and exit",
"order" : 54 },
"version" : {
"getopt" : "V",
"longopt" : "version",
"help" : "-V, --version Output version information and exit",
"required" : "0",
"shortdesc" : "Display version information and exit",
"order" : 53 },
"quiet" : {
"getopt" : "q",
"help" : "",
"order" : 50 },
"verbose" : {
"getopt" : "v",
"longopt" : "verbose",
"help" : "-v, --verbose Verbose mode",
"required" : "0",
"shortdesc" : "Verbose mode",
"order" : 51 },
"debug" : {
"getopt" : "D:",
"longopt" : "debug-file",
"help" : "-D, --debug-file=<debugfile> Debugging to output file",
"required" : "0",
"shortdesc" : "Write debug information to given file",
"order" : 52 },
"delay" : {
"getopt" : "f:",
"longopt" : "delay",
"help" : "--delay <seconds> Wait X seconds before fencing is started",
"required" : "0",
"shortdesc" : "Wait X seconds before fencing is started",
"default" : "0",
"order" : 200 },
"agent" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"web" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"action" : {
"getopt" : "o:",
"longopt" : "action",
"help" : "-o, --action=<action> Action: status, reboot (default), off or on",
"required" : "1",
"shortdesc" : "Fencing Action",
"default" : "reboot",
"order" : 1 },
"io_fencing" : {
"getopt" : "o:",
"longopt" : "action",
"help" : "-o, --action=<action> Action: status, enable or disable",
"required" : "1",
"shortdesc" : "Fencing Action",
"default" : "disable",
"order" : 1 },
"ipaddr" : {
"getopt" : "a:",
"longopt" : "ip",
"help" : "-a, --ip=<ip> IP address or hostname of fencing device",
"required" : "1",
"shortdesc" : "IP Address or Hostname",
"order" : 1 },
"ipport" : {
"getopt" : "u:",
"longopt" : "ipport",
"help" : "-u, --ipport=<port> TCP port to use",
"required" : "0",
"shortdesc" : "TCP port to use for connection with device",
"order" : 1 },
"login" : {
"getopt" : "l:",
"longopt" : "username",
"help" : "-l, --username=<name> Login name",
"required" : "?",
"shortdesc" : "Login Name",
"order" : 1 },
"no_login" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"no_password" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"passwd" : {
"getopt" : "p:",
"longopt" : "password",
"help" : "-p, --password=<password> Login password or passphrase",
"required" : "0",
"shortdesc" : "Login password or passphrase",
"order" : 1 },
"passwd_script" : {
"getopt" : "S:",
"longopt" : "password-script=",
"help" : "-S, --password-script=<script> Script to run to retrieve password",
"required" : "0",
"shortdesc" : "Script to retrieve password",
"order" : 1 },
"identity_file" : {
"getopt" : "k:",
"longopt" : "identity-file",
"help" : "-k, --identity-file=<filename> Identity file (private key) for ssh ",
"required" : "0",
"shortdesc" : "Identity file for ssh",
"order" : 1 },
"module_name" : {
"getopt" : "m:",
"longopt" : "module-name",
"help" : "-m, --module-name=<module> DRAC/MC module name",
"required" : "0",
"shortdesc" : "DRAC/MC module name",
"order" : 1 },
"drac_version" : {
"getopt" : "d:",
"longopt" : "drac-version",
"help" : "-d, --drac-version=<version> Force DRAC version to use",
"required" : "0",
"shortdesc" : "Force DRAC version to use",
"order" : 1 },
"hmc_version" : {
"getopt" : "H:",
"longopt" : "hmc-version",
"help" : "-H, --hmc-version=<version> Force HMC version to use: 3, 4 (default)",
"required" : "0",
"shortdesc" : "Force HMC version to use (3 or 4)",
"default" : "4",
"order" : 1 },
"ribcl" : {
"getopt" : "r:",
"longopt" : "ribcl-version",
"help" : "-r, --ribcl-version=<version> Force ribcl version to use",
"required" : "0",
"shortdesc" : "Force ribcl version to use",
"order" : 1 },
"login_eol_lf" : {
"getopt" : "",
"help" : "",
"order" : 1
},
"cmd_prompt" : {
"getopt" : "c:",
"longopt" : "command-prompt",
"help" : "-c, --command-prompt=<prompt> Force command prompt",
"shortdesc" : "Force command prompt",
"required" : "0",
"order" : 1 },
"secure" : {
"getopt" : "x",
"longopt" : "ssh",
"help" : "-x, --ssh Use ssh connection",
"shortdesc" : "SSH connection",
"required" : "0",
"order" : 1 },
"ssl" : {
"getopt" : "z",
"longopt" : "ssl",
"help" : "-z, --ssl Use ssl connection",
"required" : "0",
"shortdesc" : "SSL connection",
"order" : 1 },
"port" : {
"getopt" : "n:",
"longopt" : "plug",
"help" : "-n, --plug=<id> Physical plug number on device or\n" +
" name of virtual machine",
"required" : "1",
"shortdesc" : "Physical plug number or name of virtual machine",
"order" : 1 },
"switch" : {
"getopt" : "s:",
"longopt" : "switch",
"help" : "-s, --switch=<id> Physical switch number on device",
"required" : "0",
"shortdesc" : "Physical switch number on device",
"order" : 1 },
"partition" : {
"getopt" : "n:",
"help" : "-n <id> Name of the partition",
"required" : "0",
"shortdesc" : "Partition name",
"order" : 1 },
"managed" : {
"getopt" : "s:",
"help" : "-s <id> Name of the managed system",
"required" : "0",
"shortdesc" : "Managed system name",
"order" : 1 },
"test" : {
"getopt" : "T",
"help" : "",
"order" : 1,
"obsolete" : "use -o status instead" },
"exec" : {
"getopt" : "e:",
"longopt" : "exec",
"help" : "-e, --exec=<command> Command to execute",
"required" : "0",
"shortdesc" : "Command to execute",
"order" : 1 },
"vmware_type" : {
"getopt" : "d:",
"longopt" : "vmware_type",
"help" : "-d, --vmware_type=<type> Type of VMware to connect",
"required" : "0",
"shortdesc" : "Type of VMware to connect",
"order" : 1 },
"vmware_datacenter" : {
"getopt" : "s:",
"longopt" : "vmware-datacenter",
"help" : "-s, --vmware-datacenter=<dc> VMWare datacenter filter",
"required" : "0",
"shortdesc" : "Show only machines in specified datacenter",
"order" : 2 },
"snmp_version" : {
"getopt" : "d:",
"longopt" : "snmp-version",
"help" : "-d, --snmp-version=<ver> Specifies SNMP version to use",
"required" : "0",
"shortdesc" : "Specifies SNMP version to use (1,2c,3)",
"order" : 1 },
"community" : {
"getopt" : "c:",
"longopt" : "community",
"help" : "-c, --community=<community> Set the community string",
"required" : "0",
"shortdesc" : "Set the community string",
"order" : 1},
"snmp_auth_prot" : {
"getopt" : "b:",
"longopt" : "snmp-auth-prot",
"help" : "-b, --snmp-auth-prot=<prot> Set authentication protocol (MD5|SHA)",
"required" : "0",
"shortdesc" : "Set authentication protocol (MD5|SHA)",
"order" : 1},
"snmp_sec_level" : {
"getopt" : "E:",
"longopt" : "snmp-sec-level",
"help" : "-E, --snmp-sec-level=<level> Set security level\n"+
" (noAuthNoPriv|authNoPriv|authPriv)",
"required" : "0",
"shortdesc" : "Set security level (noAuthNoPriv|authNoPriv|authPriv)",
"order" : 1},
"snmp_priv_prot" : {
"getopt" : "B:",
"longopt" : "snmp-priv-prot",
"help" : "-B, --snmp-priv-prot=<prot> Set privacy protocol (DES|AES)",
"required" : "0",
"shortdesc" : "Set privacy protocol (DES|AES)",
"order" : 1},
"snmp_priv_passwd" : {
"getopt" : "P:",
"longopt" : "snmp-priv-passwd",
"help" : "-P, --snmp-priv-passwd=<pass> Set privacy protocol password",
"required" : "0",
"shortdesc" : "Set privacy protocol password",
"order" : 1},
"snmp_priv_passwd_script" : {
"getopt" : "R:",
"longopt" : "snmp-priv-passwd-script",
"help" : "-R, --snmp-priv-passwd-script Script to run to retrieve privacy password",
"required" : "0",
"shortdesc" : "Script to run to retrieve privacy password",
"order" : 1},
"inet4_only" : {
"getopt" : "4",
"longopt" : "inet4-only",
"help" : "-4, --inet4-only Forces agent to use IPv4 addresses only",
"required" : "0",
"shortdesc" : "Forces agent to use IPv4 addresses only",
"order" : 1 },
"inet6_only" : {
"getopt" : "6",
"longopt" : "inet6-only",
"help" : "-6, --inet6-only Forces agent to use IPv6 addresses only",
"required" : "0",
"shortdesc" : "Forces agent to use IPv6 addresses only",
"order" : 1 },
"udpport" : {
"getopt" : "u:",
"longopt" : "udpport",
"help" : "-u, --udpport UDP/TCP port to use",
"required" : "0",
"shortdesc" : "UDP/TCP port to use for connection with device",
"order" : 1},
"separator" : {
"getopt" : "C:",
"longopt" : "separator",
"help" : "-C, --separator=<char> Separator for CSV created by 'list' operation",
"default" : ",",
"required" : "0",
"shortdesc" : "Separator for CSV created by operation list",
"order" : 100 },
"login_timeout" : {
"getopt" : "y:",
"longopt" : "login-timeout",
"help" : "--login-timeout <seconds> Wait X seconds for cmd prompt after login",
"default" : "5",
"required" : "0",
"shortdesc" : "Wait X seconds for cmd prompt after login",
"order" : 200 },
"shell_timeout" : {
"getopt" : "Y:",
"longopt" : "shell-timeout",
"help" : "--shell-timeout <seconds> Wait X seconds for cmd prompt after issuing command",
"default" : "3",
"required" : "0",
"shortdesc" : "Wait X seconds for cmd prompt after issuing command",
"order" : 200 },
"power_timeout" : {
"getopt" : "g:",
"longopt" : "power-timeout",
"help" : "--power-timeout <seconds> Test X seconds for status change after ON/OFF",
"default" : "20",
"required" : "0",
"shortdesc" : "Test X seconds for status change after ON/OFF",
"order" : 200 },
"power_wait" : {
"getopt" : "G:",
"longopt" : "power-wait",
"help" : "--power-wait <seconds> Wait X seconds after issuing ON/OFF",
"default" : "0",
"required" : "0",
"shortdesc" : "Wait X seconds after issuing ON/OFF",
"order" : 200 },
"missing_as_off" : {
"getopt" : "M",
"longopt" : "missing-as-off",
"help" : "--missing-as-off Missing port returns OFF instead of failure",
"required" : "0",
"shortdesc" : "Missing port returns OFF instead of failure",
"order" : 200 },
"retry_on" : {
"getopt" : "F:",
"longopt" : "retry-on",
"help" : "--retry-on <attempts> Count of attempts to retry power on",
"default" : "1",
"required" : "0",
"shortdesc" : "Count of attempts to retry power on",
"order" : 200 },
"session_url" : {
"getopt" : "s:",
"longopt" : "session-url",
"help" : "-s, --session-url URL to connect to XenServer on.",
"required" : "1",
"shortdesc" : "The URL of the XenServer host.",
"order" : 1},
"vm_name" : {
"getopt" : "n:",
"longopt" : "vm-name",
"help" : "-n, --vm-name Name of the VM to fence.",
"required" : "0",
"shortdesc" : "The name of the virual machine to fence.",
"order" : 1},
"uuid" : {
"getopt" : "U:",
"longopt" : "uuid",
"help" : "-U, --uuid UUID of the VM to fence.",
"required" : "0",
"shortdesc" : "The UUID of the virtual machine to fence.",
"order" : 1}
}
common_opt = [ "retry_on", "delay" ]
class fspawn(pexpect.spawn):
def log_expect(self, options, pattern, timeout):
result = self.expect(pattern, timeout)
if options["log"] >= LOG_MODE_VERBOSE:
options["debug_fh"].write(self.before + self.after)
return result
def atexit_handler():
try:
sys.stdout.close()
os.close(1)
except IOError:
sys.stderr.write("%s failed to close standard output\n"%(sys.argv[0]))
sys.exit(EC_GENERIC_ERROR)
def version(command, release, build_date, copyright_notice):
print command, " ", release, " ", build_date
if len(copyright_notice) > 0:
print copyright_notice
def fail_usage(message = ""):
if len(message) > 0:
sys.stderr.write(message+"\n")
sys.stderr.write("Please use '-h' for usage\n")
sys.exit(EC_GENERIC_ERROR)
def fail(error_code):
message = {
EC_LOGIN_DENIED : "Unable to connect/login to fencing device",
EC_CONNECTION_LOST : "Connection lost",
EC_TIMED_OUT : "Connection timed out",
EC_WAITING_ON : "Failed: Timed out waiting to power ON",
EC_WAITING_OFF : "Failed: Timed out waiting to power OFF",
EC_STATUS : "Failed: Unable to obtain correct plug status or plug is not available",
EC_STATUS_HMC : "Failed: Either unable to obtaion correct plug status, partition is not available or incorrect HMC version used"
}[error_code] + "\n"
sys.stderr.write(message)
sys.exit(EC_GENERIC_ERROR)
def usage(avail_opt):
global all_opt
print "Usage:"
print "\t" + os.path.basename(sys.argv[0]) + " [options]"
print "Options:"
sorted_list = [ (key, all_opt[key]) for key in avail_opt ]
sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"]))
for key, value in sorted_list:
if len(value["help"]) != 0:
print " " + value["help"]
def metadata(avail_opt, options, docs):
global all_opt
sorted_list = [ (key, all_opt[key]) for key in avail_opt ]
sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"]))
print "<?xml version=\"1.0\" ?>"
print "<resource-agent name=\"" + os.path.basename(sys.argv[0]) + "\" shortdesc=\"" + docs["shortdesc"] + "\" >"
print "<longdesc>" + docs["longdesc"] + "</longdesc>"
if docs.has_key("vendorurl"):
print "<vendor-url>" + docs["vendorurl"] + "</vendor-url>"
print "<parameters>"
for option, value in sorted_list:
if all_opt[option].has_key("shortdesc"):
print "\t<parameter name=\"" + option + "\" unique=\"1\" required=\"" + all_opt[option]["required"] + "\">"
default = ""
if all_opt[option].has_key("default"):
default = "default=\""+str(all_opt[option]["default"])+"\""
elif options.has_key("-" + all_opt[option]["getopt"][:-1]):
if options["-" + all_opt[option]["getopt"][:-1]]:
try:
default = "default=\"" + options["-" + all_opt[option]["getopt"][:-1]] + "\""
except TypeError:
## @todo/@note: Currently there is no clean way how to handle lists
## we can create a string from it but we can't set it on command line
default = "default=\"" + str(options["-" + all_opt[option]["getopt"][:-1]]) +"\""
elif options.has_key("-" + all_opt[option]["getopt"]):
default = "default=\"true\" "
mixed = all_opt[option]["help"]
## split it between option and help text
res = re.compile("^(.*--\S+)\s+", re.IGNORECASE | re.S).search(mixed)
if (None != res):
mixed = res.group(1)
mixed = mixed.replace("<", "<").replace(">", ">")
print "\t\t<getopt mixed=\"" + mixed + "\" />"
if all_opt[option]["getopt"].count(":") > 0:
print "\t\t<content type=\"string\" "+default+" />"
else:
print "\t\t<content type=\"boolean\" "+default+" />"
print "\t\t<shortdesc lang=\"en\">" + all_opt[option]["shortdesc"] + "</shortdesc>"
print "\t</parameter>"
print "</parameters>"
print "<actions>"
print "\t<action name=\"on\" />"
print "\t<action name=\"off\" />"
print "\t<action name=\"reboot\" />"
print "\t<action name=\"status\" />"
print "\t<action name=\"list\" />"
print "\t<action name=\"monitor\" />"
print "\t<action name=\"metadata\" />"
print "</actions>"
print "</resource-agent>"
def process_input(avail_opt):
global all_opt
global common_opt
##
## Add options which are available for every fence agent
#####
avail_opt.extend(common_opt)
##
## Set standard environment
#####
os.putenv("LANG", "C")
os.putenv("LC_ALL", "C")
##
## Prepare list of options for getopt
#####
getopt_string = ""
longopt_list = [ ]
for k in avail_opt:
if all_opt.has_key(k):
getopt_string += all_opt[k]["getopt"]
else:
fail_usage("Parse error: unknown option '"+k+"'")
if all_opt.has_key(k) and all_opt[k].has_key("longopt"):
if all_opt[k]["getopt"].endswith(":"):
longopt_list.append(all_opt[k]["longopt"] + "=")
else:
longopt_list.append(all_opt[k]["longopt"])
## Compatibility layer
if avail_opt.count("module_name") == 1:
getopt_string += "n:"
longopt_list.append("plug=")
##
## Read options from command line or standard input
#####
if len(sys.argv) > 1:
try:
opt, args = getopt.gnu_getopt(sys.argv[1:], getopt_string, longopt_list)
except getopt.GetoptError, error:
fail_usage("Parse error: " + error.msg)
## Transform longopt to short one which are used in fencing agents
#####
old_opt = opt
opt = { }
for o in dict(old_opt).keys():
if o.startswith("--"):
for x in all_opt.keys():
if all_opt[x].has_key("longopt") and "--" + all_opt[x]["longopt"] == o:
opt["-" + all_opt[x]["getopt"].rstrip(":")] = dict(old_opt)[o]
else:
opt[o] = dict(old_opt)[o]
## Compatibility Layer
#####
z = dict(opt)
if z.has_key("-T") == 1:
z["-o"] = "status"
if z.has_key("-n") == 1:
z["-m"] = z["-n"]
opt = z
##
#####
else:
opt = { }
name = ""
for line in sys.stdin.readlines():
line = line.strip()
if ((line.startswith("#")) or (len(line) == 0)):
continue
(name, value) = (line + "=").split("=", 1)
value = value[:-1]
## Compatibility Layer
######
if name == "blade":
name = "port"
elif name == "option":
name = "action"
elif name == "fm":
name = "port"
elif name == "hostname":
name = "ipaddr"
elif name == "modulename":
name = "module_name"
elif name == "action" and 1 == avail_opt.count("io_fencing"):
name = "io_fencing"
elif name == "port" and 1 == avail_opt.count("drac_version"):
name = "module_name"
##
######
if avail_opt.count(name) == 0:
sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n")
continue
if all_opt[name]["getopt"].endswith(":"):
opt["-"+all_opt[name]["getopt"].rstrip(":")] = value
elif ((value == "1") or (value.lower() == "yes")):
opt["-"+all_opt[name]["getopt"]] = "1"
return opt
##
## This function checks input and answers if we want to have same answers
## in each of the fencing agents. It looks for possible errors and run
## password script to set a correct password
######
def check_input(device_opt, opt):
global all_opt
global common_opt
##
## Add options which are available for every fence agent
#####
device_opt.extend([x for x in common_opt if device_opt.count(x) == 0])
options = dict(opt)
options["device_opt"] = device_opt
## Set requirements that should be included in metadata
#####
if device_opt.count("login") and device_opt.count("no_login") == 0:
all_opt["login"]["required"] = "1"
else:
all_opt["login"]["required"] = "0"
## In special cases (show help, metadata or version) we don't need to check anything
#####
if options.has_key("-h") or options.has_key("-V") or (options.has_key("-o") and options["-o"].lower() == "metadata"):
return options;
## Set default values
#####
for opt in device_opt:
if all_opt[opt].has_key("default"):
getopt = "-" + all_opt[opt]["getopt"].rstrip(":")
if 0 == options.has_key(getopt):
options[getopt] = all_opt[opt]["default"]
options["-o"]=options["-o"].lower()
if options.has_key("-v"):
options["log"] = LOG_MODE_VERBOSE
else:
options["log"] = LOG_MODE_QUIET
if 0 == device_opt.count("io_fencing"):
if 0 == ["on", "off", "reboot", "status", "list", "monitor"].count(options["-o"].lower()):
fail_usage("Failed: Unrecognised action '" + options["-o"] + "'")
else:
if 0 == ["enable", "disable", "status", "list", "monitor"].count(options["-o"].lower()):
fail_usage("Failed: Unrecognised action '" + options["-o"] + "'")
if (0 == options.has_key("-l")) and device_opt.count("login") and (device_opt.count("no_login") == 0):
fail_usage("Failed: You have to set login name")
if 0 == options.has_key("-a") and 0 == options.has_key("-s"):
fail_usage("Failed: You have to enter fence address")
if (0 == ["list", "monitor"].count(options["-o"].lower())) and device_opt.count("vm_name") and device_opt.count("uuid"):
if 0 == options.has_key("-n") and 0 == options.has_key("-U"):
fail_usage("Failed: You must specify either UUID or VM name")
if (device_opt.count("no_password") == 0):
if 0 == device_opt.count("identity_file"):
if 0 == (options.has_key("-p") or options.has_key("-S")):
fail_usage("Failed: You have to enter password or password script")
else:
if 0 == (options.has_key("-p") or options.has_key("-S") or options.has_key("-k")):
fail_usage("Failed: You have to enter password, password script or identity file")
if 0 == options.has_key("-x") and 1 == options.has_key("-k"):
fail_usage("Failed: You have to use identity file together with ssh connection (-x)")
if 1 == options.has_key("-k"):
if 0 == os.path.isfile(options["-k"]):
fail_usage("Failed: Identity file " + options["-k"] + " does not exist")
if (0 == ["list", "monitor"].count(options["-o"].lower())) and (0 == options.has_key("-n")) and (device_opt.count("port")):
fail_usage("Failed: You have to enter plug number")
if options.has_key("-S"):
options["-p"] = os.popen(options["-S"]).read().rstrip()
if options.has_key("-D"):
try:
options["debug_fh"] = file (options["-D"], "w")
except IOError:
fail_usage("Failed: Unable to create file "+options["-D"])
if options.has_key("-v") and options.has_key("debug_fh") == 0:
options["debug_fh"] = sys.stderr
if options.has_key("-R"):
options["-P"] = os.popen(options["-R"]).read().rstrip()
if options.has_key("-u") == False:
if options.has_key("-x"):
options["-u"] = 22
elif options.has_key("-z"):
options["-u"] = 443
elif device_opt.count("web"):
options["-u"] = 80
else:
options["-u"] = 23
return options
def wait_power_status(tn, options, get_power_fn):
for dummy in xrange(int(options["-g"])):
if get_power_fn(tn, options) != options["-o"]:
time.sleep(1)
else:
return 1
return 0
def show_docs(options, docs = None):
device_opt = options["device_opt"]
if docs == None:
docs = { }
docs["shortdesc"] = "Fence agent"
docs["longdesc"] = ""
## Process special options (and exit)
#####
if options.has_key("-h"):
usage(device_opt)
sys.exit(0)
if options.has_key("-o") and options["-o"].lower() == "metadata":
metadata(device_opt, options, docs)
sys.exit(0)
if options.has_key("-V"):
print __main__.RELEASE_VERSION, __main__.BUILD_DATE
print __main__.REDHAT_COPYRIGHT
sys.exit(0)
def fence_action(tn, options, set_power_fn, get_power_fn, get_outlet_list = None):
result = 0
## Process options that manipulate fencing device
#####
if (options["-o"] == "list") and (0 == options["device_opt"].count("port")) and (0 == options["device_opt"].count("partition")) and (0 == options["device_opt"].count("uuid")):
print "N/A"
return
elif (options["-o"] == "list" and get_outlet_list == None):
## @todo: exception?
## This is just temporal solution, we will remove default value
## None as soon as all existing agent will support this operation
print "NOTICE: List option is not working on this device yet"
return
elif (options["-o"] == "list") or ((options["-o"] == "monitor") and 1 == options["device_opt"].count("port")):
outlets = get_outlet_list(tn, options)
## keys can be numbers (port numbers) or strings (names of VM)
for o in outlets.keys():
(alias, status) = outlets[o]
if options["-o"] != "monitor":
print o + options["-C"] + alias
return
if options["-o"] in ["off", "reboot"]:
time.sleep(int(options["-f"]))
status = get_power_fn(tn, options)
if status != "on" and status != "off":
fail(EC_STATUS)
if options["-o"] == "enable":
options["-o"] = "on"
if options["-o"] == "disable":
options["-o"] = "off"
if options["-o"] == "on":
if status == "on":
print "Success: Already ON"
else:
power_on = False
for i in range(1,1 + int(options["-F"])):
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn):
power_on = True
break
if power_on:
print "Success: Powered ON"
else:
fail(EC_WAITING_ON)
elif options["-o"] == "off":
if status == "off":
print "Success: Already OFF"
else:
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn):
print "Success: Powered OFF"
else:
fail(EC_WAITING_OFF)
elif options["-o"] == "reboot":
if status != "off":
options["-o"] = "off"
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn) == 0:
fail(EC_WAITING_OFF)
options["-o"] = "on"
power_on = False
for i in range(1,1 + int(options["-F"])):
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn) == 1:
power_on = True
break
if power_on == False:
# this should not fail as not was fenced succesfully
sys.stderr.write('Timed out waiting to power ON\n')
print "Success: Rebooted"
elif options["-o"] == "status":
print "Status: " + status.upper()
if status.upper() == "OFF":
result = 2
elif options["-o"] == "monitor":
1
return result
def fence_login(options):
force_ipvx=""
if (options.has_key("-6")):
force_ipvx="-6 "
if (options.has_key("-4")):
force_ipvx="-4 "
if (options["device_opt"].count("login_eol_lf")):
login_eol = "\n"
else:
login_eol = "\r\n"
try:
re_login = re.compile("(login\s*: )|(Login Name: )|(username: )|(User Name :)", re.IGNORECASE)
re_pass = re.compile("password", re.IGNORECASE)
if options.has_key("-z"):
command = '%s %s %s %s' % (SSL_PATH, force_ipvx, options["-a"], options["-u"])
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
## SSL telnet is part of the fencing package
sys.stderr.write(str(ex) + "\n")
sys.exit(EC_GENERIC_ERROR)
elif options.has_key("-x") and 0 == options.has_key("-k"):
command = '%s %s %s@%s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-u"])
if options.has_key("ssh_options"):
command += ' ' + options["ssh_options"]
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
if options.has_key("telnet_over_ssh"):
#This is for stupid ssh servers (like ALOM) which behave more like telnet (ignore name and display login prompt)
result = conn.log_expect(options, [ re_login, "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"]))
if result == 1:
conn.sendline("yes") # Host identity confirm
conn.log_expect(options, re_login, int(options["-y"]))
conn.sendline(options["-l"])
conn.log_expect(options, re_pass, int(options["-y"]))
else:
result = conn.log_expect(options, [ "ssword:", "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"]))
if result == 1:
conn.sendline("yes")
conn.log_expect(options, "ssword:", int(options["-y"]))
conn.sendline(options["-p"])
conn.log_expect(options, options["-c"], int(options["-y"]))
elif options.has_key("-x") and 1 == options.has_key("-k"):
command = '%s %s %s@%s -i %s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-k"], options["-u"])
if options.has_key("ssh_options"):
command += ' ' + options["ssh_options"]
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
result = conn.log_expect(options, [ options["-c"], "Are you sure you want to continue connecting (yes/no)?", "Enter passphrase for key '"+options["-k"]+"':" ], int(options["-y"]))
if result == 1:
conn.sendline("yes")
conn.log_expect(options, [ options["-c"], "Enter passphrase for key '"+options["-k"]+"':"] , int(options["-y"]))
if result != 0:
if options.has_key("-p"):
conn.sendline(options["-p"])
conn.log_expect(options, options["-c"], int(options["-y"]))
else:
fail_usage("Failed: You have to enter passphrase (-p) for identity file")
else:
try:
conn = fspawn(TELNET_PATH)
conn.send("set binary\n")
conn.send("open %s -%s\n"%(options["-a"], options["-u"]))
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
conn.log_expect(options, re_login, int(options["-y"]))
conn.send(options["-l"] + login_eol)
conn.log_expect(options, re_pass, int(options["-Y"]))
conn.send(options["-p"] + login_eol)
conn.log_expect(options, options["-c"], int(options["-Y"]))
except pexpect.EOF:
fail(EC_LOGIN_DENIED)
except pexpect.TIMEOUT:
fail(EC_LOGIN_DENIED)
return conn
| Python |
#!/usr/bin/env python
#
#############################################################################
# Copyright 2011 Matt Clark
# This file is part of fence-xenserver
#
# fence-xenserver is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# fence-xenserver is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
#############################################################################
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
import sys, string, getopt
import XenAPI
def usage():
print "Usage: fence_cxs [-hv] [-a <action>] -l <login username> -p <login password> -s <session url> [-u <UUID>]"
print "Where:-"
print " -a : Specifies the action to perfom. Can be any of \"on|off|reboot|status|list\". Defaults to \"status\"."
print " -h : Print this help message."
print " -l : The username for the XenServer host."
print " -p : The password for the XenServer host."
print " -s : The URL of the web interface on the XenServer host."
print " -U : The UUID of the virtual machine to fence or query. Defaults to the empty string which will return"
print " the status of all hosts when action is set to \"status\". If the action is set to \"on|off|reboot\""
print " then the UUID must be specified."
# Process command line options and populate the config array
def process_opts():
config = {
"action" : "status",
"session_url" : "",
"session_user" : "",
"session_pass" : "",
"uuid" : "",
"name" : "",
"verbose" : False
}
# If we have at least one argument then we want to parse the command line using getopts
if len(sys.argv) > 1:
try:
opts, args = getopt.getopt(sys.argv[1:], "a:hl:n:s:p:U:v", ["help", "verbose", "action=", "session-url=", "login-name=", "name=", "password=", "uuid="])
except getopt.GetoptError, err:
# We got an unrecognised option, so print he help message and exit
print str(err)
usage()
sys.exit(1)
for opt, arg in opts:
if opt in ("-v", "--verbose"):
config["verbose"] = True
elif opt in ("-a", "--action"):
config["action"] = clean_action(arg)
elif opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-s", "--session-url"):
config["session_url"] = arg
elif opt in ("-l", "--login-name"):
config["session_user"] = arg
elif opt in ("-n", "--name"):
config["name"] = arg
elif opt in ("-p", "--password"):
config["session_pass"] = arg
elif opt in ("-U", "--uuid"):
config["uuid"] = arg.lower()
else:
assert False, "unhandled option"
# Otherwise process stdin for parameters. This is to handle the Red Hat clustering
# mechanism where by fenced passes in name/value pairs instead of using command line
# options.
else:
for line in sys.stdin.readlines():
line = line.strip()
if ((line.startswith("#")) or (len(line) == 0)):
continue
(name, value) = (line + "=").split("=", 1)
value = value[:-1]
name = clean_param_name(name)
if name == "action":
value = clean_action(value)
if name in config:
config[name] = value
else:
sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n")
if( config["session_url"] == "" or config["session_user"] == "" or config["session_pass"] == "" ):
print "You must specify the session url, username and password.";
usage();
sys.exit(2);
return config
# why, well just to be nice. Given an action will return the corresponding
# value that the rest of the script uses.
def clean_action(action):
if action.lower() in ("on", "poweron", "powerup"):
return "on"
elif action.lower() in ("off", "poweroff", "powerdown"):
return "off"
elif action.lower() in ("reboot", "reset", "restart"):
return "reboot"
elif action.lower() in ("status", "powerstatus", "list"):
return "status"
else:
print "Bad action", action
usage()
exit(4)
# why, well just to be nice. Given a parameter will return the corresponding
# value that the rest of the script uses.
def clean_param_name(name):
if name.lower() in ("action", "operation", "op"):
return "action"
elif name.lower() in ("session_user", "login", "login-name", "login_name", "user", "username", "session-user"):
return "session_user"
elif name.lower() in ("session_pass", "pass", "passwd", "password", "session-pass"):
return "session_pass"
elif name.lower() in ("session_url", "url", "session-url"):
return "session_url"
else:
# we should never get here as getopt should handle the checking of this input.
print "Bad parameter specified", name
usage()
exit(5)
# Print the power status of a VM. If no UUID is given, then all VM's are queried
def get_power_status(session, uuid = "", name = ""):
try:
# If the UUID hasn't been set, then output the status of all
# valid virtual machines.
if( len(uuid) > 0 ):
vms = [session.xenapi.VM.get_by_uuid(uuid)]
elif( len(name) > 0 ):
vms = session.xenapi.VM.get_by_name_label(name)
else:
vms = session.xenapi.VM.get_all()
for vm in vms:
record = session.xenapi.VM.get_record(vm);
# We only want to print out the status for actual virtual machines. The above get_all function
# returns any templates and also the control domain. This is one of the reasons the process
# takes such a long time to list all VM's. Hopefully there is a way to filter this in the
# request packet in the future.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
def set_power_status(session, uuid, name, action):
try:
vm = None
if( len(uuid) > 0 ):
vm = session.xenapi.VM.get_by_uuid(uuid)
elif( len(name) > 0 ):
vm_arr = session.xenapi.VM.get_by_name_label(name)
if( len(vm_arr) == 1 ):
vm = vm_arr[0]
else
raise Exception("Multiple VM's have that name. Use UUID instead.")
if( vm != None ):
record = session.xenapi.VM.get_record(vm);
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
session.xenapi.VM.hard_reboot(vm)
else:
raise Exception("Bad power status");
except Exception, exn:
print str(exn);
def main():
config = process_opts();
session = session_start(config["session_url"]);
session_login(session, config["session_user"], config["session_pass"]);
if( config["action"] == "status" ):
get_power_status(session, config["uuid"], config["name"])
else:
if( config["verbose"] ):
print "Power status before action"
get_power_status(session, config["uuid"])
set_power_status(session, config["uuid"], config["name"], config["action"])
if( config["verbose"] ):
print "Power status after action"
get_power_status(session, config["uuid"])
# Function to initiate the session with the XenServer system
def session_start(url):
try:
session = XenAPI.Session(url);
except Exception, exn:
print str(exn);
sys.exit(3);
return session;
def session_login(session, username, password):
try:
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
sys.exit(3);
if __name__ == "__main__":
main()
# vim:set ts=4 sw=4
| Python |
#!/usr/bin/env python
#
#############################################################################
# Copyright 2011 Matt Clark
# This file is part of fence-xenserver
#
# fence-xenserver is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# fence-xenserver is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
#############################################################################
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
import sys, string, getopt
import XenAPI
def usage():
print "Usage: fence_cxs [-hv] [-a <action>] -l <login username> -p <login password> -s <session url> [-u <UUID>]"
print "Where:-"
print " -a : Specifies the action to perfom. Can be any of \"on|off|reboot|status|list\". Defaults to \"status\"."
print " -h : Print this help message."
print " -l : The username for the XenServer host."
print " -p : The password for the XenServer host."
print " -s : The URL of the web interface on the XenServer host."
print " -U : The UUID of the virtual machine to fence or query. Defaults to the empty string which will return"
print " the status of all hosts when action is set to \"status\". If the action is set to \"on|off|reboot\""
print " then the UUID must be specified."
# Process command line options and populate the config array
def process_opts():
config = {
"action" : "status",
"session_url" : "",
"session_user" : "",
"session_pass" : "",
"uuid" : "",
"name" : "",
"verbose" : False
}
# If we have at least one argument then we want to parse the command line using getopts
if len(sys.argv) > 1:
try:
opts, args = getopt.getopt(sys.argv[1:], "a:hl:n:s:p:U:v", ["help", "verbose", "action=", "session-url=", "login-name=", "name=", "password=", "uuid="])
except getopt.GetoptError, err:
# We got an unrecognised option, so print he help message and exit
print str(err)
usage()
sys.exit(1)
for opt, arg in opts:
if opt in ("-v", "--verbose"):
config["verbose"] = True
elif opt in ("-a", "--action"):
config["action"] = clean_action(arg)
elif opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-s", "--session-url"):
config["session_url"] = arg
elif opt in ("-l", "--login-name"):
config["session_user"] = arg
elif opt in ("-n", "--name"):
config["name"] = arg
elif opt in ("-p", "--password"):
config["session_pass"] = arg
elif opt in ("-U", "--uuid"):
config["uuid"] = arg.lower()
else:
assert False, "unhandled option"
# Otherwise process stdin for parameters. This is to handle the Red Hat clustering
# mechanism where by fenced passes in name/value pairs instead of using command line
# options.
else:
for line in sys.stdin.readlines():
line = line.strip()
if ((line.startswith("#")) or (len(line) == 0)):
continue
(name, value) = (line + "=").split("=", 1)
value = value[:-1]
name = clean_param_name(name)
if name == "action":
value = clean_action(value)
if name in config:
config[name] = value
else:
sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n")
if( config["session_url"] == "" or config["session_user"] == "" or config["session_pass"] == "" ):
print "You must specify the session url, username and password.";
usage();
sys.exit(2);
return config
# why, well just to be nice. Given an action will return the corresponding
# value that the rest of the script uses.
def clean_action(action):
if action.lower() in ("on", "poweron", "powerup"):
return "on"
elif action.lower() in ("off", "poweroff", "powerdown"):
return "off"
elif action.lower() in ("reboot", "reset", "restart"):
return "reboot"
elif action.lower() in ("status", "powerstatus", "list"):
return "status"
else:
print "Bad action", action
usage()
exit(4)
# why, well just to be nice. Given a parameter will return the corresponding
# value that the rest of the script uses.
def clean_param_name(name):
if name.lower() in ("action", "operation", "op"):
return "action"
elif name.lower() in ("session_user", "login", "login-name", "login_name", "user", "username", "session-user"):
return "session_user"
elif name.lower() in ("session_pass", "pass", "passwd", "password", "session-pass"):
return "session_pass"
elif name.lower() in ("session_url", "url", "session-url"):
return "session_url"
else:
# we should never get here as getopt should handle the checking of this input.
print "Bad parameter specified", name
usage()
exit(5)
# Print the power status of a VM. If no UUID is given, then all VM's are queried
def get_power_status(session, uuid = "", name = ""):
try:
# If the UUID hasn't been set, then output the status of all
# valid virtual machines.
if( len(uuid) > 0 ):
vms = [session.xenapi.VM.get_by_uuid(uuid)]
elif( len(name) > 0 ):
vms = session.xenapi.VM.get_by_name_label(name)
else:
vms = session.xenapi.VM.get_all()
for vm in vms:
record = session.xenapi.VM.get_record(vm);
# We only want to print out the status for actual virtual machines. The above get_all function
# returns any templates and also the control domain. This is one of the reasons the process
# takes such a long time to list all VM's. Hopefully there is a way to filter this in the
# request packet in the future.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
def set_power_status(session, uuid, name, action):
try:
vm = None
if( len(uuid) > 0 ):
vm = session.xenapi.VM.get_by_uuid(uuid)
elif( len(name) > 0 ):
vm_arr = session.xenapi.VM.get_by_name_label(name)
if( len(vm_arr) == 1 ):
vm = vm_arr[0]
else
raise Exception("Multiple VM's have that name. Use UUID instead.")
if( vm != None ):
record = session.xenapi.VM.get_record(vm);
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
session.xenapi.VM.hard_reboot(vm)
else:
raise Exception("Bad power status");
except Exception, exn:
print str(exn);
def main():
config = process_opts();
session = session_start(config["session_url"]);
session_login(session, config["session_user"], config["session_pass"]);
if( config["action"] == "status" ):
get_power_status(session, config["uuid"], config["name"])
else:
if( config["verbose"] ):
print "Power status before action"
get_power_status(session, config["uuid"])
set_power_status(session, config["uuid"], config["name"], config["action"])
if( config["verbose"] ):
print "Power status after action"
get_power_status(session, config["uuid"])
# Function to initiate the session with the XenServer system
def session_start(url):
try:
session = XenAPI.Session(url);
except Exception, exn:
print str(exn);
sys.exit(3);
return session;
def session_login(session, username, password):
try:
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
sys.exit(3);
if __name__ == "__main__":
main()
# vim:set ts=4 sw=4
| Python |
#============================================================================
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#============================================================================
# Copyright (C) 2006 XenSource Inc.
#============================================================================
#
# Parts of this file are based upon xmlrpclib.py, the XML-RPC client
# interface included in the Python distribution.
#
# Copyright (c) 1999-2002 by Secret Labs AB
# Copyright (c) 1999-2002 by Fredrik Lundh
#
# By obtaining, using, and/or copying this software and/or its
# associated documentation, you agree that you have read, understood,
# and will comply with the following terms and conditions:
#
# Permission to use, copy, modify, and distribute this software and
# its associated documentation for any purpose and without fee is
# hereby granted, provided that the above copyright notice appears in
# all copies, and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of
# Secret Labs AB or the author not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
# OF THIS SOFTWARE.
# --------------------------------------------------------------------
import gettext
import xmlrpclib
import httplib
import socket
translation = gettext.translation('xen-xm', fallback = True)
class Failure(Exception):
def __init__(self, details):
try:
# If this failure is MESSAGE_PARAMETER_COUNT_MISMATCH, then we
# correct the return values here, to account for the fact that we
# transparently add the session handle as the first argument.
if details[0] == 'MESSAGE_PARAMETER_COUNT_MISMATCH':
details[2] = str(int(details[2]) - 1)
details[3] = str(int(details[3]) - 1)
self.details = details
except Exception, exn:
self.details = ['INTERNAL_ERROR', 'Client-side: ' + str(exn)]
def __str__(self):
try:
return translation.ugettext(self.details[0]) % self._details_map()
except TypeError, exn:
return "Message database broken: %s.\nXen-API failure: %s" % \
(exn, str(self.details))
except Exception, exn:
import sys
print >>sys.stderr, exn
return "Xen-API failure: %s" % str(self.details)
def _details_map(self):
return dict([(str(i), self.details[i])
for i in range(len(self.details))])
_RECONNECT_AND_RETRY = (lambda _ : ())
class UDSHTTPConnection(httplib.HTTPConnection):
""" Stupid hacked up HTTPConnection subclass to allow HTTP over Unix domain
sockets. """
def connect(self):
path = self.host.replace("_", "/")
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect(path)
class UDSHTTP(httplib.HTTP):
_connection_class = UDSHTTPConnection
class UDSTransport(xmlrpclib.Transport):
def make_connection(self, host):
return UDSHTTP(host)
class Session(xmlrpclib.ServerProxy):
"""A server proxy and session manager for communicating with Xend using
the Xen-API.
Example:
session = Session('http://localhost:9363/')
session.login_with_password('me', 'mypassword')
session.xenapi.VM.start(vm_uuid)
session.xenapi.session.logout()
For now, this class also supports the legacy XML-RPC API, using
session.xend.domain('Domain-0') and similar. This support will disappear
once there is a working Xen-API replacement for every call in the legacy
API.
"""
def __init__(self, uri, transport=None, encoding=None, verbose=0,
allow_none=1):
xmlrpclib.ServerProxy.__init__(self, uri, transport, encoding,
verbose, allow_none)
self._session = None
self.last_login_method = None
self.last_login_params = None
def xenapi_request(self, methodname, params):
if methodname.startswith('login'):
self._login(methodname, params)
return None
else:
retry_count = 0
while retry_count < 3:
full_params = (self._session,) + params
result = _parse_result(getattr(self, methodname)(*full_params))
if result == _RECONNECT_AND_RETRY:
retry_count += 1
if self.last_login_method:
self._login(self.last_login_method,
self.last_login_params)
else:
raise xmlrpclib.Fault(401, 'You must log in')
else:
return result
raise xmlrpclib.Fault(
500, 'Tried 3 times to get a valid session, but failed')
def _login(self, method, params):
result = _parse_result(getattr(self, 'session.%s' % method)(*params))
if result == _RECONNECT_AND_RETRY:
raise xmlrpclib.Fault(
500, 'Received SESSION_INVALID when logging in')
self._session = result
self.last_login_method = method
self.last_login_params = params
def __getattr__(self, name):
if name == 'xenapi':
return _Dispatcher(self.xenapi_request, None)
elif name.startswith('login'):
return lambda *params: self._login(name, params)
else:
return xmlrpclib.ServerProxy.__getattr__(self, name)
def xapi_local():
return Session("http://_var_xapi_xapi/", transport=UDSTransport())
def _parse_result(result):
if type(result) != dict or 'Status' not in result:
raise xmlrpclib.Fault(500, 'Missing Status in response from server' + result)
if result['Status'] == 'Success':
if 'Value' in result:
return result['Value']
else:
raise xmlrpclib.Fault(500,
'Missing Value in response from server')
else:
if 'ErrorDescription' in result:
if result['ErrorDescription'][0] == 'SESSION_INVALID':
return _RECONNECT_AND_RETRY
else:
raise Failure(result['ErrorDescription'])
else:
raise xmlrpclib.Fault(
500, 'Missing ErrorDescription in response from server')
# Based upon _Method from xmlrpclib.
class _Dispatcher:
def __init__(self, send, name):
self.__send = send
self.__name = name
def __repr__(self):
if self.__name:
return '<XenAPI._Dispatcher for %s>' % self.__name
else:
return '<XenAPI._Dispatcher>'
def __getattr__(self, name):
if self.__name is None:
return _Dispatcher(self.__send, name)
else:
return _Dispatcher(self.__send, "%s.%s" % (self.__name, name))
def __call__(self, *args):
return self.__send(self.__name, args)
| Python |
#!/usr/bin/python
#
#############################################################################
# Copyright 2011 Matt Clark
# This file is part of fence-xenserver
#
# fence-xenserver is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# fence-xenserver is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
#############################################################################
#############################################################################
# It's only just begun...
# Current status: completely usable. This script is now working well and,
# has a lot of functionality as a result of the fencing.py library and the
# XenAPI libary.
#############################################################################
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
import sys
sys.path.append("/usr/lib/fence")
from fencing import *
import XenAPI
EC_BAD_SESSION = 1
# Find the status of the port given in the -U flag of options.
def get_power_fn(session, options):
if options.has_key("-v"):
verbose = True
else:
verbose = False
try:
# Get a reference to the vm specified in the UUID or vm_name parameter
vm = return_vm_reference(session, options)
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm);
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
status = record["power_state"]
if verbose: print "UUID:", record["uuid"], "NAME:", record["name_label"], "POWER STATUS:", record["power_state"]
# Note that the VM can be in the following states (from the XenAPI document)
# Halted: VM is offline and not using any resources.
# Paused: All resources have been allocated but the VM itself is paused and its vCPUs are not running
# Running: Running
# Paused: VM state has been saved to disk and it is nolonger running. Note that disks remain in-Use while
# We want to make sure that we only return the status "off" if the machine is actually halted as the status
# is checked before a fencing action. Only when the machine is Halted is it not consuming resources which
# may include whatever you are trying to protect with this fencing action.
return (status=="Halted" and "off" or "on")
except Exception, exn:
print str(exn)
return "Error"
# Set the state of the port given in the -U flag of options.
def set_power_fn(session, options):
action = options["-o"].lower()
if options.has_key("-v"):
verbose = True
else:
verbose = False
try:
# Get a reference to the vm specified in the UUID or vm_name parameter
vm = return_vm_reference(session, options)
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm)
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
# Start the VM
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
# Force shutdown the VM
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
# Force reboot the VM
session.xenapi.VM.hard_reboot(vm)
except Exception, exn:
print str(exn);
# Function to populate an array of virtual machines and their status
def get_outlet_list(session, options):
result = {}
if options.has_key("-v"):
verbose = True
else:
verbose = False
try:
# Return an array of all the VM's on the host
vms = session.xenapi.VM.get_all()
for vm in vms:
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm);
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
uuid = record["uuid"]
status = record["power_state"]
result[uuid] = (name, status)
if verbose: print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
return result
# Function to initiate the XenServer session via the XenAPI library.
def connect_and_login(options):
url = options["-s"]
username = options["-l"]
password = options["-p"]
try:
# Create the XML RPC session to the specified URL.
session = XenAPI.Session(url);
# Login using the supplied credentials.
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
# http://sources.redhat.com/cluster/wiki/FenceAgentAPI says that for no connectivity
# the exit value should be 1. It doesn't say anything about failed logins, so
# until I hear otherwise it is best to keep this exit the same to make sure that
# anything calling this script (that uses the same information in the web page
# above) knows that this is an error condition, not a msg signifying a down port.
sys.exit(EC_BAD_SESSION);
return session;
# return a reference to the VM by either using the UUID or the vm_name. If the UUID is set then
# this is tried first as this is the only properly unique identifier.
# Exceptions are not handled in this function, code that calls this must be ready to handle them.
def return_vm_reference(session, options):
if options.has_key("-v"):
verbose = True
else:
verbose = False
# Case where the UUID has been specified
if options.has_key("-U"):
uuid = options["-U"].lower()
# When using the -n parameter for name, we get an error message (in verbose
# mode) that tells us that we didn't find a VM. To immitate that here we
# need to catch and re-raise the exception produced by get_by_uuid.
try:
return session.xenapi.VM.get_by_uuid(uuid)
except Exception,exn:
if verbose: print "No VM's found with a UUID of \"%s\"" %uuid
raise
# Case where the vm_name has been specified
if options.has_key("-n"):
vm_name = options["-n"]
vm_arr = session.xenapi.VM.get_by_name_label(vm_name)
# Need to make sure that we only have one result as the vm_name may
# not be unique. Average case, so do it first.
if len(vm_arr) == 1:
return vm_arr[0]
else:
if len(vm_arr) == 0:
if verbose: print "No VM's found with a name of \"%s\"" %vm_name
# NAME_INVALID used as the XenAPI throws a UUID_INVALID if it can't find
# a VM with the specified UUID. This should make the output look fairly
# consistent.
raise Exception("NAME_INVALID")
else:
if verbose: print "Multiple VM's have the name \"%s\", use UUID instead" %vm_name
raise Exception("MULTIPLE_VMS_FOUND")
# We should never get to this case as the input processing checks that either the UUID or
# the name parameter is set. Regardless of whether or not a VM is found the above if
# statements will return to the calling function (either by exception or by a reference
# to the VM).
raise Exception("VM_LOGIC_ERROR")
def main():
device_opt = [ "help", "version", "agent", "quiet", "verbose", "debug", "action",
"login", "passwd", "passwd_script", "vm_name", "test", "separator",
"no_login", "no_password", "power_timeout", "shell_timeout",
"login_timeout", "power_wait", "session_url", "uuid" ]
atexit.register(atexit_handler)
options=process_input(device_opt)
options = check_input(device_opt, options)
docs = { }
docs["shortdesc"] = "XenAPI based fencing for the Citrix XenServer virtual machines."
docs["longdesc"] = "\
fence_cxs is an I/O Fencing agent used on Citrix XenServer hosts. \
It uses the XenAPI, supplied by Citrix, to establish an XML-RPC sesssion \
to a XenServer host. Once the session is established, further XML-RPC \
commands are issued in order to switch on, switch off, restart and query \
the status of virtual machines running on the host."
show_docs(options, docs)
xenSession = connect_and_login(options)
# Operate the fencing device
result = fence_action(xenSession, options, set_power_fn, get_power_fn, get_outlet_list)
sys.exit(result)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
import sys, getopt, time, os
import pexpect, re
import telnetlib
import atexit
import __main__
## do not add code here.
#BEGIN_VERSION_GENERATION
RELEASE_VERSION="3.0.17"
BUILD_DATE="(built Thu Oct 7 07:06:21 UTC 2010)"
REDHAT_COPYRIGHT="Copyright (C) Red Hat, Inc. 2004-2010 All rights reserved."
#END_VERSION_GENERATION
LOG_MODE_VERBOSE = 100
LOG_MODE_QUIET = 0
EC_GENERIC_ERROR = 1
EC_BAD_ARGS = 2
EC_LOGIN_DENIED = 3
EC_CONNECTION_LOST = 4
EC_TIMED_OUT = 5
EC_WAITING_ON = 6
EC_WAITING_OFF = 7
EC_STATUS = 8
EC_STATUS_HMC = 9
TELNET_PATH = "/usr/bin/telnet"
SSH_PATH = "/usr/bin/ssh"
SSL_PATH = "/usr/sbin/fence_nss_wrapper"
all_opt = {
"help" : {
"getopt" : "h",
"longopt" : "help",
"help" : "-h, --help Display this help and exit",
"required" : "0",
"shortdesc" : "Display help and exit",
"order" : 54 },
"version" : {
"getopt" : "V",
"longopt" : "version",
"help" : "-V, --version Output version information and exit",
"required" : "0",
"shortdesc" : "Display version information and exit",
"order" : 53 },
"quiet" : {
"getopt" : "q",
"help" : "",
"order" : 50 },
"verbose" : {
"getopt" : "v",
"longopt" : "verbose",
"help" : "-v, --verbose Verbose mode",
"required" : "0",
"shortdesc" : "Verbose mode",
"order" : 51 },
"debug" : {
"getopt" : "D:",
"longopt" : "debug-file",
"help" : "-D, --debug-file=<debugfile> Debugging to output file",
"required" : "0",
"shortdesc" : "Write debug information to given file",
"order" : 52 },
"delay" : {
"getopt" : "f:",
"longopt" : "delay",
"help" : "--delay <seconds> Wait X seconds before fencing is started",
"required" : "0",
"shortdesc" : "Wait X seconds before fencing is started",
"default" : "0",
"order" : 200 },
"agent" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"web" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"action" : {
"getopt" : "o:",
"longopt" : "action",
"help" : "-o, --action=<action> Action: status, reboot (default), off or on",
"required" : "1",
"shortdesc" : "Fencing Action",
"default" : "reboot",
"order" : 1 },
"io_fencing" : {
"getopt" : "o:",
"longopt" : "action",
"help" : "-o, --action=<action> Action: status, enable or disable",
"required" : "1",
"shortdesc" : "Fencing Action",
"default" : "disable",
"order" : 1 },
"ipaddr" : {
"getopt" : "a:",
"longopt" : "ip",
"help" : "-a, --ip=<ip> IP address or hostname of fencing device",
"required" : "1",
"shortdesc" : "IP Address or Hostname",
"order" : 1 },
"ipport" : {
"getopt" : "u:",
"longopt" : "ipport",
"help" : "-u, --ipport=<port> TCP port to use",
"required" : "0",
"shortdesc" : "TCP port to use for connection with device",
"order" : 1 },
"login" : {
"getopt" : "l:",
"longopt" : "username",
"help" : "-l, --username=<name> Login name",
"required" : "?",
"shortdesc" : "Login Name",
"order" : 1 },
"no_login" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"no_password" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"passwd" : {
"getopt" : "p:",
"longopt" : "password",
"help" : "-p, --password=<password> Login password or passphrase",
"required" : "0",
"shortdesc" : "Login password or passphrase",
"order" : 1 },
"passwd_script" : {
"getopt" : "S:",
"longopt" : "password-script=",
"help" : "-S, --password-script=<script> Script to run to retrieve password",
"required" : "0",
"shortdesc" : "Script to retrieve password",
"order" : 1 },
"identity_file" : {
"getopt" : "k:",
"longopt" : "identity-file",
"help" : "-k, --identity-file=<filename> Identity file (private key) for ssh ",
"required" : "0",
"shortdesc" : "Identity file for ssh",
"order" : 1 },
"module_name" : {
"getopt" : "m:",
"longopt" : "module-name",
"help" : "-m, --module-name=<module> DRAC/MC module name",
"required" : "0",
"shortdesc" : "DRAC/MC module name",
"order" : 1 },
"drac_version" : {
"getopt" : "d:",
"longopt" : "drac-version",
"help" : "-d, --drac-version=<version> Force DRAC version to use",
"required" : "0",
"shortdesc" : "Force DRAC version to use",
"order" : 1 },
"hmc_version" : {
"getopt" : "H:",
"longopt" : "hmc-version",
"help" : "-H, --hmc-version=<version> Force HMC version to use: 3, 4 (default)",
"required" : "0",
"shortdesc" : "Force HMC version to use (3 or 4)",
"default" : "4",
"order" : 1 },
"ribcl" : {
"getopt" : "r:",
"longopt" : "ribcl-version",
"help" : "-r, --ribcl-version=<version> Force ribcl version to use",
"required" : "0",
"shortdesc" : "Force ribcl version to use",
"order" : 1 },
"login_eol_lf" : {
"getopt" : "",
"help" : "",
"order" : 1
},
"cmd_prompt" : {
"getopt" : "c:",
"longopt" : "command-prompt",
"help" : "-c, --command-prompt=<prompt> Force command prompt",
"shortdesc" : "Force command prompt",
"required" : "0",
"order" : 1 },
"secure" : {
"getopt" : "x",
"longopt" : "ssh",
"help" : "-x, --ssh Use ssh connection",
"shortdesc" : "SSH connection",
"required" : "0",
"order" : 1 },
"ssl" : {
"getopt" : "z",
"longopt" : "ssl",
"help" : "-z, --ssl Use ssl connection",
"required" : "0",
"shortdesc" : "SSL connection",
"order" : 1 },
"port" : {
"getopt" : "n:",
"longopt" : "plug",
"help" : "-n, --plug=<id> Physical plug number on device or\n" +
" name of virtual machine",
"required" : "1",
"shortdesc" : "Physical plug number or name of virtual machine",
"order" : 1 },
"switch" : {
"getopt" : "s:",
"longopt" : "switch",
"help" : "-s, --switch=<id> Physical switch number on device",
"required" : "0",
"shortdesc" : "Physical switch number on device",
"order" : 1 },
"partition" : {
"getopt" : "n:",
"help" : "-n <id> Name of the partition",
"required" : "0",
"shortdesc" : "Partition name",
"order" : 1 },
"managed" : {
"getopt" : "s:",
"help" : "-s <id> Name of the managed system",
"required" : "0",
"shortdesc" : "Managed system name",
"order" : 1 },
"test" : {
"getopt" : "T",
"help" : "",
"order" : 1,
"obsolete" : "use -o status instead" },
"exec" : {
"getopt" : "e:",
"longopt" : "exec",
"help" : "-e, --exec=<command> Command to execute",
"required" : "0",
"shortdesc" : "Command to execute",
"order" : 1 },
"vmware_type" : {
"getopt" : "d:",
"longopt" : "vmware_type",
"help" : "-d, --vmware_type=<type> Type of VMware to connect",
"required" : "0",
"shortdesc" : "Type of VMware to connect",
"order" : 1 },
"vmware_datacenter" : {
"getopt" : "s:",
"longopt" : "vmware-datacenter",
"help" : "-s, --vmware-datacenter=<dc> VMWare datacenter filter",
"required" : "0",
"shortdesc" : "Show only machines in specified datacenter",
"order" : 2 },
"snmp_version" : {
"getopt" : "d:",
"longopt" : "snmp-version",
"help" : "-d, --snmp-version=<ver> Specifies SNMP version to use",
"required" : "0",
"shortdesc" : "Specifies SNMP version to use (1,2c,3)",
"order" : 1 },
"community" : {
"getopt" : "c:",
"longopt" : "community",
"help" : "-c, --community=<community> Set the community string",
"required" : "0",
"shortdesc" : "Set the community string",
"order" : 1},
"snmp_auth_prot" : {
"getopt" : "b:",
"longopt" : "snmp-auth-prot",
"help" : "-b, --snmp-auth-prot=<prot> Set authentication protocol (MD5|SHA)",
"required" : "0",
"shortdesc" : "Set authentication protocol (MD5|SHA)",
"order" : 1},
"snmp_sec_level" : {
"getopt" : "E:",
"longopt" : "snmp-sec-level",
"help" : "-E, --snmp-sec-level=<level> Set security level\n"+
" (noAuthNoPriv|authNoPriv|authPriv)",
"required" : "0",
"shortdesc" : "Set security level (noAuthNoPriv|authNoPriv|authPriv)",
"order" : 1},
"snmp_priv_prot" : {
"getopt" : "B:",
"longopt" : "snmp-priv-prot",
"help" : "-B, --snmp-priv-prot=<prot> Set privacy protocol (DES|AES)",
"required" : "0",
"shortdesc" : "Set privacy protocol (DES|AES)",
"order" : 1},
"snmp_priv_passwd" : {
"getopt" : "P:",
"longopt" : "snmp-priv-passwd",
"help" : "-P, --snmp-priv-passwd=<pass> Set privacy protocol password",
"required" : "0",
"shortdesc" : "Set privacy protocol password",
"order" : 1},
"snmp_priv_passwd_script" : {
"getopt" : "R:",
"longopt" : "snmp-priv-passwd-script",
"help" : "-R, --snmp-priv-passwd-script Script to run to retrieve privacy password",
"required" : "0",
"shortdesc" : "Script to run to retrieve privacy password",
"order" : 1},
"inet4_only" : {
"getopt" : "4",
"longopt" : "inet4-only",
"help" : "-4, --inet4-only Forces agent to use IPv4 addresses only",
"required" : "0",
"shortdesc" : "Forces agent to use IPv4 addresses only",
"order" : 1 },
"inet6_only" : {
"getopt" : "6",
"longopt" : "inet6-only",
"help" : "-6, --inet6-only Forces agent to use IPv6 addresses only",
"required" : "0",
"shortdesc" : "Forces agent to use IPv6 addresses only",
"order" : 1 },
"udpport" : {
"getopt" : "u:",
"longopt" : "udpport",
"help" : "-u, --udpport UDP/TCP port to use",
"required" : "0",
"shortdesc" : "UDP/TCP port to use for connection with device",
"order" : 1},
"separator" : {
"getopt" : "C:",
"longopt" : "separator",
"help" : "-C, --separator=<char> Separator for CSV created by 'list' operation",
"default" : ",",
"required" : "0",
"shortdesc" : "Separator for CSV created by operation list",
"order" : 100 },
"login_timeout" : {
"getopt" : "y:",
"longopt" : "login-timeout",
"help" : "--login-timeout <seconds> Wait X seconds for cmd prompt after login",
"default" : "5",
"required" : "0",
"shortdesc" : "Wait X seconds for cmd prompt after login",
"order" : 200 },
"shell_timeout" : {
"getopt" : "Y:",
"longopt" : "shell-timeout",
"help" : "--shell-timeout <seconds> Wait X seconds for cmd prompt after issuing command",
"default" : "3",
"required" : "0",
"shortdesc" : "Wait X seconds for cmd prompt after issuing command",
"order" : 200 },
"power_timeout" : {
"getopt" : "g:",
"longopt" : "power-timeout",
"help" : "--power-timeout <seconds> Test X seconds for status change after ON/OFF",
"default" : "20",
"required" : "0",
"shortdesc" : "Test X seconds for status change after ON/OFF",
"order" : 200 },
"power_wait" : {
"getopt" : "G:",
"longopt" : "power-wait",
"help" : "--power-wait <seconds> Wait X seconds after issuing ON/OFF",
"default" : "0",
"required" : "0",
"shortdesc" : "Wait X seconds after issuing ON/OFF",
"order" : 200 },
"missing_as_off" : {
"getopt" : "M",
"longopt" : "missing-as-off",
"help" : "--missing-as-off Missing port returns OFF instead of failure",
"required" : "0",
"shortdesc" : "Missing port returns OFF instead of failure",
"order" : 200 },
"retry_on" : {
"getopt" : "F:",
"longopt" : "retry-on",
"help" : "--retry-on <attempts> Count of attempts to retry power on",
"default" : "1",
"required" : "0",
"shortdesc" : "Count of attempts to retry power on",
"order" : 200 },
"session_url" : {
"getopt" : "s:",
"longopt" : "session-url",
"help" : "-s, --session-url URL to connect to XenServer on.",
"required" : "1",
"shortdesc" : "The URL of the XenServer host.",
"order" : 1},
"vm_name" : {
"getopt" : "n:",
"longopt" : "vm-name",
"help" : "-n, --vm-name Name of the VM to fence.",
"required" : "0",
"shortdesc" : "The name of the virual machine to fence.",
"order" : 1},
"uuid" : {
"getopt" : "U:",
"longopt" : "uuid",
"help" : "-U, --uuid UUID of the VM to fence.",
"required" : "0",
"shortdesc" : "The UUID of the virtual machine to fence.",
"order" : 1}
}
common_opt = [ "retry_on", "delay" ]
class fspawn(pexpect.spawn):
def log_expect(self, options, pattern, timeout):
result = self.expect(pattern, timeout)
if options["log"] >= LOG_MODE_VERBOSE:
options["debug_fh"].write(self.before + self.after)
return result
def atexit_handler():
try:
sys.stdout.close()
os.close(1)
except IOError:
sys.stderr.write("%s failed to close standard output\n"%(sys.argv[0]))
sys.exit(EC_GENERIC_ERROR)
def version(command, release, build_date, copyright_notice):
print command, " ", release, " ", build_date
if len(copyright_notice) > 0:
print copyright_notice
def fail_usage(message = ""):
if len(message) > 0:
sys.stderr.write(message+"\n")
sys.stderr.write("Please use '-h' for usage\n")
sys.exit(EC_GENERIC_ERROR)
def fail(error_code):
message = {
EC_LOGIN_DENIED : "Unable to connect/login to fencing device",
EC_CONNECTION_LOST : "Connection lost",
EC_TIMED_OUT : "Connection timed out",
EC_WAITING_ON : "Failed: Timed out waiting to power ON",
EC_WAITING_OFF : "Failed: Timed out waiting to power OFF",
EC_STATUS : "Failed: Unable to obtain correct plug status or plug is not available",
EC_STATUS_HMC : "Failed: Either unable to obtaion correct plug status, partition is not available or incorrect HMC version used"
}[error_code] + "\n"
sys.stderr.write(message)
sys.exit(EC_GENERIC_ERROR)
def usage(avail_opt):
global all_opt
print "Usage:"
print "\t" + os.path.basename(sys.argv[0]) + " [options]"
print "Options:"
sorted_list = [ (key, all_opt[key]) for key in avail_opt ]
sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"]))
for key, value in sorted_list:
if len(value["help"]) != 0:
print " " + value["help"]
def metadata(avail_opt, options, docs):
global all_opt
sorted_list = [ (key, all_opt[key]) for key in avail_opt ]
sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"]))
print "<?xml version=\"1.0\" ?>"
print "<resource-agent name=\"" + os.path.basename(sys.argv[0]) + "\" shortdesc=\"" + docs["shortdesc"] + "\" >"
print "<longdesc>" + docs["longdesc"] + "</longdesc>"
if docs.has_key("vendorurl"):
print "<vendor-url>" + docs["vendorurl"] + "</vendor-url>"
print "<parameters>"
for option, value in sorted_list:
if all_opt[option].has_key("shortdesc"):
print "\t<parameter name=\"" + option + "\" unique=\"1\" required=\"" + all_opt[option]["required"] + "\">"
default = ""
if all_opt[option].has_key("default"):
default = "default=\""+str(all_opt[option]["default"])+"\""
elif options.has_key("-" + all_opt[option]["getopt"][:-1]):
if options["-" + all_opt[option]["getopt"][:-1]]:
try:
default = "default=\"" + options["-" + all_opt[option]["getopt"][:-1]] + "\""
except TypeError:
## @todo/@note: Currently there is no clean way how to handle lists
## we can create a string from it but we can't set it on command line
default = "default=\"" + str(options["-" + all_opt[option]["getopt"][:-1]]) +"\""
elif options.has_key("-" + all_opt[option]["getopt"]):
default = "default=\"true\" "
mixed = all_opt[option]["help"]
## split it between option and help text
res = re.compile("^(.*--\S+)\s+", re.IGNORECASE | re.S).search(mixed)
if (None != res):
mixed = res.group(1)
mixed = mixed.replace("<", "<").replace(">", ">")
print "\t\t<getopt mixed=\"" + mixed + "\" />"
if all_opt[option]["getopt"].count(":") > 0:
print "\t\t<content type=\"string\" "+default+" />"
else:
print "\t\t<content type=\"boolean\" "+default+" />"
print "\t\t<shortdesc lang=\"en\">" + all_opt[option]["shortdesc"] + "</shortdesc>"
print "\t</parameter>"
print "</parameters>"
print "<actions>"
print "\t<action name=\"on\" />"
print "\t<action name=\"off\" />"
print "\t<action name=\"reboot\" />"
print "\t<action name=\"status\" />"
print "\t<action name=\"list\" />"
print "\t<action name=\"monitor\" />"
print "\t<action name=\"metadata\" />"
print "</actions>"
print "</resource-agent>"
def process_input(avail_opt):
global all_opt
global common_opt
##
## Add options which are available for every fence agent
#####
avail_opt.extend(common_opt)
##
## Set standard environment
#####
os.putenv("LANG", "C")
os.putenv("LC_ALL", "C")
##
## Prepare list of options for getopt
#####
getopt_string = ""
longopt_list = [ ]
for k in avail_opt:
if all_opt.has_key(k):
getopt_string += all_opt[k]["getopt"]
else:
fail_usage("Parse error: unknown option '"+k+"'")
if all_opt.has_key(k) and all_opt[k].has_key("longopt"):
if all_opt[k]["getopt"].endswith(":"):
longopt_list.append(all_opt[k]["longopt"] + "=")
else:
longopt_list.append(all_opt[k]["longopt"])
## Compatibility layer
if avail_opt.count("module_name") == 1:
getopt_string += "n:"
longopt_list.append("plug=")
##
## Read options from command line or standard input
#####
if len(sys.argv) > 1:
try:
opt, args = getopt.gnu_getopt(sys.argv[1:], getopt_string, longopt_list)
except getopt.GetoptError, error:
fail_usage("Parse error: " + error.msg)
## Transform longopt to short one which are used in fencing agents
#####
old_opt = opt
opt = { }
for o in dict(old_opt).keys():
if o.startswith("--"):
for x in all_opt.keys():
if all_opt[x].has_key("longopt") and "--" + all_opt[x]["longopt"] == o:
opt["-" + all_opt[x]["getopt"].rstrip(":")] = dict(old_opt)[o]
else:
opt[o] = dict(old_opt)[o]
## Compatibility Layer
#####
z = dict(opt)
if z.has_key("-T") == 1:
z["-o"] = "status"
if z.has_key("-n") == 1:
z["-m"] = z["-n"]
opt = z
##
#####
else:
opt = { }
name = ""
for line in sys.stdin.readlines():
line = line.strip()
if ((line.startswith("#")) or (len(line) == 0)):
continue
(name, value) = (line + "=").split("=", 1)
value = value[:-1]
## Compatibility Layer
######
if name == "blade":
name = "port"
elif name == "option":
name = "action"
elif name == "fm":
name = "port"
elif name == "hostname":
name = "ipaddr"
elif name == "modulename":
name = "module_name"
elif name == "action" and 1 == avail_opt.count("io_fencing"):
name = "io_fencing"
elif name == "port" and 1 == avail_opt.count("drac_version"):
name = "module_name"
##
######
if avail_opt.count(name) == 0:
sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n")
continue
if all_opt[name]["getopt"].endswith(":"):
opt["-"+all_opt[name]["getopt"].rstrip(":")] = value
elif ((value == "1") or (value.lower() == "yes")):
opt["-"+all_opt[name]["getopt"]] = "1"
return opt
##
## This function checks input and answers if we want to have same answers
## in each of the fencing agents. It looks for possible errors and run
## password script to set a correct password
######
def check_input(device_opt, opt):
global all_opt
global common_opt
##
## Add options which are available for every fence agent
#####
device_opt.extend([x for x in common_opt if device_opt.count(x) == 0])
options = dict(opt)
options["device_opt"] = device_opt
## Set requirements that should be included in metadata
#####
if device_opt.count("login") and device_opt.count("no_login") == 0:
all_opt["login"]["required"] = "1"
else:
all_opt["login"]["required"] = "0"
## In special cases (show help, metadata or version) we don't need to check anything
#####
if options.has_key("-h") or options.has_key("-V") or (options.has_key("-o") and options["-o"].lower() == "metadata"):
return options;
## Set default values
#####
for opt in device_opt:
if all_opt[opt].has_key("default"):
getopt = "-" + all_opt[opt]["getopt"].rstrip(":")
if 0 == options.has_key(getopt):
options[getopt] = all_opt[opt]["default"]
options["-o"]=options["-o"].lower()
if options.has_key("-v"):
options["log"] = LOG_MODE_VERBOSE
else:
options["log"] = LOG_MODE_QUIET
if 0 == device_opt.count("io_fencing"):
if 0 == ["on", "off", "reboot", "status", "list", "monitor"].count(options["-o"].lower()):
fail_usage("Failed: Unrecognised action '" + options["-o"] + "'")
else:
if 0 == ["enable", "disable", "status", "list", "monitor"].count(options["-o"].lower()):
fail_usage("Failed: Unrecognised action '" + options["-o"] + "'")
if (0 == options.has_key("-l")) and device_opt.count("login") and (device_opt.count("no_login") == 0):
fail_usage("Failed: You have to set login name")
if 0 == options.has_key("-a") and 0 == options.has_key("-s"):
fail_usage("Failed: You have to enter fence address")
if (0 == ["list", "monitor"].count(options["-o"].lower())) and device_opt.count("vm_name") and device_opt.count("uuid"):
if 0 == options.has_key("-n") and 0 == options.has_key("-U"):
fail_usage("Failed: You must specify either UUID or VM name")
if (device_opt.count("no_password") == 0):
if 0 == device_opt.count("identity_file"):
if 0 == (options.has_key("-p") or options.has_key("-S")):
fail_usage("Failed: You have to enter password or password script")
else:
if 0 == (options.has_key("-p") or options.has_key("-S") or options.has_key("-k")):
fail_usage("Failed: You have to enter password, password script or identity file")
if 0 == options.has_key("-x") and 1 == options.has_key("-k"):
fail_usage("Failed: You have to use identity file together with ssh connection (-x)")
if 1 == options.has_key("-k"):
if 0 == os.path.isfile(options["-k"]):
fail_usage("Failed: Identity file " + options["-k"] + " does not exist")
if (0 == ["list", "monitor"].count(options["-o"].lower())) and (0 == options.has_key("-n")) and (device_opt.count("port")):
fail_usage("Failed: You have to enter plug number")
if options.has_key("-S"):
options["-p"] = os.popen(options["-S"]).read().rstrip()
if options.has_key("-D"):
try:
options["debug_fh"] = file (options["-D"], "w")
except IOError:
fail_usage("Failed: Unable to create file "+options["-D"])
if options.has_key("-v") and options.has_key("debug_fh") == 0:
options["debug_fh"] = sys.stderr
if options.has_key("-R"):
options["-P"] = os.popen(options["-R"]).read().rstrip()
if options.has_key("-u") == False:
if options.has_key("-x"):
options["-u"] = 22
elif options.has_key("-z"):
options["-u"] = 443
elif device_opt.count("web"):
options["-u"] = 80
else:
options["-u"] = 23
return options
def wait_power_status(tn, options, get_power_fn):
for dummy in xrange(int(options["-g"])):
if get_power_fn(tn, options) != options["-o"]:
time.sleep(1)
else:
return 1
return 0
def show_docs(options, docs = None):
device_opt = options["device_opt"]
if docs == None:
docs = { }
docs["shortdesc"] = "Fence agent"
docs["longdesc"] = ""
## Process special options (and exit)
#####
if options.has_key("-h"):
usage(device_opt)
sys.exit(0)
if options.has_key("-o") and options["-o"].lower() == "metadata":
metadata(device_opt, options, docs)
sys.exit(0)
if options.has_key("-V"):
print __main__.RELEASE_VERSION, __main__.BUILD_DATE
print __main__.REDHAT_COPYRIGHT
sys.exit(0)
def fence_action(tn, options, set_power_fn, get_power_fn, get_outlet_list = None):
result = 0
## Process options that manipulate fencing device
#####
if (options["-o"] == "list") and (0 == options["device_opt"].count("port")) and (0 == options["device_opt"].count("partition")) and (0 == options["device_opt"].count("uuid")):
print "N/A"
return
elif (options["-o"] == "list" and get_outlet_list == None):
## @todo: exception?
## This is just temporal solution, we will remove default value
## None as soon as all existing agent will support this operation
print "NOTICE: List option is not working on this device yet"
return
elif (options["-o"] == "list") or ((options["-o"] == "monitor") and 1 == options["device_opt"].count("port")):
outlets = get_outlet_list(tn, options)
## keys can be numbers (port numbers) or strings (names of VM)
for o in outlets.keys():
(alias, status) = outlets[o]
if options["-o"] != "monitor":
print o + options["-C"] + alias
return
if options["-o"] in ["off", "reboot"]:
time.sleep(int(options["-f"]))
status = get_power_fn(tn, options)
if status != "on" and status != "off":
fail(EC_STATUS)
if options["-o"] == "enable":
options["-o"] = "on"
if options["-o"] == "disable":
options["-o"] = "off"
if options["-o"] == "on":
if status == "on":
print "Success: Already ON"
else:
power_on = False
for i in range(1,1 + int(options["-F"])):
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn):
power_on = True
break
if power_on:
print "Success: Powered ON"
else:
fail(EC_WAITING_ON)
elif options["-o"] == "off":
if status == "off":
print "Success: Already OFF"
else:
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn):
print "Success: Powered OFF"
else:
fail(EC_WAITING_OFF)
elif options["-o"] == "reboot":
if status != "off":
options["-o"] = "off"
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn) == 0:
fail(EC_WAITING_OFF)
options["-o"] = "on"
power_on = False
for i in range(1,1 + int(options["-F"])):
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn) == 1:
power_on = True
break
if power_on == False:
# this should not fail as not was fenced succesfully
sys.stderr.write('Timed out waiting to power ON\n')
print "Success: Rebooted"
elif options["-o"] == "status":
print "Status: " + status.upper()
if status.upper() == "OFF":
result = 2
elif options["-o"] == "monitor":
1
return result
def fence_login(options):
force_ipvx=""
if (options.has_key("-6")):
force_ipvx="-6 "
if (options.has_key("-4")):
force_ipvx="-4 "
if (options["device_opt"].count("login_eol_lf")):
login_eol = "\n"
else:
login_eol = "\r\n"
try:
re_login = re.compile("(login\s*: )|(Login Name: )|(username: )|(User Name :)", re.IGNORECASE)
re_pass = re.compile("password", re.IGNORECASE)
if options.has_key("-z"):
command = '%s %s %s %s' % (SSL_PATH, force_ipvx, options["-a"], options["-u"])
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
## SSL telnet is part of the fencing package
sys.stderr.write(str(ex) + "\n")
sys.exit(EC_GENERIC_ERROR)
elif options.has_key("-x") and 0 == options.has_key("-k"):
command = '%s %s %s@%s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-u"])
if options.has_key("ssh_options"):
command += ' ' + options["ssh_options"]
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
if options.has_key("telnet_over_ssh"):
#This is for stupid ssh servers (like ALOM) which behave more like telnet (ignore name and display login prompt)
result = conn.log_expect(options, [ re_login, "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"]))
if result == 1:
conn.sendline("yes") # Host identity confirm
conn.log_expect(options, re_login, int(options["-y"]))
conn.sendline(options["-l"])
conn.log_expect(options, re_pass, int(options["-y"]))
else:
result = conn.log_expect(options, [ "ssword:", "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"]))
if result == 1:
conn.sendline("yes")
conn.log_expect(options, "ssword:", int(options["-y"]))
conn.sendline(options["-p"])
conn.log_expect(options, options["-c"], int(options["-y"]))
elif options.has_key("-x") and 1 == options.has_key("-k"):
command = '%s %s %s@%s -i %s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-k"], options["-u"])
if options.has_key("ssh_options"):
command += ' ' + options["ssh_options"]
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
result = conn.log_expect(options, [ options["-c"], "Are you sure you want to continue connecting (yes/no)?", "Enter passphrase for key '"+options["-k"]+"':" ], int(options["-y"]))
if result == 1:
conn.sendline("yes")
conn.log_expect(options, [ options["-c"], "Enter passphrase for key '"+options["-k"]+"':"] , int(options["-y"]))
if result != 0:
if options.has_key("-p"):
conn.sendline(options["-p"])
conn.log_expect(options, options["-c"], int(options["-y"]))
else:
fail_usage("Failed: You have to enter passphrase (-p) for identity file")
else:
try:
conn = fspawn(TELNET_PATH)
conn.send("set binary\n")
conn.send("open %s -%s\n"%(options["-a"], options["-u"]))
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
conn.log_expect(options, re_login, int(options["-y"]))
conn.send(options["-l"] + login_eol)
conn.log_expect(options, re_pass, int(options["-Y"]))
conn.send(options["-p"] + login_eol)
conn.log_expect(options, options["-c"], int(options["-Y"]))
except pexpect.EOF:
fail(EC_LOGIN_DENIED)
except pexpect.TIMEOUT:
fail(EC_LOGIN_DENIED)
return conn
| Python |
#!/usr/bin/python
#
#############################################################################
# Copyright 2011 Matt Clark
# This file is part of fence-xenserver
#
# fence-xenserver is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# fence-xenserver is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
#############################################################################
#############################################################################
# It's only just begun...
# Current status: completely usable. This script is now working well and,
# has a lot of functionality as a result of the fencing.py library and the
# XenAPI libary.
#############################################################################
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
import sys
sys.path.append("/usr/lib/fence")
from fencing import *
import XenAPI
EC_BAD_SESSION = 1
# Find the status of the port given in the -U flag of options.
def get_power_fn(session, options):
if options.has_key("-v"):
verbose = True
else:
verbose = False
try:
# Get a reference to the vm specified in the UUID or vm_name parameter
vm = return_vm_reference(session, options)
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm);
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
status = record["power_state"]
if verbose: print "UUID:", record["uuid"], "NAME:", record["name_label"], "POWER STATUS:", record["power_state"]
# Note that the VM can be in the following states (from the XenAPI document)
# Halted: VM is offline and not using any resources.
# Paused: All resources have been allocated but the VM itself is paused and its vCPUs are not running
# Running: Running
# Paused: VM state has been saved to disk and it is nolonger running. Note that disks remain in-Use while
# We want to make sure that we only return the status "off" if the machine is actually halted as the status
# is checked before a fencing action. Only when the machine is Halted is it not consuming resources which
# may include whatever you are trying to protect with this fencing action.
return (status=="Halted" and "off" or "on")
except Exception, exn:
print str(exn)
return "Error"
# Set the state of the port given in the -U flag of options.
def set_power_fn(session, options):
action = options["-o"].lower()
if options.has_key("-v"):
verbose = True
else:
verbose = False
try:
# Get a reference to the vm specified in the UUID or vm_name parameter
vm = return_vm_reference(session, options)
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm)
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
# Start the VM
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
# Force shutdown the VM
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
# Force reboot the VM
session.xenapi.VM.hard_reboot(vm)
except Exception, exn:
print str(exn);
# Function to populate an array of virtual machines and their status
def get_outlet_list(session, options):
result = {}
if options.has_key("-v"):
verbose = True
else:
verbose = False
try:
# Return an array of all the VM's on the host
vms = session.xenapi.VM.get_all()
for vm in vms:
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm);
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
uuid = record["uuid"]
status = record["power_state"]
result[uuid] = (name, status)
if verbose: print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
return result
# Function to initiate the XenServer session via the XenAPI library.
def connect_and_login(options):
url = options["-s"]
username = options["-l"]
password = options["-p"]
try:
# Create the XML RPC session to the specified URL.
session = XenAPI.Session(url);
# Login using the supplied credentials.
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
# http://sources.redhat.com/cluster/wiki/FenceAgentAPI says that for no connectivity
# the exit value should be 1. It doesn't say anything about failed logins, so
# until I hear otherwise it is best to keep this exit the same to make sure that
# anything calling this script (that uses the same information in the web page
# above) knows that this is an error condition, not a msg signifying a down port.
sys.exit(EC_BAD_SESSION);
return session;
# return a reference to the VM by either using the UUID or the vm_name. If the UUID is set then
# this is tried first as this is the only properly unique identifier.
# Exceptions are not handled in this function, code that calls this must be ready to handle them.
def return_vm_reference(session, options):
if options.has_key("-v"):
verbose = True
else:
verbose = False
# Case where the UUID has been specified
if options.has_key("-U"):
uuid = options["-U"].lower()
# When using the -n parameter for name, we get an error message (in verbose
# mode) that tells us that we didn't find a VM. To immitate that here we
# need to catch and re-raise the exception produced by get_by_uuid.
try:
return session.xenapi.VM.get_by_uuid(uuid)
except Exception,exn:
if verbose: print "No VM's found with a UUID of \"%s\"" %uuid
raise
# Case where the vm_name has been specified
if options.has_key("-n"):
vm_name = options["-n"]
vm_arr = session.xenapi.VM.get_by_name_label(vm_name)
# Need to make sure that we only have one result as the vm_name may
# not be unique. Average case, so do it first.
if len(vm_arr) == 1:
return vm_arr[0]
else:
if len(vm_arr) == 0:
if verbose: print "No VM's found with a name of \"%s\"" %vm_name
# NAME_INVALID used as the XenAPI throws a UUID_INVALID if it can't find
# a VM with the specified UUID. This should make the output look fairly
# consistent.
raise Exception("NAME_INVALID")
else:
if verbose: print "Multiple VM's have the name \"%s\", use UUID instead" %vm_name
raise Exception("MULTIPLE_VMS_FOUND")
# We should never get to this case as the input processing checks that either the UUID or
# the name parameter is set. Regardless of whether or not a VM is found the above if
# statements will return to the calling function (either by exception or by a reference
# to the VM).
raise Exception("VM_LOGIC_ERROR")
def main():
device_opt = [ "help", "version", "agent", "quiet", "verbose", "debug", "action",
"login", "passwd", "passwd_script", "vm_name", "test", "separator",
"no_login", "no_password", "power_timeout", "shell_timeout",
"login_timeout", "power_wait", "session_url", "uuid" ]
atexit.register(atexit_handler)
options=process_input(device_opt)
options = check_input(device_opt, options)
docs = { }
docs["shortdesc"] = "XenAPI based fencing for the Citrix XenServer virtual machines."
docs["longdesc"] = "\
fence_cxs is an I/O Fencing agent used on Citrix XenServer hosts. \
It uses the XenAPI, supplied by Citrix, to establish an XML-RPC sesssion \
to a XenServer host. Once the session is established, further XML-RPC \
commands are issued in order to switch on, switch off, restart and query \
the status of virtual machines running on the host."
show_docs(options, docs)
xenSession = connect_and_login(options)
# Operate the fencing device
result = fence_action(xenSession, options, set_power_fn, get_power_fn, get_outlet_list)
sys.exit(result)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
import sys, getopt, time, os
import pexpect, re
import telnetlib
import atexit
import __main__
## do not add code here.
#BEGIN_VERSION_GENERATION
RELEASE_VERSION="3.0.17"
BUILD_DATE="(built Thu Oct 7 07:06:21 UTC 2010)"
REDHAT_COPYRIGHT="Copyright (C) Red Hat, Inc. 2004-2010 All rights reserved."
#END_VERSION_GENERATION
LOG_MODE_VERBOSE = 100
LOG_MODE_QUIET = 0
EC_GENERIC_ERROR = 1
EC_BAD_ARGS = 2
EC_LOGIN_DENIED = 3
EC_CONNECTION_LOST = 4
EC_TIMED_OUT = 5
EC_WAITING_ON = 6
EC_WAITING_OFF = 7
EC_STATUS = 8
EC_STATUS_HMC = 9
TELNET_PATH = "/usr/bin/telnet"
SSH_PATH = "/usr/bin/ssh"
SSL_PATH = "/usr/sbin/fence_nss_wrapper"
all_opt = {
"help" : {
"getopt" : "h",
"longopt" : "help",
"help" : "-h, --help Display this help and exit",
"required" : "0",
"shortdesc" : "Display help and exit",
"order" : 54 },
"version" : {
"getopt" : "V",
"longopt" : "version",
"help" : "-V, --version Output version information and exit",
"required" : "0",
"shortdesc" : "Display version information and exit",
"order" : 53 },
"quiet" : {
"getopt" : "q",
"help" : "",
"order" : 50 },
"verbose" : {
"getopt" : "v",
"longopt" : "verbose",
"help" : "-v, --verbose Verbose mode",
"required" : "0",
"shortdesc" : "Verbose mode",
"order" : 51 },
"debug" : {
"getopt" : "D:",
"longopt" : "debug-file",
"help" : "-D, --debug-file=<debugfile> Debugging to output file",
"required" : "0",
"shortdesc" : "Write debug information to given file",
"order" : 52 },
"delay" : {
"getopt" : "f:",
"longopt" : "delay",
"help" : "--delay <seconds> Wait X seconds before fencing is started",
"required" : "0",
"shortdesc" : "Wait X seconds before fencing is started",
"default" : "0",
"order" : 200 },
"agent" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"web" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"action" : {
"getopt" : "o:",
"longopt" : "action",
"help" : "-o, --action=<action> Action: status, reboot (default), off or on",
"required" : "1",
"shortdesc" : "Fencing Action",
"default" : "reboot",
"order" : 1 },
"io_fencing" : {
"getopt" : "o:",
"longopt" : "action",
"help" : "-o, --action=<action> Action: status, enable or disable",
"required" : "1",
"shortdesc" : "Fencing Action",
"default" : "disable",
"order" : 1 },
"ipaddr" : {
"getopt" : "a:",
"longopt" : "ip",
"help" : "-a, --ip=<ip> IP address or hostname of fencing device",
"required" : "1",
"shortdesc" : "IP Address or Hostname",
"order" : 1 },
"ipport" : {
"getopt" : "u:",
"longopt" : "ipport",
"help" : "-u, --ipport=<port> TCP port to use",
"required" : "0",
"shortdesc" : "TCP port to use for connection with device",
"order" : 1 },
"login" : {
"getopt" : "l:",
"longopt" : "username",
"help" : "-l, --username=<name> Login name",
"required" : "?",
"shortdesc" : "Login Name",
"order" : 1 },
"no_login" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"no_password" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"passwd" : {
"getopt" : "p:",
"longopt" : "password",
"help" : "-p, --password=<password> Login password or passphrase",
"required" : "0",
"shortdesc" : "Login password or passphrase",
"order" : 1 },
"passwd_script" : {
"getopt" : "S:",
"longopt" : "password-script=",
"help" : "-S, --password-script=<script> Script to run to retrieve password",
"required" : "0",
"shortdesc" : "Script to retrieve password",
"order" : 1 },
"identity_file" : {
"getopt" : "k:",
"longopt" : "identity-file",
"help" : "-k, --identity-file=<filename> Identity file (private key) for ssh ",
"required" : "0",
"shortdesc" : "Identity file for ssh",
"order" : 1 },
"module_name" : {
"getopt" : "m:",
"longopt" : "module-name",
"help" : "-m, --module-name=<module> DRAC/MC module name",
"required" : "0",
"shortdesc" : "DRAC/MC module name",
"order" : 1 },
"drac_version" : {
"getopt" : "d:",
"longopt" : "drac-version",
"help" : "-d, --drac-version=<version> Force DRAC version to use",
"required" : "0",
"shortdesc" : "Force DRAC version to use",
"order" : 1 },
"hmc_version" : {
"getopt" : "H:",
"longopt" : "hmc-version",
"help" : "-H, --hmc-version=<version> Force HMC version to use: 3, 4 (default)",
"required" : "0",
"shortdesc" : "Force HMC version to use (3 or 4)",
"default" : "4",
"order" : 1 },
"ribcl" : {
"getopt" : "r:",
"longopt" : "ribcl-version",
"help" : "-r, --ribcl-version=<version> Force ribcl version to use",
"required" : "0",
"shortdesc" : "Force ribcl version to use",
"order" : 1 },
"login_eol_lf" : {
"getopt" : "",
"help" : "",
"order" : 1
},
"cmd_prompt" : {
"getopt" : "c:",
"longopt" : "command-prompt",
"help" : "-c, --command-prompt=<prompt> Force command prompt",
"shortdesc" : "Force command prompt",
"required" : "0",
"order" : 1 },
"secure" : {
"getopt" : "x",
"longopt" : "ssh",
"help" : "-x, --ssh Use ssh connection",
"shortdesc" : "SSH connection",
"required" : "0",
"order" : 1 },
"ssl" : {
"getopt" : "z",
"longopt" : "ssl",
"help" : "-z, --ssl Use ssl connection",
"required" : "0",
"shortdesc" : "SSL connection",
"order" : 1 },
"port" : {
"getopt" : "n:",
"longopt" : "plug",
"help" : "-n, --plug=<id> Physical plug number on device or\n" +
" name of virtual machine",
"required" : "1",
"shortdesc" : "Physical plug number or name of virtual machine",
"order" : 1 },
"switch" : {
"getopt" : "s:",
"longopt" : "switch",
"help" : "-s, --switch=<id> Physical switch number on device",
"required" : "0",
"shortdesc" : "Physical switch number on device",
"order" : 1 },
"partition" : {
"getopt" : "n:",
"help" : "-n <id> Name of the partition",
"required" : "0",
"shortdesc" : "Partition name",
"order" : 1 },
"managed" : {
"getopt" : "s:",
"help" : "-s <id> Name of the managed system",
"required" : "0",
"shortdesc" : "Managed system name",
"order" : 1 },
"test" : {
"getopt" : "T",
"help" : "",
"order" : 1,
"obsolete" : "use -o status instead" },
"exec" : {
"getopt" : "e:",
"longopt" : "exec",
"help" : "-e, --exec=<command> Command to execute",
"required" : "0",
"shortdesc" : "Command to execute",
"order" : 1 },
"vmware_type" : {
"getopt" : "d:",
"longopt" : "vmware_type",
"help" : "-d, --vmware_type=<type> Type of VMware to connect",
"required" : "0",
"shortdesc" : "Type of VMware to connect",
"order" : 1 },
"vmware_datacenter" : {
"getopt" : "s:",
"longopt" : "vmware-datacenter",
"help" : "-s, --vmware-datacenter=<dc> VMWare datacenter filter",
"required" : "0",
"shortdesc" : "Show only machines in specified datacenter",
"order" : 2 },
"snmp_version" : {
"getopt" : "d:",
"longopt" : "snmp-version",
"help" : "-d, --snmp-version=<ver> Specifies SNMP version to use",
"required" : "0",
"shortdesc" : "Specifies SNMP version to use (1,2c,3)",
"order" : 1 },
"community" : {
"getopt" : "c:",
"longopt" : "community",
"help" : "-c, --community=<community> Set the community string",
"required" : "0",
"shortdesc" : "Set the community string",
"order" : 1},
"snmp_auth_prot" : {
"getopt" : "b:",
"longopt" : "snmp-auth-prot",
"help" : "-b, --snmp-auth-prot=<prot> Set authentication protocol (MD5|SHA)",
"required" : "0",
"shortdesc" : "Set authentication protocol (MD5|SHA)",
"order" : 1},
"snmp_sec_level" : {
"getopt" : "E:",
"longopt" : "snmp-sec-level",
"help" : "-E, --snmp-sec-level=<level> Set security level\n"+
" (noAuthNoPriv|authNoPriv|authPriv)",
"required" : "0",
"shortdesc" : "Set security level (noAuthNoPriv|authNoPriv|authPriv)",
"order" : 1},
"snmp_priv_prot" : {
"getopt" : "B:",
"longopt" : "snmp-priv-prot",
"help" : "-B, --snmp-priv-prot=<prot> Set privacy protocol (DES|AES)",
"required" : "0",
"shortdesc" : "Set privacy protocol (DES|AES)",
"order" : 1},
"snmp_priv_passwd" : {
"getopt" : "P:",
"longopt" : "snmp-priv-passwd",
"help" : "-P, --snmp-priv-passwd=<pass> Set privacy protocol password",
"required" : "0",
"shortdesc" : "Set privacy protocol password",
"order" : 1},
"snmp_priv_passwd_script" : {
"getopt" : "R:",
"longopt" : "snmp-priv-passwd-script",
"help" : "-R, --snmp-priv-passwd-script Script to run to retrieve privacy password",
"required" : "0",
"shortdesc" : "Script to run to retrieve privacy password",
"order" : 1},
"inet4_only" : {
"getopt" : "4",
"longopt" : "inet4-only",
"help" : "-4, --inet4-only Forces agent to use IPv4 addresses only",
"required" : "0",
"shortdesc" : "Forces agent to use IPv4 addresses only",
"order" : 1 },
"inet6_only" : {
"getopt" : "6",
"longopt" : "inet6-only",
"help" : "-6, --inet6-only Forces agent to use IPv6 addresses only",
"required" : "0",
"shortdesc" : "Forces agent to use IPv6 addresses only",
"order" : 1 },
"udpport" : {
"getopt" : "u:",
"longopt" : "udpport",
"help" : "-u, --udpport UDP/TCP port to use",
"required" : "0",
"shortdesc" : "UDP/TCP port to use for connection with device",
"order" : 1},
"separator" : {
"getopt" : "C:",
"longopt" : "separator",
"help" : "-C, --separator=<char> Separator for CSV created by 'list' operation",
"default" : ",",
"required" : "0",
"shortdesc" : "Separator for CSV created by operation list",
"order" : 100 },
"login_timeout" : {
"getopt" : "y:",
"longopt" : "login-timeout",
"help" : "--login-timeout <seconds> Wait X seconds for cmd prompt after login",
"default" : "5",
"required" : "0",
"shortdesc" : "Wait X seconds for cmd prompt after login",
"order" : 200 },
"shell_timeout" : {
"getopt" : "Y:",
"longopt" : "shell-timeout",
"help" : "--shell-timeout <seconds> Wait X seconds for cmd prompt after issuing command",
"default" : "3",
"required" : "0",
"shortdesc" : "Wait X seconds for cmd prompt after issuing command",
"order" : 200 },
"power_timeout" : {
"getopt" : "g:",
"longopt" : "power-timeout",
"help" : "--power-timeout <seconds> Test X seconds for status change after ON/OFF",
"default" : "20",
"required" : "0",
"shortdesc" : "Test X seconds for status change after ON/OFF",
"order" : 200 },
"power_wait" : {
"getopt" : "G:",
"longopt" : "power-wait",
"help" : "--power-wait <seconds> Wait X seconds after issuing ON/OFF",
"default" : "0",
"required" : "0",
"shortdesc" : "Wait X seconds after issuing ON/OFF",
"order" : 200 },
"missing_as_off" : {
"getopt" : "M",
"longopt" : "missing-as-off",
"help" : "--missing-as-off Missing port returns OFF instead of failure",
"required" : "0",
"shortdesc" : "Missing port returns OFF instead of failure",
"order" : 200 },
"retry_on" : {
"getopt" : "F:",
"longopt" : "retry-on",
"help" : "--retry-on <attempts> Count of attempts to retry power on",
"default" : "1",
"required" : "0",
"shortdesc" : "Count of attempts to retry power on",
"order" : 200 },
"session_url" : {
"getopt" : "s:",
"longopt" : "session-url",
"help" : "-s, --session-url URL to connect to XenServer on.",
"required" : "1",
"shortdesc" : "The URL of the XenServer host.",
"order" : 1},
"vm_name" : {
"getopt" : "n:",
"longopt" : "vm-name",
"help" : "-n, --vm-name Name of the VM to fence.",
"required" : "0",
"shortdesc" : "The name of the virual machine to fence.",
"order" : 1},
"uuid" : {
"getopt" : "U:",
"longopt" : "uuid",
"help" : "-U, --uuid UUID of the VM to fence.",
"required" : "0",
"shortdesc" : "The UUID of the virtual machine to fence.",
"order" : 1}
}
common_opt = [ "retry_on", "delay" ]
class fspawn(pexpect.spawn):
def log_expect(self, options, pattern, timeout):
result = self.expect(pattern, timeout)
if options["log"] >= LOG_MODE_VERBOSE:
options["debug_fh"].write(self.before + self.after)
return result
def atexit_handler():
try:
sys.stdout.close()
os.close(1)
except IOError:
sys.stderr.write("%s failed to close standard output\n"%(sys.argv[0]))
sys.exit(EC_GENERIC_ERROR)
def version(command, release, build_date, copyright_notice):
print command, " ", release, " ", build_date
if len(copyright_notice) > 0:
print copyright_notice
def fail_usage(message = ""):
if len(message) > 0:
sys.stderr.write(message+"\n")
sys.stderr.write("Please use '-h' for usage\n")
sys.exit(EC_GENERIC_ERROR)
def fail(error_code):
message = {
EC_LOGIN_DENIED : "Unable to connect/login to fencing device",
EC_CONNECTION_LOST : "Connection lost",
EC_TIMED_OUT : "Connection timed out",
EC_WAITING_ON : "Failed: Timed out waiting to power ON",
EC_WAITING_OFF : "Failed: Timed out waiting to power OFF",
EC_STATUS : "Failed: Unable to obtain correct plug status or plug is not available",
EC_STATUS_HMC : "Failed: Either unable to obtaion correct plug status, partition is not available or incorrect HMC version used"
}[error_code] + "\n"
sys.stderr.write(message)
sys.exit(EC_GENERIC_ERROR)
def usage(avail_opt):
global all_opt
print "Usage:"
print "\t" + os.path.basename(sys.argv[0]) + " [options]"
print "Options:"
sorted_list = [ (key, all_opt[key]) for key in avail_opt ]
sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"]))
for key, value in sorted_list:
if len(value["help"]) != 0:
print " " + value["help"]
def metadata(avail_opt, options, docs):
global all_opt
sorted_list = [ (key, all_opt[key]) for key in avail_opt ]
sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"]))
print "<?xml version=\"1.0\" ?>"
print "<resource-agent name=\"" + os.path.basename(sys.argv[0]) + "\" shortdesc=\"" + docs["shortdesc"] + "\" >"
print "<longdesc>" + docs["longdesc"] + "</longdesc>"
if docs.has_key("vendorurl"):
print "<vendor-url>" + docs["vendorurl"] + "</vendor-url>"
print "<parameters>"
for option, value in sorted_list:
if all_opt[option].has_key("shortdesc"):
print "\t<parameter name=\"" + option + "\" unique=\"1\" required=\"" + all_opt[option]["required"] + "\">"
default = ""
if all_opt[option].has_key("default"):
default = "default=\""+str(all_opt[option]["default"])+"\""
elif options.has_key("-" + all_opt[option]["getopt"][:-1]):
if options["-" + all_opt[option]["getopt"][:-1]]:
try:
default = "default=\"" + options["-" + all_opt[option]["getopt"][:-1]] + "\""
except TypeError:
## @todo/@note: Currently there is no clean way how to handle lists
## we can create a string from it but we can't set it on command line
default = "default=\"" + str(options["-" + all_opt[option]["getopt"][:-1]]) +"\""
elif options.has_key("-" + all_opt[option]["getopt"]):
default = "default=\"true\" "
mixed = all_opt[option]["help"]
## split it between option and help text
res = re.compile("^(.*--\S+)\s+", re.IGNORECASE | re.S).search(mixed)
if (None != res):
mixed = res.group(1)
mixed = mixed.replace("<", "<").replace(">", ">")
print "\t\t<getopt mixed=\"" + mixed + "\" />"
if all_opt[option]["getopt"].count(":") > 0:
print "\t\t<content type=\"string\" "+default+" />"
else:
print "\t\t<content type=\"boolean\" "+default+" />"
print "\t\t<shortdesc lang=\"en\">" + all_opt[option]["shortdesc"] + "</shortdesc>"
print "\t</parameter>"
print "</parameters>"
print "<actions>"
print "\t<action name=\"on\" />"
print "\t<action name=\"off\" />"
print "\t<action name=\"reboot\" />"
print "\t<action name=\"status\" />"
print "\t<action name=\"list\" />"
print "\t<action name=\"monitor\" />"
print "\t<action name=\"metadata\" />"
print "</actions>"
print "</resource-agent>"
def process_input(avail_opt):
global all_opt
global common_opt
##
## Add options which are available for every fence agent
#####
avail_opt.extend(common_opt)
##
## Set standard environment
#####
os.putenv("LANG", "C")
os.putenv("LC_ALL", "C")
##
## Prepare list of options for getopt
#####
getopt_string = ""
longopt_list = [ ]
for k in avail_opt:
if all_opt.has_key(k):
getopt_string += all_opt[k]["getopt"]
else:
fail_usage("Parse error: unknown option '"+k+"'")
if all_opt.has_key(k) and all_opt[k].has_key("longopt"):
if all_opt[k]["getopt"].endswith(":"):
longopt_list.append(all_opt[k]["longopt"] + "=")
else:
longopt_list.append(all_opt[k]["longopt"])
## Compatibility layer
if avail_opt.count("module_name") == 1:
getopt_string += "n:"
longopt_list.append("plug=")
##
## Read options from command line or standard input
#####
if len(sys.argv) > 1:
try:
opt, args = getopt.gnu_getopt(sys.argv[1:], getopt_string, longopt_list)
except getopt.GetoptError, error:
fail_usage("Parse error: " + error.msg)
## Transform longopt to short one which are used in fencing agents
#####
old_opt = opt
opt = { }
for o in dict(old_opt).keys():
if o.startswith("--"):
for x in all_opt.keys():
if all_opt[x].has_key("longopt") and "--" + all_opt[x]["longopt"] == o:
opt["-" + all_opt[x]["getopt"].rstrip(":")] = dict(old_opt)[o]
else:
opt[o] = dict(old_opt)[o]
## Compatibility Layer
#####
z = dict(opt)
if z.has_key("-T") == 1:
z["-o"] = "status"
if z.has_key("-n") == 1:
z["-m"] = z["-n"]
opt = z
##
#####
else:
opt = { }
name = ""
for line in sys.stdin.readlines():
line = line.strip()
if ((line.startswith("#")) or (len(line) == 0)):
continue
(name, value) = (line + "=").split("=", 1)
value = value[:-1]
## Compatibility Layer
######
if name == "blade":
name = "port"
elif name == "option":
name = "action"
elif name == "fm":
name = "port"
elif name == "hostname":
name = "ipaddr"
elif name == "modulename":
name = "module_name"
elif name == "action" and 1 == avail_opt.count("io_fencing"):
name = "io_fencing"
elif name == "port" and 1 == avail_opt.count("drac_version"):
name = "module_name"
##
######
if avail_opt.count(name) == 0:
sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n")
continue
if all_opt[name]["getopt"].endswith(":"):
opt["-"+all_opt[name]["getopt"].rstrip(":")] = value
elif ((value == "1") or (value.lower() == "yes")):
opt["-"+all_opt[name]["getopt"]] = "1"
return opt
##
## This function checks input and answers if we want to have same answers
## in each of the fencing agents. It looks for possible errors and run
## password script to set a correct password
######
def check_input(device_opt, opt):
global all_opt
global common_opt
##
## Add options which are available for every fence agent
#####
device_opt.extend([x for x in common_opt if device_opt.count(x) == 0])
options = dict(opt)
options["device_opt"] = device_opt
## Set requirements that should be included in metadata
#####
if device_opt.count("login") and device_opt.count("no_login") == 0:
all_opt["login"]["required"] = "1"
else:
all_opt["login"]["required"] = "0"
## In special cases (show help, metadata or version) we don't need to check anything
#####
if options.has_key("-h") or options.has_key("-V") or (options.has_key("-o") and options["-o"].lower() == "metadata"):
return options;
## Set default values
#####
for opt in device_opt:
if all_opt[opt].has_key("default"):
getopt = "-" + all_opt[opt]["getopt"].rstrip(":")
if 0 == options.has_key(getopt):
options[getopt] = all_opt[opt]["default"]
options["-o"]=options["-o"].lower()
if options.has_key("-v"):
options["log"] = LOG_MODE_VERBOSE
else:
options["log"] = LOG_MODE_QUIET
if 0 == device_opt.count("io_fencing"):
if 0 == ["on", "off", "reboot", "status", "list", "monitor"].count(options["-o"].lower()):
fail_usage("Failed: Unrecognised action '" + options["-o"] + "'")
else:
if 0 == ["enable", "disable", "status", "list", "monitor"].count(options["-o"].lower()):
fail_usage("Failed: Unrecognised action '" + options["-o"] + "'")
if (0 == options.has_key("-l")) and device_opt.count("login") and (device_opt.count("no_login") == 0):
fail_usage("Failed: You have to set login name")
if 0 == options.has_key("-a") and 0 == options.has_key("-s"):
fail_usage("Failed: You have to enter fence address")
if (0 == ["list", "monitor"].count(options["-o"].lower())) and device_opt.count("vm_name") and device_opt.count("uuid"):
if 0 == options.has_key("-n") and 0 == options.has_key("-U"):
fail_usage("Failed: You must specify either UUID or VM name")
if (device_opt.count("no_password") == 0):
if 0 == device_opt.count("identity_file"):
if 0 == (options.has_key("-p") or options.has_key("-S")):
fail_usage("Failed: You have to enter password or password script")
else:
if 0 == (options.has_key("-p") or options.has_key("-S") or options.has_key("-k")):
fail_usage("Failed: You have to enter password, password script or identity file")
if 0 == options.has_key("-x") and 1 == options.has_key("-k"):
fail_usage("Failed: You have to use identity file together with ssh connection (-x)")
if 1 == options.has_key("-k"):
if 0 == os.path.isfile(options["-k"]):
fail_usage("Failed: Identity file " + options["-k"] + " does not exist")
if (0 == ["list", "monitor"].count(options["-o"].lower())) and (0 == options.has_key("-n")) and (device_opt.count("port")):
fail_usage("Failed: You have to enter plug number")
if options.has_key("-S"):
options["-p"] = os.popen(options["-S"]).read().rstrip()
if options.has_key("-D"):
try:
options["debug_fh"] = file (options["-D"], "w")
except IOError:
fail_usage("Failed: Unable to create file "+options["-D"])
if options.has_key("-v") and options.has_key("debug_fh") == 0:
options["debug_fh"] = sys.stderr
if options.has_key("-R"):
options["-P"] = os.popen(options["-R"]).read().rstrip()
if options.has_key("-u") == False:
if options.has_key("-x"):
options["-u"] = 22
elif options.has_key("-z"):
options["-u"] = 443
elif device_opt.count("web"):
options["-u"] = 80
else:
options["-u"] = 23
return options
def wait_power_status(tn, options, get_power_fn):
for dummy in xrange(int(options["-g"])):
if get_power_fn(tn, options) != options["-o"]:
time.sleep(1)
else:
return 1
return 0
def show_docs(options, docs = None):
device_opt = options["device_opt"]
if docs == None:
docs = { }
docs["shortdesc"] = "Fence agent"
docs["longdesc"] = ""
## Process special options (and exit)
#####
if options.has_key("-h"):
usage(device_opt)
sys.exit(0)
if options.has_key("-o") and options["-o"].lower() == "metadata":
metadata(device_opt, options, docs)
sys.exit(0)
if options.has_key("-V"):
print __main__.RELEASE_VERSION, __main__.BUILD_DATE
print __main__.REDHAT_COPYRIGHT
sys.exit(0)
def fence_action(tn, options, set_power_fn, get_power_fn, get_outlet_list = None):
result = 0
## Process options that manipulate fencing device
#####
if (options["-o"] == "list") and (0 == options["device_opt"].count("port")) and (0 == options["device_opt"].count("partition")) and (0 == options["device_opt"].count("uuid")):
print "N/A"
return
elif (options["-o"] == "list" and get_outlet_list == None):
## @todo: exception?
## This is just temporal solution, we will remove default value
## None as soon as all existing agent will support this operation
print "NOTICE: List option is not working on this device yet"
return
elif (options["-o"] == "list") or ((options["-o"] == "monitor") and 1 == options["device_opt"].count("port")):
outlets = get_outlet_list(tn, options)
## keys can be numbers (port numbers) or strings (names of VM)
for o in outlets.keys():
(alias, status) = outlets[o]
if options["-o"] != "monitor":
print o + options["-C"] + alias
return
if options["-o"] in ["off", "reboot"]:
time.sleep(int(options["-f"]))
status = get_power_fn(tn, options)
if status != "on" and status != "off":
fail(EC_STATUS)
if options["-o"] == "enable":
options["-o"] = "on"
if options["-o"] == "disable":
options["-o"] = "off"
if options["-o"] == "on":
if status == "on":
print "Success: Already ON"
else:
power_on = False
for i in range(1,1 + int(options["-F"])):
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn):
power_on = True
break
if power_on:
print "Success: Powered ON"
else:
fail(EC_WAITING_ON)
elif options["-o"] == "off":
if status == "off":
print "Success: Already OFF"
else:
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn):
print "Success: Powered OFF"
else:
fail(EC_WAITING_OFF)
elif options["-o"] == "reboot":
if status != "off":
options["-o"] = "off"
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn) == 0:
fail(EC_WAITING_OFF)
options["-o"] = "on"
power_on = False
for i in range(1,1 + int(options["-F"])):
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn) == 1:
power_on = True
break
if power_on == False:
# this should not fail as not was fenced succesfully
sys.stderr.write('Timed out waiting to power ON\n')
print "Success: Rebooted"
elif options["-o"] == "status":
print "Status: " + status.upper()
if status.upper() == "OFF":
result = 2
elif options["-o"] == "monitor":
1
return result
def fence_login(options):
force_ipvx=""
if (options.has_key("-6")):
force_ipvx="-6 "
if (options.has_key("-4")):
force_ipvx="-4 "
if (options["device_opt"].count("login_eol_lf")):
login_eol = "\n"
else:
login_eol = "\r\n"
try:
re_login = re.compile("(login\s*: )|(Login Name: )|(username: )|(User Name :)", re.IGNORECASE)
re_pass = re.compile("password", re.IGNORECASE)
if options.has_key("-z"):
command = '%s %s %s %s' % (SSL_PATH, force_ipvx, options["-a"], options["-u"])
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
## SSL telnet is part of the fencing package
sys.stderr.write(str(ex) + "\n")
sys.exit(EC_GENERIC_ERROR)
elif options.has_key("-x") and 0 == options.has_key("-k"):
command = '%s %s %s@%s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-u"])
if options.has_key("ssh_options"):
command += ' ' + options["ssh_options"]
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
if options.has_key("telnet_over_ssh"):
#This is for stupid ssh servers (like ALOM) which behave more like telnet (ignore name and display login prompt)
result = conn.log_expect(options, [ re_login, "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"]))
if result == 1:
conn.sendline("yes") # Host identity confirm
conn.log_expect(options, re_login, int(options["-y"]))
conn.sendline(options["-l"])
conn.log_expect(options, re_pass, int(options["-y"]))
else:
result = conn.log_expect(options, [ "ssword:", "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"]))
if result == 1:
conn.sendline("yes")
conn.log_expect(options, "ssword:", int(options["-y"]))
conn.sendline(options["-p"])
conn.log_expect(options, options["-c"], int(options["-y"]))
elif options.has_key("-x") and 1 == options.has_key("-k"):
command = '%s %s %s@%s -i %s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-k"], options["-u"])
if options.has_key("ssh_options"):
command += ' ' + options["ssh_options"]
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
result = conn.log_expect(options, [ options["-c"], "Are you sure you want to continue connecting (yes/no)?", "Enter passphrase for key '"+options["-k"]+"':" ], int(options["-y"]))
if result == 1:
conn.sendline("yes")
conn.log_expect(options, [ options["-c"], "Enter passphrase for key '"+options["-k"]+"':"] , int(options["-y"]))
if result != 0:
if options.has_key("-p"):
conn.sendline(options["-p"])
conn.log_expect(options, options["-c"], int(options["-y"]))
else:
fail_usage("Failed: You have to enter passphrase (-p) for identity file")
else:
try:
conn = fspawn(TELNET_PATH)
conn.send("set binary\n")
conn.send("open %s -%s\n"%(options["-a"], options["-u"]))
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
conn.log_expect(options, re_login, int(options["-y"]))
conn.send(options["-l"] + login_eol)
conn.log_expect(options, re_pass, int(options["-Y"]))
conn.send(options["-p"] + login_eol)
conn.log_expect(options, options["-c"], int(options["-Y"]))
except pexpect.EOF:
fail(EC_LOGIN_DENIED)
except pexpect.TIMEOUT:
fail(EC_LOGIN_DENIED)
return conn
| Python |
#!/usr/bin/env python
#
#############################################################################
# Copyright 2011 Matt Clark
# This file is part of fence-xenserver
#
# fence-xenserver is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# fence-xenserver is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
#############################################################################
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
import sys, string, getopt
import XenAPI
def usage():
print "Usage: fence_cxs [-hv] [-a <action>] -l <login username> -p <login password> -s <session url> [-u <UUID>]"
print "Where:-"
print " -a : Specifies the action to perfom. Can be any of \"on|off|reboot|status|list\". Defaults to \"status\"."
print " -h : Print this help message."
print " -l : The username for the XenServer host."
print " -p : The password for the XenServer host."
print " -s : The URL of the web interface on the XenServer host."
print " -U : The UUID of the virtual machine to fence or query. Defaults to the empty string which will return"
print " the status of all hosts when action is set to \"status\". If the action is set to \"on|off|reboot\""
print " then the UUID must be specified."
# Process command line options and populate the config array
def process_opts():
config = {
"action" : "status",
"session_url" : "",
"session_user" : "",
"session_pass" : "",
"uuid" : "",
"name" : "",
"verbose" : False
}
# If we have at least one argument then we want to parse the command line using getopts
if len(sys.argv) > 1:
try:
opts, args = getopt.getopt(sys.argv[1:], "a:hl:n:s:p:U:v", ["help", "verbose", "action=", "session-url=", "login-name=", "name=", "password=", "uuid="])
except getopt.GetoptError, err:
# We got an unrecognised option, so print he help message and exit
print str(err)
usage()
sys.exit(1)
for opt, arg in opts:
if opt in ("-v", "--verbose"):
config["verbose"] = True
elif opt in ("-a", "--action"):
config["action"] = clean_action(arg)
elif opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-s", "--session-url"):
config["session_url"] = arg
elif opt in ("-l", "--login-name"):
config["session_user"] = arg
elif opt in ("-n", "--name"):
config["name"] = arg
elif opt in ("-p", "--password"):
config["session_pass"] = arg
elif opt in ("-U", "--uuid"):
config["uuid"] = arg.lower()
else:
assert False, "unhandled option"
# Otherwise process stdin for parameters. This is to handle the Red Hat clustering
# mechanism where by fenced passes in name/value pairs instead of using command line
# options.
else:
for line in sys.stdin.readlines():
line = line.strip()
if ((line.startswith("#")) or (len(line) == 0)):
continue
(name, value) = (line + "=").split("=", 1)
value = value[:-1]
name = clean_param_name(name)
if name == "action":
value = clean_action(value)
if name in config:
config[name] = value
else:
sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n")
if( config["session_url"] == "" or config["session_user"] == "" or config["session_pass"] == "" ):
print "You must specify the session url, username and password.";
usage();
sys.exit(2);
return config
# why, well just to be nice. Given an action will return the corresponding
# value that the rest of the script uses.
def clean_action(action):
if action.lower() in ("on", "poweron", "powerup"):
return "on"
elif action.lower() in ("off", "poweroff", "powerdown"):
return "off"
elif action.lower() in ("reboot", "reset", "restart"):
return "reboot"
elif action.lower() in ("status", "powerstatus", "list"):
return "status"
else:
print "Bad action", action
usage()
exit(4)
# why, well just to be nice. Given a parameter will return the corresponding
# value that the rest of the script uses.
def clean_param_name(name):
if name.lower() in ("action", "operation", "op"):
return "action"
elif name.lower() in ("session_user", "login", "login-name", "login_name", "user", "username", "session-user"):
return "session_user"
elif name.lower() in ("session_pass", "pass", "passwd", "password", "session-pass"):
return "session_pass"
elif name.lower() in ("session_url", "url", "session-url"):
return "session_url"
else:
# we should never get here as getopt should handle the checking of this input.
print "Bad parameter specified", name
usage()
exit(5)
# Print the power status of a VM. If no UUID is given, then all VM's are queried
def get_power_status(session, uuid = "", name = ""):
try:
# If the UUID hasn't been set, then output the status of all
# valid virtual machines.
if( len(uuid) > 0 ):
vms = [session.xenapi.VM.get_by_uuid(uuid)]
elif( len(name) > 0 ):
vms = session.xenapi.VM.get_by_name_label(name)
else:
vms = session.xenapi.VM.get_all()
for vm in vms:
record = session.xenapi.VM.get_record(vm);
# We only want to print out the status for actual virtual machines. The above get_all function
# returns any templates and also the control domain. This is one of the reasons the process
# takes such a long time to list all VM's. Hopefully there is a way to filter this in the
# request packet in the future.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
def set_power_status(session, uuid, name, action):
try:
vm = None
if( len(uuid) > 0 ):
vm = session.xenapi.VM.get_by_uuid(uuid)
elif( len(name) > 0 ):
vm_arr = session.xenapi.VM.get_by_name_label(name)
if( len(vm_arr) == 1 ):
vm = vm_arr[0]
else
raise Exception("Multiple VM's have that name. Use UUID instead.")
if( vm != None ):
record = session.xenapi.VM.get_record(vm);
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
session.xenapi.VM.hard_reboot(vm)
else:
raise Exception("Bad power status");
except Exception, exn:
print str(exn);
def main():
config = process_opts();
session = session_start(config["session_url"]);
session_login(session, config["session_user"], config["session_pass"]);
if( config["action"] == "status" ):
get_power_status(session, config["uuid"], config["name"])
else:
if( config["verbose"] ):
print "Power status before action"
get_power_status(session, config["uuid"])
set_power_status(session, config["uuid"], config["name"], config["action"])
if( config["verbose"] ):
print "Power status after action"
get_power_status(session, config["uuid"])
# Function to initiate the session with the XenServer system
def session_start(url):
try:
session = XenAPI.Session(url);
except Exception, exn:
print str(exn);
sys.exit(3);
return session;
def session_login(session, username, password):
try:
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
sys.exit(3);
if __name__ == "__main__":
main()
# vim:set ts=4 sw=4
| Python |
#!/usr/bin/env python
#
#############################################################################
# Copyright 2011 Matt Clark
# This file is part of fence-xenserver
#
# fence-xenserver is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# fence-xenserver is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
#############################################################################
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
import sys, string, getopt
import XenAPI
def usage():
print "Usage: fence_cxs [-hv] [-a <action>] -l <login username> -p <login password> -s <session url> [-u <UUID>]"
print "Where:-"
print " -a : Specifies the action to perfom. Can be any of \"on|off|reboot|status|list\". Defaults to \"status\"."
print " -h : Print this help message."
print " -l : The username for the XenServer host."
print " -p : The password for the XenServer host."
print " -s : The URL of the web interface on the XenServer host."
print " -U : The UUID of the virtual machine to fence or query. Defaults to the empty string which will return"
print " the status of all hosts when action is set to \"status\". If the action is set to \"on|off|reboot\""
print " then the UUID must be specified."
# Process command line options and populate the config array
def process_opts():
config = {
"action" : "status",
"session_url" : "",
"session_user" : "",
"session_pass" : "",
"uuid" : "",
"name" : "",
"verbose" : False
}
# If we have at least one argument then we want to parse the command line using getopts
if len(sys.argv) > 1:
try:
opts, args = getopt.getopt(sys.argv[1:], "a:hl:n:s:p:U:v", ["help", "verbose", "action=", "session-url=", "login-name=", "name=", "password=", "uuid="])
except getopt.GetoptError, err:
# We got an unrecognised option, so print he help message and exit
print str(err)
usage()
sys.exit(1)
for opt, arg in opts:
if opt in ("-v", "--verbose"):
config["verbose"] = True
elif opt in ("-a", "--action"):
config["action"] = clean_action(arg)
elif opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-s", "--session-url"):
config["session_url"] = arg
elif opt in ("-l", "--login-name"):
config["session_user"] = arg
elif opt in ("-n", "--name"):
config["name"] = arg
elif opt in ("-p", "--password"):
config["session_pass"] = arg
elif opt in ("-U", "--uuid"):
config["uuid"] = arg.lower()
else:
assert False, "unhandled option"
# Otherwise process stdin for parameters. This is to handle the Red Hat clustering
# mechanism where by fenced passes in name/value pairs instead of using command line
# options.
else:
for line in sys.stdin.readlines():
line = line.strip()
if ((line.startswith("#")) or (len(line) == 0)):
continue
(name, value) = (line + "=").split("=", 1)
value = value[:-1]
name = clean_param_name(name)
if name == "action":
value = clean_action(value)
if name in config:
config[name] = value
else:
sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n")
if( config["session_url"] == "" or config["session_user"] == "" or config["session_pass"] == "" ):
print "You must specify the session url, username and password.";
usage();
sys.exit(2);
return config
# why, well just to be nice. Given an action will return the corresponding
# value that the rest of the script uses.
def clean_action(action):
if action.lower() in ("on", "poweron", "powerup"):
return "on"
elif action.lower() in ("off", "poweroff", "powerdown"):
return "off"
elif action.lower() in ("reboot", "reset", "restart"):
return "reboot"
elif action.lower() in ("status", "powerstatus", "list"):
return "status"
else:
print "Bad action", action
usage()
exit(4)
# why, well just to be nice. Given a parameter will return the corresponding
# value that the rest of the script uses.
def clean_param_name(name):
if name.lower() in ("action", "operation", "op"):
return "action"
elif name.lower() in ("session_user", "login", "login-name", "login_name", "user", "username", "session-user"):
return "session_user"
elif name.lower() in ("session_pass", "pass", "passwd", "password", "session-pass"):
return "session_pass"
elif name.lower() in ("session_url", "url", "session-url"):
return "session_url"
else:
# we should never get here as getopt should handle the checking of this input.
print "Bad parameter specified", name
usage()
exit(5)
# Print the power status of a VM. If no UUID is given, then all VM's are queried
def get_power_status(session, uuid = "", name = ""):
try:
# If the UUID hasn't been set, then output the status of all
# valid virtual machines.
if( len(uuid) > 0 ):
vms = [session.xenapi.VM.get_by_uuid(uuid)]
elif( len(name) > 0 ):
vms = session.xenapi.VM.get_by_name_label(name)
else:
vms = session.xenapi.VM.get_all()
for vm in vms:
record = session.xenapi.VM.get_record(vm);
# We only want to print out the status for actual virtual machines. The above get_all function
# returns any templates and also the control domain. This is one of the reasons the process
# takes such a long time to list all VM's. Hopefully there is a way to filter this in the
# request packet in the future.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
def set_power_status(session, uuid, name, action):
try:
vm = None
if( len(uuid) > 0 ):
vm = session.xenapi.VM.get_by_uuid(uuid)
elif( len(name) > 0 ):
vm_arr = session.xenapi.VM.get_by_name_label(name)
if( len(vm_arr) == 1 ):
vm = vm_arr[0]
else
raise Exception("Multiple VM's have that name. Use UUID instead.")
if( vm != None ):
record = session.xenapi.VM.get_record(vm);
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
session.xenapi.VM.hard_reboot(vm)
else:
raise Exception("Bad power status");
except Exception, exn:
print str(exn);
def main():
config = process_opts();
session = session_start(config["session_url"]);
session_login(session, config["session_user"], config["session_pass"]);
if( config["action"] == "status" ):
get_power_status(session, config["uuid"], config["name"])
else:
if( config["verbose"] ):
print "Power status before action"
get_power_status(session, config["uuid"])
set_power_status(session, config["uuid"], config["name"], config["action"])
if( config["verbose"] ):
print "Power status after action"
get_power_status(session, config["uuid"])
# Function to initiate the session with the XenServer system
def session_start(url):
try:
session = XenAPI.Session(url);
except Exception, exn:
print str(exn);
sys.exit(3);
return session;
def session_login(session, username, password):
try:
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
sys.exit(3);
if __name__ == "__main__":
main()
# vim:set ts=4 sw=4
| Python |
#============================================================================
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#============================================================================
# Copyright (C) 2006 XenSource Inc.
#============================================================================
#
# Parts of this file are based upon xmlrpclib.py, the XML-RPC client
# interface included in the Python distribution.
#
# Copyright (c) 1999-2002 by Secret Labs AB
# Copyright (c) 1999-2002 by Fredrik Lundh
#
# By obtaining, using, and/or copying this software and/or its
# associated documentation, you agree that you have read, understood,
# and will comply with the following terms and conditions:
#
# Permission to use, copy, modify, and distribute this software and
# its associated documentation for any purpose and without fee is
# hereby granted, provided that the above copyright notice appears in
# all copies, and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of
# Secret Labs AB or the author not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
# OF THIS SOFTWARE.
# --------------------------------------------------------------------
import gettext
import xmlrpclib
import httplib
import socket
translation = gettext.translation('xen-xm', fallback = True)
class Failure(Exception):
def __init__(self, details):
try:
# If this failure is MESSAGE_PARAMETER_COUNT_MISMATCH, then we
# correct the return values here, to account for the fact that we
# transparently add the session handle as the first argument.
if details[0] == 'MESSAGE_PARAMETER_COUNT_MISMATCH':
details[2] = str(int(details[2]) - 1)
details[3] = str(int(details[3]) - 1)
self.details = details
except Exception, exn:
self.details = ['INTERNAL_ERROR', 'Client-side: ' + str(exn)]
def __str__(self):
try:
return translation.ugettext(self.details[0]) % self._details_map()
except TypeError, exn:
return "Message database broken: %s.\nXen-API failure: %s" % \
(exn, str(self.details))
except Exception, exn:
import sys
print >>sys.stderr, exn
return "Xen-API failure: %s" % str(self.details)
def _details_map(self):
return dict([(str(i), self.details[i])
for i in range(len(self.details))])
_RECONNECT_AND_RETRY = (lambda _ : ())
class UDSHTTPConnection(httplib.HTTPConnection):
""" Stupid hacked up HTTPConnection subclass to allow HTTP over Unix domain
sockets. """
def connect(self):
path = self.host.replace("_", "/")
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect(path)
class UDSHTTP(httplib.HTTP):
_connection_class = UDSHTTPConnection
class UDSTransport(xmlrpclib.Transport):
def make_connection(self, host):
return UDSHTTP(host)
class Session(xmlrpclib.ServerProxy):
"""A server proxy and session manager for communicating with Xend using
the Xen-API.
Example:
session = Session('http://localhost:9363/')
session.login_with_password('me', 'mypassword')
session.xenapi.VM.start(vm_uuid)
session.xenapi.session.logout()
For now, this class also supports the legacy XML-RPC API, using
session.xend.domain('Domain-0') and similar. This support will disappear
once there is a working Xen-API replacement for every call in the legacy
API.
"""
def __init__(self, uri, transport=None, encoding=None, verbose=0,
allow_none=1):
xmlrpclib.ServerProxy.__init__(self, uri, transport, encoding,
verbose, allow_none)
self._session = None
self.last_login_method = None
self.last_login_params = None
def xenapi_request(self, methodname, params):
if methodname.startswith('login'):
self._login(methodname, params)
return None
else:
retry_count = 0
while retry_count < 3:
full_params = (self._session,) + params
result = _parse_result(getattr(self, methodname)(*full_params))
if result == _RECONNECT_AND_RETRY:
retry_count += 1
if self.last_login_method:
self._login(self.last_login_method,
self.last_login_params)
else:
raise xmlrpclib.Fault(401, 'You must log in')
else:
return result
raise xmlrpclib.Fault(
500, 'Tried 3 times to get a valid session, but failed')
def _login(self, method, params):
result = _parse_result(getattr(self, 'session.%s' % method)(*params))
if result == _RECONNECT_AND_RETRY:
raise xmlrpclib.Fault(
500, 'Received SESSION_INVALID when logging in')
self._session = result
self.last_login_method = method
self.last_login_params = params
def __getattr__(self, name):
if name == 'xenapi':
return _Dispatcher(self.xenapi_request, None)
elif name.startswith('login'):
return lambda *params: self._login(name, params)
else:
return xmlrpclib.ServerProxy.__getattr__(self, name)
def xapi_local():
return Session("http://_var_xapi_xapi/", transport=UDSTransport())
def _parse_result(result):
if type(result) != dict or 'Status' not in result:
raise xmlrpclib.Fault(500, 'Missing Status in response from server' + result)
if result['Status'] == 'Success':
if 'Value' in result:
return result['Value']
else:
raise xmlrpclib.Fault(500,
'Missing Value in response from server')
else:
if 'ErrorDescription' in result:
if result['ErrorDescription'][0] == 'SESSION_INVALID':
return _RECONNECT_AND_RETRY
else:
raise Failure(result['ErrorDescription'])
else:
raise xmlrpclib.Fault(
500, 'Missing ErrorDescription in response from server')
# Based upon _Method from xmlrpclib.
class _Dispatcher:
def __init__(self, send, name):
self.__send = send
self.__name = name
def __repr__(self):
if self.__name:
return '<XenAPI._Dispatcher for %s>' % self.__name
else:
return '<XenAPI._Dispatcher>'
def __getattr__(self, name):
if self.__name is None:
return _Dispatcher(self.__send, name)
else:
return _Dispatcher(self.__send, "%s.%s" % (self.__name, name))
def __call__(self, *args):
return self.__send(self.__name, args)
| Python |
#!/usr/bin/python
#
#############################################################################
# Copyright 2011 Matt Clark
# This file is part of fence-xenserver
#
# fence-xenserver is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# fence-xenserver is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
#############################################################################
#############################################################################
# It's only just begun...
# Current status: completely usable. This script is now working well and,
# has a lot of functionality as a result of the fencing.py library and the
# XenAPI libary.
#############################################################################
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
import sys
sys.path.append("/usr/lib/fence")
from fencing import *
import XenAPI
EC_BAD_SESSION = 1
# Find the status of the port given in the -U flag of options.
def get_power_fn(session, options):
if options.has_key("-v"):
verbose = True
else:
verbose = False
try:
# Get a reference to the vm specified in the UUID or vm_name parameter
vm = return_vm_reference(session, options)
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm);
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
status = record["power_state"]
if verbose: print "UUID:", record["uuid"], "NAME:", record["name_label"], "POWER STATUS:", record["power_state"]
# Note that the VM can be in the following states (from the XenAPI document)
# Halted: VM is offline and not using any resources.
# Paused: All resources have been allocated but the VM itself is paused and its vCPUs are not running
# Running: Running
# Paused: VM state has been saved to disk and it is nolonger running. Note that disks remain in-Use while
# We want to make sure that we only return the status "off" if the machine is actually halted as the status
# is checked before a fencing action. Only when the machine is Halted is it not consuming resources which
# may include whatever you are trying to protect with this fencing action.
return (status=="Halted" and "off" or "on")
except Exception, exn:
print str(exn)
return "Error"
# Set the state of the port given in the -U flag of options.
def set_power_fn(session, options):
action = options["-o"].lower()
if options.has_key("-v"):
verbose = True
else:
verbose = False
try:
# Get a reference to the vm specified in the UUID or vm_name parameter
vm = return_vm_reference(session, options)
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm)
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
# Start the VM
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
# Force shutdown the VM
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
# Force reboot the VM
session.xenapi.VM.hard_reboot(vm)
except Exception, exn:
print str(exn);
# Function to populate an array of virtual machines and their status
def get_outlet_list(session, options):
result = {}
if options.has_key("-v"):
verbose = True
else:
verbose = False
try:
# Return an array of all the VM's on the host
vms = session.xenapi.VM.get_all()
for vm in vms:
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm);
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
uuid = record["uuid"]
status = record["power_state"]
result[uuid] = (name, status)
if verbose: print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
return result
# Function to initiate the XenServer session via the XenAPI library.
def connect_and_login(options):
url = options["-s"]
username = options["-l"]
password = options["-p"]
try:
# Create the XML RPC session to the specified URL.
session = XenAPI.Session(url);
# Login using the supplied credentials.
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
# http://sources.redhat.com/cluster/wiki/FenceAgentAPI says that for no connectivity
# the exit value should be 1. It doesn't say anything about failed logins, so
# until I hear otherwise it is best to keep this exit the same to make sure that
# anything calling this script (that uses the same information in the web page
# above) knows that this is an error condition, not a msg signifying a down port.
sys.exit(EC_BAD_SESSION);
return session;
# return a reference to the VM by either using the UUID or the vm_name. If the UUID is set then
# this is tried first as this is the only properly unique identifier.
# Exceptions are not handled in this function, code that calls this must be ready to handle them.
def return_vm_reference(session, options):
if options.has_key("-v"):
verbose = True
else:
verbose = False
# Case where the UUID has been specified
if options.has_key("-U"):
uuid = options["-U"].lower()
# When using the -n parameter for name, we get an error message (in verbose
# mode) that tells us that we didn't find a VM. To immitate that here we
# need to catch and re-raise the exception produced by get_by_uuid.
try:
return session.xenapi.VM.get_by_uuid(uuid)
except Exception,exn:
if verbose: print "No VM's found with a UUID of \"%s\"" %uuid
raise
# Case where the vm_name has been specified
if options.has_key("-n"):
vm_name = options["-n"]
vm_arr = session.xenapi.VM.get_by_name_label(vm_name)
# Need to make sure that we only have one result as the vm_name may
# not be unique. Average case, so do it first.
if len(vm_arr) == 1:
return vm_arr[0]
else:
if len(vm_arr) == 0:
if verbose: print "No VM's found with a name of \"%s\"" %vm_name
# NAME_INVALID used as the XenAPI throws a UUID_INVALID if it can't find
# a VM with the specified UUID. This should make the output look fairly
# consistent.
raise Exception("NAME_INVALID")
else:
if verbose: print "Multiple VM's have the name \"%s\", use UUID instead" %vm_name
raise Exception("MULTIPLE_VMS_FOUND")
# We should never get to this case as the input processing checks that either the UUID or
# the name parameter is set. Regardless of whether or not a VM is found the above if
# statements will return to the calling function (either by exception or by a reference
# to the VM).
raise Exception("VM_LOGIC_ERROR")
def main():
device_opt = [ "help", "version", "agent", "quiet", "verbose", "debug", "action",
"login", "passwd", "passwd_script", "vm_name", "test", "separator",
"no_login", "no_password", "power_timeout", "shell_timeout",
"login_timeout", "power_wait", "session_url", "uuid" ]
atexit.register(atexit_handler)
options=process_input(device_opt)
options = check_input(device_opt, options)
docs = { }
docs["shortdesc"] = "XenAPI based fencing for the Citrix XenServer virtual machines."
docs["longdesc"] = "\
fence_cxs is an I/O Fencing agent used on Citrix XenServer hosts. \
It uses the XenAPI, supplied by Citrix, to establish an XML-RPC sesssion \
to a XenServer host. Once the session is established, further XML-RPC \
commands are issued in order to switch on, switch off, restart and query \
the status of virtual machines running on the host."
show_docs(options, docs)
xenSession = connect_and_login(options)
# Operate the fencing device
result = fence_action(xenSession, options, set_power_fn, get_power_fn, get_outlet_list)
sys.exit(result)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
# It's only just begun...
# Current status: completely unusable, try the fence_cxs.py script for the moment. This Red
# Hat compatible version is just in its' infancy.
# Copyright 2011 Matt Clark
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
from fencing import *
import XenAPI
# Find the status of the port given in the -u flag of options.
def get_power_status(session, options):
if( options["-u"] == "" ):
return "bad"
try:
vm = session.xenapi.VM.get_by_uuid(options["-u"])
record = session.xenapi.VM.get_record(vm);
if not(record["is_a_template"]) and not(record["is_control_domain"]):
status = record["power_state"]
print "UUID:", record["uuid"], "NAME:", record["name_label"], "POWER STATUS:", record["power_state"]
return (status=="Running" and "on" or "off")
except Exception, exn:
print str(exn);
# Set the state of the port given in the -n flag of options.
def set_power_status(session, options):
if( options["-u"] == "" ):
return;
try:
vm = session.xenapi.VM.get_by_uuid(options["-u"])
record = session.xenapi.VM.get_record(vm);
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( options["-o"] == "on" ):
session.xenapi.VM.start(vm, False, True)
elif( options["-o"] == "off" ):
session.xenapi.VM.hard_shutdown(vm)
elif( options["-o"] == "reboot" ):
session.xenapi.VM.hard_reboot(vm)
except Exception, exn:
print str(exn);
def get_outlets_status(session, options):
result = {}
try:
vms = session.xenapi.VM.get_all()
for vm in vms:
record = session.xenapi.VM.get_record(vm);
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
uuid = record["uuid"]
status = record["power_state"]
result[uuid] = (name, status)
print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
return result
def connectAndLogin(options):
try:
session = XenAPI.Session(options["-s"]);
session.xenapi.login_with_password(options["-l"], options["-p"]);
except Exception, exn:
print str(exn);
sys.exit(3);
return session;
# Main agent method
def main():
device_opt = [ "help", "version", "agent", "quiet", "verbose", "debug", "action",
"login", "passwd", "passwd_script", "test", "separator", "no_login",
"no_password", "inet4_only","inet6_only", "power_timeout",
"shell_timeout", "login_timeout", "power_wait", "session_url", "uuid" ]
atexit.register(atexit_handler)
options=process_input(device_opt)
options = check_input(device_opt, options)
docs = { }
docs["shortdesc"] = "Fence agent for Citrix XenServer"
docs["longdesc"] = "fence_cxs_redhat"
show_docs(options, docs)
xenSession = connectAndLogin(options)
# Operate the fencing device
result = fence_action(xenSession, options, set_power_status, get_power_status, get_outlets_status)
sys.exit(result)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
# Copyright 2011 Matt Clark
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
import sys, string, getopt
import XenAPI
def usage():
print "Usage: fence_cxs [-hv] [-a <action>] -l <login username> -p <login password> -s <session url> [-u <UUID>]"
print "Where:-"
print " -a : Specifies the action to perfom. Can be any of \"on|off|reboot|status\". Defaults to \"status\"."
print " -h : Print this help message."
print " -l : The username for the XenServer host."
print " -p : The password for the XenServer host."
print " -s : The URL of the web interface on the XenServer host."
print " -u : The UUID of the virtual machine to fence or query. Defaults to the empty string which will return"
print " the status of all hosts when action is set to \"status\". If the action is set to \"on|off|reboot\""
print " then the UUID must be specified."
# Process command line options and populate the config array
def process_opts():
config = {
"action" : "status",
"session_url" : "",
"session_user" : "",
"session_pass" : "",
"uuid" : "",
"verbose" : False
}
try:
opts, args = getopt.getopt(sys.argv[1:], "a:hl:s:p:u:v", ["help", "verbose", "action=", "session-url=", "login-name=", "password=", "uuid="])
except getopt.GetoptError, err:
# We got an unrecognised option, so print he help message and exit
print str(err)
usage()
sys.exit(1)
for opt, arg in opts:
if opt in ("-v", "--verbose"):
config["verbose"] = True
elif opt in ("-a", "--action"):
if arg in ("on", "poweron", "powerup"):
config["action"] = "on"
elif arg in ("off", "poweroff", "powerdown"):
config["action"] = "off"
elif arg in ("reboot", "reset"):
config["action"] = "reboot"
elif arg in ("status", "powerstatus"):
config["action"] = "status"
elif opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-s", "--session-url"):
config["session_url"] = arg
elif opt in ("-l", "--login-name"):
config["session_user"] = arg
elif opt in ("-p", "--password"):
config["session_pass"] = arg
elif opt in ("-u", "--uuid"):
config["uuid"] = arg
else:
assert False, "unhandled option"
if( config["session_url"] == "" or config["session_user"] == "" or config["session_pass"] == "" ):
print "You must specify the session url, username and password.";
usage();
sys.exit(2);
return config
# Print the power status of a VM. If no UUID is given, then all VM's are queried
def get_power_status(session, uuid = ""):
try:
if( uuid == "" ):
vms = session.xenapi.VM.get_all()
else:
vms = [session.xenapi.VM.get_by_uuid(uuid)]
for vm in vms:
record = session.xenapi.VM.get_record(vm);
# We only want to print out the status for actual virtual machines. The above get_all function
# returns any templates and also the control domain. This is one of the reasons the process
# takes such a long time to list all VM's. Hopefully there is a way to filter this in the
# request packet in the future.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
def set_power_status(session, uuid, action):
try:
vm = session.xenapi.VM.get_by_uuid(uuid)
record = session.xenapi.VM.get_record(vm);
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
session.xenapi.VM.hard_reboot(vm)
except Exception, exn:
print str(exn);
def main():
config = process_opts();
session = session_start(config["session_url"]);
session_login(session, config["session_user"], config["session_pass"]);
if( config["action"] == "status" ):
get_power_status(session, config["uuid"])
else:
if( config["verbose"] ):
print "Power status before action"
get_power_status(session, config["uuid"])
set_power_status(session, config["uuid"], config["action"])
if( config["verbose"] ):
print "Power status after action"
get_power_status(session, config["uuid"])
# Function to initiate the session with the XenServer system
def session_start(url):
try:
session = XenAPI.Session(url);
except Exception, exn:
print str(exn);
sys.exit(3);
return session;
def session_login(session, username, password):
try:
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
sys.exit(3);
if __name__ == "__main__":
main()
# vim:set ts=4 sw=4
| Python |
#!/usr/bin/env python
# Copyright 2011 Matt Clark
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
import sys, string, getopt
import XenAPI
def usage():
print "Usage: fence_cxs [-hv] [-a <action>] -l <login username> -p <login password> -s <session url> [-u <UUID>]"
print "Where:-"
print " -a : Specifies the action to perfom. Can be any of \"on|off|reboot|status\". Defaults to \"status\"."
print " -h : Print this help message."
print " -l : The username for the XenServer host."
print " -p : The password for the XenServer host."
print " -s : The URL of the web interface on the XenServer host."
print " -u : The UUID of the virtual machine to fence or query. Defaults to the empty string which will return"
print " the status of all hosts when action is set to \"status\". If the action is set to \"on|off|reboot\""
print " then the UUID must be specified."
# Process command line options and populate the config array
def process_opts():
config = {
"action" : "status",
"session_url" : "",
"session_user" : "",
"session_pass" : "",
"uuid" : "",
"verbose" : False
}
try:
opts, args = getopt.getopt(sys.argv[1:], "a:hl:s:p:u:v", ["help", "verbose", "action=", "session-url=", "login-name=", "password=", "uuid="])
except getopt.GetoptError, err:
# We got an unrecognised option, so print he help message and exit
print str(err)
usage()
sys.exit(1)
for opt, arg in opts:
if opt in ("-v", "--verbose"):
config["verbose"] = True
elif opt in ("-a", "--action"):
if arg in ("on", "poweron", "powerup"):
config["action"] = "on"
elif arg in ("off", "poweroff", "powerdown"):
config["action"] = "off"
elif arg in ("reboot", "reset"):
config["action"] = "reboot"
elif arg in ("status", "powerstatus"):
config["action"] = "status"
elif opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-s", "--session-url"):
config["session_url"] = arg
elif opt in ("-l", "--login-name"):
config["session_user"] = arg
elif opt in ("-p", "--password"):
config["session_pass"] = arg
elif opt in ("-u", "--uuid"):
config["uuid"] = arg
else:
assert False, "unhandled option"
if( config["session_url"] == "" or config["session_user"] == "" or config["session_pass"] == "" ):
print "You must specify the session url, username and password.";
usage();
sys.exit(2);
return config
# Print the power status of a VM. If no UUID is given, then all VM's are queried
def get_power_status(session, uuid = ""):
try:
if( uuid == "" ):
vms = session.xenapi.VM.get_all()
else:
vms = [session.xenapi.VM.get_by_uuid(uuid)]
for vm in vms:
record = session.xenapi.VM.get_record(vm);
# We only want to print out the status for actual virtual machines. The above get_all function
# returns any templates and also the control domain. This is one of the reasons the process
# takes such a long time to list all VM's. Hopefully there is a way to filter this in the
# request packet in the future.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
def set_power_status(session, uuid, action):
try:
vm = session.xenapi.VM.get_by_uuid(uuid)
record = session.xenapi.VM.get_record(vm);
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
session.xenapi.VM.hard_reboot(vm)
except Exception, exn:
print str(exn);
def main():
config = process_opts();
session = session_start(config["session_url"]);
session_login(session, config["session_user"], config["session_pass"]);
if( config["action"] == "status" ):
get_power_status(session, config["uuid"])
else:
if( config["verbose"] ):
print "Power status before action"
get_power_status(session, config["uuid"])
set_power_status(session, config["uuid"], config["action"])
if( config["verbose"] ):
print "Power status after action"
get_power_status(session, config["uuid"])
# Function to initiate the session with the XenServer system
def session_start(url):
try:
session = XenAPI.Session(url);
except Exception, exn:
print str(exn);
sys.exit(3);
return session;
def session_login(session, username, password):
try:
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
sys.exit(3);
if __name__ == "__main__":
main()
# vim:set ts=4 sw=4
| Python |
#!/usr/bin/python
# It's only just begun...
# Current status: completely unusable, try the fence_cxs.py script for the moment. This Red
# Hat compatible version is just in its' infancy.
# Copyright 2011 Matt Clark
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
from fencing import *
import XenAPI
# Find the status of the port given in the -u flag of options.
def get_power_status(session, options):
if( options["-u"] == "" ):
return "bad"
try:
vm = session.xenapi.VM.get_by_uuid(options["-u"])
record = session.xenapi.VM.get_record(vm);
if not(record["is_a_template"]) and not(record["is_control_domain"]):
status = record["power_state"]
print "UUID:", record["uuid"], "NAME:", record["name_label"], "POWER STATUS:", record["power_state"]
return (status=="Running" and "on" or "off")
except Exception, exn:
print str(exn);
# Set the state of the port given in the -n flag of options.
def set_power_status(session, options):
if( options["-u"] == "" ):
return;
try:
vm = session.xenapi.VM.get_by_uuid(options["-u"])
record = session.xenapi.VM.get_record(vm);
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( options["-o"] == "on" ):
session.xenapi.VM.start(vm, False, True)
elif( options["-o"] == "off" ):
session.xenapi.VM.hard_shutdown(vm)
elif( options["-o"] == "reboot" ):
session.xenapi.VM.hard_reboot(vm)
except Exception, exn:
print str(exn);
def get_outlets_status(session, options):
result = {}
try:
vms = session.xenapi.VM.get_all()
for vm in vms:
record = session.xenapi.VM.get_record(vm);
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
uuid = record["uuid"]
status = record["power_state"]
result[uuid] = (name, status)
print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
return result
def connectAndLogin(options):
try:
session = XenAPI.Session(options["-s"]);
session.xenapi.login_with_password(options["-l"], options["-p"]);
except Exception, exn:
print str(exn);
sys.exit(3);
return session;
# Main agent method
def main():
device_opt = [ "help", "version", "agent", "quiet", "verbose", "debug", "action",
"login", "passwd", "passwd_script", "test", "separator", "no_login",
"no_password", "inet4_only","inet6_only", "power_timeout",
"shell_timeout", "login_timeout", "power_wait", "session_url", "uuid" ]
atexit.register(atexit_handler)
options=process_input(device_opt)
options = check_input(device_opt, options)
docs = { }
docs["shortdesc"] = "Fence agent for Citrix XenServer"
docs["longdesc"] = "fence_cxs_redhat"
show_docs(options, docs)
xenSession = connectAndLogin(options)
# Operate the fencing device
result = fence_action(xenSession, options, set_power_status, get_power_status, get_outlets_status)
sys.exit(result)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
import sys, getopt, time, os
import pexpect, re
import telnetlib
import atexit
import __main__
## do not add code here.
#BEGIN_VERSION_GENERATION
RELEASE_VERSION="3.0.17"
BUILD_DATE="(built Thu Oct 7 07:06:21 UTC 2010)"
REDHAT_COPYRIGHT="Copyright (C) Red Hat, Inc. 2004-2010 All rights reserved."
#END_VERSION_GENERATION
LOG_MODE_VERBOSE = 100
LOG_MODE_QUIET = 0
EC_GENERIC_ERROR = 1
EC_BAD_ARGS = 2
EC_LOGIN_DENIED = 3
EC_CONNECTION_LOST = 4
EC_TIMED_OUT = 5
EC_WAITING_ON = 6
EC_WAITING_OFF = 7
EC_STATUS = 8
EC_STATUS_HMC = 9
TELNET_PATH = "/usr/bin/telnet"
SSH_PATH = "/usr/bin/ssh"
SSL_PATH = "/usr/sbin/fence_nss_wrapper"
all_opt = {
"help" : {
"getopt" : "h",
"longopt" : "help",
"help" : "-h, --help Display this help and exit",
"required" : "0",
"shortdesc" : "Display help and exit",
"order" : 54 },
"version" : {
"getopt" : "V",
"longopt" : "version",
"help" : "-V, --version Output version information and exit",
"required" : "0",
"shortdesc" : "Display version information and exit",
"order" : 53 },
"quiet" : {
"getopt" : "q",
"help" : "",
"order" : 50 },
"verbose" : {
"getopt" : "v",
"longopt" : "verbose",
"help" : "-v, --verbose Verbose mode",
"required" : "0",
"shortdesc" : "Verbose mode",
"order" : 51 },
"debug" : {
"getopt" : "D:",
"longopt" : "debug-file",
"help" : "-D, --debug-file=<debugfile> Debugging to output file",
"required" : "0",
"shortdesc" : "Write debug information to given file",
"order" : 52 },
"delay" : {
"getopt" : "f:",
"longopt" : "delay",
"help" : "--delay <seconds> Wait X seconds before fencing is started",
"required" : "0",
"shortdesc" : "Wait X seconds before fencing is started",
"default" : "0",
"order" : 200 },
"agent" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"web" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"action" : {
"getopt" : "o:",
"longopt" : "action",
"help" : "-o, --action=<action> Action: status, reboot (default), off or on",
"required" : "1",
"shortdesc" : "Fencing Action",
"default" : "reboot",
"order" : 1 },
"io_fencing" : {
"getopt" : "o:",
"longopt" : "action",
"help" : "-o, --action=<action> Action: status, enable or disable",
"required" : "1",
"shortdesc" : "Fencing Action",
"default" : "disable",
"order" : 1 },
"ipaddr" : {
"getopt" : "a:",
"longopt" : "ip",
"help" : "-a, --ip=<ip> IP address or hostname of fencing device",
"required" : "1",
"shortdesc" : "IP Address or Hostname",
"order" : 1 },
"ipport" : {
"getopt" : "u:",
"longopt" : "ipport",
"help" : "-u, --ipport=<port> TCP port to use",
"required" : "0",
"shortdesc" : "TCP port to use for connection with device",
"order" : 1 },
"login" : {
"getopt" : "l:",
"longopt" : "username",
"help" : "-l, --username=<name> Login name",
"required" : "?",
"shortdesc" : "Login Name",
"order" : 1 },
"no_login" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"no_password" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"passwd" : {
"getopt" : "p:",
"longopt" : "password",
"help" : "-p, --password=<password> Login password or passphrase",
"required" : "0",
"shortdesc" : "Login password or passphrase",
"order" : 1 },
"passwd_script" : {
"getopt" : "S:",
"longopt" : "password-script=",
"help" : "-S, --password-script=<script> Script to run to retrieve password",
"required" : "0",
"shortdesc" : "Script to retrieve password",
"order" : 1 },
"identity_file" : {
"getopt" : "k:",
"longopt" : "identity-file",
"help" : "-k, --identity-file=<filename> Identity file (private key) for ssh ",
"required" : "0",
"shortdesc" : "Identity file for ssh",
"order" : 1 },
"module_name" : {
"getopt" : "m:",
"longopt" : "module-name",
"help" : "-m, --module-name=<module> DRAC/MC module name",
"required" : "0",
"shortdesc" : "DRAC/MC module name",
"order" : 1 },
"drac_version" : {
"getopt" : "d:",
"longopt" : "drac-version",
"help" : "-d, --drac-version=<version> Force DRAC version to use",
"required" : "0",
"shortdesc" : "Force DRAC version to use",
"order" : 1 },
"hmc_version" : {
"getopt" : "H:",
"longopt" : "hmc-version",
"help" : "-H, --hmc-version=<version> Force HMC version to use: 3, 4 (default)",
"required" : "0",
"shortdesc" : "Force HMC version to use (3 or 4)",
"default" : "4",
"order" : 1 },
"ribcl" : {
"getopt" : "r:",
"longopt" : "ribcl-version",
"help" : "-r, --ribcl-version=<version> Force ribcl version to use",
"required" : "0",
"shortdesc" : "Force ribcl version to use",
"order" : 1 },
"login_eol_lf" : {
"getopt" : "",
"help" : "",
"order" : 1
},
"cmd_prompt" : {
"getopt" : "c:",
"longopt" : "command-prompt",
"help" : "-c, --command-prompt=<prompt> Force command prompt",
"shortdesc" : "Force command prompt",
"required" : "0",
"order" : 1 },
"secure" : {
"getopt" : "x",
"longopt" : "ssh",
"help" : "-x, --ssh Use ssh connection",
"shortdesc" : "SSH connection",
"required" : "0",
"order" : 1 },
"ssl" : {
"getopt" : "z",
"longopt" : "ssl",
"help" : "-z, --ssl Use ssl connection",
"required" : "0",
"shortdesc" : "SSL connection",
"order" : 1 },
"port" : {
"getopt" : "n:",
"longopt" : "plug",
"help" : "-n, --plug=<id> Physical plug number on device or\n" +
" name of virtual machine",
"required" : "1",
"shortdesc" : "Physical plug number or name of virtual machine",
"order" : 1 },
"switch" : {
"getopt" : "s:",
"longopt" : "switch",
"help" : "-s, --switch=<id> Physical switch number on device",
"required" : "0",
"shortdesc" : "Physical switch number on device",
"order" : 1 },
"partition" : {
"getopt" : "n:",
"help" : "-n <id> Name of the partition",
"required" : "0",
"shortdesc" : "Partition name",
"order" : 1 },
"managed" : {
"getopt" : "s:",
"help" : "-s <id> Name of the managed system",
"required" : "0",
"shortdesc" : "Managed system name",
"order" : 1 },
"test" : {
"getopt" : "T",
"help" : "",
"order" : 1,
"obsolete" : "use -o status instead" },
"exec" : {
"getopt" : "e:",
"longopt" : "exec",
"help" : "-e, --exec=<command> Command to execute",
"required" : "0",
"shortdesc" : "Command to execute",
"order" : 1 },
"vmware_type" : {
"getopt" : "d:",
"longopt" : "vmware_type",
"help" : "-d, --vmware_type=<type> Type of VMware to connect",
"required" : "0",
"shortdesc" : "Type of VMware to connect",
"order" : 1 },
"vmware_datacenter" : {
"getopt" : "s:",
"longopt" : "vmware-datacenter",
"help" : "-s, --vmware-datacenter=<dc> VMWare datacenter filter",
"required" : "0",
"shortdesc" : "Show only machines in specified datacenter",
"order" : 2 },
"snmp_version" : {
"getopt" : "d:",
"longopt" : "snmp-version",
"help" : "-d, --snmp-version=<ver> Specifies SNMP version to use",
"required" : "0",
"shortdesc" : "Specifies SNMP version to use (1,2c,3)",
"order" : 1 },
"community" : {
"getopt" : "c:",
"longopt" : "community",
"help" : "-c, --community=<community> Set the community string",
"required" : "0",
"shortdesc" : "Set the community string",
"order" : 1},
"snmp_auth_prot" : {
"getopt" : "b:",
"longopt" : "snmp-auth-prot",
"help" : "-b, --snmp-auth-prot=<prot> Set authentication protocol (MD5|SHA)",
"required" : "0",
"shortdesc" : "Set authentication protocol (MD5|SHA)",
"order" : 1},
"snmp_sec_level" : {
"getopt" : "E:",
"longopt" : "snmp-sec-level",
"help" : "-E, --snmp-sec-level=<level> Set security level\n"+
" (noAuthNoPriv|authNoPriv|authPriv)",
"required" : "0",
"shortdesc" : "Set security level (noAuthNoPriv|authNoPriv|authPriv)",
"order" : 1},
"snmp_priv_prot" : {
"getopt" : "B:",
"longopt" : "snmp-priv-prot",
"help" : "-B, --snmp-priv-prot=<prot> Set privacy protocol (DES|AES)",
"required" : "0",
"shortdesc" : "Set privacy protocol (DES|AES)",
"order" : 1},
"snmp_priv_passwd" : {
"getopt" : "P:",
"longopt" : "snmp-priv-passwd",
"help" : "-P, --snmp-priv-passwd=<pass> Set privacy protocol password",
"required" : "0",
"shortdesc" : "Set privacy protocol password",
"order" : 1},
"snmp_priv_passwd_script" : {
"getopt" : "R:",
"longopt" : "snmp-priv-passwd-script",
"help" : "-R, --snmp-priv-passwd-script Script to run to retrieve privacy password",
"required" : "0",
"shortdesc" : "Script to run to retrieve privacy password",
"order" : 1},
"inet4_only" : {
"getopt" : "4",
"longopt" : "inet4-only",
"help" : "-4, --inet4-only Forces agent to use IPv4 addresses only",
"required" : "0",
"shortdesc" : "Forces agent to use IPv4 addresses only",
"order" : 1 },
"inet6_only" : {
"getopt" : "6",
"longopt" : "inet6-only",
"help" : "-6, --inet6-only Forces agent to use IPv6 addresses only",
"required" : "0",
"shortdesc" : "Forces agent to use IPv6 addresses only",
"order" : 1 },
"udpport" : {
"getopt" : "u:",
"longopt" : "udpport",
"help" : "-u, --udpport UDP/TCP port to use",
"required" : "0",
"shortdesc" : "UDP/TCP port to use for connection with device",
"order" : 1},
"separator" : {
"getopt" : "C:",
"longopt" : "separator",
"help" : "-C, --separator=<char> Separator for CSV created by 'list' operation",
"default" : ",",
"required" : "0",
"shortdesc" : "Separator for CSV created by operation list",
"order" : 100 },
"login_timeout" : {
"getopt" : "y:",
"longopt" : "login-timeout",
"help" : "--login-timeout <seconds> Wait X seconds for cmd prompt after login",
"default" : "5",
"required" : "0",
"shortdesc" : "Wait X seconds for cmd prompt after login",
"order" : 200 },
"shell_timeout" : {
"getopt" : "Y:",
"longopt" : "shell-timeout",
"help" : "--shell-timeout <seconds> Wait X seconds for cmd prompt after issuing command",
"default" : "3",
"required" : "0",
"shortdesc" : "Wait X seconds for cmd prompt after issuing command",
"order" : 200 },
"power_timeout" : {
"getopt" : "g:",
"longopt" : "power-timeout",
"help" : "--power-timeout <seconds> Test X seconds for status change after ON/OFF",
"default" : "20",
"required" : "0",
"shortdesc" : "Test X seconds for status change after ON/OFF",
"order" : 200 },
"power_wait" : {
"getopt" : "G:",
"longopt" : "power-wait",
"help" : "--power-wait <seconds> Wait X seconds after issuing ON/OFF",
"default" : "0",
"required" : "0",
"shortdesc" : "Wait X seconds after issuing ON/OFF",
"order" : 200 },
"missing_as_off" : {
"getopt" : "M",
"longopt" : "missing-as-off",
"help" : "--missing-as-off Missing port returns OFF instead of failure",
"required" : "0",
"shortdesc" : "Missing port returns OFF instead of failure",
"order" : 200 },
"retry_on" : {
"getopt" : "F:",
"longopt" : "retry-on",
"help" : "--retry-on <attempts> Count of attempts to retry power on",
"default" : "1",
"required" : "0",
"shortdesc" : "Count of attempts to retry power on",
"order" : 200 },
"session_url" : {
"getopt" : "s:",
"longopt" : "session-url",
"help" : "-s, --session-url URL to connect to XenServer on.",
"required" : "1",
"shortdesc" : "The URL of the XenServer host.",
"order" : 1},
"vm_name" : {
"getopt" : "n:",
"longopt" : "vm-name",
"help" : "-n, --vm-name Name of the VM to fence.",
"required" : "0",
"shortdesc" : "The name of the virual machine to fence.",
"order" : 1},
"uuid" : {
"getopt" : "U:",
"longopt" : "uuid",
"help" : "-U, --uuid UUID of the VM to fence.",
"required" : "0",
"shortdesc" : "The UUID of the virtual machine to fence.",
"order" : 1}
}
common_opt = [ "retry_on", "delay" ]
class fspawn(pexpect.spawn):
def log_expect(self, options, pattern, timeout):
result = self.expect(pattern, timeout)
if options["log"] >= LOG_MODE_VERBOSE:
options["debug_fh"].write(self.before + self.after)
return result
def atexit_handler():
try:
sys.stdout.close()
os.close(1)
except IOError:
sys.stderr.write("%s failed to close standard output\n"%(sys.argv[0]))
sys.exit(EC_GENERIC_ERROR)
def version(command, release, build_date, copyright_notice):
print command, " ", release, " ", build_date
if len(copyright_notice) > 0:
print copyright_notice
def fail_usage(message = ""):
if len(message) > 0:
sys.stderr.write(message+"\n")
sys.stderr.write("Please use '-h' for usage\n")
sys.exit(EC_GENERIC_ERROR)
def fail(error_code):
message = {
EC_LOGIN_DENIED : "Unable to connect/login to fencing device",
EC_CONNECTION_LOST : "Connection lost",
EC_TIMED_OUT : "Connection timed out",
EC_WAITING_ON : "Failed: Timed out waiting to power ON",
EC_WAITING_OFF : "Failed: Timed out waiting to power OFF",
EC_STATUS : "Failed: Unable to obtain correct plug status or plug is not available",
EC_STATUS_HMC : "Failed: Either unable to obtaion correct plug status, partition is not available or incorrect HMC version used"
}[error_code] + "\n"
sys.stderr.write(message)
sys.exit(EC_GENERIC_ERROR)
def usage(avail_opt):
global all_opt
print "Usage:"
print "\t" + os.path.basename(sys.argv[0]) + " [options]"
print "Options:"
sorted_list = [ (key, all_opt[key]) for key in avail_opt ]
sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"]))
for key, value in sorted_list:
if len(value["help"]) != 0:
print " " + value["help"]
def metadata(avail_opt, options, docs):
global all_opt
sorted_list = [ (key, all_opt[key]) for key in avail_opt ]
sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"]))
print "<?xml version=\"1.0\" ?>"
print "<resource-agent name=\"" + os.path.basename(sys.argv[0]) + "\" shortdesc=\"" + docs["shortdesc"] + "\" >"
print "<longdesc>" + docs["longdesc"] + "</longdesc>"
if docs.has_key("vendorurl"):
print "<vendor-url>" + docs["vendorurl"] + "</vendor-url>"
print "<parameters>"
for option, value in sorted_list:
if all_opt[option].has_key("shortdesc"):
print "\t<parameter name=\"" + option + "\" unique=\"1\" required=\"" + all_opt[option]["required"] + "\">"
default = ""
if all_opt[option].has_key("default"):
default = "default=\""+str(all_opt[option]["default"])+"\""
elif options.has_key("-" + all_opt[option]["getopt"][:-1]):
if options["-" + all_opt[option]["getopt"][:-1]]:
try:
default = "default=\"" + options["-" + all_opt[option]["getopt"][:-1]] + "\""
except TypeError:
## @todo/@note: Currently there is no clean way how to handle lists
## we can create a string from it but we can't set it on command line
default = "default=\"" + str(options["-" + all_opt[option]["getopt"][:-1]]) +"\""
elif options.has_key("-" + all_opt[option]["getopt"]):
default = "default=\"true\" "
mixed = all_opt[option]["help"]
## split it between option and help text
res = re.compile("^(.*--\S+)\s+", re.IGNORECASE | re.S).search(mixed)
if (None != res):
mixed = res.group(1)
mixed = mixed.replace("<", "<").replace(">", ">")
print "\t\t<getopt mixed=\"" + mixed + "\" />"
if all_opt[option]["getopt"].count(":") > 0:
print "\t\t<content type=\"string\" "+default+" />"
else:
print "\t\t<content type=\"boolean\" "+default+" />"
print "\t\t<shortdesc lang=\"en\">" + all_opt[option]["shortdesc"] + "</shortdesc>"
print "\t</parameter>"
print "</parameters>"
print "<actions>"
print "\t<action name=\"on\" />"
print "\t<action name=\"off\" />"
print "\t<action name=\"reboot\" />"
print "\t<action name=\"status\" />"
print "\t<action name=\"list\" />"
print "\t<action name=\"monitor\" />"
print "\t<action name=\"metadata\" />"
print "</actions>"
print "</resource-agent>"
def process_input(avail_opt):
global all_opt
global common_opt
##
## Add options which are available for every fence agent
#####
avail_opt.extend(common_opt)
##
## Set standard environment
#####
os.putenv("LANG", "C")
os.putenv("LC_ALL", "C")
##
## Prepare list of options for getopt
#####
getopt_string = ""
longopt_list = [ ]
for k in avail_opt:
if all_opt.has_key(k):
getopt_string += all_opt[k]["getopt"]
else:
fail_usage("Parse error: unknown option '"+k+"'")
if all_opt.has_key(k) and all_opt[k].has_key("longopt"):
if all_opt[k]["getopt"].endswith(":"):
longopt_list.append(all_opt[k]["longopt"] + "=")
else:
longopt_list.append(all_opt[k]["longopt"])
## Compatibility layer
if avail_opt.count("module_name") == 1:
getopt_string += "n:"
longopt_list.append("plug=")
##
## Read options from command line or standard input
#####
if len(sys.argv) > 1:
try:
opt, args = getopt.gnu_getopt(sys.argv[1:], getopt_string, longopt_list)
except getopt.GetoptError, error:
fail_usage("Parse error: " + error.msg)
## Transform longopt to short one which are used in fencing agents
#####
old_opt = opt
opt = { }
for o in dict(old_opt).keys():
if o.startswith("--"):
for x in all_opt.keys():
if all_opt[x].has_key("longopt") and "--" + all_opt[x]["longopt"] == o:
opt["-" + all_opt[x]["getopt"].rstrip(":")] = dict(old_opt)[o]
else:
opt[o] = dict(old_opt)[o]
## Compatibility Layer
#####
z = dict(opt)
if z.has_key("-T") == 1:
z["-o"] = "status"
if z.has_key("-n") == 1:
z["-m"] = z["-n"]
opt = z
##
#####
else:
opt = { }
name = ""
for line in sys.stdin.readlines():
line = line.strip()
if ((line.startswith("#")) or (len(line) == 0)):
continue
(name, value) = (line + "=").split("=", 1)
value = value[:-1]
## Compatibility Layer
######
if name == "blade":
name = "port"
elif name == "option":
name = "action"
elif name == "fm":
name = "port"
elif name == "hostname":
name = "ipaddr"
elif name == "modulename":
name = "module_name"
elif name == "action" and 1 == avail_opt.count("io_fencing"):
name = "io_fencing"
elif name == "port" and 1 == avail_opt.count("drac_version"):
name = "module_name"
##
######
if avail_opt.count(name) == 0:
sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n")
continue
if all_opt[name]["getopt"].endswith(":"):
opt["-"+all_opt[name]["getopt"].rstrip(":")] = value
elif ((value == "1") or (value.lower() == "yes")):
opt["-"+all_opt[name]["getopt"]] = "1"
return opt
##
## This function checks input and answers if we want to have same answers
## in each of the fencing agents. It looks for possible errors and run
## password script to set a correct password
######
def check_input(device_opt, opt):
global all_opt
global common_opt
##
## Add options which are available for every fence agent
#####
device_opt.extend([x for x in common_opt if device_opt.count(x) == 0])
options = dict(opt)
options["device_opt"] = device_opt
## Set requirements that should be included in metadata
#####
if device_opt.count("login") and device_opt.count("no_login") == 0:
all_opt["login"]["required"] = "1"
else:
all_opt["login"]["required"] = "0"
## In special cases (show help, metadata or version) we don't need to check anything
#####
if options.has_key("-h") or options.has_key("-V") or (options.has_key("-o") and options["-o"].lower() == "metadata"):
return options;
## Set default values
#####
for opt in device_opt:
if all_opt[opt].has_key("default"):
getopt = "-" + all_opt[opt]["getopt"].rstrip(":")
if 0 == options.has_key(getopt):
options[getopt] = all_opt[opt]["default"]
options["-o"]=options["-o"].lower()
if options.has_key("-v"):
options["log"] = LOG_MODE_VERBOSE
else:
options["log"] = LOG_MODE_QUIET
if 0 == device_opt.count("io_fencing"):
if 0 == ["on", "off", "reboot", "status", "list", "monitor"].count(options["-o"].lower()):
fail_usage("Failed: Unrecognised action '" + options["-o"] + "'")
else:
if 0 == ["enable", "disable", "status", "list", "monitor"].count(options["-o"].lower()):
fail_usage("Failed: Unrecognised action '" + options["-o"] + "'")
if (0 == options.has_key("-l")) and device_opt.count("login") and (device_opt.count("no_login") == 0):
fail_usage("Failed: You have to set login name")
if 0 == options.has_key("-a") and 0 == options.has_key("-s"):
fail_usage("Failed: You have to enter fence address")
if (0 == ["list", "monitor"].count(options["-o"].lower())) and device_opt.count("vm_name") and device_opt.count("uuid"):
if 0 == options.has_key("-n") and 0 == options.has_key("-U"):
fail_usage("Failed: You must specify either UUID or VM name")
if (device_opt.count("no_password") == 0):
if 0 == device_opt.count("identity_file"):
if 0 == (options.has_key("-p") or options.has_key("-S")):
fail_usage("Failed: You have to enter password or password script")
else:
if 0 == (options.has_key("-p") or options.has_key("-S") or options.has_key("-k")):
fail_usage("Failed: You have to enter password, password script or identity file")
if 0 == options.has_key("-x") and 1 == options.has_key("-k"):
fail_usage("Failed: You have to use identity file together with ssh connection (-x)")
if 1 == options.has_key("-k"):
if 0 == os.path.isfile(options["-k"]):
fail_usage("Failed: Identity file " + options["-k"] + " does not exist")
if (0 == ["list", "monitor"].count(options["-o"].lower())) and (0 == options.has_key("-n")) and (device_opt.count("port")):
fail_usage("Failed: You have to enter plug number")
if options.has_key("-S"):
options["-p"] = os.popen(options["-S"]).read().rstrip()
if options.has_key("-D"):
try:
options["debug_fh"] = file (options["-D"], "w")
except IOError:
fail_usage("Failed: Unable to create file "+options["-D"])
if options.has_key("-v") and options.has_key("debug_fh") == 0:
options["debug_fh"] = sys.stderr
if options.has_key("-R"):
options["-P"] = os.popen(options["-R"]).read().rstrip()
if options.has_key("-u") == False:
if options.has_key("-x"):
options["-u"] = 22
elif options.has_key("-z"):
options["-u"] = 443
elif device_opt.count("web"):
options["-u"] = 80
else:
options["-u"] = 23
return options
def wait_power_status(tn, options, get_power_fn):
for dummy in xrange(int(options["-g"])):
if get_power_fn(tn, options) != options["-o"]:
time.sleep(1)
else:
return 1
return 0
def show_docs(options, docs = None):
device_opt = options["device_opt"]
if docs == None:
docs = { }
docs["shortdesc"] = "Fence agent"
docs["longdesc"] = ""
## Process special options (and exit)
#####
if options.has_key("-h"):
usage(device_opt)
sys.exit(0)
if options.has_key("-o") and options["-o"].lower() == "metadata":
metadata(device_opt, options, docs)
sys.exit(0)
if options.has_key("-V"):
print __main__.RELEASE_VERSION, __main__.BUILD_DATE
print __main__.REDHAT_COPYRIGHT
sys.exit(0)
def fence_action(tn, options, set_power_fn, get_power_fn, get_outlet_list = None):
result = 0
## Process options that manipulate fencing device
#####
if (options["-o"] == "list") and (0 == options["device_opt"].count("port")) and (0 == options["device_opt"].count("partition")) and (0 == options["device_opt"].count("uuid")):
print "N/A"
return
elif (options["-o"] == "list" and get_outlet_list == None):
## @todo: exception?
## This is just temporal solution, we will remove default value
## None as soon as all existing agent will support this operation
print "NOTICE: List option is not working on this device yet"
return
elif (options["-o"] == "list") or ((options["-o"] == "monitor") and 1 == options["device_opt"].count("port")):
outlets = get_outlet_list(tn, options)
## keys can be numbers (port numbers) or strings (names of VM)
for o in outlets.keys():
(alias, status) = outlets[o]
if options["-o"] != "monitor":
print o + options["-C"] + alias
return
if options["-o"] in ["off", "reboot"]:
time.sleep(int(options["-f"]))
status = get_power_fn(tn, options)
if status != "on" and status != "off":
fail(EC_STATUS)
if options["-o"] == "enable":
options["-o"] = "on"
if options["-o"] == "disable":
options["-o"] = "off"
if options["-o"] == "on":
if status == "on":
print "Success: Already ON"
else:
power_on = False
for i in range(1,1 + int(options["-F"])):
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn):
power_on = True
break
if power_on:
print "Success: Powered ON"
else:
fail(EC_WAITING_ON)
elif options["-o"] == "off":
if status == "off":
print "Success: Already OFF"
else:
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn):
print "Success: Powered OFF"
else:
fail(EC_WAITING_OFF)
elif options["-o"] == "reboot":
if status != "off":
options["-o"] = "off"
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn) == 0:
fail(EC_WAITING_OFF)
options["-o"] = "on"
power_on = False
for i in range(1,1 + int(options["-F"])):
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn) == 1:
power_on = True
break
if power_on == False:
# this should not fail as not was fenced succesfully
sys.stderr.write('Timed out waiting to power ON\n')
print "Success: Rebooted"
elif options["-o"] == "status":
print "Status: " + status.upper()
if status.upper() == "OFF":
result = 2
elif options["-o"] == "monitor":
1
return result
def fence_login(options):
force_ipvx=""
if (options.has_key("-6")):
force_ipvx="-6 "
if (options.has_key("-4")):
force_ipvx="-4 "
if (options["device_opt"].count("login_eol_lf")):
login_eol = "\n"
else:
login_eol = "\r\n"
try:
re_login = re.compile("(login\s*: )|(Login Name: )|(username: )|(User Name :)", re.IGNORECASE)
re_pass = re.compile("password", re.IGNORECASE)
if options.has_key("-z"):
command = '%s %s %s %s' % (SSL_PATH, force_ipvx, options["-a"], options["-u"])
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
## SSL telnet is part of the fencing package
sys.stderr.write(str(ex) + "\n")
sys.exit(EC_GENERIC_ERROR)
elif options.has_key("-x") and 0 == options.has_key("-k"):
command = '%s %s %s@%s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-u"])
if options.has_key("ssh_options"):
command += ' ' + options["ssh_options"]
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
if options.has_key("telnet_over_ssh"):
#This is for stupid ssh servers (like ALOM) which behave more like telnet (ignore name and display login prompt)
result = conn.log_expect(options, [ re_login, "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"]))
if result == 1:
conn.sendline("yes") # Host identity confirm
conn.log_expect(options, re_login, int(options["-y"]))
conn.sendline(options["-l"])
conn.log_expect(options, re_pass, int(options["-y"]))
else:
result = conn.log_expect(options, [ "ssword:", "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"]))
if result == 1:
conn.sendline("yes")
conn.log_expect(options, "ssword:", int(options["-y"]))
conn.sendline(options["-p"])
conn.log_expect(options, options["-c"], int(options["-y"]))
elif options.has_key("-x") and 1 == options.has_key("-k"):
command = '%s %s %s@%s -i %s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-k"], options["-u"])
if options.has_key("ssh_options"):
command += ' ' + options["ssh_options"]
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
result = conn.log_expect(options, [ options["-c"], "Are you sure you want to continue connecting (yes/no)?", "Enter passphrase for key '"+options["-k"]+"':" ], int(options["-y"]))
if result == 1:
conn.sendline("yes")
conn.log_expect(options, [ options["-c"], "Enter passphrase for key '"+options["-k"]+"':"] , int(options["-y"]))
if result != 0:
if options.has_key("-p"):
conn.sendline(options["-p"])
conn.log_expect(options, options["-c"], int(options["-y"]))
else:
fail_usage("Failed: You have to enter passphrase (-p) for identity file")
else:
try:
conn = fspawn(TELNET_PATH)
conn.send("set binary\n")
conn.send("open %s -%s\n"%(options["-a"], options["-u"]))
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
conn.log_expect(options, re_login, int(options["-y"]))
conn.send(options["-l"] + login_eol)
conn.log_expect(options, re_pass, int(options["-Y"]))
conn.send(options["-p"] + login_eol)
conn.log_expect(options, options["-c"], int(options["-Y"]))
except pexpect.EOF:
fail(EC_LOGIN_DENIED)
except pexpect.TIMEOUT:
fail(EC_LOGIN_DENIED)
return conn
| Python |
#!/usr/bin/python
# It's only just begun...
# Current status: completely unusable, try the fence_cxs.py script for the moment. This Red
# Hat compatible version is just in its' infancy.
# Copyright 2011 Matt Clark
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
from fencing import *
import XenAPI
EC_BAD_SESSION = 1
# Find the status of the port given in the -U flag of options.
def get_power_fn(session, options):
#uuid = options["-U"].lower()
try:
# Get a reference to the vm specified in the UUID or vm_name parameter
vm = return_vm_reference(session, options)
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm);
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
status = record["power_state"]
print "UUID:", record["uuid"], "NAME:", record["name_label"], "POWER STATUS:", record["power_state"]
# Note that the VM can be in the following states (from the XenAPI document)
# Halted: VM is offline and not using any resources.
# Paused: All resources have been allocated but the VM itself is paused and its vCPUs are not running
# Running: Running
# Paused: VM state has been saved to disk and it is nolonger running. Note that disks remain in-Use while
# We want to make sure that we only return the status "off" if the machine is actually halted as the status
# is checked before a fencing action. Only when the machine is Halted is it not consuming resources which
# may include whatever you are trying to protect with this fencing action.
return (status=="Halted" and "off" or "on")
except Exception, exn:
print str(exn)
return "Error"
# Set the state of the port given in the -U flag of options.
def set_power_fn(session, options):
uuid = options["-U"].lower()
action = options["-o"].lower()
try:
# Get a reference to the vm specified in the UUID or vm_name parameter
vm = return_vm_reference(session, options)
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm)
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
# Start the VM
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
# Force shutdown the VM
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
# Force reboot the VM
session.xenapi.VM.hard_reboot(vm)
except Exception, exn:
print str(exn);
# Function to populate an array of virtual machines and their status
def get_outlet_list(session, options):
result = {}
try:
# Return an array of all the VM's on the host
vms = session.xenapi.VM.get_all()
for vm in vms:
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm);
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
uuid = record["uuid"]
status = record["power_state"]
result[uuid] = (name, status)
print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
return result
# Function to initiate the XenServer session via the XenAPI library.
def connect_and_login(options):
url = options["-s"]
username = options["-l"]
password = options["-p"]
try:
# Create the XML RPC session to the specified URL.
session = XenAPI.Session(url);
# Login using the supplied credentials.
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
# http://sources.redhat.com/cluster/wiki/FenceAgentAPI says that for no connectivity
# the exit value should be 1. It doesn't say anything about failed logins, so
# until I hear otherwise it is best to keep this exit the same to make sure that
# anything calling this script (that uses the same information in the web page
# above) knows that this is an error condition, not a msg signifying a down port.
sys.exit(EC_BAD_SESSION);
return session;
# return a reference to the VM by either using the UUID or the vm_name. If the UUID is set then
# this is tried first as this is the only properly unique identifier.
# Exceptions are not handled in this function, code that calls this must be ready to handle them.
def return_vm_reference(session, options):
# Case where the UUID has been specified
if options.has_key("-U"):
uuid = options["-U"].lower()
return session.xenapi.VM.get_by_uuid(uuid)
# Case where the vm_name has been specified
if options.has_key("-n"):
vm_name = options["-n"]
vm_arr = session.xenapi.VM.get_by_name_label(vm_name)
# Need to make sure that we only have one result as the vm_name may
# not be unique. Average case, so do it first.
if len(vm_arr) == 1:
return vm_arr[0]
else:
# TODO: Need to either fail usage or raise exception
# at least say something like none or multiple vms found
# with that name.
# if len(vm_arr) == 0:
# no vm's found
# else:
# multiple vms found with the same name, use uuid instead
return None
def main():
device_opt = [ "help", "version", "agent", "quiet", "verbose", "debug", "action",
"login", "passwd", "passwd_script", "vm_name", "test", "separator",
"no_login", "no_password", "power_timeout", "shell_timeout",
"login_timeout", "power_wait", "session_url", "uuid" ]
atexit.register(atexit_handler)
options=process_input(device_opt)
options = check_input(device_opt, options)
docs = { }
docs["shortdesc"] = "Fence agent for Citrix XenServer"
docs["longdesc"] = "fence_cxs_redhat"
show_docs(options, docs)
xenSession = connect_and_login(options)
# Operate the fencing device
result = fence_action(xenSession, options, set_power_fn, get_power_fn, get_outlet_list)
sys.exit(result)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
import sys, getopt, time, os
import pexpect, re
import telnetlib
import atexit
import __main__
## do not add code here.
#BEGIN_VERSION_GENERATION
RELEASE_VERSION="3.0.17"
BUILD_DATE="(built Thu Oct 7 07:06:21 UTC 2010)"
REDHAT_COPYRIGHT="Copyright (C) Red Hat, Inc. 2004-2010 All rights reserved."
#END_VERSION_GENERATION
LOG_MODE_VERBOSE = 100
LOG_MODE_QUIET = 0
EC_GENERIC_ERROR = 1
EC_BAD_ARGS = 2
EC_LOGIN_DENIED = 3
EC_CONNECTION_LOST = 4
EC_TIMED_OUT = 5
EC_WAITING_ON = 6
EC_WAITING_OFF = 7
EC_STATUS = 8
EC_STATUS_HMC = 9
TELNET_PATH = "/usr/bin/telnet"
SSH_PATH = "/usr/bin/ssh"
SSL_PATH = "/usr/sbin/fence_nss_wrapper"
all_opt = {
"help" : {
"getopt" : "h",
"longopt" : "help",
"help" : "-h, --help Display this help and exit",
"required" : "0",
"shortdesc" : "Display help and exit",
"order" : 54 },
"version" : {
"getopt" : "V",
"longopt" : "version",
"help" : "-V, --version Output version information and exit",
"required" : "0",
"shortdesc" : "Display version information and exit",
"order" : 53 },
"quiet" : {
"getopt" : "q",
"help" : "",
"order" : 50 },
"verbose" : {
"getopt" : "v",
"longopt" : "verbose",
"help" : "-v, --verbose Verbose mode",
"required" : "0",
"shortdesc" : "Verbose mode",
"order" : 51 },
"debug" : {
"getopt" : "D:",
"longopt" : "debug-file",
"help" : "-D, --debug-file=<debugfile> Debugging to output file",
"required" : "0",
"shortdesc" : "Write debug information to given file",
"order" : 52 },
"delay" : {
"getopt" : "f:",
"longopt" : "delay",
"help" : "--delay <seconds> Wait X seconds before fencing is started",
"required" : "0",
"shortdesc" : "Wait X seconds before fencing is started",
"default" : "0",
"order" : 200 },
"agent" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"web" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"action" : {
"getopt" : "o:",
"longopt" : "action",
"help" : "-o, --action=<action> Action: status, reboot (default), off or on",
"required" : "1",
"shortdesc" : "Fencing Action",
"default" : "reboot",
"order" : 1 },
"io_fencing" : {
"getopt" : "o:",
"longopt" : "action",
"help" : "-o, --action=<action> Action: status, enable or disable",
"required" : "1",
"shortdesc" : "Fencing Action",
"default" : "disable",
"order" : 1 },
"ipaddr" : {
"getopt" : "a:",
"longopt" : "ip",
"help" : "-a, --ip=<ip> IP address or hostname of fencing device",
"required" : "1",
"shortdesc" : "IP Address or Hostname",
"order" : 1 },
"ipport" : {
"getopt" : "u:",
"longopt" : "ipport",
"help" : "-u, --ipport=<port> TCP port to use",
"required" : "0",
"shortdesc" : "TCP port to use for connection with device",
"order" : 1 },
"login" : {
"getopt" : "l:",
"longopt" : "username",
"help" : "-l, --username=<name> Login name",
"required" : "?",
"shortdesc" : "Login Name",
"order" : 1 },
"no_login" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"no_password" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"passwd" : {
"getopt" : "p:",
"longopt" : "password",
"help" : "-p, --password=<password> Login password or passphrase",
"required" : "0",
"shortdesc" : "Login password or passphrase",
"order" : 1 },
"passwd_script" : {
"getopt" : "S:",
"longopt" : "password-script=",
"help" : "-S, --password-script=<script> Script to run to retrieve password",
"required" : "0",
"shortdesc" : "Script to retrieve password",
"order" : 1 },
"identity_file" : {
"getopt" : "k:",
"longopt" : "identity-file",
"help" : "-k, --identity-file=<filename> Identity file (private key) for ssh ",
"required" : "0",
"shortdesc" : "Identity file for ssh",
"order" : 1 },
"module_name" : {
"getopt" : "m:",
"longopt" : "module-name",
"help" : "-m, --module-name=<module> DRAC/MC module name",
"required" : "0",
"shortdesc" : "DRAC/MC module name",
"order" : 1 },
"drac_version" : {
"getopt" : "d:",
"longopt" : "drac-version",
"help" : "-d, --drac-version=<version> Force DRAC version to use",
"required" : "0",
"shortdesc" : "Force DRAC version to use",
"order" : 1 },
"hmc_version" : {
"getopt" : "H:",
"longopt" : "hmc-version",
"help" : "-H, --hmc-version=<version> Force HMC version to use: 3, 4 (default)",
"required" : "0",
"shortdesc" : "Force HMC version to use (3 or 4)",
"default" : "4",
"order" : 1 },
"ribcl" : {
"getopt" : "r:",
"longopt" : "ribcl-version",
"help" : "-r, --ribcl-version=<version> Force ribcl version to use",
"required" : "0",
"shortdesc" : "Force ribcl version to use",
"order" : 1 },
"login_eol_lf" : {
"getopt" : "",
"help" : "",
"order" : 1
},
"cmd_prompt" : {
"getopt" : "c:",
"longopt" : "command-prompt",
"help" : "-c, --command-prompt=<prompt> Force command prompt",
"shortdesc" : "Force command prompt",
"required" : "0",
"order" : 1 },
"secure" : {
"getopt" : "x",
"longopt" : "ssh",
"help" : "-x, --ssh Use ssh connection",
"shortdesc" : "SSH connection",
"required" : "0",
"order" : 1 },
"ssl" : {
"getopt" : "z",
"longopt" : "ssl",
"help" : "-z, --ssl Use ssl connection",
"required" : "0",
"shortdesc" : "SSL connection",
"order" : 1 },
"port" : {
"getopt" : "n:",
"longopt" : "plug",
"help" : "-n, --plug=<id> Physical plug number on device or\n" +
" name of virtual machine",
"required" : "1",
"shortdesc" : "Physical plug number or name of virtual machine",
"order" : 1 },
"switch" : {
"getopt" : "s:",
"longopt" : "switch",
"help" : "-s, --switch=<id> Physical switch number on device",
"required" : "0",
"shortdesc" : "Physical switch number on device",
"order" : 1 },
"partition" : {
"getopt" : "n:",
"help" : "-n <id> Name of the partition",
"required" : "0",
"shortdesc" : "Partition name",
"order" : 1 },
"managed" : {
"getopt" : "s:",
"help" : "-s <id> Name of the managed system",
"required" : "0",
"shortdesc" : "Managed system name",
"order" : 1 },
"test" : {
"getopt" : "T",
"help" : "",
"order" : 1,
"obsolete" : "use -o status instead" },
"exec" : {
"getopt" : "e:",
"longopt" : "exec",
"help" : "-e, --exec=<command> Command to execute",
"required" : "0",
"shortdesc" : "Command to execute",
"order" : 1 },
"vmware_type" : {
"getopt" : "d:",
"longopt" : "vmware_type",
"help" : "-d, --vmware_type=<type> Type of VMware to connect",
"required" : "0",
"shortdesc" : "Type of VMware to connect",
"order" : 1 },
"vmware_datacenter" : {
"getopt" : "s:",
"longopt" : "vmware-datacenter",
"help" : "-s, --vmware-datacenter=<dc> VMWare datacenter filter",
"required" : "0",
"shortdesc" : "Show only machines in specified datacenter",
"order" : 2 },
"snmp_version" : {
"getopt" : "d:",
"longopt" : "snmp-version",
"help" : "-d, --snmp-version=<ver> Specifies SNMP version to use",
"required" : "0",
"shortdesc" : "Specifies SNMP version to use (1,2c,3)",
"order" : 1 },
"community" : {
"getopt" : "c:",
"longopt" : "community",
"help" : "-c, --community=<community> Set the community string",
"required" : "0",
"shortdesc" : "Set the community string",
"order" : 1},
"snmp_auth_prot" : {
"getopt" : "b:",
"longopt" : "snmp-auth-prot",
"help" : "-b, --snmp-auth-prot=<prot> Set authentication protocol (MD5|SHA)",
"required" : "0",
"shortdesc" : "Set authentication protocol (MD5|SHA)",
"order" : 1},
"snmp_sec_level" : {
"getopt" : "E:",
"longopt" : "snmp-sec-level",
"help" : "-E, --snmp-sec-level=<level> Set security level\n"+
" (noAuthNoPriv|authNoPriv|authPriv)",
"required" : "0",
"shortdesc" : "Set security level (noAuthNoPriv|authNoPriv|authPriv)",
"order" : 1},
"snmp_priv_prot" : {
"getopt" : "B:",
"longopt" : "snmp-priv-prot",
"help" : "-B, --snmp-priv-prot=<prot> Set privacy protocol (DES|AES)",
"required" : "0",
"shortdesc" : "Set privacy protocol (DES|AES)",
"order" : 1},
"snmp_priv_passwd" : {
"getopt" : "P:",
"longopt" : "snmp-priv-passwd",
"help" : "-P, --snmp-priv-passwd=<pass> Set privacy protocol password",
"required" : "0",
"shortdesc" : "Set privacy protocol password",
"order" : 1},
"snmp_priv_passwd_script" : {
"getopt" : "R:",
"longopt" : "snmp-priv-passwd-script",
"help" : "-R, --snmp-priv-passwd-script Script to run to retrieve privacy password",
"required" : "0",
"shortdesc" : "Script to run to retrieve privacy password",
"order" : 1},
"inet4_only" : {
"getopt" : "4",
"longopt" : "inet4-only",
"help" : "-4, --inet4-only Forces agent to use IPv4 addresses only",
"required" : "0",
"shortdesc" : "Forces agent to use IPv4 addresses only",
"order" : 1 },
"inet6_only" : {
"getopt" : "6",
"longopt" : "inet6-only",
"help" : "-6, --inet6-only Forces agent to use IPv6 addresses only",
"required" : "0",
"shortdesc" : "Forces agent to use IPv6 addresses only",
"order" : 1 },
"udpport" : {
"getopt" : "u:",
"longopt" : "udpport",
"help" : "-u, --udpport UDP/TCP port to use",
"required" : "0",
"shortdesc" : "UDP/TCP port to use for connection with device",
"order" : 1},
"separator" : {
"getopt" : "C:",
"longopt" : "separator",
"help" : "-C, --separator=<char> Separator for CSV created by 'list' operation",
"default" : ",",
"required" : "0",
"shortdesc" : "Separator for CSV created by operation list",
"order" : 100 },
"login_timeout" : {
"getopt" : "y:",
"longopt" : "login-timeout",
"help" : "--login-timeout <seconds> Wait X seconds for cmd prompt after login",
"default" : "5",
"required" : "0",
"shortdesc" : "Wait X seconds for cmd prompt after login",
"order" : 200 },
"shell_timeout" : {
"getopt" : "Y:",
"longopt" : "shell-timeout",
"help" : "--shell-timeout <seconds> Wait X seconds for cmd prompt after issuing command",
"default" : "3",
"required" : "0",
"shortdesc" : "Wait X seconds for cmd prompt after issuing command",
"order" : 200 },
"power_timeout" : {
"getopt" : "g:",
"longopt" : "power-timeout",
"help" : "--power-timeout <seconds> Test X seconds for status change after ON/OFF",
"default" : "20",
"required" : "0",
"shortdesc" : "Test X seconds for status change after ON/OFF",
"order" : 200 },
"power_wait" : {
"getopt" : "G:",
"longopt" : "power-wait",
"help" : "--power-wait <seconds> Wait X seconds after issuing ON/OFF",
"default" : "0",
"required" : "0",
"shortdesc" : "Wait X seconds after issuing ON/OFF",
"order" : 200 },
"missing_as_off" : {
"getopt" : "M",
"longopt" : "missing-as-off",
"help" : "--missing-as-off Missing port returns OFF instead of failure",
"required" : "0",
"shortdesc" : "Missing port returns OFF instead of failure",
"order" : 200 },
"retry_on" : {
"getopt" : "F:",
"longopt" : "retry-on",
"help" : "--retry-on <attempts> Count of attempts to retry power on",
"default" : "1",
"required" : "0",
"shortdesc" : "Count of attempts to retry power on",
"order" : 200 },
"session_url" : {
"getopt" : "s:",
"longopt" : "session-url",
"help" : "-s, --session-url URL to connect to XenServer on.",
"required" : "1",
"shortdesc" : "The URL of the XenServer host.",
"order" : 1},
"vm_name" : {
"getopt" : "n:",
"longopt" : "vm-name",
"help" : "-n, --vm-name Name of the VM to fence.",
"required" : "0",
"shortdesc" : "The name of the virual machine to fence.",
"order" : 1},
"uuid" : {
"getopt" : "U:",
"longopt" : "uuid",
"help" : "-U, --uuid UUID of the VM to fence.",
"required" : "0",
"shortdesc" : "The UUID of the virtual machine to fence.",
"order" : 1}
}
common_opt = [ "retry_on", "delay" ]
class fspawn(pexpect.spawn):
def log_expect(self, options, pattern, timeout):
result = self.expect(pattern, timeout)
if options["log"] >= LOG_MODE_VERBOSE:
options["debug_fh"].write(self.before + self.after)
return result
def atexit_handler():
try:
sys.stdout.close()
os.close(1)
except IOError:
sys.stderr.write("%s failed to close standard output\n"%(sys.argv[0]))
sys.exit(EC_GENERIC_ERROR)
def version(command, release, build_date, copyright_notice):
print command, " ", release, " ", build_date
if len(copyright_notice) > 0:
print copyright_notice
def fail_usage(message = ""):
if len(message) > 0:
sys.stderr.write(message+"\n")
sys.stderr.write("Please use '-h' for usage\n")
sys.exit(EC_GENERIC_ERROR)
def fail(error_code):
message = {
EC_LOGIN_DENIED : "Unable to connect/login to fencing device",
EC_CONNECTION_LOST : "Connection lost",
EC_TIMED_OUT : "Connection timed out",
EC_WAITING_ON : "Failed: Timed out waiting to power ON",
EC_WAITING_OFF : "Failed: Timed out waiting to power OFF",
EC_STATUS : "Failed: Unable to obtain correct plug status or plug is not available",
EC_STATUS_HMC : "Failed: Either unable to obtaion correct plug status, partition is not available or incorrect HMC version used"
}[error_code] + "\n"
sys.stderr.write(message)
sys.exit(EC_GENERIC_ERROR)
def usage(avail_opt):
global all_opt
print "Usage:"
print "\t" + os.path.basename(sys.argv[0]) + " [options]"
print "Options:"
sorted_list = [ (key, all_opt[key]) for key in avail_opt ]
sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"]))
for key, value in sorted_list:
if len(value["help"]) != 0:
print " " + value["help"]
def metadata(avail_opt, options, docs):
global all_opt
sorted_list = [ (key, all_opt[key]) for key in avail_opt ]
sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"]))
print "<?xml version=\"1.0\" ?>"
print "<resource-agent name=\"" + os.path.basename(sys.argv[0]) + "\" shortdesc=\"" + docs["shortdesc"] + "\" >"
print "<longdesc>" + docs["longdesc"] + "</longdesc>"
if docs.has_key("vendorurl"):
print "<vendor-url>" + docs["vendorurl"] + "</vendor-url>"
print "<parameters>"
for option, value in sorted_list:
if all_opt[option].has_key("shortdesc"):
print "\t<parameter name=\"" + option + "\" unique=\"1\" required=\"" + all_opt[option]["required"] + "\">"
default = ""
if all_opt[option].has_key("default"):
default = "default=\""+str(all_opt[option]["default"])+"\""
elif options.has_key("-" + all_opt[option]["getopt"][:-1]):
if options["-" + all_opt[option]["getopt"][:-1]]:
try:
default = "default=\"" + options["-" + all_opt[option]["getopt"][:-1]] + "\""
except TypeError:
## @todo/@note: Currently there is no clean way how to handle lists
## we can create a string from it but we can't set it on command line
default = "default=\"" + str(options["-" + all_opt[option]["getopt"][:-1]]) +"\""
elif options.has_key("-" + all_opt[option]["getopt"]):
default = "default=\"true\" "
mixed = all_opt[option]["help"]
## split it between option and help text
res = re.compile("^(.*--\S+)\s+", re.IGNORECASE | re.S).search(mixed)
if (None != res):
mixed = res.group(1)
mixed = mixed.replace("<", "<").replace(">", ">")
print "\t\t<getopt mixed=\"" + mixed + "\" />"
if all_opt[option]["getopt"].count(":") > 0:
print "\t\t<content type=\"string\" "+default+" />"
else:
print "\t\t<content type=\"boolean\" "+default+" />"
print "\t\t<shortdesc lang=\"en\">" + all_opt[option]["shortdesc"] + "</shortdesc>"
print "\t</parameter>"
print "</parameters>"
print "<actions>"
print "\t<action name=\"on\" />"
print "\t<action name=\"off\" />"
print "\t<action name=\"reboot\" />"
print "\t<action name=\"status\" />"
print "\t<action name=\"list\" />"
print "\t<action name=\"monitor\" />"
print "\t<action name=\"metadata\" />"
print "</actions>"
print "</resource-agent>"
def process_input(avail_opt):
global all_opt
global common_opt
##
## Add options which are available for every fence agent
#####
avail_opt.extend(common_opt)
##
## Set standard environment
#####
os.putenv("LANG", "C")
os.putenv("LC_ALL", "C")
##
## Prepare list of options for getopt
#####
getopt_string = ""
longopt_list = [ ]
for k in avail_opt:
if all_opt.has_key(k):
getopt_string += all_opt[k]["getopt"]
else:
fail_usage("Parse error: unknown option '"+k+"'")
if all_opt.has_key(k) and all_opt[k].has_key("longopt"):
if all_opt[k]["getopt"].endswith(":"):
longopt_list.append(all_opt[k]["longopt"] + "=")
else:
longopt_list.append(all_opt[k]["longopt"])
## Compatibility layer
if avail_opt.count("module_name") == 1:
getopt_string += "n:"
longopt_list.append("plug=")
##
## Read options from command line or standard input
#####
if len(sys.argv) > 1:
try:
opt, args = getopt.gnu_getopt(sys.argv[1:], getopt_string, longopt_list)
except getopt.GetoptError, error:
fail_usage("Parse error: " + error.msg)
## Transform longopt to short one which are used in fencing agents
#####
old_opt = opt
opt = { }
for o in dict(old_opt).keys():
if o.startswith("--"):
for x in all_opt.keys():
if all_opt[x].has_key("longopt") and "--" + all_opt[x]["longopt"] == o:
opt["-" + all_opt[x]["getopt"].rstrip(":")] = dict(old_opt)[o]
else:
opt[o] = dict(old_opt)[o]
## Compatibility Layer
#####
z = dict(opt)
if z.has_key("-T") == 1:
z["-o"] = "status"
if z.has_key("-n") == 1:
z["-m"] = z["-n"]
opt = z
##
#####
else:
opt = { }
name = ""
for line in sys.stdin.readlines():
line = line.strip()
if ((line.startswith("#")) or (len(line) == 0)):
continue
(name, value) = (line + "=").split("=", 1)
value = value[:-1]
## Compatibility Layer
######
if name == "blade":
name = "port"
elif name == "option":
name = "action"
elif name == "fm":
name = "port"
elif name == "hostname":
name = "ipaddr"
elif name == "modulename":
name = "module_name"
elif name == "action" and 1 == avail_opt.count("io_fencing"):
name = "io_fencing"
elif name == "port" and 1 == avail_opt.count("drac_version"):
name = "module_name"
##
######
if avail_opt.count(name) == 0:
sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n")
continue
if all_opt[name]["getopt"].endswith(":"):
opt["-"+all_opt[name]["getopt"].rstrip(":")] = value
elif ((value == "1") or (value.lower() == "yes")):
opt["-"+all_opt[name]["getopt"]] = "1"
return opt
##
## This function checks input and answers if we want to have same answers
## in each of the fencing agents. It looks for possible errors and run
## password script to set a correct password
######
def check_input(device_opt, opt):
global all_opt
global common_opt
##
## Add options which are available for every fence agent
#####
device_opt.extend([x for x in common_opt if device_opt.count(x) == 0])
options = dict(opt)
options["device_opt"] = device_opt
## Set requirements that should be included in metadata
#####
if device_opt.count("login") and device_opt.count("no_login") == 0:
all_opt["login"]["required"] = "1"
else:
all_opt["login"]["required"] = "0"
## In special cases (show help, metadata or version) we don't need to check anything
#####
if options.has_key("-h") or options.has_key("-V") or (options.has_key("-o") and options["-o"].lower() == "metadata"):
return options;
## Set default values
#####
for opt in device_opt:
if all_opt[opt].has_key("default"):
getopt = "-" + all_opt[opt]["getopt"].rstrip(":")
if 0 == options.has_key(getopt):
options[getopt] = all_opt[opt]["default"]
options["-o"]=options["-o"].lower()
if options.has_key("-v"):
options["log"] = LOG_MODE_VERBOSE
else:
options["log"] = LOG_MODE_QUIET
if 0 == device_opt.count("io_fencing"):
if 0 == ["on", "off", "reboot", "status", "list", "monitor"].count(options["-o"].lower()):
fail_usage("Failed: Unrecognised action '" + options["-o"] + "'")
else:
if 0 == ["enable", "disable", "status", "list", "monitor"].count(options["-o"].lower()):
fail_usage("Failed: Unrecognised action '" + options["-o"] + "'")
if (0 == options.has_key("-l")) and device_opt.count("login") and (device_opt.count("no_login") == 0):
fail_usage("Failed: You have to set login name")
if 0 == options.has_key("-a") and 0 == options.has_key("-s"):
fail_usage("Failed: You have to enter fence address")
if (0 == ["list", "monitor"].count(options["-o"].lower())) and device_opt.count("vm_name") and device_opt.count("uuid"):
if 0 == options.has_key("-n") and 0 == options.has_key("-U"):
fail_usage("Failed: You must specify either UUID or VM name")
if (device_opt.count("no_password") == 0):
if 0 == device_opt.count("identity_file"):
if 0 == (options.has_key("-p") or options.has_key("-S")):
fail_usage("Failed: You have to enter password or password script")
else:
if 0 == (options.has_key("-p") or options.has_key("-S") or options.has_key("-k")):
fail_usage("Failed: You have to enter password, password script or identity file")
if 0 == options.has_key("-x") and 1 == options.has_key("-k"):
fail_usage("Failed: You have to use identity file together with ssh connection (-x)")
if 1 == options.has_key("-k"):
if 0 == os.path.isfile(options["-k"]):
fail_usage("Failed: Identity file " + options["-k"] + " does not exist")
if (0 == ["list", "monitor"].count(options["-o"].lower())) and (0 == options.has_key("-n")) and (device_opt.count("port")):
fail_usage("Failed: You have to enter plug number")
if options.has_key("-S"):
options["-p"] = os.popen(options["-S"]).read().rstrip()
if options.has_key("-D"):
try:
options["debug_fh"] = file (options["-D"], "w")
except IOError:
fail_usage("Failed: Unable to create file "+options["-D"])
if options.has_key("-v") and options.has_key("debug_fh") == 0:
options["debug_fh"] = sys.stderr
if options.has_key("-R"):
options["-P"] = os.popen(options["-R"]).read().rstrip()
if options.has_key("-u") == False:
if options.has_key("-x"):
options["-u"] = 22
elif options.has_key("-z"):
options["-u"] = 443
elif device_opt.count("web"):
options["-u"] = 80
else:
options["-u"] = 23
return options
def wait_power_status(tn, options, get_power_fn):
for dummy in xrange(int(options["-g"])):
if get_power_fn(tn, options) != options["-o"]:
time.sleep(1)
else:
return 1
return 0
def show_docs(options, docs = None):
device_opt = options["device_opt"]
if docs == None:
docs = { }
docs["shortdesc"] = "Fence agent"
docs["longdesc"] = ""
## Process special options (and exit)
#####
if options.has_key("-h"):
usage(device_opt)
sys.exit(0)
if options.has_key("-o") and options["-o"].lower() == "metadata":
metadata(device_opt, options, docs)
sys.exit(0)
if options.has_key("-V"):
print __main__.RELEASE_VERSION, __main__.BUILD_DATE
print __main__.REDHAT_COPYRIGHT
sys.exit(0)
def fence_action(tn, options, set_power_fn, get_power_fn, get_outlet_list = None):
result = 0
## Process options that manipulate fencing device
#####
if (options["-o"] == "list") and (0 == options["device_opt"].count("port")) and (0 == options["device_opt"].count("partition")) and (0 == options["device_opt"].count("uuid")):
print "N/A"
return
elif (options["-o"] == "list" and get_outlet_list == None):
## @todo: exception?
## This is just temporal solution, we will remove default value
## None as soon as all existing agent will support this operation
print "NOTICE: List option is not working on this device yet"
return
elif (options["-o"] == "list") or ((options["-o"] == "monitor") and 1 == options["device_opt"].count("port")):
outlets = get_outlet_list(tn, options)
## keys can be numbers (port numbers) or strings (names of VM)
for o in outlets.keys():
(alias, status) = outlets[o]
if options["-o"] != "monitor":
print o + options["-C"] + alias
return
if options["-o"] in ["off", "reboot"]:
time.sleep(int(options["-f"]))
status = get_power_fn(tn, options)
if status != "on" and status != "off":
fail(EC_STATUS)
if options["-o"] == "enable":
options["-o"] = "on"
if options["-o"] == "disable":
options["-o"] = "off"
if options["-o"] == "on":
if status == "on":
print "Success: Already ON"
else:
power_on = False
for i in range(1,1 + int(options["-F"])):
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn):
power_on = True
break
if power_on:
print "Success: Powered ON"
else:
fail(EC_WAITING_ON)
elif options["-o"] == "off":
if status == "off":
print "Success: Already OFF"
else:
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn):
print "Success: Powered OFF"
else:
fail(EC_WAITING_OFF)
elif options["-o"] == "reboot":
if status != "off":
options["-o"] = "off"
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn) == 0:
fail(EC_WAITING_OFF)
options["-o"] = "on"
power_on = False
for i in range(1,1 + int(options["-F"])):
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn) == 1:
power_on = True
break
if power_on == False:
# this should not fail as not was fenced succesfully
sys.stderr.write('Timed out waiting to power ON\n')
print "Success: Rebooted"
elif options["-o"] == "status":
print "Status: " + status.upper()
if status.upper() == "OFF":
result = 2
elif options["-o"] == "monitor":
1
return result
def fence_login(options):
force_ipvx=""
if (options.has_key("-6")):
force_ipvx="-6 "
if (options.has_key("-4")):
force_ipvx="-4 "
if (options["device_opt"].count("login_eol_lf")):
login_eol = "\n"
else:
login_eol = "\r\n"
try:
re_login = re.compile("(login\s*: )|(Login Name: )|(username: )|(User Name :)", re.IGNORECASE)
re_pass = re.compile("password", re.IGNORECASE)
if options.has_key("-z"):
command = '%s %s %s %s' % (SSL_PATH, force_ipvx, options["-a"], options["-u"])
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
## SSL telnet is part of the fencing package
sys.stderr.write(str(ex) + "\n")
sys.exit(EC_GENERIC_ERROR)
elif options.has_key("-x") and 0 == options.has_key("-k"):
command = '%s %s %s@%s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-u"])
if options.has_key("ssh_options"):
command += ' ' + options["ssh_options"]
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
if options.has_key("telnet_over_ssh"):
#This is for stupid ssh servers (like ALOM) which behave more like telnet (ignore name and display login prompt)
result = conn.log_expect(options, [ re_login, "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"]))
if result == 1:
conn.sendline("yes") # Host identity confirm
conn.log_expect(options, re_login, int(options["-y"]))
conn.sendline(options["-l"])
conn.log_expect(options, re_pass, int(options["-y"]))
else:
result = conn.log_expect(options, [ "ssword:", "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"]))
if result == 1:
conn.sendline("yes")
conn.log_expect(options, "ssword:", int(options["-y"]))
conn.sendline(options["-p"])
conn.log_expect(options, options["-c"], int(options["-y"]))
elif options.has_key("-x") and 1 == options.has_key("-k"):
command = '%s %s %s@%s -i %s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-k"], options["-u"])
if options.has_key("ssh_options"):
command += ' ' + options["ssh_options"]
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
result = conn.log_expect(options, [ options["-c"], "Are you sure you want to continue connecting (yes/no)?", "Enter passphrase for key '"+options["-k"]+"':" ], int(options["-y"]))
if result == 1:
conn.sendline("yes")
conn.log_expect(options, [ options["-c"], "Enter passphrase for key '"+options["-k"]+"':"] , int(options["-y"]))
if result != 0:
if options.has_key("-p"):
conn.sendline(options["-p"])
conn.log_expect(options, options["-c"], int(options["-y"]))
else:
fail_usage("Failed: You have to enter passphrase (-p) for identity file")
else:
try:
conn = fspawn(TELNET_PATH)
conn.send("set binary\n")
conn.send("open %s -%s\n"%(options["-a"], options["-u"]))
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
conn.log_expect(options, re_login, int(options["-y"]))
conn.send(options["-l"] + login_eol)
conn.log_expect(options, re_pass, int(options["-Y"]))
conn.send(options["-p"] + login_eol)
conn.log_expect(options, options["-c"], int(options["-Y"]))
except pexpect.EOF:
fail(EC_LOGIN_DENIED)
except pexpect.TIMEOUT:
fail(EC_LOGIN_DENIED)
return conn
| Python |
#!/usr/bin/env python
# Copyright 2011 Matt Clark
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
import sys, string, getopt
import XenAPI
def usage():
print "Usage: fence_cxs [-hv] [-a <action>] -l <login username> -p <login password> -s <session url> [-u <UUID>]"
print "Where:-"
print " -a : Specifies the action to perfom. Can be any of \"on|off|reboot|status\". Defaults to \"status\"."
print " -h : Print this help message."
print " -l : The username for the XenServer host."
print " -p : The password for the XenServer host."
print " -s : The URL of the web interface on the XenServer host."
print " -U : The UUID of the virtual machine to fence or query. Defaults to the empty string which will return"
print " the status of all hosts when action is set to \"status\". If the action is set to \"on|off|reboot\""
print " then the UUID must be specified."
# Process command line options and populate the config array
def process_opts():
config = {
"action" : "status",
"session_url" : "",
"session_user" : "",
"session_pass" : "",
"uuid" : "",
"verbose" : False
}
# If we have at least one argument then we want to parse the command line using getopts
if len(sys.argv) > 1:
try:
opts, args = getopt.getopt(sys.argv[1:], "a:hl:s:p:U:v", ["help", "verbose", "action=", "session-url=", "login-name=", "password=", "uuid="])
except getopt.GetoptError, err:
# We got an unrecognised option, so print he help message and exit
print str(err)
usage()
sys.exit(1)
for opt, arg in opts:
if opt in ("-v", "--verbose"):
config["verbose"] = True
elif opt in ("-a", "--action"):
config["action"] = clean_action(arg)
elif opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-s", "--session-url"):
config["session_url"] = arg
elif opt in ("-l", "--login-name"):
config["session_user"] = arg
elif opt in ("-p", "--password"):
config["session_pass"] = arg
elif opt in ("-U", "--uuid"):
config["uuid"] = arg.lower()
else:
assert False, "unhandled option"
# Otherwise process stdin for parameters. This is to handle the Red Hat clustering
# mechanism where by fenced passes in name/value pairs instead of using command line
# options.
else:
for line in sys.stdin.readlines():
line = line.strip()
if ((line.startswith("#")) or (len(line) == 0)):
continue
(name, value) = (line + "=").split("=", 1)
value = value[:-1]
name = clean_param_name(name)
if name == "action":
value = clean_action(value)
if name in config:
config[name] = value
else:
sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n")
if( config["session_url"] == "" or config["session_user"] == "" or config["session_pass"] == "" ):
print "You must specify the session url, username and password.";
usage();
sys.exit(2);
return config
# why, well just to be nice. Given an action will return the corresponding
# value that the rest of the script uses.
def clean_action(action):
if action.lower() in ("on", "poweron", "powerup"):
return "on"
elif action.lower() in ("off", "poweroff", "powerdown"):
return "off"
elif action.lower() in ("reboot", "reset", "restart"):
return "reboot"
elif action.lower() in ("status", "powerstatus", "list"):
return "status"
return ""
# why, well just to be nice. Given a parameter will return the corresponding
# value that the rest of the script uses.
def clean_param_name(name):
if name.lower() in ("action", "operation", "op"):
return "action"
elif name.lower() in ("session_user", "login", "login-name", "login_name", "user", "username", "session-user"):
return "session_user"
elif name.lower() in ("session_pass", "pass", "passwd", "password", "session-pass"):
return "session_pass"
elif name.lower() in ("session_url", "url", "session-url"):
return "session_url"
return ""
# Print the power status of a VM. If no UUID is given, then all VM's are queried
def get_power_status(session, uuid = ""):
try:
# If the UUID hasn't been set, then output the status of all
# valid virtual machines.
if( uuid == "" ):
vms = session.xenapi.VM.get_all()
else:
vms = [session.xenapi.VM.get_by_uuid(uuid)]
for vm in vms:
record = session.xenapi.VM.get_record(vm);
# We only want to print out the status for actual virtual machines. The above get_all function
# returns any templates and also the control domain. This is one of the reasons the process
# takes such a long time to list all VM's. Hopefully there is a way to filter this in the
# request packet in the future.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
def set_power_status(session, uuid, action):
try:
vm = session.xenapi.VM.get_by_uuid(uuid)
record = session.xenapi.VM.get_record(vm);
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
session.xenapi.VM.hard_reboot(vm)
except Exception, exn:
print str(exn);
def main():
config = process_opts();
session = session_start(config["session_url"]);
session_login(session, config["session_user"], config["session_pass"]);
if( config["action"] == "status" ):
get_power_status(session, config["uuid"])
else:
if( config["verbose"] ):
print "Power status before action"
get_power_status(session, config["uuid"])
set_power_status(session, config["uuid"], config["action"])
if( config["verbose"] ):
print "Power status after action"
get_power_status(session, config["uuid"])
# Function to initiate the session with the XenServer system
def session_start(url):
try:
session = XenAPI.Session(url);
except Exception, exn:
print str(exn);
sys.exit(3);
return session;
def session_login(session, username, password):
try:
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
sys.exit(3);
if __name__ == "__main__":
main()
# vim:set ts=4 sw=4
| Python |
#!/usr/bin/env python
# Copyright 2011 Matt Clark
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
import sys, string, getopt
import XenAPI
def usage():
print "Usage: fence_cxs [-hv] [-a <action>] -l <login username> -p <login password> -s <session url> [-u <UUID>]"
print "Where:-"
print " -a : Specifies the action to perfom. Can be any of \"on|off|reboot|status\". Defaults to \"status\"."
print " -h : Print this help message."
print " -l : The username for the XenServer host."
print " -p : The password for the XenServer host."
print " -s : The URL of the web interface on the XenServer host."
print " -U : The UUID of the virtual machine to fence or query. Defaults to the empty string which will return"
print " the status of all hosts when action is set to \"status\". If the action is set to \"on|off|reboot\""
print " then the UUID must be specified."
# Process command line options and populate the config array
def process_opts():
config = {
"action" : "status",
"session_url" : "",
"session_user" : "",
"session_pass" : "",
"uuid" : "",
"verbose" : False
}
# If we have at least one argument then we want to parse the command line using getopts
if len(sys.argv) > 1:
try:
opts, args = getopt.getopt(sys.argv[1:], "a:hl:s:p:U:v", ["help", "verbose", "action=", "session-url=", "login-name=", "password=", "uuid="])
except getopt.GetoptError, err:
# We got an unrecognised option, so print he help message and exit
print str(err)
usage()
sys.exit(1)
for opt, arg in opts:
if opt in ("-v", "--verbose"):
config["verbose"] = True
elif opt in ("-a", "--action"):
config["action"] = clean_action(arg)
elif opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-s", "--session-url"):
config["session_url"] = arg
elif opt in ("-l", "--login-name"):
config["session_user"] = arg
elif opt in ("-p", "--password"):
config["session_pass"] = arg
elif opt in ("-U", "--uuid"):
config["uuid"] = arg.lower()
else:
assert False, "unhandled option"
# Otherwise process stdin for parameters. This is to handle the Red Hat clustering
# mechanism where by fenced passes in name/value pairs instead of using command line
# options.
else:
for line in sys.stdin.readlines():
line = line.strip()
if ((line.startswith("#")) or (len(line) == 0)):
continue
(name, value) = (line + "=").split("=", 1)
value = value[:-1]
name = clean_param_name(name)
if name == "action":
value = clean_action(value)
if name in config:
config[name] = value
else:
sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n")
if( config["session_url"] == "" or config["session_user"] == "" or config["session_pass"] == "" ):
print "You must specify the session url, username and password.";
usage();
sys.exit(2);
return config
# why, well just to be nice. Given an action will return the corresponding
# value that the rest of the script uses.
def clean_action(action):
if action.lower() in ("on", "poweron", "powerup"):
return "on"
elif action.lower() in ("off", "poweroff", "powerdown"):
return "off"
elif action.lower() in ("reboot", "reset", "restart"):
return "reboot"
elif action.lower() in ("status", "powerstatus", "list"):
return "status"
return ""
# why, well just to be nice. Given a parameter will return the corresponding
# value that the rest of the script uses.
def clean_param_name(name):
if name.lower() in ("action", "operation", "op"):
return "action"
elif name.lower() in ("session_user", "login", "login-name", "login_name", "user", "username", "session-user"):
return "session_user"
elif name.lower() in ("session_pass", "pass", "passwd", "password", "session-pass"):
return "session_pass"
elif name.lower() in ("session_url", "url", "session-url"):
return "session_url"
return ""
# Print the power status of a VM. If no UUID is given, then all VM's are queried
def get_power_status(session, uuid = ""):
try:
# If the UUID hasn't been set, then output the status of all
# valid virtual machines.
if( uuid == "" ):
vms = session.xenapi.VM.get_all()
else:
vms = [session.xenapi.VM.get_by_uuid(uuid)]
for vm in vms:
record = session.xenapi.VM.get_record(vm);
# We only want to print out the status for actual virtual machines. The above get_all function
# returns any templates and also the control domain. This is one of the reasons the process
# takes such a long time to list all VM's. Hopefully there is a way to filter this in the
# request packet in the future.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
def set_power_status(session, uuid, action):
try:
vm = session.xenapi.VM.get_by_uuid(uuid)
record = session.xenapi.VM.get_record(vm);
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
session.xenapi.VM.hard_reboot(vm)
except Exception, exn:
print str(exn);
def main():
config = process_opts();
session = session_start(config["session_url"]);
session_login(session, config["session_user"], config["session_pass"]);
if( config["action"] == "status" ):
get_power_status(session, config["uuid"])
else:
if( config["verbose"] ):
print "Power status before action"
get_power_status(session, config["uuid"])
set_power_status(session, config["uuid"], config["action"])
if( config["verbose"] ):
print "Power status after action"
get_power_status(session, config["uuid"])
# Function to initiate the session with the XenServer system
def session_start(url):
try:
session = XenAPI.Session(url);
except Exception, exn:
print str(exn);
sys.exit(3);
return session;
def session_login(session, username, password):
try:
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
sys.exit(3);
if __name__ == "__main__":
main()
# vim:set ts=4 sw=4
| Python |
#!/usr/bin/python
# It's only just begun...
# Current status: completely unusable, try the fence_cxs.py script for the moment. This Red
# Hat compatible version is just in its' infancy.
# Copyright 2011 Matt Clark
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
from fencing import *
import XenAPI
EC_BAD_SESSION = 1
# Find the status of the port given in the -U flag of options.
def get_power_fn(session, options):
#uuid = options["-U"].lower()
try:
# Get a reference to the vm specified in the UUID or vm_name parameter
vm = return_vm_reference(session, options)
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm);
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
status = record["power_state"]
print "UUID:", record["uuid"], "NAME:", record["name_label"], "POWER STATUS:", record["power_state"]
# Note that the VM can be in the following states (from the XenAPI document)
# Halted: VM is offline and not using any resources.
# Paused: All resources have been allocated but the VM itself is paused and its vCPUs are not running
# Running: Running
# Paused: VM state has been saved to disk and it is nolonger running. Note that disks remain in-Use while
# We want to make sure that we only return the status "off" if the machine is actually halted as the status
# is checked before a fencing action. Only when the machine is Halted is it not consuming resources which
# may include whatever you are trying to protect with this fencing action.
return (status=="Halted" and "off" or "on")
except Exception, exn:
print str(exn)
return "Error"
# Set the state of the port given in the -U flag of options.
def set_power_fn(session, options):
uuid = options["-U"].lower()
action = options["-o"].lower()
try:
# Get a reference to the vm specified in the UUID or vm_name parameter
vm = return_vm_reference(session, options)
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm)
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
# Start the VM
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
# Force shutdown the VM
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
# Force reboot the VM
session.xenapi.VM.hard_reboot(vm)
except Exception, exn:
print str(exn);
# Function to populate an array of virtual machines and their status
def get_outlet_list(session, options):
result = {}
try:
# Return an array of all the VM's on the host
vms = session.xenapi.VM.get_all()
for vm in vms:
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm);
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
uuid = record["uuid"]
status = record["power_state"]
result[uuid] = (name, status)
print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
return result
# Function to initiate the XenServer session via the XenAPI library.
def connect_and_login(options):
url = options["-s"]
username = options["-l"]
password = options["-p"]
try:
# Create the XML RPC session to the specified URL.
session = XenAPI.Session(url);
# Login using the supplied credentials.
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
# http://sources.redhat.com/cluster/wiki/FenceAgentAPI says that for no connectivity
# the exit value should be 1. It doesn't say anything about failed logins, so
# until I hear otherwise it is best to keep this exit the same to make sure that
# anything calling this script (that uses the same information in the web page
# above) knows that this is an error condition, not a msg signifying a down port.
sys.exit(EC_BAD_SESSION);
return session;
# return a reference to the VM by either using the UUID or the vm_name. If the UUID is set then
# this is tried first as this is the only properly unique identifier.
# Exceptions are not handled in this function, code that calls this must be ready to handle them.
def return_vm_reference(session, options):
# Case where the UUID has been specified
if options.has_key("-U"):
uuid = options["-U"].lower()
return session.xenapi.VM.get_by_uuid(uuid)
# Case where the vm_name has been specified
if options.has_key("-n"):
vm_name = options["-n"]
vm_arr = session.xenapi.VM.get_by_name_label(vm_name)
# Need to make sure that we only have one result as the vm_name may
# not be unique. Average case, so do it first.
if len(vm_arr) == 1:
return vm_arr[0]
else:
# TODO: Need to either fail usage or raise exception
# at least say something like none or multiple vms found
# with that name.
# if len(vm_arr) == 0:
# no vm's found
# else:
# multiple vms found with the same name, use uuid instead
return None
def main():
device_opt = [ "help", "version", "agent", "quiet", "verbose", "debug", "action",
"login", "passwd", "passwd_script", "vm_name", "test", "separator",
"no_login", "no_password", "power_timeout", "shell_timeout",
"login_timeout", "power_wait", "session_url", "uuid" ]
atexit.register(atexit_handler)
options=process_input(device_opt)
options = check_input(device_opt, options)
docs = { }
docs["shortdesc"] = "Fence agent for Citrix XenServer"
docs["longdesc"] = "fence_cxs_redhat"
show_docs(options, docs)
xenSession = connect_and_login(options)
# Operate the fencing device
result = fence_action(xenSession, options, set_power_fn, get_power_fn, get_outlet_list)
sys.exit(result)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
import sys, getopt, time, os
import pexpect, re
import telnetlib
import atexit
import __main__
## do not add code here.
#BEGIN_VERSION_GENERATION
RELEASE_VERSION="3.0.17"
BUILD_DATE="(built Thu Oct 7 07:06:21 UTC 2010)"
REDHAT_COPYRIGHT="Copyright (C) Red Hat, Inc. 2004-2010 All rights reserved."
#END_VERSION_GENERATION
LOG_MODE_VERBOSE = 100
LOG_MODE_QUIET = 0
EC_GENERIC_ERROR = 1
EC_BAD_ARGS = 2
EC_LOGIN_DENIED = 3
EC_CONNECTION_LOST = 4
EC_TIMED_OUT = 5
EC_WAITING_ON = 6
EC_WAITING_OFF = 7
EC_STATUS = 8
EC_STATUS_HMC = 9
TELNET_PATH = "/usr/bin/telnet"
SSH_PATH = "/usr/bin/ssh"
SSL_PATH = "/usr/sbin/fence_nss_wrapper"
all_opt = {
"help" : {
"getopt" : "h",
"longopt" : "help",
"help" : "-h, --help Display this help and exit",
"required" : "0",
"shortdesc" : "Display help and exit",
"order" : 54 },
"version" : {
"getopt" : "V",
"longopt" : "version",
"help" : "-V, --version Output version information and exit",
"required" : "0",
"shortdesc" : "Display version information and exit",
"order" : 53 },
"quiet" : {
"getopt" : "q",
"help" : "",
"order" : 50 },
"verbose" : {
"getopt" : "v",
"longopt" : "verbose",
"help" : "-v, --verbose Verbose mode",
"required" : "0",
"shortdesc" : "Verbose mode",
"order" : 51 },
"debug" : {
"getopt" : "D:",
"longopt" : "debug-file",
"help" : "-D, --debug-file=<debugfile> Debugging to output file",
"required" : "0",
"shortdesc" : "Write debug information to given file",
"order" : 52 },
"delay" : {
"getopt" : "f:",
"longopt" : "delay",
"help" : "--delay <seconds> Wait X seconds before fencing is started",
"required" : "0",
"shortdesc" : "Wait X seconds before fencing is started",
"default" : "0",
"order" : 200 },
"agent" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"web" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"action" : {
"getopt" : "o:",
"longopt" : "action",
"help" : "-o, --action=<action> Action: status, reboot (default), off or on",
"required" : "1",
"shortdesc" : "Fencing Action",
"default" : "reboot",
"order" : 1 },
"io_fencing" : {
"getopt" : "o:",
"longopt" : "action",
"help" : "-o, --action=<action> Action: status, enable or disable",
"required" : "1",
"shortdesc" : "Fencing Action",
"default" : "disable",
"order" : 1 },
"ipaddr" : {
"getopt" : "a:",
"longopt" : "ip",
"help" : "-a, --ip=<ip> IP address or hostname of fencing device",
"required" : "1",
"shortdesc" : "IP Address or Hostname",
"order" : 1 },
"ipport" : {
"getopt" : "u:",
"longopt" : "ipport",
"help" : "-u, --ipport=<port> TCP port to use",
"required" : "0",
"shortdesc" : "TCP port to use for connection with device",
"order" : 1 },
"login" : {
"getopt" : "l:",
"longopt" : "username",
"help" : "-l, --username=<name> Login name",
"required" : "?",
"shortdesc" : "Login Name",
"order" : 1 },
"no_login" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"no_password" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"passwd" : {
"getopt" : "p:",
"longopt" : "password",
"help" : "-p, --password=<password> Login password or passphrase",
"required" : "0",
"shortdesc" : "Login password or passphrase",
"order" : 1 },
"passwd_script" : {
"getopt" : "S:",
"longopt" : "password-script=",
"help" : "-S, --password-script=<script> Script to run to retrieve password",
"required" : "0",
"shortdesc" : "Script to retrieve password",
"order" : 1 },
"identity_file" : {
"getopt" : "k:",
"longopt" : "identity-file",
"help" : "-k, --identity-file=<filename> Identity file (private key) for ssh ",
"required" : "0",
"shortdesc" : "Identity file for ssh",
"order" : 1 },
"module_name" : {
"getopt" : "m:",
"longopt" : "module-name",
"help" : "-m, --module-name=<module> DRAC/MC module name",
"required" : "0",
"shortdesc" : "DRAC/MC module name",
"order" : 1 },
"drac_version" : {
"getopt" : "d:",
"longopt" : "drac-version",
"help" : "-d, --drac-version=<version> Force DRAC version to use",
"required" : "0",
"shortdesc" : "Force DRAC version to use",
"order" : 1 },
"hmc_version" : {
"getopt" : "H:",
"longopt" : "hmc-version",
"help" : "-H, --hmc-version=<version> Force HMC version to use: 3, 4 (default)",
"required" : "0",
"shortdesc" : "Force HMC version to use (3 or 4)",
"default" : "4",
"order" : 1 },
"ribcl" : {
"getopt" : "r:",
"longopt" : "ribcl-version",
"help" : "-r, --ribcl-version=<version> Force ribcl version to use",
"required" : "0",
"shortdesc" : "Force ribcl version to use",
"order" : 1 },
"login_eol_lf" : {
"getopt" : "",
"help" : "",
"order" : 1
},
"cmd_prompt" : {
"getopt" : "c:",
"longopt" : "command-prompt",
"help" : "-c, --command-prompt=<prompt> Force command prompt",
"shortdesc" : "Force command prompt",
"required" : "0",
"order" : 1 },
"secure" : {
"getopt" : "x",
"longopt" : "ssh",
"help" : "-x, --ssh Use ssh connection",
"shortdesc" : "SSH connection",
"required" : "0",
"order" : 1 },
"ssl" : {
"getopt" : "z",
"longopt" : "ssl",
"help" : "-z, --ssl Use ssl connection",
"required" : "0",
"shortdesc" : "SSL connection",
"order" : 1 },
"port" : {
"getopt" : "n:",
"longopt" : "plug",
"help" : "-n, --plug=<id> Physical plug number on device or\n" +
" name of virtual machine",
"required" : "1",
"shortdesc" : "Physical plug number or name of virtual machine",
"order" : 1 },
"switch" : {
"getopt" : "s:",
"longopt" : "switch",
"help" : "-s, --switch=<id> Physical switch number on device",
"required" : "0",
"shortdesc" : "Physical switch number on device",
"order" : 1 },
"partition" : {
"getopt" : "n:",
"help" : "-n <id> Name of the partition",
"required" : "0",
"shortdesc" : "Partition name",
"order" : 1 },
"managed" : {
"getopt" : "s:",
"help" : "-s <id> Name of the managed system",
"required" : "0",
"shortdesc" : "Managed system name",
"order" : 1 },
"test" : {
"getopt" : "T",
"help" : "",
"order" : 1,
"obsolete" : "use -o status instead" },
"exec" : {
"getopt" : "e:",
"longopt" : "exec",
"help" : "-e, --exec=<command> Command to execute",
"required" : "0",
"shortdesc" : "Command to execute",
"order" : 1 },
"vmware_type" : {
"getopt" : "d:",
"longopt" : "vmware_type",
"help" : "-d, --vmware_type=<type> Type of VMware to connect",
"required" : "0",
"shortdesc" : "Type of VMware to connect",
"order" : 1 },
"vmware_datacenter" : {
"getopt" : "s:",
"longopt" : "vmware-datacenter",
"help" : "-s, --vmware-datacenter=<dc> VMWare datacenter filter",
"required" : "0",
"shortdesc" : "Show only machines in specified datacenter",
"order" : 2 },
"snmp_version" : {
"getopt" : "d:",
"longopt" : "snmp-version",
"help" : "-d, --snmp-version=<ver> Specifies SNMP version to use",
"required" : "0",
"shortdesc" : "Specifies SNMP version to use (1,2c,3)",
"order" : 1 },
"community" : {
"getopt" : "c:",
"longopt" : "community",
"help" : "-c, --community=<community> Set the community string",
"required" : "0",
"shortdesc" : "Set the community string",
"order" : 1},
"snmp_auth_prot" : {
"getopt" : "b:",
"longopt" : "snmp-auth-prot",
"help" : "-b, --snmp-auth-prot=<prot> Set authentication protocol (MD5|SHA)",
"required" : "0",
"shortdesc" : "Set authentication protocol (MD5|SHA)",
"order" : 1},
"snmp_sec_level" : {
"getopt" : "E:",
"longopt" : "snmp-sec-level",
"help" : "-E, --snmp-sec-level=<level> Set security level\n"+
" (noAuthNoPriv|authNoPriv|authPriv)",
"required" : "0",
"shortdesc" : "Set security level (noAuthNoPriv|authNoPriv|authPriv)",
"order" : 1},
"snmp_priv_prot" : {
"getopt" : "B:",
"longopt" : "snmp-priv-prot",
"help" : "-B, --snmp-priv-prot=<prot> Set privacy protocol (DES|AES)",
"required" : "0",
"shortdesc" : "Set privacy protocol (DES|AES)",
"order" : 1},
"snmp_priv_passwd" : {
"getopt" : "P:",
"longopt" : "snmp-priv-passwd",
"help" : "-P, --snmp-priv-passwd=<pass> Set privacy protocol password",
"required" : "0",
"shortdesc" : "Set privacy protocol password",
"order" : 1},
"snmp_priv_passwd_script" : {
"getopt" : "R:",
"longopt" : "snmp-priv-passwd-script",
"help" : "-R, --snmp-priv-passwd-script Script to run to retrieve privacy password",
"required" : "0",
"shortdesc" : "Script to run to retrieve privacy password",
"order" : 1},
"inet4_only" : {
"getopt" : "4",
"longopt" : "inet4-only",
"help" : "-4, --inet4-only Forces agent to use IPv4 addresses only",
"required" : "0",
"shortdesc" : "Forces agent to use IPv4 addresses only",
"order" : 1 },
"inet6_only" : {
"getopt" : "6",
"longopt" : "inet6-only",
"help" : "-6, --inet6-only Forces agent to use IPv6 addresses only",
"required" : "0",
"shortdesc" : "Forces agent to use IPv6 addresses only",
"order" : 1 },
"udpport" : {
"getopt" : "u:",
"longopt" : "udpport",
"help" : "-u, --udpport UDP/TCP port to use",
"required" : "0",
"shortdesc" : "UDP/TCP port to use for connection with device",
"order" : 1},
"separator" : {
"getopt" : "C:",
"longopt" : "separator",
"help" : "-C, --separator=<char> Separator for CSV created by 'list' operation",
"default" : ",",
"required" : "0",
"shortdesc" : "Separator for CSV created by operation list",
"order" : 100 },
"login_timeout" : {
"getopt" : "y:",
"longopt" : "login-timeout",
"help" : "--login-timeout <seconds> Wait X seconds for cmd prompt after login",
"default" : "5",
"required" : "0",
"shortdesc" : "Wait X seconds for cmd prompt after login",
"order" : 200 },
"shell_timeout" : {
"getopt" : "Y:",
"longopt" : "shell-timeout",
"help" : "--shell-timeout <seconds> Wait X seconds for cmd prompt after issuing command",
"default" : "3",
"required" : "0",
"shortdesc" : "Wait X seconds for cmd prompt after issuing command",
"order" : 200 },
"power_timeout" : {
"getopt" : "g:",
"longopt" : "power-timeout",
"help" : "--power-timeout <seconds> Test X seconds for status change after ON/OFF",
"default" : "20",
"required" : "0",
"shortdesc" : "Test X seconds for status change after ON/OFF",
"order" : 200 },
"power_wait" : {
"getopt" : "G:",
"longopt" : "power-wait",
"help" : "--power-wait <seconds> Wait X seconds after issuing ON/OFF",
"default" : "0",
"required" : "0",
"shortdesc" : "Wait X seconds after issuing ON/OFF",
"order" : 200 },
"missing_as_off" : {
"getopt" : "M",
"longopt" : "missing-as-off",
"help" : "--missing-as-off Missing port returns OFF instead of failure",
"required" : "0",
"shortdesc" : "Missing port returns OFF instead of failure",
"order" : 200 },
"retry_on" : {
"getopt" : "F:",
"longopt" : "retry-on",
"help" : "--retry-on <attempts> Count of attempts to retry power on",
"default" : "1",
"required" : "0",
"shortdesc" : "Count of attempts to retry power on",
"order" : 200 },
"session_url" : {
"getopt" : "s:",
"longopt" : "session-url",
"help" : "-s, --session-url URL to connect to XenServer on.",
"required" : "1",
"shortdesc" : "The URL of the XenServer host.",
"order" : 1},
"vm_name" : {
"getopt" : "n:",
"longopt" : "vm-name",
"help" : "-n, --vm-name Name of the VM to fence.",
"required" : "0",
"shortdesc" : "The name of the virual machine to fence.",
"order" : 1},
"uuid" : {
"getopt" : "U:",
"longopt" : "uuid",
"help" : "-U, --uuid UUID of the VM to fence.",
"required" : "0",
"shortdesc" : "The UUID of the virtual machine to fence.",
"order" : 1}
}
common_opt = [ "retry_on", "delay" ]
class fspawn(pexpect.spawn):
def log_expect(self, options, pattern, timeout):
result = self.expect(pattern, timeout)
if options["log"] >= LOG_MODE_VERBOSE:
options["debug_fh"].write(self.before + self.after)
return result
def atexit_handler():
try:
sys.stdout.close()
os.close(1)
except IOError:
sys.stderr.write("%s failed to close standard output\n"%(sys.argv[0]))
sys.exit(EC_GENERIC_ERROR)
def version(command, release, build_date, copyright_notice):
print command, " ", release, " ", build_date
if len(copyright_notice) > 0:
print copyright_notice
def fail_usage(message = ""):
if len(message) > 0:
sys.stderr.write(message+"\n")
sys.stderr.write("Please use '-h' for usage\n")
sys.exit(EC_GENERIC_ERROR)
def fail(error_code):
message = {
EC_LOGIN_DENIED : "Unable to connect/login to fencing device",
EC_CONNECTION_LOST : "Connection lost",
EC_TIMED_OUT : "Connection timed out",
EC_WAITING_ON : "Failed: Timed out waiting to power ON",
EC_WAITING_OFF : "Failed: Timed out waiting to power OFF",
EC_STATUS : "Failed: Unable to obtain correct plug status or plug is not available",
EC_STATUS_HMC : "Failed: Either unable to obtaion correct plug status, partition is not available or incorrect HMC version used"
}[error_code] + "\n"
sys.stderr.write(message)
sys.exit(EC_GENERIC_ERROR)
def usage(avail_opt):
global all_opt
print "Usage:"
print "\t" + os.path.basename(sys.argv[0]) + " [options]"
print "Options:"
sorted_list = [ (key, all_opt[key]) for key in avail_opt ]
sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"]))
for key, value in sorted_list:
if len(value["help"]) != 0:
print " " + value["help"]
def metadata(avail_opt, options, docs):
global all_opt
sorted_list = [ (key, all_opt[key]) for key in avail_opt ]
sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"]))
print "<?xml version=\"1.0\" ?>"
print "<resource-agent name=\"" + os.path.basename(sys.argv[0]) + "\" shortdesc=\"" + docs["shortdesc"] + "\" >"
print "<longdesc>" + docs["longdesc"] + "</longdesc>"
if docs.has_key("vendorurl"):
print "<vendor-url>" + docs["vendorurl"] + "</vendor-url>"
print "<parameters>"
for option, value in sorted_list:
if all_opt[option].has_key("shortdesc"):
print "\t<parameter name=\"" + option + "\" unique=\"1\" required=\"" + all_opt[option]["required"] + "\">"
default = ""
if all_opt[option].has_key("default"):
default = "default=\""+str(all_opt[option]["default"])+"\""
elif options.has_key("-" + all_opt[option]["getopt"][:-1]):
if options["-" + all_opt[option]["getopt"][:-1]]:
try:
default = "default=\"" + options["-" + all_opt[option]["getopt"][:-1]] + "\""
except TypeError:
## @todo/@note: Currently there is no clean way how to handle lists
## we can create a string from it but we can't set it on command line
default = "default=\"" + str(options["-" + all_opt[option]["getopt"][:-1]]) +"\""
elif options.has_key("-" + all_opt[option]["getopt"]):
default = "default=\"true\" "
mixed = all_opt[option]["help"]
## split it between option and help text
res = re.compile("^(.*--\S+)\s+", re.IGNORECASE | re.S).search(mixed)
if (None != res):
mixed = res.group(1)
mixed = mixed.replace("<", "<").replace(">", ">")
print "\t\t<getopt mixed=\"" + mixed + "\" />"
if all_opt[option]["getopt"].count(":") > 0:
print "\t\t<content type=\"string\" "+default+" />"
else:
print "\t\t<content type=\"boolean\" "+default+" />"
print "\t\t<shortdesc lang=\"en\">" + all_opt[option]["shortdesc"] + "</shortdesc>"
print "\t</parameter>"
print "</parameters>"
print "<actions>"
print "\t<action name=\"on\" />"
print "\t<action name=\"off\" />"
print "\t<action name=\"reboot\" />"
print "\t<action name=\"status\" />"
print "\t<action name=\"list\" />"
print "\t<action name=\"monitor\" />"
print "\t<action name=\"metadata\" />"
print "</actions>"
print "</resource-agent>"
def process_input(avail_opt):
global all_opt
global common_opt
##
## Add options which are available for every fence agent
#####
avail_opt.extend(common_opt)
##
## Set standard environment
#####
os.putenv("LANG", "C")
os.putenv("LC_ALL", "C")
##
## Prepare list of options for getopt
#####
getopt_string = ""
longopt_list = [ ]
for k in avail_opt:
if all_opt.has_key(k):
getopt_string += all_opt[k]["getopt"]
else:
fail_usage("Parse error: unknown option '"+k+"'")
if all_opt.has_key(k) and all_opt[k].has_key("longopt"):
if all_opt[k]["getopt"].endswith(":"):
longopt_list.append(all_opt[k]["longopt"] + "=")
else:
longopt_list.append(all_opt[k]["longopt"])
## Compatibility layer
if avail_opt.count("module_name") == 1:
getopt_string += "n:"
longopt_list.append("plug=")
##
## Read options from command line or standard input
#####
if len(sys.argv) > 1:
try:
opt, args = getopt.gnu_getopt(sys.argv[1:], getopt_string, longopt_list)
except getopt.GetoptError, error:
fail_usage("Parse error: " + error.msg)
## Transform longopt to short one which are used in fencing agents
#####
old_opt = opt
opt = { }
for o in dict(old_opt).keys():
if o.startswith("--"):
for x in all_opt.keys():
if all_opt[x].has_key("longopt") and "--" + all_opt[x]["longopt"] == o:
opt["-" + all_opt[x]["getopt"].rstrip(":")] = dict(old_opt)[o]
else:
opt[o] = dict(old_opt)[o]
## Compatibility Layer
#####
z = dict(opt)
if z.has_key("-T") == 1:
z["-o"] = "status"
if z.has_key("-n") == 1:
z["-m"] = z["-n"]
opt = z
##
#####
else:
opt = { }
name = ""
for line in sys.stdin.readlines():
line = line.strip()
if ((line.startswith("#")) or (len(line) == 0)):
continue
(name, value) = (line + "=").split("=", 1)
value = value[:-1]
## Compatibility Layer
######
if name == "blade":
name = "port"
elif name == "option":
name = "action"
elif name == "fm":
name = "port"
elif name == "hostname":
name = "ipaddr"
elif name == "modulename":
name = "module_name"
elif name == "action" and 1 == avail_opt.count("io_fencing"):
name = "io_fencing"
elif name == "port" and 1 == avail_opt.count("drac_version"):
name = "module_name"
##
######
if avail_opt.count(name) == 0:
sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n")
continue
if all_opt[name]["getopt"].endswith(":"):
opt["-"+all_opt[name]["getopt"].rstrip(":")] = value
elif ((value == "1") or (value.lower() == "yes")):
opt["-"+all_opt[name]["getopt"]] = "1"
return opt
##
## This function checks input and answers if we want to have same answers
## in each of the fencing agents. It looks for possible errors and run
## password script to set a correct password
######
def check_input(device_opt, opt):
global all_opt
global common_opt
##
## Add options which are available for every fence agent
#####
device_opt.extend([x for x in common_opt if device_opt.count(x) == 0])
options = dict(opt)
options["device_opt"] = device_opt
## Set requirements that should be included in metadata
#####
if device_opt.count("login") and device_opt.count("no_login") == 0:
all_opt["login"]["required"] = "1"
else:
all_opt["login"]["required"] = "0"
## In special cases (show help, metadata or version) we don't need to check anything
#####
if options.has_key("-h") or options.has_key("-V") or (options.has_key("-o") and options["-o"].lower() == "metadata"):
return options;
## Set default values
#####
for opt in device_opt:
if all_opt[opt].has_key("default"):
getopt = "-" + all_opt[opt]["getopt"].rstrip(":")
if 0 == options.has_key(getopt):
options[getopt] = all_opt[opt]["default"]
options["-o"]=options["-o"].lower()
if options.has_key("-v"):
options["log"] = LOG_MODE_VERBOSE
else:
options["log"] = LOG_MODE_QUIET
if 0 == device_opt.count("io_fencing"):
if 0 == ["on", "off", "reboot", "status", "list", "monitor"].count(options["-o"].lower()):
fail_usage("Failed: Unrecognised action '" + options["-o"] + "'")
else:
if 0 == ["enable", "disable", "status", "list", "monitor"].count(options["-o"].lower()):
fail_usage("Failed: Unrecognised action '" + options["-o"] + "'")
if (0 == options.has_key("-l")) and device_opt.count("login") and (device_opt.count("no_login") == 0):
fail_usage("Failed: You have to set login name")
if 0 == options.has_key("-a") and 0 == options.has_key("-s"):
fail_usage("Failed: You have to enter fence address")
if (0 == ["list", "monitor"].count(options["-o"].lower())) and device_opt.count("vm_name") and device_opt.count("uuid"):
if 0 == options.has_key("-n") and 0 == options.has_key("-U"):
fail_usage("Failed: You must specify either UUID or VM name")
if (device_opt.count("no_password") == 0):
if 0 == device_opt.count("identity_file"):
if 0 == (options.has_key("-p") or options.has_key("-S")):
fail_usage("Failed: You have to enter password or password script")
else:
if 0 == (options.has_key("-p") or options.has_key("-S") or options.has_key("-k")):
fail_usage("Failed: You have to enter password, password script or identity file")
if 0 == options.has_key("-x") and 1 == options.has_key("-k"):
fail_usage("Failed: You have to use identity file together with ssh connection (-x)")
if 1 == options.has_key("-k"):
if 0 == os.path.isfile(options["-k"]):
fail_usage("Failed: Identity file " + options["-k"] + " does not exist")
if (0 == ["list", "monitor"].count(options["-o"].lower())) and (0 == options.has_key("-n")) and (device_opt.count("port")):
fail_usage("Failed: You have to enter plug number")
if options.has_key("-S"):
options["-p"] = os.popen(options["-S"]).read().rstrip()
if options.has_key("-D"):
try:
options["debug_fh"] = file (options["-D"], "w")
except IOError:
fail_usage("Failed: Unable to create file "+options["-D"])
if options.has_key("-v") and options.has_key("debug_fh") == 0:
options["debug_fh"] = sys.stderr
if options.has_key("-R"):
options["-P"] = os.popen(options["-R"]).read().rstrip()
if options.has_key("-u") == False:
if options.has_key("-x"):
options["-u"] = 22
elif options.has_key("-z"):
options["-u"] = 443
elif device_opt.count("web"):
options["-u"] = 80
else:
options["-u"] = 23
return options
def wait_power_status(tn, options, get_power_fn):
for dummy in xrange(int(options["-g"])):
if get_power_fn(tn, options) != options["-o"]:
time.sleep(1)
else:
return 1
return 0
def show_docs(options, docs = None):
device_opt = options["device_opt"]
if docs == None:
docs = { }
docs["shortdesc"] = "Fence agent"
docs["longdesc"] = ""
## Process special options (and exit)
#####
if options.has_key("-h"):
usage(device_opt)
sys.exit(0)
if options.has_key("-o") and options["-o"].lower() == "metadata":
metadata(device_opt, options, docs)
sys.exit(0)
if options.has_key("-V"):
print __main__.RELEASE_VERSION, __main__.BUILD_DATE
print __main__.REDHAT_COPYRIGHT
sys.exit(0)
def fence_action(tn, options, set_power_fn, get_power_fn, get_outlet_list = None):
result = 0
## Process options that manipulate fencing device
#####
if (options["-o"] == "list") and (0 == options["device_opt"].count("port")) and (0 == options["device_opt"].count("partition")) and (0 == options["device_opt"].count("uuid")):
print "N/A"
return
elif (options["-o"] == "list" and get_outlet_list == None):
## @todo: exception?
## This is just temporal solution, we will remove default value
## None as soon as all existing agent will support this operation
print "NOTICE: List option is not working on this device yet"
return
elif (options["-o"] == "list") or ((options["-o"] == "monitor") and 1 == options["device_opt"].count("port")):
outlets = get_outlet_list(tn, options)
## keys can be numbers (port numbers) or strings (names of VM)
for o in outlets.keys():
(alias, status) = outlets[o]
if options["-o"] != "monitor":
print o + options["-C"] + alias
return
if options["-o"] in ["off", "reboot"]:
time.sleep(int(options["-f"]))
status = get_power_fn(tn, options)
if status != "on" and status != "off":
fail(EC_STATUS)
if options["-o"] == "enable":
options["-o"] = "on"
if options["-o"] == "disable":
options["-o"] = "off"
if options["-o"] == "on":
if status == "on":
print "Success: Already ON"
else:
power_on = False
for i in range(1,1 + int(options["-F"])):
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn):
power_on = True
break
if power_on:
print "Success: Powered ON"
else:
fail(EC_WAITING_ON)
elif options["-o"] == "off":
if status == "off":
print "Success: Already OFF"
else:
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn):
print "Success: Powered OFF"
else:
fail(EC_WAITING_OFF)
elif options["-o"] == "reboot":
if status != "off":
options["-o"] = "off"
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn) == 0:
fail(EC_WAITING_OFF)
options["-o"] = "on"
power_on = False
for i in range(1,1 + int(options["-F"])):
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn) == 1:
power_on = True
break
if power_on == False:
# this should not fail as not was fenced succesfully
sys.stderr.write('Timed out waiting to power ON\n')
print "Success: Rebooted"
elif options["-o"] == "status":
print "Status: " + status.upper()
if status.upper() == "OFF":
result = 2
elif options["-o"] == "monitor":
1
return result
def fence_login(options):
force_ipvx=""
if (options.has_key("-6")):
force_ipvx="-6 "
if (options.has_key("-4")):
force_ipvx="-4 "
if (options["device_opt"].count("login_eol_lf")):
login_eol = "\n"
else:
login_eol = "\r\n"
try:
re_login = re.compile("(login\s*: )|(Login Name: )|(username: )|(User Name :)", re.IGNORECASE)
re_pass = re.compile("password", re.IGNORECASE)
if options.has_key("-z"):
command = '%s %s %s %s' % (SSL_PATH, force_ipvx, options["-a"], options["-u"])
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
## SSL telnet is part of the fencing package
sys.stderr.write(str(ex) + "\n")
sys.exit(EC_GENERIC_ERROR)
elif options.has_key("-x") and 0 == options.has_key("-k"):
command = '%s %s %s@%s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-u"])
if options.has_key("ssh_options"):
command += ' ' + options["ssh_options"]
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
if options.has_key("telnet_over_ssh"):
#This is for stupid ssh servers (like ALOM) which behave more like telnet (ignore name and display login prompt)
result = conn.log_expect(options, [ re_login, "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"]))
if result == 1:
conn.sendline("yes") # Host identity confirm
conn.log_expect(options, re_login, int(options["-y"]))
conn.sendline(options["-l"])
conn.log_expect(options, re_pass, int(options["-y"]))
else:
result = conn.log_expect(options, [ "ssword:", "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"]))
if result == 1:
conn.sendline("yes")
conn.log_expect(options, "ssword:", int(options["-y"]))
conn.sendline(options["-p"])
conn.log_expect(options, options["-c"], int(options["-y"]))
elif options.has_key("-x") and 1 == options.has_key("-k"):
command = '%s %s %s@%s -i %s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-k"], options["-u"])
if options.has_key("ssh_options"):
command += ' ' + options["ssh_options"]
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
result = conn.log_expect(options, [ options["-c"], "Are you sure you want to continue connecting (yes/no)?", "Enter passphrase for key '"+options["-k"]+"':" ], int(options["-y"]))
if result == 1:
conn.sendline("yes")
conn.log_expect(options, [ options["-c"], "Enter passphrase for key '"+options["-k"]+"':"] , int(options["-y"]))
if result != 0:
if options.has_key("-p"):
conn.sendline(options["-p"])
conn.log_expect(options, options["-c"], int(options["-y"]))
else:
fail_usage("Failed: You have to enter passphrase (-p) for identity file")
else:
try:
conn = fspawn(TELNET_PATH)
conn.send("set binary\n")
conn.send("open %s -%s\n"%(options["-a"], options["-u"]))
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
conn.log_expect(options, re_login, int(options["-y"]))
conn.send(options["-l"] + login_eol)
conn.log_expect(options, re_pass, int(options["-Y"]))
conn.send(options["-p"] + login_eol)
conn.log_expect(options, options["-c"], int(options["-Y"]))
except pexpect.EOF:
fail(EC_LOGIN_DENIED)
except pexpect.TIMEOUT:
fail(EC_LOGIN_DENIED)
return conn
| Python |
#!/usr/bin/python
#
#############################################################################
# Copyright 2011 Matt Clark
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
#############################################################################
#############################################################################
# It's only just begun...
# Current status: completely usable. This script is now working well and,
# has a lot of functionality as a result of the fencing.py library and the
# XenAPI libary.
#############################################################################
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
from fencing import *
import XenAPI
EC_BAD_SESSION = 1
# Find the status of the port given in the -U flag of options.
def get_power_fn(session, options):
if options.has_key("-v"):
verbose = True
else:
verbose = False
try:
# Get a reference to the vm specified in the UUID or vm_name parameter
vm = return_vm_reference(session, options)
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm);
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
status = record["power_state"]
if verbose: print "UUID:", record["uuid"], "NAME:", record["name_label"], "POWER STATUS:", record["power_state"]
# Note that the VM can be in the following states (from the XenAPI document)
# Halted: VM is offline and not using any resources.
# Paused: All resources have been allocated but the VM itself is paused and its vCPUs are not running
# Running: Running
# Paused: VM state has been saved to disk and it is nolonger running. Note that disks remain in-Use while
# We want to make sure that we only return the status "off" if the machine is actually halted as the status
# is checked before a fencing action. Only when the machine is Halted is it not consuming resources which
# may include whatever you are trying to protect with this fencing action.
return (status=="Halted" and "off" or "on")
except Exception, exn:
print str(exn)
return "Error"
# Set the state of the port given in the -U flag of options.
def set_power_fn(session, options):
action = options["-o"].lower()
if options.has_key("-v"):
verbose = True
else:
verbose = False
try:
# Get a reference to the vm specified in the UUID or vm_name parameter
vm = return_vm_reference(session, options)
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm)
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
# Start the VM
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
# Force shutdown the VM
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
# Force reboot the VM
session.xenapi.VM.hard_reboot(vm)
except Exception, exn:
print str(exn);
# Function to populate an array of virtual machines and their status
def get_outlet_list(session, options):
result = {}
if options.has_key("-v"):
verbose = True
else:
verbose = False
try:
# Return an array of all the VM's on the host
vms = session.xenapi.VM.get_all()
for vm in vms:
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm);
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
uuid = record["uuid"]
status = record["power_state"]
result[uuid] = (name, status)
if verbose: print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
return result
# Function to initiate the XenServer session via the XenAPI library.
def connect_and_login(options):
url = options["-s"]
username = options["-l"]
password = options["-p"]
try:
# Create the XML RPC session to the specified URL.
session = XenAPI.Session(url);
# Login using the supplied credentials.
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
# http://sources.redhat.com/cluster/wiki/FenceAgentAPI says that for no connectivity
# the exit value should be 1. It doesn't say anything about failed logins, so
# until I hear otherwise it is best to keep this exit the same to make sure that
# anything calling this script (that uses the same information in the web page
# above) knows that this is an error condition, not a msg signifying a down port.
sys.exit(EC_BAD_SESSION);
return session;
# return a reference to the VM by either using the UUID or the vm_name. If the UUID is set then
# this is tried first as this is the only properly unique identifier.
# Exceptions are not handled in this function, code that calls this must be ready to handle them.
def return_vm_reference(session, options):
if options.has_key("-v"):
verbose = True
else:
verbose = False
# Case where the UUID has been specified
if options.has_key("-U"):
uuid = options["-U"].lower()
# When using the -n parameter for name, we get an error message (in verbose
# mode) that tells us that we didn't find a VM. To immitate that here we
# need to catch and re-raise the exception produced by get_by_uuid.
try:
return session.xenapi.VM.get_by_uuid(uuid)
except Exception,exn:
if verbose: print "No VM's found with a UUID of \"%s\"" %uuid
raise
# Case where the vm_name has been specified
if options.has_key("-n"):
vm_name = options["-n"]
vm_arr = session.xenapi.VM.get_by_name_label(vm_name)
# Need to make sure that we only have one result as the vm_name may
# not be unique. Average case, so do it first.
if len(vm_arr) == 1:
return vm_arr[0]
else:
if len(vm_arr) == 0:
if verbose: print "No VM's found with a name of \"%s\"" %vm_name
# NAME_INVALID used as the XenAPI throws a UUID_INVALID if it can't find
# a VM with the specified UUID. This should make the output look fairly
# consistent.
raise Exception("NAME_INVALID")
else:
if verbose: print "Multiple VM's have the name \"%s\", use UUID instead" %vm_name
raise Exception("MULTIPLE_VMS_FOUND")
# We should never get to this case as the input processing checks that either the UUID or
# the name parameter is set. Regardless of whether or not a VM is found the above if
# statements will return to the calling function (either by exception or by a reference
# to the VM).
raise Exception("VM_LOGIC_ERROR")
def main():
device_opt = [ "help", "version", "agent", "quiet", "verbose", "debug", "action",
"login", "passwd", "passwd_script", "vm_name", "test", "separator",
"no_login", "no_password", "power_timeout", "shell_timeout",
"login_timeout", "power_wait", "session_url", "uuid" ]
atexit.register(atexit_handler)
options=process_input(device_opt)
options = check_input(device_opt, options)
docs = { }
docs["shortdesc"] = "Fence agent for Citrix XenServer"
docs["longdesc"] = "fence_cxs_redhat"
show_docs(options, docs)
xenSession = connect_and_login(options)
# Operate the fencing device
result = fence_action(xenSession, options, set_power_fn, get_power_fn, get_outlet_list)
sys.exit(result)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
import sys, getopt, time, os
import pexpect, re
import telnetlib
import atexit
import __main__
## do not add code here.
#BEGIN_VERSION_GENERATION
RELEASE_VERSION="3.0.17"
BUILD_DATE="(built Thu Oct 7 07:06:21 UTC 2010)"
REDHAT_COPYRIGHT="Copyright (C) Red Hat, Inc. 2004-2010 All rights reserved."
#END_VERSION_GENERATION
LOG_MODE_VERBOSE = 100
LOG_MODE_QUIET = 0
EC_GENERIC_ERROR = 1
EC_BAD_ARGS = 2
EC_LOGIN_DENIED = 3
EC_CONNECTION_LOST = 4
EC_TIMED_OUT = 5
EC_WAITING_ON = 6
EC_WAITING_OFF = 7
EC_STATUS = 8
EC_STATUS_HMC = 9
TELNET_PATH = "/usr/bin/telnet"
SSH_PATH = "/usr/bin/ssh"
SSL_PATH = "/usr/sbin/fence_nss_wrapper"
all_opt = {
"help" : {
"getopt" : "h",
"longopt" : "help",
"help" : "-h, --help Display this help and exit",
"required" : "0",
"shortdesc" : "Display help and exit",
"order" : 54 },
"version" : {
"getopt" : "V",
"longopt" : "version",
"help" : "-V, --version Output version information and exit",
"required" : "0",
"shortdesc" : "Display version information and exit",
"order" : 53 },
"quiet" : {
"getopt" : "q",
"help" : "",
"order" : 50 },
"verbose" : {
"getopt" : "v",
"longopt" : "verbose",
"help" : "-v, --verbose Verbose mode",
"required" : "0",
"shortdesc" : "Verbose mode",
"order" : 51 },
"debug" : {
"getopt" : "D:",
"longopt" : "debug-file",
"help" : "-D, --debug-file=<debugfile> Debugging to output file",
"required" : "0",
"shortdesc" : "Write debug information to given file",
"order" : 52 },
"delay" : {
"getopt" : "f:",
"longopt" : "delay",
"help" : "--delay <seconds> Wait X seconds before fencing is started",
"required" : "0",
"shortdesc" : "Wait X seconds before fencing is started",
"default" : "0",
"order" : 200 },
"agent" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"web" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"action" : {
"getopt" : "o:",
"longopt" : "action",
"help" : "-o, --action=<action> Action: status, reboot (default), off or on",
"required" : "1",
"shortdesc" : "Fencing Action",
"default" : "reboot",
"order" : 1 },
"io_fencing" : {
"getopt" : "o:",
"longopt" : "action",
"help" : "-o, --action=<action> Action: status, enable or disable",
"required" : "1",
"shortdesc" : "Fencing Action",
"default" : "disable",
"order" : 1 },
"ipaddr" : {
"getopt" : "a:",
"longopt" : "ip",
"help" : "-a, --ip=<ip> IP address or hostname of fencing device",
"required" : "1",
"shortdesc" : "IP Address or Hostname",
"order" : 1 },
"ipport" : {
"getopt" : "u:",
"longopt" : "ipport",
"help" : "-u, --ipport=<port> TCP port to use",
"required" : "0",
"shortdesc" : "TCP port to use for connection with device",
"order" : 1 },
"login" : {
"getopt" : "l:",
"longopt" : "username",
"help" : "-l, --username=<name> Login name",
"required" : "?",
"shortdesc" : "Login Name",
"order" : 1 },
"no_login" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"no_password" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"passwd" : {
"getopt" : "p:",
"longopt" : "password",
"help" : "-p, --password=<password> Login password or passphrase",
"required" : "0",
"shortdesc" : "Login password or passphrase",
"order" : 1 },
"passwd_script" : {
"getopt" : "S:",
"longopt" : "password-script=",
"help" : "-S, --password-script=<script> Script to run to retrieve password",
"required" : "0",
"shortdesc" : "Script to retrieve password",
"order" : 1 },
"identity_file" : {
"getopt" : "k:",
"longopt" : "identity-file",
"help" : "-k, --identity-file=<filename> Identity file (private key) for ssh ",
"required" : "0",
"shortdesc" : "Identity file for ssh",
"order" : 1 },
"module_name" : {
"getopt" : "m:",
"longopt" : "module-name",
"help" : "-m, --module-name=<module> DRAC/MC module name",
"required" : "0",
"shortdesc" : "DRAC/MC module name",
"order" : 1 },
"drac_version" : {
"getopt" : "d:",
"longopt" : "drac-version",
"help" : "-d, --drac-version=<version> Force DRAC version to use",
"required" : "0",
"shortdesc" : "Force DRAC version to use",
"order" : 1 },
"hmc_version" : {
"getopt" : "H:",
"longopt" : "hmc-version",
"help" : "-H, --hmc-version=<version> Force HMC version to use: 3, 4 (default)",
"required" : "0",
"shortdesc" : "Force HMC version to use (3 or 4)",
"default" : "4",
"order" : 1 },
"ribcl" : {
"getopt" : "r:",
"longopt" : "ribcl-version",
"help" : "-r, --ribcl-version=<version> Force ribcl version to use",
"required" : "0",
"shortdesc" : "Force ribcl version to use",
"order" : 1 },
"login_eol_lf" : {
"getopt" : "",
"help" : "",
"order" : 1
},
"cmd_prompt" : {
"getopt" : "c:",
"longopt" : "command-prompt",
"help" : "-c, --command-prompt=<prompt> Force command prompt",
"shortdesc" : "Force command prompt",
"required" : "0",
"order" : 1 },
"secure" : {
"getopt" : "x",
"longopt" : "ssh",
"help" : "-x, --ssh Use ssh connection",
"shortdesc" : "SSH connection",
"required" : "0",
"order" : 1 },
"ssl" : {
"getopt" : "z",
"longopt" : "ssl",
"help" : "-z, --ssl Use ssl connection",
"required" : "0",
"shortdesc" : "SSL connection",
"order" : 1 },
"port" : {
"getopt" : "n:",
"longopt" : "plug",
"help" : "-n, --plug=<id> Physical plug number on device or\n" +
" name of virtual machine",
"required" : "1",
"shortdesc" : "Physical plug number or name of virtual machine",
"order" : 1 },
"switch" : {
"getopt" : "s:",
"longopt" : "switch",
"help" : "-s, --switch=<id> Physical switch number on device",
"required" : "0",
"shortdesc" : "Physical switch number on device",
"order" : 1 },
"partition" : {
"getopt" : "n:",
"help" : "-n <id> Name of the partition",
"required" : "0",
"shortdesc" : "Partition name",
"order" : 1 },
"managed" : {
"getopt" : "s:",
"help" : "-s <id> Name of the managed system",
"required" : "0",
"shortdesc" : "Managed system name",
"order" : 1 },
"test" : {
"getopt" : "T",
"help" : "",
"order" : 1,
"obsolete" : "use -o status instead" },
"exec" : {
"getopt" : "e:",
"longopt" : "exec",
"help" : "-e, --exec=<command> Command to execute",
"required" : "0",
"shortdesc" : "Command to execute",
"order" : 1 },
"vmware_type" : {
"getopt" : "d:",
"longopt" : "vmware_type",
"help" : "-d, --vmware_type=<type> Type of VMware to connect",
"required" : "0",
"shortdesc" : "Type of VMware to connect",
"order" : 1 },
"vmware_datacenter" : {
"getopt" : "s:",
"longopt" : "vmware-datacenter",
"help" : "-s, --vmware-datacenter=<dc> VMWare datacenter filter",
"required" : "0",
"shortdesc" : "Show only machines in specified datacenter",
"order" : 2 },
"snmp_version" : {
"getopt" : "d:",
"longopt" : "snmp-version",
"help" : "-d, --snmp-version=<ver> Specifies SNMP version to use",
"required" : "0",
"shortdesc" : "Specifies SNMP version to use (1,2c,3)",
"order" : 1 },
"community" : {
"getopt" : "c:",
"longopt" : "community",
"help" : "-c, --community=<community> Set the community string",
"required" : "0",
"shortdesc" : "Set the community string",
"order" : 1},
"snmp_auth_prot" : {
"getopt" : "b:",
"longopt" : "snmp-auth-prot",
"help" : "-b, --snmp-auth-prot=<prot> Set authentication protocol (MD5|SHA)",
"required" : "0",
"shortdesc" : "Set authentication protocol (MD5|SHA)",
"order" : 1},
"snmp_sec_level" : {
"getopt" : "E:",
"longopt" : "snmp-sec-level",
"help" : "-E, --snmp-sec-level=<level> Set security level\n"+
" (noAuthNoPriv|authNoPriv|authPriv)",
"required" : "0",
"shortdesc" : "Set security level (noAuthNoPriv|authNoPriv|authPriv)",
"order" : 1},
"snmp_priv_prot" : {
"getopt" : "B:",
"longopt" : "snmp-priv-prot",
"help" : "-B, --snmp-priv-prot=<prot> Set privacy protocol (DES|AES)",
"required" : "0",
"shortdesc" : "Set privacy protocol (DES|AES)",
"order" : 1},
"snmp_priv_passwd" : {
"getopt" : "P:",
"longopt" : "snmp-priv-passwd",
"help" : "-P, --snmp-priv-passwd=<pass> Set privacy protocol password",
"required" : "0",
"shortdesc" : "Set privacy protocol password",
"order" : 1},
"snmp_priv_passwd_script" : {
"getopt" : "R:",
"longopt" : "snmp-priv-passwd-script",
"help" : "-R, --snmp-priv-passwd-script Script to run to retrieve privacy password",
"required" : "0",
"shortdesc" : "Script to run to retrieve privacy password",
"order" : 1},
"inet4_only" : {
"getopt" : "4",
"longopt" : "inet4-only",
"help" : "-4, --inet4-only Forces agent to use IPv4 addresses only",
"required" : "0",
"shortdesc" : "Forces agent to use IPv4 addresses only",
"order" : 1 },
"inet6_only" : {
"getopt" : "6",
"longopt" : "inet6-only",
"help" : "-6, --inet6-only Forces agent to use IPv6 addresses only",
"required" : "0",
"shortdesc" : "Forces agent to use IPv6 addresses only",
"order" : 1 },
"udpport" : {
"getopt" : "u:",
"longopt" : "udpport",
"help" : "-u, --udpport UDP/TCP port to use",
"required" : "0",
"shortdesc" : "UDP/TCP port to use for connection with device",
"order" : 1},
"separator" : {
"getopt" : "C:",
"longopt" : "separator",
"help" : "-C, --separator=<char> Separator for CSV created by 'list' operation",
"default" : ",",
"required" : "0",
"shortdesc" : "Separator for CSV created by operation list",
"order" : 100 },
"login_timeout" : {
"getopt" : "y:",
"longopt" : "login-timeout",
"help" : "--login-timeout <seconds> Wait X seconds for cmd prompt after login",
"default" : "5",
"required" : "0",
"shortdesc" : "Wait X seconds for cmd prompt after login",
"order" : 200 },
"shell_timeout" : {
"getopt" : "Y:",
"longopt" : "shell-timeout",
"help" : "--shell-timeout <seconds> Wait X seconds for cmd prompt after issuing command",
"default" : "3",
"required" : "0",
"shortdesc" : "Wait X seconds for cmd prompt after issuing command",
"order" : 200 },
"power_timeout" : {
"getopt" : "g:",
"longopt" : "power-timeout",
"help" : "--power-timeout <seconds> Test X seconds for status change after ON/OFF",
"default" : "20",
"required" : "0",
"shortdesc" : "Test X seconds for status change after ON/OFF",
"order" : 200 },
"power_wait" : {
"getopt" : "G:",
"longopt" : "power-wait",
"help" : "--power-wait <seconds> Wait X seconds after issuing ON/OFF",
"default" : "0",
"required" : "0",
"shortdesc" : "Wait X seconds after issuing ON/OFF",
"order" : 200 },
"missing_as_off" : {
"getopt" : "M",
"longopt" : "missing-as-off",
"help" : "--missing-as-off Missing port returns OFF instead of failure",
"required" : "0",
"shortdesc" : "Missing port returns OFF instead of failure",
"order" : 200 },
"retry_on" : {
"getopt" : "F:",
"longopt" : "retry-on",
"help" : "--retry-on <attempts> Count of attempts to retry power on",
"default" : "1",
"required" : "0",
"shortdesc" : "Count of attempts to retry power on",
"order" : 200 },
"session_url" : {
"getopt" : "s:",
"longopt" : "session-url",
"help" : "-s, --session-url URL to connect to XenServer on.",
"required" : "1",
"shortdesc" : "The URL of the XenServer host.",
"order" : 1},
"vm_name" : {
"getopt" : "n:",
"longopt" : "vm-name",
"help" : "-n, --vm-name Name of the VM to fence.",
"required" : "0",
"shortdesc" : "The name of the virual machine to fence.",
"order" : 1},
"uuid" : {
"getopt" : "U:",
"longopt" : "uuid",
"help" : "-U, --uuid UUID of the VM to fence.",
"required" : "0",
"shortdesc" : "The UUID of the virtual machine to fence.",
"order" : 1}
}
common_opt = [ "retry_on", "delay" ]
class fspawn(pexpect.spawn):
def log_expect(self, options, pattern, timeout):
result = self.expect(pattern, timeout)
if options["log"] >= LOG_MODE_VERBOSE:
options["debug_fh"].write(self.before + self.after)
return result
def atexit_handler():
try:
sys.stdout.close()
os.close(1)
except IOError:
sys.stderr.write("%s failed to close standard output\n"%(sys.argv[0]))
sys.exit(EC_GENERIC_ERROR)
def version(command, release, build_date, copyright_notice):
print command, " ", release, " ", build_date
if len(copyright_notice) > 0:
print copyright_notice
def fail_usage(message = ""):
if len(message) > 0:
sys.stderr.write(message+"\n")
sys.stderr.write("Please use '-h' for usage\n")
sys.exit(EC_GENERIC_ERROR)
def fail(error_code):
message = {
EC_LOGIN_DENIED : "Unable to connect/login to fencing device",
EC_CONNECTION_LOST : "Connection lost",
EC_TIMED_OUT : "Connection timed out",
EC_WAITING_ON : "Failed: Timed out waiting to power ON",
EC_WAITING_OFF : "Failed: Timed out waiting to power OFF",
EC_STATUS : "Failed: Unable to obtain correct plug status or plug is not available",
EC_STATUS_HMC : "Failed: Either unable to obtaion correct plug status, partition is not available or incorrect HMC version used"
}[error_code] + "\n"
sys.stderr.write(message)
sys.exit(EC_GENERIC_ERROR)
def usage(avail_opt):
global all_opt
print "Usage:"
print "\t" + os.path.basename(sys.argv[0]) + " [options]"
print "Options:"
sorted_list = [ (key, all_opt[key]) for key in avail_opt ]
sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"]))
for key, value in sorted_list:
if len(value["help"]) != 0:
print " " + value["help"]
def metadata(avail_opt, options, docs):
global all_opt
sorted_list = [ (key, all_opt[key]) for key in avail_opt ]
sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"]))
print "<?xml version=\"1.0\" ?>"
print "<resource-agent name=\"" + os.path.basename(sys.argv[0]) + "\" shortdesc=\"" + docs["shortdesc"] + "\" >"
print "<longdesc>" + docs["longdesc"] + "</longdesc>"
if docs.has_key("vendorurl"):
print "<vendor-url>" + docs["vendorurl"] + "</vendor-url>"
print "<parameters>"
for option, value in sorted_list:
if all_opt[option].has_key("shortdesc"):
print "\t<parameter name=\"" + option + "\" unique=\"1\" required=\"" + all_opt[option]["required"] + "\">"
default = ""
if all_opt[option].has_key("default"):
default = "default=\""+str(all_opt[option]["default"])+"\""
elif options.has_key("-" + all_opt[option]["getopt"][:-1]):
if options["-" + all_opt[option]["getopt"][:-1]]:
try:
default = "default=\"" + options["-" + all_opt[option]["getopt"][:-1]] + "\""
except TypeError:
## @todo/@note: Currently there is no clean way how to handle lists
## we can create a string from it but we can't set it on command line
default = "default=\"" + str(options["-" + all_opt[option]["getopt"][:-1]]) +"\""
elif options.has_key("-" + all_opt[option]["getopt"]):
default = "default=\"true\" "
mixed = all_opt[option]["help"]
## split it between option and help text
res = re.compile("^(.*--\S+)\s+", re.IGNORECASE | re.S).search(mixed)
if (None != res):
mixed = res.group(1)
mixed = mixed.replace("<", "<").replace(">", ">")
print "\t\t<getopt mixed=\"" + mixed + "\" />"
if all_opt[option]["getopt"].count(":") > 0:
print "\t\t<content type=\"string\" "+default+" />"
else:
print "\t\t<content type=\"boolean\" "+default+" />"
print "\t\t<shortdesc lang=\"en\">" + all_opt[option]["shortdesc"] + "</shortdesc>"
print "\t</parameter>"
print "</parameters>"
print "<actions>"
print "\t<action name=\"on\" />"
print "\t<action name=\"off\" />"
print "\t<action name=\"reboot\" />"
print "\t<action name=\"status\" />"
print "\t<action name=\"list\" />"
print "\t<action name=\"monitor\" />"
print "\t<action name=\"metadata\" />"
print "</actions>"
print "</resource-agent>"
def process_input(avail_opt):
global all_opt
global common_opt
##
## Add options which are available for every fence agent
#####
avail_opt.extend(common_opt)
##
## Set standard environment
#####
os.putenv("LANG", "C")
os.putenv("LC_ALL", "C")
##
## Prepare list of options for getopt
#####
getopt_string = ""
longopt_list = [ ]
for k in avail_opt:
if all_opt.has_key(k):
getopt_string += all_opt[k]["getopt"]
else:
fail_usage("Parse error: unknown option '"+k+"'")
if all_opt.has_key(k) and all_opt[k].has_key("longopt"):
if all_opt[k]["getopt"].endswith(":"):
longopt_list.append(all_opt[k]["longopt"] + "=")
else:
longopt_list.append(all_opt[k]["longopt"])
## Compatibility layer
if avail_opt.count("module_name") == 1:
getopt_string += "n:"
longopt_list.append("plug=")
##
## Read options from command line or standard input
#####
if len(sys.argv) > 1:
try:
opt, args = getopt.gnu_getopt(sys.argv[1:], getopt_string, longopt_list)
except getopt.GetoptError, error:
fail_usage("Parse error: " + error.msg)
## Transform longopt to short one which are used in fencing agents
#####
old_opt = opt
opt = { }
for o in dict(old_opt).keys():
if o.startswith("--"):
for x in all_opt.keys():
if all_opt[x].has_key("longopt") and "--" + all_opt[x]["longopt"] == o:
opt["-" + all_opt[x]["getopt"].rstrip(":")] = dict(old_opt)[o]
else:
opt[o] = dict(old_opt)[o]
## Compatibility Layer
#####
z = dict(opt)
if z.has_key("-T") == 1:
z["-o"] = "status"
if z.has_key("-n") == 1:
z["-m"] = z["-n"]
opt = z
##
#####
else:
opt = { }
name = ""
for line in sys.stdin.readlines():
line = line.strip()
if ((line.startswith("#")) or (len(line) == 0)):
continue
(name, value) = (line + "=").split("=", 1)
value = value[:-1]
## Compatibility Layer
######
if name == "blade":
name = "port"
elif name == "option":
name = "action"
elif name == "fm":
name = "port"
elif name == "hostname":
name = "ipaddr"
elif name == "modulename":
name = "module_name"
elif name == "action" and 1 == avail_opt.count("io_fencing"):
name = "io_fencing"
elif name == "port" and 1 == avail_opt.count("drac_version"):
name = "module_name"
##
######
if avail_opt.count(name) == 0:
sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n")
continue
if all_opt[name]["getopt"].endswith(":"):
opt["-"+all_opt[name]["getopt"].rstrip(":")] = value
elif ((value == "1") or (value.lower() == "yes")):
opt["-"+all_opt[name]["getopt"]] = "1"
return opt
##
## This function checks input and answers if we want to have same answers
## in each of the fencing agents. It looks for possible errors and run
## password script to set a correct password
######
def check_input(device_opt, opt):
global all_opt
global common_opt
##
## Add options which are available for every fence agent
#####
device_opt.extend([x for x in common_opt if device_opt.count(x) == 0])
options = dict(opt)
options["device_opt"] = device_opt
## Set requirements that should be included in metadata
#####
if device_opt.count("login") and device_opt.count("no_login") == 0:
all_opt["login"]["required"] = "1"
else:
all_opt["login"]["required"] = "0"
## In special cases (show help, metadata or version) we don't need to check anything
#####
if options.has_key("-h") or options.has_key("-V") or (options.has_key("-o") and options["-o"].lower() == "metadata"):
return options;
## Set default values
#####
for opt in device_opt:
if all_opt[opt].has_key("default"):
getopt = "-" + all_opt[opt]["getopt"].rstrip(":")
if 0 == options.has_key(getopt):
options[getopt] = all_opt[opt]["default"]
options["-o"]=options["-o"].lower()
if options.has_key("-v"):
options["log"] = LOG_MODE_VERBOSE
else:
options["log"] = LOG_MODE_QUIET
if 0 == device_opt.count("io_fencing"):
if 0 == ["on", "off", "reboot", "status", "list", "monitor"].count(options["-o"].lower()):
fail_usage("Failed: Unrecognised action '" + options["-o"] + "'")
else:
if 0 == ["enable", "disable", "status", "list", "monitor"].count(options["-o"].lower()):
fail_usage("Failed: Unrecognised action '" + options["-o"] + "'")
if (0 == options.has_key("-l")) and device_opt.count("login") and (device_opt.count("no_login") == 0):
fail_usage("Failed: You have to set login name")
if 0 == options.has_key("-a") and 0 == options.has_key("-s"):
fail_usage("Failed: You have to enter fence address")
if (0 == ["list", "monitor"].count(options["-o"].lower())) and device_opt.count("vm_name") and device_opt.count("uuid"):
if 0 == options.has_key("-n") and 0 == options.has_key("-U"):
fail_usage("Failed: You must specify either UUID or VM name")
if (device_opt.count("no_password") == 0):
if 0 == device_opt.count("identity_file"):
if 0 == (options.has_key("-p") or options.has_key("-S")):
fail_usage("Failed: You have to enter password or password script")
else:
if 0 == (options.has_key("-p") or options.has_key("-S") or options.has_key("-k")):
fail_usage("Failed: You have to enter password, password script or identity file")
if 0 == options.has_key("-x") and 1 == options.has_key("-k"):
fail_usage("Failed: You have to use identity file together with ssh connection (-x)")
if 1 == options.has_key("-k"):
if 0 == os.path.isfile(options["-k"]):
fail_usage("Failed: Identity file " + options["-k"] + " does not exist")
if (0 == ["list", "monitor"].count(options["-o"].lower())) and (0 == options.has_key("-n")) and (device_opt.count("port")):
fail_usage("Failed: You have to enter plug number")
if options.has_key("-S"):
options["-p"] = os.popen(options["-S"]).read().rstrip()
if options.has_key("-D"):
try:
options["debug_fh"] = file (options["-D"], "w")
except IOError:
fail_usage("Failed: Unable to create file "+options["-D"])
if options.has_key("-v") and options.has_key("debug_fh") == 0:
options["debug_fh"] = sys.stderr
if options.has_key("-R"):
options["-P"] = os.popen(options["-R"]).read().rstrip()
if options.has_key("-u") == False:
if options.has_key("-x"):
options["-u"] = 22
elif options.has_key("-z"):
options["-u"] = 443
elif device_opt.count("web"):
options["-u"] = 80
else:
options["-u"] = 23
return options
def wait_power_status(tn, options, get_power_fn):
for dummy in xrange(int(options["-g"])):
if get_power_fn(tn, options) != options["-o"]:
time.sleep(1)
else:
return 1
return 0
def show_docs(options, docs = None):
device_opt = options["device_opt"]
if docs == None:
docs = { }
docs["shortdesc"] = "Fence agent"
docs["longdesc"] = ""
## Process special options (and exit)
#####
if options.has_key("-h"):
usage(device_opt)
sys.exit(0)
if options.has_key("-o") and options["-o"].lower() == "metadata":
metadata(device_opt, options, docs)
sys.exit(0)
if options.has_key("-V"):
print __main__.RELEASE_VERSION, __main__.BUILD_DATE
print __main__.REDHAT_COPYRIGHT
sys.exit(0)
def fence_action(tn, options, set_power_fn, get_power_fn, get_outlet_list = None):
result = 0
## Process options that manipulate fencing device
#####
if (options["-o"] == "list") and (0 == options["device_opt"].count("port")) and (0 == options["device_opt"].count("partition")) and (0 == options["device_opt"].count("uuid")):
print "N/A"
return
elif (options["-o"] == "list" and get_outlet_list == None):
## @todo: exception?
## This is just temporal solution, we will remove default value
## None as soon as all existing agent will support this operation
print "NOTICE: List option is not working on this device yet"
return
elif (options["-o"] == "list") or ((options["-o"] == "monitor") and 1 == options["device_opt"].count("port")):
outlets = get_outlet_list(tn, options)
## keys can be numbers (port numbers) or strings (names of VM)
for o in outlets.keys():
(alias, status) = outlets[o]
if options["-o"] != "monitor":
print o + options["-C"] + alias
return
if options["-o"] in ["off", "reboot"]:
time.sleep(int(options["-f"]))
status = get_power_fn(tn, options)
if status != "on" and status != "off":
fail(EC_STATUS)
if options["-o"] == "enable":
options["-o"] = "on"
if options["-o"] == "disable":
options["-o"] = "off"
if options["-o"] == "on":
if status == "on":
print "Success: Already ON"
else:
power_on = False
for i in range(1,1 + int(options["-F"])):
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn):
power_on = True
break
if power_on:
print "Success: Powered ON"
else:
fail(EC_WAITING_ON)
elif options["-o"] == "off":
if status == "off":
print "Success: Already OFF"
else:
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn):
print "Success: Powered OFF"
else:
fail(EC_WAITING_OFF)
elif options["-o"] == "reboot":
if status != "off":
options["-o"] = "off"
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn) == 0:
fail(EC_WAITING_OFF)
options["-o"] = "on"
power_on = False
for i in range(1,1 + int(options["-F"])):
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn) == 1:
power_on = True
break
if power_on == False:
# this should not fail as not was fenced succesfully
sys.stderr.write('Timed out waiting to power ON\n')
print "Success: Rebooted"
elif options["-o"] == "status":
print "Status: " + status.upper()
if status.upper() == "OFF":
result = 2
elif options["-o"] == "monitor":
1
return result
def fence_login(options):
force_ipvx=""
if (options.has_key("-6")):
force_ipvx="-6 "
if (options.has_key("-4")):
force_ipvx="-4 "
if (options["device_opt"].count("login_eol_lf")):
login_eol = "\n"
else:
login_eol = "\r\n"
try:
re_login = re.compile("(login\s*: )|(Login Name: )|(username: )|(User Name :)", re.IGNORECASE)
re_pass = re.compile("password", re.IGNORECASE)
if options.has_key("-z"):
command = '%s %s %s %s' % (SSL_PATH, force_ipvx, options["-a"], options["-u"])
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
## SSL telnet is part of the fencing package
sys.stderr.write(str(ex) + "\n")
sys.exit(EC_GENERIC_ERROR)
elif options.has_key("-x") and 0 == options.has_key("-k"):
command = '%s %s %s@%s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-u"])
if options.has_key("ssh_options"):
command += ' ' + options["ssh_options"]
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
if options.has_key("telnet_over_ssh"):
#This is for stupid ssh servers (like ALOM) which behave more like telnet (ignore name and display login prompt)
result = conn.log_expect(options, [ re_login, "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"]))
if result == 1:
conn.sendline("yes") # Host identity confirm
conn.log_expect(options, re_login, int(options["-y"]))
conn.sendline(options["-l"])
conn.log_expect(options, re_pass, int(options["-y"]))
else:
result = conn.log_expect(options, [ "ssword:", "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"]))
if result == 1:
conn.sendline("yes")
conn.log_expect(options, "ssword:", int(options["-y"]))
conn.sendline(options["-p"])
conn.log_expect(options, options["-c"], int(options["-y"]))
elif options.has_key("-x") and 1 == options.has_key("-k"):
command = '%s %s %s@%s -i %s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-k"], options["-u"])
if options.has_key("ssh_options"):
command += ' ' + options["ssh_options"]
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
result = conn.log_expect(options, [ options["-c"], "Are you sure you want to continue connecting (yes/no)?", "Enter passphrase for key '"+options["-k"]+"':" ], int(options["-y"]))
if result == 1:
conn.sendline("yes")
conn.log_expect(options, [ options["-c"], "Enter passphrase for key '"+options["-k"]+"':"] , int(options["-y"]))
if result != 0:
if options.has_key("-p"):
conn.sendline(options["-p"])
conn.log_expect(options, options["-c"], int(options["-y"]))
else:
fail_usage("Failed: You have to enter passphrase (-p) for identity file")
else:
try:
conn = fspawn(TELNET_PATH)
conn.send("set binary\n")
conn.send("open %s -%s\n"%(options["-a"], options["-u"]))
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
conn.log_expect(options, re_login, int(options["-y"]))
conn.send(options["-l"] + login_eol)
conn.log_expect(options, re_pass, int(options["-Y"]))
conn.send(options["-p"] + login_eol)
conn.log_expect(options, options["-c"], int(options["-Y"]))
except pexpect.EOF:
fail(EC_LOGIN_DENIED)
except pexpect.TIMEOUT:
fail(EC_LOGIN_DENIED)
return conn
| Python |
#!/usr/bin/env python
#
#############################################################################
# Copyright 2011 Matt Clark
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#############################################################################
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
import sys, string, getopt
import XenAPI
def usage():
print "Usage: fence_cxs [-hv] [-a <action>] -l <login username> -p <login password> -s <session url> [-u <UUID>]"
print "Where:-"
print " -a : Specifies the action to perfom. Can be any of \"on|off|reboot|status|list\". Defaults to \"status\"."
print " -h : Print this help message."
print " -l : The username for the XenServer host."
print " -p : The password for the XenServer host."
print " -s : The URL of the web interface on the XenServer host."
print " -U : The UUID of the virtual machine to fence or query. Defaults to the empty string which will return"
print " the status of all hosts when action is set to \"status\". If the action is set to \"on|off|reboot\""
print " then the UUID must be specified."
# Process command line options and populate the config array
def process_opts():
config = {
"action" : "status",
"session_url" : "",
"session_user" : "",
"session_pass" : "",
"uuid" : "",
"name" : "",
"verbose" : False
}
# If we have at least one argument then we want to parse the command line using getopts
if len(sys.argv) > 1:
try:
opts, args = getopt.getopt(sys.argv[1:], "a:hl:n:s:p:U:v", ["help", "verbose", "action=", "session-url=", "login-name=", "name=", "password=", "uuid="])
except getopt.GetoptError, err:
# We got an unrecognised option, so print he help message and exit
print str(err)
usage()
sys.exit(1)
for opt, arg in opts:
if opt in ("-v", "--verbose"):
config["verbose"] = True
elif opt in ("-a", "--action"):
config["action"] = clean_action(arg)
elif opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-s", "--session-url"):
config["session_url"] = arg
elif opt in ("-l", "--login-name"):
config["session_user"] = arg
elif opt in ("-n", "--name"):
config["name"] = arg
elif opt in ("-p", "--password"):
config["session_pass"] = arg
elif opt in ("-U", "--uuid"):
config["uuid"] = arg.lower()
else:
assert False, "unhandled option"
# Otherwise process stdin for parameters. This is to handle the Red Hat clustering
# mechanism where by fenced passes in name/value pairs instead of using command line
# options.
else:
for line in sys.stdin.readlines():
line = line.strip()
if ((line.startswith("#")) or (len(line) == 0)):
continue
(name, value) = (line + "=").split("=", 1)
value = value[:-1]
name = clean_param_name(name)
if name == "action":
value = clean_action(value)
if name in config:
config[name] = value
else:
sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n")
if( config["session_url"] == "" or config["session_user"] == "" or config["session_pass"] == "" ):
print "You must specify the session url, username and password.";
usage();
sys.exit(2);
return config
# why, well just to be nice. Given an action will return the corresponding
# value that the rest of the script uses.
def clean_action(action):
if action.lower() in ("on", "poweron", "powerup"):
return "on"
elif action.lower() in ("off", "poweroff", "powerdown"):
return "off"
elif action.lower() in ("reboot", "reset", "restart"):
return "reboot"
elif action.lower() in ("status", "powerstatus", "list"):
return "status"
else:
print "Bad action", action
usage()
exit(4)
# why, well just to be nice. Given a parameter will return the corresponding
# value that the rest of the script uses.
def clean_param_name(name):
if name.lower() in ("action", "operation", "op"):
return "action"
elif name.lower() in ("session_user", "login", "login-name", "login_name", "user", "username", "session-user"):
return "session_user"
elif name.lower() in ("session_pass", "pass", "passwd", "password", "session-pass"):
return "session_pass"
elif name.lower() in ("session_url", "url", "session-url"):
return "session_url"
else:
# we should never get here as getopt should handle the checking of this input.
print "Bad parameter specified", name
usage()
exit(5)
# Print the power status of a VM. If no UUID is given, then all VM's are queried
def get_power_status(session, uuid = "", name = ""):
try:
# If the UUID hasn't been set, then output the status of all
# valid virtual machines.
if( len(uuid) > 0 ):
vms = [session.xenapi.VM.get_by_uuid(uuid)]
elif( len(name) > 0 ):
vms = session.xenapi.VM.get_by_name_label(name)
else:
vms = session.xenapi.VM.get_all()
for vm in vms:
record = session.xenapi.VM.get_record(vm);
# We only want to print out the status for actual virtual machines. The above get_all function
# returns any templates and also the control domain. This is one of the reasons the process
# takes such a long time to list all VM's. Hopefully there is a way to filter this in the
# request packet in the future.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
def set_power_status(session, uuid, name, action):
try:
vm = None
if( len(uuid) > 0 ):
vm = session.xenapi.VM.get_by_uuid(uuid)
elif( len(name) > 0 ):
vm_arr = session.xenapi.VM.get_by_name_label(name)
if( len(vm_arr) == 1 ):
vm = vm_arr[0]
else
raise Exception("Multiple VM's have that name. Use UUID instead.")
if( vm != None ):
record = session.xenapi.VM.get_record(vm);
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
session.xenapi.VM.hard_reboot(vm)
else:
raise Exception("Bad power status");
except Exception, exn:
print str(exn);
def main():
config = process_opts();
session = session_start(config["session_url"]);
session_login(session, config["session_user"], config["session_pass"]);
if( config["action"] == "status" ):
get_power_status(session, config["uuid"], config["name"])
else:
if( config["verbose"] ):
print "Power status before action"
get_power_status(session, config["uuid"])
set_power_status(session, config["uuid"], config["name"], config["action"])
if( config["verbose"] ):
print "Power status after action"
get_power_status(session, config["uuid"])
# Function to initiate the session with the XenServer system
def session_start(url):
try:
session = XenAPI.Session(url);
except Exception, exn:
print str(exn);
sys.exit(3);
return session;
def session_login(session, username, password):
try:
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
sys.exit(3);
if __name__ == "__main__":
main()
# vim:set ts=4 sw=4
| Python |
#!/usr/bin/env python
#
#############################################################################
# Copyright 2011 Matt Clark
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#############################################################################
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
import sys, string, getopt
import XenAPI
def usage():
print "Usage: fence_cxs [-hv] [-a <action>] -l <login username> -p <login password> -s <session url> [-u <UUID>]"
print "Where:-"
print " -a : Specifies the action to perfom. Can be any of \"on|off|reboot|status|list\". Defaults to \"status\"."
print " -h : Print this help message."
print " -l : The username for the XenServer host."
print " -p : The password for the XenServer host."
print " -s : The URL of the web interface on the XenServer host."
print " -U : The UUID of the virtual machine to fence or query. Defaults to the empty string which will return"
print " the status of all hosts when action is set to \"status\". If the action is set to \"on|off|reboot\""
print " then the UUID must be specified."
# Process command line options and populate the config array
def process_opts():
config = {
"action" : "status",
"session_url" : "",
"session_user" : "",
"session_pass" : "",
"uuid" : "",
"name" : "",
"verbose" : False
}
# If we have at least one argument then we want to parse the command line using getopts
if len(sys.argv) > 1:
try:
opts, args = getopt.getopt(sys.argv[1:], "a:hl:n:s:p:U:v", ["help", "verbose", "action=", "session-url=", "login-name=", "name=", "password=", "uuid="])
except getopt.GetoptError, err:
# We got an unrecognised option, so print he help message and exit
print str(err)
usage()
sys.exit(1)
for opt, arg in opts:
if opt in ("-v", "--verbose"):
config["verbose"] = True
elif opt in ("-a", "--action"):
config["action"] = clean_action(arg)
elif opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-s", "--session-url"):
config["session_url"] = arg
elif opt in ("-l", "--login-name"):
config["session_user"] = arg
elif opt in ("-n", "--name"):
config["name"] = arg
elif opt in ("-p", "--password"):
config["session_pass"] = arg
elif opt in ("-U", "--uuid"):
config["uuid"] = arg.lower()
else:
assert False, "unhandled option"
# Otherwise process stdin for parameters. This is to handle the Red Hat clustering
# mechanism where by fenced passes in name/value pairs instead of using command line
# options.
else:
for line in sys.stdin.readlines():
line = line.strip()
if ((line.startswith("#")) or (len(line) == 0)):
continue
(name, value) = (line + "=").split("=", 1)
value = value[:-1]
name = clean_param_name(name)
if name == "action":
value = clean_action(value)
if name in config:
config[name] = value
else:
sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n")
if( config["session_url"] == "" or config["session_user"] == "" or config["session_pass"] == "" ):
print "You must specify the session url, username and password.";
usage();
sys.exit(2);
return config
# why, well just to be nice. Given an action will return the corresponding
# value that the rest of the script uses.
def clean_action(action):
if action.lower() in ("on", "poweron", "powerup"):
return "on"
elif action.lower() in ("off", "poweroff", "powerdown"):
return "off"
elif action.lower() in ("reboot", "reset", "restart"):
return "reboot"
elif action.lower() in ("status", "powerstatus", "list"):
return "status"
else:
print "Bad action", action
usage()
exit(4)
# why, well just to be nice. Given a parameter will return the corresponding
# value that the rest of the script uses.
def clean_param_name(name):
if name.lower() in ("action", "operation", "op"):
return "action"
elif name.lower() in ("session_user", "login", "login-name", "login_name", "user", "username", "session-user"):
return "session_user"
elif name.lower() in ("session_pass", "pass", "passwd", "password", "session-pass"):
return "session_pass"
elif name.lower() in ("session_url", "url", "session-url"):
return "session_url"
else:
# we should never get here as getopt should handle the checking of this input.
print "Bad parameter specified", name
usage()
exit(5)
# Print the power status of a VM. If no UUID is given, then all VM's are queried
def get_power_status(session, uuid = "", name = ""):
try:
# If the UUID hasn't been set, then output the status of all
# valid virtual machines.
if( len(uuid) > 0 ):
vms = [session.xenapi.VM.get_by_uuid(uuid)]
elif( len(name) > 0 ):
vms = session.xenapi.VM.get_by_name_label(name)
else:
vms = session.xenapi.VM.get_all()
for vm in vms:
record = session.xenapi.VM.get_record(vm);
# We only want to print out the status for actual virtual machines. The above get_all function
# returns any templates and also the control domain. This is one of the reasons the process
# takes such a long time to list all VM's. Hopefully there is a way to filter this in the
# request packet in the future.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
def set_power_status(session, uuid, name, action):
try:
vm = None
if( len(uuid) > 0 ):
vm = session.xenapi.VM.get_by_uuid(uuid)
elif( len(name) > 0 ):
vm_arr = session.xenapi.VM.get_by_name_label(name)
if( len(vm_arr) == 1 ):
vm = vm_arr[0]
else
raise Exception("Multiple VM's have that name. Use UUID instead.")
if( vm != None ):
record = session.xenapi.VM.get_record(vm);
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
session.xenapi.VM.hard_reboot(vm)
else:
raise Exception("Bad power status");
except Exception, exn:
print str(exn);
def main():
config = process_opts();
session = session_start(config["session_url"]);
session_login(session, config["session_user"], config["session_pass"]);
if( config["action"] == "status" ):
get_power_status(session, config["uuid"], config["name"])
else:
if( config["verbose"] ):
print "Power status before action"
get_power_status(session, config["uuid"])
set_power_status(session, config["uuid"], config["name"], config["action"])
if( config["verbose"] ):
print "Power status after action"
get_power_status(session, config["uuid"])
# Function to initiate the session with the XenServer system
def session_start(url):
try:
session = XenAPI.Session(url);
except Exception, exn:
print str(exn);
sys.exit(3);
return session;
def session_login(session, username, password):
try:
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
sys.exit(3);
if __name__ == "__main__":
main()
# vim:set ts=4 sw=4
| Python |
#!/usr/bin/python
#
#############################################################################
# Copyright 2011 Matt Clark
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
#############################################################################
#############################################################################
# It's only just begun...
# Current status: completely usable. This script is now working well and,
# has a lot of functionality as a result of the fencing.py library and the
# XenAPI libary.
#############################################################################
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
from fencing import *
import XenAPI
EC_BAD_SESSION = 1
# Find the status of the port given in the -U flag of options.
def get_power_fn(session, options):
if options.has_key("-v"):
verbose = True
else:
verbose = False
try:
# Get a reference to the vm specified in the UUID or vm_name parameter
vm = return_vm_reference(session, options)
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm);
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
status = record["power_state"]
if verbose: print "UUID:", record["uuid"], "NAME:", record["name_label"], "POWER STATUS:", record["power_state"]
# Note that the VM can be in the following states (from the XenAPI document)
# Halted: VM is offline and not using any resources.
# Paused: All resources have been allocated but the VM itself is paused and its vCPUs are not running
# Running: Running
# Paused: VM state has been saved to disk and it is nolonger running. Note that disks remain in-Use while
# We want to make sure that we only return the status "off" if the machine is actually halted as the status
# is checked before a fencing action. Only when the machine is Halted is it not consuming resources which
# may include whatever you are trying to protect with this fencing action.
return (status=="Halted" and "off" or "on")
except Exception, exn:
print str(exn)
return "Error"
# Set the state of the port given in the -U flag of options.
def set_power_fn(session, options):
action = options["-o"].lower()
if options.has_key("-v"):
verbose = True
else:
verbose = False
try:
# Get a reference to the vm specified in the UUID or vm_name parameter
vm = return_vm_reference(session, options)
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm)
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
# Start the VM
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
# Force shutdown the VM
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
# Force reboot the VM
session.xenapi.VM.hard_reboot(vm)
except Exception, exn:
print str(exn);
# Function to populate an array of virtual machines and their status
def get_outlet_list(session, options):
result = {}
if options.has_key("-v"):
verbose = True
else:
verbose = False
try:
# Return an array of all the VM's on the host
vms = session.xenapi.VM.get_all()
for vm in vms:
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm);
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
uuid = record["uuid"]
status = record["power_state"]
result[uuid] = (name, status)
if verbose: print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
return result
# Function to initiate the XenServer session via the XenAPI library.
def connect_and_login(options):
url = options["-s"]
username = options["-l"]
password = options["-p"]
try:
# Create the XML RPC session to the specified URL.
session = XenAPI.Session(url);
# Login using the supplied credentials.
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
# http://sources.redhat.com/cluster/wiki/FenceAgentAPI says that for no connectivity
# the exit value should be 1. It doesn't say anything about failed logins, so
# until I hear otherwise it is best to keep this exit the same to make sure that
# anything calling this script (that uses the same information in the web page
# above) knows that this is an error condition, not a msg signifying a down port.
sys.exit(EC_BAD_SESSION);
return session;
# return a reference to the VM by either using the UUID or the vm_name. If the UUID is set then
# this is tried first as this is the only properly unique identifier.
# Exceptions are not handled in this function, code that calls this must be ready to handle them.
def return_vm_reference(session, options):
if options.has_key("-v"):
verbose = True
else:
verbose = False
# Case where the UUID has been specified
if options.has_key("-U"):
uuid = options["-U"].lower()
# When using the -n parameter for name, we get an error message (in verbose
# mode) that tells us that we didn't find a VM. To immitate that here we
# need to catch and re-raise the exception produced by get_by_uuid.
try:
return session.xenapi.VM.get_by_uuid(uuid)
except Exception,exn:
if verbose: print "No VM's found with a UUID of \"%s\"" %uuid
raise
# Case where the vm_name has been specified
if options.has_key("-n"):
vm_name = options["-n"]
vm_arr = session.xenapi.VM.get_by_name_label(vm_name)
# Need to make sure that we only have one result as the vm_name may
# not be unique. Average case, so do it first.
if len(vm_arr) == 1:
return vm_arr[0]
else:
if len(vm_arr) == 0:
if verbose: print "No VM's found with a name of \"%s\"" %vm_name
# NAME_INVALID used as the XenAPI throws a UUID_INVALID if it can't find
# a VM with the specified UUID. This should make the output look fairly
# consistent.
raise Exception("NAME_INVALID")
else:
if verbose: print "Multiple VM's have the name \"%s\", use UUID instead" %vm_name
raise Exception("MULTIPLE_VMS_FOUND")
# We should never get to this case as the input processing checks that either the UUID or
# the name parameter is set. Regardless of whether or not a VM is found the above if
# statements will return to the calling function (either by exception or by a reference
# to the VM).
raise Exception("VM_LOGIC_ERROR")
def main():
device_opt = [ "help", "version", "agent", "quiet", "verbose", "debug", "action",
"login", "passwd", "passwd_script", "vm_name", "test", "separator",
"no_login", "no_password", "power_timeout", "shell_timeout",
"login_timeout", "power_wait", "session_url", "uuid" ]
atexit.register(atexit_handler)
options=process_input(device_opt)
options = check_input(device_opt, options)
docs = { }
docs["shortdesc"] = "Fence agent for Citrix XenServer"
docs["longdesc"] = "fence_cxs_redhat"
show_docs(options, docs)
xenSession = connect_and_login(options)
# Operate the fencing device
result = fence_action(xenSession, options, set_power_fn, get_power_fn, get_outlet_list)
sys.exit(result)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
import sys, getopt, time, os
import pexpect, re
import telnetlib
import atexit
import __main__
## do not add code here.
#BEGIN_VERSION_GENERATION
RELEASE_VERSION="3.0.17"
BUILD_DATE="(built Thu Oct 7 07:06:21 UTC 2010)"
REDHAT_COPYRIGHT="Copyright (C) Red Hat, Inc. 2004-2010 All rights reserved."
#END_VERSION_GENERATION
LOG_MODE_VERBOSE = 100
LOG_MODE_QUIET = 0
EC_GENERIC_ERROR = 1
EC_BAD_ARGS = 2
EC_LOGIN_DENIED = 3
EC_CONNECTION_LOST = 4
EC_TIMED_OUT = 5
EC_WAITING_ON = 6
EC_WAITING_OFF = 7
EC_STATUS = 8
EC_STATUS_HMC = 9
TELNET_PATH = "/usr/bin/telnet"
SSH_PATH = "/usr/bin/ssh"
SSL_PATH = "/usr/sbin/fence_nss_wrapper"
all_opt = {
"help" : {
"getopt" : "h",
"longopt" : "help",
"help" : "-h, --help Display this help and exit",
"required" : "0",
"shortdesc" : "Display help and exit",
"order" : 54 },
"version" : {
"getopt" : "V",
"longopt" : "version",
"help" : "-V, --version Output version information and exit",
"required" : "0",
"shortdesc" : "Display version information and exit",
"order" : 53 },
"quiet" : {
"getopt" : "q",
"help" : "",
"order" : 50 },
"verbose" : {
"getopt" : "v",
"longopt" : "verbose",
"help" : "-v, --verbose Verbose mode",
"required" : "0",
"shortdesc" : "Verbose mode",
"order" : 51 },
"debug" : {
"getopt" : "D:",
"longopt" : "debug-file",
"help" : "-D, --debug-file=<debugfile> Debugging to output file",
"required" : "0",
"shortdesc" : "Write debug information to given file",
"order" : 52 },
"delay" : {
"getopt" : "f:",
"longopt" : "delay",
"help" : "--delay <seconds> Wait X seconds before fencing is started",
"required" : "0",
"shortdesc" : "Wait X seconds before fencing is started",
"default" : "0",
"order" : 200 },
"agent" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"web" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"action" : {
"getopt" : "o:",
"longopt" : "action",
"help" : "-o, --action=<action> Action: status, reboot (default), off or on",
"required" : "1",
"shortdesc" : "Fencing Action",
"default" : "reboot",
"order" : 1 },
"io_fencing" : {
"getopt" : "o:",
"longopt" : "action",
"help" : "-o, --action=<action> Action: status, enable or disable",
"required" : "1",
"shortdesc" : "Fencing Action",
"default" : "disable",
"order" : 1 },
"ipaddr" : {
"getopt" : "a:",
"longopt" : "ip",
"help" : "-a, --ip=<ip> IP address or hostname of fencing device",
"required" : "1",
"shortdesc" : "IP Address or Hostname",
"order" : 1 },
"ipport" : {
"getopt" : "u:",
"longopt" : "ipport",
"help" : "-u, --ipport=<port> TCP port to use",
"required" : "0",
"shortdesc" : "TCP port to use for connection with device",
"order" : 1 },
"login" : {
"getopt" : "l:",
"longopt" : "username",
"help" : "-l, --username=<name> Login name",
"required" : "?",
"shortdesc" : "Login Name",
"order" : 1 },
"no_login" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"no_password" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"passwd" : {
"getopt" : "p:",
"longopt" : "password",
"help" : "-p, --password=<password> Login password or passphrase",
"required" : "0",
"shortdesc" : "Login password or passphrase",
"order" : 1 },
"passwd_script" : {
"getopt" : "S:",
"longopt" : "password-script=",
"help" : "-S, --password-script=<script> Script to run to retrieve password",
"required" : "0",
"shortdesc" : "Script to retrieve password",
"order" : 1 },
"identity_file" : {
"getopt" : "k:",
"longopt" : "identity-file",
"help" : "-k, --identity-file=<filename> Identity file (private key) for ssh ",
"required" : "0",
"shortdesc" : "Identity file for ssh",
"order" : 1 },
"module_name" : {
"getopt" : "m:",
"longopt" : "module-name",
"help" : "-m, --module-name=<module> DRAC/MC module name",
"required" : "0",
"shortdesc" : "DRAC/MC module name",
"order" : 1 },
"drac_version" : {
"getopt" : "d:",
"longopt" : "drac-version",
"help" : "-d, --drac-version=<version> Force DRAC version to use",
"required" : "0",
"shortdesc" : "Force DRAC version to use",
"order" : 1 },
"hmc_version" : {
"getopt" : "H:",
"longopt" : "hmc-version",
"help" : "-H, --hmc-version=<version> Force HMC version to use: 3, 4 (default)",
"required" : "0",
"shortdesc" : "Force HMC version to use (3 or 4)",
"default" : "4",
"order" : 1 },
"ribcl" : {
"getopt" : "r:",
"longopt" : "ribcl-version",
"help" : "-r, --ribcl-version=<version> Force ribcl version to use",
"required" : "0",
"shortdesc" : "Force ribcl version to use",
"order" : 1 },
"login_eol_lf" : {
"getopt" : "",
"help" : "",
"order" : 1
},
"cmd_prompt" : {
"getopt" : "c:",
"longopt" : "command-prompt",
"help" : "-c, --command-prompt=<prompt> Force command prompt",
"shortdesc" : "Force command prompt",
"required" : "0",
"order" : 1 },
"secure" : {
"getopt" : "x",
"longopt" : "ssh",
"help" : "-x, --ssh Use ssh connection",
"shortdesc" : "SSH connection",
"required" : "0",
"order" : 1 },
"ssl" : {
"getopt" : "z",
"longopt" : "ssl",
"help" : "-z, --ssl Use ssl connection",
"required" : "0",
"shortdesc" : "SSL connection",
"order" : 1 },
"port" : {
"getopt" : "n:",
"longopt" : "plug",
"help" : "-n, --plug=<id> Physical plug number on device or\n" +
" name of virtual machine",
"required" : "1",
"shortdesc" : "Physical plug number or name of virtual machine",
"order" : 1 },
"switch" : {
"getopt" : "s:",
"longopt" : "switch",
"help" : "-s, --switch=<id> Physical switch number on device",
"required" : "0",
"shortdesc" : "Physical switch number on device",
"order" : 1 },
"partition" : {
"getopt" : "n:",
"help" : "-n <id> Name of the partition",
"required" : "0",
"shortdesc" : "Partition name",
"order" : 1 },
"managed" : {
"getopt" : "s:",
"help" : "-s <id> Name of the managed system",
"required" : "0",
"shortdesc" : "Managed system name",
"order" : 1 },
"test" : {
"getopt" : "T",
"help" : "",
"order" : 1,
"obsolete" : "use -o status instead" },
"exec" : {
"getopt" : "e:",
"longopt" : "exec",
"help" : "-e, --exec=<command> Command to execute",
"required" : "0",
"shortdesc" : "Command to execute",
"order" : 1 },
"vmware_type" : {
"getopt" : "d:",
"longopt" : "vmware_type",
"help" : "-d, --vmware_type=<type> Type of VMware to connect",
"required" : "0",
"shortdesc" : "Type of VMware to connect",
"order" : 1 },
"vmware_datacenter" : {
"getopt" : "s:",
"longopt" : "vmware-datacenter",
"help" : "-s, --vmware-datacenter=<dc> VMWare datacenter filter",
"required" : "0",
"shortdesc" : "Show only machines in specified datacenter",
"order" : 2 },
"snmp_version" : {
"getopt" : "d:",
"longopt" : "snmp-version",
"help" : "-d, --snmp-version=<ver> Specifies SNMP version to use",
"required" : "0",
"shortdesc" : "Specifies SNMP version to use (1,2c,3)",
"order" : 1 },
"community" : {
"getopt" : "c:",
"longopt" : "community",
"help" : "-c, --community=<community> Set the community string",
"required" : "0",
"shortdesc" : "Set the community string",
"order" : 1},
"snmp_auth_prot" : {
"getopt" : "b:",
"longopt" : "snmp-auth-prot",
"help" : "-b, --snmp-auth-prot=<prot> Set authentication protocol (MD5|SHA)",
"required" : "0",
"shortdesc" : "Set authentication protocol (MD5|SHA)",
"order" : 1},
"snmp_sec_level" : {
"getopt" : "E:",
"longopt" : "snmp-sec-level",
"help" : "-E, --snmp-sec-level=<level> Set security level\n"+
" (noAuthNoPriv|authNoPriv|authPriv)",
"required" : "0",
"shortdesc" : "Set security level (noAuthNoPriv|authNoPriv|authPriv)",
"order" : 1},
"snmp_priv_prot" : {
"getopt" : "B:",
"longopt" : "snmp-priv-prot",
"help" : "-B, --snmp-priv-prot=<prot> Set privacy protocol (DES|AES)",
"required" : "0",
"shortdesc" : "Set privacy protocol (DES|AES)",
"order" : 1},
"snmp_priv_passwd" : {
"getopt" : "P:",
"longopt" : "snmp-priv-passwd",
"help" : "-P, --snmp-priv-passwd=<pass> Set privacy protocol password",
"required" : "0",
"shortdesc" : "Set privacy protocol password",
"order" : 1},
"snmp_priv_passwd_script" : {
"getopt" : "R:",
"longopt" : "snmp-priv-passwd-script",
"help" : "-R, --snmp-priv-passwd-script Script to run to retrieve privacy password",
"required" : "0",
"shortdesc" : "Script to run to retrieve privacy password",
"order" : 1},
"inet4_only" : {
"getopt" : "4",
"longopt" : "inet4-only",
"help" : "-4, --inet4-only Forces agent to use IPv4 addresses only",
"required" : "0",
"shortdesc" : "Forces agent to use IPv4 addresses only",
"order" : 1 },
"inet6_only" : {
"getopt" : "6",
"longopt" : "inet6-only",
"help" : "-6, --inet6-only Forces agent to use IPv6 addresses only",
"required" : "0",
"shortdesc" : "Forces agent to use IPv6 addresses only",
"order" : 1 },
"udpport" : {
"getopt" : "u:",
"longopt" : "udpport",
"help" : "-u, --udpport UDP/TCP port to use",
"required" : "0",
"shortdesc" : "UDP/TCP port to use for connection with device",
"order" : 1},
"separator" : {
"getopt" : "C:",
"longopt" : "separator",
"help" : "-C, --separator=<char> Separator for CSV created by 'list' operation",
"default" : ",",
"required" : "0",
"shortdesc" : "Separator for CSV created by operation list",
"order" : 100 },
"login_timeout" : {
"getopt" : "y:",
"longopt" : "login-timeout",
"help" : "--login-timeout <seconds> Wait X seconds for cmd prompt after login",
"default" : "5",
"required" : "0",
"shortdesc" : "Wait X seconds for cmd prompt after login",
"order" : 200 },
"shell_timeout" : {
"getopt" : "Y:",
"longopt" : "shell-timeout",
"help" : "--shell-timeout <seconds> Wait X seconds for cmd prompt after issuing command",
"default" : "3",
"required" : "0",
"shortdesc" : "Wait X seconds for cmd prompt after issuing command",
"order" : 200 },
"power_timeout" : {
"getopt" : "g:",
"longopt" : "power-timeout",
"help" : "--power-timeout <seconds> Test X seconds for status change after ON/OFF",
"default" : "20",
"required" : "0",
"shortdesc" : "Test X seconds for status change after ON/OFF",
"order" : 200 },
"power_wait" : {
"getopt" : "G:",
"longopt" : "power-wait",
"help" : "--power-wait <seconds> Wait X seconds after issuing ON/OFF",
"default" : "0",
"required" : "0",
"shortdesc" : "Wait X seconds after issuing ON/OFF",
"order" : 200 },
"missing_as_off" : {
"getopt" : "M",
"longopt" : "missing-as-off",
"help" : "--missing-as-off Missing port returns OFF instead of failure",
"required" : "0",
"shortdesc" : "Missing port returns OFF instead of failure",
"order" : 200 },
"retry_on" : {
"getopt" : "F:",
"longopt" : "retry-on",
"help" : "--retry-on <attempts> Count of attempts to retry power on",
"default" : "1",
"required" : "0",
"shortdesc" : "Count of attempts to retry power on",
"order" : 200 },
"session_url" : {
"getopt" : "s:",
"longopt" : "session-url",
"help" : "-s, --session-url URL to connect to XenServer on.",
"required" : "1",
"shortdesc" : "The URL of the XenServer host.",
"order" : 1},
"uuid" : {
"getopt" : "u:",
"longopt" : "uuid",
"help" : "-u, --uuid UUID of the VM to fence.",
"required" : "1",
"shortdesc" : "The UUID of the VM to fence.",
"order" : 1}
}
common_opt = [ "retry_on", "delay" ]
class fspawn(pexpect.spawn):
def log_expect(self, options, pattern, timeout):
result = self.expect(pattern, timeout)
if options["log"] >= LOG_MODE_VERBOSE:
options["debug_fh"].write(self.before + self.after)
return result
def atexit_handler():
try:
sys.stdout.close()
os.close(1)
except IOError:
sys.stderr.write("%s failed to close standard output\n"%(sys.argv[0]))
sys.exit(EC_GENERIC_ERROR)
def version(command, release, build_date, copyright_notice):
print command, " ", release, " ", build_date
if len(copyright_notice) > 0:
print copyright_notice
def fail_usage(message = ""):
if len(message) > 0:
sys.stderr.write(message+"\n")
sys.stderr.write("Please use '-h' for usage\n")
sys.exit(EC_GENERIC_ERROR)
def fail(error_code):
message = {
EC_LOGIN_DENIED : "Unable to connect/login to fencing device",
EC_CONNECTION_LOST : "Connection lost",
EC_TIMED_OUT : "Connection timed out",
EC_WAITING_ON : "Failed: Timed out waiting to power ON",
EC_WAITING_OFF : "Failed: Timed out waiting to power OFF",
EC_STATUS : "Failed: Unable to obtain correct plug status or plug is not available",
EC_STATUS_HMC : "Failed: Either unable to obtaion correct plug status, partition is not available or incorrect HMC version used"
}[error_code] + "\n"
sys.stderr.write(message)
sys.exit(EC_GENERIC_ERROR)
def usage(avail_opt):
global all_opt
print "Usage:"
print "\t" + os.path.basename(sys.argv[0]) + " [options]"
print "Options:"
sorted_list = [ (key, all_opt[key]) for key in avail_opt ]
sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"]))
for key, value in sorted_list:
if len(value["help"]) != 0:
print " " + value["help"]
def metadata(avail_opt, options, docs):
global all_opt
sorted_list = [ (key, all_opt[key]) for key in avail_opt ]
sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"]))
print "<?xml version=\"1.0\" ?>"
print "<resource-agent name=\"" + os.path.basename(sys.argv[0]) + "\" shortdesc=\"" + docs["shortdesc"] + "\" >"
print "<longdesc>" + docs["longdesc"] + "</longdesc>"
if docs.has_key("vendorurl"):
print "<vendor-url>" + docs["vendorurl"] + "</vendor-url>"
print "<parameters>"
for option, value in sorted_list:
if all_opt[option].has_key("shortdesc"):
print "\t<parameter name=\"" + option + "\" unique=\"1\" required=\"" + all_opt[option]["required"] + "\">"
default = ""
if all_opt[option].has_key("default"):
default = "default=\""+str(all_opt[option]["default"])+"\""
elif options.has_key("-" + all_opt[option]["getopt"][:-1]):
if options["-" + all_opt[option]["getopt"][:-1]]:
try:
default = "default=\"" + options["-" + all_opt[option]["getopt"][:-1]] + "\""
except TypeError:
## @todo/@note: Currently there is no clean way how to handle lists
## we can create a string from it but we can't set it on command line
default = "default=\"" + str(options["-" + all_opt[option]["getopt"][:-1]]) +"\""
elif options.has_key("-" + all_opt[option]["getopt"]):
default = "default=\"true\" "
mixed = all_opt[option]["help"]
## split it between option and help text
res = re.compile("^(.*--\S+)\s+", re.IGNORECASE | re.S).search(mixed)
if (None != res):
mixed = res.group(1)
mixed = mixed.replace("<", "<").replace(">", ">")
print "\t\t<getopt mixed=\"" + mixed + "\" />"
if all_opt[option]["getopt"].count(":") > 0:
print "\t\t<content type=\"string\" "+default+" />"
else:
print "\t\t<content type=\"boolean\" "+default+" />"
print "\t\t<shortdesc lang=\"en\">" + all_opt[option]["shortdesc"] + "</shortdesc>"
print "\t</parameter>"
print "</parameters>"
print "<actions>"
print "\t<action name=\"on\" />"
print "\t<action name=\"off\" />"
print "\t<action name=\"reboot\" />"
print "\t<action name=\"status\" />"
print "\t<action name=\"list\" />"
print "\t<action name=\"monitor\" />"
print "\t<action name=\"metadata\" />"
print "</actions>"
print "</resource-agent>"
def process_input(avail_opt):
global all_opt
global common_opt
##
## Add options which are available for every fence agent
#####
avail_opt.extend(common_opt)
##
## Set standard environment
#####
os.putenv("LANG", "C")
os.putenv("LC_ALL", "C")
##
## Prepare list of options for getopt
#####
getopt_string = ""
longopt_list = [ ]
for k in avail_opt:
if all_opt.has_key(k):
getopt_string += all_opt[k]["getopt"]
else:
fail_usage("Parse error: unknown option '"+k+"'")
if all_opt.has_key(k) and all_opt[k].has_key("longopt"):
if all_opt[k]["getopt"].endswith(":"):
longopt_list.append(all_opt[k]["longopt"] + "=")
else:
longopt_list.append(all_opt[k]["longopt"])
## Compatibility layer
if avail_opt.count("module_name") == 1:
getopt_string += "n:"
longopt_list.append("plug=")
##
## Read options from command line or standard input
#####
if len(sys.argv) > 1:
try:
opt, args = getopt.gnu_getopt(sys.argv[1:], getopt_string, longopt_list)
except getopt.GetoptError, error:
fail_usage("Parse error: " + error.msg)
## Transform longopt to short one which are used in fencing agents
#####
old_opt = opt
opt = { }
for o in dict(old_opt).keys():
if o.startswith("--"):
for x in all_opt.keys():
if all_opt[x].has_key("longopt") and "--" + all_opt[x]["longopt"] == o:
opt["-" + all_opt[x]["getopt"].rstrip(":")] = dict(old_opt)[o]
else:
opt[o] = dict(old_opt)[o]
## Compatibility Layer
#####
z = dict(opt)
if z.has_key("-T") == 1:
z["-o"] = "status"
if z.has_key("-n") == 1:
z["-m"] = z["-n"]
opt = z
##
#####
else:
opt = { }
name = ""
for line in sys.stdin.readlines():
line = line.strip()
if ((line.startswith("#")) or (len(line) == 0)):
continue
(name, value) = (line + "=").split("=", 1)
value = value[:-1]
## Compatibility Layer
######
if name == "blade":
name = "port"
elif name == "option":
name = "action"
elif name == "fm":
name = "port"
elif name == "hostname":
name = "ipaddr"
elif name == "modulename":
name = "module_name"
elif name == "action" and 1 == avail_opt.count("io_fencing"):
name = "io_fencing"
elif name == "port" and 1 == avail_opt.count("drac_version"):
name = "module_name"
##
######
if avail_opt.count(name) == 0:
sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n")
continue
if all_opt[name]["getopt"].endswith(":"):
opt["-"+all_opt[name]["getopt"].rstrip(":")] = value
elif ((value == "1") or (value.lower() == "yes")):
opt["-"+all_opt[name]["getopt"]] = "1"
return opt
##
## This function checks input and answers if we want to have same answers
## in each of the fencing agents. It looks for possible errors and run
## password script to set a correct password
######
def check_input(device_opt, opt):
global all_opt
global common_opt
##
## Add options which are available for every fence agent
#####
device_opt.extend([x for x in common_opt if device_opt.count(x) == 0])
options = dict(opt)
options["device_opt"] = device_opt
## Set requirements that should be included in metadata
#####
if device_opt.count("login") and device_opt.count("no_login") == 0:
all_opt["login"]["required"] = "1"
else:
all_opt["login"]["required"] = "0"
## In special cases (show help, metadata or version) we don't need to check anything
#####
if options.has_key("-h") or options.has_key("-V") or (options.has_key("-o") and options["-o"].lower() == "metadata"):
return options;
## Set default values
#####
for opt in device_opt:
if all_opt[opt].has_key("default"):
getopt = "-" + all_opt[opt]["getopt"].rstrip(":")
if 0 == options.has_key(getopt):
options[getopt] = all_opt[opt]["default"]
options["-o"]=options["-o"].lower()
if options.has_key("-v"):
options["log"] = LOG_MODE_VERBOSE
else:
options["log"] = LOG_MODE_QUIET
if 0 == device_opt.count("io_fencing"):
if 0 == ["on", "off", "reboot", "status", "list", "monitor"].count(options["-o"].lower()):
fail_usage("Failed: Unrecognised action '" + options["-o"] + "'")
else:
if 0 == ["enable", "disable", "status", "list", "monitor"].count(options["-o"].lower()):
fail_usage("Failed: Unrecognised action '" + options["-o"] + "'")
if (0 == options.has_key("-l")) and device_opt.count("login") and (device_opt.count("no_login") == 0):
fail_usage("Failed: You have to set login name")
if 0 == options.has_key("-a") and 0 == options.has_key("-s"):
fail_usage("Failed: You have to enter fence address")
if (device_opt.count("no_password") == 0):
if 0 == device_opt.count("identity_file"):
if 0 == (options.has_key("-p") or options.has_key("-S")):
fail_usage("Failed: You have to enter password or password script")
else:
if 0 == (options.has_key("-p") or options.has_key("-S") or options.has_key("-k")):
fail_usage("Failed: You have to enter password, password script or identity file")
if 0 == options.has_key("-x") and 1 == options.has_key("-k"):
fail_usage("Failed: You have to use identity file together with ssh connection (-x)")
if 1 == options.has_key("-k"):
if 0 == os.path.isfile(options["-k"]):
fail_usage("Failed: Identity file " + options["-k"] + " does not exist")
if (0 == ["list", "monitor"].count(options["-o"].lower())) and (0 == options.has_key("-n")) and (device_opt.count("port")):
fail_usage("Failed: You have to enter plug number")
if options.has_key("-S"):
options["-p"] = os.popen(options["-S"]).read().rstrip()
if options.has_key("-D"):
try:
options["debug_fh"] = file (options["-D"], "w")
except IOError:
fail_usage("Failed: Unable to create file "+options["-D"])
if options.has_key("-v") and options.has_key("debug_fh") == 0:
options["debug_fh"] = sys.stderr
if options.has_key("-R"):
options["-P"] = os.popen(options["-R"]).read().rstrip()
if options.has_key("-u") == False:
if options.has_key("-x"):
options["-u"] = 22
elif options.has_key("-z"):
options["-u"] = 443
elif device_opt.count("web"):
options["-u"] = 80
else:
options["-u"] = 23
return options
def wait_power_status(tn, options, get_power_fn):
for dummy in xrange(int(options["-g"])):
if get_power_fn(tn, options) != options["-o"]:
time.sleep(1)
else:
return 1
return 0
def show_docs(options, docs = None):
device_opt = options["device_opt"]
if docs == None:
docs = { }
docs["shortdesc"] = "Fence agent"
docs["longdesc"] = ""
## Process special options (and exit)
#####
if options.has_key("-h"):
usage(device_opt)
sys.exit(0)
if options.has_key("-o") and options["-o"].lower() == "metadata":
metadata(device_opt, options, docs)
sys.exit(0)
if options.has_key("-V"):
print __main__.RELEASE_VERSION, __main__.BUILD_DATE
print __main__.REDHAT_COPYRIGHT
sys.exit(0)
def fence_action(tn, options, set_power_fn, get_power_fn, get_outlet_list = None):
result = 0
## Process options that manipulate fencing device
#####
if (options["-o"] == "list") and (0 == options["device_opt"].count("port")) and (0 == options["device_opt"].count("partition")) and 0:
print "N/A"
return
elif (options["-o"] == "list" and get_outlet_list == None):
## @todo: exception?
## This is just temporal solution, we will remove default value
## None as soon as all existing agent will support this operation
print "NOTICE: List option is not working on this device yet"
return
elif (options["-o"] == "list") or ((options["-o"] == "monitor") and 1 == options["device_opt"].count("port")):
outlets = get_outlet_list(tn, options)
## keys can be numbers (port numbers) or strings (names of VM)
for o in outlets.keys():
(alias, status) = outlets[o]
if options["-o"] != "monitor":
print o + options["-C"] + alias
return
if options["-o"] in ["off", "reboot"]:
time.sleep(int(options["-f"]))
status = get_power_fn(tn, options)
if status != "on" and status != "off":
fail(EC_STATUS)
if options["-o"] == "enable":
options["-o"] = "on"
if options["-o"] == "disable":
options["-o"] = "off"
if options["-o"] == "on":
if status == "on":
print "Success: Already ON"
else:
power_on = False
for i in range(1,1 + int(options["-F"])):
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn):
power_on = True
break
if power_on:
print "Success: Powered ON"
else:
fail(EC_WAITING_ON)
elif options["-o"] == "off":
if status == "off":
print "Success: Already OFF"
else:
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn):
print "Success: Powered OFF"
else:
fail(EC_WAITING_OFF)
elif options["-o"] == "reboot":
if status != "off":
options["-o"] = "off"
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn) == 0:
fail(EC_WAITING_OFF)
options["-o"] = "on"
power_on = False
for i in range(1,1 + int(options["-F"])):
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn) == 1:
power_on = True
break
if power_on == False:
# this should not fail as not was fenced succesfully
sys.stderr.write('Timed out waiting to power ON\n')
print "Success: Rebooted"
elif options["-o"] == "status":
print "Status: " + status.upper()
if status.upper() == "OFF":
result = 2
elif options["-o"] == "monitor":
1
return result
def fence_login(options):
force_ipvx=""
if (options.has_key("-6")):
force_ipvx="-6 "
if (options.has_key("-4")):
force_ipvx="-4 "
if (options["device_opt"].count("login_eol_lf")):
login_eol = "\n"
else:
login_eol = "\r\n"
try:
re_login = re.compile("(login\s*: )|(Login Name: )|(username: )|(User Name :)", re.IGNORECASE)
re_pass = re.compile("password", re.IGNORECASE)
if options.has_key("-z"):
command = '%s %s %s %s' % (SSL_PATH, force_ipvx, options["-a"], options["-u"])
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
## SSL telnet is part of the fencing package
sys.stderr.write(str(ex) + "\n")
sys.exit(EC_GENERIC_ERROR)
elif options.has_key("-x") and 0 == options.has_key("-k"):
command = '%s %s %s@%s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-u"])
if options.has_key("ssh_options"):
command += ' ' + options["ssh_options"]
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
if options.has_key("telnet_over_ssh"):
#This is for stupid ssh servers (like ALOM) which behave more like telnet (ignore name and display login prompt)
result = conn.log_expect(options, [ re_login, "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"]))
if result == 1:
conn.sendline("yes") # Host identity confirm
conn.log_expect(options, re_login, int(options["-y"]))
conn.sendline(options["-l"])
conn.log_expect(options, re_pass, int(options["-y"]))
else:
result = conn.log_expect(options, [ "ssword:", "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"]))
if result == 1:
conn.sendline("yes")
conn.log_expect(options, "ssword:", int(options["-y"]))
conn.sendline(options["-p"])
conn.log_expect(options, options["-c"], int(options["-y"]))
elif options.has_key("-x") and 1 == options.has_key("-k"):
command = '%s %s %s@%s -i %s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-k"], options["-u"])
if options.has_key("ssh_options"):
command += ' ' + options["ssh_options"]
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
result = conn.log_expect(options, [ options["-c"], "Are you sure you want to continue connecting (yes/no)?", "Enter passphrase for key '"+options["-k"]+"':" ], int(options["-y"]))
if result == 1:
conn.sendline("yes")
conn.log_expect(options, [ options["-c"], "Enter passphrase for key '"+options["-k"]+"':"] , int(options["-y"]))
if result != 0:
if options.has_key("-p"):
conn.sendline(options["-p"])
conn.log_expect(options, options["-c"], int(options["-y"]))
else:
fail_usage("Failed: You have to enter passphrase (-p) for identity file")
else:
try:
conn = fspawn(TELNET_PATH)
conn.send("set binary\n")
conn.send("open %s -%s\n"%(options["-a"], options["-u"]))
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
conn.log_expect(options, re_login, int(options["-y"]))
conn.send(options["-l"] + login_eol)
conn.log_expect(options, re_pass, int(options["-Y"]))
conn.send(options["-p"] + login_eol)
conn.log_expect(options, options["-c"], int(options["-Y"]))
except pexpect.EOF:
fail(EC_LOGIN_DENIED)
except pexpect.TIMEOUT:
fail(EC_LOGIN_DENIED)
return conn
| Python |
#!/usr/bin/python
# It's only just begun...
# Current status: completely unusable, try the fence_cxs.py script for the moment. This Red
# Hat compatible version is just in its' infancy.
# Copyright 2011 Matt Clark
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
from fencing import *
import XenAPI
EC_BAD_SESSION = 1
# Find the status of the port given in the -u flag of options.
def get_power_fn(session, options):
uuid = options["-u"].lower()
try:
# Get a reference to the vm specified in the UUID parameter
vm = session.xenapi.VM.get_by_uuid(uuid)
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm);
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
status = record["power_state"]
print "UUID:", record["uuid"], "NAME:", record["name_label"], "POWER STATUS:", record["power_state"]
# Note that the VM can be in the following states (from the XenAPI document)
# Halted: VM is offline and not using any resources.
# Paused: All resources have been allocated but the VM itself is paused and its vCPUs are not running
# Running: Running
# Paused: VM state has been saved to disk and it is nolonger running. Note that disks remain in-use while
# We want to make sure that we only return the status "off" if the machine is actually halted as the status
# is checked before a fencing action. Only when the machine is Halted is it not consuming resources which
# may include whatever you are trying to protect with this fencing action.
return (status=="Halted" and "off" or "on")
except Exception, exn:
print str(exn)
return "Error"
# Set the state of the port given in the -u flag of options.
def set_power_fn(session, options):
uuid = options["-u"].lower()
action = options["-o"].lower()
try:
# Get a reference to the vm specified in the UUID parameter
vm = session.xenapi.VM.get_by_uuid(uuid)
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm)
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
# Start the VM
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
# Force shutdown the VM
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
# Force reboot the VM
session.xenapi.VM.hard_reboot(vm)
except Exception, exn:
print str(exn);
# Function to populate an array of virtual machines and their status
def get_outlet_list(session, options):
result = {}
try:
# Return an array of all the VM's on the host
vms = session.xenapi.VM.get_all()
for vm in vms:
# Query the VM for its' associated parameters
record = session.xenapi.VM.get_record(vm);
# Check that we are not trying to manipulate a template or a control
# domain as they show up as VM's with specific properties.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
uuid = record["uuid"]
status = record["power_state"]
result[uuid] = (name, status)
print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
return result
# Function to initiate the XenServer session via the XenAPI library.
def connect_and_login(options):
url = options["-s"]
username = options["-l"]
password = options["-p"]
try:
# Create the XML RPC session to the specified URL.
session = XenAPI.Session(url);
# Login using the supplied credentials.
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
# http://sources.redhat.com/cluster/wiki/FenceAgentAPI says that for no connectivity
# the exit value should be 1. It doesn't say anything about failed logins, so
# until I hear otherwise it is best to keep this exit the same to make sure that
# anything calling this script (that uses the same information in the web page
# above) knows that this is an error condition, not a msg signifying a down port.
sys.exit(EC_BAD_SESSION);
return session;
def main():
device_opt = [ "help", "version", "agent", "quiet", "verbose", "debug", "action",
"login", "passwd", "passwd_script", "test", "separator", "no_login",
"no_password", "power_timeout", "shell_timeout", "login_timeout",
"power_wait", "session_url", "uuid" ]
atexit.register(atexit_handler)
options=process_input(device_opt)
options = check_input(device_opt, options)
docs = { }
docs["shortdesc"] = "Fence agent for Citrix XenServer"
docs["longdesc"] = "fence_cxs_redhat"
show_docs(options, docs)
xenSession = connect_and_login(options)
# Operate the fencing device
result = fence_action(xenSession, options, set_power_fn, get_power_fn, get_outlet_list)
sys.exit(result)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
import sys, getopt, time, os
import pexpect, re
import telnetlib
import atexit
import __main__
## do not add code here.
#BEGIN_VERSION_GENERATION
RELEASE_VERSION="3.0.17"
BUILD_DATE="(built Thu Oct 7 07:06:21 UTC 2010)"
REDHAT_COPYRIGHT="Copyright (C) Red Hat, Inc. 2004-2010 All rights reserved."
#END_VERSION_GENERATION
LOG_MODE_VERBOSE = 100
LOG_MODE_QUIET = 0
EC_GENERIC_ERROR = 1
EC_BAD_ARGS = 2
EC_LOGIN_DENIED = 3
EC_CONNECTION_LOST = 4
EC_TIMED_OUT = 5
EC_WAITING_ON = 6
EC_WAITING_OFF = 7
EC_STATUS = 8
EC_STATUS_HMC = 9
TELNET_PATH = "/usr/bin/telnet"
SSH_PATH = "/usr/bin/ssh"
SSL_PATH = "/usr/sbin/fence_nss_wrapper"
all_opt = {
"help" : {
"getopt" : "h",
"longopt" : "help",
"help" : "-h, --help Display this help and exit",
"required" : "0",
"shortdesc" : "Display help and exit",
"order" : 54 },
"version" : {
"getopt" : "V",
"longopt" : "version",
"help" : "-V, --version Output version information and exit",
"required" : "0",
"shortdesc" : "Display version information and exit",
"order" : 53 },
"quiet" : {
"getopt" : "q",
"help" : "",
"order" : 50 },
"verbose" : {
"getopt" : "v",
"longopt" : "verbose",
"help" : "-v, --verbose Verbose mode",
"required" : "0",
"shortdesc" : "Verbose mode",
"order" : 51 },
"debug" : {
"getopt" : "D:",
"longopt" : "debug-file",
"help" : "-D, --debug-file=<debugfile> Debugging to output file",
"required" : "0",
"shortdesc" : "Write debug information to given file",
"order" : 52 },
"delay" : {
"getopt" : "f:",
"longopt" : "delay",
"help" : "--delay <seconds> Wait X seconds before fencing is started",
"required" : "0",
"shortdesc" : "Wait X seconds before fencing is started",
"default" : "0",
"order" : 200 },
"agent" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"web" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"action" : {
"getopt" : "o:",
"longopt" : "action",
"help" : "-o, --action=<action> Action: status, reboot (default), off or on",
"required" : "1",
"shortdesc" : "Fencing Action",
"default" : "reboot",
"order" : 1 },
"io_fencing" : {
"getopt" : "o:",
"longopt" : "action",
"help" : "-o, --action=<action> Action: status, enable or disable",
"required" : "1",
"shortdesc" : "Fencing Action",
"default" : "disable",
"order" : 1 },
"ipaddr" : {
"getopt" : "a:",
"longopt" : "ip",
"help" : "-a, --ip=<ip> IP address or hostname of fencing device",
"required" : "1",
"shortdesc" : "IP Address or Hostname",
"order" : 1 },
"ipport" : {
"getopt" : "u:",
"longopt" : "ipport",
"help" : "-u, --ipport=<port> TCP port to use",
"required" : "0",
"shortdesc" : "TCP port to use for connection with device",
"order" : 1 },
"login" : {
"getopt" : "l:",
"longopt" : "username",
"help" : "-l, --username=<name> Login name",
"required" : "?",
"shortdesc" : "Login Name",
"order" : 1 },
"no_login" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"no_password" : {
"getopt" : "",
"help" : "",
"order" : 1 },
"passwd" : {
"getopt" : "p:",
"longopt" : "password",
"help" : "-p, --password=<password> Login password or passphrase",
"required" : "0",
"shortdesc" : "Login password or passphrase",
"order" : 1 },
"passwd_script" : {
"getopt" : "S:",
"longopt" : "password-script=",
"help" : "-S, --password-script=<script> Script to run to retrieve password",
"required" : "0",
"shortdesc" : "Script to retrieve password",
"order" : 1 },
"identity_file" : {
"getopt" : "k:",
"longopt" : "identity-file",
"help" : "-k, --identity-file=<filename> Identity file (private key) for ssh ",
"required" : "0",
"shortdesc" : "Identity file for ssh",
"order" : 1 },
"module_name" : {
"getopt" : "m:",
"longopt" : "module-name",
"help" : "-m, --module-name=<module> DRAC/MC module name",
"required" : "0",
"shortdesc" : "DRAC/MC module name",
"order" : 1 },
"drac_version" : {
"getopt" : "d:",
"longopt" : "drac-version",
"help" : "-d, --drac-version=<version> Force DRAC version to use",
"required" : "0",
"shortdesc" : "Force DRAC version to use",
"order" : 1 },
"hmc_version" : {
"getopt" : "H:",
"longopt" : "hmc-version",
"help" : "-H, --hmc-version=<version> Force HMC version to use: 3, 4 (default)",
"required" : "0",
"shortdesc" : "Force HMC version to use (3 or 4)",
"default" : "4",
"order" : 1 },
"ribcl" : {
"getopt" : "r:",
"longopt" : "ribcl-version",
"help" : "-r, --ribcl-version=<version> Force ribcl version to use",
"required" : "0",
"shortdesc" : "Force ribcl version to use",
"order" : 1 },
"login_eol_lf" : {
"getopt" : "",
"help" : "",
"order" : 1
},
"cmd_prompt" : {
"getopt" : "c:",
"longopt" : "command-prompt",
"help" : "-c, --command-prompt=<prompt> Force command prompt",
"shortdesc" : "Force command prompt",
"required" : "0",
"order" : 1 },
"secure" : {
"getopt" : "x",
"longopt" : "ssh",
"help" : "-x, --ssh Use ssh connection",
"shortdesc" : "SSH connection",
"required" : "0",
"order" : 1 },
"ssl" : {
"getopt" : "z",
"longopt" : "ssl",
"help" : "-z, --ssl Use ssl connection",
"required" : "0",
"shortdesc" : "SSL connection",
"order" : 1 },
"port" : {
"getopt" : "n:",
"longopt" : "plug",
"help" : "-n, --plug=<id> Physical plug number on device or\n" +
" name of virtual machine",
"required" : "1",
"shortdesc" : "Physical plug number or name of virtual machine",
"order" : 1 },
"switch" : {
"getopt" : "s:",
"longopt" : "switch",
"help" : "-s, --switch=<id> Physical switch number on device",
"required" : "0",
"shortdesc" : "Physical switch number on device",
"order" : 1 },
"partition" : {
"getopt" : "n:",
"help" : "-n <id> Name of the partition",
"required" : "0",
"shortdesc" : "Partition name",
"order" : 1 },
"managed" : {
"getopt" : "s:",
"help" : "-s <id> Name of the managed system",
"required" : "0",
"shortdesc" : "Managed system name",
"order" : 1 },
"test" : {
"getopt" : "T",
"help" : "",
"order" : 1,
"obsolete" : "use -o status instead" },
"exec" : {
"getopt" : "e:",
"longopt" : "exec",
"help" : "-e, --exec=<command> Command to execute",
"required" : "0",
"shortdesc" : "Command to execute",
"order" : 1 },
"vmware_type" : {
"getopt" : "d:",
"longopt" : "vmware_type",
"help" : "-d, --vmware_type=<type> Type of VMware to connect",
"required" : "0",
"shortdesc" : "Type of VMware to connect",
"order" : 1 },
"vmware_datacenter" : {
"getopt" : "s:",
"longopt" : "vmware-datacenter",
"help" : "-s, --vmware-datacenter=<dc> VMWare datacenter filter",
"required" : "0",
"shortdesc" : "Show only machines in specified datacenter",
"order" : 2 },
"snmp_version" : {
"getopt" : "d:",
"longopt" : "snmp-version",
"help" : "-d, --snmp-version=<ver> Specifies SNMP version to use",
"required" : "0",
"shortdesc" : "Specifies SNMP version to use (1,2c,3)",
"order" : 1 },
"community" : {
"getopt" : "c:",
"longopt" : "community",
"help" : "-c, --community=<community> Set the community string",
"required" : "0",
"shortdesc" : "Set the community string",
"order" : 1},
"snmp_auth_prot" : {
"getopt" : "b:",
"longopt" : "snmp-auth-prot",
"help" : "-b, --snmp-auth-prot=<prot> Set authentication protocol (MD5|SHA)",
"required" : "0",
"shortdesc" : "Set authentication protocol (MD5|SHA)",
"order" : 1},
"snmp_sec_level" : {
"getopt" : "E:",
"longopt" : "snmp-sec-level",
"help" : "-E, --snmp-sec-level=<level> Set security level\n"+
" (noAuthNoPriv|authNoPriv|authPriv)",
"required" : "0",
"shortdesc" : "Set security level (noAuthNoPriv|authNoPriv|authPriv)",
"order" : 1},
"snmp_priv_prot" : {
"getopt" : "B:",
"longopt" : "snmp-priv-prot",
"help" : "-B, --snmp-priv-prot=<prot> Set privacy protocol (DES|AES)",
"required" : "0",
"shortdesc" : "Set privacy protocol (DES|AES)",
"order" : 1},
"snmp_priv_passwd" : {
"getopt" : "P:",
"longopt" : "snmp-priv-passwd",
"help" : "-P, --snmp-priv-passwd=<pass> Set privacy protocol password",
"required" : "0",
"shortdesc" : "Set privacy protocol password",
"order" : 1},
"snmp_priv_passwd_script" : {
"getopt" : "R:",
"longopt" : "snmp-priv-passwd-script",
"help" : "-R, --snmp-priv-passwd-script Script to run to retrieve privacy password",
"required" : "0",
"shortdesc" : "Script to run to retrieve privacy password",
"order" : 1},
"inet4_only" : {
"getopt" : "4",
"longopt" : "inet4-only",
"help" : "-4, --inet4-only Forces agent to use IPv4 addresses only",
"required" : "0",
"shortdesc" : "Forces agent to use IPv4 addresses only",
"order" : 1 },
"inet6_only" : {
"getopt" : "6",
"longopt" : "inet6-only",
"help" : "-6, --inet6-only Forces agent to use IPv6 addresses only",
"required" : "0",
"shortdesc" : "Forces agent to use IPv6 addresses only",
"order" : 1 },
"udpport" : {
"getopt" : "u:",
"longopt" : "udpport",
"help" : "-u, --udpport UDP/TCP port to use",
"required" : "0",
"shortdesc" : "UDP/TCP port to use for connection with device",
"order" : 1},
"separator" : {
"getopt" : "C:",
"longopt" : "separator",
"help" : "-C, --separator=<char> Separator for CSV created by 'list' operation",
"default" : ",",
"required" : "0",
"shortdesc" : "Separator for CSV created by operation list",
"order" : 100 },
"login_timeout" : {
"getopt" : "y:",
"longopt" : "login-timeout",
"help" : "--login-timeout <seconds> Wait X seconds for cmd prompt after login",
"default" : "5",
"required" : "0",
"shortdesc" : "Wait X seconds for cmd prompt after login",
"order" : 200 },
"shell_timeout" : {
"getopt" : "Y:",
"longopt" : "shell-timeout",
"help" : "--shell-timeout <seconds> Wait X seconds for cmd prompt after issuing command",
"default" : "3",
"required" : "0",
"shortdesc" : "Wait X seconds for cmd prompt after issuing command",
"order" : 200 },
"power_timeout" : {
"getopt" : "g:",
"longopt" : "power-timeout",
"help" : "--power-timeout <seconds> Test X seconds for status change after ON/OFF",
"default" : "20",
"required" : "0",
"shortdesc" : "Test X seconds for status change after ON/OFF",
"order" : 200 },
"power_wait" : {
"getopt" : "G:",
"longopt" : "power-wait",
"help" : "--power-wait <seconds> Wait X seconds after issuing ON/OFF",
"default" : "0",
"required" : "0",
"shortdesc" : "Wait X seconds after issuing ON/OFF",
"order" : 200 },
"missing_as_off" : {
"getopt" : "M",
"longopt" : "missing-as-off",
"help" : "--missing-as-off Missing port returns OFF instead of failure",
"required" : "0",
"shortdesc" : "Missing port returns OFF instead of failure",
"order" : 200 },
"retry_on" : {
"getopt" : "F:",
"longopt" : "retry-on",
"help" : "--retry-on <attempts> Count of attempts to retry power on",
"default" : "1",
"required" : "0",
"shortdesc" : "Count of attempts to retry power on",
"order" : 200 },
"session_url" : {
"getopt" : "s:",
"longopt" : "session-url",
"help" : "-s, --session-url URL to connect to XenServer on.",
"required" : "1",
"shortdesc" : "The URL of the XenServer host.",
"order" : 1},
"uuid" : {
"getopt" : "u:",
"longopt" : "uuid",
"help" : "-u, --uuid UUID of the VM to fence.",
"required" : "1",
"shortdesc" : "The UUID of the VM to fence.",
"order" : 1}
}
common_opt = [ "retry_on", "delay" ]
class fspawn(pexpect.spawn):
def log_expect(self, options, pattern, timeout):
result = self.expect(pattern, timeout)
if options["log"] >= LOG_MODE_VERBOSE:
options["debug_fh"].write(self.before + self.after)
return result
def atexit_handler():
try:
sys.stdout.close()
os.close(1)
except IOError:
sys.stderr.write("%s failed to close standard output\n"%(sys.argv[0]))
sys.exit(EC_GENERIC_ERROR)
def version(command, release, build_date, copyright_notice):
print command, " ", release, " ", build_date
if len(copyright_notice) > 0:
print copyright_notice
def fail_usage(message = ""):
if len(message) > 0:
sys.stderr.write(message+"\n")
sys.stderr.write("Please use '-h' for usage\n")
sys.exit(EC_GENERIC_ERROR)
def fail(error_code):
message = {
EC_LOGIN_DENIED : "Unable to connect/login to fencing device",
EC_CONNECTION_LOST : "Connection lost",
EC_TIMED_OUT : "Connection timed out",
EC_WAITING_ON : "Failed: Timed out waiting to power ON",
EC_WAITING_OFF : "Failed: Timed out waiting to power OFF",
EC_STATUS : "Failed: Unable to obtain correct plug status or plug is not available",
EC_STATUS_HMC : "Failed: Either unable to obtaion correct plug status, partition is not available or incorrect HMC version used"
}[error_code] + "\n"
sys.stderr.write(message)
sys.exit(EC_GENERIC_ERROR)
def usage(avail_opt):
global all_opt
print "Usage:"
print "\t" + os.path.basename(sys.argv[0]) + " [options]"
print "Options:"
sorted_list = [ (key, all_opt[key]) for key in avail_opt ]
sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"]))
for key, value in sorted_list:
if len(value["help"]) != 0:
print " " + value["help"]
def metadata(avail_opt, options, docs):
global all_opt
sorted_list = [ (key, all_opt[key]) for key in avail_opt ]
sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"]))
print "<?xml version=\"1.0\" ?>"
print "<resource-agent name=\"" + os.path.basename(sys.argv[0]) + "\" shortdesc=\"" + docs["shortdesc"] + "\" >"
print "<longdesc>" + docs["longdesc"] + "</longdesc>"
if docs.has_key("vendorurl"):
print "<vendor-url>" + docs["vendorurl"] + "</vendor-url>"
print "<parameters>"
for option, value in sorted_list:
if all_opt[option].has_key("shortdesc"):
print "\t<parameter name=\"" + option + "\" unique=\"1\" required=\"" + all_opt[option]["required"] + "\">"
default = ""
if all_opt[option].has_key("default"):
default = "default=\""+str(all_opt[option]["default"])+"\""
elif options.has_key("-" + all_opt[option]["getopt"][:-1]):
if options["-" + all_opt[option]["getopt"][:-1]]:
try:
default = "default=\"" + options["-" + all_opt[option]["getopt"][:-1]] + "\""
except TypeError:
## @todo/@note: Currently there is no clean way how to handle lists
## we can create a string from it but we can't set it on command line
default = "default=\"" + str(options["-" + all_opt[option]["getopt"][:-1]]) +"\""
elif options.has_key("-" + all_opt[option]["getopt"]):
default = "default=\"true\" "
mixed = all_opt[option]["help"]
## split it between option and help text
res = re.compile("^(.*--\S+)\s+", re.IGNORECASE | re.S).search(mixed)
if (None != res):
mixed = res.group(1)
mixed = mixed.replace("<", "<").replace(">", ">")
print "\t\t<getopt mixed=\"" + mixed + "\" />"
if all_opt[option]["getopt"].count(":") > 0:
print "\t\t<content type=\"string\" "+default+" />"
else:
print "\t\t<content type=\"boolean\" "+default+" />"
print "\t\t<shortdesc lang=\"en\">" + all_opt[option]["shortdesc"] + "</shortdesc>"
print "\t</parameter>"
print "</parameters>"
print "<actions>"
print "\t<action name=\"on\" />"
print "\t<action name=\"off\" />"
print "\t<action name=\"reboot\" />"
print "\t<action name=\"status\" />"
print "\t<action name=\"list\" />"
print "\t<action name=\"monitor\" />"
print "\t<action name=\"metadata\" />"
print "</actions>"
print "</resource-agent>"
def process_input(avail_opt):
global all_opt
global common_opt
##
## Add options which are available for every fence agent
#####
avail_opt.extend(common_opt)
##
## Set standard environment
#####
os.putenv("LANG", "C")
os.putenv("LC_ALL", "C")
##
## Prepare list of options for getopt
#####
getopt_string = ""
longopt_list = [ ]
for k in avail_opt:
if all_opt.has_key(k):
getopt_string += all_opt[k]["getopt"]
else:
fail_usage("Parse error: unknown option '"+k+"'")
if all_opt.has_key(k) and all_opt[k].has_key("longopt"):
if all_opt[k]["getopt"].endswith(":"):
longopt_list.append(all_opt[k]["longopt"] + "=")
else:
longopt_list.append(all_opt[k]["longopt"])
## Compatibility layer
if avail_opt.count("module_name") == 1:
getopt_string += "n:"
longopt_list.append("plug=")
##
## Read options from command line or standard input
#####
if len(sys.argv) > 1:
try:
opt, args = getopt.gnu_getopt(sys.argv[1:], getopt_string, longopt_list)
except getopt.GetoptError, error:
fail_usage("Parse error: " + error.msg)
## Transform longopt to short one which are used in fencing agents
#####
old_opt = opt
opt = { }
for o in dict(old_opt).keys():
if o.startswith("--"):
for x in all_opt.keys():
if all_opt[x].has_key("longopt") and "--" + all_opt[x]["longopt"] == o:
opt["-" + all_opt[x]["getopt"].rstrip(":")] = dict(old_opt)[o]
else:
opt[o] = dict(old_opt)[o]
## Compatibility Layer
#####
z = dict(opt)
if z.has_key("-T") == 1:
z["-o"] = "status"
if z.has_key("-n") == 1:
z["-m"] = z["-n"]
opt = z
##
#####
else:
opt = { }
name = ""
for line in sys.stdin.readlines():
line = line.strip()
if ((line.startswith("#")) or (len(line) == 0)):
continue
(name, value) = (line + "=").split("=", 1)
value = value[:-1]
## Compatibility Layer
######
if name == "blade":
name = "port"
elif name == "option":
name = "action"
elif name == "fm":
name = "port"
elif name == "hostname":
name = "ipaddr"
elif name == "modulename":
name = "module_name"
elif name == "action" and 1 == avail_opt.count("io_fencing"):
name = "io_fencing"
elif name == "port" and 1 == avail_opt.count("drac_version"):
name = "module_name"
##
######
if avail_opt.count(name) == 0:
sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n")
continue
if all_opt[name]["getopt"].endswith(":"):
opt["-"+all_opt[name]["getopt"].rstrip(":")] = value
elif ((value == "1") or (value.lower() == "yes")):
opt["-"+all_opt[name]["getopt"]] = "1"
return opt
##
## This function checks input and answers if we want to have same answers
## in each of the fencing agents. It looks for possible errors and run
## password script to set a correct password
######
def check_input(device_opt, opt):
global all_opt
global common_opt
##
## Add options which are available for every fence agent
#####
device_opt.extend([x for x in common_opt if device_opt.count(x) == 0])
options = dict(opt)
options["device_opt"] = device_opt
## Set requirements that should be included in metadata
#####
if device_opt.count("login") and device_opt.count("no_login") == 0:
all_opt["login"]["required"] = "1"
else:
all_opt["login"]["required"] = "0"
## In special cases (show help, metadata or version) we don't need to check anything
#####
if options.has_key("-h") or options.has_key("-V") or (options.has_key("-o") and options["-o"].lower() == "metadata"):
return options;
## Set default values
#####
for opt in device_opt:
if all_opt[opt].has_key("default"):
getopt = "-" + all_opt[opt]["getopt"].rstrip(":")
if 0 == options.has_key(getopt):
options[getopt] = all_opt[opt]["default"]
options["-o"]=options["-o"].lower()
if options.has_key("-v"):
options["log"] = LOG_MODE_VERBOSE
else:
options["log"] = LOG_MODE_QUIET
if 0 == device_opt.count("io_fencing"):
if 0 == ["on", "off", "reboot", "status", "list", "monitor"].count(options["-o"].lower()):
fail_usage("Failed: Unrecognised action '" + options["-o"] + "'")
else:
if 0 == ["enable", "disable", "status", "list", "monitor"].count(options["-o"].lower()):
fail_usage("Failed: Unrecognised action '" + options["-o"] + "'")
if (0 == options.has_key("-l")) and device_opt.count("login") and (device_opt.count("no_login") == 0):
fail_usage("Failed: You have to set login name")
if 0 == options.has_key("-a") and 0 == options.has_key("-s"):
fail_usage("Failed: You have to enter fence address")
if (device_opt.count("no_password") == 0):
if 0 == device_opt.count("identity_file"):
if 0 == (options.has_key("-p") or options.has_key("-S")):
fail_usage("Failed: You have to enter password or password script")
else:
if 0 == (options.has_key("-p") or options.has_key("-S") or options.has_key("-k")):
fail_usage("Failed: You have to enter password, password script or identity file")
if 0 == options.has_key("-x") and 1 == options.has_key("-k"):
fail_usage("Failed: You have to use identity file together with ssh connection (-x)")
if 1 == options.has_key("-k"):
if 0 == os.path.isfile(options["-k"]):
fail_usage("Failed: Identity file " + options["-k"] + " does not exist")
if (0 == ["list", "monitor"].count(options["-o"].lower())) and (0 == options.has_key("-n")) and (device_opt.count("port")):
fail_usage("Failed: You have to enter plug number")
if options.has_key("-S"):
options["-p"] = os.popen(options["-S"]).read().rstrip()
if options.has_key("-D"):
try:
options["debug_fh"] = file (options["-D"], "w")
except IOError:
fail_usage("Failed: Unable to create file "+options["-D"])
if options.has_key("-v") and options.has_key("debug_fh") == 0:
options["debug_fh"] = sys.stderr
if options.has_key("-R"):
options["-P"] = os.popen(options["-R"]).read().rstrip()
if options.has_key("-u") == False:
if options.has_key("-x"):
options["-u"] = 22
elif options.has_key("-z"):
options["-u"] = 443
elif device_opt.count("web"):
options["-u"] = 80
else:
options["-u"] = 23
return options
def wait_power_status(tn, options, get_power_fn):
for dummy in xrange(int(options["-g"])):
if get_power_fn(tn, options) != options["-o"]:
time.sleep(1)
else:
return 1
return 0
def show_docs(options, docs = None):
device_opt = options["device_opt"]
if docs == None:
docs = { }
docs["shortdesc"] = "Fence agent"
docs["longdesc"] = ""
## Process special options (and exit)
#####
if options.has_key("-h"):
usage(device_opt)
sys.exit(0)
if options.has_key("-o") and options["-o"].lower() == "metadata":
metadata(device_opt, options, docs)
sys.exit(0)
if options.has_key("-V"):
print __main__.RELEASE_VERSION, __main__.BUILD_DATE
print __main__.REDHAT_COPYRIGHT
sys.exit(0)
def fence_action(tn, options, set_power_fn, get_power_fn, get_outlet_list = None):
result = 0
## Process options that manipulate fencing device
#####
if (options["-o"] == "list") and (0 == options["device_opt"].count("port")) and (0 == options["device_opt"].count("partition")) and 0:
print "N/A"
return
elif (options["-o"] == "list" and get_outlet_list == None):
## @todo: exception?
## This is just temporal solution, we will remove default value
## None as soon as all existing agent will support this operation
print "NOTICE: List option is not working on this device yet"
return
elif (options["-o"] == "list") or ((options["-o"] == "monitor") and 1 == options["device_opt"].count("port")):
outlets = get_outlet_list(tn, options)
## keys can be numbers (port numbers) or strings (names of VM)
for o in outlets.keys():
(alias, status) = outlets[o]
if options["-o"] != "monitor":
print o + options["-C"] + alias
return
if options["-o"] in ["off", "reboot"]:
time.sleep(int(options["-f"]))
status = get_power_fn(tn, options)
if status != "on" and status != "off":
fail(EC_STATUS)
if options["-o"] == "enable":
options["-o"] = "on"
if options["-o"] == "disable":
options["-o"] = "off"
if options["-o"] == "on":
if status == "on":
print "Success: Already ON"
else:
power_on = False
for i in range(1,1 + int(options["-F"])):
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn):
power_on = True
break
if power_on:
print "Success: Powered ON"
else:
fail(EC_WAITING_ON)
elif options["-o"] == "off":
if status == "off":
print "Success: Already OFF"
else:
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn):
print "Success: Powered OFF"
else:
fail(EC_WAITING_OFF)
elif options["-o"] == "reboot":
if status != "off":
options["-o"] = "off"
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn) == 0:
fail(EC_WAITING_OFF)
options["-o"] = "on"
power_on = False
for i in range(1,1 + int(options["-F"])):
set_power_fn(tn, options)
time.sleep(int(options["-G"]))
if wait_power_status(tn, options, get_power_fn) == 1:
power_on = True
break
if power_on == False:
# this should not fail as not was fenced succesfully
sys.stderr.write('Timed out waiting to power ON\n')
print "Success: Rebooted"
elif options["-o"] == "status":
print "Status: " + status.upper()
if status.upper() == "OFF":
result = 2
elif options["-o"] == "monitor":
1
return result
def fence_login(options):
force_ipvx=""
if (options.has_key("-6")):
force_ipvx="-6 "
if (options.has_key("-4")):
force_ipvx="-4 "
if (options["device_opt"].count("login_eol_lf")):
login_eol = "\n"
else:
login_eol = "\r\n"
try:
re_login = re.compile("(login\s*: )|(Login Name: )|(username: )|(User Name :)", re.IGNORECASE)
re_pass = re.compile("password", re.IGNORECASE)
if options.has_key("-z"):
command = '%s %s %s %s' % (SSL_PATH, force_ipvx, options["-a"], options["-u"])
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
## SSL telnet is part of the fencing package
sys.stderr.write(str(ex) + "\n")
sys.exit(EC_GENERIC_ERROR)
elif options.has_key("-x") and 0 == options.has_key("-k"):
command = '%s %s %s@%s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-u"])
if options.has_key("ssh_options"):
command += ' ' + options["ssh_options"]
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
if options.has_key("telnet_over_ssh"):
#This is for stupid ssh servers (like ALOM) which behave more like telnet (ignore name and display login prompt)
result = conn.log_expect(options, [ re_login, "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"]))
if result == 1:
conn.sendline("yes") # Host identity confirm
conn.log_expect(options, re_login, int(options["-y"]))
conn.sendline(options["-l"])
conn.log_expect(options, re_pass, int(options["-y"]))
else:
result = conn.log_expect(options, [ "ssword:", "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"]))
if result == 1:
conn.sendline("yes")
conn.log_expect(options, "ssword:", int(options["-y"]))
conn.sendline(options["-p"])
conn.log_expect(options, options["-c"], int(options["-y"]))
elif options.has_key("-x") and 1 == options.has_key("-k"):
command = '%s %s %s@%s -i %s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-k"], options["-u"])
if options.has_key("ssh_options"):
command += ' ' + options["ssh_options"]
try:
conn = fspawn(command)
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
result = conn.log_expect(options, [ options["-c"], "Are you sure you want to continue connecting (yes/no)?", "Enter passphrase for key '"+options["-k"]+"':" ], int(options["-y"]))
if result == 1:
conn.sendline("yes")
conn.log_expect(options, [ options["-c"], "Enter passphrase for key '"+options["-k"]+"':"] , int(options["-y"]))
if result != 0:
if options.has_key("-p"):
conn.sendline(options["-p"])
conn.log_expect(options, options["-c"], int(options["-y"]))
else:
fail_usage("Failed: You have to enter passphrase (-p) for identity file")
else:
try:
conn = fspawn(TELNET_PATH)
conn.send("set binary\n")
conn.send("open %s -%s\n"%(options["-a"], options["-u"]))
except pexpect.ExceptionPexpect, ex:
sys.stderr.write(str(ex) + "\n")
sys.stderr.write("Due to limitations, binary dependencies on fence agents "
"are not in the spec file and must be installed separately." + "\n")
sys.exit(EC_GENERIC_ERROR)
conn.log_expect(options, re_login, int(options["-y"]))
conn.send(options["-l"] + login_eol)
conn.log_expect(options, re_pass, int(options["-Y"]))
conn.send(options["-p"] + login_eol)
conn.log_expect(options, options["-c"], int(options["-Y"]))
except pexpect.EOF:
fail(EC_LOGIN_DENIED)
except pexpect.TIMEOUT:
fail(EC_LOGIN_DENIED)
return conn
| Python |
#!/usr/bin/env python
# Copyright 2011 Matt Clark
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
import sys, string, getopt
import XenAPI
def usage():
print "Usage: fence_cxs [-hv] [-a <action>] -l <login username> -p <login password> -s <session url> [-u <UUID>]"
print "Where:-"
print " -a : Specifies the action to perfom. Can be any of \"on|off|reboot|status\". Defaults to \"status\"."
print " -h : Print this help message."
print " -l : The username for the XenServer host."
print " -p : The password for the XenServer host."
print " -s : The URL of the web interface on the XenServer host."
print " -u : The UUID of the virtual machine to fence or query. Defaults to the empty string which will return"
print " the status of all hosts when action is set to \"status\". If the action is set to \"on|off|reboot\""
print " then the UUID must be specified."
# Process command line options and populate the config array
def process_opts():
config = {
"action" : "status",
"session_url" : "",
"session_user" : "",
"session_pass" : "",
"uuid" : "",
"verbose" : False
}
# If we have at least one argument then we want to parse the command line using getopts
if len(sys.argv) > 1:
try:
opts, args = getopt.getopt(sys.argv[1:], "a:hl:s:p:u:v", ["help", "verbose", "action=", "session-url=", "login-name=", "password=", "uuid="])
except getopt.GetoptError, err:
# We got an unrecognised option, so print he help message and exit
print str(err)
usage()
sys.exit(1)
for opt, arg in opts:
if opt in ("-v", "--verbose"):
config["verbose"] = True
elif opt in ("-a", "--action"):
config["action"] = clean_action(arg)
elif opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-s", "--session-url"):
config["session_url"] = arg
elif opt in ("-l", "--login-name"):
config["session_user"] = arg
elif opt in ("-p", "--password"):
config["session_pass"] = arg
elif opt in ("-u", "--uuid"):
config["uuid"] = arg.lower()
else:
assert False, "unhandled option"
# Otherwise process stdin for parameters. This is to handle the Red Hat clustering
# mechanism where by fenced passes in name/value pairs instead of using command line
# options.
else:
for line in sys.stdin.readlines():
line = line.strip()
if ((line.startswith("#")) or (len(line) == 0)):
continue
(name, value) = (line + "=").split("=", 1)
value = value[:-1]
name = clean_param_name(name)
if name == "action":
value = clean_action(value)
if name in config:
config[name] = value
else:
sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n")
if( config["session_url"] == "" or config["session_user"] == "" or config["session_pass"] == "" ):
print "You must specify the session url, username and password.";
usage();
sys.exit(2);
return config
# why, well just to be nice. Given an action will return the corresponding
# value that the rest of the script uses.
def clean_action(action):
if action.lower() in ("on", "poweron", "powerup"):
return "on"
elif action.lower() in ("off", "poweroff", "powerdown"):
return "off"
elif action.lower() in ("reboot", "reset", "restart"):
return "reboot"
elif action.lower() in ("status", "powerstatus", "list"):
return "status"
return ""
# why, well just to be nice. Given a parameter will return the corresponding
# value that the rest of the script uses.
def clean_param_name(name):
if name.lower() in ("action", "operation", "op"):
return "action"
elif name.lower() in ("session_user", "login", "login-name", "login_name", "user", "username", "session-user"):
return "session_user"
elif name.lower() in ("session_pass", "pass", "passwd", "password", "session-pass"):
return "session_pass"
elif name.lower() in ("session_url", "url", "session-url"):
return "session_url"
return ""
# Print the power status of a VM. If no UUID is given, then all VM's are queried
def get_power_status(session, uuid = ""):
try:
# If the UUID hasn't been set, then output the status of all
# valid virtual machines.
if( uuid == "" ):
vms = session.xenapi.VM.get_all()
else:
vms = [session.xenapi.VM.get_by_uuid(uuid)]
for vm in vms:
record = session.xenapi.VM.get_record(vm);
# We only want to print out the status for actual virtual machines. The above get_all function
# returns any templates and also the control domain. This is one of the reasons the process
# takes such a long time to list all VM's. Hopefully there is a way to filter this in the
# request packet in the future.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
def set_power_status(session, uuid, action):
try:
vm = session.xenapi.VM.get_by_uuid(uuid)
record = session.xenapi.VM.get_record(vm);
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
session.xenapi.VM.hard_reboot(vm)
except Exception, exn:
print str(exn);
def main():
config = process_opts();
session = session_start(config["session_url"]);
session_login(session, config["session_user"], config["session_pass"]);
if( config["action"] == "status" ):
get_power_status(session, config["uuid"])
else:
if( config["verbose"] ):
print "Power status before action"
get_power_status(session, config["uuid"])
set_power_status(session, config["uuid"], config["action"])
if( config["verbose"] ):
print "Power status after action"
get_power_status(session, config["uuid"])
# Function to initiate the session with the XenServer system
def session_start(url):
try:
session = XenAPI.Session(url);
except Exception, exn:
print str(exn);
sys.exit(3);
return session;
def session_login(session, username, password):
try:
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
sys.exit(3);
if __name__ == "__main__":
main()
# vim:set ts=4 sw=4
| Python |
#!/usr/bin/env python
# Copyright 2011 Matt Clark
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Please let me know if you are using this script so that I can work out
# whether I should continue support for it. mattjclark0407 at hotmail dot com
import sys, string, getopt
import XenAPI
def usage():
print "Usage: fence_cxs [-hv] [-a <action>] -l <login username> -p <login password> -s <session url> [-u <UUID>]"
print "Where:-"
print " -a : Specifies the action to perfom. Can be any of \"on|off|reboot|status\". Defaults to \"status\"."
print " -h : Print this help message."
print " -l : The username for the XenServer host."
print " -p : The password for the XenServer host."
print " -s : The URL of the web interface on the XenServer host."
print " -u : The UUID of the virtual machine to fence or query. Defaults to the empty string which will return"
print " the status of all hosts when action is set to \"status\". If the action is set to \"on|off|reboot\""
print " then the UUID must be specified."
# Process command line options and populate the config array
def process_opts():
config = {
"action" : "status",
"session_url" : "",
"session_user" : "",
"session_pass" : "",
"uuid" : "",
"verbose" : False
}
# If we have at least one argument then we want to parse the command line using getopts
if len(sys.argv) > 1:
try:
opts, args = getopt.getopt(sys.argv[1:], "a:hl:s:p:u:v", ["help", "verbose", "action=", "session-url=", "login-name=", "password=", "uuid="])
except getopt.GetoptError, err:
# We got an unrecognised option, so print he help message and exit
print str(err)
usage()
sys.exit(1)
for opt, arg in opts:
if opt in ("-v", "--verbose"):
config["verbose"] = True
elif opt in ("-a", "--action"):
config["action"] = clean_action(arg)
elif opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-s", "--session-url"):
config["session_url"] = arg
elif opt in ("-l", "--login-name"):
config["session_user"] = arg
elif opt in ("-p", "--password"):
config["session_pass"] = arg
elif opt in ("-u", "--uuid"):
config["uuid"] = arg.lower()
else:
assert False, "unhandled option"
# Otherwise process stdin for parameters. This is to handle the Red Hat clustering
# mechanism where by fenced passes in name/value pairs instead of using command line
# options.
else:
for line in sys.stdin.readlines():
line = line.strip()
if ((line.startswith("#")) or (len(line) == 0)):
continue
(name, value) = (line + "=").split("=", 1)
value = value[:-1]
name = clean_param_name(name)
if name == "action":
value = clean_action(value)
if name in config:
config[name] = value
else:
sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n")
if( config["session_url"] == "" or config["session_user"] == "" or config["session_pass"] == "" ):
print "You must specify the session url, username and password.";
usage();
sys.exit(2);
return config
# why, well just to be nice. Given an action will return the corresponding
# value that the rest of the script uses.
def clean_action(action):
if action.lower() in ("on", "poweron", "powerup"):
return "on"
elif action.lower() in ("off", "poweroff", "powerdown"):
return "off"
elif action.lower() in ("reboot", "reset", "restart"):
return "reboot"
elif action.lower() in ("status", "powerstatus", "list"):
return "status"
return ""
# why, well just to be nice. Given a parameter will return the corresponding
# value that the rest of the script uses.
def clean_param_name(name):
if name.lower() in ("action", "operation", "op"):
return "action"
elif name.lower() in ("session_user", "login", "login-name", "login_name", "user", "username", "session-user"):
return "session_user"
elif name.lower() in ("session_pass", "pass", "passwd", "password", "session-pass"):
return "session_pass"
elif name.lower() in ("session_url", "url", "session-url"):
return "session_url"
return ""
# Print the power status of a VM. If no UUID is given, then all VM's are queried
def get_power_status(session, uuid = ""):
try:
# If the UUID hasn't been set, then output the status of all
# valid virtual machines.
if( uuid == "" ):
vms = session.xenapi.VM.get_all()
else:
vms = [session.xenapi.VM.get_by_uuid(uuid)]
for vm in vms:
record = session.xenapi.VM.get_record(vm);
# We only want to print out the status for actual virtual machines. The above get_all function
# returns any templates and also the control domain. This is one of the reasons the process
# takes such a long time to list all VM's. Hopefully there is a way to filter this in the
# request packet in the future.
if not(record["is_a_template"]) and not(record["is_control_domain"]):
name = record["name_label"]
print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"]
except Exception, exn:
print str(exn);
def set_power_status(session, uuid, action):
try:
vm = session.xenapi.VM.get_by_uuid(uuid)
record = session.xenapi.VM.get_record(vm);
if not(record["is_a_template"]) and not(record["is_control_domain"]):
if( action == "on" ):
session.xenapi.VM.start(vm, False, True)
elif( action == "off" ):
session.xenapi.VM.hard_shutdown(vm)
elif( action == "reboot" ):
session.xenapi.VM.hard_reboot(vm)
except Exception, exn:
print str(exn);
def main():
config = process_opts();
session = session_start(config["session_url"]);
session_login(session, config["session_user"], config["session_pass"]);
if( config["action"] == "status" ):
get_power_status(session, config["uuid"])
else:
if( config["verbose"] ):
print "Power status before action"
get_power_status(session, config["uuid"])
set_power_status(session, config["uuid"], config["action"])
if( config["verbose"] ):
print "Power status after action"
get_power_status(session, config["uuid"])
# Function to initiate the session with the XenServer system
def session_start(url):
try:
session = XenAPI.Session(url);
except Exception, exn:
print str(exn);
sys.exit(3);
return session;
def session_login(session, username, password):
try:
session.xenapi.login_with_password(username, password);
except Exception, exn:
print str(exn);
sys.exit(3);
if __name__ == "__main__":
main()
# vim:set ts=4 sw=4
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.