code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
# -*- coding: UTF-8 -*-
"""
$Id: calendar.py 270 2012-02-01 22:59:11Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/interaction/irc/modules/calendar.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Aug, 05 2010
@author Rack Rackowitsch
@author Mario Steinhoff
"""
__version__ = '$Rev: 270 $'
import logging
import re
from datetime import date
from core.constants import TIME_MINUTE
from core.config import Config
from objects.calendar import Event
from components.calendar import InvalidObjectId
from interaction.irc.module import InteractiveModule, InteractiveModuleCommand, InteractiveModuleRequest, InteractiveModuleResponse, ModuleError, Location
#-------------------------------------------------------------------------------
# Constants
#-------------------------------------------------------------------------------
REGEX_DATE = re.compile('^(\d{1,2})\.(\d{1,2})\.(\d{4})$')
#-------------------------------------------------------------------------------
# Exceptions
#-------------------------------------------------------------------------------
class CalendarModuleError(ModuleError): pass
class EventError(CalendarModuleError): pass
class EventNotFound(EventError): pass
class NoEventsFound(EventError): pass
class AmbiguousEventsFound(EventError): pass
class DateError(CalendarModuleError): pass
class DateFormatInvalid(DateError): pass
class DateRangeInvalid(DateError): pass
#-------------------------------------------------------------------------------
# Business Logic
#-------------------------------------------------------------------------------
class Calendar(InteractiveModule):
"""
This module provides calendaring functions.
"""
#---------------------------------------------------------------------------
# Module implementation
#---------------------------------------------------------------------------
def initialize(self):
bot = self.client.bot;
bot.register_config(CalendarConfig)
self.logger = logging.getLogger('interaction.irc.calendar')
self.config = bot.get_config('interaction.irc.calendar')
self.component = bot.get_subsystem('calendar-component');
bot.register_timer(
'interaction.irc.calendar.reminder',
'daily',
self.config.get('reminderInterval'),
self._display_reminder
)
# --------------------------------------------------------------------------
# Lifecycle
# --------------------------------------------------------------------------
def start(self):
self.client.bot.get_timer('interaction.irc.calendar.reminder').start()
def stop(self):
self.client.bot.get_timer('interaction.irc.calendar.reminder').stop()
#---------------------------------------------------------------------------
# InteractiveModule implementation
#---------------------------------------------------------------------------
def module_identifier(self):
return 'Kalender'
def init_commands(self):
return [
InteractiveModuleCommand(
keyword='kalender',
callback=self.display_calendar_address,
),
InteractiveModuleCommand(
keyword='listtoday',
callback=self.display_events_today,
),
InteractiveModuleCommand(
keyword='listdeleted',
callback=self.display_deleted_objects,
pattern=r'^(.*)$',
syntaxhint='[kalendar|event|kontakt]'
),
InteractiveModuleCommand(
keyword='restore',
callback=self.restore_deleted_object,
pattern=r'^[\d]+$',
syntaxhint='<id>'
),
InteractiveModuleCommand(
keyword='addevent',
callback=self.insert_event,
pattern=r'^(\d{1,2}\.\d{1,2}\.\d{4}|\d{1,2}\.\d{1,2}\.\d{4}-\d{1,2}\.\d{1,2}\.\d{4})\s(.+)$',
syntaxhint='<datumvon>[-datumbis] <titel>'
),
InteractiveModuleCommand(
keyword='editevent',
callback=self.change_event,
pattern=r'^([\d]+)\s(.+?)\s(.+)$',
syntaxhint='<id> <start|ende|titel|beschreibung|ort> <wert>'
),
InteractiveModuleCommand(
keyword='delevent',
callback=self.delete_event,
pattern=r'^([\d]+|\d{1,2}\.\d{1,2}\.\d{4})$',
syntaxhint='<id|datum>'
),
InteractiveModuleCommand(
keyword='searchevent',
callback=self.search_event,
pattern=r'^(.+)$',
syntaxhint='<text>'
),
InteractiveModuleCommand(
keyword='topicevent',
callback=self.topic_event,
pattern=r'^[\d]+$',
syntaxhint='<id>'
),
InteractiveModuleCommand(
keyword='addcontact',
callback=self.insert_contact,
pattern=r'^(.+)\s(\d{1,2}\.\d{1,2}\.\d{4})$',
syntaxhint='<nickname> <geburtsdatum>'
),
InteractiveModuleCommand(
keyword='editcontact',
callback=self.change_contact,
pattern=r'^[\d]+\s(.+)\s(.+)$',
syntaxhint='<id> <vorname|nachname|nickname|geburtsdatum> <wert>'
),
InteractiveModuleCommand(
keyword='delcontact',
callback=self.delete_contact,
pattern=r'^([\d]+|(.+))$',
syntaxhint='<id>'
),
InteractiveModuleCommand(
keyword='searchcontact',
callback=self.search_contact,
pattern=r'^(.+)$',
syntaxhint='<text>'
)
]
#---------------------------------------------------------------------------
# Internal module commands
#---------------------------------------------------------------------------
def _get_date(self, date_string):
"""
Check if the input_string contains a valid date.
The input string is first converted using REGEX_DATE and then
checked.
@param date_string: The input string. See REGEX_DATE for the format.
@return A date object.
@raise DateFormatInvalid If no properly formatted date was given.
@raise DateRangeInvalid If the date values are out of range.
"""
matchlist = REGEX_DATE.search(date_string)
if not matchlist:
raise DateFormatInvalid
date_tokens = matchlist.group(1, 2, 3)
try:
return date(int(date_tokens[2]),int(date_tokens[1]),int(date_tokens[0]))
except ValueError as e:
raise DateRangeInvalid(e)
def _display_reminder(self, date):
"""
Timer callback function.
"""
request = InteractiveModuleRequest(
)
response = self.display_events_by_date(None, Location.CHANNEL, None, [date])
for channel in self.usermgmt.chanlist.get_channels().values():
self.send_response(channel, response)
#---------------------------------------------------------------------------
# InteractiveModule commands - display
#---------------------------------------------------------------------------
def display_calendar_address(self, request):
"""
Display the web calendar's address.
"""
response = InteractiveModuleResponse(self.config.get('calendarUrl'))
return response
def display_events_today(self, request):
"""
Display today's events, if any.
"""
request.parameter = [date.today()]
return self.display_events_by_date(request)
def display_events_by_date(self, request):
"""
Display events occuring at the given date.
"""
response = InteractiveModuleResponse()
date = request.parameter[0]
try:
calendar_events = self.component.find_events_by_date(date)
if len(calendar_events) == 0:
raise NoEventsFound
for calendar_event in calendar_events:
response.add_line("ID {0}: {1}".format(calendar_event.id, calendar_event.title))
except NoEventsFound:
response.add_line('Keine Termine gefunden.')
return response
def display_deleted_objects(self, event, location, command, parameter):
"""
"""
return InteractiveModuleResponse('not implemented')
def restore_deleted_object(self, request):
"""
"""
return InteractiveModuleResponse('not implemented')
#---------------------------------------------------------------------------
# InteractiveModule commands - events
#---------------------------------------------------------------------------
def insert_event(self, request):
"""
Create a new event.
.addevent <startdate>[-<enddate>] title
"""
response = InteractiveModuleResponse()
date = request.parameter[0]
title = request.parameter[1]
try:
if '-' not in date:
dateFrom = self._get_date(date)
dateTo = dateFrom
else:
dates = date.split('-')
dateFrom = self._get_date(dates[0])
dateTo = self._get_date(dates[1])
calendar = self.component.find_default_calendar()
event = Event(calendar=calendar, start=dateFrom, end=dateTo, title=title)
event = self.component.insert_object(event)
response.add_line("Eintrag erfolgreich eingefügt! ID: {0}".format(event.id))
except DateFormatInvalid:
response.add_line("Datum muss im Format [d]d.[m]m.yyyy sein. Bsp: 12.5.2010")
except DateRangeInvalid as e:
response.add_line('Ungültiges Datum: {0}.'.format(e))
return response
def change_event(self, event, location, command, parameter):
"""
Change an existing event.
The event is identified by its ID.
Syntax: <id> <start|ende|titel|beschreibung|ort> <wert>
"""
response = InteractiveModuleResponse()
eventId = parameter[0]
attribute = parameter[1]
value = parameter[2]
try:
map = {
'start' : 'start',
'ende' : 'end',
'titel' : 'title',
'beschreibung' : 'description',
'ort' : 'location'
}
if attribute in ['start', 'ende']:
value = self._get_date(value)
event = self.component.find_event_by_id(eventId)
setattr(event, map[attribute], value)
self.component.update_object(event)
response.add_line('{0} fuer Eintrag {1} wurde auf {2} gesetzt'.format(
attribute.capitalize(),
event.id,
value
))
except DateFormatInvalid:
response.add_line("Datum muss im Format [d]d.[m]m.yyyy sein. Bsp: 12.5.2010")
except EventNotFound:
response.add_line('Kein Event mit ID {0} gefunden'.format(eventId))
return response
def delete_event(self, request):
"""
.delevent [<id>|<datum>]
"""
response = InteractiveModuleResponse()
# when only one parameter is defined a string is returned
id_or_date = request.parameter[0]
try:
try:
date = self._get_date(id_or_date)
#---------------------------------------------------------------
# delete by date
#---------------------------------------------------------------
events = self.component.find_events_by_date(date)
count = len(events)
if count == 0:
raise NoEventsFound
if count > 1:
raise AmbiguousEventsFound(events)
event = events[0]
except DateFormatInvalid:
#---------------------------------------------------------------
# delete by id
#---------------------------------------------------------------
eventId = int(id_or_date)
event = self.component.find_event_by_id(eventId)
if not event:
raise NoEventsFound
self.component.delete_object(event)
response.add_line("Eintrag {0} wurde geloescht.".format(id_or_date))
except InvalidObjectId:
response.add_line("Kein Eintrag zu dieser ID gefunden.")
except NoEventsFound:
response.add_line("Kein Eintrag zu diesem Datum gefunden.")
except AmbiguousEventsFound as error:
response.add_line('Mehrere Einträge gefunden:')
[response.add_line("(ID={0}) {1}".format(event.id, event.title)) for event in error.message]
return response
def search_event(self, request):
"""
Search for an event
.searchevent <text>
"""
response = InteractiveModuleResponse()
query = request.parameter[0]
try:
events = self.component.find_events_by_substring(query)
[response.add_line("(ID={0}) {1}".format(event.id, event.title)) for event in events]
except NoEventsFound:
response.add_line("Keine Einträge mit diesem Inhalt gefunden.")
return response
def topic_event(self, request):
"""
Post the given event to the current topic.
.topicevent
TODO: implement
"""
response = InteractiveModuleResponse()
eventId = int(request.parameter[0])
try:
result = self.component.find_event_by_id(eventId)
if result is None:
raise EventNotFound
response.add_line('currently not implemented');
except EventNotFound:
response.add_line('Kein Event mit ID {0} gefunden'.format(eventId))
return response
#---------------------------------------------------------------------------
# InteractiveModule commands - contacts
#---------------------------------------------------------------------------
def insert_contact(self, request):
"""
"""
response = InteractiveModuleResponse("not implemented")
return response
def change_contact(self, request):
"""
"""
response = InteractiveModuleResponse("not implemented")
return response
def delete_contact(self, request):
"""
"""
response = InteractiveModuleResponse("not implemented")
return response
def search_contact(self, request):
"""
"""
response = InteractiveModuleResponse("not implemented")
return response
class CalendarConfig(Config):
identifier = 'interaction.irc.calendar'
def valid_keys(self):
return [
'reminderInterval',
'calendarUrl'
]
def default_values(self):
return {
'reminderInterval' : TIME_MINUTE * 5,
'calendarUrl' : ''
}
| Python |
# -*- coding: UTF-8 -*-
'''
Created on 27.01.2012
@author: rack
'''
import logging
import random
from datetime import date
from interaction.irc.module import InteractiveModule, InteractiveModuleCommand, InteractiveModuleResponse
from components.topic import TopicNotFound, AdditionNotFound, NoAdditionAvailable, NoAffectedRows
#-------------------------------------------------------------------------------
# Constants
#-------------------------------------------------------------------------------
BOT_IS_OPERATOR = 2
RANDOM_YEAR_START = 1983
RANDOM_YEAR_END = 2020
DEFAULT_TOPIC = 'Willkommen im Sammelbecken für sozial Benachteiligte'
#-------------------------------------------------------------------------------
# Module 'Logic'
#-------------------------------------------------------------------------------
class Topic(InteractiveModule):
"""
This module provides topic functions
"""
def initialize(self):
"""
Initialize the module.
"""
self.me = self.client.me
self.logger = logging.getLogger('interaction.irc.topic')
self.component = self.client.bot.get_subsystem('topic-component')
def module_identifier(self):
"""
Declare the module identifier.
"""
return 'TopicMod'
def init_commands(self):
return [
InteractiveModuleCommand(
keyword='topic',
callback=self.display_current_topic
),
InteractiveModuleCommand(
keyword='settopic',
callback=self.set_new_topic,
pattern=r'^(.+)$',
syntaxhint='<new topic>'
),
InteractiveModuleCommand(
keyword='addtopic',
callback=self.add_new_addition,
pattern=r'^(.+)$',
syntaxhint='<addition>'
),
InteractiveModuleCommand(
keyword='deltopic',
callback=self.del_addition,
pattern=r'^(.+)$',
syntaxhint=r'<id>'
),
InteractiveModuleCommand(
keyword='listtopic',
callback=self.display_topic_additions
)
]
def display_current_topic(self, request):
"""
Display the current topic.
Usage: .topic
@return InteractiveModuleResponse
"""
response = InteractiveModuleResponse()
try:
topic = self.component.get_last_topic()
topic_string = self.component.create_topic_string(topic.text,topic.addition.text,topic.year)
response.add_line('{0} set by {1}'.format(topic_string,topic.user))
except TopicNotFound:
response.add_line("No topic available.")
return response
def set_new_topic(self, request):
"""
Change the topic of a channel.
Usage: .settopic <text|'reset'>
If the module receive the string 'reset', it will set the default topic
@param request: A runtime request of an InteractiveModule command.
@return InteractiveModuleResponse
"""
response = InteractiveModuleResponse()
#Normally, here I would check if there was set the mode +t in channel modes
#because if it was set, I won't need to check the userMode.
#But get_modes() is not implemnted, yet :(
#channelModes = channelObject.get_modes()
channel_object = self.usermgmt.chanlist.get(request.target)
userMode = channel_object.get_user_mode(self.me.source.nickname)
try:
if (userMode == BOT_IS_OPERATOR):
text = request.parameter[0]
if (text == 'reset'): #default topic
text = DEFAULT_TOPIC
addition = self.component.get_random_addition().text
year = random.randint(RANDOM_YEAR_START,RANDOM_YEAR_END)
topic_cmd = self.client.get_command('Topic').get_sender()
topic_cmd.channel = request.target
topic_cmd.topic = self.create_topic_string(text,addition,year)
topic_cmd.send()
self.component.insert_topic(text,addition,year,request.source.nickname)
else:
response.add_line("Bot needs to be an operator to do this.")
except NoAdditionAvailable:
response.add_line("There are no topic additions available at the moment.")
return response
def add_new_addition(self, request):
"""
Insert a new addition to database
Usage: .addtopic <addtion(text)>
@param request: A runtime request of an InteractiveModule command.
@return InteractiveModuleResponse
"""
response = InteractiveModuleResponse()
self.component.insert_addition(request.parameter[0],request.source.nickname)
response.add_line("The process was successful.")
return response
def del_addition(self, request):
"""
Delete a addition with the given id.
.deltopic <id>
@param request: A runtime request of an InteractiveModule command.
@return: InteractiveModuleResponse
"""
response = InteractiveModuleResponse()
try:
id = int(request.parameter[0])
self.component.delete_addition_by_id(id)
response.add_line("Delete was successful.")
except NoAffectedRows:
response.add_line("No entry was deleted.")
except ValueError:
response.add_line("Please enter a valid ID!")
return response
def display_topic_additions(self, request):
"""
Send a link to a list with all additions.
Usage: .listtopic
@return: InteractiveModuleResponse
"""
return InteractiveModuleResponse("www.derlinkfehltnoch.de")
def create_topic_string(self,text,addition,year):
"""
Return a formated topic string with text, addition and year
@param text: a topic text
@param addition: an addition text
@param year: a year for the second addition part
@return: formated string
"""
if (year <= date.today().year):
since_until = "since"
else:
since_until = "until"
return "127,1.:. Welcome� 7,1� 14,1F4,1=15,1O7,1=0,1P" \
+ "7,1=0,1T7,1=0,1I7,1=15O4,1=14,1N 7,1�" \
+ " 7,14Topic: {0} 47,1� {1} {2} {3}! .:.".format(text, addition, since_until, year) | Python |
# -*- coding: UTF-8 -*-
"""
$Id: facts.py 260 2012-01-23 21:45:31Z steinhoff.mario@googlemail.com $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/interaction/irc/modules/facts.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Apr, 07 2010
@author Rack Rackowitsch
@author Mario Steinhoff
"""
__version__ = '$Rev: 260 $'
import logging
import random
from interaction.irc.module import Module
class Facts(Module):
"""
This module posts random facts in the channel.
"""
#---------------------------------------------------------------------------
# Module implementation
#---------------------------------------------------------------------------
def initialize(self):
self.logger = logging.getLogger('interaction.irc.facts')
self.component = self.client.bot.get_subsystem('facts-component')
def get_receive_listeners(self):
return {'Privmsg': self.random_post}
#---------------------------------------------------------------------------
# module commands
#---------------------------------------------------------------------------
def random_post(self, event):
if random.randint(1,88) != 12:
return
fact = self.component.find_random_fact()
reply = self.client.get_command('Privmsg').get_sender()
reply.target = event.parameter[0]
reply.text = 'ACTION ist kluK und weiss: "{0}"'.format(fact.text)
reply.send()
self.logger.info('posted random fact number %s', fact.id)
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: usermgmt.py 271 2012-02-02 18:20:23Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/interaction/irc/modules/usermgmt.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Feb 2, 2011
@author Mario Steinhoff
"""
__version__ = '$Rev: 271 $'
import time
import hashlib
from objects.principal import Role
from objects.irc import ClientSource, User, Channel, Location
from interaction.irc.message import SPACE
from interaction.irc.module import InteractiveModule, InteractiveModuleCommand, InteractiveModuleResponse, ModuleError
#-------------------------------------------------------------------------------
# Constants
#-------------------------------------------------------------------------------
KEY_ROLE = 'usermgmt.role'
KEY_AUTH = 'usermgmt.auth'
KEY_IDLETIME = 'usermgmt.idletime'
KEY_SIGNONTIME = 'usermgmt.signontime'
TOKEN_OP = '\x40'
TOKEN_VOICE = '\x2B'
#-------------------------------------------------------------------------------
# Exceptions
#-------------------------------------------------------------------------------
class UserError(ModuleError): pass
class UserInvalid(UserError): pass
class UserExists(UserError): pass
class UserNotAuthenticated(UserError): pass
class UserNotAuthorized(UserError): pass
#-------------------------------------------------------------------------------
# Business Logic
#-------------------------------------------------------------------------------
class Usermgmt(InteractiveModule):
"""
Maintain a list of channels the bot has joined and users known to the bot.
"""
#---------------------------------------------------------------------------
# Module implementation
#---------------------------------------------------------------------------
def initialize(self):
"""
Initialize the module.
"""
self.me = self.client.me
self.chanlist = ChannelList(self.client)
self.userlist = UserList(self.client)
def get_receive_listeners(self):
"""
Return a mapping between commands and callback functions.
"""
listeners = InteractiveModule.get_receive_listeners(self)
listeners.update({
'Join': self.process_join,
'Mode': self.process_mode,
'Part': self.process_part,
'Kick': self.process_kick,
'Quit': self.process_quit,
'Nick': self.process_nick,
'Invite': self.process_invite,
'Topic': self.process_topic,
'NamesReply': self.process_names,
'WhoReply': self.process_who,
'WhoisUserReply': self.process_whois_user,
'WhoisIdleReply': self.process_whois_idle,
'WhoisAuthReply': self.process_whois_auth,
})
return listeners
#---------------------------------------------------------------------------
# InteractiveModule implementation
#---------------------------------------------------------------------------
def module_identifier(self):
return 'Benutzerverwaltung'
def init_commands(self):
return [
InteractiveModuleCommand(
keyword='listuser',
callback=self.list_user,
location=Location.QUERY,
role=Role.ADMIN),
InteractiveModuleCommand(
keyword='adduser',
callback=self.insert_user,
location=Location.QUERY,
role=Role.ADMIN,
pattern=r'^$',
syntaxhint='???'
),
InteractiveModuleCommand(
keyword='chguser',
callback=self.change_user,
location=Location.QUERY,
role=Role.ADMIN,
pattern=r'^$',
syntaxhint='???'
),
InteractiveModuleCommand(
keyword='deluser',
callback=self.delete_user,
location=Location.QUERY,
role=Role.ADMIN,
pattern=r'^$',
syntaxhint='???'
)
]
#---------------------------------------------------------------------------
# protocol handling
#---------------------------------------------------------------------------
def process_join(self, event):
"""
Process all incoming JOIN events.
If the bot joins a channel, the channel is requested from the
channel list. The bot is getting added as the first user to that
channel.
TODO: Check whether the bot's nickname is included in NAMES.
TODO: If yes, do not add the bot here but check for client.me
TODO: in process_names.
If another user joins a channel, that user is requested from
the userlist. Then the channel is requested from the channel
list to prevent race-conditions on close-together JOIN events
and the user is added to the channel.
"""
channel_name = event.parameter[0]
if event.source.nickname == self.me.source.nickname:
user = self.me
else:
user = self.userlist.request(event.source)
user.set_data(KEY_ROLE, Role.USER)
self.client.logger.info('User {0} joined {1}'.format(user, channel_name))
channel = self.chanlist.request(channel_name)
user.add_channel(channel, None)
if event.source.nickname != self.me.source.nickname:
whois = self.client.get_command('Whois').get_sender()
whois.user = event.source.nickname
whois.send()
def process_mode(self, event):
"""
Process all incoming MODE events.
Currently only user mode changes in channels are process.
The IRC protocol is really buggy/incomplete at this point.
Modes can not be correctly detected: When a user is opped and
has voice on a given channel and the bot joins that channel,
the user is only flagged as op. When op is revoked, The only
way to check the user mode reliable in this situation is
another WHOIS or NAMES request, which out put unnecessary load
on the bot, connection and server.
Because of the incomplete protocol, this method is only listening
for user op mode changes.
This method has limited support for multi-mode changes, e.g.
+oooo Nickname1 Nickname2 Nickname3 Nickname4d
"""
CHANGE_GRANT = 1
CHANGE_REVOKE = 1
target = event.parameter[0]
modes = event.parameter[1]
users = event.parameter[2:]
#-----------------------------------------------------------------------
# Process only user modes
#-----------------------------------------------------------------------
if Location.get(target) is not Location.CHANNEL:
return
#-----------------------------------------------------------------------
# Check what change needs to be applied
#-----------------------------------------------------------------------
if modes[0] == '+':
change = CHANGE_GRANT
elif modes[0] == '-':
change = CHANGE_REVOKE
else:
# unknown condition, dont process
return
# remove change flag from modes
modes = modes[1:]
#-----------------------------------------------------------------------
# Apply mode changes
#-----------------------------------------------------------------------
channel = self.chanlist.get(target)
for index, nickname in enumerate(users):
mode = modes[index]
# process only op changes
if mode != 'o':
continue
if change == CHANGE_GRANT:
channel.set_user_mode(nickname, Channel.USERMODE_OP)
msg = 'Setting mode to +{0} for user {1} on channel {2}'.format(
modes[index],
nickname,
channel.name
)
elif change == CHANGE_REVOKE:
channel.set_user_mode(nickname, None)
msg = 'Setting mode to -{0} for user {1} on channel {2}'.format(
modes[index],
nickname,
channel.name
)
self.client.logger.info(msg)
def process_part(self, event):
"""
Process all incoming PART events.
If the bot parts a channel, the channel is removed from the
channel list.
TODO: Moar GC when the bot parts a channel. Remove users that
TODO: are not on any channels the bot has joined. Priority 3
TODO: because the bot is currently only in one channel
TODO: simultaneously.
If another user parts a channel, the user is removed from that
channel's userlist and the channel is removed from the user's
channel list.
"""
channel_name = event.parameter[0]
if event.source.nickname == self.me.source.nickname:
self.client.logger.info('I am parting {0}'.format(channel_name))
channel = self.chanlist.remove(channel_name)
else:
user = self.userlist.get(event.source.nickname)
channel = self.chanlist.get(channel_name)
self.client.logger.info('User {0} left channel {1}'.format(user, channel_name))
user.remove_channel(channel)
if len(user.get_channels()) == 0:
self.userlist.remove(user.source.nickname)
def process_kick(self, event):
"""
Process all incoming KICK events.
This is currently mapped to process_part
"""
# remove user from channel list
# if user==self, notify someone
# if user==self, on autorejoin join channel again
channel_name = event.parameter[0]
victim = event.parameter[1]
if victim == self.me.source.nickname:
self.client.logger.info('I was kicked from {0}'.format(channel_name))
channel = self.chanlist.remove(channel_name)
# remove all users that were on the channel we were kicked from
for user in self.userlist.get_users().values():
if len(user.get_channels()) == 0:
self.userlist.remove(user.source.nickname)
time.sleep(1)
join = self.client.get_command('Join').get_sender()
join.channels = [channel_name]
join.send()
else:
self.client.logger.info('User {0} was kicked from {1} by {2}'.format(victim, channel_name, event.source.nickname))
user = self.userlist.get(victim)
channel = self.chanlist.get(channel_name)
user.remove_channel(channel)
if len(user.get_channels()) == 0:
self.userlist.remove(user.source.nickname)
def process_quit(self, event):
"""
Process all incoming QUIT events.
If the bot quits, the channel list and user list are deleted.
If another user quits, the user is removed from the user list
and every channel's userlist the user had joined.
"""
if event.source.nickname == self.me.source.nickname:
self.chanlist = None
self.userlist = None
self.client.logger.info('I have quit from IRC')
else:
self.client.logger.info('User {0} has quit IRC'.format(event.source.nickname))
self.userlist.remove(event.source.nickname)
def process_nick(self, event):
"""
Process all incoming NICK events.
"""
if event.source.nickname == self.me.source.nickname:
return
new_nickname = event.parameter[0]
self.client.logger.info('User {0} is now known as {1}'.format(event.source.nickname, new_nickname))
self.userlist.rename(event.source.nickname, new_nickname)
def process_invite(self, event):
"""
Process all incoming INVITE events.
"""
channel_name = ''
nickname = ''
self.client.logger.info('I were invited into {0} by {1}'.format(channel_name, nickname))
pass
def process_topic(self, event):
"""
Process all incoming topic events.
"""
channel_name, topic = event.parameter
channel = self.chanlist.get(channel_name)
channel.topic = topic
def process_names(self, event):
"""
Process NAMES events.
TODO: handle user modes
"""
channel_name, nicklist = event.parameter[2:4]
channel = self.chanlist.get(channel_name)
for nickname in nicklist.split(SPACE):
if nickname.startswith(TOKEN_OP):
nickname = nickname[1:]
mode = Channel.USERMODE_OP
elif nickname.startswith(TOKEN_VOICE):
nickname = nickname[1:]
mode = Channel.USERMODE_VOICE
else:
mode = None
user = self.userlist.request(ClientSource(nickname=nickname))
user.set_data(KEY_ROLE, Role.USER)
user.add_channel(channel, mode)
if nickname != self.me.source.nickname:
whois = self.client.get_command('Whois').get_sender()
whois.user = nickname
whois.send()
def process_who(self, event):
"""
Process WHO events.
"""
print event.parameter
def process_whois_user(self, event):
"""
Process the user part of a WHOIS event.
"""
nickname = event.parameter[1]
ident = event.parameter[2]
host = event.parameter[3]
realname = event.parameter[5]
user = self.userlist.get(nickname)
user.source.ident = ident
user.source.host = host
user.source.realname = realname
self.client.logger.info('User information: {0} has Ident {1}, Hostname {2}, Realname {3}'.format(nickname, ident, host, realname))
def process_whois_idle(self, event):
"""
Process the idle part of a WHOIS event.
"""
nickname = event.parameter[1]
idle_time = event.parameter[2]
signon_time = event.parameter[3]
user = self.userlist.get(nickname)
user.set_data(KEY_IDLETIME, idle_time)
user.set_data(KEY_SIGNONTIME, signon_time)
self.client.logger.info('User information: {0} has idled {1} seconds'.format(nickname, idle_time))
self.client.logger.info('User information: {0} has signed on at {1}'.format(nickname, signon_time))
def process_whois_auth(self, event):
"""
Process the auth part of a WHOIS event.
"""
nickname = event.parameter[1]
auth = event.parameter[2]
user = self.userlist.get(nickname)
user.set_data(KEY_ROLE, Role.AUTHED)
user.set_data(KEY_AUTH, auth)
self.client.logger.info('User information: {0} is authed as {1}'.format(nickname, auth))
#---------------------------------------------------------------------------
# User management
#---------------------------------------------------------------------------
def list_user(self, request):
response = InteractiveModuleResponse('not implemented')
return response
def insert_user(self, request):
"""
.adduser [password]
"""
"""password = request.parameter[0]
try:
user = self.getAuth(request.source)
return "User '???' wurde als Admin hinzugefügt."
if not user:
raise UserNotAuthenticated
if self.isPrivateUser(user):
raise UserExists
# TODO impl
#password_hash = hashlib.sha1(password).hexdigest()
except UserNotAuthenticated:
return "Du bist nicht geauthed!"
except UserExists:
return "Du hast bereits einen Account!"
return "Dein Account wurde erstellt!"""
response = InteractiveModuleResponse('not implemented')
return response
def change_user(self, request):
response = InteractiveModuleResponse('not implemented')
return response
def delete_user(self, request):
response = InteractiveModuleResponse('not implemented')
return response
#---------------------------------------------------------------------------
# public API
#---------------------------------------------------------------------------
def get_role(self, nickname):
user = self.userlist.get(nickname=nickname)
try:
return user.get_data(identifier=KEY_ROLE)
except KeyError:
return Role.USER
class ChannelList(object):
"""
Maintain a list of channels the bot has joined.
The information this module contains include
- the channel name
- the channel topic
- the channel modes
- a list of ban masks
- a list of invite masks
- a list of users currently on each channel
"""
def __init__(self, client):
"""
Initialize the channel list.
"""
self.client = client
self.channels = {}
def __str__(self):
"""
Return a string representation for debugging purposes.
"""
return 'ChannelList(Channels={0})'.format('|'.join([str(channel) for channel in self.channels.values()]))
def add(self, channel):
"""
Add a channel object to the channel list.
If the channel name exists, it will be overwritten.
@param channel: A channel object.
"""
self.channels[channel.name] = channel
def request(self, name):
"""
Request a channel from the channel list by name.
If the channel does not exist, it will be created and returned.
@param name: The channel name.
@return A channel object.
"""
try:
return self.get(name)
except KeyError:
channel = Channel(name=name)
self.add(channel)
return channel
def get(self, name):
"""
Return a channel object from the channel list.
@param name: The channel name.
@return A channel object.
@raise KeyError If the channel does not exist.
"""
return self.channels[name]
def get_all(self):
"""
Return the current user list of the channel.
@return The user list.
"""
return self.channels
def remove(self, name):
"""
Remove a channel object from the channel list.
This will remove the channel from every user's channel list
who had joined chat channel.
@param name: The channel name.
@raise KeyError If the channel does not exist.
"""
channel = self.channels[name]
for user_tuple in channel.get_users().values():
user = user_tuple[0]
user.remove_channel(channel)
channel = None
del self.channels[name]
class UserList(object):
"""
Provide a List with User entities that are known to the bot. Each
user on a given IRC network only exists once in this list, even if
the user shares multiple channels with the bot.
Every channel is also maintaining a user list, but only uses
references to Userlist objects.
"""
def __init__(self, client):
"""
Create an empty user list.
"""
self.client = client
self.users = {}
def __str__(self):
"""
Return a string representation for debugging purposes.
"""
return 'Userlist(Users={0})'.format('|'.join([str(user) for user in self.users.values()]))
def add(self, user):
"""
Add a new User object to the list.
@param user: The user object.
"""
self.users[user.source.nickname] = user
def request(self, source, realname=''):
"""
Request a user from the user list by source.
If the user object does not exist, it will be created and returned.
@param name: The channel name.
@return A channel object.
"""
try:
return self.get(source)
except KeyError:
user = User(source=source, realname=realname)
self.add(user)
return user
def get(self, nickname):
"""
Return a user object by its nickname.
@param source: The source object of the user.
@return The user object, if existent.
@raise KeyError if no such user was found.
"""
return self.users[nickname]
def get_all(self):
"""
Return the current list of users known to the bot.
@return The user list.
"""
return self.users
def rename(self, current_nickname, new_nickname):
"""
Changes the nickname of a user.
@param current_nickname: The current nickname of the user
@param new_nickname: The new nickname of the user
"""
self.users[new_nickname] = self.users[current_nickname]
self.users[new_nickname].rename(new_nickname)
del self.users[current_nickname]
def remove(self, nickname):
"""
Remove a user object by its nickname from the user list.
Any references to channels the user had joined are also
removed.
@param source: The source object of the user.
@raise KeyError if no such user was found.
"""
user = self.get(nickname)
for channel in user.get_channels():
user.remove_channel(channel)
user = None
del self.users[nickname]
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: info.py 221 2011-07-21 18:25:10Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/interaction/irc/modules/info.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Jan 11, 2011
@author Mario Steinhoff
"""
from core.config import Config
from interaction.irc.module import Module
from interaction.irc.client import Message, Privilege
from
moduleName = "InfoModule"
class InfoModule(Module):
'''
Provide general information to users.
'''
class Config(Config):
def __init__(self, persistence):
valid = [
"help_url",
"twitter_url",
"info_url",
"ts_address",
"ts_port",
"ts_password"
]
Config.__init__("module-admin", persistence, valid);
def __init__(self, bot):
commands = [
(Message.PRIVMSG_CHANNEL, Message.PRIVMSG_CHANNEL, Privilege.USER, 'help', self.displayHelpURL),
(Message.PRIVMSG_CHANNEL, Message.PRIVMSG_CHANNEL, Privilege.USER, 'info', self.displayInfoURL),
(Message.PRIVMSG_CHANNEL, Message.PRIVMSG_CHANNEL, Privilege.USER, 'twitter', self.displayTwitterURL),
(Message.PRIVMSG_CHANNEL, Message.NOTICE, Privilege.USER, 'ts3', self.displayTeamspeakData),
(Message.PRIVMSG_CHANNEL, Message.NOTICE, Privilege.USER, 'todo', self.addTodoEntry),
(Message.PRIVMSG_USER, Message.NOTICE, Privilege.ADMIN, 'modlist', self.displayModuleList),
(Message.PRIVMSG_USER, Message.NOTICE, Privilege.ADMIN, 'ts3-updateaddr', self.updateTeamspeakAddress),
(Message.PRIVMSG_USER, Message.NOTICE, Privilege.ADMIN, 'ts3-updatepw', self.updateTeamspeakPassword),
]
Module.__init__(bot, commands)
def displayHelpURL(self, event, data):
message = ""
def displayInfoURL(self, event, data):
message = ""
def displayTwitterURL(self, event, data):
message = ""
def dislayModuleList(self, event, data):
List = ""
for i in InstanceModlist:
try:
r = re.search('<(?:.+)\.(.+?) instance at (?:.+)>',str(i)).group(1)
List += (", " if List != "" else "") + "'" + r + "'"
except:
pass
def displayTeamspeakData(self, event, data):
message = "Address: %s:%s - Password: %s" % (
self._config.ts_address,
self._config.ts_port,
self._config.ts_password
)
def updateTeamspeakAddress(self, address):
try:
matchlist = re.search("^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$",Text[1]).group(1,2,3,4)
except:
message = "Address: Ungültige IP-Adresse. Buchstabe in der IP"
try:
matchlist = re.search("^(\d{1,5})$",Text[1]).group(1)
except:
message = "Ungültiger Port! Deine Angabe enthält Zeichen oder ist zu lang."
for i in matchlist:
if int(i) > 255:
message = "Address: Ungültige IP-Adresse. Zu Hohe Zahlen"
return
if int(matchlist) > 65536:
message = "Ungültiger Port! Port muss zwischen 1-65536 liegen"
return
self._config.ts_address = Text[1]
self._config.ts_port = re.search("^(\d{1,5})$",Text[1]).group(1)
def updateTeamspeakPassword(self, event, data):
self._config.ts_password = data
def addTodoEntry(self, event, data):
self.Filename = "../public_html/fptbot.txt"
Source = re.match("(.+?)!",Source).group(1)
File = open(self.Filename, "a")
File.write("\t" + Text + "\t\trequested by " + Source + "\n")
File.close
message = "Auftrag wurde gespeichert!"
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: orakel.py 278 2012-02-23 21:19:11Z rackowitsch@gmail.com $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/interaction/irc/modules/orakel.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Mar, 03 2010
@author Rack Rackowitsch
@author Mario Steinhoff
"""
__version__ = '$Rev: 278 $'
import random
import re
from objects.irc import Location
from interaction.irc.module import InteractiveModule, InteractiveModuleCommand, InteractiveModuleResponse
#-------------------------------------------------------------------------------
# Business Logic
#-------------------------------------------------------------------------------
class Orakel(InteractiveModule):
"""
This module aids the user to make a decision.
"""
#---------------------------------------------------------------------------
# InteractiveModule implementation
#---------------------------------------------------------------------------
def module_identifier(self):
return 'Orakel'
def init_commands(self):
return [
InteractiveModuleCommand(
keyword='wer',
callback=self.who,
location=Location.CHANNEL
),
InteractiveModuleCommand(
keyword='decide',
callback=self.decide,
pattern=r'^((.+)$|$)',
syntaxhint='[Auswahl1[, [Auswahl2[, ...]]]]'
),
InteractiveModuleCommand(
keyword='makemyday',
callback=self.sort,
pattern=r'^(.+)$',
syntaxhint='[Item1[, Item2[, ...]]]'
)
]
#---------------------------------------------------------------------------
# module commands
#---------------------------------------------------------------------------
def who(self, request):
response = InteractiveModuleResponse()
channel_name = request.target
channel = self.usermgmt.chanlist.get(channel_name)
user = random.choice(channel.get_users().keys())
response.add_line('Meine Wahl fällt auf {0}!'.format(user))
return response
def decide(self, request):
response = InteractiveModuleResponse()
issue = request.parameter[0]
if len(issue) == 0:
if random.randint(1,1000) % 2 == 0:
response.add_line('Du solltst dich dafür entscheiden!')
else:
response.add_line('Du solltst dich dagegen entscheiden!')
else:
choices = re.sub('( oder | or )', ',', issue).split(',')
if len(choices) == 1:
pick = choices[0]
if random.randint(1,1000) % 2 == 0:
response.add_line('Du solltst dich für \'{0}\' entscheiden!'.format(pick.strip()))
else:
response.add_line('Du solltst dich gegen \'{0}\' entscheiden'.format(pick.strip()))
else:
pick = random.choice(choices)
response.add_line('Du solltst dich für \'{0}\' entscheiden'.format(pick.strip()))
return response
def sort(self,request):
"""
Reorder the given items.
@return: InteractiveModuleResponse()
"""
response = InteractiveModuleResponse()
items_unsorted = request.parameter[0].split(',')
items_sorted = []
while len(items_unsorted) > 0:
num = random.randint(0,len(items_unsorted)-1)
items_sorted.append(items_unsorted[num].strip())
del items_unsorted[num]
response.add_line(", ".join(items_sorted))
return response | Python |
# -*- coding: UTF-8 -*-
"""
$Id: calendar.py 270 2012-02-01 22:59:11Z steinhoff.mario $
$URL: https://fptbot.googlecode.com/svn/trunk/fptbot/src/python/interaction/irc/modules/calendar.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Mar, 03 2012
@author Rack Rackowitsch
@author Mario Steinhoff
"""
from objects.principal import Role
from objects.irc import Location
from interaction.irc.module import InteractiveModule, InteractiveModuleCommand, InteractiveModuleResponse, ModuleError
#-------------------------------------------------------------------------------
# Constants
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# Exceptions
#-------------------------------------------------------------------------------
class AdminError(ModuleError): pass
#-------------------------------------------------------------------------------
# Business Logic
#-------------------------------------------------------------------------------
class Admin(InteractiveModule):
"""
Control the bots IRC behavior.
"""
#---------------------------------------------------------------------------
# Module implementation
#---------------------------------------------------------------------------
def initialize(self):
"""
Initialize the module.
"""
self.me = self.client.me
#---------------------------------------------------------------------------
# InteractiveModule implementation
#---------------------------------------------------------------------------
def module_identifier(self):
return 'IRC-Administration'
def init_commands(self):
return [
InteractiveModuleCommand(
keyword='nick',
callback=self.change_nickame,
location=Location.QUERY,
role=Role.ADMIN,
pattern=r'^$',
syntaxhint='???'
),
InteractiveModuleCommand(
keyword='join',
callback=self.join_channel,
location=Location.QUERY,
role=Role.ADMIN,
pattern=r'^$',
syntaxhint='???'
),
InteractiveModuleCommand(
keyword='part',
callback=self.part_channel,
location=Location.QUERY,
role=Role.ADMIN,
pattern=r'^$',
syntaxhint='???'
),
InteractiveModuleCommand(
keyword='quit',
callback=self.quit,
location=Location.QUERY,
role=Role.ADMIN,
pattern=r'^$',
syntaxhint='???'
)
]
def change_nickname(self, request):
response = InteractiveModuleResponse('not implemented')
return response
def join_channel(self, request):
response = InteractiveModuleResponse('not implemented')
return response
def part_channel(self, request):
response = InteractiveModuleResponse('not implemented')
return response
def quit(self, request):
response = InteractiveModuleResponse('not implemented')
return response
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: roll.py 270 2012-02-01 22:59:11Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/interaction/irc/modules/roll.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Mar, 03 2010
@author Rack Rackowitsch
@author Mario Steinhoff
"""
__version__ = '$Rev: 270 $'
import random
from interaction.irc.module import InteractiveModule, InteractiveModuleCommand, InteractiveModuleResponse
#-------------------------------------------------------------------------------
# Business Logic
#-------------------------------------------------------------------------------
class Roll(InteractiveModule):
"""
This module provides a virtual dice.
"""
#---------------------------------------------------------------------------
# InteractiveModule implementation
#---------------------------------------------------------------------------
def module_identifier(self):
return 'Rollapparillo'
def init_commands(self):
return [
InteractiveModuleCommand(
keyword='roll',
callback=self.roll,
pattern=r'^([\d]+)(?:-([\d]+))?$',
syntaxhint='zahl[-zahl]'
)
]
#---------------------------------------------------------------------------
# module commands
#---------------------------------------------------------------------------
def roll(self, request):
response = InteractiveModuleResponse()
if request.parameter[1]:
min_value = int(request.parameter[0])
max_value = int(request.parameter[1])
else:
min_value = 1
max_value = int(request.parameter[0])
if max_value <= 0:
response.add_line('Zahl muss groesser als 0 sein')
return response
if max_value <= 1:
response.add_line('Zahl muss groesser als 1 sein')
return response
if max_value == min_value:
response.add_line('Erste Zahl ({0}) == zweite Zahl ({0}), wie soll das denn gehen du Trottel?'.format(min_value, min_value))
return response
if max_value < min_value:
max_value, min_value = min_value, max_value
result = random.randint(min_value, max_value)
response.add_line('{0} has rolled: {1} ({2}-{3})'.format(
request.source.nickname,
result,
min_value,
min_value
))
return response
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: funlink.py 221 2011-07-21 18:25:10Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/interaction/irc/modules/funlink.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Mar 26, 2010
@author rack
"""
import tinyurl
import re
from twitter import Twitter
from youtube import YouTube
from system import PrivMsg
class Funlink():
regexpattern = r':(.+) (?:PRIVMSG) ([\S]+) :.addurl(?: (.+))'
def __init__(self):
self.Twitter = Twitter("","")
self.YouTube = YouTube()
def handleInput(self,Matchlist):
Source = Matchlist[0]
Target = Matchlist[1]
Text = Matchlist[2].split()
try:
URL = tinyurl.create_one(Text[0])
except Exception:
PrivMsg(Target,"4Error in 'TINYURL.Modul' >> '" + str(Exception) + "'")
return
Nick = re.match("(.+?)!", Source).group(1)
if (len(Text) >= 2) or (re.search("(?:.+)youtube.com/(?:.+)v=(\w+)",Text[0]) and len(Text) == 1): #Beschreibung mit angegeben
x = "[" + Nick + "] "
#Zusatzinformation ermitteln, wie [YouTube] [PNG] [TIF]
if (re.search("(?:.+)youtube.com/(?:.+)v=(\w+)",Text[0])):
x += "[YouTube] "
elif (re.search("(\w+).rofl.to",Text[0])):
r = re.search("(\w+).rofl.to",Text[0]).group(1)
x += "[rofl.to] (" + str(r) +") "
elif (re.search("collegehumor.com/(\w+)",Text[0])):
r = re.search("collegehumor.com/(\w+)",Text[0]).group(1)
x += "[CollegeHumor] (" + str(r) + ")"
elif (re.search("newgrounds.com/",Text[0])):
x += "[Newsground] "
else:
try:
Tag = re.search("\.(bmp|jpg|gif|img|jp2|jpeg|png|psd|tga|tif|txt)$",Text[0]).group(1)
x += "[" + Tag.upper() + "] "
except:
pass
if (len(Text) > 1):
x += URL + " " + " ".join(Text[1:])
else:
r = re.search("(?:.+)youtube.com/(?:.+)v=([-_\w]+)",Text[0]).group(1)
t = self.YouTube.getInfo(r)
x += URL + " " + t
#Twitter Tweets dürfen nicht länger als 140 Zeichen sein
if (len(x) <= 140):
self.Twitter.sendTweet(x)
PrivMsg(Target,"hinzugefügt! - http://twitter.com/fptlnk","15Funlink:07 ")
else:
PrivMsg(Target,"Beschreibung zu lang. Max 140 Zeichen. Dein Add war " \
+ str(len(x)) + " Zeichen lang.","15Funlink:07 ")
else: #Keine Beschreibung
PrivMsg(Target,"Die Beschreibung fehlt!","15Funlink:07 ") | Python |
# -*- coding: UTF-8 -*-
"""
$Id: __init__.py 118 2011-02-09 22:14:45Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/interaction/irc/modules/__init__.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Jan 11, 2010
@author Mario Steinhoff
"""
__version__ = '$Rev: 118 $'
__all__ = [
# Internal modules
'usermgmt',
# Information
'info',
'kalender',
'quote',
'stats',
'topic',
'funlink',
# Games
'bombkick',
'satz',
# Everything else
'orakel',
'roll',
'wissen'
]
| Python |
# -*- coding: UTF-8 -*-
'''
Created on 24.02.2012
@author: rack
TODO: - limit .delquote to admin only?
'''
import logging
from interaction.irc.module import InteractiveModule, InteractiveModuleCommand, InteractiveModuleResponse
from components.quote import NoQuoteAvailable, NoAffectedRows
#-------------------------------------------------------------------------------
# Constants
#-------------------------------------------------------------------------------
MAX_LENGTH_QUOTE = 375
#-------------------------------------------------------------------------------
# Module 'Logic'
#-------------------------------------------------------------------------------
class Quote(InteractiveModule):
"""
This module provides quote functions
"""
def initialize(self):
self.me = self.client.me
self.logger = logging.getLogger('interaction.irc.quote')
self.component = self.client.bot.get_subsystem('quote-component')
def module_identifier(self):
"""
Declare the module identifier.
"""
return 'QuoteMod'
def init_commands(self):
"""
Declare all commands of the module.
"""
return [
InteractiveModuleCommand(
keyword='addquote',
callback=self.add_new_quote,
pattern=r'^(.+)$',
syntaxhint='<text>'
),
InteractiveModuleCommand(
keyword='delquote',
callback=self.del_quote,
pattern=r'^(\d+)$',
syntaxhint='<id>'
),
InteractiveModuleCommand(
keyword='quote',
callback=self.display_quote,
pattern=r'^(.+)$|^$',
syntaxhint='<id|text>'
),
InteractiveModuleCommand(
keyword='searchquote',
callback=self.search_quotes,
pattern=r'^(.+)$',
syntaxhint='<text>'
)
]
def display_quote(self, request):
"""
Select a quote from database and post it to a channel.
Usage: .quote [<text>|<id>]
@param request: A runtime request of an InteractiveModule command.
@return InteractiveModuleResponse
"""
response = InteractiveModuleResponse()
try:
text = request.parameter[0]
if (len(text) > 0):
try:
id = int(text)
quote = self.component.get_quote_by_id(id)
except ValueError:
quote = self.component.get_random_quote_by_string(request.parameter[0])
else:
quote = self.component.get_random_quote()
response.add_line("{0} ({1})".format(quote.text,quote.id))
except NoQuoteAvailable:
response.add_line("No quotes in database.")
return response
def add_new_quote(self, request):
"""
Add a new quote to database.
Max length of the quote is 375 letters.
Usage: .addquote <text>
@param request: A runtime request of an InteractiveModule command.
@return InteractiveModuleResponse
"""
response = InteractiveModuleResponse()
text = request.parameter[0]
if len(text) <= MAX_LENGTH_QUOTE:
self.component.insert_quote(text,request.source.nickname)
response.add_line("The process was successful.")
else:
response.add_line("Max length of a quote is {0} letters. Yours is {1}."
.format(MAX_LENGTH_QUOTE,str(len(text))))
return response
def del_quote(self,request):
"""
Delete a quote with the given id from database.
Usage: .delquote <id>
@param request: A runtime request of an InteractiveModule command.
@return InteractiveModuleResponse
"""
response = InteractiveModuleResponse()
try:
id = int(request.parameter[0])
self.component.delete_quote_by_id(id)
response.add_line("Delete was successful.")
except ValueError:
response.add_line("If you like to delete a quote, you'll have to declare an ID instead of a string.")
except NoAffectedRows:
response.add_line("Delete didn't work. Maybe, there isn't a quote with the given ID.")
return response
def search_quotes(self,request):
"""
Search in database for quote with the given string.
It will display all IDs of the founded quotes
Usage: .searchquote <text>
@param request: A runtime request of an InteractiveModule command.
@return InteractiveModuleResponse
"""
response = InteractiveModuleResponse()
ids = self.component.get_ids_by_string(request.parameter[0])
if len(ids) > 0:
response.add_line("Found the string in following quotes: {0}".format(" ".join(str(ids))))
else:
response.add_line("There isn't a quote with the given id.")
return response | Python |
# -*- coding: UTF-8 -*-
"""
$Id: bombkick.py 249 2011-09-27 00:31:00Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/interaction/irc/modules/bombkick.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since May 01, 2010
@author rack
"""
class Bombkick():
regexpattern = r':(.+) PRIVMSG ([\S]+) :(?:(\.schwarz|\.rot|\.gelb|\.blau|\.weiss|\.lila)|\.bombkick(?:$| ([\S]+)$)|(.bombstats))'
def __init__(self):
self.FilenameDB = "db/bombkick.db"
self.Config = Config()
self.Channel = self.Config.Channel
x = file2obj(self.FilenameDB)
self.BombDB = (x if x != False else {})
self.Colors = ["schwarz","rot","gelb","blau","weiss","lila"]
def handleInput(self,Matchlist):
Source = Matchlist[0]
if (Matchlist[2] == '') and (Matchlist[3] == '') and (Matchlist[4] == ''):
self.setBomb(self.getUsername(Source),re.match("(.+?)!", Source).group(1))
elif (Matchlist[3] != '') and (Matchlist[4] == ''):
if (self.isInChannel(Matchlist[3])) and (Matchlist[3] != self.Config.cnick):
self.setBomb(self.getUsername(Matchlist[3] + '!'),Matchlist[3])
elif (Matchlist[2] != '') and (Matchlist[4] == ''):
self.defuseBomb(self.getUsername(Source),Matchlist[2][1:])
elif (Matchlist[4] == ".bombstats"):
self.BombStats()
def shutdown(self):
obj2file(self.BombDB, self.FilenameDB)
print ">> Bombstats saved!"
def isInChannel(self,Nick):
if (self.Config.Nicklist.has_key(Nick)):
return True
return False
def getUsername(self,Source):
n = re.match("(.+?)!", Source).group(1)
if (self.Config.Nicklist[n][1] != ""):
return self.Config.Nicklist[n][1]
return self.Config.Nicklist[n][2]
def getColors(self):
x = random.randint(3,5)
Colorlist = deepcopy(self.Colors)
Colors = []
y = 1
while (y <= x):
ColorID = random.randint(0,len(Colorlist)-1)
Colors.append(Colorlist[ColorID])
del Colorlist[ColorID]
y += 1
ID = random.randint(0,2)
#print Colors[ID] + ' ' + str(Colors)
return Colors[ID],Colors
def setBomb(self,Auth,Nick):
if ('@' in self.Config.Nicklist[self.Config.cnick][0]):
if (self.BombDB.has_key(Auth) == False):
#[Bombs defused,Failed defused,[Bombs in a row,'+' or '-'],[aktive timer,colors,color],nick]
self.BombDB[Auth] = [0,0,[0,'+'],[None,[],""],'']
if (self.BombDB[Auth][3][0] is None):
Bombtimer = Timer(20,self.fireBomb,[Auth])
Color, Colors = self.getColors()
self.BombDB[Auth][3][0] = Bombtimer
self.BombDB[Auth][3][1] = Colors
self.BombDB[Auth][3][2] = Color
self.BombDB[Auth][4] = Nick
self.BombDB[Auth][3][0].start()
PrivMsg(self.Channel,"ACTION gibt " + Auth + " eine Bombe in die Hand!" \
+ " Versuch das richtige Kabel durchzuschneiden mit " + self.getColorString(Colors)\
+ "!!! Schnell, du hast nur 20 Sekunden!")
def fireBomb(self,Auth):
self.BombDB[Auth][1] += 1
if (self.BombDB[Auth][2][1] == '-'):
self.BombDB[Auth][2][0] += 1
else:
self.BombDB[Auth][2][0] = 1
self.BombDB[Auth][2][1] = '-'
try:
self.BombDB[Auth][3][0].cancel()
except:
pass
self.BombDB[Auth][3][0] = None
BOOMs = self.BombDB[Auth][1]
ServerMsg("KICK " + self.Channel + " " + self.BombDB[Auth][4] \
+ " :Du bist zum " + str(BOOMs) + ". mal in die Luft geflogen.")
def defuseBomb(self,Auth,Color):
if (self.BombDB[Auth][3][2] != Color):
self.fireBomb(Auth)
else:
self.BombDB[Auth][0] += 1
if (self.BombDB[Auth][2][1] == '+'):
self.BombDB[Auth][2][0] += 1
else:
self.BombDB[Auth][2][0] = 1
self.BombDB[Auth][2][1] = '+'
try:
self.BombDB[Auth][3][0].cancel()
except:
pass
self.BombDB[Auth][3][0] = None
PrivMsg(self.Channel, Auth + " hats geschafft! Er hat zum " \
+ str(self.BombDB[Auth][0]) + ". mal die Bombe entschärft!")
def getColorString(self,Colors):
String = ""
x = 0
while (x < len(Colors)):
String += '.' + Colors[x] + (', ' if (x < len(Colors)-1) else '')
x += 1
return String
def BombStats(self):
DefuseKitUser = "" #+ in a row
DefuseKitNum = 0
LearningByDoing = "" #most bombs
LearningNum = 0
ChooseADiffJob = "" #most boooms
JobNum = 0
PassingLane = "" #- in a row
LaneNum = 0
Pro = "" #most defuse
ProNum = 0
for key,value in self.BombDB.iteritems():
if (value[2][1] == '+'):
if (value[2][0] > DefuseKitNum):
DefuseKitUser = key
DefuseKitNum = value[2][0]
else:
if (value[2][0] > LaneNum):
PassingLane = key
LaneNum = value[2][0]
if (value[0]+value[1] > LearningNum):
LearningByDoing = key
LearningNum = value[0]+value[1]
if (value[1] > JobNum):
ChooseADiffJob = key
JobNum = value[1]
if (value[0] > ProNum):
Pro = key
ProNum = value[0]
Timer(0,PrivMsg,[self.Channel,"'" + LearningByDoing + "' macht es nach dem 'learning by doing' Prinzip und hat sich schon " + str(LearningNum) + " mal zum Bombenentschärfen gemeldet."]).start()
Timer(1,PrivMsg,[self.Channel,"'" + DefuseKitUser + "' benutzt anscheinend ein DefuseKit. Er hat " + str(DefuseKitNum) + " Bombe(n) hintereinander entschärft!"]).start()
Timer(2,PrivMsg,[self.Channel,"'" + ChooseADiffJob + "' sollte sich besser einen anderen Job suchen. Bei ihm ist die Bombe " + str(JobNum) + " mal explodiert."]).start()
Timer(3,PrivMsg,[self.Channel,"'" + PassingLane + "' ist auf einem guten Weg '" + ChooseADiffJob + "' zu überholen. Die letzten " + str(LaneNum) + " Bomben sind ihm explodiert."]).start()
Timer(4,PrivMsg,[self.Channel,"Am besten nehmen alle Nachhilfe bei '" + Pro + "', denn er hat schon " + str(ProNum) + " Bomben entschärft!"]).start()
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: satz.py 249 2011-09-27 00:31:00Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/interaction/irc/modules/satz.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Apr 08, 2010
@author rack
"""
import re
import time
import random
import datetime
from copy import deepcopy
from threading import Timer
from config import Config
from system import file2obj,obj2file,PrivMsg
class Satz():
regexpattern = r':(.+) PRIVMSG ([\S]+) :(?:.fail (.+)|.satz(?:([\S]+)\s?([\S]*)$| ([\S]+)|$))'
__CharSet = {\
'a': 1,'b': 3,'c': 2,'d': 2,'e': 1,'f': 3,'g': 2,'h': 2,'i': 1,
'j': 4,'k': 3,'l': 2,'m': 2,'n': 1,'o': 3,'p': 4,'q': 4,'r': 1,
's': 1,'t': 2,'u': 2,'v': 4,'w': 3,'x': 4,'y': 4,'z': 3
}
'''
.satz -> Satzausgabe
.satz <wort> -> Wort anhängen
.satz.score -> akutelle Highscore
.satz.highscore -> Gesamthighscore
.satz.reset -> Satz löschen, ohne -Punkte berechnen
.fail <nick> -> Satz löschen mit -Punkten berechnen
'''
def __init__(self):
self.Config = Config()
self.__FilenameCfg = "satz.conf"
self.__SatzDB = "db/satz.db"
self.__SaveSettingsInterval = 3000 #secs
self.__Channel = self.Config.Channel
self.__Run = True
#Loading settings -- BEGIN --
s = file2obj(self.__FilenameCfg)
if (s != False):
self.__Highscore = s[0]
self.__Score = s[1]
self.__Satz = s[2]
self.__NickBan = s[3]
else:
self.__Run = False
#Loading settings -- END --
h = file2obj(self.__SatzDB)
if (h != False):
self.__SatzHistory = h
else:
self.__Run = False
self.__Votes = {}
self.__Wortreservierung = []
self.__LastPostTime = time.time()
self.__tmpVoter = ""
self.Timer = Timer(self.__SaveSettingsInterval,self.isNextDay,[datetime.date.today()])
self.Timer.start()
def shutdown(self):
if (self.__Run):
self.saveConfig()
self.Timer.cancel()
print ">> Satz-config saved!"
def saveConfig(self):
varConfig = [self.__Highscore,self.__Score,self.__Satz,self.__NickBan]
obj2file(varConfig, self.__FilenameCfg)
obj2file(self.__SatzHistory, self.__SatzDB)
def handleInput(self,Matchlist):
#print str(Matchlist) #('rack!~rack@rack.users.quakenet.org', '#rack', '', '', '.satz', '', '')
Source = Matchlist[0]
Target = Matchlist[1]
if (self.__Run):
if (Matchlist[3] == "") and (Matchlist[2] == ""): #.satz <wort>
self.__addWort(Source,Target,Matchlist[5])
elif (Matchlist[3] == ".score"):
PrivMsg(Target, "Punktestande (Runde): " + self.__getScore(),"15SatzSpiel: 7")
elif (Matchlist[3] == ".highscore"):
PrivMsg(Target, "Punktestande (Gesamt): " + self.__getHighscore(),"15SatzSpiel: 7")
elif (Matchlist[3] == ".verkackt") and (Matchlist[4] != ""):
self.__votePlayer(Source, Target, Matchlist[4])
elif (Matchlist[3] == ".old"):
if (Matchlist[4] != ""): #ID mit angegeben!
try:
ID = int(Matchlist[4])
if (ID > 0) and (ID <= len(self.__SatzHistory)):
length = len(self.__SatzHistory)
Sentence = self.__getHistorySentence(ID-1)
PrivMsg(Target, "'" + " ".join(Sentence[0][0:]) + "' verkackt von '"
+ Sentence[1] + "' [" + str(ID) + "/" + str(length) + "]","15SatzSpiel: 7")
else:
PrivMsg(Target, "Die ID muss zwischen 1 und "
+ str(len(self.__SatzHistory)) + " liegen.","15SatzSpiel: 7")
except:
PrivMsg(Target, "ID muss eine Zahl sein!","15SatzSpiel: 7")
else:
Sentence, ID = self.__getHistorySentence()
PrivMsg(Target, "'" + " ".join(Sentence[0][0:]) + "' verkackt von '"
+ Sentence[1] + "' [" + str(ID) + "/" + str(len(self.__SatzHistory)) + "]","15SatzSpiel: 7")
elif (Matchlist[3] == ".reset"):
if (len(self.__Satz) > 0):
self.__MergeScore()
else:
PrivMsg(Target, "Es gibt keine Satzrunde zum reseten!","15SatzSpiel: 7")
elif (Matchlist[2] != ""): #.fail nick ->> nick = Matchlist[2]
self.__votePlayer(Source, Target, Matchlist[2])
else:
PrivMsg(Target, "Fehler beim Laden der Cfg-Datei! Spielen NICHT möglich","15SatzSpiel: 7")
def isNextDay(self,Date):
today = datetime.date.today()
if (today != Date):
self.saveConfig()
self.Timer = Timer(self.__SaveSettingsInterval,self.isNextDay,[datetime.date.today()])
self.Timer.start()
def __getHistorySentence(self,ID=None):
if (ID is not None):
return self.__SatzHistory[ID]
else:
ID = random.randint(1,len(self.__SatzHistory))
return self.__SatzHistory[ID-1],ID
def __getSatz(self):
return " ".join(self.__Satz[0:])
def __getScore(self):
return str(self.__Score)
def __getHighscore(self):
return str(self.__Highscore)
def __votePlayer(self,Source,Target,Vote):
if (self.Config.Nicklist.has_key(Vote)):
Player = self.__getPlayer(Vote)
Voter = re.match("(.+?)!", Source).group(1)
self.__tmpVoter = self.__getPlayer(Voter)
elif (self.__Score.has_key(Vote)):
Player = Vote
Voter = re.match("(.+?)!", Source).group(1)
self.__tmpVoter = self.__getPlayer(Voter)
else:
PrivMsg(Target, "Es spiel kein Spieler mit dem Namen '" \
+ Vote + "' mit.","15SatzSpiel: 7")
return
if (self.__Votes.has_key(Player)):
x = self.__Votes[Player]
x = x.split(",")
if (self.__tmpVoter in x == False):
self.__Votes[Player] += "," + self.__tmpVoter
self.__tmpVoter = ""
else:
PrivMsg(self.__Channel, "Du hast bereits '" + Player \
+ "' nominiert!","15SatzSpiel: 7")
return
else:
if (self.__Score.has_key(Player)):
self.__Votes[Player] = self.__tmpVoter
self.__tmpVoter = ""
else:
PrivMsg(self.__Channel, "Es spielt kein Spieler mit dem Auth/Ident '"
+ Player + "' mit.","15SatzSpiel: 7")
return
PrivMsg(self.__Channel, "'" + Player + "' wurde bisher von '" \
+ str(self.__Votes[Player]) + "' nominiert! Benötigt werden " \
+ (str(len(self.__Score)-1) if len(self.__Score) < 6 else str(int(len(self.__Score)/2))) \
+ " Nominierungen.","15SatzSpiel: 7")
#Punkteberechnung für 5 oder weniger Spieler: Regel "n-1"
if (len(self.__Votes) < 6):
Voters = self.__Votes[Player]
if (Voters.count(",")+1 >= len(self.__Score)-1):
pkt = int((self.__calcScore(self.__Satz[len(self.__Satz)-1]) + 100 - len(self.__Satz)) * 1.9)
PrivMsg(self.__Channel, "4'" + Player + "' hat den Satz verkackt und bekommt dafür -" \
+ str(pkt) + " Punkte","15SatzSpiel: 7")
self.__MergeScore(pkt,Player)
else:
Voters = self.__Votes[Player]
if (Voters.count(",")+1 >= int(len(self.__Score)/2)):
pkt = int((self.__calcScore(self.__Satz[len(self.__Satz)-1]) + 100 - len(self.__Satz)) * 1.9)
PrivMsg(self.__Channel, "4'" + Player + "' hat den Satz verkackt und bekommt dafür -" \
+ str(pkt) + " Punkte","15SatzSpiel: 7")
self.__MergeScore(pkt,Player)
def __getPlayer(self,Nick):
if (self.Config.Nicklist.has_key(Nick)):
n = self.Config.Nicklist[Nick]
if (n[1] != ''):
return n[1]
else:
return n[2]
return Nick
def __addWort(self,Source,Target,Wort=""):
if (time.time() - self.__LastPostTime > 2):
Nick = re.match("(.+?)!", Source).group(1)
if (Wort == ""): #satz ausgeben
tmp = self.__getSatz()
if (tmp == ""): #Gibt noch keinen Satz
tmp = "Fang einen neuen Satz an!"
PrivMsg(Target, tmp,"15SatzSpiel: 7")
return
#Wortreservierungsteil
#Falls jmd anderes zuvor schreibt, wird geblockt
if (Wort != "") and (len(self.__Wortreservierung) > 0):
if (time.time() - self.__Wortreservierung[1] < 30):
if (self.__getPlayer(Nick) != self.__Wortreservierung[0]):
PrivMsg(Target, "Du bist nicht " + self.__Wortreservierung[0],"15SatzSpiel: 7")
return
else:
# "30 sek abgelaufen"
self.__Wortreservierung = []
#Wenn jmd ein Komma schreibt, darf er das nächste Wort noch anfügen. Zeit -> 30 Sekunden
if (Wort == ",") and (self.__getPlayer(Nick) != self.__NickBan) and (len(self.__Wortreservierung) == 0):
self.__Wortreservierung.append(self.__getPlayer(Nick))
self.__Wortreservierung.append(time.time())
PrivMsg(Target, Nick + " hat eine Wortreservierung für 30 Sekunden.","15SatzSpiel: 7")
self.__Satz[len(self.__Satz)-1] += Wort
return
#Sonderzeichen ersetzen
subWort = Wort.replace('ä','ae')\
.replace('ö','oe')\
.replace('ü','ue')\
.replace('ß','ss')\
.replace('#','4')\
.replace('-','4')\
.replace("'",'4')\
.replace('@','4')\
.replace('#','4')\
.replace('.','4')\
.replace('"','4')
#Wort hat keine Sonderzeichen mehr und der Spieler ist nicht geblockt!
if (subWort.isalnum()) and (self.__NickBan != self.__getPlayer(Nick)):
#Das Wort gibt es schon
if (self.__Satz.count(Wort)):
x = self.__calcScore(subWort) + 100 - len(self.__Satz) #Minuspunkte
Player = self.__getPlayer(Nick)
if (self.__Score.has_key(Player)): #Spieler hat bereits Punkte
for nick in self.__Score.iterkeys():
if (Player == nick):
self.__Score[nick] -= x #Punkte werden abgezogen
break
else: #Spieler wird für diese Runde neu angelegt
self.__Score[Player] = x * -1
PrivMsg(Target, "4 Das Wort " + Wort + " ist bereits im Satz. " \
+ Nick + " bekommt deswegen " + str(x) + " Punkte abgezogen!","15SatzSpiel: 7")
return
#Wort ist noch nicht im Satz
else:
x = self.__calcScore(subWort) + len(self.__Satz) #Punkte für das Wort
Player = self.__getPlayer(Nick)
if (self.__Score.has_key(Player)):
self.__Score[Player] += x #Punkte werden auf's Konto gutgeschrieben
else:
self.__Score[Player] = x
self.__Satz.append(Wort)
#Damit man nicht 2 Wörter hintereinander schreiben kann
self.__NickBan = self.__getPlayer(Nick)
#Falls es eine Wortreservierung gab, wird diese aufgehoben
if (len(self.__Wortreservierung) > 0):
self.__Wortreservierung = []
#Ausgabe der letzten Wörter des Satzes
if (len(self.__Satz) > 10):
PrivMsg(Target, " ".join(self.__Satz[len(self.__Satz)-10:]),"15SatzSpiel: 7")
else:
PrivMsg(Target, "..." + " ".join(self.__Satz),"15SatzSpiel: 7")
#"Doppelpost"-Spamprotection
self.__LastPostTime = time.time()
else:
PrivMsg(Target, "4 Du hast bereits dass letzte Wort angehängt!","15SatzSpiel: 7")
def __calcScore(self,Wort):
'''
Berechnet die Punkte für das übgergebende Wort anhand des "CharSet"
'''
Points = 0
Wort = Wort.lower()
for char in Wort:
try:
x = int(char)
Points += x
except:
for key,value in self.__CharSet.iteritems():#super(Satz,self).__CharSet.iteritems():
if (char == key):
Points += value
break
return Points
def __MergeScore(self,Punkte=0,Loser=None):
#Punkteabzug für die Verlierer
if (self.__Score.has_key(Loser)):
self.__Score[Loser] -= Punkte
Name = Loser
Score = self.__Score[Loser]
else:
Name = ""
Score = 0
#Ausgabe des Gewinnters
for Key,Value in self.__Score.iteritems():
if (Value > Score):
Name = Key
Score = Value
PrivMsg(self.__Channel, "Der Gewinner dieser Runde ist '" \
+ Name + "' mit " + str(Score) + " Punkten. Es kann eine neue Runde " \
+ "mit .satz <wort> angefangen werden.","15SatzSpiel: 7")
#Übertragen der Punkte
#Punkte auf vorhandene Konten überspielen
var_score = deepcopy(self.__Score)
var_highscore = deepcopy(self.__Highscore)
for Key,Value in var_score.iteritems():
for Ident in var_highscore.iterkeys():
if (Key == Ident):
self.__Highscore[Ident] += Value
del self.__Score[Key]
break
#Konten für neue Spieler anlegen
for Key,Value in self.__Score.iteritems():
self.__Highscore[Key] = Value
self.__resetSatz(Loser)
def __resetSatz(self,Loser=None):
if (len(self.__Satz) > 0):
self.__SatzHistory.append([self.__Satz,Loser])
self.__Satz = []
self.__Score= {}
self.__NickBan = ""
self.__Votes = {}
self.__tmpVoter = "" | Python |
# -*- coding: UTF-8 -*-
"""
$Id: client.py 281 2012-03-08 19:38:55Z steinhoff.mario@googlemail.com $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/interaction/irc/client.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Jan 06, 2011
@author Mario Steinhoff
"""
__version__ = '$Rev: 281 $'
import logging
import socket
import asyncore
import asynchat
import traceback
from core import runlevel
from core.config import Config
from objects.irc import ClientSource, User
from interaction.interaction import Interaction
from interaction.irc import commands
from interaction.irc.message import Message
from interaction.irc.networks import quakenet
#-------------------------------------------------------------------------------
# Constants
#-------------------------------------------------------------------------------
CRLF = '\x0D\x0A'
#-------------------------------------------------------------------------------
# Business Logic
#-------------------------------------------------------------------------------
class Client(Interaction, asynchat.async_chat):
"""
Provide a RFC 2812 compilant IRC client implementation using asyncore.
"""
RUNLEVEL = runlevel.Runlevel(
autoboot=True,
minimum_start=runlevel.NETWORK_INTERACTION
)
def __init__(self, bot):
"""
Initialize the IRC client.
@param bot: The bot instance that this client should use.
"""
Interaction.__init__(self, bot)
asynchat.async_chat.__init__(self)
self.set_terminator(CRLF)
self._commands = {}
self._recvname = {}
self._recvtoken = {}
self._modules = {}
self.bot.register_config(ClientConfig)
self.config = self.bot.get_config(ClientConfig.identifier)
self.logger = logging.getLogger(ClientConfig.identifier)
self.me = User(
source=ClientSource(nickname=self.config.get('nickname'), ident=self.config.get('ident')),
realname=self.config.get('realname')
)
self.register_commands()
self.load_modules()
#---------------------------------------------------------------------------
# protocol commands
#---------------------------------------------------------------------------
def register_commands(self):
"""
Register default command handlers that implement protocol
functionality.
"""
for command in commands.list:
self.register_command(getattr(commands, command, None))
for command in quakenet.list:
self.register_command(getattr(quakenet, command, None))
def register_command(self, command):
"""
Register a command handler.
The command will be registered by it's token. If a command with
the same token already exists, it will be overwritten.
@param command: A pointer to the handler class.
"""
if command is None:
return
name = command.__name__
token = command.token
self.logger.debug('registering command handler: (Name=%s,IRCToken=%s)', name, token)
instance = command(self)
receiver = instance.get_receiver()
self._commands[name] = instance
self._recvname[name] = receiver
self._recvtoken[token] = receiver
def get_command(self, name):
"""
Get a command handler.
@param name: The command name.
"""
return self._commands[name]
def unregister_command(self, name):
"""
Remove a command handler.
@param token: The command token.
"""
token = self._commands[name].token
del self._commands[name]
del self._recvname[name]
del self._recvtoken[token]
#---------------------------------------------------------------------------
# client modules
#---------------------------------------------------------------------------
def load_modules(self):
"""
Load all configured modules.
"""
for module in self.config.get('modules'):
self.load_module(module)
def load_module(self, name):
"""
Load a client module that extends the client's functionality.
This will import a python module located in interaction.irc.modules
using python's __import__ builtin.
The class that contains all the module logic must be named after
the module name and must be in CamelCase.
If the import was successful, the class is instanciated and its
receive listeners are registered with all commands currently known.
@param name: The name of the module that should be loaded.
@return The module object.
"""
self.logger.debug('initializing module: %s', name)
classname = 'interaction.irc.modules.{0}.{1}'.format(name, name.capitalize())
clazz = self.bot.get_object(classname)
instance = clazz(self)
self._modules[name] = instance
for command_name, listener in instance.get_receive_listeners().items():
self.logger.debug('registering receive listener: (Module=%s,Listener=%s)', name, command_name)
self._recvname[command_name].add_listener(listener)
self.logger.debug('initialized module: %s', name)
return instance
def get_module(self, name):
"""
Return a given module instance.
@param name: The name of the module that should be returned.
@return The module instance, a subclass of Module.
@raise KeyError if there is no such module
"""
return self._modules[name]
#---------------------------------------------------------------------------
# connection handling
#---------------------------------------------------------------------------
def _start(self):
"""
Connect to the IRC server.
This method creates a streaming socket, connects to the IRC
server defined in the local Config-object and starts the
asyncore event loop.
Implementation of Subsystem.start()
"""
self.logger.info('starting client')
try:
self.logger.info('starting modules')
for module_name, module in self._modules.items():
try:
self.logger.info('starting module %s', module_name)
module.start()
except Exception as msg:
self.logger.error('starting module %s failed: %s', module_name, msg)
self.logger.info('starting modules done')
self.logger.info('connecting to %s:%d', self.config.get('address'), self.config.get('port'))
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((self.config.get('address'), self.config.get('port')))
self._buffer = []
asyncore.loop()
except Exception as msg:
for module_name, module in self._modules.items():
try:
self.logger.info('stopping module %s because starting the client failed', module_name)
module.stop()
except Exception as msg:
self.logger.error('starting the client failed and stopping module %s failed: %s', module_name, msg)
raise msg
def _stop(self):
"""
Disconnect from the IRC server.
This message tells asyncore to close the connection after all
queued messages were sent.
Implementation of Subsystem.stop()
"""
self.logger.info('stopping client')
self.pre_disconnect()
self.close_when_done()
#---------------------------------------------------------------------------
# connection trigger
#---------------------------------------------------------------------------
def pre_connect(self):
"""
This trigger is called after the socket is opened.
It will send the USER and NICK commands according to the RFC.
The parameters are retrieved from the local Config-Object.
As this method is only called once, error conditions such as
nickname in use are catched and handled by high-level IRC commands.
"""
self.logger.info('Registering connection, Nickname: %s, Realname: %s, Ident: %s', self.me.source.nickname, self.me.realname, self.me.source.ident)
nick = self.get_command('Nick').get_sender()
nick.nickname = self.me.source.nickname
user = self.get_command('User').get_sender()
user.ident = self.me.source.ident
user.realname = self.me.realname
nick.send()
user.send()
def post_connect(self):
"""
This trigger is called after the MOTD or the NoMotdError was
received.
"""
channels = self.config.get('channels')
self.logger.info('Connected to server.')
self.logger.info('Joining channels: %s', ','.join(channels))
join = self.get_command('Join').get_sender()
join.channels = channels
join.send()
self._running()
def pre_disconnect(self):
"""
This trigger is called before the connection will be closed.
"""
self.get_command('Quit').get_sender().send()
def post_disconnect(self):
"""
This trigger is called after the connection was closed.
"""
self._halted()
#---------------------------------------------------------------------------
# low-level communication
#---------------------------------------------------------------------------
def receive_event(self, event):
"""
Handle all incoming IRC events.
This method is called every time an IRC event is generated by
asyncore. It receives the Event and implements the dispatching
for both low-level IRC functionality and bot commands based on
IRC commands.
@param event: A event instance with the message data.
"""
self.logger.info('Received: <%s> %s: %s', event.source, event.command, event.parameter)
try:
receiver = self._recvtoken[event.command]
except KeyError:
return
try:
receiver.receive(event)
except:
traceback.print_exc()
def send_event(self, event):
"""
Handle all outgoing IRC events.
This method creates a Message object from the Event, adds
message separation characters to the string representation of
the message and pushes that data to the asyncore socket.
@param event: A event instance with the message data.
"""
message = event.create_message()
self.logger.info('Sent: <%s> %s: %s', event.source, event.command, event.parameter)
self.push('{0}{1}'.format(message, CRLF))
#---------------------------------------------------------------------------
# asyncore implementation
#---------------------------------------------------------------------------
def handle_connect(self):
"""
Send IRC specific commands when connecting.
This method is called by asyncore after the first read or write
event occured and will call the pre_connect hook.
"""
self.pre_connect()
def handle_close(self):
"""
Close socket after connection is closed.
"""
self.close()
self.post_disconnect()
for module_name, module in self._modules.items():
try:
self.logger.info('stopping module %s', module_name)
module.stop()
except Exception as msg:
self.logger.error('stopping module %s failed: %s', module_name, msg)
#---------------------------------------------------------------------------
# asynchat implementation
#---------------------------------------------------------------------------
def collect_incoming_data(self, data):
"""
Add any received data to the internal buffer.
This will be called by asynchat whenever new data hits the
socket. The data gets added to the internal buffer. The buffer
gets cleaned as soon as found_terminator() is called.
"""
self._buffer.append(data)
def found_terminator(self):
"""
Send event when a command terminator was found.
This will be called by asynchat whenever the command terminator
was found. It will copy all received data from the internal
buffer and reset the buffer. Then the IRC message separator
characters are removed from the end of the line. The message
will be parsed into an Event object with the content of the
message cleanly separated. Finally, receive_event() is called,
where the message can be further dispatched.
"""
data = self._buffer
self._buffer = []
"""
This is possible since this method gets called right after CRLF
is detected, so there should only be one message in the buffer
at call-time. If there is more than one element/message in the
buffer, everthing could get screwed really hard.
FIXME: find better way to do this
"""
data = ''.join([line.strip(CRLF) for line in data])
try:
data = unicode(data, 'utf8')
except UnicodeDecodeError:
pass
message = Message(data)
self.receive_event(message.create_event())
class ClientConfig(Config):
identifier = 'interaction.irc'
def valid_keys(self):
return [
'nickname',
'anickname',
'realname',
'ident',
'address',
'port',
'modules',
'channels',
]
def default_values(self):
return {
'nickname' : 'Bot',
'anickname' : 'Bot-',
'realname' : 'Bot',
'ident' : 'bot',
'address' : 'irc.example.org',
'port' : 6667,
'modules' : ['usermgmt'],
'channels' : ['#test']
}
| Python |
# -*- coding: UTF-8 -*-
"""
$Id$
$URL$
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since 06.01.2010
@author Mario Steinhoff
"""
__version__ = '$Rev$'
from interaction.irc.commands import Command
list = [
'WhoisAuthReply'
]
class Auth(Command):
"""
Command: AUTH
Parameters: <username> <password>
AUTH command is used to authenticate user with Quakenet Q9 service.
"""
token = 'AUTH'
class Sender(Command.Sender):
def _send(self):
"""
Authenticate with Quakenet Q9 service.
"""
self.check_attr('username')
self.check_attr('password')
return self.create_event(Auth, [self.username, self.password])
class WhoisAuthReply(Command):
token = '330'
| Python |
# -*- coding: UTF-8 -*-
"""
$Id$
$URL$
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since 06.01.2010
@author Mario Steinhoff
"""
__version__ = '$Rev$'
__all__ = [
'quakenet'
]
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: commands.py 281 2012-03-08 19:38:55Z steinhoff.mario@googlemail.com $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/interaction/irc/commands.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Jan 14, 2011
@author Mario Steinhoff
"""
__version__ = '$Rev: 281 $'
list = [
'Nick', 'User', 'Mode', 'Quit',
'Join', 'Part', 'Topic', 'Names', 'Invite', 'Kick',
'Privmsg', 'Notice',
'Motd', 'Who', 'Whois',
'Ping', 'Pong',
'WelcomeReply', 'YourHostReply', 'CreatedReply', 'MyInfoReply',
'BounceReply',
'MotdStartReply', 'MotdReply', 'MotdEndReply',
'AwayReply', 'UniqueOpIsReply', 'ChannelModeIsReply', 'InvitingReply',
'TopicReply', 'NoTopicReply',
'WhoisUserReply', 'WhoisServerReply', 'WhoisOperatorReply',
'WhoisIdleReply', 'WhoisChannelsReply', 'quakenet.WhoisAuthReply',
'WhoisEndReply',
'WhoReply', 'WhoEndReply',
'NamesReply', 'NamesEndReply',
'BanListReply', 'BanListEndReply',
'InviteListReply', 'InviteListEndReply',
'ExceptListReply', 'ExceptListEndReply'
'NoSuchServerError', 'TooManyTargetsError', 'NoOriginError',
'NoRecipientError', 'NoTextToSendError', 'NoToplevelError',
'WildTopLevelError', 'NoMotdError', 'UnavailableResourceError',
'NeedMoreParamsError', 'AlreadyRegisteredError', 'UnknownModeError',
'RestrictedError', 'UsersDontMachtError',
'NoSuchNickError', 'NoNicknameGivenError', 'ErroneusNicknameError',
'NicknameInUseError', 'NickCollisionError',
'NoSuchChannelError', 'KeySetError', 'ChannelIsFullError',
'InviteOnlyChannelError', 'BannedFromChannelError', 'BadChannelKeyError',
'BadChannelMaskError', 'NoChannelModesError', 'CannotSendToChannelError',
'TooManyChannelsError', 'UserNotInChannelError', 'NotOnChannelError',
'UserOnChannelError', 'ChanOpPrivilegesNeededError',
]
import string
import random
from core.bot import BotError
from interaction.irc.message import Event
#-------------------------------------------------------------------------------
# Exceptions
#-------------------------------------------------------------------------------
class CommandError(BotError): pass
class MissingArgumentError(CommandError): pass
#-------------------------------------------------------------------------------
# Business Logic
#-------------------------------------------------------------------------------
class Command(object):
"""
High-level API for IRC commands.
"""
def __init__(self, client):
self.client = client
def get_receiver(self):
return self.Receiver(self.client)
def get_sender(self):
return self.Sender(self.client)
class Receiver(object):
"""
IRC command receiver.
Respond to incoming IRC events and dispatch them to all
registered listeners.
"""
def __init__(self, client):
"""
Initialize the receiver object.
@param client: The IRC client instance.
"""
self._listener = []
self.client = client
def add_listener(self, callback):
"""
Add a listener to the receiver instance.
The callback function is called everytime a receive event
occured.
@param callback: A pointer to the callback function.
"""
self._listener.append(callback)
def receive(self, event):
"""
Push a receive event to the command handler.
This will first call the internal command logic and then notice
additional listeners about the event. The event itself can be
modified at any time, altough this is not encouraged.
@param event: The event object.
"""
self._receive(event)
[callback(event) for callback in self._listener]
def _receive(self, event):
"""
Implement general command logic for receive events.
This method can be overriden in sub-classes to implement
module-independent logic.
@param event: The event.
"""
pass
class Sender(object):
def __init__(self, client):
self.client = client
def check_attr(self, attr):
if not hasattr(self, attr):
raise MissingArgumentError(attr)
def create_event(self, container, parameters):
return Event(None, container.token, parameters)
def send(self):
"""
Push a send event to the command handler.
This enables a high-level API for IRC commands. Each command
handler can define class attributes for clean user input and
format input data according to the IRC specifications.
"""
self.client.send_event(self._send())
def _send(self):
"""
Implement general command logic for receive events.
@return An event to send.
"""
pass
"""-------------------------------------------------------------------------
Section: 3.1 Connection Registration
----------------------------------------------------------------------------
The commands described here are used to register a connection with an
IRC server as a user as well as to correctly disconnect.
A "PASS" command is not required for a client connection to be
registered, but it MUST precede the latter of the NICK/USER
combination (for a user connection) or the SERVICE command (for a
service connection). The RECOMMENDED order for a client to register
is as follows:
1. Pass message
2. Nick message 2. Service message
3. User message
Upon success, the client will receive an RPL_WELCOME (for users) or
RPL_YOURESERVICE (for services) message indicating that the
connection is now registered and known the to the entire IRC network.
The reply message MUST contain the full client identifier upon which
it was registered.
----------------------------------------------------------------------------
3.1.1 Password message .................................. 10 - not needed
3.1.2 Nick message ...................................... 10 - needed
3.1.3 User message ...................................... 11 - needed
3.1.4 Oper message ...................................... 12 - not needed
3.1.5 User mode message ................................. 12 - needed
3.1.6 Service message ................................... 13 - not needed
3.1.7 Quit .............................................. 14 - needed
3.1.8 Squit ............................................. 15 - not needed
-------------------------------------------------------------------------"""
class Nick(Command):
"""
Command: NICK
Parameters: <nickname>
NICK command is used to give user a nickname or change the existing
one.
Numeric Replies:
ERR_NONICKNAMEGIVEN ERR_ERRONEUSNICKNAME
ERR_NICKNAMEINUSE ERR_NICKCOLLISION
ERR_UNAVAILRESOURCE ERR_RESTRICTED
"""
token = 'NICK'
class Receiver(Command.Receiver):
def _receive(self, event):
"""
Update the client's identity with the current nickname.
"""
if event.source.nickname == self.client.me.source.nickname:
self.client.me.rename(event.parameter[0])
class Sender(Command.Sender):
def _send(self):
"""
Send a request to set/change the client's nickname.
"""
self.check_attr('nickname')
return self.create_event(Nick, [self.nickname])
class User(Command):
"""
Command: USER
Parameters: <user> <mode> <unused> <realname>
The USER command is used at the beginning of connection to specify
the username, hostname and realname of a new user.
The <mode> parameter should be a numeric, and can be used to
automatically set user modes when registering with the server. This
parameter is a bitmask, with only 2 bits having any signification: if
the bit 2 is set, the user mode 'w' will be set and if the bit 3 is
set, the user mode 'i' will be set. (See Section 3.1.5 "User
Modes").
The <realname> may contain space characters.
Numeric Replies:
ERR_NEEDMOREPARAMS ERR_ALREADYREGISTRED
"""
token ='USER'
class Sender(Command.Sender):
def _send(self):
"""
Register with the IRC server.
"""
self.check_attr('ident')
self.check_attr('realname')
return self.create_event(User, [self.ident, '0', '*', '{0}'.format(self.realname)])
class Mode(Command):
"""
Because user mode message and channel mode are using the same command,
user mode and channel mode logic are implemented in the same class at
the user section.
Command: MODE
Parameters: <nickname>
*( ( "+" / "-" ) *( "i" / "w" / "o" / "O" / "r" ) )
The user MODE's are typically changes which affect either how the
client is seen by others or what 'extra' messages the client is sent.
[...] If no other parameter is given, then the server will return
the current settings for the nick.
The available modes are as follows:
a - user is flagged as away;
i - marks a users as invisible;
w - user receives wallops;
r - restricted user connection;
o - operator flag;
O - local operator flag;
s - marks a user for receipt of server notices.
Additional modes may be available later on.
[...]
Numeric Replies:
ERR_NEEDMOREPARAMS ERR_USERSDONTMATCH
ERR_UMODEUNKNOWNFLAG RPL_UMODEIS
[...]
Command: MODE
Parameters: <channel> *( ( "-" / "+" ) *<modes> *<modeparams> )
The MODE command is provided so that users may query and change the
characteristics of a channel. For more details on available modes
and their uses, see "Internet Relay Chat: Channel Management" [IRC-
CHAN]. Note that there is a maximum limit of three (3) changes per
command for modes that take a parameter.
Numeric Replies:
ERR_NEEDMOREPARAMS ERR_KEYSET
ERR_NOCHANMODES ERR_CHANOPRIVSNEEDED
ERR_USERNOTINCHANNEL ERR_UNKNOWNMODE
RPL_CHANNELMODEIS
RPL_BANLIST RPL_ENDOFBANLIST
RPL_EXCEPTLIST RPL_ENDOFEXCEPTLIST
RPL_INVITELIST RPL_ENDOFINVITELIST
RPL_UNIQOPIS
"""
token = 'MODE'
class Receiver(Command.Receiver):
def _receive(self, event):
pass
class Sender(Command.Sender):
def _send(self):
pass
class Quit(Command):
"""
3.1.7 Quit
Command: QUIT
Parameters: [ <Quit Message> ]
A client session is terminated with a quit message. The server
acknowledges this by sending an ERROR message to the client.
Numeric Replies:
None.
Example:
QUIT :Gone to have lunch ; Preferred message format.
:syrk!kalt@millennium.stealth.net QUIT :Gone to have lunch ; User
syrk has quit IRC to have lunch.
"""
token = 'QUIT'
class Receiver(Command.Receiver):
def _receive(self, event):
pass
class Sender(Command.Sender):
def _send(self):
"""
Send a quit command with a optional quit message.
@param message: The quit message.
"""
parameter = []
if hasattr(self, 'message') and self.message is not None:
parameter.append(self.message)
return self.create_event(Quit, parameter)
"""
----------------------------------------------------------------------------
Section: 3.2 Channel operations
----------------------------------------------------------------------------
This group of messages is concerned with manipulating channels, their
properties (channel modes), and their contents (typically users).
For this reason, these messages SHALL NOT be made available to
services.
All of these messages are requests which will or will not be granted
by the server. The server MUST send a reply informing the user
whether the request was granted, denied or generated an error. When
the server grants the request, the message is typically sent back
(eventually reformatted) to the user with the prefix set to the user
itself.
----------------------------------------------------------------------------
3.2.1 Join message ...................................... 16 - needed
3.2.2 Part message ...................................... 17 - needed
3.2.3 Channel mode message .............................. 18 - needed
3.2.4 Topic message ..................................... 19 - needed
3.2.5 Names message ..................................... 20 - needed
3.2.6 List message ...................................... 21 - not needed
3.2.7 Invite message .................................... 21 - not needed (maybe implemented in the future)
3.2.8 Kick command ...................................... 22 - needed
-------------------------------------------------------------------------"""
class Join(Command):
"""
Command: JOIN
Parameters: ( <channel> *( "," <channel> ) [ <key> *( "," <key> ) ] )
/ "0"
The JOIN command is used by a user to request to start listening to
the specific channel. Servers MUST be able to parse arguments in the
form of a list of target, but SHOULD NOT use lists when sending JOIN
messages to clients.
Once a user has joined a channel, he receives information about
all commands his server receives affecting the channel. This
includes JOIN, MODE, KICK, PART, QUIT and of course PRIVMSG/NOTICE.
This allows channel members to keep track of the other channel
members, as well as channel modes.
If a JOIN is successful, the user receives a JOIN message as
confirmation and is then sent the channel's topic (using RPL_TOPIC) and
the list of users who are on the channel (using RPL_NAMREPLY), which
MUST include the user joining.
[...]
Numeric Replies:
ERR_NEEDMOREPARAMS ERR_BANNEDFROMCHAN
ERR_INVITEONLYCHAN ERR_BADCHANNELKEY
ERR_CHANNELISFULL ERR_BADCHANMASK
ERR_NOSUCHCHANNEL ERR_TOOMANYCHANNELS
ERR_TOOMANYTARGETS ERR_UNAVAILRESOURCE
RPL_TOPIC
"""
token = 'JOIN'
class Sender(Command.Sender):
def _send(self):
"""
Join a channel.
@param channels: The channel names.
@param keys: The optional channel keys.
"""
if hasattr(self, 'channels') and self.channels is None:
parameter = ['0']
else:
parameter = [','.join(self.channels)]
if hasattr(self, 'keys') and self.keys is not None:
parameter.append(','.join(self.keys))
return self.create_event(Join, parameter)
class Part(Command):
"""
Command: PART
Parameters: <channel> *( "," <channel> ) [ <Part Message> ]
The PART command causes the user sending the message to be removed
from the list of active members for all given channels listed in the
parameter string. If a "Part Message" is given, this will be sent
instead of the default message, the nickname. This request is always
granted by the server.
Servers MUST be able to parse arguments in the form of a list of
target, but SHOULD NOT use lists when sending PART messages to
clients.
Numeric Replies:
ERR_NEEDMOREPARAMS ERR_NOSUCHCHANNEL
ERR_NOTONCHANNEL
"""
token = 'PART'
class Sender(Command.Sender):
def _send(self):
"""
Part a channel.
@param channel: The channel name.
@param message: The optional part message.
"""
self.check_attr('channel')
parameter = [self.channel]
if self.message is not None:
parameter.append(self.message)
return self.create_event(Part, parameter)
class Topic(Command):
"""
Command: TOPIC
Parameters: <channel> [ <topic> ]
The TOPIC command is used to change or view the topic of a channel.
The topic for channel <channel> is returned if there is no <topic>
given. If the <topic> parameter is present, the topic for that
channel will be changed, if this action is allowed for the user
requesting it. If the <topic> parameter is an empty string, the
topic for that channel will be removed.
Numeric Replies:
ERR_NEEDMOREPARAMS ERR_NOTONCHANNEL
RPL_NOTOPIC RPL_TOPIC
ERR_CHANOPRIVSNEEDED ERR_NOCHANMODES
"""
token = 'TOPIC'
class Sender(Command.Sender):
def _send(self):
"""
Get/set a channels topic.
"""
self.check_attr('channel')
parameter = [self.channel]
if hasattr(self, 'topic') and self.topic is not None:
parameter.append(self.topic)
return self.create_event(Topic, parameter)
class Names(Command):
"""
Command: NAMES
Parameters: [ <channel> *( "," <channel> ) [ <target> ] ]
By using the NAMES command, a user can list all nicknames that are
visible to him. For more details on what is visible and what is not,
see "Internet Relay Chat: Channel Management" [IRC-CHAN]. The
<channel> parameter specifies which channel(s) to return information
about. There is no error reply for bad channel names.
If no <channel> parameter is given, a list of all channels and their
occupants is returned. At the end of this list, a list of users who
are visible but either not on any channel or not on a visible channel
are listed as being on `channel' "*".
If the <target> parameter is specified, the request is forwarded to
that server which will generate the reply.
Wildcards are allowed in the <target> parameter.
Numerics:
ERR_TOOMANYMATCHES ERR_NOSUCHSERVER
RPL_NAMREPLY RPL_ENDOFNAMES
"""
token = 'NAMES'
class Sender(Command.Sender):
def _send(self):
"""
Request a NAMES list.
"""
self.check_attr('channels')
return self.create_event(Names, [','.join(self.channels)])
class Invite(Command):
"""
Command: INVITE
Parameters: <nickname> <channel>
The INVITE command is used to invite a user to a channel. The
parameter <nickname> is the nickname of the person to be invited to
the target channel <channel>. There is no requirement that the
channel the target user is being invited to must exist or be a valid
channel. However, if the channel exists, only members of the channel
are allowed to invite other users. When the channel has invite-only
flag set, only channel operators may issue INVITE command.
Only the user inviting and the user being invited will receive
notification of the invitation. Other channel members are not
notified. (This is unlike the MODE changes, and is occasionally the
source of trouble for users.)
Numeric Replies:
ERR_NEEDMOREPARAMS ERR_NOSUCHNICK
ERR_NOTONCHANNEL ERR_USERONCHANNEL
ERR_CHANOPRIVSNEEDED
RPL_INVITING RPL_AWAY
"""
token = 'INVITE'
class Sender(Command.Sender):
def _send(self):
self.check_attr('nickname')
self.check_attr('channel')
return self.create_event(Invite, [self.nickname, self.channel])
class Kick(Command):
"""
Command: KICK
Parameters: <channel> *( "," <channel> ) <user> *( "," <user> )
[<comment>]
The KICK command can be used to request the forced removal of a user
from a channel. It causes the <user> to PART from the <channel> by
force. For the message to be syntactically correct, there MUST be
either one channel parameter and multiple user parameter, or as many
channel parameters as there are user parameters. If a "comment" is
given, this will be sent instead of the default message, the nickname
of the user issuing the KICK.
The server MUST NOT send KICK messages with multiple channels or
users to clients. This is necessarily to maintain backward
compatibility with old client software.
Numeric Replies:
ERR_NEEDMOREPARAMS ERR_NOSUCHCHANNEL
ERR_BADCHANMASK ERR_CHANOPRIVSNEEDED
ERR_USERNOTINCHANNEL ERR_NOTONCHANNEL
"""
token = 'KICK'
class Sender(Command.Sender):
def _send(self):
self.check_attr('channels')
self.check_attr('users')
parameter = [','.join(self.channels), ','.join(self.users)]
if hasattr(self, 'message') and self.message is not None:
parameter.append(self.message)
return self.create_event(Kick, parameter)
"""
----------------------------------------------------------------------------
Section: 3.3 Sending messages
----------------------------------------------------------------------------
The main purpose of the IRC protocol is to provide a base for clients
to communicate with each other. PRIVMSG, NOTICE and SQUERY
(described in Section 3.5 on Service Query and Commands) are the only
messages available which actually perform delivery of a text message
from one client to another - the rest just make it possible and try
to ensure it happens in a reliable and structured manner.
----------------------------------------------------------------------------
3.3.1 Private messages .................................. 23 - needed
3.3.2 Notice ............................................ 24 - needed
-------------------------------------------------------------------------"""
class Privmsg(Command):
"""
Command: PRIVMSG
Parameters: <msgtarget> <text to be sent>
PRIVMSG is used to send private messages between users, as well as to
send messages to channels. <msgtarget> is usually the nickname of
the recipient of the message, or a channel name.
The <msgtarget> parameter may also be a host mask (#<mask>) or server
mask ($<mask>). In both cases the server will only send the PRIVMSG
to those who have a server or host matching the mask. The mask MUST
have at least 1 (one) "." in it and no wildcards following the last
".". This requirement exists to prevent people sending messages to
"#*" or "$*", which would broadcast to all users. Wildcards are the
'*' and '?' characters. This extension to the PRIVMSG command is
only available to operators.
Numeric Replies:
ERR_NORECIPIENT ERR_NOTEXTTOSEND
ERR_CANNOTSENDTOCHAN ERR_NOTOPLEVEL
ERR_WILDTOPLEVEL ERR_TOOMANYTARGETS
ERR_NOSUCHNICK
RPL_AWAY
"""
token = 'PRIVMSG'
class Receiver(Command.Receiver):
def _receive(self, event):
if not event.parameter[0].startswith('#') and event.parameter[1] == 'fotzenscheisse':
self.client.stop()
class Sender(Command.Sender):
def _send(self):
self.check_attr('target')
self.check_attr('text')
return self.create_event(Privmsg, [self.target, self.text])
class Notice(Command):
"""
Command: NOTICE
Parameters: <msgtarget> <text>
The NOTICE command is used similarly to PRIVMSG. The difference
between NOTICE and PRIVMSG is that automatic replies MUST NEVER be
sent in response to a NOTICE message. This rule applies to servers
too - they MUST NOT send any error reply back to the client on
receipt of a notice. The object of this rule is to avoid loops
between clients automatically sending something in response to
something it received.
This command is available to services as well as users.
This is typically used by services, and automatons (clients with
either an AI or other interactive program controlling their actions).
See PRIVMSG for more details on replies and examples.
"""
token = 'NOTICE'
class Sender(Command.Sender):
def _send(self):
self.check_attr('target')
self.check_attr('text')
return self.create_event(Notice, [self.target, self.text])
"""
----------------------------------------------------------------------------
Section: 3.4 Server queries and commands
----------------------------------------------------------------------------
3.4.1 Motd message ...................................... 25 - needed
3.4.2 Lusers message .................................... 25 - not needed
3.4.3 Version message ................................... 26 - not needed
3.4.4 Stats message ..................................... 26 - not needed
3.4.5 Links message ..................................... 27 - not needed
3.4.6 Time message ...................................... 28 - not needed
3.4.7 Connect message ................................... 28 - not needed
3.4.8 Trace message ..................................... 29 - not needed
3.4.9 Admin command ..................................... 30 - not needed
3.4.10 Info command ...................................... 31 - not needed
-------------------------------------------------------------------------"""
class Motd(Command):
"""
Command: MOTD
Parameters: [ <target> ]
The MOTD command is used to get the "Message Of The Day" of the given
server, or current server if <target> is omitted.
Wildcards are allowed in the <target> parameter.
Numeric Replies:
RPL_MOTDSTART RPL_MOTD
RPL_ENDOFMOTD ERR_NOMOTD
"""
token = 'MOTD'
class Sender(Command.Sender):
def _send(self):
parameter = []
if hasattr(self, 'target') and self.target is not None:
parameter.append(self.target)
return self.create_event(Motd, parameter)
"""
----------------------------------------------------------------------------
Section: 3.5 Service query and commands
----------------------------------------------------------------------------
3.5.1 Servlist message .................................. 31 - not needed
3.5.2 Squery ............................................ 32 - not needed
-------------------------------------------------------------------------"""
"""
----------------------------------------------------------------------------
Section: 3.6 User based queries
----------------------------------------------------------------------------
3.6.1 Who query ......................................... 32 - needed
3.6.2 Whois query ....................................... 33 - needed
3.6.3 Whowas ............................................ 34 - not needed
-------------------------------------------------------------------------"""
class Who(Command):
"""
Command: WHO
Parameters: [ <mask> [ "o" ] ]
The WHO command is used by a client to generate a query which returns
a list of information which 'matches' the <mask> parameter given by
the client. In the absence of the <mask> parameter, all visible
(users who aren't invisible (user mode +i) and who don't have a
common channel with the requesting client) are listed. The same
result can be achieved by using a <mask> of "0" or any wildcard which
will end up matching every visible user.
The <mask> passed to WHO is matched against users' host, server, real
name and nickname if the channel <mask> cannot be found.
If the "o" parameter is passed only operators are returned according
to the <mask> supplied.
Numeric Replies:
ERR_NOSUCHSERVER
RPL_WHOREPLY RPL_ENDOFWHO
"""
token = 'WHO'
class Sender(Command.Sender):
def _send(self):
self.check_attr('mask')
parameter = [self.mask]
if hasattr(self, 'operators') and self.operators:
parameter.append('o')
return self.create_event(Who, parameter)
class Whois(Command):
"""
Command: WHOIS
Parameters: [ <target> ] <mask> *( "," <mask> )
This command is used to query information about particular user.
The server will answer this command with several numeric messages
indicating different statuses of each user which matches the mask (if
you are entitled to see them). If no wildcard is present in the
<mask>, any information about that nick which you are allowed to see
is presented.
If the <target> parameter is specified, it sends the query to a
specific server. It is useful if you want to know how long the user
in question has been idle as only local server (i.e., the server the
user is directly connected to) knows that information, while
everything else is globally known.
Wildcards are allowed in the <target> parameter.
Numeric Replies:
ERR_NOSUCHSERVER ERR_NONICKNAMEGIVEN
RPL_WHOISUSER RPL_WHOISCHANNELS
RPL_WHOISCHANNELS RPL_WHOISSERVER
RPL_AWAY RPL_WHOISOPERATOR
RPL_WHOISIDLE ERR_NOSUCHNICK
RPL_ENDOFWHOIS
"""
token = 'WHOIS'
class Sender(Command.Sender):
def _send(self):
self.check_attr('user')
parameter = []
if hasattr(self, 'server') and self.server is not None:
parameter.append(self.server)
# add user 2x for extended whois
parameter.append(self.user)
parameter.append(self.user)
return self.create_event(Whois, parameter)
"""
----------------------------------------------------------------------------
Section: 3.7 Miscellaneous messages
----------------------------------------------------------------------------
3.7.1 Kill message ...................................... 35 - not needed
3.7.2 Ping message ...................................... 36 - needed
3.7.3 Pong message ...................................... 37 - needed
3.7.4 Error ............................................. 37 - not needed
-------------------------------------------------------------------------"""
class Ping(Command):
"""
Command: PING
Parameters: <server1> [ <server2> ]
The PING command is used to test the presence of an active client or
server at the other end of the connection. Servers send a PING
message at regular intervals if no other activity detected coming
from a connection. If a connection fails to respond to a PING
message within a set amount of time, that connection is closed. A
PING message MAY be sent even if the connection is active.
When a PING message is received, the appropriate PONG message MUST be
sent as reply to <server1> (server which sent the PING message out)
as soon as possible. If the <server2> parameter is specified, it
represents the target of the ping, and the message gets forwarded
there.
Numeric Replies:
ERR_NOORIGIN ERR_NOSUCHSERVER
"""
token = 'PING'
class Receiver(Command.Receiver):
def _receive(self, event):
pong = self.client.get_command('Pong').get_sender()
if len(event.parameter) == 1:
pong.server = event.parameter[0]
if len(event.parameter) == 2:
pong.server = event.parameter[0]
pong.server2 = event.parameter[1]
pong.send()
class Pong(Command):
"""
Command: PONG
Parameters: <server> [ <server2> ]
PONG message is a reply to ping message. If parameter <server2> is
given, this message MUST be forwarded to given target. The <server>
parameter is the name of the entity who has responded to PING message
and generated this message.
Numeric Replies:
ERR_NOORIGIN ERR_NOSUCHSERVER
"""
token = 'PONG'
class Sender(Command.Sender):
def _send(self):
self.check_attr('server')
parameter = [self.server]
if hasattr(self, 'server2') and self.server2:
parameter.append(self.server2)
return self.create_event(Pong, parameter)
"""-----------------------------------------------------------------------------
5. Replies .................................................... 43
5.1 Command responses ...................................... 43
5.2 Error Replies .......................................... 53
5.3 Reserved numerics ...................................... 59
Numerics in the range from 001 to 099 are used for client-server
connections only and should never travel between servers.
-----------------------------------------------------------------------------"""
class WelcomeReply(Command):
token = '001'
class YourHostReply(Command):
token = '002'
class CreatedReply(Command):
token = '003'
class MyInfoReply(Command):
token = '004'
class BounceReply(Command):
token = '005'
"""-----------------------------------------------------------------------------
Replies generated in the response to commands are found in the
range from 200 to 399.
-----------------------------------------------------------------------------"""
class AwayReply(Command):
token = '301'
class WhoisUserReply(Command):
token = '311'
class WhoisServerReply(Command):
token = '312'
class WhoisOperatorReply(Command):
token = '313'
class WhoEndReply(Command):
token = '315'
class WhoisIdleReply(Command):
token = '317'
class WhoisEndReply(Command):
token = '318'
class WhoisChannelsReply(Command):
token = '319'
class UniqueOpIsReply(Command):
token = '325'
class ChannelModeIsReply(Command):
token = '324'
class NoTopicReply(Command):
token = '331'
class TopicReply(Command):
token = '332'
class InvitingReply(Command):
token = '341'
class InviteListReply(Command):
token = '346'
class InviteListEndReply(Command):
token = '347'
class ExceptListReply(Command):
token = '348'
class ExceptListEndReply(Command):
token = '349'
class WhoReply(Command):
token = '352'
class NamesReply(Command):
"""
353 RPL_NAMREPLY
"( "=" / "*" / "@" ) <channel>
:[ "@" / "+" ] <nick> *( " " [ "@" / "+" ] <nick> )
"@" is used for secret channels
"*" for private channels, and
"=" for others (public channels).
"""
token = '353'
class NamesEndReply(Command):
token = '366'
class BanListReply(Command):
token = '367'
class BanListEndReply(Command):
token = '368'
class MotdReply(Command):
token = '372'
class MotdStartReply(Command):
token = '375'
class MotdEndReply(Command):
token = '376'
class Receiver(Command.Receiver):
def _receive(self, event):
self.client.post_connect()
"""-----------------------------------------------------------------------------
Error replies are found in the range from 400 to 599.
-----------------------------------------------------------------------------"""
class NoSuchNickError(Command):
token = '401'
class NoSuchServerError(Command):
token = '402'
class NoSuchChannelError(Command):
token = '403'
class CannotSendToChannelError(Command):
token = '404'
class TooManyChannelsError(Command):
token = '405'
class TooManyTargetsError(Command):
token = '407'
class NoOriginError(Command):
token = '409'
class NoRecipientError(Command):
token = '411'
class NoTextToSendError(Command):
token = '412'
class NoToplevelError(Command):
token = '413'
class WildTopLevelError(Command):
token = '414'
class NoMotdError(Command):
token = '422'
class Receiver(Command.Receiver):
def _receive(self, event):
self.client.post_connect()
class NoNicknameGivenError(Command):
token = '431'
class Receiver(Command.Receiver):
def _receive(self, event):
nick = self.client.get_command('Nick').get_sender()
nick.nickname = self.client.config.get('nickname')
if len(nick.nickname) == 0:
nick.nickname = self.client.config.get('anickname')
if len(nick.nickname) == 0:
nick.nickname = 'Bot-' + ''.join(random.choice(string.ascii_uppercase) for x in range(3))
self.client.logger.info(
'No nickname was given, trying to use %s',
self.client.me.source.nickname,
nick.nickname
)
nick.send()
class ErroneusNicknameError(Command):
token = '432'
class Receiver(Command.Receiver):
def _receive(self, event):
nick = self.client.get_command('Nick').get_sender()
nick.nickname = 'Bot-' + ''.join(random.choice(string.ascii_uppercase) for x in range(3))
self.client.logger.info(
'Requested nickname %s is not valid on network, trying to use %s instead',
self.client.me.source.nickname,
nick.nickname
)
nick.send()
class NicknameInUseError(Command):
token = '433'
class Receiver(Command.Receiver):
def _receive(self, event):
nick = self.client.get_command('Nick').get_sender()
nick.nickname = self.client.config.get('anickname')
if nick.nickname == self.client.me.source.nickname:
# TODO honor NICKLEN from BounceReply
nickname_length = 15 #quakenet default, hardcoded
random_length = 3 #chosen by fair dice roll
nickname_maxlength = nickname_length - random_length
nick.nickname = nick.nickname[nickname_maxlength:]
nick.nickname += ''.join(random.choice(string.ascii_uppercase) for x in range(random_length))
self.client.logger.info(
'Requested nickname %s is already used on network, trying to use %s instead',
self.client.me.source.nickname,
nick.nickname
)
nick.send()
class NickCollisionError(Command):
token = '436'
class UnavailableResourceError(Command):
token = '437'
class UserNotInChannelError(Command):
token = '441'
class NotOnChannelError(Command):
token = '442'
class UserOnChannelError(Command):
token = '443'
class NeedMoreParamsError(Command):
token = '461'
class AlreadyRegisteredError(Command):
token = '462'
class KeySetError(Command):
token = '467'
class ChannelIsFullError(Command):
token = '471'
class UnknownModeError(Command):
token = '472'
class InviteOnlyChannelError(Command):
token = '473'
class BannedFromChannelError(Command):
token = '474'
class BadChannelKeyError(Command):
token = '475'
class BadChannelMaskError(Command):
token = '476'
class NoChannelModesError(Command):
token = '477'
class ChanOpPrivilegesNeededError(Command):
token = '482'
class RestrictedError(Command):
token = '484'
class UsersDontMachtError(Command):
token = '502'
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: __init__.py 221 2011-07-21 18:25:10Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/interaction/irc/__init__.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since 06.01.2010
@author Mario Steinhoff
"""
__version__ = '$Rev: 221 $'
__all__ = [
'client',
'command',
'module',
'networks',
'modules',
]
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: module.py 272 2012-02-02 18:20:42Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/interaction/irc/module.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Jan 11, 2011
@author Mario Steinhoff
"""
__version__ = '$Rev: 272 $'
import re
import time
from core.bot import BotError
from objects.principal import Role
from objects.irc import Location
#-------------------------------------------------------------------------------
# Constants
#-------------------------------------------------------------------------------
MIRC_COLOR = '\x03'
#-------------------------------------------------------------------------------
# Exceptions
#-------------------------------------------------------------------------------
class ModuleError(BotError): pass
class InteractiveModuleError(ModuleError): pass
class InvalidCommandError(InteractiveModuleError): pass
class InvalidParameterError(InteractiveModuleError): pass
class InvalidLocationError(InteractiveModuleError): pass
class InvalidRoleError(InteractiveModuleError): pass
#-------------------------------------------------------------------------------
# Business Logic
#-------------------------------------------------------------------------------
class Module(object):
"""
Extend the IRC client's functionality.
A module is loaded and instantiated by the client. An interface
to the IRC is provided by registering callback functions for each
IRC command needed and known by the client.
"""
def __init__(self, client):
"""
Initialize the module.
This will populate the client instance in the module, so the
module can interact with the client.
@param client: The client instance.
"""
self.client = client
self.initialize()
def __del__(self):
self.shutdown()
#---------------------------------------------------------------------------
# irc interface
#---------------------------------------------------------------------------
def get_receive_listeners(self):
"""
Return a mapping between commands and callback functions.
This will return a dictionary with the mapping.
- They keys are command classes
- the values are pointers to methods provided by the class.
@return list with mapping between commands and class methods
"""
raise NotImplementedError
#---------------------------------------------------------------------------
# state handling
#---------------------------------------------------------------------------
def initialize(self):
"""
Initialization hook.
This will execute additional initialization code in the module
without overriding the constructor.
Code in this method may only initialize data structures.
This method MUST NOT start or manipulate any external entity, e.g.
start threads, open connections, write files, etc.
For manipulation, use start().
"""
pass
def shutdown(self):
"""
Cleanup hook.
This will execute additional cleanup code in the module without
overriding the destructor.
"""
pass
def start(self):
"""
launch hook.
This will execute additional launch code needed at runtime
without overriding the constructor.
It will be called before any IRC connection is available.
Code in this method may start or manipulate external entities, e.g.
start threads, open sockets or files, etc.
For initialization, use initialize().
"""
pass
def stop(self):
"""
The opposite of start().
It will be called after the IRC connection was closed.
Stop threads, close sockets or files, etc.
"""
pass
class InteractiveModule(Module):
"""
Provide a framework for user interaction.
This implementation can parse Privmsg or Notice messages, that
encapsulate bot/module commands.
Each module can specify one or more keywords. Each keyword can
either have parameters or further sub-commands. If sub-commands
are specified, each sub-command can again have parameters.
Parameters are defined by an arbitrary regular expression.
Parameters can be defined for commands and sub-commands.
"""
PATTERN_BASE = r'^\.(?P<command>{0})(\s(?P<parameter>.+)$|$)'
PATTERN_SEPARATOR = '|'
def __init__(self, client):
"""
Initialize the Inactive Module.
Generate and compile a command regex pattern to match all
defined commands. Compile all parameter regex patterns.
Cache all compiled RegexObjects and the mapping between
commands and callback functions.
"""
Module.__init__(self, client)
# cache reference to usermgmt module
if self.__class__.__name__.lower() == 'usermgmt':
self.usermgmt = self
else:
self.usermgmt = self.client.get_module('usermgmt')
self.identifier = self.module_identifier()
self.command_dict = {}
for command in self.init_commands():
self.command_dict[command.keyword] = command
pattern = self.PATTERN_BASE.format(
self.PATTERN_SEPARATOR.join(self.command_dict)
)
self.module_re = re.compile(pattern, re.I)
self.VALID_TOKENS = (
self.client.get_command('Privmsg').token,
self.client.get_command('Notice').token
)
#---------------------------------------------------------------------------
# irc interface
#---------------------------------------------------------------------------
def get_receive_listeners(self):
"""
Setup default receive listeners needed for Privmsg handling.
"""
return {'Privmsg': self.parse}
#---------------------------------------------------------------------------
# identification and behavior
#---------------------------------------------------------------------------
def module_identifier(self):
"""
Return a verbose string that identifies the module.
This prefix is used when sending replies.
@return An identifier, e.g. 'Rollapparillo'
"""
raise NotImplementedError
def init_commands(self):
"""
Return a definition of commands/sub-commands and callbacks.
The module will respond on every command defined. The commands
must be given without the trigger character.
Sub-commands are defined as ordinary commands separated by a
space (0x20) character.
Examples:
self.add_command('roll', r'^([\d]+)(?:-([\d]+))$', Role.USER, self.roll)
self.add_command('black', None, Role.USER, self.choose)
self.add_command('white', None, Role.USER, self.choose)
self.add_command('pink', None, Role.USER, self.choose)
self.add_command('calendar add', '???', Role.USER, self.add)
self.add_command('calendar delete', '???', Role.USER, self.delete)
"""
raise NotImplementedError
#---------------------------------------------------------------------------
# interactive command handling
#---------------------------------------------------------------------------
def parse(self, event):
"""
Parse the event and dispatch it to the actual module logic.
This will check if any module command was found in the message.
If no command was found, the method will return.
If a command was found, the corresponding parameter RegexObject
is retrieved and matched against the parameter raw data. If no
RegexObject was found, the parameter data will be None.
Then, the command's callback will be called with command and
parameter data passed as arguments.
This module will only accept Privmsg or Notice events. It needs
to be activated in get_receive_listeners().
TODO: add mirc color codes to reply
@param event: The Privmsg or Notice event.
"""
if event.command not in self.VALID_TOKENS:
raise ValueError('invalid command token')
#-----------------------------------------------------------------------
# handle input
#-----------------------------------------------------------------------
target, message = event.parameter[0:2]
message = message.strip()
message_match = self.module_re.search(message)
if message_match is None:
return
command = message_match.group('command')
parameter = message_match.group('parameter') or ''
location = Location.get(target)
role = self.usermgmt.get_role(event.source.nickname)
command_object = self.command_dict[command]
#-----------------------------------------------------------------------
# dispatch
#-----------------------------------------------------------------------
try:
if not Location.valid(required=command_object.location, location=location):
raise InvalidLocationError(command_object.location)
if not Role.valid(required=command_object.role, role=role):
raise InvalidRoleError(command_object.role)
callback = command_object.callback
parameter = command_object.match_parameter(parameter)
request = InteractiveModuleRequest(
event=event,
source=event.source,
target=target,
message=message,
location=location,
role=role,
command=command,
parameter=parameter
)
response = callback(request)
except InvalidLocationError as required_location:
response = InteractiveModuleResponse()
response.send_to(event.source.nickname)
response.use_notice()
response.add_line('Befehl {0} geht nur im {1}'.format(command, Location.string(required_location[0])))
except InvalidRoleError as required_role:
response = InteractiveModuleResponse()
response.send_to(event.source.nickname)
response.use_notice()
response.add_line('Nicht genug Rechte (benötigt: {0})'.format(Role.string(required_role[0])))
except InvalidParameterError:
response = InteractiveModuleResponse()
response.add_line('usage: .{0} {1}'.format(command_object.keyword, command_object.syntaxhint))
except Exception as ex:
response = InteractiveModuleResponse()
response.add_line('Es ist ein interner Fehler aufgetreten, lol opfeeeeeer!')
self.client.logger.exception('Unhandled exception "{1}" thrown in {0}'.format(
self.__class__.__name__,
str(ex)
))
#-----------------------------------------------------------------------
# send reply
#-----------------------------------------------------------------------
if response and not hasattr(response, 'target'):
if location == Location.CHANNEL:
response.send_to(event.parameter[0])
elif location == Location.QUERY:
response.send_to(event.source.nickname)
self.send_response(response.target, response)
def send_response(self, target, response):
"""
Send a response to the target.
@param target: The receiver of the response.
@param response: The response to send.
"""
if hasattr(response, 'replies') and hasattr(response, 'type'):
sender = self.client.get_command(response.type).get_sender()
sender.target = target
for line in response.replies:
sender.text = '{0}: {1}'.format(self.identifier, line)
sender.send()
time.sleep(0.2)
else:
sender = self.client.get_command('Privmsg').get_sender()
sender.target = target
sender.text = '{0}: {1}'.format(self.identifier, response)
sender.send()
class InteractiveModuleCommand(object):
"""
The static definition of an InteractiveModule command.
Module commands can be triggered by other IRC clients sending
messages in a pre-defined format. When a command is detected,
a InteractiveModuleRequest is generated and sent to the command
handler callback.
After the callback has been finished with processing the request,
it returns a InteractiveModuleResponse which is sent back to the
IRC server.
"""
def __init__(self, keyword, callback, pattern=None, location=Location.CHANNEL, role=Role.USER, syntaxhint=None, help=None):
"""
Define a module command.
@param keyword: The keyword that triggers the command.
@param callback: The callback function that handles the command.
@param pattern: A regex pattern that defines the command parameters.
@param location: The location where the command can be executed.
@param role: The role the calling user needs to have.
@param syntaxhint: A string that is sent when using invalid parameters.
@param help: A string that describes the command.
"""
self.keyword = keyword
self.callback = callback
if pattern:
self.pattern = re.compile(pattern, re.I)
else:
self.pattern = None
self.location = location
self.role = role
self.syntaxhint = syntaxhint or ''
self.help = help or ''
def match_parameter(self, data):
"""
Match and extract data according to the commands's pattern.
@param data: The raw parameter string.
@return: A tuple, the format depends on the command's pattern.
@raise ValueError If the data format is invalid.
@raise InvalidParameterError If there were no matches found.
"""
if self.pattern is None:
return None
try:
match = self.pattern.findall(data)
arguments = match[0]
# force tuple for consistent api
if type(arguments) != tuple:
arguments = (arguments,)
# TypeError when data can not be matched
# KeyError when no match was found
# IndexError when no match was found
except (TypeError):
raise ValueError
except (KeyError, IndexError):
raise InvalidParameterError
return arguments
class InteractiveModuleRequest(object):
"""
The runtime request of an InteractiveModule command.
A runtime request is generated each time the command is triggered
and passed to the command handler callback.
It contains context information about the incoming command that
can be processed by the command handler.
"""
def __init__(self, event=None, source=None, target=None, message=None, location=None, role=None, command=None, parameter=None):
"""
Initialize a runtime request.
@param event: The original event of the command.
@param source: Who sent the command.
@param target: Where the command was sent to.
@param message: The raw message, extracted from the event.
@param location: The location where the command was sent.
@param role: The role of the user sending the command.
@param command: The actual command name.
@param parameter"The command parameters.
"""
self.event = event
self.source = source
self.target = target
self.message = message
self.location = location
self.role = role
self.command = command
self.parameter = parameter
class InteractiveModuleResponse(object):
"""
The runtime response of an InteractiveModule command.
A response is created by the command handler callback and
contains 1-n reply lines.
"""
def __init__(self, firstline=None):
"""
Initialize a runtime response.
The default IRC command used is Privmsg.
@param firstline: The first line of the response.
@param target: The target to send the response to.
"""
self.use_message()
self.replies = []
if firstline:
self.replies.append(firstline)
def add_line(self, line):
"""
Add another line to the reponse.
@param line: The text to add.
"""
self.replies.append(line)
def send_to(self, target):
"""
Override the target to send the response to.
The target where the response is sent to is computed by the
InteractiveModule framework. It can be overridden using this
method.
@param target: A valid channel or nickname to send the response to.
"""
self.target = target
def use_message(self):
"""
Use the Privmsg IRC command for the reply.
"""
self.type = 'Privmsg'
def use_notice(self):
"""
Use the Notice IRC command for the reply.
"""
self.type = 'Notice'
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: youtube.py 109 2011-02-09 22:07:37Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/interaction/http/client/youtube.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Jan 6, 2011
@author Rack
"""
__version__ = '$Rev: 109 $'
import re
import urllib
from system import PrivMsg
class YouTube():
regexpattern = r':(.+) (?:PRIVMSG) ([\S]+) :(?:.+)youtube.com/(?:.+)v=([-_\w]+)'
'''
If a user posts a YouTube link, this module will post the video title in the channel
'''
#Texthandling
def handleInput(self,Matchlist):
#Source = Matchlist[0]
Target = Matchlist[1]
Text = Matchlist[2]
PrivMsg(Target, "14Titel: 3[ " + self.getInfo(Text) + " 3]")
#Details zum Link abrufen
def getInfo(self,VideoID):
url = urllib.urlopen("http://www.youtube.com/watch?v=" + VideoID)
gdata = url.read()
Titel = ''
try:
Titel = (re.search("<meta name=\"title\" content=\"(.+)\">", gdata)).group(1)
except:
pass
return Titel | Python |
# -*- coding: UTF-8 -*-
"""
$Id: twitter.py 109 2011-02-09 22:07:37Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/interaction/http/client/twitter.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Jan 6, 2011
@author Rack
"""
__version__ = '$Rev: 109 $'
import socket
import base64
import urllib
class Twitter():
"""
This module posts tweets on twitter.
"""
def __init__(self,User,Password):
self.User = User
self.Password = Password
def sendTweet(self,Tweet):
Tweet = Tweet.decode("iso-8859-1")
Tweet = Tweet.encode("utf-8")
Tweet = urllib.quote(Tweet)
encoded = base64.b64encode(self.User + ":" + self.Password)
postdata = "status=" + Tweet
strhead = "POST /statuses/update.xml HTTP/1.1\r\n"
strhead += "Host: twitter.com\r\n"
strhead += "Content-Length: " + str(len(postdata)) + "\r\n"
strhead += "Authorization: Basic " + encoded + "\r\n\r\n"
strhead += postdata + "\r\n\r\n"
TwitterSocket = socket.socket()
TwitterSocket.connect(("www.twitter.com", 80))
TwitterSocket.send(strhead)
TwitterSocket.close()
| Python |
# -*- coding: UTF-8 -*-
"""
$Id$
$URL$
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Jan 6, 2011
@author Mario Steinhoff
"""
__version__ = '$Rev$'
__all__ = [
'twitter',
'youtube'
]
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: management.py 106 2011-02-09 22:05:09Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/interaction/http/server/management.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Jan 8, 2011
@author Mario Steinhoff
"""
__version__ = '$Rev: 106 $'
class Management(object):
"""
Web-based bot management
"""
def __init__(self):
"""
"""
pass
| Python |
# -*- coding: UTF-8 -*-
"""
$Id$
$URL$
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Jan 6, 2011
@author Mario Steinhoff
"""
__version__ = '$Rev$'
__all__ = [
'management'
]
| Python |
# -*- coding: UTF-8 -*-
"""
$Id$
$URL$
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Jan 6, 2011
@author Mario Steinhoff
"""
__version__ = '$Rev$'
__all__ = [
'server',
'client'
]
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: interaction.py 232 2011-09-23 01:26:30Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/interaction/interaction.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Jan 13, 2011
@author Mario Steinhoff
"""
__version__ = '$Rev: 232 $'
from core import subsystem
from core.bot import BotError
# ------------------------------------------------------------------------------
# Exceptions
# ------------------------------------------------------------------------------
class InteractionError(BotError): pass
# ------------------------------------------------------------------------------
# Business Logic
# ------------------------------------------------------------------------------
class Interaction(subsystem.Subsystem):
"""
Provides a basic structure for all interaction sub-systems.
"""
@staticmethod
def startInteraction(bot, object):
instance = object(bot)
instance.start()
def __init__(self, bot):
"""
Initialize the subsystem.
@param bot: The bot instance.
"""
subsystem.Subsystem.__init__(self, bot)
| Python |
# -*- coding: UTF-8 -*-
"""
$Id$
$URL$
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Jan 06, 2011
@author Mario Steinhoff
"""
__version__ = '$Rev$'
__all__ = [
'interaction',
'irc',
'http'
]
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: calendar.py 257 2012-01-12 23:29:03Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/objects/calendar.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Apr 26, 2011
@author Mario Steinhoff
"""
__version__ = '$Rev: 257 $'
from sqlalchemy import Column, Integer, String, Date, DateTime, Boolean, Text, Enum
from sqlalchemy.schema import ForeignKey
from sqlalchemy.orm import relationship, backref
from core.persistence import SqlAlchemyPersistence
from objects import set_deletion_date
#-------------------------------------------------------------------------------
# Calendar
#-------------------------------------------------------------------------------
class Calendar(SqlAlchemyPersistence.Base):
"""
Represent a calendar for the calendar component.
"""
__tablename__ = 'calendars'
# DDL
id = Column(Integer, primary_key=True)
isDeleted = Column(Boolean, default=False)
deletedOn = Column(DateTime, nullable=True, onupdate=set_deletion_date)
authority = Column(String(255))
title = Column(String(255))
summary = Column(Text)
location = Column(String(255))
color = Column(String(6))
def get_authority_name(self):
return self.authority
def __repr__(self):
return '<Calendar(id={0},title={1}|authority={2})>'.format(
self.id,
self.title,
self.authority
)
class Event(SqlAlchemyPersistence.Base):
"""
Represent an event for the calendar component.
"""
__tablename__ = 'events'
# DDL
id = Column(Integer, primary_key=True)
isDeleted = Column(Boolean, default=False)
deletedOn = Column(DateTime, nullable=True, onupdate=set_deletion_date)
calendar_id = Column(Integer, ForeignKey('calendars.id'))
start = Column(DateTime)
end = Column(DateTime)
allday = Column(Boolean, default=False)
title = Column(String(255))
description = Column(Text, nullable=True)
location = Column(String(255), nullable=True)
# ORM
calendar = relationship('Calendar', backref=backref('events'))
def get_authority_name(self):
return self.calendar.get_authority_name()
def __repr__(self):
return '<Event(id={0}|start={1}|end={2}|title={3})>'.format(
self.id,
self.start,
self.end,
self.title,
)
class Contact(SqlAlchemyPersistence.Base):
"""
Represent a contact for the calendar component.
SQLAlchemy mapped class.
"""
__tablename__ = 'contacts'
# DDL
id = Column(Integer, primary_key=True)
isDeleted = Column(Boolean, default=False)
deletedOn = Column(DateTime, nullable=True, onupdate=set_deletion_date)
firstname = Column(String(64), nullable=True)
lastname = Column(String(64), nullable=True)
nickname = Column(String(32))
birthday = Column(Date)
def __repr__(self):
return '<Contact(id={0}|firstname={1}|lastname={2}|nickname={3}|birthday={4})>'.format(
self.id,
self.firstname,
self.lastname,
self.nickname,
self.birthday
)
#-------------------------------------------------------------------------------
# Backend mapping
#-------------------------------------------------------------------------------
class Backend(SqlAlchemyPersistence.Base):
"""
Represents a secondary backend.
"""
__tablename__ = 'backends'
id = Column(Integer, primary_key=True)
name = Column(String(64))
typename = Column(String(255))
def __repr__(self):
return '<Backend(id={0}|name={1}|classname={2})>'.format(
self.id,
self.name,
self.typename
)
class BackendPeerIdentity(SqlAlchemyPersistence.Base):
"""
Represent a remote (peer) identity for a locally stored object.
The class structure is as the following:
+ BackendPeerIdentity
+-- CalendarPeerIdentity
+-- EventPeerIdentity
+-- ContactPeerIdentity
"""
__tablename__ = 'backend_identity'
identity = Column(Text, primary_key=True)
backend_id = Column(Integer, ForeignKey('backends.id'))
version = Column(String(255), nullable=True)
typename = Column(String(255))
backend = relationship('Backend')
__mapper_args__ = {
'polymorphic_on': typename
}
def __repr__(self):
return '<BackendPeerIdentity(identity={0}|typename={2},version={3})>'.format(
self.identity,
self.typename,
self.version
)
class CalendarPeerIdentity(BackendPeerIdentity):
__mapper_args__ = {
'polymorphic_identity': 'Calendar'
}
calendar_id = Column(Integer, ForeignKey('calendars.id'))
calendar = relationship('Calendar', backref=backref('identities', order_by=BackendPeerIdentity.backend_id, cascade="all, delete-orphan"))
class EventPeerIdentity(BackendPeerIdentity):
__mapper_args__ = {
'polymorphic_identity': 'Event'
}
event_id = Column(Integer, ForeignKey('events.id'))
event = relationship('Event', backref=backref('identities', order_by=BackendPeerIdentity.backend_id, cascade="all, delete-orphan"))
class ContactPeerIdentity(BackendPeerIdentity):
__mapper_args__ = {
'polymorphic_identity': 'Contact'
}
contact_id = Column(Integer, ForeignKey('contacts.id'))
contact = relationship('Contact', backref=backref('identities', order_by=BackendPeerIdentity.backend_id, cascade="all, delete-orphan"))
#-------------------------------------------------------------------------------
# Auditing
#-------------------------------------------------------------------------------
class AuditEntry(SqlAlchemyPersistence.Base):
"""
Represent an audit entry for the calendar component.
SQLAlchemy mapped class.
"""
__tablename__ = 'auditlog'
id = Column(Integer, primary_key=True)
datetime = Column(DateTime)
principal = Column(String(128))
action = Column(String(32))
data_type = Column(String(255))
data_before = Column(Text)
data_after = Column(Text)
__mapper_args__ = {
'polymorphic_on': data_type
}
def __repr__(self):
return '<AuditEntry(id={0}|datetime={1}|principal={2}|action={3}|datatype={4})>'.format(
self.id,
self.datetime,
self.principal,
self.action,
self.datatype
)
class CalendarAuditEntry(AuditEntry):
__mapper_args__ = {
'polymorphic_identity': 'calendar'
}
class EventAuditEntry(AuditEntry):
__mapper_args__ = {
'polymorphic_identity': 'event'
}
class ContactAuditEntry(AuditEntry):
__mapper_args__ = {
'polymorphic_identity': 'contact'
}
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: principal.py 269 2012-02-01 22:58:55Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/objects/principal.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Apr 26, 2011
@author Mario Steinhoff
"""
__version__ = '$Rev: 269 $'
from sqlalchemy import Column, Integer, String, Boolean
from sqlalchemy.schema import ForeignKey
from sqlalchemy.orm import relationship, backref
from core.persistence import SqlAlchemyPersistence
class Principal(SqlAlchemyPersistence.Base):
"""
Represent a principal for the principal component.
SQLAlchemy mapped class.
"""
__tablename__ = 'principals'
id = Column(Integer, primary_key=True)
login = Column(String(32))
password = Column(String(255))
role = Column(Integer)
disabled = Column(Boolean)
class Nickname(SqlAlchemyPersistence.Base):
"""
Represent a IRC nickname associated with a principal.
SQLAlchemy mapped class.
"""
__tablename__ = 'nicknames'
nickname = Column(String(32), primary_key=True)
principal_id = Column(Integer, ForeignKey('principals.id'), nullable=True)
principal = relationship(Principal, backref=backref('nicknames', order_by=nickname))
class Role(object):
"""
Represent a role.
Right.USER = 1
Right.AUTHED = 2
Right.ADMIN = 4
TODO: rework role/rights concept.
"""
USER = 1 # Right.USER
AUTHED = 3 # Right.USER | Right.AUTHED
ADMIN = 7 # Right.USER | Right.AUTHED | Right.ADMIN
def __init__(self):
"""
This class may currently not be instantiated.
"""
raise NotImplementedError
@staticmethod
def valid(required, role):
"""
Check whether the user role contains sufficient rights.
@param required: The minimum rights to validate.
@param role: The actual rights.
@return True if there are sufficient rights, False otherwise.
"""
return (required & role == required)
@staticmethod
def string(role):
"""
Return the string representation of the given role.
@param role: The role.
@return The role string.
"""
strings = {
1: 'User',
2: 'Authenticated',
3: 'Authenticated',
4: 'Administrator',
7: 'Administrator'
}
return strings[role]
class Right(object):
"""
Represents an individual right. (read, write, delete, etc)
"""
def __init__(self, name=None, mask=None):
self.name = name
self.mask = mask
| Python |
'''
Created on 27.01.2012
@author: rack
'''
from sqlalchemy import Column, Integer, DateTime, Text
from sqlalchemy.orm import relationship, backref
from sqlalchemy.schema import ForeignKey
from core.persistence import SqlAlchemyPersistence
class Topic(SqlAlchemyPersistence.Base):
"""
Represent an individual topic for the topic component
"""
__tablename__ = 'topics'
#DLL
id = Column(Integer, primary_key=True)
addition_id = Column(Integer, ForeignKey('topicadditions.id'))
date = Column(DateTime)
text = Column(Text)
year = Column(Integer)
user = Column(Text)
#ORM - one-to-many
addition = relationship('TopicAddition', backref=backref('topics'))
def __repr__(self):
return '<Topic(id={0}|date={1}|text={2}|year={3}|user={4})>'.format(
self.id,
self.date,
self.text,
self.year,
self.user
)
class TopicAddition(SqlAlchemyPersistence.Base):
"""
Represent an addition for the topic component
"""
__tablename__ = 'topicadditions'
#DLL
id = Column(Integer, primary_key=True)
date = Column(DateTime)
text = Column(Text)
user = Column(Text)
def __repr__(self):
return '<TopicAddition(id={0}|date={1}|text={2}|user={3})>'.format(
self.id,
self.date,
self.text,
self.user,
) | Python |
# -*- coding: UTF-8 -*-
"""
$Id: facts.py 227 2011-09-12 22:15:03Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/objects/facts.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since May 6, 2011
@author Mario Steinhoff
"""
__version__ = '$Rev: 227 $'
__all__ = [
'Fact'
]
from sqlalchemy import Column, Integer, Date, Text
from core.persistence import SqlAlchemyPersistence
class Fact(SqlAlchemyPersistence.Base):
"""
Represent an individual fact for the fact component.
SQLAlchemy mapped class.
"""
__tablename__ = 'facts'
id = Column(Integer, primary_key=True)
date = Column(Date)
text = Column(Text)
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: irc.py 269 2012-02-01 22:58:55Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/objects/irc.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since May 3, 2011
@author Mario Steinhoff
"""
__version__ = '$Rev: 269 $'
_all = [
'ServerSource',
'ClientSource',
'User',
'Channel',
'Location'
]
CHANNEL_TOKEN = '\x23'
class ServerSource(object):
"""
A IRC server source entity.
"""
def __init__(self, servername=None):
"""
Create a new instance.
@param servername: The servername of the entity
"""
self.servername = servername or ''
def __str__(self):
"""
Return the string representation in the format 'servername'.
"""
return '{0}'.format(self.servername)
class ClientSource(object):
"""
A IRC client source entity.
"""
def __init__(self, nickname=None, ident=None, host=None):
"""
Create a new instance.
@param nickname: The nickname of the entity
@param ident: The ident of the entity
@param host: The hostname of the entity
"""
self.nickname = nickname or ''
self.ident = ident or ''
self.host = host or ''
def __str__(self):
"""
Return the string representation in the format 'nickname!ident@host'.
"""
return '{0}!{1}@{2}'.format(self.nickname, self.ident, self.host)
class User(object):
AWAY = 'a'
INVISIBLE = 'i'
WALLOPS = 'w'
RESTRICTED = 'r'
OPER = 'o'
LOCALOPER = 'O'
SERVERNOTICE = 's'
def __init__(self, source=None, realname=None):
"""
Initialize the user.
@param source: The Source object.
@param realname: The realname of the user.
"""
self.source = source
self.realname = realname or ''
self.channels = []
self.nicklist = [source.nickname]
self.data = {}
def __str__(self):
"""
Return a string representation for debugging purposes.
"""
return 'User(Nickname={0},Ident={1},Host={2},Realname={3},Channels={4})'.format(
self.source.nickname,
self.source.ident,
self.source.host,
self.realname,
'|'.join(map(str, self.channels))
)
def set_data(self, identifier, data):
"""
Set arbitrary information on a per-user basis.
@param identifier: The identifier name.
@param data: Any python object.
"""
self.data[identifier] = data
def get_data(self, identifier):
"""
Retrieve user-based information.
@param identifier: The identifier name.
"""
return self.data[identifier]
def rename(self, new_nickname):
"""
Rename the user.
Notify all channels the user and bot have in common.
@param new_nickname: The user's new nickname.
"""
for channel in self.channels:
channel.rename_user(self.source.nickname, new_nickname)
if new_nickname not in self.nicklist:
self.nicklist.append(new_nickname)
self.source.nickname = new_nickname
def add_channel(self, channel, mode=None):
"""
Adds a channel to the user.
This should never be called directly but only by the
Channellist module.
@param channel: The channel object to add.
"""
if channel in self.channels:
raise KeyError
channel.add_user(self, mode)
self.channels.append(channel)
def get_channel(self, channel):
"""
Return a channel object by its name.
@param channel: The name of the channel object.
"""
return self.channel[channel]
def get_channels(self):
"""
Return a list of all channels that user and bot have in common.
"""
return self.channels
def is_on(self, channel):
"""
Determines whether the user is on the given channel.
@param channel: The channel object to check against.
"""
return channel in self.channels
def remove_channel(self, channel):
"""
Removes a channel from the user.
@param channel: The channel object to remove.
"""
if channel not in self.channels:
raise KeyError
channel.remove_user(self.source.nickname)
self.channels.remove(channel)
class Channel(object):
"""
A channel entity.
"""
USERMODE_NONE = 1
USERMODE_OP = 2
USERMODE_VOICE = 4
def __init__(self, name, topic=None):
"""
Initialize a channel.
"""
self.name = name
self.topic = topic or ''
self.users = {}
self.modes = []
def __str__(self):
"""
Return a string representation for debugging purposes.
"""
return 'Channel(Name={0}, Users={1})'.format(self.name, '|'.join(self.users))
def get_modes(self):
"""
Yeah, what to do here? do we need this actually?
"""
pass
def add_user(self, user, mode=USERMODE_NONE):
"""
Add a user object to the channel.
@param user: The user object.
@param mode: The user mode in the channel.
"""
self.users[user.source.nickname] = (user, mode)
def get_user(self, nickname):
"""
Return a user object by its nickname.
@param nickname: The nickname of the user object.
"""
return self.users[nickname][0]
def set_user_mode(self, nickname, mode):
"""
Updates the user mode.
@param nickname: The nickname of the user.
@param mode: The new user mode.
"""
self.users[nickname] = (self.get_user(nickname), mode)
def get_user_mode(self, nickname):
"""
Return the mode of a user by its nickname.
@param nickname: The nickname of the user object.
"""
return self.users[nickname][1]
def get_users(self):
"""
Return the current user list of the channel.
@return The user list.
"""
return self.users
def rename_user(self, current_nickname, new_nickname):
"""
Rename a user object.
This will only modify the internal user key but will not touch
the user object directly.
@param current_nickname: The current nickname of the user object.
@param new_nickname: The new nickname of the user object.
"""
user = self.users[current_nickname]
self.users[new_nickname] = user
del self.users[current_nickname]
def remove_user(self, nickname):
"""
Remove a user object from the channel.
@param nickname: The nickname of the user.
"""
del self.users[nickname]
"""class Location(object):
def __init__(self, id=None, name=None):
self.id = id
self.name = name
def __str__(self):
return self.name"""
class Location(object):
"""
Represent a location determining where a ModuleCommand can be executed.
TODO: need real object here or maybe move to own python module?
"""
CHANNEL = 1
QUERY = 2
BOTH = CHANNEL | QUERY
def __init__(self):
"""
This class may currently not be instantiated.
"""
raise NotImplementedError
@staticmethod
def get(target):
"""
Derive the location from the target.
@param target: The target to check.
@return CHANNEL If the target starts with a channel token,
QUERY otherwise.
"""
if target.startswith(CHANNEL_TOKEN):
location = Location.CHANNEL
else:
location = Location.QUERY
return location
@staticmethod
def valid(required, location):
"""
Check whether the location matches the requirements.
@param required: The locations that are valid.
@param location: The actual location.
@return True if the actual location is within the required location,
False otherwise.
"""
return (required | location == required)
@staticmethod
def string(location):
"""
Return the string representation of the given location.
@param location: The location.
@return The location string.
"""
strings = {
1: 'Channel',
2: 'Query'
}
return strings[location]
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: __init__.py 250 2011-09-27 00:35:29Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/objects/__init__.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Apr 26, 2011
@author Mario Steinhoff
"""
__version__ = '$Rev: 250 $'
__all__ = [
'principal',
'calendar',
'facts',
'irc',
]
import datetime
def set_deletion_date(context):
if 'isDeleted' in context.current_parameters and context.current_parameters['isDeleted'] == True:
return datetime.datetime.now()
| Python |
'''
Created on 21.02.2012
@author: rack
'''
from sqlalchemy import Column, Integer, DateTime, Text
from core.persistence import SqlAlchemyPersistence
class Quote(SqlAlchemyPersistence.Base):
"""
Represent a quote.
"""
__tablename__ = 'quotes'
#DLL
id = Column(Integer, primary_key=True)
date = Column(DateTime)
text = Column(Text)
user = Column(Text)
def __repr__(self):
return '<Quote(id={0}|date={1}|text={2}|user={3})>'.format(
self.id,
self.date,
self.text,
self.user
) | Python |
# -*- coding: UTF-8 -*-
"""
$Id$
$URL$
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Jan 6, 2011
@author Mario Steinhoff
"""
__version__ = '$Rev$'
import os
from core import runlevel
from core.bot import Bot
if __name__ == '__main__':
config_root = os.environ['FPTBOT_CONFIG']
bot = Bot(root=config_root)
bot.init(runlevel.NETWORK_INTERACTION)
| Python |
# -*- coding: UTF-8 -*-
"""
$Id$
$URL$
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Aug 05, 2010
@author rack
"""
import sqlite3
def main():
conn = sqlite3.connect('db/kalender')
c = conn.cursor()
c.execute('''create table stocks (date text, trans text, symbol text, qty real, price real)''')
c.execute("""insert into stocks values ('2006-01-05','BUY','RHAT',100,35.14)""")
conn.commit()
c.close()
print "done"
if __name__ == '__main__':
main()
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: mp.py 221 2011-07-21 18:25:10Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/test/language/mp.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Jan 9, 2011
@author Mario Steinhoff
"""
from multiprocessing import Process, Pipe
from random import seed, choice
from time import sleep
class Thread(object):
def __init__(self, name, pipe):
self.name = name
self._pipe = pipe
def sendMessage(self, target, data):
message = {}
message['source'] = self.name
message['target'] = target
message['data'] = data
self._pipe.send(message)
def recvMessage(self):
msg = self._pipe.recv()
if len(msg) > 0:
return msg
class ProcessOne(Thread):
def __init__(self, pipe):
Thread.__init__(self, 'one', pipe)
while True:
msg = self.recvMessage()
print "From %s to %s: %s" % (msg['source'], msg['target'], msg['data'])
if msg['source'] == "two" and msg['data'] == "foo":
self.sendMessage(msg['source'], 'bar')
class ProcessTwo(Thread):
def __init__(self, pipe):
Thread.__init__(self, 'two', pipe)
while True:
msg = self.recvMessage()
print "Two: %s" % msg['data']
self.sendMessage('one', 'foo')
if msg['source'] == "one" and msg['data'] == "bar":
self.sendMessage(msg['source'], 'ok')
def startProcess(f):
dispatcher_pipe, process_pipe = Pipe()
process = Process(target=f, args=(process_pipe, ))
process.start()
return {'process': process, 'pipe': dispatcher_pipe}
if __name__ == '__main__':
print "main start"
pr = {}
pr['a'] = startProcess(ProcessOne)
pr['b'] = startProcess(ProcessTwo)
while True:
print "loop"
# retrieve from all processes
msgs = [pr[p]['pipe'].recv() for p in pr]
print msgs
[pr[msg['target']]['pipe'].send(msg['data']) for msg in msgs if len(msgs['data']) > 0 and msg['target'] in pr]
print "main stop"
| Python |
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
"""A really tiny interface to ``tinyurl.com``."""
import sys
import urllib
import optparse
API_CREATE = "http://tinyurl.com/api-create.php"
DEFAULT_DELIM = "\n"
USAGE = """%prog [options] url [url url ...]
""" + __doc__ + """
Any number of urls may be passed and will be returned
in order with the given delimiter, default=%r
""" % DEFAULT_DELIM
ALL_OPTIONS = (
(('-d', '--delimiter'),
dict(dest='delimiter', default=DEFAULT_DELIM,
help='delimiter for returned results')),
)
def _build_option_parser():
prs = optparse.OptionParser(usage=USAGE)
for args, kwargs in ALL_OPTIONS:
prs.add_option(*args, **kwargs)
return prs
def create_one(url):
url_data = urllib.urlencode(dict(url=url))
ret = urllib.urlopen(API_CREATE, data=url_data).read().strip()
return ret
def create(*urls):
for url in urls:
yield create_one(url)
def main(sysargs=sys.argv[:]):
parser = _build_option_parser()
opts, urls = parser.parse_args(sysargs[1:])
for url in create(*urls):
sys.stdout.write(url + opts.delimiter)
return 0
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
"""A really tiny interface to ``tinyurl.com``."""
import sys
import urllib
import optparse
API_CREATE = "http://tinyurl.com/api-create.php"
DEFAULT_DELIM = "\n"
USAGE = """%prog [options] url [url url ...]
""" + __doc__ + """
Any number of urls may be passed and will be returned
in order with the given delimiter, default=%r
""" % DEFAULT_DELIM
ALL_OPTIONS = (
(('-d', '--delimiter'),
dict(dest='delimiter', default=DEFAULT_DELIM,
help='delimiter for returned results')),
)
def _build_option_parser():
prs = optparse.OptionParser(usage=USAGE)
for args, kwargs in ALL_OPTIONS:
prs.add_option(*args, **kwargs)
return prs
def create_one(url):
url_data = urllib.urlencode(dict(url=url))
ret = urllib.urlopen(API_CREATE, data=url_data).read().strip()
return ret
def create(*urls):
for url in urls:
yield create_one(url)
def main(sysargs=sys.argv[:]):
parser = _build_option_parser()
opts, urls = parser.parse_args(sysargs[1:])
for url in create(*urls):
sys.stdout.write(url + opts.delimiter)
return 0
if __name__ == '__main__':
sys.exit(main())
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: bottest.py 221 2011-07-21 18:25:10Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/test/language/bottest.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Jan 12, 2011
@author Mario Steinhoff
"""
"""
import gdata.calendar.client
def PrintUserCalendars(calendar_client):
feed = calendar_client.GetAllCalendarsFeed()
print feed.title.text
for i, a_calendar in enumerate(feed.entry):
print '\t%s. %s' % (i, a_calendar.title.text,)
calendar_client = gdata.calendar.client.CalendarClient(source='foption-fptbot-1.0')
calendar_client.ssl = True
calendar_client.ClientLogin('fptbot@googlemail.com', 'deinemudderfistedbots1337', calendar_client.source);
PrintUserCalendars(calendar_client)
"""
import urllib
import re
import htmlentitydefs
import datetime
from objects.facts import Fact
class SchoelnastAtFactSource(object):
"""
A data source for wissen.schoelnast.at.
"""
URL = 'http://wissen.schoelnast.at/alles.shtml'
LINE_PATTERN = r'<tr><td class="li"><a(.*)>(?P<date>\d{1,2}\.\d{1,2}\.\d{4})</a></td><td class="re2">(?P<fact>.*)<span class="blau">'
LINE_DATE_FORMAT = '%d.%m.%Y'
ENTITY_NAME_PATTERN = r'&({0});'.format('|'.join(htmlentitydefs.name2codepoint))
ENTITY_CP_PATTERN = r'&#(\d{1,4});'
def __init__(self):
self.line_matcher = re.compile(self.LINE_PATTERN)
self.entity_name_matcher = re.compile(self.ENTITY_NAME_PATTERN)
self.entity_cp_matcher = re.compile(self.ENTITY_CP_PATTERN)
def _entity2unichr(self, input):
"""
# TODO optimize
"""
def name_converter(entity_match):
return unichr(htmlentitydefs.name2codepoint[entity_match.group(1)])
def cp_converter(entity_match):
return unichr(int(entity_match.group(1)))
output = re.sub(self.entity_name_matcher, name_converter, input)
output = re.sub(self.entity_cp_matcher, cp_converter, output)
return output
def get_data(self):
stream = urllib.urlopen(self.URL)
raw_lines = stream.readlines()
stream.close()
limit_date = getattr(self, 'limit_date', datetime.date(2000, 1, 1))
new_data = []
for raw_line in raw_lines:
raw_line = raw_line.strip()
result = self.line_matcher.search(raw_line)
if not result:
continue
date = datetime.datetime.strptime(result.group('date'), self.LINE_DATE_FORMAT).date()
if date < limit_date:
continue
fact = Fact()
fact.date = date
fact.text = self._entity2unichr(result.group('fact')).strip()
new_data.append(fact)
return new_data
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: calendar.py 287 2012-05-31 17:26:48Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/test/feature/components/calendar.py $
Copyright (c) 2011 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Jul 23, 2011
@author Mario Steinhoff
"""
__version__ = '$$'
import datetime
import json
from core import runlevel
from core.bot import Bot
from objects.calendar import Calendar, Event
from components.calendar import GoogleBackend
try:
bot = Bot()
bot.init(runlevel.NETWORK_SERVICE)
cc = bot.get_subsystem('calendar-component')
"""
event = Event(start=datetime.date(2011, 9, 26), end=datetime.date(2011, 9, 27), title="sync-test")
event = cc.insert_object(event)
scnds = cc.datastore.secondary_backends
gbe = [scnd for scnd in scnds if isinstance(scnd, GoogleBackend)][0]
query = cc.datastore.get_query('event_by_id')
local_id = [identity for identity in event.identities if identity.backend.typename == 'GoogleBackend'][0]
query.id = json.loads(local_id.identity)['edit']
gev = gbe.find_objects(query)
query = cc.datastore.get_query('all_calendars_feed')
for i, calendar in enumerate(gbe.find_objects(query).entry):
print calendar.title.text
print calendar.id.text
print calendar.find_url(gbe.LINK_EVENTFEED)
print "---"
"""
calendar = Calendar(title='Party')
cc.insert_object(calendar)
event = Event(calendar=calendar, start=datetime.date(2011, 9, 30), end=datetime.date(2011, 10, 1), title="gangbang bei baums mutter")
cc.insert_object(event)
except:
bot.get_logger().exception('Unhandled exception')
finally:
bot.init(runlevel.HALT)
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: persistence.py 285 2012-05-31 17:25:54Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/test/feature/core/persistence.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Sep 8, 2011
@author Mario Steinhoff
"""
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: config.py 221 2011-07-21 18:25:10Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/test/feature/core/config.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Mar 12, 2011
@author Mario Steinhoff
"""
__version__ = '$Rev: 221 $'
import unittest
from core.constants import DIR_CONFIG
from core.config import Config
class TestConfig(unittest.TestCase):
def setUp(self):
self.bot = DummyBot()
self.config = DummyConfig(self.bot)
def test_00_instantiation(self):
self.assertTrue(isinstance(self.config._bot, DummyBot))
self.assertTrue(len(self.config._keys) > 0)
def test_01_name(self):
self.assertEquals(self.config.identifier, 'test.core.config')
def test_02_validation(self):
invalid = {'test5': 'foobar', 'test2' : 42}
result = self.config.filter_valid_keys(invalid)
self.assertTrue('test2' in result)
self.assertTrue('test5' not in result)
def test_03_data_io(self):
object1 = 03
object2 = 4.3382
object3 = 'foobar42'
self.config.set('test10', object1)
self.config.set('test20', object2)
self.config.set('test30', object3)
self.assertTrue('test10' in self.config._keys)
self.assertEquals(self.config.get('test10'), object1)
self.assertTrue('test20' in self.config._keys)
self.assertEquals(self.config.get('test20'), object2)
self.assertTrue('test30' in self.config._keys)
self.assertEquals(self.config.get('test30'), object3)
def test_05_delete(self):
self.config.delete('test2')
self.assertRaises(KeyError, self.config.get, 'test2')
self.assertTrue('test1' in self.config._keys)
def test_06_save(self):
self.config.save()
self.config.set('test10', 'foobar84')
filename = '{0}/{1}'.format(DIR_CONFIG, self.config.identifier)
self.assertTrue(filename in self.bot.get_persistence().storage)
self.assertEquals(self.bot.get_persistence().storage[filename]['test1'], 10)
self.assertTrue('test10' not in self.bot.get_persistence().storage[filename])
def test_07_load(self):
pass
class DummyBot():
def __init__(self):
self.persistence = MemoryPersistence()
def get_persistence(self):
return self.persistence
class MemoryPersistence():
def __init__(self):
self.storage = {}
def readobject(self, filename):
if filename not in self.storage:
self.storage[filename] = {}
return self.storage[filename]
def writeobject(self, filename, object):
self.storage[filename] = {}
self.storage[filename].update(object)
class DummyConfig(Config):
identifier = 'test.core.config'
def valid_keys(self):
return ['test1', 'test2', 'test3', 'test10', 'test20', 'test30']
def default_values(self):
return {'test1': 10, 'test2': 'foobar', 'test3': False}
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: channel.py 201 2011-05-02 20:11:11Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/test/feature/interaction/irc/channel.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Mar 10, 2011
@author Mario Steinhoff
"""
__version__ = '$Rev: 201 $'
import unittest
from interaction.irc.source import ClientSource
from interaction.irc.channel import ChannelList, Channel, UserList, User
class TestModule(unittest.TestCase):
def setUp(self):
self.source = ClientSource(nickname='Testnick', ident='testident', host='testhost.example.org')
self.user = User(source=self.source, realname='Testname')
self.channel = Channel(name='#channel')
self.chanlist = ChannelList(client=None)
self.userlist = UserList(client=None)
class TestChannel(TestModule):
def test_00_instantiation(self):
self.assertEquals(self.channel.name, '#channel')
self.assertEquals(self.channel.users, {})
def test_01_adduser(self):
lenbefore = len(self.channel.get_users())
self.channel.add_user(self.user)
lenafter = len(self.channel.get_users())
self.assertTrue(lenafter-lenbefore == 1)
self.assertTrue(self.channel.get_user('Testnick') == self.user)
def test_02_getusers(self):
self.channel.add_user(self.user, None)
self.assertTrue('Testnick' in self.channel.get_users())
def test_03_renameuser(self):
self.channel.add_user(self.user, None)
self.channel.rename_user('Testnick', 'NewTestNick')
self.assertRaises(KeyError, self.channel.get_user, 'Testnick')
self.assertRaises(KeyError, self.channel.get_user, 'newtestnick')
self.assertEquals(self.channel.get_user('NewTestNick'), self.user)
self.assertEquals(self.user.source.nickname, 'Testnick')
class TestChannellist(TestModule):
def test_00_instantiation(self):
self.assertEquals(self.chanlist.channels, {})
def test_01_addchannel(self):
self.chanlist.add(self.channel)
self.assertNotEquals(self.chanlist.channels, {})
self.assertEquals(self.chanlist.get('#channel'), self.channel)
class TestUser(TestModule):
pass
class TestUserlist(TestModule):
pass
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: source.py 221 2011-07-21 18:25:10Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/test/feature/interaction/irc/source.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Mar 10, 2011
@author Mario Steinhoff
"""
__version__ = '$Rev: 221 $'
import unittest
from interaction.irc.source import ServerSource, ClientSource
class TestServerSource(unittest.TestCase):
def test_00_instantiation(self):
servername = 'irc.example.org'
self.source = ServerSource(servername)
self.assertTrue(isinstance(self.source, ServerSource))
self.assertEquals(self.source.servername, servername)
class TestClientSource(unittest.TestCase):
def test_00_instantiation(self):
nickname = 'Testnick'
ident = 'testident'
host = 'test.example.org'
self.source = ClientSource(nickname, ident, host)
self.assertTrue(isinstance(self.source, ClientSource))
self.assertEquals(self.source.nickname, nickname)
self.assertEquals(self.source.ident, ident)
self.assertEquals(self.source.host, host)
| Python |
# -*- coding: UTF-8 -*-
"""
$Id: bot.py 221 2011-07-21 18:25:10Z steinhoff.mario $
$URL: http://fptbot.googlecode.com/svn/trunk/fptbot/src/python/test/feature/bot.py $
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Mar 10, 2011
@author Mario Steinhoff
"""
__version__ = '$Rev: 221 $'
from test.feature.core.config import TestConfig
from test.feature.interaction.irc.channel import TestChannel, TestChannellist, TestUser, TestUserlist
from test.feature.interaction.irc.source import TestServerSource, TestClientSource
| Python |
# -*- coding: UTF-8 -*-
"""
$Id$
$URL$
Copyright (c) 2010 foption
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@since Jan 6, 2011
@author Mario Steinhoff
"""
__all__ = [
]
| Python |
import re
import syms
import copy
from Odict import odict
import pprint
pretty = pprint.PrettyPrinter(indent=1)
def get_line_number(original, position):
return len(original[0:position].split('\n'))
class Parsed(object):
def __init__(self, obj, *args, **kwargs):
self.type = obj.parser_name
self.nodes = [node for node in args if node]
self.value = kwargs.get('value')
def is_terminal(self):
if self.nodes:
return False
return True
def to_data(self):
if self.is_terminal():
if self.value is not None:
return '<' + self.type + ': ' + self.value + '>'
else:
return '<' + self.type + '>'
else:
return ( self.type, [ to_data(node) for node in self.nodes ])
def __repr__(self):
return pretty.pformat(self.to_data())
def to_data(obj):
if hasattr(obj, 'to_data'):
return obj.to_data()
elif isinstance(obj, list):
return [ to_data(ele) for ele in obj ]
elif isinstance(obj, dict):
return dict( [ (key, to_data(value)) for key, value in obj.items() ] )
elif isinstance(obj, tuple):
return tuple( [ to_data(ele) for ele in obj ] )
return obj
class ParserPointer(syms.symbol):
def parse(self, input):
return self.parser.parse(input)
def set_parser(self, parser):
self._parser = parser
def check_parser(self):
if hasattr(self,'_parser'):
return self._parser
else:
raise Exception('Symbol '+self.name+' has no parser assigned')
parser = property(fget=check_parser, fset=set_parser)
def get_parser_name(self):
return self.name
parser_name = property(fget=get_parser_name);
def __call__(self, *args):
if hasattr(self, '_parser'):
return self.parser(*args)
else:
return RepeatFactory(self, *args)
syms.set_default(ParserPointer)
class Token(Parsed):
def __init__(self, name, value=None):
self.type = name
self.nodes = []
self.value = value
self.parser_name = name
def parse(self, input):
if input[0].type == self.type:
return (input[0], 1)
return False
class AST(Parsed):
def __init__(self, name, **kwargs):
self.type = name
self.keys = []
self.nodes = []
for key in kwargs:
self.__dict__[key] = kwargs[key]
self.keys.append(key)
def to_data(self):
out_list = [ self.type ]
for key in self.keys:
out_list += [ ( key, to_data(self.__dict__[key]) ) ]
return tuple(out_list)
def ParsedF(obj, *args, **kwargs):
"""Factory Function for the Parsed object"""
new = Parsed(obj, *args, **kwargs)
if hasattr(obj, '_handler'):
ret_val = getattr(obj, '_handler')(new)
if ret_val is not None:
return ret_val
return new
class ParserClass(object):
def __call__(self, *args):
return RepeatFactory(self, *args)
def RepeatFactory(self, *args):
def make_dct(min=0,max=None):
dct = {'min' : min, 'item': self}
if max:
dct['max']=max
return dct
if len(args)==0:
name = get_name(self.parser_name + '__many')
else:
if isinstance(args[0], str):
name=args[0]
args = args[1:]
else:
name=get_name(self.parser_name + '__many' + '__'.join(args))
return Repeat(name, **make_dct(*args))
class Empty(ParserClass):
def __init__(self, name='Empty'):
self.parser_name = name
def parse(self, input):
return Token(self.parser_name), 0
EMPTY = Empty()
class Node(ParserClass):
def __init__(self, name, regexp, has_value=False, ignore_groups=False, ignore_case=False):
self.parser_name = name
flags = re.DOTALL
if ignore_case:
flags |= re.IGNORECASE
self.regexp = re.compile('^'+regexp, flags)
self.has_value = has_value
self.ignore_groups = ignore_groups
def parse(self, input):
match_obj = self.regexp.match(input)
if match_obj:
if self.has_value:
if not self.ignore_groups and match_obj.groups():
value = match_obj.groups()[0]
else:
value = input[match_obj.start():match_obj.end()]
value = value
else:
value = None
return ParsedF(self,value=value), match_obj.end()
else:
return False
def T(name, regexp, has_value=True):
return Node(name, regexp,has_value=has_value)
lit = re.escape
class Choice(ParserClass):
def __init__(self, name, choices):
self.parser_name=name
self.choices=choices
def parse(self, input):
for choice in self.choices:
parse_result = choice.parse(input)
if parse_result:
return ParsedF(self, parse_result[0]), parse_result[1]
return False
def C(name, *args, **kwargs):
choices = [ factory(arg, name+'_'+str(cnt)) for cnt, arg in enumerate(args) ]
for _name, parser in odict(kwargs).items():
choices += [ factory(parser, _name) ]
return Choice(name, choices)
class Repeat(ParserClass):
def __init__(self, name, item, min=0, max=None):
self.parser_name = name
self.item = item
self.min = min
self.max = max
self.has_max = (max is not None)
self.length = 0
def parse(self, input):
success = True
results = []
self.length = 0
while success and not self.done(results):
result = self.item.parse(input)
if result:
results.append(result[0])
input = input[result[1]:]
self.length += result[1]
else:
success=False
if len(results) >= self.min:
return ParsedF(self, *results), self.length
return False
def done(self, lst):
if self.has_max:
return (len(lst) >= self.max)
class Rule(ParserClass):
def __init__(self, name, rule):
self.parser_name = name
self.rule = R(None, rule, True)
def parse(self, input):
results = []
chars = 0
for item in self.rule:
result = item.parse(input)
if result:
results.append(result[0])
input = input[result[1]:]
chars += result[1]
else:
return False
return ParsedF(self, *results), chars
def R(name, parsers, root=False):
rule = [ factory(parser) for parser in parsers ]
if root:
return rule
return Rule(name, rule)
def L(*parsers):
name = parsers[0].parser_name
for parser in parsers[1:]:
name += '__' + parser.parser_name
return R(get_name(name), parsers)
nameless_parsers = 0
semi_nameless = {}
def get_name(name=None):
global nameless_parsers
global semi_nameless
if name:
if semi_nameless.has_key(name):
semi_nameless[name] += 1
else:
semi_nameless[name] = 0
return name + '_' + str(semi_nameless[name])
else:
nameless_parsers += 1
return '_' + str(nameless_parsers)
def reset_names():
global nameless_parsers
global semi_nameless
nameless_parsers = 0
semi_nameless = {}
def factory(arg, _name=None, **kwarg):
has_value = (_name is not None)
if _name is None:
_name = get_name()
if isinstance(arg, str):
return T(_name, arg, has_value)
if isinstance(arg, list):
return R(_name, arg)
if isinstance(arg, tuple):
return C(_name, *arg, **kwarg)
for parser_class in [ParserClass, syms.symbol, Token]:
if isinstance(arg, parser_class):
return arg
raise Exception('Parser unbuildable:' + repr(arg))
_regexp = re.compile('^_')
def D(sym, *arg, **kwargs):
#seperate out the keywords that begin with '_'
_kwargs = {}
for key in kwargs:
if _regexp.match(key):
_kwargs[key] = kwargs[key]
for key in _kwargs:
del kwargs[key]
if len(arg)== 1 and len(kwargs)==0:
arg = arg[0]
if isinstance(arg, syms.symbol):
grammer = copy.copy(arg.parser)
grammer.parser_name = sym.name
else:
grammer = factory(arg, sym.name, **kwargs)
sym.set_parser(grammer)
if _kwargs.has_key('_handler'):
grammer._handler = _kwargs['_handler']
| Python |
import Parser
clean_methods = {}
def clean_AST(self):
return clean_methods[self.type](self)
Parser.Parsed.clean = clean_AST
def clean(aName):
def aDecorator(aMethod):
clean_methods[aName] = aMethod
return aDecorator
@clean('Statement_0')
def simple(self):
return AST('FunctionDecl',
Parameters = self.nodes[2].clean(),
Code = self.nodes[4].clean(),
)
@clean('Statement_1')
def simple(self):
return self.nodes[0]
@clean('Statement_2')
def simple(self):
return AST('Assignment',
Var = self.nodes[0],
Expression = self.nodes[2].clean(),
)
@clean('Statement_3')
def simple(self):
return AST('Call',
Function = self.nodes[0],
Arguments = [ expression.clean() for expression in
self.nodes[1].nodes ],
)
@clean('ParList_0')
def simple(self):
par_list = [ self.nodes[0] ]
for par_item in self.nodes[1].nodes:
par_list += [ par_item.nodes[1] ]
return par_list
@clean('ParList_1')
def simple(self):
return []
@clean('ArgList_0')
def simple(self):
arg_list = [ self.nodes[0] ]
for arg_item in self.nodes[1].nodes:
arg_list += [ arg_item.nodes[1] ]
return arg_list
@clean('ArgList_1')
def simple(self):
return []
@clean('NewScope')
def simple(self):
return AST('NewScope', Statements=self.nodes[1].clean() )
@clean('Statement__many_0')
def simple(self):
return [ node.clean() for node in self.nodes ]
@clean('Expression_0')
def simple(self):
return AST('Call',
Function = self.nodes[0],
Arguments = self.nodes[2].clean(),
)
def first_node(self):
return self.nodes[0].clean()
for type in ['Statement', 'ParList', 'Expression', 'ArgList']:
clean_methods[type] = first_node
def no_clean(self):
return self
for type in ['Var', 'Value']:
clean_methods[type] = no_clean
| Python |
class symbol(object):
"""a class of symbol objects"""
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.name.__eq__(other.name)
def __repr__(self):
return 'S:'+self.name
def set_default(def_sym_class):
global symbol
symbol = def_sym_class
def constructor(kwargs):
constructor = symbol
if kwargs.has_key('sym_type'):
constructor = kwargs['sym_type']
return constructor
def define_module(mod, *symbols, **kwargs):
"""a function that lets you define symbols for a module"""
symbol_class = constructor(kwargs)
for symbol_name in symbols:
sym = symbol_class(symbol_name)
if isinstance(mod, dict):
mod[symbol_name] = sym
else:
setattr(mod, symbol_name, sym)
def define(*symbols, **kwargs):
"""a decorator that lets your the input function have a list
of symbols"""
symbol_class = constructor(kwargs)
def decorator(old_func):
def new_func(*args, **kwargs):
#initalize symbols
#keep track of overriden variables
old_globals = {}
none_globals = {}
f_globals = old_func.func_globals
#load up the local syms from the attached dict
for name, local_sym in new_func.local_syms.items():
if f_globals.has_key(name):
old_globals[name] = f_globals[name]
else:
none_globals[name] = True
f_globals[name] = local_sym
try:
ret_val = old_func(*args, **kwargs)
finally:
#restore previous globals
for key in old_globals:
f_globals[key] = old_globals[key]
for key in none_globals:
del f_globals[key]
return ret_val
#add the local syms to an aux dict attached to the function
if hasattr(old_func, 'local_syms'):
for key in symbols:
old_func.local_syms[key] = symbol_class(key)
return old_func
new_func.local_syms = {}
for key in symbols:
new_func.local_syms[key] = symbol_class(key)
return new_func
return decorator
| Python |
from Parser import Node, D, R, Token, EMPTY, L, lit, AST
import Parser
import re
token_types = ['TOKEN', 'COMMENT', 'LPAREN', 'RPAREN', 'LCURLY', 'COLON', 'NEXTLINE',
'RCURLY', 'LBRACK', 'RBRACK', 'EQUAL', 'COMMA', 'LANCE',
'SIMPLE_VAR', 'SPECIAL_VAR', 'TRUE', 'FALSE',
'ENDL', 'CODEBLOCK', 'STYLEBLOCK', 'ENDBLOCK',
'INTEGER_LITERAL', 'SYMBOL_LITERAL', 'SPACE', 'ERROR' ]
@Parser.syms.define(*token_types)
def Tokenizer(filename):
class ParseErr(Exception):
def __init__(self, msg):
self.args = (msg, Parser.get_line_number(input_stream, tokenizer.length))
token_list = []
class stack(object):
line = []
indent = [ 0 ]
total = []
styles_end = 0
D(COLON, ':' )
D(ENDL, '\s*\n( *)' )
def ind_val(Nd):
"""return how many spaces the line is indented"""
return len(Nd.value)
def colon_indent(Nd):
stack.line = []
Nd.value = Nd.nodes[1].value
Nd.nodes = []
if ind_val(Nd) > stack.indent[-1]:
stack.indent.append(ind_val(Nd))
stack.total.append('c')
else:
raise ParseErr('Illegal indentation')
D(CODEBLOCK, [COLON, ENDL],
_handler = colon_indent
)
def match_pairs(*args):
pairs = { '(':')', '[':']', '{':'}', 'c':'Dedentation', 's':'Dedentation' }
last = stack.total.pop()
if last not in args:
raise ParseErr('Expecting '+ pairs[last])
return last
def indent_hdlr(Nd):
d_list = []
#check if statement is over
open_statement = 0
for sym in ['(', '{', '[']:
open_statement += stack.total.count(sym)
if not open_statement:
#statement is over
d_list = ['newl']
if ind_val(Nd) > stack.indent[-1]:
if stack.line:
stack.total.append('s')
stack.line=[]
stack.indent.append(ind_val(Nd))
return Token('STYLEBLOCK')
else:
raise ParseErr('Indentation Not Allowed')
elif ind_val(Nd) < stack.indent[-1]:
try:
stack.line=[]
dedents = len(stack.indent)-stack.indent.index(ind_val(Nd))-1
for cnt in range(dedents):
stack.indent.pop()
d_list.append(match_pairs('s','c'))
except ValueError:
raise ParseErr('Indentations do not match')
return Token('END', d_list)
D(NEXTLINE, ENDL,
_handler = indent_hdlr
)
def make_hdlr(symbol):
def on(Nd):
stack.total.append(symbol)
stack.line.append(symbol)
def off(Nd):
match_pairs(symbol)
if stack.line:
stack.line.pop()
return {'on':on, 'off':off}
paren_hdlr = make_hdlr( '(' )
curly_hdlr = make_hdlr( '{' )
brack_hdlr = make_hdlr( '[' )
D(LPAREN, r'\(',
_handler = paren_hdlr['on']
)
D(RPAREN, r'\)',
_handler = paren_hdlr['off']
)
D(LCURLY, r'\{',
_handler = curly_hdlr['on']
)
D(RCURLY, r'\}',
_handler = curly_hdlr['off']
)
D(LBRACK, r'\[',
_handler = brack_hdlr['on']
)
D(RBRACK, r'\]',
_handler = brack_hdlr['off']
)
D(EQUAL, '=')
D(COMMA, ',')
D(LANCE, '->')
D(SIMPLE_VAR, '[a-z]\w*')
D(SPECIAL_VAR, '[A-Z]\w*')
D(INTEGER_LITERAL, '\d+')
D(SYMBOL_LITERAL, '`([a-z]\w*)')
D(SPACE, ' +')
TRUE = Node('TRUE', 'true', ignore_case=True)
FALSE = Node('FALSE', 'false', ignore_case=True)
def nothing_found(Nd):
raise ParseErr('Nothing Found')
D(ERROR, '.', _handler = nothing_found)
QUOTE=Node('QUOTE', r"('(\\'|[^'])*')" + '|' + r'("(\\"|[^"])*")',
has_value=True,
ignore_groups=True,
)
def get_quote(aNode):
aNode.value = ''.join(re.split(r'\\(.)', aNode.value))[1:-1]
QUOTE._handler = get_quote
D(COMMENT, r'#.*?\n' )
def emit_token(aToken):
token = aToken.nodes[0]
if token.type in ['SPACE', 'COMMENT', 'NEXTLINE']:
return
if stack.styles_end:
if token.type in ['RPAREN', 'RCURLY', 'RBRACK']:
stack.styles_end -= 1
else:
raise ParseErr('First non whitespace character on this line must be a ) or ] or }')
end_map = {'newl':'ENDSTATEMENT', 'c': 'ENDBLOCK', 's': 'ENDBLOCK'}
if token.type == 'END':
for type in token.value:
new_token = Token(end_map[type])
print new_token
token_list.append(new_token)
stack.styles_end = token.value.count('s')
else:
print token
token_list.append(token)
D(TOKEN,
CODEBLOCK, NEXTLINE, COLON, QUOTE, COMMENT, LPAREN, RPAREN, LCURLY,
TRUE, FALSE,
RCURLY, LBRACK, RBRACK, EQUAL, COMMA, SIMPLE_VAR, SPECIAL_VAR, LANCE,
INTEGER_LITERAL, SYMBOL_LITERAL, SYMBOL_LITERAL,
SPACE, ERROR,
_handler = emit_token
)
tokenizer = TOKEN()
input_stream = open(filename).read()
tokenizer.parse(input_stream)
for cnt in range(len(stack.indent)-1):
token_list.append(Token('ENDBLOCK'))
return token_list
@Parser.syms.define('Expression', 'ArgList', 'Var', 'Statement', 'Value',
'ParList', 'FnDcl', 'NewScope', 'ParItem', 'SymPar', 'ValPar')
@Parser.syms.define(sym_type=Parser.Token, *(token_types+['ENDSTATEMENT','QUOTE']))
def construct_AST(tokens):
Parser.reset_names()
D(Value, QUOTE, INTEGER_LITERAL, SYMBOL_LITERAL, TRUE, FALSE)
D(Statement,
[Var, LPAREN, ParList, RPAREN, NewScope],
[Expression, ENDSTATEMENT],
[SIMPLE_VAR, EQUAL, Expression, ENDSTATEMENT],
[Var, Expression(), ENDSTATEMENT]
)
D(ParList,
[ParItem, L(COMMA, ParItem)()],
EMPTY,
)
D(ParItem,
[SymPar, LANCE, ValPar],
ValPar,
)
D(SymPar, SIMPLE_VAR, SYMBOL_LITERAL)
D(ValPar, SIMPLE_VAR, Value)
D(NewScope, [CODEBLOCK, Statement(), ENDBLOCK] )
D(Expression,
[Var, LPAREN, ArgList, RPAREN],
Var,
Value,
)
D(ArgList,
[Expression, L(COMMA, Expression)()],
EMPTY,
)
D(Var, SIMPLE_VAR, SPECIAL_VAR)
Statements = []
# print Expression.parse(tokens)
while tokens:
exp, token_num = Statement.parse(tokens)
print exp
tokens = tokens[token_num:]
Statements += [exp]
return Statements
| Python |
import re
class odict(dict):
"""implements an ordered dictionary by keeping track of the order of the keys
>>> order_dict = odict( [(5, 'x'), (7,'r'), (1, 'err')] )
>>> for key in order_dict:
... print key
...
5
7
1
>>> order_dict
ordered dict {5: 'x', 7: 'r', 1: 'err'}
"""
key_regexp = re.compile('[a-zA-Z](\d+)$')
def __init__(self, dct = None):
def key_val(key):
return int(self.key_regexp.search(key).groups()[0])
def cmp_keys(key1, key2):
return cmp(key_val(key1), key_val(key2))
if isinstance(dct, dict):
self._keys = dct.keys()
self._keys.sort(cmp_keys)
new_dict = dct
else:
self._keys = []
new_dict = {}
for key, value in dct:
self._keys.append(key)
new_dict[key] = value
dict.__init__(self, new_dict)
def __delitem__(self, key):
self.__delitem__(self, key)
self._keys.remove(key)
def __setitem__(self, key, item):
dict.__setitem__(self, key, item)
if key not in self._keys: self._keys.append(key)
def clear(self):
dict.clear(self)
self._keys = []
def copy(self):
dict = dict.copy(self)
dict._keys = self._keys[:]
return dict
def items(self):
return zip(self._keys, self.values())
def keys(self):
return self._keys
def popitem(self):
try:
key = self._keys[-1]
except IndexError:
raise KeyError('dictionary is empty')
val = self[key]
del self[key]
return (key, val)
def setdefault(self, key, failobj = None):
dict.setdefault(self, key, failobj)
if key not in self._keys: self._keys.append(key)
def update(self, dct):
dict.update(self, dict)
for key in dct.keys():
if key not in self._keys: self._keys.append(key)
def values(self):
return map(self.get, self._keys)
def __iter__(self):
return self.odict_iter(self._keys)
def __repr__(self):
entry = lambda ky: repr(ky) + ': ' + repr(self[ky])
rep = 'ordered dict {' + entry(self._keys[0])
for key in self._keys[1:]:
rep += ', ' + entry(key)
return rep + '}'
class odict_iter(object):
def __init__(self, keys):
self._keys = keys
self.index = -1
def __iter__(self):
return self
def next(self):
if self.index+1 >= len(self._keys):
raise StopIteration
self.index += 1
return self._keys[self.index]
| Python |
print "hello world"
print "Here are the ten numbers from 0 to 9\n0 1 2 3 4 5 6 7 8 9"
print "I'm done!"
| Python |
# To change this template, choose Tools | Templates
# and open the template in the editor.
import sys
from xml.dom import minidom
from xml.etree import ElementTree as ET
__author__="muchmeck"
__date__ ="$Dec 20, 2010 8:20:49 PM$"
WIN_PROJECT_PATH = 'e:/programming/projectSettings.xml'
LNX_PROJECT_PATH = '/media/Project/programming/projectSettings.xml'
def xmlParser(projectPath):
try:
element = ET.parse(projectPath)
except Exception, inst:
print "Unexpected error opening %s: %s" % (projectPath, inst)
return
a = []
print a
print element._root
for subelement in element._root:
a.append(subelement.attrib)
a.append(subelement.text)
return a
if __name__ == "__main__":
print "Hello World"
if sys.platform== "win32":
result = xmlParser(WIN_PROJECT_PATH)
else:
result = xmlParser(LNX_PROJECT_PATH)
print result
print result[0]['attribute']
| Python |
# To change this template, choose Tools | Templates
# and open the template in the editor.
from maya.api import *
__author__="muchmeck"
__date__ ="$2011-jan-04 13:15:22$"
class SpamCmd(MPxCommand):
def __init__(self):
MPxCommand.__init__(self)
def doIt(self, arglist):
print "Spam & Eggs"
return MStatus()
@staticmethod
def newSyntax():
syntax = MSyntax()
return syntax
@staticmethod
def creator():
return SpamCmd()
def initializePlugin(obj):
plugin = MfnPlugin(obj)
stat= plugin.registerCommand("spam", SpamCmd.creator)
if not stat:
stat.perror("registerCommand failed")
return stat
def uninitializePlugin(obj):
plugin = MFnPlugin(obj)
stat = plugin.deregisterCommand("spam")
if not stat:
stat.perror("deregisterCommand failed")
return stat
"""
if __name__ == "__main__":
print "Hello World"
""" | Python |
import random as rand
#import maya.cmds as mc
revolve = 5
amount = 10
while i < amount:
print rand.randint(1, revolve)
i += 1
| Python |
import random as rand
#import maya.cmds as mc
revolve = 5
amount = 10
while i < amount:
print rand.randint(1, revolve)
i += 1
| Python |
import random as rand
#import maya.cmds as mc
holeList = mc.ls(sl=True)
materialList = mc.ls(mat=True)
revolve = 5
amount = 10
while i < amount:
print rand.randint(1, revolve)
i += 1
"""
## this is up for review
import random
import maya.cmds as cmds
dWin = cmds.window(title="Random Shader", wh=(182,160))
cmds.columnLayout()
cmds.button(label="Load objects", command="selObjects = cmds.ls(selection=True)")
cmds.text(label="Load objects to shade")
cmds.button(label="Load shaders", command="selShaders = cmds.ls(selection=True)")
cmds.text(label="Load shaders")
cmds.button(label="Assign shaders", command="assignShaders()")
cmds.text(label="Randomise and assign shaders")
cmds.showWindow(dWin)
def assignShaders():
sizeListObjects = len(selObjects)
sizeListShaders = len(selShaders)
for i in range(0,sizeListObjects,1):
cmds.select(selObjects[i], r=True)
rNo = random.randint(0,sizeListShaders-1)
cmds.hyperShade(assign=selShaders[rNo])
"""
| Python |
import maya.cmds as mc
selectionConnection = mc.outlinerEditor("graphEditor1OutlineEd",
query=True, selectionConnection=True)
selObj = mc.ls(selection=True, long=True)
selAttr = mc.channelBox("mainChannelBox", query=True,
selectedMainAttributes=True)
for so in selObj:
mc.selectionConnection(selectionConnection, edit=True, deselect=so)
for sa in selAttr:
mc.selectionConnection(selectionConnection, edit=True, select=so+"."+sa) | Python |
###
# tl_contribMapper
#
# The script automates the process of creating contribution mapsfor rendering or
#
# Author: Marcus Olofsson
# Maya version: 2011-x64
# Date: 2011/03/15
###
import pymel.core as pm
import maya.mel as mel
def tl_contribMapper():
objList = pm.ls(sl=True)
currentLayer = pm.editRenderLayerGlobals(q=1, crl=1)
for obj in objList:
contMap = pm.createNode('passContributionMap', ss=True)
pm.rename(contMap, obj+'_contMap')
pm.connectAttr(currentLayer+'.passContributionMap', contMap+'.owner', na=True)
mel.eval('renderLayerEditorAlterObjectsInContMap "RenderLayerTab" '+str(currentLayer)+' '+str(contMap)+' 1 ')
renderPS = pm.createNode("renderPass", ss=True)
pm.rename(renderPS, ("a_"+obj))
mel.eval('applyAttrPreset '+renderPS+' "C:/Program Files/Autodesk/Maya2011/presets/attrPresets/renderPass/beauty.mel" 1')
pm.connectAttr(currentLayer+".renderPass", renderPS+".owner", na=True)
pm.connectAttr(renderPS+'.message', contMap+'.renderPass', na=True)
| 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 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 |
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 |
#-*- 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) < 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 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 |
#-*- 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 |
'''
/* -----------------------------------------------------------------------
*
* $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 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 |
#!/usr/bin/env python
# pylint: disable-msg=C0103
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""Starter script for Fractus API."""
import gettext
import os
import sys
# If ../fractus/__init__.py exists, add ../ to Python search path, so that
# it will override what happens to be installed in /usr/(local/)lib/python...
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
os.pardir,
os.pardir))
if os.path.exists(os.path.join(possible_topdir, 'fractus', '__init__.py')):
sys.path.insert(0, possible_topdir)
gettext.install('fractus', unicode=1)
from fractus import flags
from fractus import log as logging
from fractus import version
from fractus import wsgi
from fractus import utils
logging.basicConfig()
LOG = logging.getLogger('fractus.api')
LOG.setLevel(logging.DEBUG)
FLAGS = flags.FLAGS
API_ENDPOINTS = ['osapi']
def run_app(paste_config_file):
LOG.debug(_("Using paste.deploy config at: %s"), paste_config_file)
apps = []
for api in API_ENDPOINTS:
config = wsgi.load_paste_configuration(paste_config_file, api)
if config is None:
LOG.debug(_("No paste configuration for app: %s"), api)
continue
LOG.debug(_("App Config: %(api)s\n%(config)r") % locals())
wsgi.paste_config_to_flags(config, {
"verbose": FLAGS.verbose,
"%s_host" % api: config.get('host', '0.0.0.0'),
"%s_port" % api: getattr(FLAGS, "%s_port" % api)})
LOG.info(_("Running %s API"), api)
app = wsgi.load_paste_app(paste_config_file, api)
apps.append((app, getattr(FLAGS, "%s_port" % api),
getattr(FLAGS, "%s_host" % api)))
if len(apps) == 0:
LOG.error(_("No known API applications configured in %s."),
paste_config_file)
return
# NOTE(todd): redo logging config, verbose could be set in paste config
logging.basicConfig()
server = wsgi.Server()
for app in apps:
server.start(*app)
server.wait()
if __name__ == '__main__':
FLAGS(sys.argv)
LOG.audit(_("Starting fractus-api node (version %s)"),
version.version_string())
conf = utils.config_file('fractus-api.conf')
if conf:
run_app(conf)
else:
LOG.error(_("No paste configuration found for: %s"), 'fractus-api.conf')
| Python |
#!/usr/bin/env python
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""Starter script for Fractus Agent."""
import eventlet
eventlet.monkey_patch()
import gettext
import os
import sys
# If ../fractus/__init__.py exists, add ../ to Python search path, so that
# it will override what happens to be installed in /usr/(local/)lib/python...
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
os.pardir,
os.pardir))
if os.path.exists(os.path.join(possible_topdir, 'fractus', '__init__.py')):
sys.path.insert(0, possible_topdir)
gettext.install('fractus', unicode=1)
from fractus import service
from fractus import utils
if __name__ == '__main__':
utils.default_flagfile()
service.serve()
service.wait()
| Python |
#!/usr/bin/env python
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""Starter script for Fractus Agent."""
import eventlet
eventlet.monkey_patch()
import gettext
import os
import sys
# If ../fractus/__init__.py exists, add ../ to Python search path, so that
# it will override what happens to be installed in /usr/(local/)lib/python...
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
os.pardir,
os.pardir))
if os.path.exists(os.path.join(possible_topdir, 'fractus', '__init__.py')):
sys.path.insert(0, possible_topdir)
gettext.install('fractus', unicode=1)
from fractus import service
from fractus import utils
if __name__ == '__main__':
utils.default_flagfile()
service.serve()
service.wait()
| Python |
#!/usr/bin/env python
# pylint: disable-msg=C0103
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""Starter script for Fractus API."""
import gettext
import os
import sys
# If ../fractus/__init__.py exists, add ../ to Python search path, so that
# it will override what happens to be installed in /usr/(local/)lib/python...
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
os.pardir,
os.pardir))
if os.path.exists(os.path.join(possible_topdir, 'fractus', '__init__.py')):
sys.path.insert(0, possible_topdir)
gettext.install('fractus', unicode=1)
from fractus import flags
from fractus import log as logging
from fractus import version
from fractus import wsgi
from fractus import utils
logging.basicConfig()
LOG = logging.getLogger('fractus.api')
LOG.setLevel(logging.DEBUG)
FLAGS = flags.FLAGS
API_ENDPOINTS = ['osapi']
def run_app(paste_config_file):
LOG.debug(_("Using paste.deploy config at: %s"), paste_config_file)
apps = []
for api in API_ENDPOINTS:
config = wsgi.load_paste_configuration(paste_config_file, api)
if config is None:
LOG.debug(_("No paste configuration for app: %s"), api)
continue
LOG.debug(_("App Config: %(api)s\n%(config)r") % locals())
wsgi.paste_config_to_flags(config, {
"verbose": FLAGS.verbose,
"%s_host" % api: config.get('host', '0.0.0.0'),
"%s_port" % api: getattr(FLAGS, "%s_port" % api)})
LOG.info(_("Running %s API"), api)
app = wsgi.load_paste_app(paste_config_file, api)
apps.append((app, getattr(FLAGS, "%s_port" % api),
getattr(FLAGS, "%s_host" % api)))
if len(apps) == 0:
LOG.error(_("No known API applications configured in %s."),
paste_config_file)
return
# NOTE(todd): redo logging config, verbose could be set in paste config
logging.basicConfig()
server = wsgi.Server()
for app in apps:
server.start(*app)
server.wait()
if __name__ == '__main__':
FLAGS(sys.argv)
LOG.audit(_("Starting fractus-api node (version %s)"),
version.version_string())
conf = utils.config_file('fractus-api.conf')
if conf:
run_app(conf)
else:
LOG.error(_("No paste configuration found for: %s"), 'fractus-api.conf')
| Python |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
# Interactive shell based on Django:
#
# Copyright (c) 2005, the Lawrence Journal-World
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. 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.
#
# 3. Neither the name of Django 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.
"""
CLI interface for fractus management.
"""
import datetime
import gettext
import os
import re
import sys
import time
import IPy
# If ../nova/__init__.py exists, add ../ to Python search path, so that
# it will override what happens to be installed in /usr/(local/)lib/python...
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
os.pardir,
os.pardir))
if os.path.exists(os.path.join(possible_topdir, 'fractus', '__init__.py')):
sys.path.insert(0, possible_topdir)
gettext.install('fractus', unicode=1)
from fractus import context
from fractus import crypto
from fractus import db
from fractus import exception
from fractus import flags
from fractus import log as logging
from fractus import rpc
from fractus import utils
from fractus.auth import manager
from fractus.db import migration
logging.basicConfig()
FLAGS = flags.FLAGS
"""
flags.DECLARE('fixed_range', 'nova.network.manager')
flags.DECLARE('num_networks', 'nova.network.manager')
flags.DECLARE('network_size', 'nova.network.manager')
flags.DECLARE('vlan_start', 'nova.network.manager')
flags.DECLARE('vpn_start', 'nova.network.manager')
flags.DECLARE('fixed_range_v6', 'nova.network.manager')
"""
def param2id(object_id):
"""Helper function to convert various id types to internal id.
args: [object_id], e.g. 'vol-0000000a' or 'volume-0000000a' or '10'
"""
if '-' in object_id:
return ec2_id_to_id(object_id)
else:
return int(object_id)
class VpnCommands(object):
"""Class for managing VPNs."""
def __init__(self):
self.manager = manager.AuthManager()
self.pipe = pipelib.CloudPipe()
def list(self, project=None):
"""Print a listing of the VPN data for one or all projects.
args: [project=all]"""
print "%-12s\t" % 'project',
print "%-20s\t" % 'ip:port',
print "%-20s\t" % 'private_ip',
print "%s" % 'state'
if project:
projects = [self.manager.get_project(project)]
else:
projects = self.manager.get_projects()
# NOTE(vish): This hits the database a lot. We could optimize
# by getting all networks in one query and all vpns
# in aother query, then doing lookups by project
for project in projects:
print "%-12s\t" % project.name,
ipport = "%s:%s" % (project.vpn_ip, project.vpn_port)
print "%-20s\t" % ipport,
ctxt = context.get_admin_context()
vpn = db.instance_get_project_vpn(ctxt, project.id)
if vpn:
address = None
state = 'down'
if vpn.get('fixed_ip', None):
address = vpn['fixed_ip']['address']
if project.vpn_ip and utils.vpn_ping(project.vpn_ip,
project.vpn_port):
state = 'up'
print address,
print vpn['host'],
print vpn['ec2_id'],
print vpn['state_description'],
print state
else:
print None
def spawn(self):
"""Run all VPNs."""
for p in reversed(self.manager.get_projects()):
if not self._vpn_for(p.id):
print 'spawning %s' % p.id
self.pipe.launch_vpn_instance(p.id)
time.sleep(10)
def run(self, project_id):
"""Start the VPN for a given project."""
self.pipe.launch_vpn_instance(project_id)
def change(self, project_id, ip, port):
"""Change the ip and port for a vpn.
args: project, ip, port"""
project = self.manager.get_project(project_id)
if not project:
print 'No project %s' % (project_id)
return
admin = context.get_admin_context()
network_ref = db.project_get_network(admin, project_id)
db.network_update(admin,
network_ref['id'],
{'vpn_public_address': ip,
'vpn_public_port': int(port)})
class ShellCommands(object):
def bpython(self):
"""Runs a bpython shell.
Falls back to Ipython/python shell if unavailable"""
self.run('bpython')
def ipython(self):
"""Runs an Ipython shell.
Falls back to Python shell if unavailable"""
self.run('ipython')
def python(self):
"""Runs a python shell.
Falls back to Python shell if unavailable"""
self.run('python')
def run(self, shell=None):
"""Runs a Python interactive interpreter.
args: [shell=bpython]"""
if not shell:
shell = 'bpython'
if shell == 'bpython':
try:
import bpython
bpython.embed()
except ImportError:
shell = 'ipython'
if shell == 'ipython':
try:
import IPython
# Explicitly pass an empty list as arguments, because
# otherwise IPython would use sys.argv from this script.
shell = IPython.Shell.IPShell(argv=[])
shell.mainloop()
except ImportError:
shell = 'python'
if shell == 'python':
import code
try:
# Try activating rlcompleter, because it's handy.
import readline
except ImportError:
pass
else:
# We don't have to wrap the following import in a 'try',
# because we already know 'readline' was imported successfully.
import rlcompleter
readline.parse_and_bind("tab:complete")
code.interact()
def script(self, path):
"""Runs the script from the specifed path with flags set properly.
arguments: path"""
exec(compile(open(path).read(), path, 'exec'), locals(), globals())
class RoleCommands(object):
"""Class for managing roles."""
def __init__(self):
self.manager = manager.AuthManager()
def add(self, user, role, project=None):
"""adds role to user
if project is specified, adds project specific role
arguments: user, role [project]"""
self.manager.add_role(user, role, project)
def has(self, user, role, project=None):
"""checks to see if user has role
if project is specified, returns True if user has
the global role and the project role
arguments: user, role [project]"""
print self.manager.has_role(user, role, project)
def remove(self, user, role, project=None):
"""removes role from user
if project is specified, removes project specific role
arguments: user, role [project]"""
self.manager.remove_role(user, role, project)
def _db_error(caught_exception):
print caught_exception
print _("The above error may show that the database has not "
"been created.\nPlease create a database using "
"nova-manage sync db before running this command.")
exit(1)
class UserCommands(object):
"""Class for managing users."""
@staticmethod
def _print_export(user):
"""Print export variables to use with API."""
print 'export EC2_ACCESS_KEY=%s' % user.access
print 'export EC2_SECRET_KEY=%s' % user.secret
def __init__(self):
self.manager = manager.AuthManager()
def admin(self, name, access=None, secret=None):
"""creates a new admin and prints exports
arguments: name [access] [secret]"""
try:
user = self.manager.create_user(name, access, secret, True)
except exception.DBError, e:
_db_error(e)
self._print_export(user)
def create(self, name, access=None, secret=None):
"""creates a new user and prints exports
arguments: name [access] [secret]"""
try:
user = self.manager.create_user(name, access, secret, False)
except exception.DBError, e:
_db_error(e)
self._print_export(user)
def delete(self, name):
"""deletes an existing user
arguments: name"""
self.manager.delete_user(name)
def exports(self, name):
"""prints access and secrets for user in export format
arguments: name"""
user = self.manager.get_user(name)
if user:
self._print_export(user)
else:
print "User %s doesn't exist" % name
def list(self):
"""lists all users
arguments: <none>"""
for user in self.manager.get_users():
print user.name
def modify(self, name, access_key, secret_key, is_admin):
"""update a users keys & admin flag
arguments: accesskey secretkey admin
leave any field blank to ignore it, admin should be 'T', 'F', or blank
"""
if not is_admin:
is_admin = None
elif is_admin.upper()[0] == 'T':
is_admin = True
else:
is_admin = False
self.manager.modify_user(name, access_key, secret_key, is_admin)
def revoke(self, user_id, project_id=None):
"""revoke certs for a user
arguments: user_id [project_id]"""
if project_id:
crypto.revoke_certs_by_user_and_project(user_id, project_id)
else:
crypto.revoke_certs_by_user(user_id)
class ProjectCommands(object):
"""Class for managing projects."""
def __init__(self):
self.manager = manager.AuthManager()
def add(self, project_id, user_id):
"""Adds user to project
arguments: project_id user_id"""
self.manager.add_to_project(user_id, project_id)
def create(self, name, project_manager, description=None):
"""Creates a new project
arguments: name project_manager [description]"""
self.manager.create_project(name, project_manager, description)
def modify(self, name, project_manager, description=None):
"""Modifies a project
arguments: name project_manager [description]"""
self.manager.modify_project(name, project_manager, description)
def delete(self, name):
"""Deletes an existing project
arguments: name"""
self.manager.delete_project(name)
def environment(self, project_id, user_id, filename='novarc'):
"""Exports environment variables to an sourcable file
arguments: project_id user_id [filename='novarc]"""
rc = self.manager.get_environment_rc(user_id, project_id)
with open(filename, 'w') as f:
f.write(rc)
def list(self):
"""Lists all projects
arguments: <none>"""
for project in self.manager.get_projects():
print project.name
def quota(self, project_id, key=None, value=None):
"""Set or display quotas for project
arguments: project_id [key] [value]"""
ctxt = context.get_admin_context()
if key:
quo = {'project_id': project_id, key: value}
try:
db.quota_update(ctxt, project_id, quo)
except exception.NotFound:
db.quota_create(ctxt, quo)
project_quota = quota.get_quota(ctxt, project_id)
for key, value in project_quota.iteritems():
print '%s: %s' % (key, value)
def remove(self, project_id, user_id):
"""Removes user from project
arguments: project_id user_id"""
self.manager.remove_from_project(user_id, project_id)
def scrub(self, project_id):
"""Deletes data associated with project
arguments: project_id"""
ctxt = context.get_admin_context()
network_ref = db.project_get_network(ctxt, project_id)
db.network_disassociate(ctxt, network_ref['id'])
groups = db.security_group_get_by_project(ctxt, project_id)
for group in groups:
db.security_group_destroy(ctxt, group['id'])
def zipfile(self, project_id, user_id, filename='nova.zip'):
"""Exports credentials for project to a zip file
arguments: project_id user_id [filename='nova.zip]"""
try:
zip_file = self.manager.get_credentials(user_id, project_id)
with open(filename, 'w') as f:
f.write(zip_file)
except db.api.NoMoreNetworks:
print _('No more networks available. If this is a new '
'installation, you need\nto call something like this:\n\n'
' nova-manage network create 10.0.0.0/8 10 64\n\n')
except exception.ProcessExecutionError, e:
print e
print _("The above error may show that the certificate db has not "
"been created.\nPlease create a database by running a "
"nova-api server on this host.")
class FixedIpCommands(object):
"""Class for managing fixed ip."""
def list(self, host=None):
"""Lists all fixed ips (optionally by host) arguments: [host]"""
ctxt = context.get_admin_context()
if host == None:
fixed_ips = db.fixed_ip_get_all(ctxt)
else:
fixed_ips = db.fixed_ip_get_all_by_host(ctxt, host)
print "%-18s\t%-15s\t%-17s\t%-15s\t%s" % (_('network'),
_('IP address'),
_('MAC address'),
_('hostname'),
_('host'))
for fixed_ip in fixed_ips:
hostname = None
host = None
mac_address = None
if fixed_ip['instance']:
instance = fixed_ip['instance']
hostname = instance['hostname']
host = instance['host']
mac_address = instance['mac_address']
print "%-18s\t%-15s\t%-17s\t%-15s\t%s" % (
fixed_ip['network']['cidr'],
fixed_ip['address'],
mac_address, hostname, host)
class FloatingIpCommands(object):
"""Class for managing floating ip."""
def create(self, host, range):
"""Creates floating ips for host by range
arguments: host ip_range"""
for address in IPy.IP(range):
db.floating_ip_create(context.get_admin_context(),
{'address': str(address),
'host': host})
def delete(self, ip_range):
"""Deletes floating ips by range
arguments: range"""
for address in IPy.IP(ip_range):
db.floating_ip_destroy(context.get_admin_context(),
str(address))
def list(self, host=None):
"""Lists all floating ips (optionally by host)
arguments: [host]"""
ctxt = context.get_admin_context()
if host == None:
floating_ips = db.floating_ip_get_all(ctxt)
else:
floating_ips = db.floating_ip_get_all_by_host(ctxt, host)
for floating_ip in floating_ips:
instance = None
if floating_ip['fixed_ip']:
instance = floating_ip['fixed_ip']['instance']['ec2_id']
print "%s\t%s\t%s" % (floating_ip['host'],
floating_ip['address'],
instance)
class NetworkCommands(object):
"""Class for managing networks."""
def create(self, fixed_range=None, num_networks=None,
network_size=None, vlan_start=None,
vpn_start=None, fixed_range_v6=None, label='public'):
"""Creates fixed ips for host by range
arguments: [fixed_range=FLAG], [num_networks=FLAG],
[network_size=FLAG], [vlan_start=FLAG],
[vpn_start=FLAG], [fixed_range_v6=FLAG]"""
if not fixed_range:
fixed_range = FLAGS.fixed_range
if not num_networks:
num_networks = FLAGS.num_networks
if not network_size:
network_size = FLAGS.network_size
if not vlan_start:
vlan_start = FLAGS.vlan_start
if not vpn_start:
vpn_start = FLAGS.vpn_start
if not fixed_range_v6:
fixed_range_v6 = FLAGS.fixed_range_v6
net_manager = utils.import_object(FLAGS.network_manager)
net_manager.create_networks(context.get_admin_context(),
cidr=fixed_range,
num_networks=int(num_networks),
network_size=int(network_size),
vlan_start=int(vlan_start),
vpn_start=int(vpn_start),
cidr_v6=fixed_range_v6,
label=label)
def list(self):
"""List all created networks"""
print "%-18s\t%-15s\t%-15s\t%-15s" % (_('network'),
_('netmask'),
_('start address'),
'DNS')
for network in db.network_get_all(context.get_admin_context()):
print "%-18s\t%-15s\t%-15s\t%-15s" % (network.cidr,
network.netmask,
network.dhcp_start,
network.dns)
class ServiceCommands(object):
"""Enable and disable running services"""
def list(self, host=None, service=None):
"""Show a list of all running services. Filter by host & service name.
args: [host] [service]"""
ctxt = context.get_admin_context()
now = datetime.datetime.utcnow()
services = db.service_get_all(ctxt)
if host:
services = [s for s in services if s['host'] == host]
if service:
services = [s for s in services if s['binary'] == service]
for svc in services:
delta = now - (svc['updated_at'] or svc['created_at'])
alive = (delta.seconds <= 15)
art = (alive and ":-)") or "XXX"
active = 'enabled'
if svc['disabled']:
active = 'disabled'
print "%-10s %-10s %-8s %s %s" % (svc['host'], svc['binary'],
active, art,
svc['updated_at'])
def enable(self, host, service):
"""Enable scheduling for a service
args: host service"""
ctxt = context.get_admin_context()
svc = db.service_get_by_args(ctxt, host, service)
if not svc:
print "Unable to find service"
return
db.service_update(ctxt, svc['id'], {'disabled': False})
def disable(self, host, service):
"""Disable scheduling for a service
args: host service"""
ctxt = context.get_admin_context()
svc = db.service_get_by_args(ctxt, host, service)
if not svc:
print "Unable to find service"
return
db.service_update(ctxt, svc['id'], {'disabled': True})
class LogCommands(object):
def request(self, request_id, logfile='/var/log/nova.log'):
"""Show all fields in the log for the given request. Assumes you
haven't changed the log format too much.
ARGS: request_id [logfile]"""
lines = utils.execute("cat %s | grep '\[%s '" % (logfile, request_id))
print re.sub('#012', "\n", "\n".join(lines))
class DbCommands(object):
"""Class for managing the database."""
def __init__(self):
pass
def sync(self, version=None):
"""Sync the database up to the most recent version."""
return migration.db_sync(version)
def version(self):
"""Print the current database version."""
print migration.db_version()
class VolumeCommands(object):
"""Methods for dealing with a cloud in an odd state"""
def delete(self, volume_id):
"""Delete a volume, bypassing the check that it
must be available.
args: volume_id_id"""
ctxt = context.get_admin_context()
volume = db.volume_get(ctxt, param2id(volume_id))
host = volume['host']
if not host:
print "Volume not yet assigned to host."
print "Deleting volume from database and skipping rpc."
db.volume_destroy(ctxt, param2id(volume_id))
return
if volume['status'] == 'in-use':
print "Volume is in-use."
print "Detach volume from instance and then try again."
return
rpc.cast(ctxt,
db.queue_get_for(ctxt, FLAGS.volume_topic, host),
{"method": "delete_volume",
"args": {"volume_id": volume['id']}})
def reattach(self, volume_id):
"""Re-attach a volume that has previously been attached
to an instance. Typically called after a compute host
has been rebooted.
args: volume_id_id"""
ctxt = context.get_admin_context()
volume = db.volume_get(ctxt, param2id(volume_id))
if not volume['instance_id']:
print "volume is not attached to an instance"
return
instance = db.instance_get(ctxt, volume['instance_id'])
host = instance['host']
rpc.cast(ctxt,
db.queue_get_for(ctxt, FLAGS.compute_topic, host),
{"method": "attach_volume",
"args": {"instance_id": instance['id'],
"volume_id": volume['id'],
"mountpoint": volume['mountpoint']}})
CATEGORIES = [
('user', UserCommands),
('project', ProjectCommands),
('role', RoleCommands),
('shell', ShellCommands),
('vpn', VpnCommands),
('fixed', FixedIpCommands),
('floating', FloatingIpCommands),
('network', NetworkCommands),
('service', ServiceCommands),
('log', LogCommands),
('db', DbCommands),
('volume', VolumeCommands)]
def lazy_match(name, key_value_tuples):
"""Finds all objects that have a key that case insensitively contains
[name] key_value_tuples is a list of tuples of the form (key, value)
returns a list of tuples of the form (key, value)"""
result = []
for (k, v) in key_value_tuples:
if k.lower().find(name.lower()) == 0:
result.append((k, v))
if len(result) == 0:
print "%s does not match any options:" % name
for k, _v in key_value_tuples:
print "\t%s" % k
sys.exit(2)
if len(result) > 1:
print "%s matched multiple options:" % name
for k, _v in result:
print "\t%s" % k
sys.exit(2)
return result
def methods_of(obj):
"""Get all callable methods of an object that don't start with underscore
returns a list of tuples of the form (method_name, method)"""
result = []
for i in dir(obj):
if callable(getattr(obj, i)) and not i.startswith('_'):
result.append((i, getattr(obj, i)))
return result
def main():
"""Parse options and call the appropriate class/method."""
utils.default_flagfile()
argv = FLAGS(sys.argv)
script_name = argv.pop(0)
if len(argv) < 1:
print script_name + " category action [<args>]"
print "Available categories:"
for k, _ in CATEGORIES:
print "\t%s" % k
sys.exit(2)
category = argv.pop(0)
matches = lazy_match(category, CATEGORIES)
# instantiate the command group object
category, fn = matches[0]
command_object = fn()
actions = methods_of(command_object)
if len(argv) < 1:
print script_name + " category action [<args>]"
print "Available actions for %s category:" % category
for k, _v in actions:
print "\t%s" % k
sys.exit(2)
action = argv.pop(0)
matches = lazy_match(action, actions)
action, fn = matches[0]
# call the action with the remaining arguments
try:
fn(*argv)
sys.exit(0)
except TypeError:
print "Possible wrong number of arguments supplied"
print "%s %s: %s" % (category, action, fn.__doc__)
raise
if __name__ == '__main__':
main()
| Python |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""
Fractus base exception handling, including decorator for re-raising
Fractus-type exceptions. SHOULD include dedicated exception logging.
"""
from fractus import log as logging
LOG = logging.getLogger('fractus.exception')
class ProcessExecutionError(IOError):
def __init__(self, stdout=None, stderr=None, exit_code=None, cmd=None,
description=None):
if description is None:
description = _("Unexpected error while running command.")
if exit_code is None:
exit_code = '-'
message = _("%(description)s\nCommand: %(cmd)s\n"
"Exit code: %(exit_code)s\nStdout: %(stdout)r\n"
"Stderr: %(stderr)r") % locals()
IOError.__init__(self, message)
class Error(Exception):
def __init__(self, message=None):
super(Error, self).__init__(message)
class ApiError(Error):
def __init__(self, message='Unknown', code='Unknown'):
self.message = message
self.code = code
super(ApiError, self).__init__('%s: %s' % (code, message))
class NotFound(Error):
pass
class InstanceNotFound(NotFound):
def __init__(self, message, instance_id):
self.instance_id = instance_id
super(InstanceNotFound, self).__init__(message)
class VolumeNotFound(NotFound):
def __init__(self, message, volume_id):
self.volume_id = volume_id
super(VolumeNotFound, self).__init__(message)
class Duplicate(Error):
pass
class NotAuthorized(Error):
pass
class NotEmpty(Error):
pass
class Invalid(Error):
pass
class InvalidInputException(Error):
pass
class TimeoutException(Error):
pass
class DBError(Error):
"""Wraps an implementation specific exception"""
def __init__(self, inner_exception):
self.inner_exception = inner_exception
super(DBError, self).__init__(str(inner_exception))
def wrap_db_error(f):
def _wrap(*args, **kwargs):
try:
return f(*args, **kwargs)
except Exception, e:
LOG.exception(_('DB exception wrapped'))
raise DBError(e)
return _wrap
_wrap.func_name = f.func_name
def wrap_exception(f):
def _wrap(*args, **kw):
try:
return f(*args, **kw)
except Exception, e:
if not isinstance(e, Error):
#exc_type, exc_value, exc_traceback = sys.exc_info()
LOG.exception(_('Uncaught exception'))
#logging.error(traceback.extract_stack(exc_traceback))
raise Error(str(e))
raise
_wrap.func_name = f.func_name
return _wrap
| Python |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""Based a bit on the carrot.backeds.queue backend... but a lot better."""
import Queue as queue
from carrot.backends import base
from eventlet import greenthread
from fractus import log as logging
LOG = logging.getLogger("fractus.fakerabbit")
EXCHANGES = {}
QUEUES = {}
class Message(base.BaseMessage):
pass
class Exchange(object):
def __init__(self, name, exchange_type):
self.name = name
self.exchange_type = exchange_type
self._queue = queue.Queue()
self._routes = {}
def publish(self, message, routing_key=None):
nm = self.name
LOG.debug(_('(%(nm)s) publish (key: %(routing_key)s)'
' %(message)s') % locals())
routing_key = routing_key.split('.')[0]
if routing_key in self._routes:
for f in self._routes[routing_key]:
LOG.debug(_('Publishing to route %s'), f)
f(message, routing_key=routing_key)
def bind(self, callback, routing_key):
self._routes.setdefault(routing_key, [])
self._routes[routing_key].append(callback)
class Queue(object):
def __init__(self, name):
self.name = name
self._queue = queue.Queue()
def __repr__(self):
return '<Queue: %s>' % self.name
def push(self, message, routing_key=None):
self._queue.put(message)
def size(self):
return self._queue.qsize()
def pop(self):
return self._queue.get()
class Backend(base.BaseBackend):
def queue_declare(self, queue, **kwargs):
global QUEUES
if queue not in QUEUES:
LOG.debug(_('Declaring queue %s'), queue)
QUEUES[queue] = Queue(queue)
def exchange_declare(self, exchange, type, *args, **kwargs):
global EXCHANGES
if exchange not in EXCHANGES:
LOG.debug(_('Declaring exchange %s'), exchange)
EXCHANGES[exchange] = Exchange(exchange, type)
def queue_bind(self, queue, exchange, routing_key, **kwargs):
global EXCHANGES
global QUEUES
LOG.debug(_('Binding %(queue)s to %(exchange)s with'
' key %(routing_key)s') % locals())
EXCHANGES[exchange].bind(QUEUES[queue].push, routing_key)
def declare_consumer(self, queue, callback, *args, **kwargs):
self.current_queue = queue
self.current_callback = callback
def consume(self, limit=None):
while True:
item = self.get(self.current_queue)
if item:
self.current_callback(item)
raise StopIteration()
greenthread.sleep(0)
def get(self, queue, no_ack=False):
global QUEUES
if not queue in QUEUES or not QUEUES[queue].size():
return None
(message_data, content_type, content_encoding) = QUEUES[queue].pop()
message = Message(backend=self, body=message_data,
content_type=content_type,
content_encoding=content_encoding)
message.result = True
LOG.debug(_('Getting from %(queue)s: %(message)s') % locals())
return message
def prepare_message(self, message_data, delivery_mode,
content_type, content_encoding, **kwargs):
"""Prepare message for sending."""
return (message_data, content_type, content_encoding)
def publish(self, message, exchange, routing_key, **kwargs):
global EXCHANGES
if exchange in EXCHANGES:
EXCHANGES[exchange].publish(message, routing_key=routing_key)
def reset_all():
global EXCHANGES
global QUEUES
EXCHANGES = {}
QUEUES = {}
| Python |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""
RequestContext: context for requests that persist through all of fractus.
"""
import datetime
import random
from fractus import exception
from fractus import utils
class RequestContext(object):
def __init__(self, user, project, is_admin=None, read_deleted=False,
remote_address=None, timestamp=None, request_id=None):
if hasattr(user, 'id'):
self._user = user
self.user_id = user.id
else:
self._user = None
self.user_id = user
if hasattr(project, 'id'):
self._project = project
self.project_id = project.id
else:
self._project = None
self.project_id = project
if is_admin is None:
if self.user_id and self.user:
self.is_admin = self.user.is_admin()
else:
self.is_admin = False
else:
self.is_admin = is_admin
self.read_deleted = read_deleted
self.remote_address = remote_address
if not timestamp:
timestamp = utils.utcnow()
if isinstance(timestamp, str) or isinstance(timestamp, unicode):
timestamp = utils.parse_isotime(timestamp)
self.timestamp = timestamp
if not request_id:
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-'
request_id = ''.join([random.choice(chars) for x in xrange(20)])
self.request_id = request_id
@property
def user(self):
# NOTE(vish): Delay import of manager, so that we can import this
# file from manager.
from fractus.auth import manager
if not self._user:
try:
self._user = manager.AuthManager().get_user(self.user_id)
except exception.NotFound:
pass
return self._user
@property
def project(self):
# NOTE(vish): Delay import of manager, so that we can import this
# file from manager.
from fractus.auth import manager
if not self._project:
try:
auth_manager = manager.AuthManager()
self._project = auth_manager.get_project(self.project_id)
except exception.NotFound:
pass
return self._project
def to_dict(self):
return {'user': self.user_id,
'project': self.project_id,
'is_admin': self.is_admin,
'read_deleted': self.read_deleted,
'remote_address': self.remote_address,
'timestamp': utils.isotime(self.timestamp),
'request_id': self.request_id}
@classmethod
def from_dict(cls, values):
return cls(**values)
def elevated(self, read_deleted=False):
"""Return a version of this context with admin flag set."""
return RequestContext(self.user_id,
self.project_id,
True,
read_deleted,
self.remote_address,
self.timestamp,
self.request_id)
def get_admin_context(read_deleted=False):
return RequestContext(None, None, True, read_deleted)
| Python |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""Public HTTP interface that allows services to self-register.
The general flow of a request is:
- Request is parsed into WSGI bits.
- Some middleware checks authentication.
- Routing takes place based on the URL to find a controller.
(/controller/method)
- Parameters are parsed from the request and passed to a method on the
controller as keyword arguments.
- Optionally 'json' is decoded to provide all the parameters.
- Actual work is done and a result is returned.
- That result is turned into json and returned.
"""
import inspect
import urllib
import routes
import webob
from fractus import context
from fractus import flags
from fractus import utils
from fractus import wsgi
ROUTES = {}
def register_service(path, handle):
ROUTES[path] = handle
class Router(wsgi.Router):
def __init__(self, mapper=None):
if mapper is None:
mapper = routes.Mapper()
self._load_registered_routes(mapper)
super(Router, self).__init__(mapper=mapper)
def _load_registered_routes(self, mapper):
for route in ROUTES:
mapper.connect('/%s/{action}' % route,
controller=ServiceWrapper(ROUTES[route]))
class DelegatedAuthMiddleware(wsgi.Middleware):
def process_request(self, request):
os_user = request.headers['X-OpenStack-User']
os_project = request.headers['X-OpenStack-Project']
context_ref = context.RequestContext(user=os_user, project=os_project)
request.environ['openstack.context'] = context_ref
class JsonParamsMiddleware(wsgi.Middleware):
def process_request(self, request):
if 'json' not in request.params:
return
params_json = request.params['json']
params_parsed = utils.loads(params_json)
params = {}
for k, v in params_parsed.iteritems():
if k in ('self', 'context'):
continue
if k.startswith('_'):
continue
params[k] = v
request.environ['openstack.params'] = params
class PostParamsMiddleware(wsgi.Middleware):
def process_request(self, request):
params_parsed = request.params
params = {}
for k, v in params_parsed.iteritems():
if k in ('self', 'context'):
continue
if k.startswith('_'):
continue
params[k] = v
request.environ['openstack.params'] = params
class Reflection(object):
"""Reflection methods to list available methods."""
def __init__(self):
self._methods = {}
self._controllers = {}
def _gather_methods(self):
methods = {}
controllers = {}
for route, handler in ROUTES.iteritems():
controllers[route] = handler.__doc__.split('\n')[0]
for k in dir(handler):
if k.startswith('_'):
continue
f = getattr(handler, k)
if not callable(f):
continue
# bunch of ugly formatting stuff
argspec = inspect.getargspec(f)
args = [x for x in argspec[0]
if x != 'self' and x != 'context']
defaults = argspec[3] and argspec[3] or []
args_r = list(reversed(args))
defaults_r = list(reversed(defaults))
args_out = []
while args_r:
if defaults_r:
args_out.append((args_r.pop(0),
repr(defaults_r.pop(0))))
else:
args_out.append((str(args_r.pop(0)),))
# if the method accepts keywords
if argspec[2]:
args_out.insert(0, ('**%s' % argspec[2],))
if f.__doc__:
short_doc = f.__doc__.split('\n')[0]
doc = f.__doc__
else:
short_doc = doc = _('not available')
methods['/%s/%s' % (route, k)] = {
'short_doc': short_doc,
'doc': doc,
'name': k,
'args': list(reversed(args_out))}
self._methods = methods
self._controllers = controllers
def get_controllers(self, context):
"""List available controllers."""
if not self._controllers:
self._gather_methods()
return self._controllers
def get_methods(self, context):
"""List available methods."""
if not self._methods:
self._gather_methods()
method_list = self._methods.keys()
method_list.sort()
methods = {}
for k in method_list:
methods[k] = self._methods[k]['short_doc']
return methods
def get_method_info(self, context, method):
"""Get detailed information about a method."""
if not self._methods:
self._gather_methods()
return self._methods[method]
class ServiceWrapper(wsgi.Controller):
def __init__(self, service_handle):
self.service_handle = service_handle
@webob.dec.wsgify
def __call__(self, req):
arg_dict = req.environ['wsgiorg.routing_args'][1]
action = arg_dict['action']
del arg_dict['action']
context = req.environ['openstack.context']
# allow middleware up the stack to override the params
params = {}
if 'openstack.params' in req.environ:
params = req.environ['openstack.params']
# TODO(termie): do some basic normalization on methods
method = getattr(self.service_handle, action)
# NOTE(vish): make sure we have no unicode keys for py2.6.
params = dict([(str(k), v) for (k, v) in params.iteritems()])
result = method(context, **params)
if type(result) is dict or type(result) is list:
return self._serialize(result, req)
else:
return result
class Proxy(object):
"""Pretend a Direct API endpoint is an object."""
def __init__(self, app, prefix=None):
self.app = app
self.prefix = prefix
def __do_request(self, path, context, **kwargs):
req = webob.Request.blank(path)
req.method = 'POST'
req.body = urllib.urlencode({'json': utils.dumps(kwargs)})
req.environ['openstack.context'] = context
resp = req.get_response(self.app)
try:
return utils.loads(resp.body)
except Exception:
return resp.body
def __getattr__(self, key):
if self.prefix is None:
return self.__class__(self.app, prefix=key)
def _wrapper(context, **kwargs):
return self.__do_request('/%s/%s' % (self.prefix, key),
context,
**kwargs)
_wrapper.func_name = key
return _wrapper
| Python |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""No-op __init__ for directory full of api goodies."""
| Python |
# Copyright 2010 OpenStack LLC.
# 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 webob.dec
import webob.exc
from fractus import wsgi
class Fault(webob.exc.HTTPException):
"""An RS API fault response."""
_fault_names = {
400: "badRequest",
401: "unauthorized",
403: "resizeNotAllowed",
404: "itemNotFound",
405: "badMethod",
409: "inProgress",
413: "overLimit",
415: "badMediaType",
501: "notImplemented",
503: "serviceUnavailable"}
def __init__(self, exception):
"""Create a Fault for the given webob.exc.exception."""
self.wrapped_exc = exception
@webob.dec.wsgify
def __call__(self, req):
"""Generate a WSGI response based on the exception passed to ctor."""
# Replace the body with fault details.
code = self.wrapped_exc.status_int
fault_name = self._fault_names.get(code, "computeFault")
fault_data = {
fault_name: {
'code': code,
'message': self.wrapped_exc.explanation}}
if code == 413:
retry = self.wrapped_exc.headers['Retry-After']
fault_data[fault_name]['retryAfter'] = retry
# 'code' is an attribute on the fault tag itself
metadata = {'application/xml': {'attributes': {fault_name: 'code'}}}
serializer = wsgi.Serializer(req.environ, metadata)
self.wrapped_exc.body = serializer.to_content_type(fault_data)
return self.wrapped_exc
| Python |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""
WSGI middleware for Fractus API controllers.
"""
import routes
import webob.dec
import webob.exc
from fractus import flags
from fractus import log as logging
from fractus import wsgi
from fractus.api.fractus import faults
from fractus.api.fractus import backup_schedules
from fractus.api.fractus import consoles
from fractus.api.fractus import flavors
from fractus.api.fractus import images
from fractus.api.fractus import servers
from fractus.api.fractus import shared_ip_groups
LOG = logging.getLogger('fractus.api.fractus')
FLAGS = flags.FLAGS
flags.DEFINE_bool('allow_admin_api',
False,
'When True, this API service will accept admin operations.')
class FaultWrapper(wsgi.Middleware):
"""Calls down the middleware stack, making exceptions into faults."""
@webob.dec.wsgify
def __call__(self, req):
try:
return req.get_response(self.application)
except Exception as ex:
LOG.exception(_("Caught error: %s"), unicode(ex))
exc = webob.exc.HTTPInternalServerError(explanation=unicode(ex))
return faults.Fault(exc)
class APIRouter(wsgi.Router):
"""
Routes requests on the Fractus API to the appropriate controller
and method.
"""
@classmethod
def factory(cls, global_config, **local_config):
"""Simple paste factory, :class:`fractus.wsgi.Router` doesn't have one"""
return cls()
def __init__(self):
mapper = routes.Mapper()
server_members = {'action': 'POST'}
if FLAGS.allow_admin_api:
LOG.debug(_("Including admin operations in API."))
server_members['pause'] = 'POST'
server_members['unpause'] = 'POST'
server_members["diagnostics"] = "GET"
server_members["actions"] = "GET"
server_members['suspend'] = 'POST'
server_members['resume'] = 'POST'
mapper.resource("server", "servers", controller=servers.Controller(),
collection={'detail': 'GET'},
member=server_members)
mapper.resource("backup_schedule", "backup_schedule",
controller=backup_schedules.Controller(),
parent_resource=dict(member_name='server',
collection_name='servers'))
mapper.resource("console", "consoles",
controller=consoles.Controller(),
parent_resource=dict(member_name='server',
collection_name='servers'))
mapper.resource("image", "images", controller=images.Controller(),
collection={'detail': 'GET'})
mapper.resource("flavor", "flavors", controller=flavors.Controller(),
collection={'detail': 'GET'})
mapper.resource("shared_ip_group", "shared_ip_groups",
collection={'detail': 'GET'},
controller=shared_ip_groups.Controller())
super(APIRouter, self).__init__(mapper)
class Versions(wsgi.Application):
@webob.dec.wsgify
def __call__(self, req):
"""Respond to a request for all Fractus API versions."""
response = {
"versions": [
dict(status="CURRENT", id="v1.0")]}
metadata = {
"application/xml": {
"attributes": dict(version=["status", "id"])}}
return wsgi.Serializer(req.environ, metadata).to_content_type(response)
| Python |
# Copyright 2011 Fractus Labs (www.fractus-labs.com)
# 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.
"""
System-level utilities and helper functions.
"""
import datetime
import json
import os
import random
import socket
import struct
import sys
import time
from xml.sax import saxutils
import re
import netaddr
from eventlet import event
from eventlet import greenthread
from eventlet.green import subprocess
from fractus import exception
from fractus.exception import ProcessExecutionError
from fractus import log as logging
from fractus import flags
LOG = logging.getLogger("fractus.utils")
TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
FLAGS = flags.FLAGS
def import_class(import_str):
"""Returns a class from a string including module and class"""
mod_str, _sep, class_str = import_str.rpartition('.')
try:
__import__(mod_str)
return getattr(sys.modules[mod_str], class_str)
except (ImportError, ValueError, AttributeError), exc:
logging.debug(_('Inner Exception: %s'), exc)
raise exception.NotFound(_('Class %s cannot be found') % class_str)
def import_object(import_str):
"""Returns an object including a module or module and class"""
try:
__import__(import_str)
return sys.modules[import_str]
except ImportError:
cls = import_class(import_str)
return cls()
def vpn_ping(address, port, timeout=0.05, session_id=None):
"""Sends a vpn negotiation packet and returns the server session.
Returns False on a failure. Basic packet structure is below.
Client packet (14 bytes)::
0 1 8 9 13
+-+--------+-----+
|x| cli_id |?????|
+-+--------+-----+
x = packet identifier 0x38
cli_id = 64 bit identifier
? = unknown, probably flags/padding
Server packet (26 bytes)::
0 1 8 9 13 14 21 2225
+-+--------+-----+--------+----+
|x| srv_id |?????| cli_id |????|
+-+--------+-----+--------+----+
x = packet identifier 0x40
cli_id = 64 bit identifier
? = unknown, probably flags/padding
bit 9 was 1 and the rest were 0 in testing
"""
if session_id is None:
session_id = random.randint(0, 0xffffffffffffffff)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
data = struct.pack("!BQxxxxxx", 0x38, session_id)
sock.sendto(data, (address, port))
sock.settimeout(timeout)
try:
received = sock.recv(2048)
except socket.timeout:
return False
finally:
sock.close()
fmt = "!BQxxxxxQxxxx"
if len(received) != struct.calcsize(fmt):
print struct.calcsize(fmt)
return False
(identifier, server_sess, client_sess) = struct.unpack(fmt, received)
if identifier == 0x40 and client_sess == session_id:
return server_sess
def fetchfile(url, target):
LOG.debug(_("Fetching %s") % url)
# c = pycurl.Curl()
# fp = open(target, "wb")
# c.setopt(c.URL, url)
# c.setopt(c.WRITEDATA, fp)
# c.perform()
# c.close()
# fp.close()
execute("curl --fail %s -o %s" % (url, target))
def execute(cmd, process_input=None, addl_env=None, check_exit_code=True):
LOG.debug(_("Running cmd (subprocess): %s"), cmd)
env = os.environ.copy()
if addl_env:
env.update(addl_env)
obj = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
result = None
if process_input != None:
result = obj.communicate(process_input)
else:
result = obj.communicate()
obj.stdin.close()
if obj.returncode:
LOG.debug(_("Result was %s") % obj.returncode)
if check_exit_code and obj.returncode != 0:
(stdout, stderr) = result
raise ProcessExecutionError(exit_code=obj.returncode,
stdout=stdout,
stderr=stderr,
cmd=cmd)
# NOTE(termie): this appears to be necessary to let the subprocess call
# clean something up in between calls, without it two
# execute calls in a row hangs the second one
greenthread.sleep(0)
return result
def ssh_execute(ssh, cmd, process_input=None,
addl_env=None, check_exit_code=True):
LOG.debug(_("Running cmd (SSH): %s"), cmd)
if addl_env:
raise exception.Error("Environment not supported over SSH")
if process_input:
# This is (probably) fixable if we need it...
raise exception.Error("process_input not supported over SSH")
stdin_stream, stdout_stream, stderr_stream = ssh.exec_command(cmd)
channel = stdout_stream.channel
#stdin.write('process_input would go here')
#stdin.flush()
# NOTE(justinsb): This seems suspicious...
# ...other SSH clients have buffering issues with this approach
stdout = stdout_stream.read()
stderr = stderr_stream.read()
stdin_stream.close()
exit_status = channel.recv_exit_status()
# exit_status == -1 if no exit code was returned
if exit_status != -1:
LOG.debug(_("Result was %s") % exit_status)
if check_exit_code and exit_status != 0:
raise exception.ProcessExecutionError(exit_code=exit_status,
stdout=stdout,
stderr=stderr,
cmd=cmd)
return (stdout, stderr)
def abspath(s):
return os.path.join(os.path.dirname(__file__), s)
def fractusdir():
import fractus
return os.path.abspath(fractus.__file__).split('fractus/__init__.pyc')[0]
def default_flagfile(filename='fractus.conf'):
for arg in sys.argv:
if arg.find('flagfile') != -1:
break
else:
if not os.path.isabs(filename):
# turn relative filename into an absolute path
filename = config_file(filename)
if os.path.exists(filename):
flagfile = ['--flagfile=%s' % filename]
sys.argv = sys.argv[:1] + flagfile + sys.argv[1:]
def debug(arg):
LOG.debug(_('debug in callback: %s'), arg)
return arg
def runthis(prompt, cmd, check_exit_code=True):
LOG.debug(_("Running %s"), (cmd))
rv, err = execute(cmd, check_exit_code=check_exit_code)
def generate_uid(topic, size=8):
characters = '01234567890abcdefghijklmnopqrstuvwxyz'
choices = [random.choice(characters) for x in xrange(size)]
return '%s-%s' % (topic, ''.join(choices))
def generate_mac():
mac = [0x02, 0x16, 0x3e,
random.randint(0x00, 0x7f),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff)]
return ':'.join(map(lambda x: "%02x" % x, mac))
def last_octet(address):
return int(address.split(".")[-1])
def get_my_linklocal(interface):
try:
if_str = execute("ip -f inet6 -o addr show %s" % interface)
condition = "\s+inet6\s+([0-9a-f:]+)/\d+\s+scope\s+link"
links = [re.search(condition, x) for x in if_str[0].split('\n')]
address = [w.group(1) for w in links if w is not None]
if address[0] is not None:
return address[0]
else:
raise exception.Error(_("Link Local address is not found.:%s")
% if_str)
except Exception as ex:
raise exception.Error(_("Couldn't get Link Local IP of %(interface)s"
" :%(ex)s") % locals())
def to_global_ipv6(prefix, mac):
mac64 = netaddr.EUI(mac).eui64().words
int_addr = int(''.join(['%02x' % i for i in mac64]), 16)
mac64_addr = netaddr.IPAddress(int_addr)
maskIP = netaddr.IPNetwork(prefix).ip
return (mac64_addr ^ netaddr.IPAddress('::0200:0:0:0') | maskIP).format()
def to_mac(ipv6_address):
address = netaddr.IPAddress(ipv6_address)
mask1 = netaddr.IPAddress("::ffff:ffff:ffff:ffff")
mask2 = netaddr.IPAddress("::0200:0:0:0")
mac64 = netaddr.EUI(int(address & mask1 ^ mask2)).words
return ":".join(["%02x" % i for i in mac64[0:3] + mac64[5:8]])
def utcnow():
"""Overridable version of datetime.datetime.utcnow."""
if utcnow.override_time:
return utcnow.override_time
return datetime.datetime.utcnow()
utcnow.override_time = None
def utcnow_ts():
"""Timestamp version of our utcnow function."""
return time.mktime(utcnow().timetuple())
def set_time_override(override_time=datetime.datetime.utcnow()):
"""Override utils.utcnow to return a constant time."""
utcnow.override_time = override_time
def advance_time_delta(timedelta):
"""Advance overriden time using a datetime.timedelta."""
assert(not utcnow.override_time is None)
utcnow.override_time += timedelta
def advance_time_seconds(seconds):
"""Advance overriden time by seconds."""
advance_time_delta(datetime.timedelta(0, seconds))
def clear_time_override():
"""Remove the overridden time."""
utcnow.override_time = None
def isotime(at=None):
"""Returns iso formatted utcnow."""
if not at:
at = utcnow()
return at.strftime(TIME_FORMAT)
def parse_isotime(timestr):
"""Turn an iso formatted time back into a datetime"""
return datetime.datetime.strptime(timestr, TIME_FORMAT)
def parse_mailmap(mailmap='.mailmap'):
mapping = {}
if os.path.exists(mailmap):
fp = open(mailmap, 'r')
for l in fp:
l = l.strip()
if not l.startswith('#') and ' ' in l:
canonical_email, alias = l.split(' ')
mapping[alias] = canonical_email
return mapping
def str_dict_replace(s, mapping):
for s1, s2 in mapping.iteritems():
s = s.replace(s1, s2)
return s
class LazyPluggable(object):
"""A pluggable backend loaded lazily based on some value."""
def __init__(self, pivot, **backends):
self.__backends = backends
self.__pivot = pivot
self.__backend = None
def __get_backend(self):
if not self.__backend:
backend_name = self.__pivot.value
if backend_name not in self.__backends:
raise exception.Error(_('Invalid backend: %s') % backend_name)
backend = self.__backends[backend_name]
if type(backend) == type(tuple()):
name = backend[0]
fromlist = backend[1]
else:
name = backend
fromlist = backend
self.__backend = __import__(name, None, None, fromlist)
LOG.debug(_('backend %s'), self.__backend)
return self.__backend
def __getattr__(self, key):
backend = self.__get_backend()
return getattr(backend, key)
class LoopingCallDone(Exception):
"""The poll-function passed to LoopingCall can raise this exception to
break out of the loop normally. This is somewhat analogous to
StopIteration.
An optional return-value can be included as the argument to the exception;
this return-value will be returned by LoopingCall.wait()
"""
def __init__(self, retvalue=True):
""":param retvalue: Value that LoopingCall.wait() should return"""
self.retvalue = retvalue
class LoopingCall(object):
def __init__(self, f=None, *args, **kw):
self.args = args
self.kw = kw
self.f = f
self._running = False
def start(self, interval, now=True):
self._running = True
done = event.Event()
def _inner():
if not now:
greenthread.sleep(interval)
try:
while self._running:
self.f(*self.args, **self.kw)
greenthread.sleep(interval)
except LoopingCallDone, e:
self.stop()
done.send(e.retvalue)
except Exception:
logging.exception('in looping call')
done.send_exception(*sys.exc_info())
return
else:
done.send(True)
self.done = done
greenthread.spawn(_inner)
return self.done
def stop(self):
self._running = False
def wait(self):
return self.done.wait()
def xhtml_escape(value):
"""Escapes a string so it is valid within XML or XHTML.
Code is directly from the utf8 function in
http://github.com/facebook/tornado/blob/master/tornado/escape.py
"""
return saxutils.escape(value, {'"': """})
def utf8(value):
"""Try to turn a string into utf-8 if possible.
Code is directly from the utf8 function in
http://github.com/facebook/tornado/blob/master/tornado/escape.py
"""
if isinstance(value, unicode):
return value.encode("utf-8")
assert isinstance(value, str)
return value
def to_primitive(value):
if type(value) is type([]) or type(value) is type((None,)):
o = []
for v in value:
o.append(to_primitive(v))
return o
elif type(value) is type({}):
o = {}
for k, v in value.iteritems():
o[k] = to_primitive(v)
return o
elif isinstance(value, datetime.datetime):
return str(value)
elif hasattr(value, 'iteritems'):
return to_primitive(dict(value.iteritems()))
elif hasattr(value, '__iter__'):
return to_primitive(list(value))
else:
return value
def dumps(value):
try:
return json.dumps(value)
except TypeError:
pass
return json.dumps(to_primitive(value))
def loads(s):
return json.loads(s)
def config_file(basename):
"""Find the best location in the system for a config file.
Search Order
------------
The search for a paste config file honors `FLAGS.state_path`, which in a
version checked out from bzr will be the `fractus` directory in the top level
of the checkout, and in an installation for a package for your distribution
will likely point to someplace like /etc/fractus.
This method tries to load places likely to be used in development or
experimentation before falling back to the system-wide configuration
in `/etc/fractus/`.
* Current working directory
* the `etc` directory under state_path, because when working on a checkout
from bzr this will point to the default
* top level of FLAGS.state_path, for distributions
* /etc/fractus, which may not be differerent from state_path on your distro
"""
configfiles = [basename,
os.path.join(FLAGS.state_path, 'etc', basename),
os.path.join(FLAGS.state_path, basename),
'/etc/fractus/%s' % basename]
for configfile in configfiles:
if os.path.exists(configfile):
return configfile
| Python |
# Copyright 2011 OpenStack LLC
#
# 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.
try:
from fractus.vcsversion import version_info
except ImportError:
version_info = {'branch_nick': u'LOCALBRANCH',
'revision_id': 'LOCALREVISION',
'revno': 0}
FRACTUS_VERSION = ['2011', '1']
YEAR, COUNT = FRACTUS_VERSION
FINAL = False # This becomes true at Release Candidate time
def canonical_version_string():
return '.'.join([YEAR, COUNT])
def version_string():
if FINAL:
return canonical_version_string()
else:
return '%s-dev' % (canonical_version_string(),)
def vcs_version_string():
return "%s:%s" % (version_info['branch_nick'], version_info['revision_id'])
def version_string_with_vcs():
return "%s-%s" % (canonical_version_string(), vcs_version_string())
| Python |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""
AMQP-based RPC. Queues have consumers and publishers.
No fan-out support yet.
"""
import json
import sys
import time
import traceback
import uuid
from carrot import connection as carrot_connection
from carrot import messaging
from eventlet import greenpool
from eventlet import greenthread
from fractus import context
from fractus import exception
from fractus import fakerabbit
from fractus import flags
from fractus import log as logging
from fractus import utils
FLAGS = flags.FLAGS
LOG = logging.getLogger('fractus.rpc')
flags.DEFINE_integer('rpc_thread_pool_size', 1024, 'Size of RPC thread pool')
class Connection(carrot_connection.BrokerConnection):
"""Connection instance object"""
@classmethod
def instance(cls, new=True):
"""Returns the instance"""
if new or not hasattr(cls, '_instance'):
params = dict(hostname=FLAGS.rabbit_host,
port=FLAGS.rabbit_port,
userid=FLAGS.rabbit_userid,
password=FLAGS.rabbit_password,
virtual_host=FLAGS.rabbit_virtual_host)
if FLAGS.fake_rabbit:
params['backend_cls'] = fakerabbit.Backend
# NOTE(vish): magic is fun!
# pylint: disable-msg=W0142
if new:
return cls(**params)
else:
cls._instance = cls(**params)
return cls._instance
@classmethod
def recreate(cls):
"""Recreates the connection instance
This is necessary to recover from some network errors/disconnects"""
del cls._instance
return cls.instance()
class Consumer(messaging.Consumer):
"""Consumer base class
Contains methods for connecting the fetch method to async loops
"""
def __init__(self, *args, **kwargs):
for i in xrange(FLAGS.rabbit_max_retries):
if i > 0:
time.sleep(FLAGS.rabbit_retry_interval)
try:
super(Consumer, self).__init__(*args, **kwargs)
self.failed_connection = False
break
except: # Catching all because carrot sucks
fl_host = FLAGS.rabbit_host
fl_port = FLAGS.rabbit_port
fl_intv = FLAGS.rabbit_retry_interval
LOG.exception(_("AMQP server on %(fl_host)s:%(fl_port)d is"
" unreachable. Trying again in %(fl_intv)d seconds.")
% locals())
self.failed_connection = True
if self.failed_connection:
LOG.exception(_("Unable to connect to AMQP server "
"after %d tries. Shutting down."),
FLAGS.rabbit_max_retries)
sys.exit(1)
def fetch(self, no_ack=None, auto_ack=None, enable_callbacks=False):
"""Wraps the parent fetch with some logic for failed connections"""
# TODO(vish): the logic for failed connections and logging should be
# refactored into some sort of connection manager object
try:
if self.failed_connection:
# NOTE(vish): connection is defined in the parent class, we can
# recreate it as long as we create the backend too
# pylint: disable-msg=W0201
self.connection = Connection.recreate()
self.backend = self.connection.create_backend()
self.declare()
super(Consumer, self).fetch(no_ack, auto_ack, enable_callbacks)
if self.failed_connection:
LOG.error(_("Reconnected to queue"))
self.failed_connection = False
# NOTE(vish): This is catching all errors because we really don't
# exceptions to be logged 10 times a second if some
# persistent failure occurs.
except Exception: # pylint: disable-msg=W0703
if not self.failed_connection:
LOG.exception(_("Failed to fetch message from queue"))
self.failed_connection = True
def attach_to_eventlet(self):
"""Only needed for unit tests!"""
timer = utils.LoopingCall(self.fetch, enable_callbacks=True)
timer.start(0.1)
return timer
class Publisher(messaging.Publisher):
"""Publisher base class"""
pass
class TopicConsumer(Consumer):
"""Consumes messages on a specific topic"""
exchange_type = "topic"
def __init__(self, connection=None, topic="broadcast"):
self.queue = topic
self.routing_key = topic
self.exchange = FLAGS.control_exchange
self.durable = False
super(TopicConsumer, self).__init__(connection=connection)
class AdapterConsumer(TopicConsumer):
"""Calls methods on a proxy object based on method and args"""
def __init__(self, connection=None, topic="broadcast", proxy=None):
LOG.debug(_('Initing the Adapter Consumer for %s') % topic)
self.proxy = proxy
self.pool = greenpool.GreenPool(FLAGS.rpc_thread_pool_size)
super(AdapterConsumer, self).__init__(connection=connection,
topic=topic)
def receive(self, *args, **kwargs):
self.pool.spawn_n(self._receive, *args, **kwargs)
@exception.wrap_exception
def _receive(self, message_data, message):
"""Magically looks for a method on the proxy object and calls it
Message data should be a dictionary with two keys:
method: string representing the method to call
args: dictionary of arg: value
Example: {'method': 'echo', 'args': {'value': 42}}
"""
LOG.debug(_('received %s') % message_data)
msg_id = message_data.pop('_msg_id', None)
ctxt = _unpack_context(message_data)
method = message_data.get('method')
args = message_data.get('args', {})
message.ack()
if not method:
# NOTE(vish): we may not want to ack here, but that means that bad
# messages stay in the queue indefinitely, so for now
# we just log the message and send an error string
# back to the caller
LOG.warn(_('no method for message: %s') % message_data)
msg_reply(msg_id, _('No method for message: %s') % message_data)
return
node_func = getattr(self.proxy, str(method))
node_args = dict((str(k), v) for k, v in args.iteritems())
# NOTE(vish): magic is fun!
try:
rval = node_func(context=ctxt, **node_args)
if msg_id:
msg_reply(msg_id, rval, None)
except Exception as e:
logging.exception("Exception during message handling")
if msg_id:
msg_reply(msg_id, None, sys.exc_info())
return
class TopicPublisher(Publisher):
"""Publishes messages on a specific topic"""
exchange_type = "topic"
def __init__(self, connection=None, topic="broadcast"):
self.routing_key = topic
self.exchange = FLAGS.control_exchange
self.durable = False
super(TopicPublisher, self).__init__(connection=connection)
class DirectConsumer(Consumer):
"""Consumes messages directly on a channel specified by msg_id"""
exchange_type = "direct"
def __init__(self, connection=None, msg_id=None):
self.queue = msg_id
self.routing_key = msg_id
self.exchange = msg_id
self.auto_delete = True
self.exclusive = True
super(DirectConsumer, self).__init__(connection=connection)
class DirectPublisher(Publisher):
"""Publishes messages directly on a channel specified by msg_id"""
exchange_type = "direct"
def __init__(self, connection=None, msg_id=None):
self.routing_key = msg_id
self.exchange = msg_id
self.auto_delete = True
super(DirectPublisher, self).__init__(connection=connection)
def msg_reply(msg_id, reply=None, failure=None):
"""Sends a reply or an error on the channel signified by msg_id
failure should be a sys.exc_info() tuple.
"""
if failure:
message = str(failure[1])
tb = traceback.format_exception(*failure)
LOG.error(_("Returning exception %s to caller"), message)
LOG.error(tb)
failure = (failure[0].__name__, str(failure[1]), tb)
conn = Connection.instance()
publisher = DirectPublisher(connection=conn, msg_id=msg_id)
try:
publisher.send({'result': reply, 'failure': failure})
except TypeError:
publisher.send(
{'result': dict((k, repr(v))
for k, v in reply.__dict__.iteritems()),
'failure': failure})
publisher.close()
class RemoteError(exception.Error):
"""Signifies that a remote class has raised an exception
Containes a string representation of the type of the original exception,
the value of the original exception, and the traceback. These are
sent to the parent as a joined string so printing the exception
contains all of the relevent info."""
def __init__(self, exc_type, value, traceback):
self.exc_type = exc_type
self.value = value
self.traceback = traceback
super(RemoteError, self).__init__("%s %s\n%s" % (exc_type,
value,
traceback))
def _unpack_context(msg):
"""Unpack context from msg."""
context_dict = {}
for key in list(msg.keys()):
# NOTE(vish): Some versions of python don't like unicode keys
# in kwargs.
key = str(key)
if key.startswith('_context_'):
value = msg.pop(key)
context_dict[key[9:]] = value
LOG.debug(_('unpacked context: %s'), context_dict)
return context.RequestContext.from_dict(context_dict)
def _pack_context(msg, context):
"""Pack context into msg.
Values for message keys need to be less than 255 chars, so we pull
context out into a bunch of separate keys. If we want to support
more arguments in rabbit messages, we may want to do the same
for args at some point.
"""
context = dict([('_context_%s' % key, value)
for (key, value) in context.to_dict().iteritems()])
msg.update(context)
def call(context, topic, msg):
"""Sends a message on a topic and wait for a response"""
LOG.debug(_("Making asynchronous call..."))
msg_id = uuid.uuid4().hex
msg.update({'_msg_id': msg_id})
LOG.debug(_("MSG_ID is %s") % (msg_id))
_pack_context(msg, context)
class WaitMessage(object):
def __call__(self, data, message):
"""Acks message and sets result."""
message.ack()
if data['failure']:
self.result = RemoteError(*data['failure'])
else:
self.result = data['result']
wait_msg = WaitMessage()
conn = Connection.instance()
consumer = DirectConsumer(connection=conn, msg_id=msg_id)
consumer.register_callback(wait_msg)
conn = Connection.instance()
publisher = TopicPublisher(connection=conn, topic=topic)
publisher.send(msg)
publisher.close()
try:
consumer.wait(limit=1)
except StopIteration:
pass
consumer.close()
# NOTE(termie): this is a little bit of a change from the original
# non-eventlet code where returning a Failure
# instance from a deferred call is very similar to
# raising an exception
if isinstance(wait_msg.result, Exception):
raise wait_msg.result
return wait_msg.result
def cast(context, topic, msg):
"""Sends a message on a topic without waiting for a response"""
LOG.debug(_("Making asynchronous cast..."))
_pack_context(msg, context)
conn = Connection.instance()
publisher = TopicPublisher(connection=conn, topic=topic)
publisher.send(msg)
publisher.close()
def generic_response(message_data, message):
"""Logs a result and exits"""
LOG.debug(_('response %s'), message_data)
message.ack()
sys.exit(0)
def send_message(topic, message, wait=True):
"""Sends a message for testing"""
msg_id = uuid.uuid4().hex
message.update({'_msg_id': msg_id})
LOG.debug(_('topic is %s'), topic)
LOG.debug(_('message %s'), message)
if wait:
consumer = messaging.Consumer(connection=Connection.instance(),
queue=msg_id,
exchange=msg_id,
auto_delete=True,
exchange_type="direct",
routing_key=msg_id)
consumer.register_callback(generic_response)
publisher = messaging.Publisher(connection=Connection.instance(),
exchange=FLAGS.control_exchange,
durable=False,
exchange_type="topic",
routing_key=topic)
publisher.send(message)
publisher.close()
if wait:
consumer.wait()
if __name__ == "__main__":
# NOTE(vish): you can send messages from the command line using
# topic and a json sting representing a dictionary
# for the method
send_message(sys.argv[1], json.loads(sys.argv[2]))
| Python |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""
Defines interface for DB access.
The underlying driver is loaded as a :class:`LazyPluggable`.
**Related Flags**
:db_backend: string to lookup in the list of LazyPluggable backends.
`sqlalchemy` is the only supported backend right now.
:sql_connection: string specifying the sqlalchemy connection to use, like:
`sqlite:///var/lib/nova/nova.sqlite`.
:enable_new_services: when adding a new service to the database, is it in the
pool of available hardware (Default: True)
"""
from fractus import exception
from fractus import flags
from fractus import utils
FLAGS = flags.FLAGS
flags.DEFINE_string('db_backend', 'sqlalchemy',
'The backend to use for db')
flags.DEFINE_boolean('enable_new_services', True,
'Services to be added to the available pool on create')
flags.DEFINE_string('instance_name_template', 'instance-%08x',
'Template string to be used to generate instance names')
flags.DEFINE_string('volume_name_template', 'volume-%08x',
'Template string to be used to generate instance names')
IMPL = utils.LazyPluggable(FLAGS['db_backend'],
sqlalchemy='fractus.db.sqlalchemy.api')
class NoMoreAddresses(exception.Error):
"""No more available addresses."""
pass
class NoMoreBlades(exception.Error):
"""No more available blades."""
pass
class NoMoreNetworks(exception.Error):
"""No more available networks."""
pass
class NoMoreTargets(exception.Error):
"""No more available blades"""
pass
###################
def service_destroy(context, instance_id):
"""Destroy the service or raise if it does not exist."""
return IMPL.service_destroy(context, instance_id)
def service_get(context, service_id):
"""Get an service or raise if it does not exist."""
return IMPL.service_get(context, service_id)
def service_get_all(context, disabled=False):
"""Get all service."""
return IMPL.service_get_all(context, None, disabled)
def service_get_all_by_topic(context, topic):
"""Get all services for a given topic."""
return IMPL.service_get_all_by_topic(context, topic)
def service_get_all_by_host(context, host):
"""Get all services for a given host."""
return IMPL.service_get_all_by_host(context, host)
def service_get_all_compute_sorted(context):
"""Get all compute services sorted by instance count.
Returns a list of (Service, instance_count) tuples.
"""
return IMPL.service_get_all_compute_sorted(context)
def service_get_all_network_sorted(context):
"""Get all network services sorted by network count.
Returns a list of (Service, network_count) tuples.
"""
return IMPL.service_get_all_network_sorted(context)
def service_get_all_volume_sorted(context):
"""Get all volume services sorted by volume count.
Returns a list of (Service, volume_count) tuples.
"""
return IMPL.service_get_all_volume_sorted(context)
def service_get_by_args(context, host, binary):
"""Get the state of an service by node name and binary."""
return IMPL.service_get_by_args(context, host, binary)
def service_create(context, values):
"""Create a service from the values dictionary."""
return IMPL.service_create(context, values)
def service_update(context, service_id, values):
"""Set the given properties on an service and update it.
Raises NotFound if service does not exist.
"""
return IMPL.service_update(context, service_id, values)
###################
def certificate_create(context, values):
"""Create a certificate from the values dictionary."""
return IMPL.certificate_create(context, values)
def certificate_destroy(context, certificate_id):
"""Destroy the certificate or raise if it does not exist."""
return IMPL.certificate_destroy(context, certificate_id)
def certificate_get_all_by_project(context, project_id):
"""Get all certificates for a project."""
return IMPL.certificate_get_all_by_project(context, project_id)
def certificate_get_all_by_user(context, user_id):
"""Get all certificates for a user."""
return IMPL.certificate_get_all_by_user(context, user_id)
def certificate_get_all_by_user_and_project(context, user_id, project_id):
"""Get all certificates for a user and project."""
return IMPL.certificate_get_all_by_user_and_project(context,
user_id,
project_id)
def certificate_update(context, certificate_id, values):
"""Set the given properties on an certificate and update it.
Raises NotFound if service does not exist.
"""
return IMPL.service_update(context, certificate_id, values)
###################
def floating_ip_allocate_address(context, host, project_id):
"""Allocate free floating ip and return the address.
Raises if one is not available.
"""
return IMPL.floating_ip_allocate_address(context, host, project_id)
def floating_ip_create(context, values):
"""Create a floating ip from the values dictionary."""
return IMPL.floating_ip_create(context, values)
def floating_ip_count_by_project(context, project_id):
"""Count floating ips used by project."""
return IMPL.floating_ip_count_by_project(context, project_id)
def floating_ip_deallocate(context, address):
"""Deallocate an floating ip by address"""
return IMPL.floating_ip_deallocate(context, address)
def floating_ip_destroy(context, address):
"""Destroy the floating_ip or raise if it does not exist."""
return IMPL.floating_ip_destroy(context, address)
def floating_ip_disassociate(context, address):
"""Disassociate an floating ip from a fixed ip by address.
Returns the address of the existing fixed ip.
"""
return IMPL.floating_ip_disassociate(context, address)
def floating_ip_fixed_ip_associate(context, floating_address, fixed_address):
"""Associate an floating ip to a fixed_ip by address."""
return IMPL.floating_ip_fixed_ip_associate(context,
floating_address,
fixed_address)
def floating_ip_get_all(context):
"""Get all floating ips."""
return IMPL.floating_ip_get_all(context)
def floating_ip_get_all_by_host(context, host):
"""Get all floating ips by host."""
return IMPL.floating_ip_get_all_by_host(context, host)
def floating_ip_get_all_by_project(context, project_id):
"""Get all floating ips by project."""
return IMPL.floating_ip_get_all_by_project(context, project_id)
def floating_ip_get_by_address(context, address):
"""Get a floating ip by address or raise if it doesn't exist."""
return IMPL.floating_ip_get_by_address(context, address)
####################
def fixed_ip_associate(context, address, instance_id):
"""Associate fixed ip to instance.
Raises if fixed ip is not available.
"""
return IMPL.fixed_ip_associate(context, address, instance_id)
def fixed_ip_associate_pool(context, network_id, instance_id):
"""Find free ip in network and associate it to instance.
Raises if one is not available.
"""
return IMPL.fixed_ip_associate_pool(context, network_id, instance_id)
def fixed_ip_create(context, values):
"""Create a fixed ip from the values dictionary."""
return IMPL.fixed_ip_create(context, values)
def fixed_ip_disassociate(context, address):
"""Disassociate a fixed ip from an instance by address."""
return IMPL.fixed_ip_disassociate(context, address)
def fixed_ip_disassociate_all_by_timeout(context, host, time):
"""Disassociate old fixed ips from host."""
return IMPL.fixed_ip_disassociate_all_by_timeout(context, host, time)
def fixed_ip_get_all(context):
"""Get all defined fixed ips."""
return IMPL.fixed_ip_get_all(context)
def fixed_ip_get_by_address(context, address):
"""Get a fixed ip by address or raise if it does not exist."""
return IMPL.fixed_ip_get_by_address(context, address)
def fixed_ip_get_all_by_instance(context, instance_id):
"""Get fixed ips by instance or raise if none exist."""
return IMPL.fixed_ip_get_all_by_instance(context, instance_id)
def fixed_ip_get_instance(context, address):
"""Get an instance for a fixed ip by address."""
return IMPL.fixed_ip_get_instance(context, address)
def fixed_ip_get_instance_v6(context, address):
return IMPL.fixed_ip_get_instance_v6(context, address)
def fixed_ip_get_network(context, address):
"""Get a network for a fixed ip by address."""
return IMPL.fixed_ip_get_network(context, address)
def fixed_ip_update(context, address, values):
"""Create a fixed ip from the values dictionary."""
return IMPL.fixed_ip_update(context, address, values)
####################
def instance_create(context, values):
"""Create an instance from the values dictionary."""
return IMPL.instance_create(context, values)
def instance_data_get_for_project(context, project_id):
"""Get (instance_count, core_count) for project."""
return IMPL.instance_data_get_for_project(context, project_id)
def instance_destroy(context, instance_id):
"""Destroy the instance or raise if it does not exist."""
return IMPL.instance_destroy(context, instance_id)
def instance_get(context, instance_id):
"""Get an instance or raise if it does not exist."""
return IMPL.instance_get(context, instance_id)
def instance_get_all(context):
"""Get all instances."""
return IMPL.instance_get_all(context)
def instance_get_all_by_user(context, user_id):
"""Get all instances."""
return IMPL.instance_get_all_by_user(context, user_id)
def instance_get_all_by_project(context, project_id):
"""Get all instance belonging to a project."""
return IMPL.instance_get_all_by_project(context, project_id)
def instance_get_all_by_host(context, host):
"""Get all instance belonging to a host."""
return IMPL.instance_get_all_by_host(context, host)
def instance_get_all_by_reservation(context, reservation_id):
"""Get all instance belonging to a reservation."""
return IMPL.instance_get_all_by_reservation(context, reservation_id)
def instance_get_fixed_address(context, instance_id):
"""Get the fixed ip address of an instance."""
return IMPL.instance_get_fixed_address(context, instance_id)
def instance_get_fixed_address_v6(context, instance_id):
return IMPL.instance_get_fixed_address_v6(context, instance_id)
def instance_get_floating_address(context, instance_id):
"""Get the first floating ip address of an instance."""
return IMPL.instance_get_floating_address(context, instance_id)
def instance_get_project_vpn(context, project_id):
"""Get a vpn instance by project or return None."""
return IMPL.instance_get_project_vpn(context, project_id)
def instance_is_vpn(context, instance_id):
"""True if instance is a vpn."""
return IMPL.instance_is_vpn(context, instance_id)
def instance_set_state(context, instance_id, state, description=None):
"""Set the state of an instance."""
return IMPL.instance_set_state(context, instance_id, state, description)
def instance_update(context, instance_id, values):
"""Set the given properties on an instance and update it.
Raises NotFound if instance does not exist.
"""
return IMPL.instance_update(context, instance_id, values)
def instance_add_security_group(context, instance_id, security_group_id):
"""Associate the given security group with the given instance."""
return IMPL.instance_add_security_group(context, instance_id,
security_group_id)
def instance_action_create(context, values):
"""Create an instance action from the values dictionary."""
return IMPL.instance_action_create(context, values)
def instance_get_actions(context, instance_id):
"""Get instance actions by instance id."""
return IMPL.instance_get_actions(context, instance_id)
###################
def key_pair_create(context, values):
"""Create a key_pair from the values dictionary."""
return IMPL.key_pair_create(context, values)
def key_pair_destroy(context, user_id, name):
"""Destroy the key_pair or raise if it does not exist."""
return IMPL.key_pair_destroy(context, user_id, name)
def key_pair_destroy_all_by_user(context, user_id):
"""Destroy all key_pairs by user."""
return IMPL.key_pair_destroy_all_by_user(context, user_id)
def key_pair_get(context, user_id, name):
"""Get a key_pair or raise if it does not exist."""
return IMPL.key_pair_get(context, user_id, name)
def key_pair_get_all_by_user(context, user_id):
"""Get all key_pairs by user."""
return IMPL.key_pair_get_all_by_user(context, user_id)
####################
def network_associate(context, project_id):
"""Associate a free network to a project."""
return IMPL.network_associate(context, project_id)
def network_count(context):
"""Return the number of networks."""
return IMPL.network_count(context)
def network_count_allocated_ips(context, network_id):
"""Return the number of allocated non-reserved ips in the network."""
return IMPL.network_count_allocated_ips(context, network_id)
def network_count_available_ips(context, network_id):
"""Return the number of available ips in the network."""
return IMPL.network_count_available_ips(context, network_id)
def network_count_reserved_ips(context, network_id):
"""Return the number of reserved ips in the network."""
return IMPL.network_count_reserved_ips(context, network_id)
def network_create_safe(context, values):
"""Create a network from the values dict.
The network is only returned if the create succeeds. If the create violates
constraints because the network already exists, no exception is raised.
"""
return IMPL.network_create_safe(context, values)
def network_create_fixed_ips(context, network_id, num_vpn_clients):
"""Create the ips for the network, reserving sepecified ips."""
return IMPL.network_create_fixed_ips(context, network_id, num_vpn_clients)
def network_disassociate(context, network_id):
"""Disassociate the network from project or raise if it does not exist."""
return IMPL.network_disassociate(context, network_id)
def network_disassociate_all(context):
"""Disassociate all networks from projects."""
return IMPL.network_disassociate_all(context)
def network_get(context, network_id):
"""Get an network or raise if it does not exist."""
return IMPL.network_get(context, network_id)
def network_get_all(context):
"""Return all defined networks."""
return IMPL.network_get_all(context)
# pylint: disable-msg=C0103
def network_get_associated_fixed_ips(context, network_id):
"""Get all network's ips that have been associated."""
return IMPL.network_get_associated_fixed_ips(context, network_id)
def network_get_by_bridge(context, bridge):
"""Get a network by bridge or raise if it does not exist."""
return IMPL.network_get_by_bridge(context, bridge)
def network_get_by_instance(context, instance_id):
"""Get a network by instance id or raise if it does not exist."""
return IMPL.network_get_by_instance(context, instance_id)
def network_get_all_by_instance(context, instance_id):
"""Get all networks by instance id or raise if none exist."""
return IMPL.network_get_all_by_instance(context, instance_id)
def network_get_index(context, network_id):
"""Get non-conflicting index for network."""
return IMPL.network_get_index(context, network_id)
def network_get_vpn_ip(context, network_id):
"""Get non-conflicting index for network."""
return IMPL.network_get_vpn_ip(context, network_id)
def network_set_cidr(context, network_id, cidr):
"""Set the Classless Inner Domain Routing for the network."""
return IMPL.network_set_cidr(context, network_id, cidr)
def network_set_host(context, network_id, host_id):
"""Safely set the host for network."""
return IMPL.network_set_host(context, network_id, host_id)
def network_update(context, network_id, values):
"""Set the given properties on an network and update it.
Raises NotFound if network does not exist.
"""
return IMPL.network_update(context, network_id, values)
###################
def project_get_network(context, project_id, associate=True):
"""Return the network associated with the project.
If associate is true, it will attempt to associate a new
network if one is not found, otherwise it returns None.
"""
return IMPL.project_get_network(context, project_id, associate)
def project_get_network_v6(context, project_id):
return IMPL.project_get_network_v6(context, project_id)
###################
def queue_get_for(context, topic, physical_node_id):
"""Return a channel to send a message to a node with a topic."""
return IMPL.queue_get_for(context, topic, physical_node_id)
###################
def export_device_count(context):
"""Return count of export devices."""
return IMPL.export_device_count(context)
def export_device_create_safe(context, values):
"""Create an export_device from the values dictionary.
The device is not returned. If the create violates the unique
constraints because the shelf_id and blade_id already exist,
no exception is raised.
"""
return IMPL.export_device_create_safe(context, values)
###################
def iscsi_target_count_by_host(context, host):
"""Return count of export devices."""
return IMPL.iscsi_target_count_by_host(context, host)
def iscsi_target_create_safe(context, values):
"""Create an iscsi_target from the values dictionary.
The device is not returned. If the create violates the unique
constraints because the iscsi_target and host already exist,
no exception is raised."""
return IMPL.iscsi_target_create_safe(context, values)
###############
def auth_destroy_token(context, token):
"""Destroy an auth token."""
return IMPL.auth_destroy_token(context, token)
def auth_get_token(context, token_hash):
"""Retrieves a token given the hash representing it."""
return IMPL.auth_get_token(context, token_hash)
def auth_create_token(context, token):
"""Creates a new token."""
return IMPL.auth_create_token(context, token)
###################
def quota_create(context, values):
"""Create a quota from the values dictionary."""
return IMPL.quota_create(context, values)
def quota_get(context, project_id):
"""Retrieve a quota or raise if it does not exist."""
return IMPL.quota_get(context, project_id)
def quota_update(context, project_id, values):
"""Update a quota from the values dictionary."""
return IMPL.quota_update(context, project_id, values)
def quota_destroy(context, project_id):
"""Destroy the quota or raise if it does not exist."""
return IMPL.quota_destroy(context, project_id)
###################
def volume_allocate_shelf_and_blade(context, volume_id):
"""Atomically allocate a free shelf and blade from the pool."""
return IMPL.volume_allocate_shelf_and_blade(context, volume_id)
def volume_allocate_iscsi_target(context, volume_id, host):
"""Atomically allocate a free iscsi_target from the pool."""
return IMPL.volume_allocate_iscsi_target(context, volume_id, host)
def volume_attached(context, volume_id, instance_id, mountpoint):
"""Ensure that a volume is set as attached."""
return IMPL.volume_attached(context, volume_id, instance_id, mountpoint)
def volume_create(context, values):
"""Create a volume from the values dictionary."""
return IMPL.volume_create(context, values)
def volume_data_get_for_project(context, project_id):
"""Get (volume_count, gigabytes) for project."""
return IMPL.volume_data_get_for_project(context, project_id)
def volume_destroy(context, volume_id):
"""Destroy the volume or raise if it does not exist."""
return IMPL.volume_destroy(context, volume_id)
def volume_detached(context, volume_id):
"""Ensure that a volume is set as detached."""
return IMPL.volume_detached(context, volume_id)
def volume_get(context, volume_id):
"""Get a volume or raise if it does not exist."""
return IMPL.volume_get(context, volume_id)
def volume_get_all(context):
"""Get all volumes."""
return IMPL.volume_get_all(context)
def volume_get_all_by_host(context, host):
"""Get all volumes belonging to a host."""
return IMPL.volume_get_all_by_host(context, host)
def volume_get_all_by_project(context, project_id):
"""Get all volumes belonging to a project."""
return IMPL.volume_get_all_by_project(context, project_id)
def volume_get_by_ec2_id(context, ec2_id):
"""Get a volume by ec2 id."""
return IMPL.volume_get_by_ec2_id(context, ec2_id)
def volume_get_instance(context, volume_id):
"""Get the instance that a volume is attached to."""
return IMPL.volume_get_instance(context, volume_id)
def volume_get_shelf_and_blade(context, volume_id):
"""Get the shelf and blade allocated to the volume."""
return IMPL.volume_get_shelf_and_blade(context, volume_id)
def volume_get_iscsi_target_num(context, volume_id):
"""Get the target num (tid) allocated to the volume."""
return IMPL.volume_get_iscsi_target_num(context, volume_id)
def volume_update(context, volume_id, values):
"""Set the given properties on an volume and update it.
Raises NotFound if volume does not exist.
"""
return IMPL.volume_update(context, volume_id, values)
####################
def security_group_get_all(context):
"""Get all security groups."""
return IMPL.security_group_get_all(context)
def security_group_get(context, security_group_id):
"""Get security group by its id."""
return IMPL.security_group_get(context, security_group_id)
def security_group_get_by_name(context, project_id, group_name):
"""Returns a security group with the specified name from a project."""
return IMPL.security_group_get_by_name(context, project_id, group_name)
def security_group_get_by_project(context, project_id):
"""Get all security groups belonging to a project."""
return IMPL.security_group_get_by_project(context, project_id)
def security_group_get_by_instance(context, instance_id):
"""Get security groups to which the instance is assigned."""
return IMPL.security_group_get_by_instance(context, instance_id)
def security_group_exists(context, project_id, group_name):
"""Indicates if a group name exists in a project."""
return IMPL.security_group_exists(context, project_id, group_name)
def security_group_create(context, values):
"""Create a new security group."""
return IMPL.security_group_create(context, values)
def security_group_destroy(context, security_group_id):
"""Deletes a security group."""
return IMPL.security_group_destroy(context, security_group_id)
def security_group_destroy_all(context):
"""Deletes a security group."""
return IMPL.security_group_destroy_all(context)
####################
def security_group_rule_create(context, values):
"""Create a new security group."""
return IMPL.security_group_rule_create(context, values)
def security_group_rule_get_by_security_group(context, security_group_id):
"""Get all rules for a a given security group."""
return IMPL.security_group_rule_get_by_security_group(context,
security_group_id)
def security_group_rule_get_by_security_group_grantee(context,
security_group_id):
"""Get all rules that grant access to the given security group."""
return IMPL.security_group_rule_get_by_security_group_grantee(context,
security_group_id)
def security_group_rule_destroy(context, security_group_rule_id):
"""Deletes a security group rule."""
return IMPL.security_group_rule_destroy(context, security_group_rule_id)
###################
def user_get(context, id):
"""Get user by id."""
return IMPL.user_get(context, id)
def user_get_by_uid(context, uid):
"""Get user by uid."""
return IMPL.user_get_by_uid(context, uid)
def user_get_by_access_key(context, access_key):
"""Get user by access key."""
return IMPL.user_get_by_access_key(context, access_key)
def user_create(context, values):
"""Create a new user."""
return IMPL.user_create(context, values)
def user_delete(context, id):
"""Delete a user."""
return IMPL.user_delete(context, id)
def user_get_all(context):
"""Create a new user."""
return IMPL.user_get_all(context)
def user_add_role(context, user_id, role):
"""Add another global role for user."""
return IMPL.user_add_role(context, user_id, role)
def user_remove_role(context, user_id, role):
"""Remove global role from user."""
return IMPL.user_remove_role(context, user_id, role)
def user_get_roles(context, user_id):
"""Get global roles for user."""
return IMPL.user_get_roles(context, user_id)
def user_add_project_role(context, user_id, project_id, role):
"""Add project role for user."""
return IMPL.user_add_project_role(context, user_id, project_id, role)
def user_remove_project_role(context, user_id, project_id, role):
"""Remove project role from user."""
return IMPL.user_remove_project_role(context, user_id, project_id, role)
def user_get_roles_for_project(context, user_id, project_id):
"""Return list of roles a user holds on project."""
return IMPL.user_get_roles_for_project(context, user_id, project_id)
def user_update(context, user_id, values):
"""Update user."""
return IMPL.user_update(context, user_id, values)
def project_get(context, id):
"""Get project by id."""
return IMPL.project_get(context, id)
def project_create(context, values):
"""Create a new project."""
return IMPL.project_create(context, values)
def project_add_member(context, project_id, user_id):
"""Add user to project."""
return IMPL.project_add_member(context, project_id, user_id)
def project_get_all(context):
"""Get all projects."""
return IMPL.project_get_all(context)
def project_get_by_user(context, user_id):
"""Get all projects of which the given user is a member."""
return IMPL.project_get_by_user(context, user_id)
def project_remove_member(context, project_id, user_id):
"""Remove the given user from the given project."""
return IMPL.project_remove_member(context, project_id, user_id)
def project_update(context, project_id, values):
"""Update Remove the given user from the given project."""
return IMPL.project_update(context, project_id, values)
def project_delete(context, project_id):
"""Delete project."""
return IMPL.project_delete(context, project_id)
###################
def host_get_networks(context, host):
"""Return all networks for which the given host is the designated
network host.
"""
return IMPL.host_get_networks(context, host)
##################
def console_pool_create(context, values):
"""Create console pool."""
return IMPL.console_pool_create(context, values)
def console_pool_get(context, pool_id):
"""Get a console pool."""
return IMPL.console_pool_get(context, pool_id)
def console_pool_get_by_host_type(context, compute_host, proxy_host,
console_type):
"""Fetch a console pool for a given proxy host, compute host, and type."""
return IMPL.console_pool_get_by_host_type(context,
compute_host,
proxy_host,
console_type)
def console_pool_get_all_by_host_type(context, host, console_type):
"""Fetch all pools for given proxy host and type."""
return IMPL.console_pool_get_all_by_host_type(context,
host,
console_type)
def console_create(context, values):
"""Create a console."""
return IMPL.console_create(context, values)
def console_delete(context, console_id):
"""Delete a console."""
return IMPL.console_delete(context, console_id)
def console_get_by_pool_instance(context, pool_id, instance_id):
"""Get console entry for a given instance and pool."""
return IMPL.console_get_by_pool_instance(context, pool_id, instance_id)
def console_get_all_by_instance(context, instance_id):
"""Get consoles for a given instance."""
return IMPL.console_get_all_by_instance(context, instance_id)
def console_get(context, console_id, instance_id=None):
"""Get a specific console (possibly on a given instance)."""
return IMPL.console_get(context, console_id, instance_id)
####################
def zone_create(context, values):
"""Create a new child Zone entry."""
return IMPL.zone_create(context, values)
def zone_update(context, zone_id, values):
"""Update a child Zone entry."""
return IMPL.zone_update(context, values)
def zone_delete(context, zone_id):
"""Delete a child Zone."""
return IMPL.zone_delete(context, zone_id)
def zone_get(context, zone_id):
"""Get a specific child Zone."""
return IMPL.zone_get(context, zone_id)
def zone_get_all(context):
"""Get all child Zones."""
return IMPL.zone_get_all(context)
| Python |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""
Implementation of SQLAlchemy backend.
"""
import datetime
import warnings
from fractus import db
from fractus import exception
from fractus import flags
from fractus import utils
from fractus.db.sqlalchemy import models
from fractus.db.sqlalchemy.session import get_session
from sqlalchemy import or_
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import joinedload
from sqlalchemy.orm import joinedload_all
from sqlalchemy.sql import exists
from sqlalchemy.sql import func
FLAGS = flags.FLAGS
def is_admin_context(context):
"""Indicates if the request context is an administrator."""
if not context:
warnings.warn(_('Use of empty request context is deprecated'),
DeprecationWarning)
raise Exception('die')
return context.is_admin
def is_user_context(context):
"""Indicates if the request context is a normal user."""
if not context:
return False
if context.is_admin:
return False
if not context.user_id or not context.project_id:
return False
return True
def authorize_project_context(context, project_id):
"""Ensures that the request context has permission to access the
given project.
"""
if is_user_context(context):
if not context.project:
raise exception.NotAuthorized()
elif context.project_id != project_id:
raise exception.NotAuthorized()
def authorize_user_context(context, user_id):
"""Ensures that the request context has permission to access the
given user.
"""
if is_user_context(context):
if not context.user:
raise exception.NotAuthorized()
elif context.user_id != user_id:
raise exception.NotAuthorized()
def can_read_deleted(context):
"""Indicates if the context has access to deleted objects."""
if not context:
return False
return context.read_deleted
def require_admin_context(f):
"""Decorator used to indicate that the method requires an
administrator context.
"""
def wrapper(*args, **kwargs):
if not is_admin_context(args[0]):
raise exception.NotAuthorized()
return f(*args, **kwargs)
return wrapper
def require_context(f):
"""Decorator used to indicate that the method requires either
an administrator or normal user context.
"""
def wrapper(*args, **kwargs):
if not is_admin_context(args[0]) and not is_user_context(args[0]):
raise exception.NotAuthorized()
return f(*args, **kwargs)
return wrapper
###################
@require_admin_context
def service_destroy(context, service_id):
session = get_session()
with session.begin():
service_ref = service_get(context, service_id, session=session)
service_ref.delete(session=session)
@require_admin_context
def service_get(context, service_id, session=None):
if not session:
session = get_session()
result = session.query(models.Service).\
filter_by(id=service_id).\
filter_by(deleted=can_read_deleted(context)).\
first()
if not result:
raise exception.NotFound(_('No service for id %s') % service_id)
return result
@require_admin_context
def service_get_all(context, session=None, disabled=False):
if not session:
session = get_session()
result = session.query(models.Service).\
filter_by(deleted=can_read_deleted(context)).\
filter_by(disabled=disabled).\
all()
return result
@require_admin_context
def service_get_all_by_topic(context, topic):
session = get_session()
return session.query(models.Service).\
filter_by(deleted=False).\
filter_by(disabled=False).\
filter_by(topic=topic).\
all()
@require_admin_context
def service_get_all_by_host(context, host):
session = get_session()
return session.query(models.Service).\
filter_by(deleted=False).\
filter_by(host=host).\
all()
@require_admin_context
def _service_get_all_topic_subquery(context, session, topic, subq, label):
sort_value = getattr(subq.c, label)
return session.query(models.Service, func.coalesce(sort_value, 0)).\
filter_by(topic=topic).\
filter_by(deleted=False).\
filter_by(disabled=False).\
outerjoin((subq, models.Service.host == subq.c.host)).\
order_by(sort_value).\
all()
@require_admin_context
def service_get_all_compute_sorted(context):
session = get_session()
with session.begin():
# NOTE(vish): The intended query is below
# SELECT services.*, COALESCE(inst_cores.instance_cores,
# 0)
# FROM services LEFT OUTER JOIN
# (SELECT host, SUM(instances.vcpus) AS instance_cores
# FROM instances GROUP BY host) AS inst_cores
# ON services.host = inst_cores.host
topic = 'compute'
label = 'instance_cores'
subq = session.query(models.Instance.host,
func.sum(models.Instance.vcpus).label(label)).\
filter_by(deleted=False).\
group_by(models.Instance.host).\
subquery()
return _service_get_all_topic_subquery(context,
session,
topic,
subq,
label)
@require_admin_context
def service_get_all_network_sorted(context):
session = get_session()
with session.begin():
topic = 'network'
label = 'network_count'
subq = session.query(models.Network.host,
func.count(models.Network.id).label(label)).\
filter_by(deleted=False).\
group_by(models.Network.host).\
subquery()
return _service_get_all_topic_subquery(context,
session,
topic,
subq,
label)
@require_admin_context
def service_get_all_volume_sorted(context):
session = get_session()
with session.begin():
topic = 'volume'
label = 'volume_gigabytes'
subq = session.query(models.Volume.host,
func.sum(models.Volume.size).label(label)).\
filter_by(deleted=False).\
group_by(models.Volume.host).\
subquery()
return _service_get_all_topic_subquery(context,
session,
topic,
subq,
label)
@require_admin_context
def service_get_by_args(context, host, binary):
session = get_session()
result = session.query(models.Service).\
filter_by(host=host).\
filter_by(binary=binary).\
filter_by(deleted=can_read_deleted(context)).\
first()
if not result:
raise exception.NotFound(_('No service for %(host)s, %(binary)s')
% locals())
return result
@require_admin_context
def service_create(context, values):
service_ref = models.Service()
service_ref.update(values)
if not FLAGS.enable_new_services:
service_ref.disabled = True
service_ref.save()
return service_ref
@require_admin_context
def service_update(context, service_id, values):
session = get_session()
with session.begin():
service_ref = service_get(context, service_id, session=session)
service_ref.update(values)
service_ref.save(session=session)
###################
@require_admin_context
def certificate_get(context, certificate_id, session=None):
if not session:
session = get_session()
result = session.query(models.Certificate).\
filter_by(id=certificate_id).\
filter_by(deleted=can_read_deleted(context)).\
first()
if not result:
raise exception.NotFound('No certificate for id %s' % certificate_id)
return result
@require_admin_context
def certificate_create(context, values):
certificate_ref = models.Certificate()
for (key, value) in values.iteritems():
certificate_ref[key] = value
certificate_ref.save()
return certificate_ref
@require_admin_context
def certificate_destroy(context, certificate_id):
session = get_session()
with session.begin():
certificate_ref = certificate_get(context,
certificate_id,
session=session)
certificate_ref.delete(session=session)
@require_admin_context
def certificate_get_all_by_project(context, project_id):
session = get_session()
return session.query(models.Certificate).\
filter_by(project_id=project_id).\
filter_by(deleted=False).\
all()
@require_admin_context
def certificate_get_all_by_user(context, user_id):
session = get_session()
return session.query(models.Certificate).\
filter_by(user_id=user_id).\
filter_by(deleted=False).\
all()
@require_admin_context
def certificate_get_all_by_user_and_project(_context, user_id, project_id):
session = get_session()
return session.query(models.Certificate).\
filter_by(user_id=user_id).\
filter_by(project_id=project_id).\
filter_by(deleted=False).\
all()
@require_admin_context
def certificate_update(context, certificate_id, values):
session = get_session()
with session.begin():
certificate_ref = certificate_get(context,
certificate_id,
session=session)
for (key, value) in values.iteritems():
certificate_ref[key] = value
certificate_ref.save(session=session)
###################
@require_context
def floating_ip_allocate_address(context, host, project_id):
authorize_project_context(context, project_id)
session = get_session()
with session.begin():
floating_ip_ref = session.query(models.FloatingIp).\
filter_by(host=host).\
filter_by(fixed_ip_id=None).\
filter_by(project_id=None).\
filter_by(deleted=False).\
with_lockmode('update').\
first()
# NOTE(vish): if with_lockmode isn't supported, as in sqlite,
# then this has concurrency issues
if not floating_ip_ref:
raise db.NoMoreAddresses()
floating_ip_ref['project_id'] = project_id
session.add(floating_ip_ref)
return floating_ip_ref['address']
@require_context
def floating_ip_create(context, values):
floating_ip_ref = models.FloatingIp()
floating_ip_ref.update(values)
floating_ip_ref.save()
return floating_ip_ref['address']
@require_context
def floating_ip_count_by_project(context, project_id):
authorize_project_context(context, project_id)
session = get_session()
return session.query(models.FloatingIp).\
filter_by(project_id=project_id).\
filter_by(deleted=False).\
count()
@require_context
def floating_ip_fixed_ip_associate(context, floating_address, fixed_address):
session = get_session()
with session.begin():
# TODO(devcamcar): How to ensure floating_id belongs to user?
floating_ip_ref = floating_ip_get_by_address(context,
floating_address,
session=session)
fixed_ip_ref = fixed_ip_get_by_address(context,
fixed_address,
session=session)
floating_ip_ref.fixed_ip = fixed_ip_ref
floating_ip_ref.save(session=session)
@require_context
def floating_ip_deallocate(context, address):
session = get_session()
with session.begin():
# TODO(devcamcar): How to ensure floating id belongs to user?
floating_ip_ref = floating_ip_get_by_address(context,
address,
session=session)
floating_ip_ref['project_id'] = None
floating_ip_ref.save(session=session)
@require_context
def floating_ip_destroy(context, address):
session = get_session()
with session.begin():
# TODO(devcamcar): Ensure address belongs to user.
floating_ip_ref = floating_ip_get_by_address(context,
address,
session=session)
floating_ip_ref.delete(session=session)
@require_context
def floating_ip_disassociate(context, address):
session = get_session()
with session.begin():
# TODO(devcamcar): Ensure address belongs to user.
# Does get_floating_ip_by_address handle this?
floating_ip_ref = floating_ip_get_by_address(context,
address,
session=session)
fixed_ip_ref = floating_ip_ref.fixed_ip
if fixed_ip_ref:
fixed_ip_address = fixed_ip_ref['address']
else:
fixed_ip_address = None
floating_ip_ref.fixed_ip = None
floating_ip_ref.save(session=session)
return fixed_ip_address
@require_admin_context
def floating_ip_get_all(context):
session = get_session()
return session.query(models.FloatingIp).\
options(joinedload_all('fixed_ip.instance')).\
filter_by(deleted=False).\
all()
@require_admin_context
def floating_ip_get_all_by_host(context, host):
session = get_session()
return session.query(models.FloatingIp).\
options(joinedload_all('fixed_ip.instance')).\
filter_by(host=host).\
filter_by(deleted=False).\
all()
@require_context
def floating_ip_get_all_by_project(context, project_id):
authorize_project_context(context, project_id)
session = get_session()
return session.query(models.FloatingIp).\
options(joinedload_all('fixed_ip.instance')).\
filter_by(project_id=project_id).\
filter_by(deleted=False).\
all()
@require_context
def floating_ip_get_by_address(context, address, session=None):
# TODO(devcamcar): Ensure the address belongs to user.
if not session:
session = get_session()
result = session.query(models.FloatingIp).\
options(joinedload_all('fixed_ip.network')).\
filter_by(address=address).\
filter_by(deleted=can_read_deleted(context)).\
first()
if not result:
raise exception.NotFound('No floating ip for address %s' % address)
return result
###################
@require_context
def fixed_ip_associate(context, address, instance_id):
session = get_session()
with session.begin():
instance = instance_get(context, instance_id, session=session)
fixed_ip_ref = session.query(models.FixedIp).\
filter_by(address=address).\
filter_by(deleted=False).\
filter_by(instance=None).\
with_lockmode('update').\
first()
# NOTE(vish): if with_lockmode isn't supported, as in sqlite,
# then this has concurrency issues
if not fixed_ip_ref:
raise db.NoMoreAddresses()
fixed_ip_ref.instance = instance
session.add(fixed_ip_ref)
@require_admin_context
def fixed_ip_associate_pool(context, network_id, instance_id):
session = get_session()
with session.begin():
network_or_none = or_(models.FixedIp.network_id == network_id,
models.FixedIp.network_id == None)
fixed_ip_ref = session.query(models.FixedIp).\
filter(network_or_none).\
filter_by(reserved=False).\
filter_by(deleted=False).\
filter_by(instance=None).\
with_lockmode('update').\
first()
# NOTE(vish): if with_lockmode isn't supported, as in sqlite,
# then this has concurrency issues
if not fixed_ip_ref:
raise db.NoMoreAddresses()
if not fixed_ip_ref.network:
fixed_ip_ref.network = network_get(context,
network_id,
session=session)
fixed_ip_ref.instance = instance_get(context,
instance_id,
session=session)
session.add(fixed_ip_ref)
return fixed_ip_ref['address']
@require_context
def fixed_ip_create(_context, values):
fixed_ip_ref = models.FixedIp()
fixed_ip_ref.update(values)
fixed_ip_ref.save()
return fixed_ip_ref['address']
@require_context
def fixed_ip_disassociate(context, address):
session = get_session()
with session.begin():
fixed_ip_ref = fixed_ip_get_by_address(context,
address,
session=session)
fixed_ip_ref.instance = None
fixed_ip_ref.save(session=session)
@require_admin_context
def fixed_ip_disassociate_all_by_timeout(_context, host, time):
session = get_session()
# NOTE(vish): The nested select is because sqlite doesn't support
# JOINs in UPDATEs.
result = session.execute('UPDATE fixed_ips SET instance_id = NULL, '
'leased = 0 '
'WHERE network_id IN (SELECT id FROM networks '
'WHERE host = :host) '
'AND updated_at < :time '
'AND instance_id IS NOT NULL '
'AND allocated = 0',
{'host': host,
'time': time})
return result.rowcount
@require_admin_context
def fixed_ip_get_all(context, session=None):
if not session:
session = get_session()
result = session.query(models.FixedIp).all()
if not result:
raise exception.NotFound(_('No fixed ips defined'))
return result
@require_context
def fixed_ip_get_by_address(context, address, session=None):
if not session:
session = get_session()
result = session.query(models.FixedIp).\
filter_by(address=address).\
filter_by(deleted=can_read_deleted(context)).\
options(joinedload('network')).\
options(joinedload('instance')).\
first()
if not result:
raise exception.NotFound(_('No floating ip for address %s') % address)
if is_user_context(context):
authorize_project_context(context, result.instance.project_id)
return result
@require_context
def fixed_ip_get_instance(context, address):
fixed_ip_ref = fixed_ip_get_by_address(context, address)
return fixed_ip_ref.instance
@require_context
def fixed_ip_get_all_by_instance(context, instance_id):
session = get_session()
rv = session.query(models.FixedIp).\
filter_by(instance_id=instance_id).\
filter_by(deleted=False)
if not rv:
raise exception.NotFound(_('No address for instance %s') % instance_id)
return rv
@require_context
def fixed_ip_get_instance_v6(context, address):
session = get_session()
mac = utils.to_mac(address)
result = session.query(models.Instance).\
filter_by(mac_address=mac).\
first()
return result
@require_admin_context
def fixed_ip_get_network(context, address):
fixed_ip_ref = fixed_ip_get_by_address(context, address)
return fixed_ip_ref.network
@require_context
def fixed_ip_update(context, address, values):
session = get_session()
with session.begin():
fixed_ip_ref = fixed_ip_get_by_address(context,
address,
session=session)
fixed_ip_ref.update(values)
fixed_ip_ref.save(session=session)
###################
@require_context
def instance_create(context, values):
"""Create a new Instance record in the database.
context - request context object
values - dict containing column values.
"""
instance_ref = models.Instance()
instance_ref.update(values)
session = get_session()
with session.begin():
instance_ref.save(session=session)
return instance_ref
@require_admin_context
def instance_data_get_for_project(context, project_id):
session = get_session()
result = session.query(func.count(models.Instance.id),
func.sum(models.Instance.vcpus)).\
filter_by(project_id=project_id).\
filter_by(deleted=False).\
first()
# NOTE(vish): convert None to 0
return (result[0] or 0, result[1] or 0)
@require_context
def instance_destroy(context, instance_id):
session = get_session()
with session.begin():
session.execute('update instances set deleted=1,'
'deleted_at=:at where id=:id',
{'id': instance_id,
'at': datetime.datetime.utcnow()})
session.execute('update security_group_instance_association '
'set deleted=1,deleted_at=:at where instance_id=:id',
{'id': instance_id,
'at': datetime.datetime.utcnow()})
@require_context
def instance_get(context, instance_id, session=None):
if not session:
session = get_session()
result = None
if is_admin_context(context):
result = session.query(models.Instance).\
options(joinedload_all('fixed_ip.floating_ips')).\
options(joinedload_all('security_groups.rules')).\
options(joinedload('volumes')).\
options(joinedload_all('fixed_ip.network')).\
filter_by(id=instance_id).\
filter_by(deleted=can_read_deleted(context)).\
first()
elif is_user_context(context):
result = session.query(models.Instance).\
options(joinedload_all('fixed_ip.floating_ips')).\
options(joinedload_all('security_groups.rules')).\
options(joinedload('volumes')).\
filter_by(project_id=context.project_id).\
filter_by(id=instance_id).\
filter_by(deleted=False).\
first()
if not result:
raise exception.InstanceNotFound(_('Instance %s not found')
% instance_id,
instance_id)
return result
@require_admin_context
def instance_get_all(context):
session = get_session()
return session.query(models.Instance).\
options(joinedload_all('fixed_ip.floating_ips')).\
options(joinedload('security_groups')).\
options(joinedload_all('fixed_ip.network')).\
filter_by(deleted=can_read_deleted(context)).\
all()
@require_admin_context
def instance_get_all_by_user(context, user_id):
session = get_session()
return session.query(models.Instance).\
options(joinedload_all('fixed_ip.floating_ips')).\
options(joinedload('security_groups')).\
options(joinedload_all('fixed_ip.network')).\
filter_by(deleted=can_read_deleted(context)).\
filter_by(user_id=user_id).\
all()
@require_admin_context
def instance_get_all_by_host(context, host):
session = get_session()
return session.query(models.Instance).\
options(joinedload_all('fixed_ip.floating_ips')).\
options(joinedload('security_groups')).\
options(joinedload_all('fixed_ip.network')).\
filter_by(host=host).\
filter_by(deleted=can_read_deleted(context)).\
all()
@require_context
def instance_get_all_by_project(context, project_id):
authorize_project_context(context, project_id)
session = get_session()
return session.query(models.Instance).\
options(joinedload_all('fixed_ip.floating_ips')).\
options(joinedload('security_groups')).\
options(joinedload_all('fixed_ip.network')).\
filter_by(project_id=project_id).\
filter_by(deleted=can_read_deleted(context)).\
all()
@require_context
def instance_get_all_by_reservation(context, reservation_id):
session = get_session()
if is_admin_context(context):
return session.query(models.Instance).\
options(joinedload_all('fixed_ip.floating_ips')).\
options(joinedload('security_groups')).\
options(joinedload_all('fixed_ip.network')).\
filter_by(reservation_id=reservation_id).\
filter_by(deleted=can_read_deleted(context)).\
all()
elif is_user_context(context):
return session.query(models.Instance).\
options(joinedload_all('fixed_ip.floating_ips')).\
options(joinedload('security_groups')).\
options(joinedload_all('fixed_ip.network')).\
filter_by(project_id=context.project_id).\
filter_by(reservation_id=reservation_id).\
filter_by(deleted=False).\
all()
@require_admin_context
def instance_get_project_vpn(context, project_id):
session = get_session()
return session.query(models.Instance).\
options(joinedload_all('fixed_ip.floating_ips')).\
options(joinedload('security_groups')).\
filter_by(project_id=project_id).\
filter_by(image_id=FLAGS.vpn_image_id).\
filter_by(deleted=can_read_deleted(context)).\
first()
@require_context
def instance_get_fixed_address(context, instance_id):
session = get_session()
with session.begin():
instance_ref = instance_get(context, instance_id, session=session)
if not instance_ref.fixed_ip:
return None
return instance_ref.fixed_ip['address']
@require_context
def instance_get_fixed_address_v6(context, instance_id):
session = get_session()
with session.begin():
instance_ref = instance_get(context, instance_id, session=session)
network_ref = network_get_by_instance(context, instance_id)
prefix = network_ref.cidr_v6
mac = instance_ref.mac_address
return utils.to_global_ipv6(prefix, mac)
@require_context
def instance_get_floating_address(context, instance_id):
session = get_session()
with session.begin():
instance_ref = instance_get(context, instance_id, session=session)
if not instance_ref.fixed_ip:
return None
if not instance_ref.fixed_ip.floating_ips:
return None
# NOTE(vish): this just returns the first floating ip
return instance_ref.fixed_ip.floating_ips[0]['address']
@require_admin_context
def instance_is_vpn(context, instance_id):
# TODO(vish): Move this into image code somewhere
instance_ref = instance_get(context, instance_id)
return instance_ref['image_id'] == FLAGS.vpn_image_id
@require_admin_context
def instance_set_state(context, instance_id, state, description=None):
# TODO(devcamcar): Move this out of models and into driver
from nova.compute import power_state
if not description:
description = power_state.name(state)
db.instance_update(context,
instance_id,
{'state': state,
'state_description': description})
@require_context
def instance_update(context, instance_id, values):
session = get_session()
with session.begin():
instance_ref = instance_get(context, instance_id, session=session)
instance_ref.update(values)
instance_ref.save(session=session)
return instance_ref
def instance_add_security_group(context, instance_id, security_group_id):
"""Associate the given security group with the given instance"""
session = get_session()
with session.begin():
instance_ref = instance_get(context, instance_id, session=session)
security_group_ref = security_group_get(context,
security_group_id,
session=session)
instance_ref.security_groups += [security_group_ref]
instance_ref.save(session=session)
@require_context
def instance_action_create(context, values):
"""Create an instance action from the values dictionary."""
action_ref = models.InstanceActions()
action_ref.update(values)
session = get_session()
with session.begin():
action_ref.save(session=session)
return action_ref
@require_admin_context
def instance_get_actions(context, instance_id):
"""Return the actions associated to the given instance id"""
session = get_session()
return session.query(models.InstanceActions).\
filter_by(instance_id=instance_id).\
all()
###################
@require_context
def key_pair_create(context, values):
key_pair_ref = models.KeyPair()
key_pair_ref.update(values)
key_pair_ref.save()
return key_pair_ref
@require_context
def key_pair_destroy(context, user_id, name):
authorize_user_context(context, user_id)
session = get_session()
with session.begin():
key_pair_ref = key_pair_get(context, user_id, name, session=session)
key_pair_ref.delete(session=session)
@require_context
def key_pair_destroy_all_by_user(context, user_id):
authorize_user_context(context, user_id)
session = get_session()
with session.begin():
# TODO(vish): do we have to use sql here?
session.execute('update key_pairs set deleted=1 where user_id=:id',
{'id': user_id})
@require_context
def key_pair_get(context, user_id, name, session=None):
authorize_user_context(context, user_id)
if not session:
session = get_session()
result = session.query(models.KeyPair).\
filter_by(user_id=user_id).\
filter_by(name=name).\
filter_by(deleted=can_read_deleted(context)).\
first()
if not result:
raise exception.NotFound(_('no keypair for user %(user_id)s,'
' name %(name)s') % locals())
return result
@require_context
def key_pair_get_all_by_user(context, user_id):
authorize_user_context(context, user_id)
session = get_session()
return session.query(models.KeyPair).\
filter_by(user_id=user_id).\
filter_by(deleted=False).\
all()
###################
@require_admin_context
def network_associate(context, project_id):
session = get_session()
with session.begin():
network_ref = session.query(models.Network).\
filter_by(deleted=False).\
filter_by(project_id=None).\
with_lockmode('update').\
first()
# NOTE(vish): if with_lockmode isn't supported, as in sqlite,
# then this has concurrency issues
if not network_ref:
raise db.NoMoreNetworks()
network_ref['project_id'] = project_id
session.add(network_ref)
return network_ref
@require_admin_context
def network_count(context):
session = get_session()
return session.query(models.Network).\
filter_by(deleted=can_read_deleted(context)).\
count()
@require_admin_context
def network_count_allocated_ips(context, network_id):
session = get_session()
return session.query(models.FixedIp).\
filter_by(network_id=network_id).\
filter_by(allocated=True).\
filter_by(deleted=False).\
count()
@require_admin_context
def network_count_available_ips(context, network_id):
session = get_session()
return session.query(models.FixedIp).\
filter_by(network_id=network_id).\
filter_by(allocated=False).\
filter_by(reserved=False).\
filter_by(deleted=False).\
count()
@require_admin_context
def network_count_reserved_ips(context, network_id):
session = get_session()
return session.query(models.FixedIp).\
filter_by(network_id=network_id).\
filter_by(reserved=True).\
filter_by(deleted=False).\
count()
@require_admin_context
def network_create_safe(context, values):
network_ref = models.Network()
network_ref.update(values)
try:
network_ref.save()
return network_ref
except IntegrityError:
return None
@require_admin_context
def network_disassociate(context, network_id):
network_update(context, network_id, {'project_id': None})
@require_admin_context
def network_disassociate_all(context):
session = get_session()
session.execute('update networks set project_id=NULL')
@require_context
def network_get(context, network_id, session=None):
if not session:
session = get_session()
result = None
if is_admin_context(context):
result = session.query(models.Network).\
filter_by(id=network_id).\
filter_by(deleted=can_read_deleted(context)).\
first()
elif is_user_context(context):
result = session.query(models.Network).\
filter_by(project_id=context.project_id).\
filter_by(id=network_id).\
filter_by(deleted=False).\
first()
if not result:
raise exception.NotFound(_('No network for id %s') % network_id)
return result
@require_admin_context
def network_get_all(context):
session = get_session()
result = session.query(models.Network)
if not result:
raise exception.NotFound(_('No networks defined'))
return result
# NOTE(vish): pylint complains because of the long method name, but
# it fits with the names of the rest of the methods
# pylint: disable-msg=C0103
@require_admin_context
def network_get_associated_fixed_ips(context, network_id):
session = get_session()
return session.query(models.FixedIp).\
options(joinedload_all('instance')).\
filter_by(network_id=network_id).\
filter(models.FixedIp.instance_id != None).\
filter_by(deleted=False).\
all()
@require_admin_context
def network_get_by_bridge(context, bridge):
session = get_session()
result = session.query(models.Network).\
filter_by(bridge=bridge).\
filter_by(deleted=False).\
first()
if not result:
raise exception.NotFound(_('No network for bridge %s') % bridge)
return result
@require_admin_context
def network_get_by_instance(_context, instance_id):
session = get_session()
rv = session.query(models.Network).\
filter_by(deleted=False).\
join(models.Network.fixed_ips).\
filter_by(instance_id=instance_id).\
filter_by(deleted=False).\
first()
if not rv:
raise exception.NotFound(_('No network for instance %s') % instance_id)
return rv
@require_admin_context
def network_get_all_by_instance(_context, instance_id):
session = get_session()
rv = session.query(models.Network).\
filter_by(deleted=False).\
join(models.Network.fixed_ips).\
filter_by(instance_id=instance_id).\
filter_by(deleted=False)
if not rv:
raise exception.NotFound(_('No network for instance %s') % instance_id)
return rv
@require_admin_context
def network_set_host(context, network_id, host_id):
session = get_session()
with session.begin():
network_ref = session.query(models.Network).\
filter_by(id=network_id).\
filter_by(deleted=False).\
with_lockmode('update').\
first()
if not network_ref:
raise exception.NotFound(_('No network for id %s') % network_id)
# NOTE(vish): if with_lockmode isn't supported, as in sqlite,
# then this has concurrency issues
if not network_ref['host']:
network_ref['host'] = host_id
session.add(network_ref)
return network_ref['host']
@require_context
def network_update(context, network_id, values):
session = get_session()
with session.begin():
network_ref = network_get(context, network_id, session=session)
network_ref.update(values)
network_ref.save(session=session)
###################
@require_context
def project_get_network(context, project_id, associate=True):
session = get_session()
result = session.query(models.Network).\
filter_by(project_id=project_id).\
filter_by(deleted=False).\
first()
if not result:
if not associate:
return None
try:
return network_associate(context, project_id)
except IntegrityError:
# NOTE(vish): We hit this if there is a race and two
# processes are attempting to allocate the
# network at the same time
result = session.query(models.Network).\
filter_by(project_id=project_id).\
filter_by(deleted=False).\
first()
return result
@require_context
def project_get_network_v6(context, project_id):
return project_get_network(context, project_id)
###################
def queue_get_for(_context, topic, physical_node_id):
# FIXME(ja): this should be servername?
return "%s.%s" % (topic, physical_node_id)
###################
@require_admin_context
def export_device_count(context):
session = get_session()
return session.query(models.ExportDevice).\
filter_by(deleted=can_read_deleted(context)).\
count()
@require_admin_context
def export_device_create_safe(context, values):
export_device_ref = models.ExportDevice()
export_device_ref.update(values)
try:
export_device_ref.save()
return export_device_ref
except IntegrityError:
return None
###################
@require_admin_context
def iscsi_target_count_by_host(context, host):
session = get_session()
return session.query(models.IscsiTarget).\
filter_by(deleted=can_read_deleted(context)).\
filter_by(host=host).\
count()
@require_admin_context
def iscsi_target_create_safe(context, values):
iscsi_target_ref = models.IscsiTarget()
for (key, value) in values.iteritems():
iscsi_target_ref[key] = value
try:
iscsi_target_ref.save()
return iscsi_target_ref
except IntegrityError:
return None
###################
@require_admin_context
def auth_destroy_token(_context, token):
session = get_session()
session.delete(token)
@require_admin_context
def auth_get_token(_context, token_hash):
session = get_session()
tk = session.query(models.AuthToken).\
filter_by(token_hash=token_hash).\
first()
if not tk:
raise exception.NotFound(_('Token %s does not exist') % token_hash)
return tk
@require_admin_context
def auth_create_token(_context, token):
tk = models.AuthToken()
tk.update(token)
tk.save()
return tk
###################
@require_admin_context
def quota_get(context, project_id, session=None):
if not session:
session = get_session()
result = session.query(models.Quota).\
filter_by(project_id=project_id).\
filter_by(deleted=can_read_deleted(context)).\
first()
if not result:
raise exception.NotFound(_('No quota for project_id %s') % project_id)
return result
@require_admin_context
def quota_create(context, values):
quota_ref = models.Quota()
quota_ref.update(values)
quota_ref.save()
return quota_ref
@require_admin_context
def quota_update(context, project_id, values):
session = get_session()
with session.begin():
quota_ref = quota_get(context, project_id, session=session)
quota_ref.update(values)
quota_ref.save(session=session)
@require_admin_context
def quota_destroy(context, project_id):
session = get_session()
with session.begin():
quota_ref = quota_get(context, project_id, session=session)
quota_ref.delete(session=session)
###################
@require_admin_context
def volume_allocate_shelf_and_blade(context, volume_id):
session = get_session()
with session.begin():
export_device = session.query(models.ExportDevice).\
filter_by(volume=None).\
filter_by(deleted=False).\
with_lockmode('update').\
first()
# NOTE(vish): if with_lockmode isn't supported, as in sqlite,
# then this has concurrency issues
if not export_device:
raise db.NoMoreBlades()
export_device.volume_id = volume_id
session.add(export_device)
return (export_device.shelf_id, export_device.blade_id)
@require_admin_context
def volume_allocate_iscsi_target(context, volume_id, host):
session = get_session()
with session.begin():
iscsi_target_ref = session.query(models.IscsiTarget).\
filter_by(volume=None).\
filter_by(host=host).\
filter_by(deleted=False).\
with_lockmode('update').\
first()
# NOTE(vish): if with_lockmode isn't supported, as in sqlite,
# then this has concurrency issues
if not iscsi_target_ref:
raise db.NoMoreTargets()
iscsi_target_ref.volume_id = volume_id
session.add(iscsi_target_ref)
return iscsi_target_ref.target_num
@require_admin_context
def volume_attached(context, volume_id, instance_id, mountpoint):
session = get_session()
with session.begin():
volume_ref = volume_get(context, volume_id, session=session)
volume_ref['status'] = 'in-use'
volume_ref['mountpoint'] = mountpoint
volume_ref['attach_status'] = 'attached'
volume_ref.instance = instance_get(context, instance_id,
session=session)
volume_ref.save(session=session)
@require_context
def volume_create(context, values):
volume_ref = models.Volume()
volume_ref.update(values)
session = get_session()
with session.begin():
volume_ref.save(session=session)
return volume_ref
@require_admin_context
def volume_data_get_for_project(context, project_id):
session = get_session()
result = session.query(func.count(models.Volume.id),
func.sum(models.Volume.size)).\
filter_by(project_id=project_id).\
filter_by(deleted=False).\
first()
# NOTE(vish): convert None to 0
return (result[0] or 0, result[1] or 0)
@require_admin_context
def volume_destroy(context, volume_id):
session = get_session()
with session.begin():
# TODO(vish): do we have to use sql here?
session.execute('update volumes set deleted=1 where id=:id',
{'id': volume_id})
session.execute('update export_devices set volume_id=NULL '
'where volume_id=:id',
{'id': volume_id})
session.execute('update iscsi_targets set volume_id=NULL '
'where volume_id=:id',
{'id': volume_id})
@require_admin_context
def volume_detached(context, volume_id):
session = get_session()
with session.begin():
volume_ref = volume_get(context, volume_id, session=session)
volume_ref['status'] = 'available'
volume_ref['mountpoint'] = None
volume_ref['attach_status'] = 'detached'
volume_ref.instance = None
volume_ref.save(session=session)
@require_context
def volume_get(context, volume_id, session=None):
if not session:
session = get_session()
result = None
if is_admin_context(context):
result = session.query(models.Volume).\
options(joinedload('instance')).\
filter_by(id=volume_id).\
filter_by(deleted=can_read_deleted(context)).\
first()
elif is_user_context(context):
result = session.query(models.Volume).\
options(joinedload('instance')).\
filter_by(project_id=context.project_id).\
filter_by(id=volume_id).\
filter_by(deleted=False).\
first()
if not result:
raise exception.VolumeNotFound(_('Volume %s not found') % volume_id,
volume_id)
return result
@require_admin_context
def volume_get_all(context):
session = get_session()
return session.query(models.Volume).\
options(joinedload('instance')).\
filter_by(deleted=can_read_deleted(context)).\
all()
@require_admin_context
def volume_get_all_by_host(context, host):
session = get_session()
return session.query(models.Volume).\
options(joinedload('instance')).\
filter_by(host=host).\
filter_by(deleted=can_read_deleted(context)).\
all()
@require_context
def volume_get_all_by_project(context, project_id):
authorize_project_context(context, project_id)
session = get_session()
return session.query(models.Volume).\
options(joinedload('instance')).\
filter_by(project_id=project_id).\
filter_by(deleted=can_read_deleted(context)).\
all()
@require_admin_context
def volume_get_instance(context, volume_id):
session = get_session()
result = session.query(models.Volume).\
filter_by(id=volume_id).\
filter_by(deleted=can_read_deleted(context)).\
options(joinedload('instance')).\
first()
if not result:
raise exception.VolumeNotFound(_('Volume %s not found') % volume_id,
volume_id)
return result.instance
@require_admin_context
def volume_get_shelf_and_blade(context, volume_id):
session = get_session()
result = session.query(models.ExportDevice).\
filter_by(volume_id=volume_id).\
first()
if not result:
raise exception.NotFound(_('No export device found for volume %s') %
volume_id)
return (result.shelf_id, result.blade_id)
@require_admin_context
def volume_get_iscsi_target_num(context, volume_id):
session = get_session()
result = session.query(models.IscsiTarget).\
filter_by(volume_id=volume_id).\
first()
if not result:
raise exception.NotFound(_('No target id found for volume %s') %
volume_id)
return result.target_num
@require_context
def volume_update(context, volume_id, values):
session = get_session()
with session.begin():
volume_ref = volume_get(context, volume_id, session=session)
volume_ref.update(values)
volume_ref.save(session=session)
###################
@require_context
def security_group_get_all(context):
session = get_session()
return session.query(models.SecurityGroup).\
filter_by(deleted=can_read_deleted(context)).\
options(joinedload_all('rules')).\
all()
@require_context
def security_group_get(context, security_group_id, session=None):
if not session:
session = get_session()
if is_admin_context(context):
result = session.query(models.SecurityGroup).\
filter_by(deleted=can_read_deleted(context),).\
filter_by(id=security_group_id).\
options(joinedload_all('rules')).\
first()
else:
result = session.query(models.SecurityGroup).\
filter_by(deleted=False).\
filter_by(id=security_group_id).\
filter_by(project_id=context.project_id).\
options(joinedload_all('rules')).\
first()
if not result:
raise exception.NotFound(_("No security group with id %s") %
security_group_id)
return result
@require_context
def security_group_get_by_name(context, project_id, group_name):
session = get_session()
result = session.query(models.SecurityGroup).\
filter_by(project_id=project_id).\
filter_by(name=group_name).\
filter_by(deleted=False).\
options(joinedload_all('rules')).\
options(joinedload_all('instances')).\
first()
if not result:
raise exception.NotFound(
_('No security group named %(group_name)s'
' for project: %(project_id)s') % locals())
return result
@require_context
def security_group_get_by_project(context, project_id):
session = get_session()
return session.query(models.SecurityGroup).\
filter_by(project_id=project_id).\
filter_by(deleted=False).\
options(joinedload_all('rules')).\
all()
@require_context
def security_group_get_by_instance(context, instance_id):
session = get_session()
return session.query(models.SecurityGroup).\
filter_by(deleted=False).\
options(joinedload_all('rules')).\
join(models.SecurityGroup.instances).\
filter_by(id=instance_id).\
filter_by(deleted=False).\
all()
@require_context
def security_group_exists(context, project_id, group_name):
try:
group = security_group_get_by_name(context, project_id, group_name)
return group != None
except exception.NotFound:
return False
@require_context
def security_group_create(context, values):
security_group_ref = models.SecurityGroup()
# FIXME(devcamcar): Unless I do this, rules fails with lazy load exception
# once save() is called. This will get cleaned up in next orm pass.
security_group_ref.rules
security_group_ref.update(values)
security_group_ref.save()
return security_group_ref
@require_context
def security_group_destroy(context, security_group_id):
session = get_session()
with session.begin():
# TODO(vish): do we have to use sql here?
session.execute('update security_groups set deleted=1 where id=:id',
{'id': security_group_id})
session.execute('update security_group_instance_association '
'set deleted=1,deleted_at=:at '
'where security_group_id=:id',
{'id': security_group_id,
'at': datetime.datetime.utcnow()})
session.execute('update security_group_rules set deleted=1 '
'where group_id=:id',
{'id': security_group_id})
@require_context
def security_group_destroy_all(context, session=None):
if not session:
session = get_session()
with session.begin():
# TODO(vish): do we have to use sql here?
session.execute('update security_groups set deleted=1')
session.execute('update security_group_rules set deleted=1')
###################
@require_context
def security_group_rule_get(context, security_group_rule_id, session=None):
if not session:
session = get_session()
if is_admin_context(context):
result = session.query(models.SecurityGroupIngressRule).\
filter_by(deleted=can_read_deleted(context)).\
filter_by(id=security_group_rule_id).\
first()
else:
# TODO(vish): Join to group and check for project_id
result = session.query(models.SecurityGroupIngressRule).\
filter_by(deleted=False).\
filter_by(id=security_group_rule_id).\
first()
if not result:
raise exception.NotFound(_("No secuity group rule with id %s") %
security_group_rule_id)
return result
@require_context
def security_group_rule_get_by_security_group(context, security_group_id,
session=None):
if not session:
session = get_session()
if is_admin_context(context):
result = session.query(models.SecurityGroupIngressRule).\
filter_by(deleted=can_read_deleted(context)).\
filter_by(parent_group_id=security_group_id).\
all()
else:
# TODO(vish): Join to group and check for project_id
result = session.query(models.SecurityGroupIngressRule).\
filter_by(deleted=False).\
filter_by(parent_group_id=security_group_id).\
all()
return result
@require_context
def security_group_rule_get_by_security_group_grantee(context,
security_group_id,
session=None):
if not session:
session = get_session()
if is_admin_context(context):
result = session.query(models.SecurityGroupIngressRule).\
filter_by(deleted=can_read_deleted(context)).\
filter_by(group_id=security_group_id).\
all()
else:
result = session.query(models.SecurityGroupIngressRule).\
filter_by(deleted=False).\
filter_by(group_id=security_group_id).\
all()
return result
@require_context
def security_group_rule_create(context, values):
security_group_rule_ref = models.SecurityGroupIngressRule()
security_group_rule_ref.update(values)
security_group_rule_ref.save()
return security_group_rule_ref
@require_context
def security_group_rule_destroy(context, security_group_rule_id):
session = get_session()
with session.begin():
security_group_rule = security_group_rule_get(context,
security_group_rule_id,
session=session)
security_group_rule.delete(session=session)
###################
@require_admin_context
def user_get(context, id, session=None):
if not session:
session = get_session()
result = session.query(models.User).\
filter_by(id=id).\
filter_by(deleted=can_read_deleted(context)).\
first()
if not result:
raise exception.NotFound(_('No user for id %s') % id)
return result
@require_admin_context
def user_get_by_access_key(context, access_key, session=None):
if not session:
session = get_session()
result = session.query(models.User).\
filter_by(access_key=access_key).\
filter_by(deleted=can_read_deleted(context)).\
first()
if not result:
raise exception.NotFound(_('No user for access key %s') % access_key)
return result
@require_admin_context
def user_create(_context, values):
user_ref = models.User()
user_ref.update(values)
user_ref.save()
return user_ref
@require_admin_context
def user_delete(context, id):
session = get_session()
with session.begin():
session.execute('delete from user_project_association '
'where user_id=:id', {'id': id})
session.execute('delete from user_role_association '
'where user_id=:id', {'id': id})
session.execute('delete from user_project_role_association '
'where user_id=:id', {'id': id})
user_ref = user_get(context, id, session=session)
session.delete(user_ref)
def user_get_all(context):
session = get_session()
return session.query(models.User).\
filter_by(deleted=can_read_deleted(context)).\
all()
def project_create(_context, values):
project_ref = models.Project()
project_ref.update(values)
project_ref.save()
return project_ref
def project_add_member(context, project_id, user_id):
session = get_session()
with session.begin():
project_ref = project_get(context, project_id, session=session)
user_ref = user_get(context, user_id, session=session)
project_ref.members += [user_ref]
project_ref.save(session=session)
def project_get(context, id, session=None):
if not session:
session = get_session()
result = session.query(models.Project).\
filter_by(deleted=False).\
filter_by(id=id).\
options(joinedload_all('members')).\
first()
if not result:
raise exception.NotFound(_("No project with id %s") % id)
return result
def project_get_all(context):
session = get_session()
return session.query(models.Project).\
filter_by(deleted=can_read_deleted(context)).\
options(joinedload_all('members')).\
all()
def project_get_by_user(context, user_id):
session = get_session()
user = session.query(models.User).\
filter_by(deleted=can_read_deleted(context)).\
options(joinedload_all('projects')).\
first()
return user.projects
def project_remove_member(context, project_id, user_id):
session = get_session()
project = project_get(context, project_id, session=session)
user = user_get(context, user_id, session=session)
if user in project.members:
project.members.remove(user)
project.save(session=session)
def user_update(context, user_id, values):
session = get_session()
with session.begin():
user_ref = user_get(context, user_id, session=session)
user_ref.update(values)
user_ref.save(session=session)
def project_update(context, project_id, values):
session = get_session()
with session.begin():
project_ref = project_get(context, project_id, session=session)
project_ref.update(values)
project_ref.save(session=session)
def project_delete(context, id):
session = get_session()
with session.begin():
session.execute('delete from user_project_association '
'where project_id=:id', {'id': id})
session.execute('delete from user_project_role_association '
'where project_id=:id', {'id': id})
project_ref = project_get(context, id, session=session)
session.delete(project_ref)
def user_get_roles(context, user_id):
session = get_session()
with session.begin():
user_ref = user_get(context, user_id, session=session)
return [role.role for role in user_ref['roles']]
def user_get_roles_for_project(context, user_id, project_id):
session = get_session()
with session.begin():
res = session.query(models.UserProjectRoleAssociation).\
filter_by(user_id=user_id).\
filter_by(project_id=project_id).\
all()
return [association.role for association in res]
def user_remove_project_role(context, user_id, project_id, role):
session = get_session()
with session.begin():
session.execute('delete from user_project_role_association where '
'user_id=:user_id and project_id=:project_id and '
'role=:role', {'user_id': user_id,
'project_id': project_id,
'role': role})
def user_remove_role(context, user_id, role):
session = get_session()
with session.begin():
res = session.query(models.UserRoleAssociation).\
filter_by(user_id=user_id).\
filter_by(role=role).\
all()
for role in res:
session.delete(role)
def user_add_role(context, user_id, role):
session = get_session()
with session.begin():
user_ref = user_get(context, user_id, session=session)
models.UserRoleAssociation(user=user_ref, role=role).\
save(session=session)
def user_add_project_role(context, user_id, project_id, role):
session = get_session()
with session.begin():
user_ref = user_get(context, user_id, session=session)
project_ref = project_get(context, project_id, session=session)
models.UserProjectRoleAssociation(user_id=user_ref['id'],
project_id=project_ref['id'],
role=role).save(session=session)
###################
@require_admin_context
def host_get_networks(context, host):
session = get_session()
with session.begin():
return session.query(models.Network).\
filter_by(deleted=False).\
filter_by(host=host).\
all()
##################
def console_pool_create(context, values):
pool = models.ConsolePool()
pool.update(values)
pool.save()
return pool
def console_pool_get(context, pool_id):
session = get_session()
result = session.query(models.ConsolePool).\
filter_by(deleted=False).\
filter_by(id=pool_id).\
first()
if not result:
raise exception.NotFound(_("No console pool with id %(pool_id)s")
% locals())
return result
def console_pool_get_by_host_type(context, compute_host, host,
console_type):
session = get_session()
result = session.query(models.ConsolePool).\
filter_by(host=host).\
filter_by(console_type=console_type).\
filter_by(compute_host=compute_host).\
filter_by(deleted=False).\
options(joinedload('consoles')).\
first()
if not result:
raise exception.NotFound(_('No console pool of type %(console_type)s '
'for compute host %(compute_host)s '
'on proxy host %(host)s') % locals())
return result
def console_pool_get_all_by_host_type(context, host, console_type):
session = get_session()
return session.query(models.ConsolePool).\
filter_by(host=host).\
filter_by(console_type=console_type).\
filter_by(deleted=False).\
options(joinedload('consoles')).\
all()
def console_create(context, values):
console = models.Console()
console.update(values)
console.save()
return console
def console_delete(context, console_id):
session = get_session()
with session.begin():
# consoles are meant to be transient. (mdragon)
session.execute('delete from consoles '
'where id=:id', {'id': console_id})
def console_get_by_pool_instance(context, pool_id, instance_id):
session = get_session()
result = session.query(models.Console).\
filter_by(pool_id=pool_id).\
filter_by(instance_id=instance_id).\
options(joinedload('pool')).\
first()
if not result:
raise exception.NotFound(_('No console for instance %(instance_id)s '
'in pool %(pool_id)s') % locals())
return result
def console_get_all_by_instance(context, instance_id):
session = get_session()
results = session.query(models.Console).\
filter_by(instance_id=instance_id).\
options(joinedload('pool')).\
all()
return results
def console_get(context, console_id, instance_id=None):
session = get_session()
query = session.query(models.Console).\
filter_by(id=console_id)
if instance_id:
query = query.filter_by(instance_id=instance_id)
result = query.options(joinedload('pool')).first()
if not result:
idesc = (_("on instance %s") % instance_id) if instance_id else ""
raise exception.NotFound(_("No console with id %(console_id)s"
" %(idesc)s") % locals())
return result
####################
@require_admin_context
def zone_create(context, values):
zone = models.Zone()
zone.update(values)
zone.save()
return zone
@require_admin_context
def zone_update(context, zone_id, values):
zone = session.query(models.Zone).filter_by(id=zone_id).first()
if not zone:
raise exception.NotFound(_("No zone with id %(zone_id)s") % locals())
zone.update(values)
zone.save()
return zone
@require_admin_context
def zone_delete(context, zone_id):
session = get_session()
with session.begin():
session.execute('delete from zones '
'where id=:id', {'id': zone_id})
@require_admin_context
def zone_get(context, zone_id):
session = get_session()
result = session.query(models.Zone).filter_by(id=zone_id).first()
if not result:
raise exception.NotFound(_("No zone with id %(zone_id)s") % locals())
return result
@require_admin_context
def zone_get_all(context):
session = get_session()
return session.query(models.Zone).all()
| Python |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""
SQLAlchemy models for nova data.
"""
import datetime
from sqlalchemy.orm import relationship, backref, object_mapper
from sqlalchemy import Column, Integer, String, schema
from sqlalchemy import ForeignKey, DateTime, Boolean, Text
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.schema import ForeignKeyConstraint
from fractus.db.sqlalchemy.session import get_session
from fractus import auth
from fractus import exception
from fractus import flags
FLAGS = flags.FLAGS
BASE = declarative_base()
class FractusBase(object):
"""Base class for Fractus Models."""
__table_args__ = {'mysql_engine': 'InnoDB'}
__table_initialized__ = False
created_at = Column(DateTime, default=datetime.datetime.utcnow)
updated_at = Column(DateTime, onupdate=datetime.datetime.utcnow)
deleted_at = Column(DateTime)
deleted = Column(Boolean, default=False)
def save(self, session=None):
"""Save this object."""
if not session:
session = get_session()
session.add(self)
try:
session.flush()
except IntegrityError, e:
if str(e).endswith('is not unique'):
raise exception.Duplicate(str(e))
else:
raise
def delete(self, session=None):
"""Delete this object."""
self.deleted = True
self.deleted_at = datetime.datetime.utcnow()
self.save(session=session)
def __setitem__(self, key, value):
setattr(self, key, value)
def __getitem__(self, key):
return getattr(self, key)
def get(self, key, default=None):
return getattr(self, key, default)
def __iter__(self):
self._i = iter(object_mapper(self).columns)
return self
def next(self):
n = self._i.next().name
return n, getattr(self, n)
def update(self, values):
"""Make the model object behave like a dict"""
for k, v in values.iteritems():
setattr(self, k, v)
def iteritems(self):
"""Make the model object behave like a dict.
Includes attributes from joins."""
local = dict(self)
joined = dict([(k, v) for k, v in self.__dict__.iteritems()
if not k[0] == '_'])
local.update(joined)
return local.iteritems()
class Service(BASE, FractusBase):
"""Represents a running service on a host."""
__tablename__ = 'services'
id = Column(Integer, primary_key=True)
host = Column(String(255)) # , ForeignKey('hosts.id'))
binary = Column(String(255))
topic = Column(String(255))
report_count = Column(Integer, nullable=False, default=0)
disabled = Column(Boolean, default=False)
availability_zone = Column(String(255), default='nova')
class Certificate(BASE, FractusBase):
"""Represents a an x509 certificate"""
__tablename__ = 'certificates'
id = Column(Integer, primary_key=True)
user_id = Column(String(255))
project_id = Column(String(255))
file_name = Column(String(255))
class Node(BASE, FractusBase):
"""Represents a node (machine managed)."""
__tablename__ = 'nodes'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(255))
ip = Column(String(255))
os = Column(String(255))
class Instance(BASE, FractusBase):
"""Represents a guest vm."""
__tablename__ = 'instances'
id = Column(Integer, primary_key=True, autoincrement=True)
@property
def name(self):
return FLAGS.instance_name_template % self.id
admin_pass = Column(String(255))
user_id = Column(String(255))
project_id = Column(String(255))
@property
def user(self):
return auth.manager.AuthManager().get_user(self.user_id)
@property
def project(self):
return auth.manager.AuthManager().get_project(self.project_id)
image_id = Column(String(255))
kernel_id = Column(String(255))
ramdisk_id = Column(String(255))
# image_id = Column(Integer, ForeignKey('images.id'), nullable=True)
# kernel_id = Column(Integer, ForeignKey('images.id'), nullable=True)
# ramdisk_id = Column(Integer, ForeignKey('images.id'), nullable=True)
# ramdisk = relationship(Ramdisk, backref=backref('instances', order_by=id))
# kernel = relationship(Kernel, backref=backref('instances', order_by=id))
# project = relationship(Project, backref=backref('instances', order_by=id))
launch_index = Column(Integer)
key_name = Column(String(255))
key_data = Column(Text)
state = Column(Integer)
state_description = Column(String(255))
memory_mb = Column(Integer)
vcpus = Column(Integer)
local_gb = Column(Integer)
hostname = Column(String(255))
host = Column(String(255)) # , ForeignKey('hosts.id'))
instance_type = Column(String(255))
user_data = Column(Text)
reservation_id = Column(String(255))
mac_address = Column(String(255))
scheduled_at = Column(DateTime)
launched_at = Column(DateTime)
terminated_at = Column(DateTime)
availability_zone = Column(String(255))
# User editable field for display in user-facing UIs
display_name = Column(String(255))
display_description = Column(String(255))
locked = Column(Boolean)
# TODO(vish): see Ewan's email about state improvements, probably
# should be in a driver base class or some such
# vmstate_state = running, halted, suspended, paused
# power_state = what we have
# task_state = transitory and may trigger power state transition
#@validates('state')
#def validate_state(self, key, state):
# assert(state in ['nostate', 'running', 'blocked', 'paused',
# 'shutdown', 'shutoff', 'crashed'])
class InstanceActions(BASE, FractusBase):
"""Represents a guest VM's actions and results"""
__tablename__ = "instance_actions"
id = Column(Integer, primary_key=True)
instance_id = Column(Integer, ForeignKey('instances.id'))
action = Column(String(255))
error = Column(Text)
class Volume(BASE, FractusBase):
"""Represents a block storage device that can be attached to a vm."""
__tablename__ = 'volumes'
id = Column(Integer, primary_key=True, autoincrement=True)
@property
def name(self):
return FLAGS.volume_name_template % self.id
user_id = Column(String(255))
project_id = Column(String(255))
host = Column(String(255)) # , ForeignKey('hosts.id'))
size = Column(Integer)
availability_zone = Column(String(255)) # TODO(vish): foreign key?
instance_id = Column(Integer, ForeignKey('instances.id'), nullable=True)
instance = relationship(Instance,
backref=backref('volumes'),
foreign_keys=instance_id,
primaryjoin='and_(Volume.instance_id==Instance.id,'
'Volume.deleted==False)')
mountpoint = Column(String(255))
attach_time = Column(String(255)) # TODO(vish): datetime
status = Column(String(255)) # TODO(vish): enum?
attach_status = Column(String(255)) # TODO(vish): enum
scheduled_at = Column(DateTime)
launched_at = Column(DateTime)
terminated_at = Column(DateTime)
display_name = Column(String(255))
display_description = Column(String(255))
class Quota(BASE, FractusBase):
"""Represents quota overrides for a project."""
__tablename__ = 'quotas'
id = Column(Integer, primary_key=True)
project_id = Column(String(255))
instances = Column(Integer)
cores = Column(Integer)
volumes = Column(Integer)
gigabytes = Column(Integer)
floating_ips = Column(Integer)
class ExportDevice(BASE, FractusBase):
"""Represates a shelf and blade that a volume can be exported on."""
__tablename__ = 'export_devices'
__table_args__ = (schema.UniqueConstraint("shelf_id", "blade_id"),
{'mysql_engine': 'InnoDB'})
id = Column(Integer, primary_key=True)
shelf_id = Column(Integer)
blade_id = Column(Integer)
volume_id = Column(Integer, ForeignKey('volumes.id'), nullable=True)
volume = relationship(Volume,
backref=backref('export_device', uselist=False),
foreign_keys=volume_id,
primaryjoin='and_(ExportDevice.volume_id==Volume.id,'
'ExportDevice.deleted==False)')
class IscsiTarget(BASE, FractusBase):
"""Represates an iscsi target for a given host"""
__tablename__ = 'iscsi_targets'
__table_args__ = (schema.UniqueConstraint("target_num", "host"),
{'mysql_engine': 'InnoDB'})
id = Column(Integer, primary_key=True)
target_num = Column(Integer)
host = Column(String(255))
volume_id = Column(Integer, ForeignKey('volumes.id'), nullable=True)
volume = relationship(Volume,
backref=backref('iscsi_target', uselist=False),
foreign_keys=volume_id,
primaryjoin='and_(IscsiTarget.volume_id==Volume.id,'
'IscsiTarget.deleted==False)')
class SecurityGroupInstanceAssociation(BASE, FractusBase):
__tablename__ = 'security_group_instance_association'
id = Column(Integer, primary_key=True)
security_group_id = Column(Integer, ForeignKey('security_groups.id'))
instance_id = Column(Integer, ForeignKey('instances.id'))
class SecurityGroup(BASE, FractusBase):
"""Represents a security group."""
__tablename__ = 'security_groups'
id = Column(Integer, primary_key=True)
name = Column(String(255))
description = Column(String(255))
user_id = Column(String(255))
project_id = Column(String(255))
instances = relationship(Instance,
secondary="security_group_instance_association",
primaryjoin='and_('
'SecurityGroup.id == '
'SecurityGroupInstanceAssociation.security_group_id,'
'SecurityGroupInstanceAssociation.deleted == False,'
'SecurityGroup.deleted == False)',
secondaryjoin='and_('
'SecurityGroupInstanceAssociation.instance_id == Instance.id,'
# (anthony) the condition below shouldn't be necessary now that the
# association is being marked as deleted. However, removing this
# may cause existing deployments to choke, so I'm leaving it
'Instance.deleted == False)',
backref='security_groups')
@property
def user(self):
return auth.manager.AuthManager().get_user(self.user_id)
@property
def project(self):
return auth.manager.AuthManager().get_project(self.project_id)
class SecurityGroupIngressRule(BASE, FractusBase):
"""Represents a rule in a security group."""
__tablename__ = 'security_group_rules'
id = Column(Integer, primary_key=True)
parent_group_id = Column(Integer, ForeignKey('security_groups.id'))
parent_group = relationship("SecurityGroup", backref="rules",
foreign_keys=parent_group_id,
primaryjoin='and_('
'SecurityGroupIngressRule.parent_group_id == SecurityGroup.id,'
'SecurityGroupIngressRule.deleted == False)')
protocol = Column(String(5)) # "tcp", "udp", or "icmp"
from_port = Column(Integer)
to_port = Column(Integer)
cidr = Column(String(255))
# Note: This is not the parent SecurityGroup. It's SecurityGroup we're
# granting access for.
group_id = Column(Integer, ForeignKey('security_groups.id'))
class KeyPair(BASE, FractusBase):
"""Represents a public key pair for ssh."""
__tablename__ = 'key_pairs'
id = Column(Integer, primary_key=True)
name = Column(String(255))
user_id = Column(String(255))
fingerprint = Column(String(255))
public_key = Column(Text)
class Network(BASE, FractusBase):
"""Represents a network."""
__tablename__ = 'networks'
__table_args__ = (schema.UniqueConstraint("vpn_public_address",
"vpn_public_port"),
{'mysql_engine': 'InnoDB'})
id = Column(Integer, primary_key=True)
label = Column(String(255))
injected = Column(Boolean, default=False)
cidr = Column(String(255), unique=True)
cidr_v6 = Column(String(255), unique=True)
ra_server = Column(String(255))
netmask = Column(String(255))
bridge = Column(String(255))
gateway = Column(String(255))
broadcast = Column(String(255))
dns = Column(String(255))
vlan = Column(Integer)
vpn_public_address = Column(String(255))
vpn_public_port = Column(Integer)
vpn_private_address = Column(String(255))
dhcp_start = Column(String(255))
# NOTE(vish): The unique constraint below helps avoid a race condition
# when associating a network, but it also means that we
# can't associate two networks with one project.
project_id = Column(String(255), unique=True)
host = Column(String(255)) # , ForeignKey('hosts.id'))
class AuthToken(BASE, FractusBase):
"""Represents an authorization token for all API transactions.
Fields are a string representing the actual token and a user id for
mapping to the actual user
"""
__tablename__ = 'auth_tokens'
token_hash = Column(String(255), primary_key=True)
user_id = Column(String(255))
server_manageent_url = Column(String(255))
storage_url = Column(String(255))
cdn_management_url = Column(String(255))
# TODO(vish): can these both come from the same baseclass?
class FixedIp(BASE, FractusBase):
"""Represents a fixed ip for an instance."""
__tablename__ = 'fixed_ips'
id = Column(Integer, primary_key=True)
address = Column(String(255))
network_id = Column(Integer, ForeignKey('networks.id'), nullable=True)
network = relationship(Network, backref=backref('fixed_ips'))
instance_id = Column(Integer, ForeignKey('instances.id'), nullable=True)
instance = relationship(Instance,
backref=backref('fixed_ip', uselist=False),
foreign_keys=instance_id,
primaryjoin='and_('
'FixedIp.instance_id == Instance.id,'
'FixedIp.deleted == False)')
allocated = Column(Boolean, default=False)
leased = Column(Boolean, default=False)
reserved = Column(Boolean, default=False)
class User(BASE, FractusBase):
"""Represents a user."""
__tablename__ = 'users'
id = Column(String(255), primary_key=True)
name = Column(String(255))
access_key = Column(String(255))
secret_key = Column(String(255))
is_admin = Column(Boolean)
class Project(BASE, FractusBase):
"""Represents a project."""
__tablename__ = 'projects'
id = Column(String(255), primary_key=True)
name = Column(String(255))
description = Column(String(255))
project_manager = Column(String(255), ForeignKey(User.id))
members = relationship(User,
secondary='user_project_association',
backref='projects')
class UserProjectRoleAssociation(BASE, FractusBase):
__tablename__ = 'user_project_role_association'
user_id = Column(String(255), primary_key=True)
user = relationship(User,
primaryjoin=user_id == User.id,
foreign_keys=[User.id],
uselist=False)
project_id = Column(String(255), primary_key=True)
project = relationship(Project,
primaryjoin=project_id == Project.id,
foreign_keys=[Project.id],
uselist=False)
role = Column(String(255), primary_key=True)
ForeignKeyConstraint(['user_id',
'project_id'],
['user_project_association.user_id',
'user_project_association.project_id'])
class UserRoleAssociation(BASE, FractusBase):
__tablename__ = 'user_role_association'
user_id = Column(String(255), ForeignKey('users.id'), primary_key=True)
user = relationship(User, backref='roles')
role = Column(String(255), primary_key=True)
class UserProjectAssociation(BASE, FractusBase):
__tablename__ = 'user_project_association'
user_id = Column(String(255), ForeignKey(User.id), primary_key=True)
project_id = Column(String(255), ForeignKey(Project.id), primary_key=True)
class FloatingIp(BASE, FractusBase):
"""Represents a floating ip that dynamically forwards to a fixed ip."""
__tablename__ = 'floating_ips'
id = Column(Integer, primary_key=True)
address = Column(String(255))
fixed_ip_id = Column(Integer, ForeignKey('fixed_ips.id'), nullable=True)
fixed_ip = relationship(FixedIp,
backref=backref('floating_ips'),
foreign_keys=fixed_ip_id,
primaryjoin='and_('
'FloatingIp.fixed_ip_id == FixedIp.id,'
'FloatingIp.deleted == False)')
project_id = Column(String(255))
host = Column(String(255)) # , ForeignKey('hosts.id'))
class ConsolePool(BASE, FractusBase):
"""Represents pool of consoles on the same physical node."""
__tablename__ = 'console_pools'
id = Column(Integer, primary_key=True)
address = Column(String(255))
username = Column(String(255))
password = Column(String(255))
console_type = Column(String(255))
public_hostname = Column(String(255))
host = Column(String(255))
compute_host = Column(String(255))
class Console(BASE, FractusBase):
"""Represents a console session for an instance."""
__tablename__ = 'consoles'
id = Column(Integer, primary_key=True)
instance_name = Column(String(255))
instance_id = Column(Integer)
password = Column(String(255))
port = Column(Integer, nullable=True)
pool_id = Column(Integer, ForeignKey('console_pools.id'))
pool = relationship(ConsolePool, backref=backref('consoles'))
class Zone(BASE, FractusBase):
"""Represents a child zone of this zone."""
__tablename__ = 'zones'
id = Column(Integer, primary_key=True)
api_url = Column(String(255))
username = Column(String(255))
password = Column(String(255))
def register_models():
"""Register Models and create metadata.
Called from nova.db.sqlalchemy.__init__ as part of loading the driver,
it will never need to be called explicitly elsewhere unless the
connection is lost and needs to be reestablished.
"""
from sqlalchemy import create_engine
models = (Service, Instance, InstanceActions,
Volume, ExportDevice, IscsiTarget, FixedIp, FloatingIp,
Network, SecurityGroup, SecurityGroupIngressRule,
SecurityGroupInstanceAssociation, AuthToken, User,
Project, Certificate, ConsolePool, Console, Zone, Node)
engine = create_engine(FLAGS.sql_connection, echo=False)
for model in models:
model.metadata.create_all(engine)
| Python |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 os
import sys
from fractus import flags
import sqlalchemy
from migrate.versioning import api as versioning_api
try:
from migrate.versioning import exceptions as versioning_exceptions
except ImportError:
try:
# python-migration changed location of exceptions after 1.6.3
# See LP Bug #717467
from migrate import exceptions as versioning_exceptions
except ImportError:
sys.exit(_("python-migrate is not installed. Exiting."))
FLAGS = flags.FLAGS
def db_sync(version=None):
db_version()
repo_path = _find_migrate_repo()
return versioning_api.upgrade(FLAGS.sql_connection, repo_path, version)
def db_version():
repo_path = _find_migrate_repo()
try:
return versioning_api.db_version(FLAGS.sql_connection, repo_path)
except versioning_exceptions.DatabaseNotControlledError:
# If we aren't version controlled we may already have the database
# in the state from before we started version control, check for that
# and set up version_control appropriately
meta = sqlalchemy.MetaData()
engine = sqlalchemy.create_engine(FLAGS.sql_connection, echo=False)
meta.reflect(bind=engine)
try:
for table in ('auth_tokens', 'zones', 'export_devices',
'fixed_ips', 'floating_ips', 'instances',
'key_pairs', 'networks', 'projects', 'quotas',
'security_group_instance_association',
'security_group_rules', 'security_groups',
'services',
'users', 'user_project_association',
'user_project_role_association',
'user_role_association',
'volumes'):
assert table in meta.tables
return db_version_control(1)
except AssertionError:
return db_version_control(0)
def db_version_control(version=None):
repo_path = _find_migrate_repo()
versioning_api.version_control(FLAGS.sql_connection, repo_path, version)
return version
def _find_migrate_repo():
"""Get the path for the migrate repository."""
path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
'migrate_repo')
assert os.path.exists(path)
return path
| Python |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""
Session Handling for SQLAlchemy backend
"""
from sqlalchemy import create_engine
from sqlalchemy import pool
from sqlalchemy.orm import sessionmaker
from fractus import exception
from fractus import flags
FLAGS = flags.FLAGS
_ENGINE = None
_MAKER = None
def get_session(autocommit=True, expire_on_commit=False):
"""Helper method to grab session"""
global _ENGINE
global _MAKER
if not _MAKER:
if not _ENGINE:
kwargs = {'pool_recycle': FLAGS.sql_idle_timeout,
'echo': False}
if FLAGS.sql_connection.startswith('sqlite'):
kwargs['poolclass'] = pool.NullPool
_ENGINE = create_engine(FLAGS.sql_connection,
**kwargs)
_MAKER = (sessionmaker(bind=_ENGINE,
autocommit=autocommit,
expire_on_commit=expire_on_commit))
session = _MAKER()
session.query = exception.wrap_db_error(session.query)
session.flush = exception.wrap_db_error(session.flush)
return session
| Python |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 sqlalchemy import *
from migrate import *
from fractus import log as logging
meta = MetaData()
# Just for the ForeignKey and column creation to succeed, these are not the
# actual definitions of instances or services.
instances = Table('instances', meta,
Column('id', Integer(), primary_key=True, nullable=False),
)
services = Table('services', meta,
Column('id', Integer(), primary_key=True, nullable=False),
)
networks = Table('networks', meta,
Column('id', Integer(), primary_key=True, nullable=False),
)
volumes = Table('volumes', meta,
Column('id', Integer(), primary_key=True, nullable=False),
)
#
# New Tables
#
certificates = Table('certificates', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id', Integer(), primary_key=True, nullable=False),
Column('user_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('project_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('file_name',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
)
consoles = Table('consoles', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id', Integer(), primary_key=True, nullable=False),
Column('instance_name',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('instance_id', Integer()),
Column('password',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('port', Integer(), nullable=True),
Column('pool_id',
Integer(),
ForeignKey('console_pools.id')),
)
console_pools = Table('console_pools', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id', Integer(), primary_key=True, nullable=False),
Column('address',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('username',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('password',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('console_type',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('public_hostname',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('host',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('compute_host',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
)
instance_actions = Table('instance_actions', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id', Integer(), primary_key=True, nullable=False),
Column('instance_id',
Integer(),
ForeignKey('instances.id')),
Column('action',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('error',
Text(length=None, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
)
iscsi_targets = Table('iscsi_targets', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id', Integer(), primary_key=True, nullable=False),
Column('target_num', Integer()),
Column('host',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('volume_id',
Integer(),
ForeignKey('volumes.id'),
nullable=True),
)
#
# Tables to alter
#
auth_tokens = Table('auth_tokens', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('token_hash',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False),
primary_key=True,
nullable=False),
Column('user_id', Integer()),
Column('server_manageent_url',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('storage_url',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('cdn_management_url',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
)
instances_availability_zone = Column(
'availability_zone',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False))
instances_locked = Column('locked',
Boolean(create_constraint=True, name=None))
networks_cidr_v6 = Column(
'cidr_v6',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False))
networks_ra_server = Column(
'ra_server',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False))
services_availability_zone = Column(
'availability_zone',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False))
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine;
# bind migrate_engine to your metadata
meta.bind = migrate_engine
tables = [certificates, console_pools, consoles, instance_actions,
iscsi_targets]
for table in tables:
try:
table.create()
except Exception:
logging.info(repr(table))
logging.exception('Exception while creating table')
meta.drop_all(tables=tables)
raise
auth_tokens.c.user_id.alter(type=String(length=255,
convert_unicode=False,
assert_unicode=None,
unicode_error=None,
_warn_on_bytestring=False))
instances.create_column(instances_availability_zone)
instances.create_column(instances_locked)
networks.create_column(networks_cidr_v6)
networks.create_column(networks_ra_server)
services.create_column(services_availability_zone)
| Python |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
## Table code mostly autogenerated by genmodel.py
from sqlalchemy import *
from migrate import *
from fractus import log as logging
meta = MetaData()
nodes = Table('nodes', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id', Integer(), primary_key=True, nullable=False),
Column('name',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('ip',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('os',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
)
auth_tokens = Table('auth_tokens', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('token_hash',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False),
primary_key=True,
nullable=False),
Column('user_id', Integer()),
Column('server_manageent_url',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('storage_url',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('cdn_management_url',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
)
export_devices = Table('export_devices', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id', Integer(), primary_key=True, nullable=False),
Column('shelf_id', Integer()),
Column('blade_id', Integer()),
Column('volume_id',
Integer(),
ForeignKey('volumes.id'),
nullable=True),
)
fixed_ips = Table('fixed_ips', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id', Integer(), primary_key=True, nullable=False),
Column('address',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('network_id',
Integer(),
ForeignKey('networks.id'),
nullable=True),
Column('instance_id',
Integer(),
ForeignKey('instances.id'),
nullable=True),
Column('allocated', Boolean(create_constraint=True, name=None)),
Column('leased', Boolean(create_constraint=True, name=None)),
Column('reserved', Boolean(create_constraint=True, name=None)),
)
floating_ips = Table('floating_ips', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id', Integer(), primary_key=True, nullable=False),
Column('address',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('fixed_ip_id',
Integer(),
ForeignKey('fixed_ips.id'),
nullable=True),
Column('project_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('host',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
)
instances = Table('instances', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id', Integer(), primary_key=True, nullable=False),
Column('internal_id', Integer()),
Column('admin_pass',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('user_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('project_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('image_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('kernel_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('ramdisk_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('server_name',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('launch_index', Integer()),
Column('key_name',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('key_data',
Text(length=None, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('state', Integer()),
Column('state_description',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('memory_mb', Integer()),
Column('vcpus', Integer()),
Column('local_gb', Integer()),
Column('hostname',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('host',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('instance_type',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('user_data',
Text(length=None, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('reservation_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('mac_address',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('scheduled_at', DateTime(timezone=False)),
Column('launched_at', DateTime(timezone=False)),
Column('terminated_at', DateTime(timezone=False)),
Column('display_name',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('display_description',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
)
key_pairs = Table('key_pairs', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id', Integer(), primary_key=True, nullable=False),
Column('name',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('user_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('fingerprint',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('public_key',
Text(length=None, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
)
networks = Table('networks', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id', Integer(), primary_key=True, nullable=False),
Column('injected', Boolean(create_constraint=True, name=None)),
Column('cidr',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('netmask',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('bridge',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('gateway',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('broadcast',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('dns',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('vlan', Integer()),
Column('vpn_public_address',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('vpn_public_port', Integer()),
Column('vpn_private_address',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('dhcp_start',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('project_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('host',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
)
projects = Table('projects', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False),
primary_key=True,
nullable=False),
Column('name',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('description',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('project_manager',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False),
ForeignKey('users.id')),
)
quotas = Table('quotas', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id', Integer(), primary_key=True, nullable=False),
Column('project_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('instances', Integer()),
Column('cores', Integer()),
Column('volumes', Integer()),
Column('gigabytes', Integer()),
Column('floating_ips', Integer()),
)
security_groups = Table('security_groups', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id', Integer(), primary_key=True, nullable=False),
Column('name',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('description',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('user_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('project_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
)
security_group_inst_assoc = Table('security_group_instance_association', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id', Integer(), primary_key=True, nullable=False),
Column('security_group_id',
Integer(),
ForeignKey('security_groups.id')),
Column('instance_id', Integer(), ForeignKey('instances.id')),
)
security_group_rules = Table('security_group_rules', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id', Integer(), primary_key=True, nullable=False),
Column('parent_group_id',
Integer(),
ForeignKey('security_groups.id')),
Column('protocol',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('from_port', Integer()),
Column('to_port', Integer()),
Column('cidr',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('group_id',
Integer(),
ForeignKey('security_groups.id')),
)
services = Table('services', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id', Integer(), primary_key=True, nullable=False),
Column('host',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('binary',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('topic',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('report_count', Integer(), nullable=False),
Column('disabled', Boolean(create_constraint=True, name=None)),
)
users = Table('users', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False),
primary_key=True,
nullable=False),
Column('name',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('access_key',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('secret_key',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('is_admin', Boolean(create_constraint=True, name=None)),
)
user_project_association = Table('user_project_association', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('user_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False),
ForeignKey('users.id'),
primary_key=True,
nullable=False),
Column('project_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False),
ForeignKey('projects.id'),
primary_key=True,
nullable=False),
)
user_project_role_association = Table('user_project_role_association', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('user_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False),
primary_key=True,
nullable=False),
Column('project_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False),
primary_key=True,
nullable=False),
Column('role',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False),
primary_key=True,
nullable=False),
ForeignKeyConstraint(['user_id',
'project_id'],
['user_project_association.user_id',
'user_project_association.project_id']),
)
user_role_association = Table('user_role_association', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('user_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False),
ForeignKey('users.id'),
primary_key=True,
nullable=False),
Column('role',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False),
primary_key=True,
nullable=False),
)
volumes = Table('volumes', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id', Integer(), primary_key=True, nullable=False),
Column('ec2_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('user_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('project_id',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('host',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('size', Integer()),
Column('availability_zone',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('instance_id',
Integer(),
ForeignKey('instances.id'),
nullable=True),
Column('mountpoint',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('attach_time',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('status',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('attach_status',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('scheduled_at', DateTime(timezone=False)),
Column('launched_at', DateTime(timezone=False)),
Column('terminated_at', DateTime(timezone=False)),
Column('display_name',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
Column('display_description',
String(length=255, convert_unicode=False, assert_unicode=None,
unicode_error=None, _warn_on_bytestring=False)),
)
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine;
# bind migrate_engine to your metadata
meta.bind = migrate_engine
tables = [auth_tokens,
instances, key_pairs, networks, fixed_ips, floating_ips,
quotas, security_groups, security_group_inst_assoc,
security_group_rules, services, users, projects,
user_project_association, user_project_role_association,
user_role_association, volumes, export_devices, nodes]
for table in tables:
try:
table.create()
except Exception:
logging.info(repr(table))
logging.exception('Exception while creating table')
meta.drop_all(tables=tables)
raise
def downgrade(migrate_engine):
# Operations to reverse the above upgrade go here.
for table in (auth_tokens, export_devices, fixed_ips, floating_ips,
instances, key_pairs, networks,
projects, quotas, security_groups, security_group_inst_assoc,
security_group_rules, services, users,
user_project_association, user_project_role_association,
user_role_association, volumes, nodes):
table.drop()
| Python |
#!/usr/bin/env python
from migrate.versioning.shell import main
if __name__ == '__main__':
main(debug='False', repository='.')
| Python |
#!/usr/bin/env python
from migrate.versioning.shell import main
if __name__ == '__main__':
main(debug='False', repository='.')
| Python |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""Database setup and migration commands."""
from fractus import flags
from fractus import utils
FLAGS = flags.FLAGS
flags.DECLARE('db_backend', 'fractus.db.api')
IMPL = utils.LazyPluggable(FLAGS['db_backend'],
sqlalchemy='fractus.db.sqlalchemy.migration')
def db_sync(version=None):
"""Migrate the database to `version` or the most recent version."""
return IMPL.db_sync(version=version)
def db_version():
"""Display the current database version."""
return IMPL.db_version()
| Python |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""
Base class for classes that need modular database access.
"""
from fractus import utils
from fractus import flags
FLAGS = flags.FLAGS
flags.DEFINE_string('db_driver', 'fractus.db.api',
'driver to use for database access')
class Base(object):
"""DB driver is injected in the init method"""
def __init__(self, db_driver=None):
if not db_driver:
db_driver = FLAGS.db_driver
self.db = utils.import_object(db_driver) # pylint: disable-msg=C0103
| Python |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""
DB abstraction for Fractus
"""
from fractus.db.api import *
| Python |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""
Fractus logging handler.
This module adds to logging functionality by adding the option to specify
a context object when calling the various log methods. If the context object
is not specified, default formatting is used.
It also allows setting of formatting information through flags.
"""
import cStringIO
import inspect
import json
import logging
import logging.handlers
import os
import sys
import traceback
from fractus import flags
from fractus import version
FLAGS = flags.FLAGS
flags.DEFINE_string('logging_context_format_string',
'%(asctime)s %(levelname)s %(name)s '
'[%(request_id)s %(user)s '
'%(project)s] %(message)s',
'format string to use for log messages with context')
flags.DEFINE_string('logging_default_format_string',
'%(asctime)s %(levelname)s %(name)s [-] '
'%(message)s',
'format string to use for log messages without context')
flags.DEFINE_string('logging_debug_format_suffix',
'from %(processName)s (pid=%(process)d) %(funcName)s'
' %(pathname)s:%(lineno)d',
'data to append to log format when level is DEBUG')
flags.DEFINE_string('logging_exception_prefix',
'(%(name)s): TRACE: ',
'prefix each line of exception output with this format')
flags.DEFINE_list('default_log_levels',
['amqplib=WARN',
'sqlalchemy=WARN',
'eventlet.wsgi.server=WARN'],
'list of logger=LEVEL pairs')
flags.DEFINE_bool('use_syslog', False, 'output to syslog')
flags.DEFINE_string('logfile', None, 'output to named file')
# A list of things we want to replicate from logging.
# levels
CRITICAL = logging.CRITICAL
FATAL = logging.FATAL
ERROR = logging.ERROR
WARNING = logging.WARNING
WARN = logging.WARN
INFO = logging.INFO
DEBUG = logging.DEBUG
NOTSET = logging.NOTSET
# methods
getLogger = logging.getLogger
debug = logging.debug
info = logging.info
warning = logging.warning
warn = logging.warn
error = logging.error
exception = logging.exception
critical = logging.critical
log = logging.log
# handlers
StreamHandler = logging.StreamHandler
RotatingFileHandler = logging.handlers.RotatingFileHandler
# logging.SysLogHandler is nicer than logging.logging.handler.SysLogHandler.
SysLogHandler = logging.handlers.SysLogHandler
# our new audit level
AUDIT = logging.INFO + 1
logging.addLevelName(AUDIT, 'AUDIT')
def _dictify_context(context):
if context == None:
return None
if not isinstance(context, dict) \
and getattr(context, 'to_dict', None):
context = context.to_dict()
return context
def _get_binary_name():
return os.path.basename(inspect.stack()[-1][1])
def get_log_file_path(binary=None):
if FLAGS.logfile:
return FLAGS.logfile
if FLAGS.logdir:
binary = binary or _get_binary_name()
return '%s.log' % (os.path.join(FLAGS.logdir, binary),)
def basicConfig():
logging.basicConfig()
for handler in logging.root.handlers:
handler.setFormatter(_formatter)
if FLAGS.verbose:
logging.root.setLevel(logging.DEBUG)
else:
logging.root.setLevel(logging.INFO)
if FLAGS.use_syslog:
syslog = SysLogHandler(address='/dev/log')
syslog.setFormatter(_formatter)
logging.root.addHandler(syslog)
logpath = get_log_file_path()
if logpath:
logfile = RotatingFileHandler(logpath)
logfile.setFormatter(_formatter)
logging.root.addHandler(logfile)
class FractusLogger(logging.Logger):
"""
FractusLogger manages request context and formatting.
This becomes the class that is instanciated by logging.getLogger.
"""
def __init__(self, name, level=NOTSET):
level_name = self._get_level_from_flags(name, FLAGS)
level = globals()[level_name]
logging.Logger.__init__(self, name, level)
def _get_level_from_flags(self, name, FLAGS):
# if exactly "fractus", or a child logger, honor the verbose flag
if (name == "fractus" or name.startswith("fractus.")) and FLAGS.verbose:
return 'DEBUG'
for pair in FLAGS.default_log_levels:
logger, _sep, level = pair.partition('=')
# NOTE(todd): if we set a.b, we want a.b.c to have the same level
# (but not a.bc, so we check the dot)
if name == logger:
return level
if name.startswith(logger) and name[len(logger)] == '.':
return level
return 'INFO'
def _log(self, level, msg, args, exc_info=None, extra=None, context=None):
"""Extract context from any log call"""
if not extra:
extra = {}
if context:
extra.update(_dictify_context(context))
extra.update({"fractus_version": version.version_string_with_vcs()})
logging.Logger._log(self, level, msg, args, exc_info, extra)
def addHandler(self, handler):
"""Each handler gets our custom formatter"""
handler.setFormatter(_formatter)
logging.Logger.addHandler(self, handler)
def audit(self, msg, *args, **kwargs):
"""Shortcut for our AUDIT level"""
if self.isEnabledFor(AUDIT):
self._log(AUDIT, msg, args, **kwargs)
def exception(self, msg, *args, **kwargs):
"""Logging.exception doesn't handle kwargs, so breaks context"""
if not kwargs.get('exc_info'):
kwargs['exc_info'] = 1
self.error(msg, *args, **kwargs)
# NOTE(todd): does this really go here, or in _log ?
extra = kwargs.get('extra')
if not extra:
return
env = extra.get('environment')
if env:
env = env.copy()
for k in env.keys():
if not isinstance(env[k], str):
env.pop(k)
message = "Environment: %s" % json.dumps(env)
kwargs.pop('exc_info')
self.error(message, **kwargs)
def handle_exception(type, value, tb):
logging.root.critical(str(value), exc_info=(type, value, tb))
sys.excepthook = handle_exception
logging.setLoggerClass(FractusLogger)
class FractusRootLogger(FractusLogger):
pass
if not isinstance(logging.root, FractusRootLogger):
logging.root = FractusRootLogger("fractus.root", WARNING)
FractusLogger.root = logging.root
FractusLogger.manager.root = logging.root
class FractusFormatter(logging.Formatter):
"""
A fractus.context.RequestContext aware formatter configured through flags.
The flags used to set format strings are: logging_context_foramt_string
and logging_default_format_string. You can also specify
logging_debug_format_suffix to append extra formatting if the log level is
debug.
For information about what variables are available for the formatter see:
http://docs.python.org/library/logging.html#formatter
"""
def format(self, record):
"""Uses contextstring if request_id is set, otherwise default"""
if record.__dict__.get('request_id', None):
self._fmt = FLAGS.logging_context_format_string
else:
self._fmt = FLAGS.logging_default_format_string
if record.levelno == logging.DEBUG \
and FLAGS.logging_debug_format_suffix:
self._fmt += " " + FLAGS.logging_debug_format_suffix
# Cache this on the record, Logger will respect our formated copy
if record.exc_info:
record.exc_text = self.formatException(record.exc_info, record)
return logging.Formatter.format(self, record)
def formatException(self, exc_info, record=None):
"""Format exception output with FLAGS.logging_exception_prefix"""
if not record:
return logging.Formatter.formatException(self, exc_info)
stringbuffer = cStringIO.StringIO()
traceback.print_exception(exc_info[0], exc_info[1], exc_info[2],
None, stringbuffer)
lines = stringbuffer.getvalue().split("\n")
stringbuffer.close()
formatted_lines = []
for line in lines:
pl = FLAGS.logging_exception_prefix % record.__dict__
fl = "%s%s" % (pl, line)
formatted_lines.append(fl)
return "\n".join(formatted_lines)
_formatter = FractusFormatter()
def audit(msg, *args, **kwargs):
"""Shortcut for logging to root log with sevrity 'AUDIT'."""
if len(logging.root.handlers) == 0:
basicConfig()
logging.root.log(AUDIT, msg, *args, **kwargs)
| 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.