<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from prettytable import PrettyTable

class Transaction:
	"""Class to store transactions"""
	def __init__(self, data):
		self.data = data
	def get_data_from_text(self, text):
		valid = False
		type = ''
		line_counter = 0
		lines = text.split('\n')
		print_all = False
		total_value = None
		currency = ''
		value = 0.0
		wert_found = False
		charge = 0.0
		while line_counter < len(lines):
			line = lines[line_counter]
			if (line.find('Daniel Dumke') != -1 or
				line.find('Daniel Stengel') != -1):
				valid = True
#				  print('Valid document for Daniel Dumke')
			if valid:
				if type == '':
					if line.find('DIVIDENDENGUTSCHRIFT ') != -1:
						type = 'dividende'
					elif line.find('ERTRAGSGUTSCHRIFT') != -1:
						type = 'dividende'
					elif line.find('WERTPAPIERABRECHNUNG') != -1:
#						  print_all = True
						line_counter += 1
						line = lines[line_counter]
						if line.find('KAUF') != -1:
							type = 'kauf'
						elif line.find('VERKAUF') != -1:
							type = 'verkauf'
				else:
					if line.find('WKN') != -1:
#						  print(line)
						try:
							wkn = re.match('.*WKN.*([A-Z0-9]{6}).*', line).group(1)
						except:
							pass
						else:
#							  print(wkn)
							line_counter += 1
							line = lines[line_counter]
							name = line.strip(' ')
					elif line.find('UMGER.ZUM DEV.-KURS') != -1:
						# Will be overwritten if WERT Line is found (and correct)
#						  print(line)
						result = re.match('UMGER.ZUM DEV.-KURS\s.*([A-Z]{3})\s*([0-9\.,]*)', line)
						currency = result.group(1)
						if currency != 'EUR':
							print('Error while importing, currency not EUR')
							sys.exit()
						value = float(result.group(2).replace('.','').replace(',','.'))
						wert_found = True
					elif line.find('WERT') != -1:
#						  print(line)
#						  pdb.set_trace()
						result = re.match('WERT\s*([0-9]{2}\.[0-9]{2}\.[0-9]{4}).*([A-Z]{3})\s*([0-9\.,]*)', line)
						if not result:
							result = re.match('WERT\s*([0-9]{2}\.[0-9]{2}\.[0-9]{4})', line)
						date = datetime.datetime.strptime(result.group(1), "%d.%m.%Y").date()
						if currency == '':
							currency = result.group(2)
						if currency != 'EUR':
							print('Error while importing, currency not EUR')
							sys.exit()
						if value == 0.0:
							value = float(result.group(3).replace('.','').replace(',','.'))
							wert_found = True
#						  print(date, currency, value)
#						  print(result)

					elif line.find('Umsatz') != -1:
					# Nominale when buying
#						  print(line)
						line_counter += 1
						line = lines[line_counter]
#						  print(line)
						nominale = float(line.replace(',','.'))
#						  print(nominale)
					elif line == 'Wertpapier':
					# Nominale when buying
#						  print(line)
						line_counter += 1
						line = lines[line_counter]
						name = line.strip(' ')
						result = re.match('0,0.%.(.*?)00.*', name)
						if result:
							name = result.group(1).strip()
#						  print(name)

					elif re.match('AM.*([0-9\.]{10}).*UM.*', line) != None:
						date = re.match('AM.*([0-9\.]{10}).*UM.*', line).group(1)
						date = datetime.datetime.strptime(date, "%d.%m.%Y").date()
#						  print(date)
					elif line == 'Kurs':
					# Nominale when buying
#						  print(line)
						line_counter += 2
						line = lines[line_counter]
#						  print(line)
						value = float(line.split(' ')[0].replace(',','.'))
#						  print(value)
						total_value = value * nominale
#						  print(total_value)
#						  print('total value ', total_value)
#						  print_all = True
					elif line.replace('.', '').find(str(total_value).replace('.',',')) != -1:
					# Nominale when buying
					# All additional lines
						while lines[line_counter+2] != '':
#							  print(line)
							line_counter += 1
							line = lines[line_counter]
							charge += float(line.replace('.', '').replace(',', '.'))
#							  print(charge)
						line_counter += 1
						line = lines[line_counter]
#						  print(line)
						total = float(line.replace('.', '').replace(',', '.'))
#						  print(total)
#						  print(total_value + charge, total)
#						  print(abs(total - (total_value + charge)))
#						  print(lines[line_counter+1])
#						  print(lines[line_counter+2])
#						  print(lines[line_counter+3])
						if abs(total - (total_value + charge)) > 0.01:
							print('Error while importing, totals do not match')
							sys.exit()
#						  print(line)
#			  if print_all:
#			  print(line.replace('.', ''))
			line_counter += 1
		if not valid:
			return None
		elif type == 'dividende':
			return {'type': 'd', 'name': name, 'date': date, 'value': value}
		elif type == 'kauf':
			return {'type': 'b', 'name': name, 'date': date, 'nominale': nominale, 'value': value, 'cost': charge}
		elif type == 'verkauf':
			return {'type': 's', 'name': name, 'date': date, 'nominale': nominale, 'value': value, 'cost': charge}

	def add(self, type, stock_id, date, nominal, price, cost, portfolio):
		if stock_id != None:
			if price < 0:
				price = -1 * price
			if cost < 0:
				cost = -1 * cost
			if type == 'b':
				if nominal < 0:
					nominal = -1 * nominal
				total = -1 * price * nominal - cost
			elif type == 's':
				if nominal > 0:
					nominal = -1 * nominal
				total = -1 * price * nominal + cost
			elif type == 'd':
				if nominal != 0:
					price = price * nominal
					nominal = 0
				cost = 0
				total = price
			result = self.data.c.execute('''SELECT id FROM transactions WHERE type = ? AND portfolio = ? AND stock_id = ? AND date = ? AND nominal = ? AND price = ? AND cost = ? AND total = ?''', (type, portfolio, stock_id, date, nominal, price, cost, total)).fetchall()

			if result == []:
				self.data.c.execute('INSERT INTO transactions (id, type, portfolio, stock_id, date, nominal, price, cost, total) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', (uuid.uuid4(), type, portfolio, stock_id, date, nominal, price, cost, total))
				return True
			else:
				print('Transaction already seems to exist: ' + str(result))
				return True
		else:
			return False
#		  self.data.commit()
	def get_total_invest(self, portfolio, from_date, to_date):
		return self.get_total(portfolio, 'b', from_date, to_date)
	def get_total_divest(self, portfolio, from_date, to_date):
		return self.get_total(portfolio, 's', from_date, to_date)
	def get_total_dividend(self, portfolio, from_date, to_date):
		return self.get_total(portfolio, 'd', from_date, to_date)
	def get_total(self, portfolio, type, from_date, to_date):
		result = self.data.c.execute('''SELECT SUM(total) FROM transactions WHERE portfolio = ? AND type = ? AND date >= ? AND date <= ?''', (portfolio, type, from_date, to_date)).fetchall()
		if result != None:
			result = result[0]
			if result != None:
				result = result[0]
		if result == None:
			result = 0.0
		return result
	def get_portfolio(self, portfolio, date):
		"""Get portfolio contents on that specific date, incl. all transactions from that date"""
		result = self.data.c.execute("""SELECT stock_id, nominal FROM transactions WHERE portfolio = ? AND (type = 'b' OR type = 's') AND date <= ?""", (portfolio, date)).fetchall()
		stocks = {}
		for item in result:
			if item[0] not in stocks.keys():
				stocks[item[0]] = 0.0
			stocks[item[0]] = stocks[item[0]] + item[1]
		return stocks

	def get_total_for_portfolio(self, portfolio):
		result = self.data.c.execute('''SELECT yahoo_id, SUM(nominal), SUM(cost), SUM(total) FROM transactions WHERE portfolio = ? GROUP BY yahoo_id''', (portfolio,)).fetchall()
		return result
	def __repr__(self):
		keys = ['ID', 'Type', 'Date', 'Total']
		result = self.data.c.execute('''SELECT stock_id, type, date, total FROM transactions''').fetchall()
		x = PrettyTable(keys)
		x.padding_width = 1 # One space between column edges and contents (default)
		for item in result:
			x.add_row(item)
		return str(x)<commit_msg>Make output of transactions more readable<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from prettytable import PrettyTable

class Transaction:
	"""Class to store transactions"""
	def __init__(self, data, secs):
		self.data = data
		self.secs = secs
	def get_data_from_text(self, text):
		valid = False
		type = ''
		line_counter = 0
		lines = text.split('\n')
		print_all = False
		total_value = None
		currency = ''
		value = 0.0
		wert_found = False
		charge = 0.0
		while line_counter < len(lines):
			line = lines[line_counter]
			if (line.find('Daniel Dumke') != -1 or
				line.find('Daniel Stengel') != -1):
				valid = True
#				  print('Valid document for Daniel Dumke')
			if valid:
				if type == '':
					if line.find('DIVIDENDENGUTSCHRIFT ') != -1:
						type = 'dividende'
					elif line.find('ERTRAGSGUTSCHRIFT') != -1:
						type = 'dividende'
					elif line.find('WERTPAPIERABRECHNUNG') != -1:
#						  print_all = True
						line_counter += 1
						line = lines[line_counter]
						if line.find('KAUF') != -1:
							type = 'kauf'
						elif line.find('VERKAUF') != -1:
							type = 'verkauf'
				else:
					if line.find('WKN') != -1:
#						  print(line)
						try:
							wkn = re.match('.*WKN.*([A-Z0-9]{6}).*', line).group(1)
						except:
							pass
						else:
#							  print(wkn)
							line_counter += 1
							line = lines[line_counter]
							name = line.strip(' ')
					elif line.find('UMGER.ZUM DEV.-KURS') != -1:
						# Will be overwritten if WERT Line is found (and correct)
#						  print(line)
						result = re.match('UMGER.ZUM DEV.-KURS\s.*([A-Z]{3})\s*([0-9\.,]*)', line)
						currency = result.group(1)
						if currency != 'EUR':
							print('Error while importing, currency not EUR')
							sys.exit()
						value = float(result.group(2).replace('.','').replace(',','.'))
						wert_found = True
					elif line.find('WERT') != -1:
#						  print(line)
#						  pdb.set_trace()
						result = re.match('WERT\s*([0-9]{2}\.[0-9]{2}\.[0-9]{4}).*([A-Z]{3})\s*([0-9\.,]*)', line)
						if not result:
							result = re.match('WERT\s*([0-9]{2}\.[0-9]{2}\.[0-9]{4})', line)
						date = datetime.datetime.strptime(result.group(1), "%d.%m.%Y").date()
						if currency == '':
							currency = result.group(2)
						if currency != 'EUR':
							print('Error while importing, currency not EUR')
							sys.exit()
						if value == 0.0:
							value = float(result.group(3).replace('.','').replace(',','.'))
							wert_found = True
#						  print(date, currency, value)
#						  print(result)

					elif line.find('Umsatz') != -1:
					# Nominale when buying
#						  print(line)
						line_counter += 1
						line = lines[line_counter]
#						  print(line)
						nominale = float(line.replace(',','.'))
#						  print(nominale)
					elif line == 'Wertpapier':
					# Nominale when buying
#						  print(line)
						line_counter += 1
						line = lines[line_counter]
						name = line.strip(' ')
						result = re.match('0,0.%.(.*?)00.*', name)
						if result:
							name = result.group(1).strip()
#						  print(name)

					elif re.match('AM.*([0-9\.]{10}).*UM.*', line) != None:
						date = re.match('AM.*([0-9\.]{10}).*UM.*', line).group(1)
						date = datetime.datetime.strptime(date, "%d.%m.%Y").date()
#						  print(date)
					elif line == 'Kurs':
					# Nominale when buying
#						  print(line)
						line_counter += 2
						line = lines[line_counter]
#						  print(line)
						value = float(line.split(' ')[0].replace(',','.'))
#						  print(value)
						total_value = value * nominale
#						  print(total_value)
#						  print('total value ', total_value)
#						  print_all = True
					elif line.replace('.', '').find(str(total_value).replace('.',',')) != -1:
					# Nominale when buying
					# All additional lines
						while lines[line_counter+2] != '':
#							  print(line)
							line_counter += 1
							line = lines[line_counter]
							charge += float(line.replace('.', '').replace(',', '.'))
#							  print(charge)
						line_counter += 1
						line = lines[line_counter]
#						  print(line)
						total = float(line.replace('.', '').replace(',', '.'))
#						  print(total)
#						  print(total_value + charge, total)
#						  print(abs(total - (total_value + charge)))
#						  print(lines[line_counter+1])
#						  print(lines[line_counter+2])
#						  print(lines[line_counter+3])
						if abs(total - (total_value + charge)) > 0.01:
							print('Error while importing, totals do not match')
							sys.exit()
#						  print(line)
#			  if print_all:
#			  print(line.replace('.', ''))
			line_counter += 1
		if not valid:
			return None
		elif type == 'dividende':
			return {'type': 'd', 'name': name, 'date': date, 'value': value}
		elif type == 'kauf':
			return {'type': 'b', 'name': name, 'date': date, 'nominale': nominale, 'value': value, 'cost': charge}
		elif type == 'verkauf':
			return {'type': 's', 'name': name, 'date': date, 'nominale': nominale, 'value': value, 'cost': charge}

	def add(self, type, stock_id, date, nominal, price, cost, portfolio):
		if stock_id != None:
			if price < 0:
				price = -1 * price
			if cost < 0:
				cost = -1 * cost
			if type == 'b':
				if nominal < 0:
					nominal = -1 * nominal
				total = -1 * price * nominal - cost
			elif type == 's':
				if nominal > 0:
					nominal = -1 * nominal
				total = -1 * price * nominal + cost
			elif type == 'd':
				if nominal != 0:
					price = price * nominal
					nominal = 0
				cost = 0
				total = price
			result = self.data.c.execute('''SELECT id FROM transactions WHERE type = ? AND portfolio = ? AND stock_id = ? AND date = ? AND nominal = ? AND price = ? AND cost = ? AND total = ?''', (type, portfolio, stock_id, date, nominal, price, cost, total)).fetchall()

			if result == []:
				self.data.c.execute('INSERT INTO transactions (id, type, portfolio, stock_id, date, nominal, price, cost, total) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', (uuid.uuid4(), type, portfolio, stock_id, date, nominal, price, cost, total))
				return True
			else:
				print('Transaction already seems to exist: ' + str(result))
				return True
		else:
			return False
#		  self.data.commit()
	def get_total_invest(self, portfolio, from_date, to_date):
		return self.get_total(portfolio, 'b', from_date, to_date)
	def get_total_divest(self, portfolio, from_date, to_date):
		return self.get_total(portfolio, 's', from_date, to_date)
	def get_total_dividend(self, portfolio, from_date, to_date):
		return self.get_total(portfolio, 'd', from_date, to_date)
	def get_total(self, portfolio, type, from_date, to_date):
		result = self.data.c.execute('''SELECT SUM(total) FROM transactions WHERE portfolio = ? AND type = ? AND date >= ? AND date <= ?''', (portfolio, type, from_date, to_date)).fetchall()
		if result != None:
			result = result[0]
			if result != None:
				result = result[0]
		if result == None:
			result = 0.0
		return result
	def get_portfolio(self, portfolio, date):
		"""Get portfolio contents on that specific date, incl. all transactions from that date"""
		result = self.data.c.execute("""SELECT stock_id, nominal FROM transactions WHERE portfolio = ? AND (type = 'b' OR type = 's') AND date <= ?""", (portfolio, date)).fetchall()
		stocks = {}
		for item in result:
			if item[0] not in stocks.keys():
				stocks[item[0]] = 0.0
			stocks[item[0]] = stocks[item[0]] + item[1]
		return stocks

	def get_total_for_portfolio(self, portfolio):
		result = self.data.c.execute('''SELECT yahoo_id, SUM(nominal), SUM(cost), SUM(total) FROM transactions WHERE portfolio = ? GROUP BY yahoo_id''', (portfolio,)).fetchall()
		return result
	def __repr__(self):
		keys = ['Name', 'Type', 'Date', 'Total']
		result = self.data.c.execute('''SELECT stock_id, type, date, total FROM transactions ORDER BY date DESC''').fetchall()
		x = PrettyTable(keys)
		x.padding_width = 1 # One space between column edges and contents (default)
		for item in result:
			item = list(item)
			item[0] = self.secs.get_name_from_stock_id(item[0])
			x.add_row(item)
		return str(x)<|endoftext|>


<commit_before>__version__ = '1.2.1'

import __builtin__
import importlib
import inspect
import logging
import pkgutil

import maps

from tendrl.commons import etcdobj
from tendrl.commons import flows
from tendrl.commons import log
from tendrl.commons import objects
from tendrl.commons.objects import BaseAtom

LOG = logging.getLogger(__name__)

class TendrlNS(object):
    def __init__(self, ns_name="tendrl", ns_src="tendrl.commons"):
        super(TendrlNS, self).__init__()
        if not hasattr(__builtin__, "NS"):
            setattr(__builtin__, "NS", maps.NamedDict())
        LOG.info("Creating namespace.%s from source %s", ns_name, ns_src)
        self.ns_name = ns_name
        self.ns_src = ns_src

        self._create_ns()

        self.current_ns = self._get_ns()
        LOG.info("namespace.%s created!", self.ns_name)
        self._register_subclasses_to_ns()

        self.setup_definitions()
        self.setup_common_objects()

    def setup_definitions(self):
        LOG.info("Setup Definitions for namespace.%s", self.ns_name)
        self.current_ns.definitions = self.current_ns.objects.Definition()

    def setup_common_objects(self):
        # Config, if the namespace has implemented its own Config object
        if "Config" in self.current_ns.objects:
            LOG.info("Setup Config for namespace.%s", self.ns_name)
            self.current_ns.config = self.current_ns.objects.Config()
            NS.config = self.current_ns.config

            # etcd_orm
            etcd_kwargs = {'port': self.current_ns.config.data['etcd_port'],
                           'host': self.current_ns.config.data[
                               "etcd_connection"]}
            LOG.info("Setup Etcd Orm for namespace.%s", self.ns_name)
            NS.etcd_orm = etcdobj.Server(etcd_kwargs=etcd_kwargs)
            log.setup_logging(self.current_ns.config.data['log_cfg_path'])

        # NodeContext, if the namespace has implemented its own
        if "NodeContext" in self.current_ns.objects:
            LOG.info("Setup NodeContext for namespace.%s", self.ns_name)

            self.current_ns.node_context = \
                self.current_ns.objects.NodeContext()
            NS.node_context = self.current_ns.node_context

        # TendrlContext, if the namespace has implemented its own
        if "TendrlContext" in self.current_ns.objects:
            LOG.info("Setup TendrlContext for namespace.%s", self.ns_name)
            self.current_ns.tendrl_context = \
                self.current_ns.objects.TendrlContext()
            NS.tendrl_context = self.current_ns.tendrl_context

    def _create_ns(self):
        ns_map = maps.NamedDict(objects=maps.NamedDict(),
                                flows=maps.NamedDict(),
                                ns=self)
        self.ns_str = self.ns_name.split(".")[-1]

        if 'integrations' in self.ns_name:
            if not hasattr(NS, "integrations"):
                setattr(NS, "integrations",
                        maps.NamedDict())
            setattr(NS.integrations, self.ns_str, ns_map)
        else:
            # Create the component namespace
            setattr(NS, self.ns_str, ns_map)

    def _get_ns(self):
        # eg: input : "tendrl.node_agent", return: "node_agent"
        if "integrations" in self.ns_name:
            return getattr(NS.integrations, self.ns_str)
        else:
            return getattr(NS, self.ns_str)

    def _add_object(self, name, obj_class):
        # obj is the actual instance of that Tendrl object
        # name of object as defined in Tendrl definitions
        obj_class._ns = self
        self.current_ns.objects[name] = obj_class

        # This is to link atoms and flows (insdie obj) to the obj ns
        private_name = "_" + name
        self.current_ns.objects[private_name] = maps.NamedDict()

        if 'atoms' not in self._get_ns().objects[private_name]:
            self.current_ns.objects[private_name]['atoms'] = maps.NamedDict()

        if "flows" not in self._get_ns().objects[private_name]:
            self.current_ns.objects[private_name]['flows'] = maps.NamedDict()

    def _get_object(self, name):
        return self.current_ns.objects[name]

    def get_atom(self, obj_name, atom_name):
        private_name = "_" + obj_name
        if private_name in self.current_ns.objects:
            self.current_ns.objects[private_name]['atoms'][atom_name]
        else:
            return NS.tendrl.objects[private_name]['atoms'][atom_name]
        #return self.current_ns.objects[private_name]['atoms'][atom_name]

    def get_obj_flow(self, obj_name, flow_name):
        private_name = "_" + obj_name
        return self.current_ns.objects[private_name]['flows'][flow_name]

    def _add_atom(self, obj_name, atom_name, atom_class):
        atom_class._ns = self
        private_name = "_" + obj_name
        self.current_ns.objects[private_name]['atoms'][atom_name] = atom_class
        atom_class.obj = self._get_object(obj_name)

    def _add_obj_flow(self, obj_name, flow_name, flow_class):
        flow_class._ns = self
        private_name = "_" + obj_name
        self.current_ns.objects[private_name]['flows'][flow_name] = flow_class
        flow_class.obj = self._get_object(obj_name)

    def _add_flow(self, name, flow_class):
        flow_class._ns = self
        # flow is the actual instance of that Tendrl flow
        # name of object as defined in Tendrl definitions
        self.current_ns.flows[name] = flow_class

    def get_flow(self, name):
        return self.current_ns.flows[name]

    def get_obj_definition(self, obj_name):
        raw_ns = "namespace.%s" % self.ns_name
        if hasattr(NS, "compiled_definitions"):
            raw_obj = NS.compiled_definitions.get_parsed_defs()[raw_ns][
                'objects'][obj_name]
        else:
            raw_obj = self.current_ns.definitions.get_parsed_defs()[raw_ns][
                'objects'][obj_name]

        return maps.NamedDict(attrs=raw_obj['attrs'],
                              enabled=raw_obj['enabled'],
                              obj_list=raw_obj.get('list', ""),
                              obj_value=raw_obj['value'],
                              atoms=raw_obj.get('atoms', {}),
                              flows=raw_obj.get('flows', {}),
                              help=raw_obj['help']
                              )

    def get_obj_flow_definition(self, obj_name, flow_name):
        obj_def = self.get_obj_definition(obj_name)
        raw_flow = obj_def.flows[flow_name]
        return maps.NamedDict(atoms=raw_flow['atoms'],
                              help=raw_flow['help'],
                              enabled=raw_flow['enabled'],
                              inputs=raw_flow['inputs'],
                              pre_run=raw_flow.get('pre_run', []),
                              post_run=raw_flow.get('post_run', []),
                              type=raw_flow['type'],
                              uuid=raw_flow['uuid'])

    def get_atom_definition(self, obj_name, atom_name):
        obj_def = self.get_obj_definition(obj_name)
        raw_atom = obj_def.atoms[atom_name]
        return maps.NamedDict(help=raw_atom['help'],
                              enabled=raw_atom['enabled'],
                              inputs=raw_atom.get('inputs').get('mandatory'),
                              outputs=raw_atom.get('outputs', []),
                              uuid=raw_atom['uuid'])

    def get_flow_definition(self, flow_name):
        raw_ns = "namespace.%s" % self.ns_name

        if hasattr(NS, "compiled_definitions"):
            raw_flow = NS.compiled_definitions.get_parsed_defs()[
                raw_ns][
                'flows'][flow_name]
        else:
            raw_flow = self.current_ns.definitions.get_parsed_defs()[raw_ns][
                'flows'][flow_name]
        return maps.NamedDict(atoms=raw_flow['atoms'],
                              help=raw_flow['help'],
                              enabled=raw_flow['enabled'],
                              inputs=raw_flow['inputs'],
                              pre_run=raw_flow.get('pre_run', []),
                              post_run=raw_flow.get('post_run', []),
                              type=raw_flow['type'],
                              uuid=raw_flow['uuid'])

    def _register_subclasses_to_ns(self):
        # registers all subclasses of BaseObject, BaseFlow, BaseAtom to
        # NS
        LOG.info("Finding objects in namespace.%s.objects", self.ns_name)

        ns_root = importlib.import_module(self.ns_src).__path__[0]

        # register objects and atoms, flows inside the objects
        ns_objects_path = ns_root + "/objects"
        ns_objects_prefix = self.ns_src + ".objects."
        objs = self._list_modules_in_package_path(ns_objects_path,
                                                  ns_objects_prefix)
        for name, obj_fqdn in objs:
            obj = importlib.import_module(obj_fqdn)
            for obj_cls in inspect.getmembers(obj, inspect.isclass):
                if issubclass(obj_cls[1], objects.BaseObject):
                    obj_name = obj_cls[0]
                    LOG.info("Registering object namespace.%s.objects.%s",
                             self.ns_name, obj_name)
                    self._add_object(obj_name, obj_cls[1])

                    ns_object_atoms_path = obj.__path__[0] + "/atoms"
                    ns_object_atoms_prefix = obj_fqdn + ".atoms."
                    LOG.info("Finding atoms in "
                             "namespace.%s.objects.%s.atoms", self.ns_name,
                             obj_name)
                    for atom_name, atom_fqdn in \
                        self._list_modules_in_package_path(
                            ns_object_atoms_path,
                            ns_object_atoms_prefix):
                        atom = importlib.import_module(atom_fqdn)

                        for atom_cls in inspect.getmembers(atom,
                                                           inspect.isclass):
                            if issubclass(atom_cls[1], BaseAtom):
                                LOG.info("Registering atom "
                                         "namespace.%s.objects.%s.atoms.%s",
                                         self.ns_name, obj_name,
                                         atom_cls[1].__name__)

                                self._add_atom(obj_name,
                                               atom_cls[1].__name__,
                                               atom_cls[1])

                    ns_object_flows_path = obj.__path__[0] + "/flows"
                    ns_object_flows_prefix = obj_fqdn + ".flows."
                    LOG.info("Finding flows in "
                             "namespace.%s.objects.%s.flows", self.ns_name,
                             obj_name)
                    for flow_name, flow_fqdn in \
                        self._list_modules_in_package_path(
                            ns_object_flows_path,
                            ns_object_flows_prefix):
                        flow = importlib.import_module(flow_fqdn)

                        for flow_cls in inspect.getmembers(flow,
                                                           inspect.isclass):
                            if issubclass(flow_cls[1], flows.BaseFlow):
                                LOG.info("Registering flow "
                                         "namespace.%s.objects.%s.flow.%s",
                                         self.ns_name, obj_name,
                                         flow_cls[1].__name__)
                                self._add_obj_flow(obj_name,
                                                   flow_cls[1].__name__,
                                                   flow_cls[1])

        ns_flows_path = ns_root + "/flows"
        ns_flows_prefix = self.ns_src + ".flows."
        flowz = self._list_modules_in_package_path(ns_flows_path,
                                                   ns_flows_prefix)
        LOG.info("Finding flows in namespace.%s.flows", self.ns_name)
        for name, flow_fqdn in flowz:
            the_flow = importlib.import_module(flow_fqdn)
            for flow_cls in inspect.getmembers(the_flow, inspect.isclass):
                if issubclass(flow_cls[1], flows.BaseFlow):
                    LOG.info("Registering flow namespace.%s.flows.%s",
                             self.ns_name, flow_cls[0])
                    self._add_flow(flow_cls[0], flow_cls[1])

    def _list_modules_in_package_path(self, package_path, prefix):
        modules = []
        for importer, name, ispkg in pkgutil.walk_packages(
                path=[package_path]):
            modules.append((name, prefix + name))
        return modules
<commit_msg>Update __init__.py<commit_after>__version__ = '1.2.1'

import __builtin__
import importlib
import inspect
import logging
import pkgutil

import maps

from tendrl.commons import etcdobj
from tendrl.commons import flows
from tendrl.commons import log
from tendrl.commons import objects
from tendrl.commons.objects import BaseAtom

LOG = logging.getLogger(__name__)

class TendrlNS(object):
    def __init__(self, ns_name="tendrl", ns_src="tendrl.commons"):
        super(TendrlNS, self).__init__()
        if not hasattr(__builtin__, "NS"):
            setattr(__builtin__, "NS", maps.NamedDict())
        LOG.info("Creating namespace.%s from source %s", ns_name, ns_src)
        self.ns_name = ns_name
        self.ns_src = ns_src

        self._create_ns()

        self.current_ns = self._get_ns()
        LOG.info("namespace.%s created!", self.ns_name)
        self._register_subclasses_to_ns()

        self.setup_definitions()
        self.setup_common_objects()

    def setup_definitions(self):
        LOG.info("Setup Definitions for namespace.%s", self.ns_name)
        self.current_ns.definitions = self.current_ns.objects.Definition()

    def setup_common_objects(self):
        # Config, if the namespace has implemented its own Config object
        if "Config" in self.current_ns.objects:
            LOG.info("Setup Config for namespace.%s", self.ns_name)
            self.current_ns.config = self.current_ns.objects.Config()
            NS.config = self.current_ns.config

            # etcd_orm
            etcd_kwargs = {'port': self.current_ns.config.data['etcd_port'],
                           'host': self.current_ns.config.data[
                               "etcd_connection"]}
            LOG.info("Setup Etcd Orm for namespace.%s", self.ns_name)
            NS.etcd_orm = etcdobj.Server(etcd_kwargs=etcd_kwargs)
            log.setup_logging(self.current_ns.config.data['log_cfg_path'])

        # NodeContext, if the namespace has implemented its own
        if "NodeContext" in self.current_ns.objects:
            LOG.info("Setup NodeContext for namespace.%s", self.ns_name)

            self.current_ns.node_context = \
                self.current_ns.objects.NodeContext()
            NS.node_context = self.current_ns.node_context

        # TendrlContext, if the namespace has implemented its own
        if "TendrlContext" in self.current_ns.objects:
            LOG.info("Setup TendrlContext for namespace.%s", self.ns_name)
            self.current_ns.tendrl_context = \
                self.current_ns.objects.TendrlContext()
            NS.tendrl_context = self.current_ns.tendrl_context

    def _create_ns(self):
        ns_map = maps.NamedDict(objects=maps.NamedDict(),
                                flows=maps.NamedDict(),
                                ns=self)
        self.ns_str = self.ns_name.split(".")[-1]

        if 'integrations' in self.ns_name:
            if not hasattr(NS, "integrations"):
                setattr(NS, "integrations",
                        maps.NamedDict())
            setattr(NS.integrations, self.ns_str, ns_map)
        else:
            # Create the component namespace
            setattr(NS, self.ns_str, ns_map)

    def _get_ns(self):
        # eg: input : "tendrl.node_agent", return: "node_agent"
        if "integrations" in self.ns_name:
            return getattr(NS.integrations, self.ns_str)
        else:
            return getattr(NS, self.ns_str)

    def _add_object(self, name, obj_class):
        # obj is the actual instance of that Tendrl object
        # name of object as defined in Tendrl definitions
        obj_class._ns = self
        self.current_ns.objects[name] = obj_class

        # This is to link atoms and flows (insdie obj) to the obj ns
        private_name = "_" + name
        self.current_ns.objects[private_name] = maps.NamedDict()

        if 'atoms' not in self._get_ns().objects[private_name]:
            self.current_ns.objects[private_name]['atoms'] = maps.NamedDict()

        if "flows" not in self._get_ns().objects[private_name]:
            self.current_ns.objects[private_name]['flows'] = maps.NamedDict()

    def _get_object(self, name):
        return self.current_ns.objects[name]

    def get_atom(self, obj_name, atom_name):
        private_name = "_" + obj_name
        return self.current_ns.objects[private_name]['atoms'][atom_name]

    def get_obj_flow(self, obj_name, flow_name):
        private_name = "_" + obj_name
        return self.current_ns.objects[private_name]['flows'][flow_name]

    def _add_atom(self, obj_name, atom_name, atom_class):
        atom_class._ns = self
        private_name = "_" + obj_name
        self.current_ns.objects[private_name]['atoms'][atom_name] = atom_class
        atom_class.obj = self._get_object(obj_name)

    def _add_obj_flow(self, obj_name, flow_name, flow_class):
        flow_class._ns = self
        private_name = "_" + obj_name
        self.current_ns.objects[private_name]['flows'][flow_name] = flow_class
        flow_class.obj = self._get_object(obj_name)

    def _add_flow(self, name, flow_class):
        flow_class._ns = self
        # flow is the actual instance of that Tendrl flow
        # name of object as defined in Tendrl definitions
        self.current_ns.flows[name] = flow_class

    def get_flow(self, name):
        return self.current_ns.flows[name]

    def get_obj_definition(self, obj_name):
        raw_ns = "namespace.%s" % self.ns_name
        if hasattr(NS, "compiled_definitions"):
            raw_obj = NS.compiled_definitions.get_parsed_defs()[raw_ns][
                'objects'][obj_name]
        else:
            raw_obj = self.current_ns.definitions.get_parsed_defs()[raw_ns][
                'objects'][obj_name]

        return maps.NamedDict(attrs=raw_obj['attrs'],
                              enabled=raw_obj['enabled'],
                              obj_list=raw_obj.get('list', ""),
                              obj_value=raw_obj['value'],
                              atoms=raw_obj.get('atoms', {}),
                              flows=raw_obj.get('flows', {}),
                              help=raw_obj['help']
                              )

    def get_obj_flow_definition(self, obj_name, flow_name):
        obj_def = self.get_obj_definition(obj_name)
        raw_flow = obj_def.flows[flow_name]
        return maps.NamedDict(atoms=raw_flow['atoms'],
                              help=raw_flow['help'],
                              enabled=raw_flow['enabled'],
                              inputs=raw_flow['inputs'],
                              pre_run=raw_flow.get('pre_run', []),
                              post_run=raw_flow.get('post_run', []),
                              type=raw_flow['type'],
                              uuid=raw_flow['uuid'])

    def get_atom_definition(self, obj_name, atom_name):
        obj_def = self.get_obj_definition(obj_name)
        raw_atom = obj_def.atoms[atom_name]
        return maps.NamedDict(help=raw_atom['help'],
                              enabled=raw_atom['enabled'],
                              inputs=raw_atom.get('inputs').get('mandatory'),
                              outputs=raw_atom.get('outputs', []),
                              uuid=raw_atom['uuid'])

    def get_flow_definition(self, flow_name):
        raw_ns = "namespace.%s" % self.ns_name

        if hasattr(NS, "compiled_definitions"):
            raw_flow = NS.compiled_definitions.get_parsed_defs()[
                raw_ns][
                'flows'][flow_name]
        else:
            raw_flow = self.current_ns.definitions.get_parsed_defs()[raw_ns][
                'flows'][flow_name]
        return maps.NamedDict(atoms=raw_flow['atoms'],
                              help=raw_flow['help'],
                              enabled=raw_flow['enabled'],
                              inputs=raw_flow['inputs'],
                              pre_run=raw_flow.get('pre_run', []),
                              post_run=raw_flow.get('post_run', []),
                              type=raw_flow['type'],
                              uuid=raw_flow['uuid'])

    def _register_subclasses_to_ns(self):
        # registers all subclasses of BaseObject, BaseFlow, BaseAtom to
        # NS
        LOG.info("Finding objects in namespace.%s.objects", self.ns_name)

        ns_root = importlib.import_module(self.ns_src).__path__[0]

        # register objects and atoms, flows inside the objects
        ns_objects_path = ns_root + "/objects"
        ns_objects_prefix = self.ns_src + ".objects."
        objs = self._list_modules_in_package_path(ns_objects_path,
                                                  ns_objects_prefix)
        for name, obj_fqdn in objs:
            obj = importlib.import_module(obj_fqdn)
            for obj_cls in inspect.getmembers(obj, inspect.isclass):
                if issubclass(obj_cls[1], objects.BaseObject):
                    obj_name = obj_cls[0]
                    LOG.info("Registering object namespace.%s.objects.%s",
                             self.ns_name, obj_name)
                    self._add_object(obj_name, obj_cls[1])

                    ns_object_atoms_path = obj.__path__[0] + "/atoms"
                    ns_object_atoms_prefix = obj_fqdn + ".atoms."
                    LOG.info("Finding atoms in "
                             "namespace.%s.objects.%s.atoms", self.ns_name,
                             obj_name)
                    for atom_name, atom_fqdn in \
                        self._list_modules_in_package_path(
                            ns_object_atoms_path,
                            ns_object_atoms_prefix):
                        atom = importlib.import_module(atom_fqdn)

                        for atom_cls in inspect.getmembers(atom,
                                                           inspect.isclass):
                            if issubclass(atom_cls[1], BaseAtom):
                                LOG.info("Registering atom "
                                         "namespace.%s.objects.%s.atoms.%s",
                                         self.ns_name, obj_name,
                                         atom_cls[1].__name__)

                                self._add_atom(obj_name,
                                               atom_cls[1].__name__,
                                               atom_cls[1])

                    ns_object_flows_path = obj.__path__[0] + "/flows"
                    ns_object_flows_prefix = obj_fqdn + ".flows."
                    LOG.info("Finding flows in "
                             "namespace.%s.objects.%s.flows", self.ns_name,
                             obj_name)
                    for flow_name, flow_fqdn in \
                        self._list_modules_in_package_path(
                            ns_object_flows_path,
                            ns_object_flows_prefix):
                        flow = importlib.import_module(flow_fqdn)

                        for flow_cls in inspect.getmembers(flow,
                                                           inspect.isclass):
                            if issubclass(flow_cls[1], flows.BaseFlow):
                                LOG.info("Registering flow "
                                         "namespace.%s.objects.%s.flow.%s",
                                         self.ns_name, obj_name,
                                         flow_cls[1].__name__)
                                self._add_obj_flow(obj_name,
                                                   flow_cls[1].__name__,
                                                   flow_cls[1])

        ns_flows_path = ns_root + "/flows"
        ns_flows_prefix = self.ns_src + ".flows."
        flowz = self._list_modules_in_package_path(ns_flows_path,
                                                   ns_flows_prefix)
        LOG.info("Finding flows in namespace.%s.flows", self.ns_name)
        for name, flow_fqdn in flowz:
            the_flow = importlib.import_module(flow_fqdn)
            for flow_cls in inspect.getmembers(the_flow, inspect.isclass):
                if issubclass(flow_cls[1], flows.BaseFlow):
                    LOG.info("Registering flow namespace.%s.flows.%s",
                             self.ns_name, flow_cls[0])
                    self._add_flow(flow_cls[0], flow_cls[1])

    def _list_modules_in_package_path(self, package_path, prefix):
        modules = []
        for importer, name, ispkg in pkgutil.walk_packages(
                path=[package_path]):
            modules.append((name, prefix + name))
        return modules
<|endoftext|>


<commit_before># coding: utf-8
# QtCreator Debugger用のpretty-printer
from dumper import *
import math

Fr_ElementName = ["x", "y", "z", "w"]
Fr_ElementIndex = []
for idx in range(64):
    Fr_ElementIndex.append("[" + str(idx) + "]")

def fr_GetElementIndex(size):
    u''' 要素数が4つまでのベクトルはXYZW表記、それ以上の場合は数値インデックスのリストを返す '''
    return Fr_ElementName if size<=len(Fr_ElementName) else Fr_ElementIndex

def fr_TypePrefix(b_integral, bitwidth, b_align):
    # Alignedなら先頭にA(aligned)を付与
    typv = "A" if b_align else ""
    if b_integral:
        # 整数型にはI(integral)を付与
        typv += "I"
    else:
        # 内部表現に使うサイズが32bitを超える場合はD(double)を付与
        typv += "" if bitwidth <= 32 else "D"
    return typv

def fr_ArrayString(elem, size, typ):
    s = ""
    comma = False
    for idx in range(size):
        if comma:
            s += ", "
        e = elem[idx]
        if typ == float:
            s += "{0:4.6f}".format(float(e))
        elif typ != None:
            s += str(typ(e))
        else:
            s += str(e)
        comma = True
    return s
def fr_ArrayStringB(elem, size, typ):
    return Embrace(fr_ArrayString(elem, size, typ))
def Embrace(s):
    return "[" + s + "]"

def fr_DumpVector(d, elem, size, typ):
    d.putValue(fr_ArrayStringB(elem, size, typ))
    d.putNumChild(size)

    if d.isExpanded():
        index = fr_GetElementIndex(size)
        with Children(d):
            for idx in range(size):
                d.putSubItem(index[idx], elem[idx])

# ------------------------------------------------------------
# Vector
def fr_DumpData(d, value, name):
    bInt = bool(value["is_integral"])
    d.putType(
        fr_TypePrefix(
            bInt,
            value["bit_width"],
            value["align"]
        )
        + name
        + str(value["size"])
    )
    fr_DumpVector(d, value["m"], int(value["size"]), int if bInt else float)

def qdump__frea__Data(d, value):
    fr_DumpData(d, value, "Data")
def qdump__frea__VecT(d, value):
    fr_DumpData(d, value, "Vec")
def qdump__frea__VecT_spec(d, value):
    fr_DumpData(d, value, "Vec(s)")

# ------------------------------------------------------------
# Vector wrapper
def fr_DumpWrap(d, value, name):
    elem = value["m"]
    size = int(value["size"])
    bw = int(value["bit_width"])
    bInt = bool(value["is_integral"])
    d.putType(fr_TypePrefix(bInt, bw, False) + name + str(size))
    if bInt:
        d.putArrayData(elem.address, size, d.lookupType("unsigned int"))
    else:
        d.putValue(fr_ArrayStringB(elem, size, float))
        d.putNumChild(size)
        if d.isExpanded():
            index = fr_GetElementIndex(size)
            with Children(d):
                for idx in range(size):
                    d.putSubItem(index[idx], elem[idx])

def qdump__frea__wrap(d, value):
    fr_DumpWrap(d, value, "Wrap")
def qdump__frea__wrap_spec(d, value):
    fr_DumpWrap(d, value, "Wrap(s)")

def fr_TupString(value):
    data = value["data"]
    wcap = int(value["w_capacity"])
    bInt = bool(value["is_integral"])
    size = int(value["size"])
    numChild = int(size/wcap)
    modChild = size%wcap
    if modChild != 0:
        numChild += 1
    s = "["
    if not bInt:
        comma = False
        for i in range(numChild-1):
            if comma:
                s += ", "
            s += fr_ArrayString(data[i]["m"], wcap, float)
            comma = True
        s += ", "
        s += fr_ArrayString(
                data[numChild-1]["m"],
                modChild if modChild>0 else wcap,
                float
             )
    s += "]"
    return s

def fr_DumpTup(d, value, name):
    bw = int(value["bit_width"])
    data = value["data"]
    wcap = int(value["w_capacity"])
    bInt = bool(value["is_integral"])
    size = int(value["size"])
    numChild = int(size/wcap)
    modChild = size%wcap
    if modChild != 0:
        numChild += 1
    # 整数型は今の所未対応
    if not bInt:
        d.putValue(fr_TupString(value))
        d.putType(fr_TypePrefix(bInt, bw, False) + name + str(size))
    d.putNumChild(numChild)
    if d.isExpanded():
        with Children(d):
            for idx in range(numChild):
                d.putSubItem(idx, data[idx])

def qdump__frea__tup(d, value):
    fr_DumpTup(d, value, "Wrap")
def qdump__frea__tup_spec(d, value):
    fr_DumpTup(d, value, "Wrap(s)")

# ------------------------------------------------------------
# Matrix wrapper
def fr_DumpWrapM(d, value, name):
    m = int(value["dim_m"])
    n = int(value["dim_n"])
    bInt = bool(value["is_integral"])
    elem = value["v"]

    # 整数型は今の所未対応
    if not bInt:
        s = "["
        comma = False
        for idx in range(m):
            if comma:
                s += ", "
            comma = True
            el = elem[idx]
            try:
                s += fr_ArrayStringB(el["m"], n, None if bInt else float)
            except RuntimeError:
                s += fr_TupString(el)
        s += "]"
        d.putValue(s)
        d.putType(name + "[" + str(m) + "][" + str(n) + "]")
    d.putNumChild(m)
    if d.isExpanded():
        with Children(d):
            for idx in range(m):
                d.putSubItem(idx, elem[idx])

def qdump__frea__wrapM(d, value):
    fr_DumpWrapM(d, value, "WrapM")
def qdump__frea__wrapM_spec(d, value):
    fr_DumpWrapM(d, value, "WrapM(s)")

# ------------------------------------------------------------
# Matrix
def fr_DumpMData(d, value, name):
    m = int(value["dim_m"])
    n = int(value["dim_n"])
    bInt = bool(value["is_integral"])
    bw = int(value["bit_width"])
    align = bool(value["align"])
    elem = value["m"]
    d.putType(
        fr_TypePrefix(bInt, bw, align)
        + name + "[" + str(m) + "][" + str(n) + "]"
    )
    s = "["
    comma = False
    for idx in range(m):
        if comma:
            s += ", "
        comma = True
        s += fr_ArrayStringB(elem[idx]["m"], n, None if bInt else float)
    s += "]"
    d.putValue(s)
    d.putNumChild(m)
    if d. isExpanded():
        index = Fr_ElementIndex
        with Children(d):
            for idx in range(m):
                d.putSubItem(index[idx], elem[idx])

def qdump__frea__DataM(d, value):
    fr_DumpMData(d, value, "DataM")
def qdump__frea__MatT_spec(d, value):
    fr_DumpMData(d, value, "MatT(s)")
def qdump__frea__MatT(d, value):
    fr_DumpMData(d, value, "MatT")

# ------------------------------------------------------------
# Range
def qdump__frea__Range(d, value):
    d.putValue("[" + str(value["from"]) + " | " + str(value["to"]) + "]")
    d.putType("Range")
    d.putNumChild(0)

def fr_RotationString(axis, angle):
    fmt = "{0:3.3f}"
    str_axis = []
    for a in axis:
        str_axis.append(fmt.format(a))
    s = "Axis=[" + ",".join(str_axis) + "] Deg=[" + fmt.format(angle) + "]"
    return s
# ------------------------------------------------------------
# Quaternion
def qdump__frea__QuatT(d, value):
    val = value["m"]
    s_theta = math.sqrt(1.0 - val[3]*val[3])
    if s_theta < 1e-6:
        # 無回転クォータニオンとして扱う
        axis = [0,0,0]
        angle = 0
    else:
        s_theta = 1.0 / s_theta
        axis = []
        for i in range(3):
            axis.append(float(val[i] * s_theta))
        angle = math.acos(val[3])*2 / math.pi * 180

    d.putValue("Quat:" + fr_RotationString(axis, angle))
    d.putType(fr_TypePrefix(value["is_integral"], value["bit_width"], value["align"]) + "Quat")
    d.putNumChild(4)
    if d. isExpanded():
        index = Fr_ElementIndex
        with Children(d):
            for idx in range(4):
                d.putSubItem(index[idx], val[idx])

# ------------------------------------------------------------
# ExpQuaternion
def qdump__frea__ExpQuatT(d, value):
    val = value["m"]
    theta = math.sqrt(val[0]*val[0] + val[1]*val[1] + val[2]*val[2])
    if theta < 1e-6:
        # 無回転クォータニオンとして扱う
        axis = [0,0,0]
        angle = 0
    else:
        axis = []
        for i in range(3):
            axis.append(float(val[i] / theta))
        angle = theta*2 / math.pi * 180
    d.putValue("ExpQuat: " + fr_RotationString(axis, angle))
    d.putNumChild(3)
    if d. isExpanded():
        index = Fr_ElementIndex
        with Children(d):
            for idx in range(3):
                d.putSubItem(index[idx], val[idx])

# ------------------------------------------------------------
# Plane
def qdump__frea__PlaneT(d, value):
    fr_DumpData(d, value, "Plane")
<commit_msg>plane: pretty-printerは法線と原点との距離を印字する<commit_after># coding: utf-8
# QtCreator Debugger用のpretty-printer
from dumper import *
import math

Fr_ElementName = ["x", "y", "z", "w"]
Fr_ElementIndex = []
for idx in range(64):
    Fr_ElementIndex.append("[" + str(idx) + "]")

def fr_GetElementIndex(size):
    u''' 要素数が4つまでのベクトルはXYZW表記、それ以上の場合は数値インデックスのリストを返す '''
    return Fr_ElementName if size<=len(Fr_ElementName) else Fr_ElementIndex

def fr_TypePrefix(b_integral, bitwidth, b_align):
    # Alignedなら先頭にA(aligned)を付与
    typv = "A" if b_align else ""
    if b_integral:
        # 整数型にはI(integral)を付与
        typv += "I"
    else:
        # 内部表現に使うサイズが32bitを超える場合はD(double)を付与
        typv += "" if bitwidth <= 32 else "D"
    return typv

def fr_ArrayString(elem, size, typ):
    s = ""
    comma = False
    for idx in range(size):
        if comma:
            s += ", "
        e = elem[idx]
        if typ == float:
            s += "{0:4.6f}".format(float(e))
        elif typ != None:
            s += str(typ(e))
        else:
            s += str(e)
        comma = True
    return s
def fr_ArrayStringB(elem, size, typ):
    return Embrace(fr_ArrayString(elem, size, typ))
def Embrace(s):
    return "[" + s + "]"

def fr_DumpVector(d, elem, size, typ):
    d.putValue(fr_ArrayStringB(elem, size, typ))
    d.putNumChild(size)

    if d.isExpanded():
        index = fr_GetElementIndex(size)
        with Children(d):
            for idx in range(size):
                d.putSubItem(index[idx], elem[idx])

# ------------------------------------------------------------
# Vector
def fr_DumpData(d, value, name):
    bInt = bool(value["is_integral"])
    d.putType(
        fr_TypePrefix(
            bInt,
            value["bit_width"],
            value["align"]
        )
        + name
        + str(value["size"])
    )
    fr_DumpVector(d, value["m"], int(value["size"]), int if bInt else float)

def qdump__frea__Data(d, value):
    fr_DumpData(d, value, "Data")
def qdump__frea__VecT(d, value):
    fr_DumpData(d, value, "Vec")
def qdump__frea__VecT_spec(d, value):
    fr_DumpData(d, value, "Vec(s)")

# ------------------------------------------------------------
# Vector wrapper
def fr_DumpWrap(d, value, name):
    elem = value["m"]
    size = int(value["size"])
    bw = int(value["bit_width"])
    bInt = bool(value["is_integral"])
    d.putType(fr_TypePrefix(bInt, bw, False) + name + str(size))
    if bInt:
        d.putArrayData(elem.address, size, d.lookupType("unsigned int"))
    else:
        d.putValue(fr_ArrayStringB(elem, size, float))
        d.putNumChild(size)
        if d.isExpanded():
            index = fr_GetElementIndex(size)
            with Children(d):
                for idx in range(size):
                    d.putSubItem(index[idx], elem[idx])

def qdump__frea__wrap(d, value):
    fr_DumpWrap(d, value, "Wrap")
def qdump__frea__wrap_spec(d, value):
    fr_DumpWrap(d, value, "Wrap(s)")

def fr_TupString(value):
    data = value["data"]
    wcap = int(value["w_capacity"])
    bInt = bool(value["is_integral"])
    size = int(value["size"])
    numChild = int(size/wcap)
    modChild = size%wcap
    if modChild != 0:
        numChild += 1
    s = "["
    if not bInt:
        comma = False
        for i in range(numChild-1):
            if comma:
                s += ", "
            s += fr_ArrayString(data[i]["m"], wcap, float)
            comma = True
        s += ", "
        s += fr_ArrayString(
                data[numChild-1]["m"],
                modChild if modChild>0 else wcap,
                float
             )
    s += "]"
    return s

def fr_DumpTup(d, value, name):
    bw = int(value["bit_width"])
    data = value["data"]
    wcap = int(value["w_capacity"])
    bInt = bool(value["is_integral"])
    size = int(value["size"])
    numChild = int(size/wcap)
    modChild = size%wcap
    if modChild != 0:
        numChild += 1
    # 整数型は今の所未対応
    if not bInt:
        d.putValue(fr_TupString(value))
        d.putType(fr_TypePrefix(bInt, bw, False) + name + str(size))
    d.putNumChild(numChild)
    if d.isExpanded():
        with Children(d):
            for idx in range(numChild):
                d.putSubItem(idx, data[idx])

def qdump__frea__tup(d, value):
    fr_DumpTup(d, value, "Wrap")
def qdump__frea__tup_spec(d, value):
    fr_DumpTup(d, value, "Wrap(s)")

# ------------------------------------------------------------
# Matrix wrapper
def fr_DumpWrapM(d, value, name):
    m = int(value["dim_m"])
    n = int(value["dim_n"])
    bInt = bool(value["is_integral"])
    elem = value["v"]

    # 整数型は今の所未対応
    if not bInt:
        s = "["
        comma = False
        for idx in range(m):
            if comma:
                s += ", "
            comma = True
            el = elem[idx]
            try:
                s += fr_ArrayStringB(el["m"], n, None if bInt else float)
            except RuntimeError:
                s += fr_TupString(el)
        s += "]"
        d.putValue(s)
        d.putType(name + "[" + str(m) + "][" + str(n) + "]")
    d.putNumChild(m)
    if d.isExpanded():
        with Children(d):
            for idx in range(m):
                d.putSubItem(idx, elem[idx])

def qdump__frea__wrapM(d, value):
    fr_DumpWrapM(d, value, "WrapM")
def qdump__frea__wrapM_spec(d, value):
    fr_DumpWrapM(d, value, "WrapM(s)")

# ------------------------------------------------------------
# Matrix
def fr_DumpMData(d, value, name):
    m = int(value["dim_m"])
    n = int(value["dim_n"])
    bInt = bool(value["is_integral"])
    bw = int(value["bit_width"])
    align = bool(value["align"])
    elem = value["m"]
    d.putType(
        fr_TypePrefix(bInt, bw, align)
        + name + "[" + str(m) + "][" + str(n) + "]"
    )
    s = "["
    comma = False
    for idx in range(m):
        if comma:
            s += ", "
        comma = True
        s += fr_ArrayStringB(elem[idx]["m"], n, None if bInt else float)
    s += "]"
    d.putValue(s)
    d.putNumChild(m)
    if d. isExpanded():
        index = Fr_ElementIndex
        with Children(d):
            for idx in range(m):
                d.putSubItem(index[idx], elem[idx])

def qdump__frea__DataM(d, value):
    fr_DumpMData(d, value, "DataM")
def qdump__frea__MatT_spec(d, value):
    fr_DumpMData(d, value, "MatT(s)")
def qdump__frea__MatT(d, value):
    fr_DumpMData(d, value, "MatT")

# ------------------------------------------------------------
# Range
def qdump__frea__Range(d, value):
    d.putValue("[" + str(value["from"]) + " | " + str(value["to"]) + "]")
    d.putType("Range")
    d.putNumChild(0)

def fr_AxisString(axis):
    fmt = "{0:3.3f}"
    str_axis = []
    for a in axis:
        str_axis.append(fmt.format(a))
    s = "Axis=[" + ",".join(str_axis) + "]"
    return s
def fr_RotationString(axis, angle):
    fmt = "{0:3.3f}"
    s = fr_AxisString(axis) + " Deg=[" + fmt.format(angle) + "]"
    return s
# ------------------------------------------------------------
# Quaternion
def qdump__frea__QuatT(d, value):
    val = value["m"]
    s_theta = math.sqrt(1.0 - val[3]*val[3])
    if s_theta < 1e-6:
        # 無回転クォータニオンとして扱う
        axis = [0,0,0]
        angle = 0
    else:
        s_theta = 1.0 / s_theta
        axis = []
        for i in range(3):
            axis.append(float(val[i] * s_theta))
        angle = math.acos(val[3])*2 / math.pi * 180

    d.putValue("Quat:" + fr_RotationString(axis, angle))
    d.putType(fr_TypePrefix(value["is_integral"], value["bit_width"], value["align"]) + "Quat")
    d.putNumChild(4)
    if d. isExpanded():
        index = Fr_ElementIndex
        with Children(d):
            for idx in range(4):
                d.putSubItem(index[idx], val[idx])

# ------------------------------------------------------------
# ExpQuaternion
def qdump__frea__ExpQuatT(d, value):
    val = value["m"]
    theta = math.sqrt(val[0]*val[0] + val[1]*val[1] + val[2]*val[2])
    if theta < 1e-6:
        # 無回転クォータニオンとして扱う
        axis = [0,0,0]
        angle = 0
    else:
        axis = []
        for i in range(3):
            axis.append(float(val[i] / theta))
        angle = theta*2 / math.pi * 180
    d.putValue("ExpQuat: " + fr_RotationString(axis, angle))
    d.putNumChild(3)
    if d. isExpanded():
        index = Fr_ElementIndex
        with Children(d):
            for idx in range(3):
                d.putSubItem(index[idx], val[idx])

# ------------------------------------------------------------
# Plane
def qdump__frea__PlaneT(d, value):
    val = value["m"]
    axis = [float(val[0]), float(val[1]), float(val[2])]
    fmt = "{0:3.3f}"
    d.putValue("Plane: " + fr_AxisString(axis) + " D=" + fmt.format(float(val[3])))
    d.putNumChild(4)
    if d. isExpanded():
        index = Fr_ElementIndex
        with Children(d):
            for idx in range(4):
                d.putSubItem(index[idx], val[idx])
<|endoftext|>


<commit_before>"""

fs.remote
=========

Utilities for interfacing with remote filesystems

This module provides reusable utility functions that can be used to construct
FS subclasses interfacing with a remote filesystem.  These include:

  * RemoteFileBuffer:  a file-like object that locally buffers the contents of
                       a remote file, writing them back on flush() or close().

  * ConnectionManagerFS:  a WrapFS subclass that tracks the connection state
                          of a remote FS, and allows client code to wait for
                          a connection to be re-established.

   * CacheFS:  a WrapFS subclass that caces file and directory meta-data in
               memory, to speed access to a remote FS.

"""

import time
import copy

from fs.base import FS, threading
from fs.wrapfs import WrapFS, wrap_fs_methods
from fs.wrapfs.lazyfs import LazyFS
from fs.path import *
from fs.errors import *

try:
   from tempfile import SpooledTemporaryFile as TempFile
except ImportError:
   from tempfile import NamedTemporaryFile as TempFile

class RemoteFileBuffer(object):
    """File-like object providing buffer for local file operations.

    Instances of this class manage a local tempfile buffer corresponding
    to the contents of a remote file.  All reads and writes happen locally,
    with the content being copied to the remote file only on flush() or
    close().  Writes to the remote file are performed using the setcontents()
    method on the owning FS object.

    The intended use-case is for a remote filesystem (e.g. S3FS) to return
    instances of this class from its open() method, and to provide the
    file-uploading logic in its setcontents() method, as in the following
    pseudo-code::

        def open(self,path,mode="r"):
            rf = self._get_remote_file(path)
            return RemoteFileBuffer(self,path,mode,rf)

        def setcontents(self,path,file):
            self._put_remote_file(path,file)

    The current implementation reads the entire contents of the file into
    the buffer before returning.  Future implementations may pull data into
    the buffer on demand.
    """

    def __init__(self,fs,path,mode,rfile=None):
        """RemoteFileBuffer constructor.

        The owning filesystem, path and mode must be provided.  If the
        optional argument 'rfile' is provided, it must be a read()-able
        object or a string containing the initial file contents.
        """
        self.file = TempFile()
        self.fs = fs
        self.path = path
        self.mode = mode
        self.closed = False
        self._flushed = False
        if getattr(fs,"_lock",None) is not None:
            self._lock = fs._lock.__class__()
        else:
            self._lock = threading.RLock()
        if "r" in mode or "+" in mode or "a" in mode:
            if rfile is not None:
                if hasattr(rfile,"read"):
                    data = rfile.read(1024*256)
                    while data:
                        self.file.write(data)
                        data = rfile.read(1024*256)
                else:
                    self.file.write(str(rfile))
                if "a" not in mode:
                    self.file.seek(0)

    def __del__(self):
        if not self.closed:
            self.close()

    def __getattr__(self,name):
        file = self.__dict__['file']
        a = getattr(file, name)
        if not callable(a):
            return a
        @wraps(a)
        def call_with_lock(*args,**kwds):
            self._lock.acquire()
            try:
                if "write" in name:
                    self._flushed = False
                return a(*args,**kwds)
            finally:
                self._lock.release()
        setattr(self, name, call_with_lock)
        return call_with_lock

    def __enter__(self):
        self.file.__enter__()
        return self

    def __exit__(self,exc,value,tb):
        self.close()
        return False

    def __iter__(self):
        return iter(self.file)

    def truncate(self,size=None):
        self._lock.acquire()
        try:
            self.file.truncate(size)
            self.flush()
        finally:
            self._lock.release()

    def flush(self):
        self._lock.acquire()
        try:
            self.file.flush()
            if "w" in self.mode or "a" in self.mode or "+" in self.mode:
                if not self._flushed:
                    pos = self.file.tell()
                    self.file.seek(0)
                    self.fs.setcontents(self.path,self.file)
                    self.file.seek(pos)
                    self._flushed = True
        finally:
            self._lock.release()

    def close(self):
        self._lock.acquire()
        try:
            if not self.closed:
                self.closed = True
                if "w" in self.mode or "a" in self.mode or "+" in self.mode:
                    if not self._flushed:
                        self.file.seek(0)
                        self.file.seek(0)
                        self.fs.setcontents(self.path,self.file)
                self.file.close()
        finally:
            self._lock.release()

class ConnectionManagerFS(LazyFS):
    """FS wrapper providing simple connection management of a remote FS.

    The ConnectionManagerFS class is designed to wrap a remote FS object
    and provide some convenience methods for dealing with its remote
    connection state.

    The boolean attribute 'connected' indicates whether the remote fileystem
    has an active connection, and is initially True.  If any of the remote
    filesystem methods raises a RemoteConnectionError, 'connected' will
    switch to False and remain so until a successful remote method call.

    Application code can use the method 'wait_for_connection' to block
    until the connection is re-established.  Currently this reconnection
    is checked by a simple polling loop; eventually more sophisticated
    operating-system integration may be added.

    Since some remote FS classes can raise RemoteConnectionError during
    initialisation, this class makes use of lazy initialization. The
    remote FS can be specified as an FS instance, an FS subclass, or a
    (class,args) or (class,args,kwds) tuple. For example::

        >>> fs = ConnectionManagerFS(MyRemoteFS("http://www.example.com/"))
        Traceback (most recent call last):
            ...
        RemoteConnectionError: couldn't connect to "http://www.example.com/"
        >>> fs = ConnectionManagerFS((MyRemoteFS,["http://www.example.com/"]))
        >>> fs.connected
        False
        >>>

    """

    poll_interval = 1

    def __init__(self,wrapped_fs,poll_interval=None,connected=True):
        super(ConnectionManagerFS,self).__init__(wrapped_fs)
        if poll_interval is not None:
            self.poll_interval = poll_interval
        self._connection_cond = threading.Condition()
        self._poll_thread = None
        self._poll_sleeper = threading.Event()
        self.connected = connected

    def setcontents(self,path,data):
        return self.wrapped_fs.setcontents(path,data)

    def __getstate__(self):
        state = super(ConnectionManagerFS,self).__getstate__()
        del state["_connection_cond"]
        del state["_poll_sleeper"]
        state["_poll_thread"] = None
        return state

    def __setstate__(self,state):
        super(ConnectionManagerFS,self).__setstate__(state)
        self._connection_cond = threading.Condition()
        self._poll_sleeper = threading.Event()

    def wait_for_connection(self,timeout=None):
        self._connection_cond.acquire()
        try:
            if not self.connected:
                if not self._poll_thread:
                    target = self._poll_connection
                    self._poll_thread = threading.Thread(target=target)
                    self._poll_thread.start()
                self._connection_cond.wait(timeout)
        finally:
            self._connection_cond.release()

    def _poll_connection(self):
        while not self.connected and not self.closed:
            try:
                self.wrapped_fs.isdir("")
            except RemoteConnectionError:
                self._poll_sleeper.wait(self.poll_interval)
                self._poll_sleeper.clear()
            except FSError:
                break
            else:
                break
        self._connection_cond.acquire()
        try:
            if not self.closed:
                self.connected = True
            self._poll_thread = None
            self._connection_cond.notifyAll()
        finally:
            self._connection_cond.release()

    def close(self):
        if not self.closed:
            try:
                super(ConnectionManagerFS,self).close()
            except (RemoteConnectionError,):
                pass
            if self._poll_thread:
                self.connected = True
                self._poll_sleeper.set()
                self._poll_thread.join()
                self._poll_thread = None

def _ConnectionManagerFS_method_wrapper(func):
    """Method wrapper for ConnectionManagerFS.

    This method wrapper keeps an eye out for RemoteConnectionErrors and
    adjusts self.connected accordingly.
    """
    @wraps(func)
    def wrapper(self,*args,**kwds):
        try:
            result = func(self,*args,**kwds)
        except RemoteConnectionError:
            self.connected = False
            raise
        except FSError:
            self.connected = True
            raise
        else:
            self.connected = True
            return result
    return wrapper

wrap_fs_methods(_ConnectionManagerFS_method_wrapper,ConnectionManagerFS)

def _cached_method(func):
    """Method decorator that caches results for CacheFS."""
    @wraps(func)
    def wrapper(self,path="",*args,**kwds):
        try:
            (success,result) = self._cache_get(path,func.__name__,args,kwds)
        except KeyError:
            try:
                res = func(self,path,*args,**kwds)
            except Exception, e:
                self._cache_set(path,func.__name__,args,kwds,(False,e))
                raise
            else:
                self._cache_set(path,func.__name__,args,kwds,(True,res))
                return copy.copy(res)
        else:
            if not success:
                raise result
            else:
                return copy.copy(result)
    return wrapper

class CacheFS(WrapFS):
    """Simple wrapper to cache meta-data of a remote filesystems.

    This FS wrapper implements a simplistic cache that can help speed up
    access to a remote filesystem.  File and directory meta-data is cached
    but the actual file contents are not.
    """

    def __init__(self,fs,timeout=1):
        """CacheFS constructor.

        The optional argument 'timeout' specifies the cache timeout in
        seconds.  The default timeout is 1 second.  To prevent cache
        entries from ever timing out, set it to None.
        """
        self.timeout = timeout
        self._cache = {"":{}}
        super(CacheFS,self).__init__(fs)

    def _path_cache(self,path):
        cache = self._cache
        for name in iteratepath(path):
            cache = cache.setdefault(name,{"":{}})
        return cache

    def _cache_get(self,path,func,args,kwds):
        now = time.time()
        cache = self._path_cache(path)
        key = (tuple(args),tuple(sorted(kwds.iteritems())))
        (t,v) = cache[""][func][key]
        if self.timeout is not None:
            if t < now - self.timeout:
                raise KeyError
        return v

    def _cache_set(self,path,func,args,kwds,v):
        t = time.time()
        cache = self._path_cache(path)
        key = (tuple(args),tuple(sorted(kwds.iteritems())))
        cache[""].setdefault(func,{})[key] = (t,v)

    def _uncache(self,path,added=False,removed=False,unmoved=False):
        cache = self._cache
        names = list(iteratepath(path))
        # If it's not the root dir, also clear some items for ancestors
        if names:
            # Clear cached 'getinfo' and 'getsize' for all ancestors
            for name in names[:-1]:
                cache[""].pop("getinfo",None)
                cache[""].pop("getsize",None)
                cache = cache.get(name,None)
                if cache is None:
                    return
            # Adjust cached 'listdir' for parent directory.
            # TODO: account for whether it was added, removed, or unmoved
            cache[""].pop("getinfo",None)
            cache[""].pop("getsize",None)
            cache[""].pop("listdir",None)
        # Clear all cached info for the path itself.
        cache[names[-1]] = {"":{}}

    @_cached_method
    def exists(self,path):
        return super(CacheFS,self).exists(path)

    @_cached_method
    def isdir(self,path):
        return super(CacheFS,self).isdir(path)

    @_cached_method
    def isfile(self,path):
        return super(CacheFS,self).isfile(path)

    @_cached_method
    def listdir(self,path="",**kwds):
        return super(CacheFS,self).listdir(path,**kwds)

    @_cached_method
    def getinfo(self,path):
        return super(CacheFS,self).getinfo(path)

    @_cached_method
    def getsize(self,path):
        return super(CacheFS,self).getsize(path)

    @_cached_method
    def getxattr(self,path,name,default=None):
        return super(CacheFS,self).getxattr(path,name,default)

    @_cached_method
    def listxattrs(self,path):
        return super(CacheFS,self).listxattrs(path)

    def open(self,path,mode="r"):
        f = super(CacheFS,self).open(path,mode)
        self._uncache(path,unmoved=True)
        return f

    def setcontents(self,path,contents):
        res = super(CacheFS,self).setcontents(path,contents)
        self._uncache(path,unmoved=True)
        return res

    def getcontents(self,path):
        res = super(CacheFS,self).getcontents(path)
        self._uncache(path,unmoved=True)
        return res

    def makedir(self,path,**kwds):
        super(CacheFS,self).makedir(path,**kwds)
        self._uncache(path,added=True)

    def remove(self,path):
        super(CacheFS,self).remove(path)
        self._uncache(path,removed=True)

    def removedir(self,path,**kwds):
        super(CacheFS,self).removedir(path,**kwds)
        self._uncache(path,removed=True)

    def rename(self,src,dst):
        super(CacheFS,self).rename(src,dst)
        self._uncache(src,removed=True)
        self._uncache(dst,added=True)

    def copy(self,src,dst,**kwds):
        super(CacheFS,self).copy(src,dst,**kwds)
        self._uncache(dst,added=True)

    def copydir(self,src,dst,**kwds):
        super(CacheFS,self).copydir(src,dst,**kwds)
        self._uncache(dst,added=True)

    def move(self,src,dst,**kwds):
        super(CacheFS,self).move(src,dst,**kwds)
        self._uncache(src,removed=True)
        self._uncache(dst,added=True)

    def movedir(self,src,dst,**kwds):
        super(CacheFS,self).movedir(src,dst,**kwds)
        self._uncache(src,removed=True)
        self._uncache(dst,added=True)

    def setxattr(self,path,name,value):
        self._uncache(path,unmoved=True)
        return super(CacheFS,self).setxattr(path,name,value)

    def delxattr(self,path,name):
        self._uncache(path,unmoved=True)
        return super(CacheFS,self).delxattr(path,name)

<commit_msg>ensure max_size is always given to SpooledTemporaryFile<commit_after>"""

fs.remote
=========

Utilities for interfacing with remote filesystems

This module provides reusable utility functions that can be used to construct
FS subclasses interfacing with a remote filesystem.  These include:

  * RemoteFileBuffer:  a file-like object that locally buffers the contents of
                       a remote file, writing them back on flush() or close().

  * ConnectionManagerFS:  a WrapFS subclass that tracks the connection state
                          of a remote FS, and allows client code to wait for
                          a connection to be re-established.

   * CacheFS:  a WrapFS subclass that caches file and directory meta-data in
               memory, to speed access to a remote FS.

"""

import time
import copy

from fs.base import FS, threading
from fs.wrapfs import WrapFS, wrap_fs_methods
from fs.wrapfs.lazyfs import LazyFS
from fs.path import *
from fs.errors import *

try:
   from tempfile import SpooledTemporaryFile
except ImportError:
   from tempfile import NamedTemporaryFile
   class SpooledTemporaryFile(NamedTemporaryFile):
        def __init__(self,max_size=0,*args,**kwds):
            NamedTemporaryFile.__init__(self,*args,**kwds)

class RemoteFileBuffer(object):
    """File-like object providing buffer for local file operations.

    Instances of this class manage a local tempfile buffer corresponding
    to the contents of a remote file.  All reads and writes happen locally,
    with the content being copied to the remote file only on flush() or
    close().  Writes to the remote file are performed using the setcontents()
    method on the owning FS object.

    The intended use-case is for a remote filesystem (e.g. S3FS) to return
    instances of this class from its open() method, and to provide the
    file-uploading logic in its setcontents() method, as in the following
    pseudo-code::

        def open(self,path,mode="r"):
            rf = self._get_remote_file(path)
            return RemoteFileBuffer(self,path,mode,rf)

        def setcontents(self,path,file):
            self._put_remote_file(path,file)

    The current implementation reads the entire contents of the file into
    the buffer before returning.  Future implementations may pull data into
    the buffer on demand.
    """

    max_size_in_memory = 1024 * 8

    def __init__(self,fs,path,mode,rfile=None):
        """RemoteFileBuffer constructor.

        The owning filesystem, path and mode must be provided.  If the
        optional argument 'rfile' is provided, it must be a read()-able
        object or a string containing the initial file contents.
        """
        self.file = SpooledTemporyFile(max_size=self.max_size_in_memory)
        self.fs = fs
        self.path = path
        self.mode = mode
        self.closed = False
        self._flushed = False
        if getattr(fs,"_lock",None) is not None:
            self._lock = fs._lock.__class__()
        else:
            self._lock = threading.RLock()
        if "r" in mode or "+" in mode or "a" in mode:
            if rfile is not None:
                if hasattr(rfile,"read"):
                    data = rfile.read(1024*256)
                    while data:
                        self.file.write(data)
                        data = rfile.read(1024*256)
                else:
                    self.file.write(str(rfile))
                if "a" not in mode:
                    self.file.seek(0)

    def __del__(self):
        if not self.closed:
            self.close()

    def __getattr__(self,name):
        file = self.__dict__['file']
        a = getattr(file, name)
        if not callable(a):
            return a
        @wraps(a)
        def call_with_lock(*args,**kwds):
            self._lock.acquire()
            try:
                if "write" in name:
                    self._flushed = False
                return a(*args,**kwds)
            finally:
                self._lock.release()
        setattr(self, name, call_with_lock)
        return call_with_lock

    def __enter__(self):
        self.file.__enter__()
        return self

    def __exit__(self,exc,value,tb):
        self.close()
        return False

    def __iter__(self):
        return iter(self.file)

    def truncate(self,size=None):
        self._lock.acquire()
        try:
            self.file.truncate(size)
            self.flush()
        finally:
            self._lock.release()

    def flush(self):
        self._lock.acquire()
        try:
            self.file.flush()
            if "w" in self.mode or "a" in self.mode or "+" in self.mode:
                if not self._flushed:
                    pos = self.file.tell()
                    self.file.seek(0)
                    self.fs.setcontents(self.path,self.file)
                    self.file.seek(pos)
                    self._flushed = True
        finally:
            self._lock.release()

    def close(self):
        self._lock.acquire()
        try:
            if not self.closed:
                self.closed = True
                if "w" in self.mode or "a" in self.mode or "+" in self.mode:
                    if not self._flushed:
                        self.file.seek(0)
                        self.file.seek(0)
                        self.fs.setcontents(self.path,self.file)
                self.file.close()
        finally:
            self._lock.release()

class ConnectionManagerFS(LazyFS):
    """FS wrapper providing simple connection management of a remote FS.

    The ConnectionManagerFS class is designed to wrap a remote FS object
    and provide some convenience methods for dealing with its remote
    connection state.

    The boolean attribute 'connected' indicates whether the remote fileystem
    has an active connection, and is initially True.  If any of the remote
    filesystem methods raises a RemoteConnectionError, 'connected' will
    switch to False and remain so until a successful remote method call.

    Application code can use the method 'wait_for_connection' to block
    until the connection is re-established.  Currently this reconnection
    is checked by a simple polling loop; eventually more sophisticated
    operating-system integration may be added.

    Since some remote FS classes can raise RemoteConnectionError during
    initialisation, this class makes use of lazy initialization. The
    remote FS can be specified as an FS instance, an FS subclass, or a
    (class,args) or (class,args,kwds) tuple. For example::

        >>> fs = ConnectionManagerFS(MyRemoteFS("http://www.example.com/"))
        Traceback (most recent call last):
            ...
        RemoteConnectionError: couldn't connect to "http://www.example.com/"
        >>> fs = ConnectionManagerFS((MyRemoteFS,["http://www.example.com/"]))
        >>> fs.connected
        False
        >>>

    """

    poll_interval = 1

    def __init__(self,wrapped_fs,poll_interval=None,connected=True):
        super(ConnectionManagerFS,self).__init__(wrapped_fs)
        if poll_interval is not None:
            self.poll_interval = poll_interval
        self._connection_cond = threading.Condition()
        self._poll_thread = None
        self._poll_sleeper = threading.Event()
        self.connected = connected

    def setcontents(self,path,data):
        return self.wrapped_fs.setcontents(path,data)

    def __getstate__(self):
        state = super(ConnectionManagerFS,self).__getstate__()
        del state["_connection_cond"]
        del state["_poll_sleeper"]
        state["_poll_thread"] = None
        return state

    def __setstate__(self,state):
        super(ConnectionManagerFS,self).__setstate__(state)
        self._connection_cond = threading.Condition()
        self._poll_sleeper = threading.Event()

    def wait_for_connection(self,timeout=None):
        self._connection_cond.acquire()
        try:
            if not self.connected:
                if not self._poll_thread:
                    target = self._poll_connection
                    self._poll_thread = threading.Thread(target=target)
                    self._poll_thread.start()
                self._connection_cond.wait(timeout)
        finally:
            self._connection_cond.release()

    def _poll_connection(self):
        while not self.connected and not self.closed:
            try:
                self.wrapped_fs.isdir("")
            except RemoteConnectionError:
                self._poll_sleeper.wait(self.poll_interval)
                self._poll_sleeper.clear()
            except FSError:
                break
            else:
                break
        self._connection_cond.acquire()
        try:
            if not self.closed:
                self.connected = True
            self._poll_thread = None
            self._connection_cond.notifyAll()
        finally:
            self._connection_cond.release()

    def close(self):
        if not self.closed:
            try:
                super(ConnectionManagerFS,self).close()
            except (RemoteConnectionError,):
                pass
            if self._poll_thread:
                self.connected = True
                self._poll_sleeper.set()
                self._poll_thread.join()
                self._poll_thread = None

def _ConnectionManagerFS_method_wrapper(func):
    """Method wrapper for ConnectionManagerFS.

    This method wrapper keeps an eye out for RemoteConnectionErrors and
    adjusts self.connected accordingly.
    """
    @wraps(func)
    def wrapper(self,*args,**kwds):
        try:
            result = func(self,*args,**kwds)
        except RemoteConnectionError:
            self.connected = False
            raise
        except FSError:
            self.connected = True
            raise
        else:
            self.connected = True
            return result
    return wrapper

wrap_fs_methods(_ConnectionManagerFS_method_wrapper,ConnectionManagerFS)

def _cached_method(func):
    """Method decorator that caches results for CacheFS."""
    @wraps(func)
    def wrapper(self,path="",*args,**kwds):
        try:
            (success,result) = self._cache_get(path,func.__name__,args,kwds)
        except KeyError:
            try:
                res = func(self,path,*args,**kwds)
            except Exception, e:
                self._cache_set(path,func.__name__,args,kwds,(False,e))
                raise
            else:
                self._cache_set(path,func.__name__,args,kwds,(True,res))
                return copy.copy(res)
        else:
            if not success:
                raise result
            else:
                return copy.copy(result)
    return wrapper

class CacheFS(WrapFS):
    """Simple wrapper to cache meta-data of a remote filesystems.

    This FS wrapper implements a simplistic cache that can help speed up
    access to a remote filesystem.  File and directory meta-data is cached
    but the actual file contents are not.
    """

    def __init__(self,fs,timeout=1):
        """CacheFS constructor.

        The optional argument 'timeout' specifies the cache timeout in
        seconds.  The default timeout is 1 second.  To prevent cache
        entries from ever timing out, set it to None.
        """
        self.timeout = timeout
        self._cache = {"":{}}
        super(CacheFS,self).__init__(fs)

    def _path_cache(self,path):
        cache = self._cache
        for name in iteratepath(path):
            cache = cache.setdefault(name,{"":{}})
        return cache

    def _cache_get(self,path,func,args,kwds):
        now = time.time()
        cache = self._path_cache(path)
        key = (tuple(args),tuple(sorted(kwds.iteritems())))
        (t,v) = cache[""][func][key]
        if self.timeout is not None:
            if t < now - self.timeout:
                raise KeyError
        return v

    def _cache_set(self,path,func,args,kwds,v):
        t = time.time()
        cache = self._path_cache(path)
        key = (tuple(args),tuple(sorted(kwds.iteritems())))
        cache[""].setdefault(func,{})[key] = (t,v)

    def _uncache(self,path,added=False,removed=False,unmoved=False):
        cache = self._cache
        names = list(iteratepath(path))
        # If it's not the root dir, also clear some items for ancestors
        if names:
            # Clear cached 'getinfo' and 'getsize' for all ancestors
            for name in names[:-1]:
                cache[""].pop("getinfo",None)
                cache[""].pop("getsize",None)
                cache = cache.get(name,None)
                if cache is None:
                    return
            # Adjust cached 'listdir' for parent directory.
            # TODO: account for whether it was added, removed, or unmoved
            cache[""].pop("getinfo",None)
            cache[""].pop("getsize",None)
            cache[""].pop("listdir",None)
        # Clear all cached info for the path itself.
        cache[names[-1]] = {"":{}}

    @_cached_method
    def exists(self,path):
        return super(CacheFS,self).exists(path)

    @_cached_method
    def isdir(self,path):
        return super(CacheFS,self).isdir(path)

    @_cached_method
    def isfile(self,path):
        return super(CacheFS,self).isfile(path)

    @_cached_method
    def listdir(self,path="",**kwds):
        return super(CacheFS,self).listdir(path,**kwds)

    @_cached_method
    def getinfo(self,path):
        return super(CacheFS,self).getinfo(path)

    @_cached_method
    def getsize(self,path):
        return super(CacheFS,self).getsize(path)

    @_cached_method
    def getxattr(self,path,name,default=None):
        return super(CacheFS,self).getxattr(path,name,default)

    @_cached_method
    def listxattrs(self,path):
        return super(CacheFS,self).listxattrs(path)

    def open(self,path,mode="r"):
        f = super(CacheFS,self).open(path,mode)
        self._uncache(path,unmoved=True)
        return f

    def setcontents(self,path,contents):
        res = super(CacheFS,self).setcontents(path,contents)
        self._uncache(path,unmoved=True)
        return res

    def getcontents(self,path):
        res = super(CacheFS,self).getcontents(path)
        self._uncache(path,unmoved=True)
        return res

    def makedir(self,path,**kwds):
        super(CacheFS,self).makedir(path,**kwds)
        self._uncache(path,added=True)

    def remove(self,path):
        super(CacheFS,self).remove(path)
        self._uncache(path,removed=True)

    def removedir(self,path,**kwds):
        super(CacheFS,self).removedir(path,**kwds)
        self._uncache(path,removed=True)

    def rename(self,src,dst):
        super(CacheFS,self).rename(src,dst)
        self._uncache(src,removed=True)
        self._uncache(dst,added=True)

    def copy(self,src,dst,**kwds):
        super(CacheFS,self).copy(src,dst,**kwds)
        self._uncache(dst,added=True)

    def copydir(self,src,dst,**kwds):
        super(CacheFS,self).copydir(src,dst,**kwds)
        self._uncache(dst,added=True)

    def move(self,src,dst,**kwds):
        super(CacheFS,self).move(src,dst,**kwds)
        self._uncache(src,removed=True)
        self._uncache(dst,added=True)

    def movedir(self,src,dst,**kwds):
        super(CacheFS,self).movedir(src,dst,**kwds)
        self._uncache(src,removed=True)
        self._uncache(dst,added=True)

    def setxattr(self,path,name,value):
        self._uncache(path,unmoved=True)
        return super(CacheFS,self).setxattr(path,name,value)

    def delxattr(self,path,name):
        self._uncache(path,unmoved=True)
        return super(CacheFS,self).delxattr(path,name)

<|endoftext|>