Permalink
Browse files

NMControl 0.8

Split plugins between plugins and services
New service "DNS"
plugin NamespaceDomain now use the DNS service
  • Loading branch information...
1 parent fe6fe21 commit 0abd8a32de6b48ac665cc2c2347f7ddf10e6d0b1 @khalahan khalahan committed Jul 26, 2012
View
@@ -2,6 +2,8 @@ TODO
====
Remarks/TODO :
+- need to clean old code + dns server code (remove endswith from lib/dnsServer/namecoindns.py, etc)
+- finish the split between the DNS service and namespaces plugins
* plugins
- DATA: allow to start and stop namecoin to do full updates
- DATA: fetch data only for used namespaces
@@ -12,3 +14,4 @@ Remarks/TODO :
- tested only on linux => need to be adapted for windows & mac too
- need a gui
+
@@ -1,15 +1,15 @@
+from common import *
import os, json
class backendData():
- def __init__(self, app, filename):
- self.app = app
+ def __init__(self, filename):
self.datafile = filename
def getAllNames(self):
if not os.path.exists(self.datafile):
return True, 'Config file "' + self.datafile + '" doesn\'t exist.'
- data = open(self.app['path']['app'] + self.datafile).read()
+ data = open(app['path']['app'] + self.datafile).read()
try:
data = json.loads(data)
except:
@@ -1,9 +1,9 @@
+from common import *
import rpcClient
import ConfigParser, StringIO
class backendData():
- def __init__(self, app, conf):
- self.app = app
+ def __init__(self, conf):
self.conf = conf
rpc = None
@@ -32,7 +32,7 @@ def _loadRPCConfig(self):
def getAllNames(self):
datas = {}
- error, data = self._rpcSend(["name_filter", self.app['plugins']['data'].conf['name_filter']])
+ error, data = self._rpcSend(["name_filter", app['plugins']['data'].conf['name_filter']])
for name in data:
datas[name['name']] = name
return error, datas
@@ -41,7 +41,7 @@ def getName(self, name):
return self._rpcSend(["name_show", name])
def _rpcSend(self, rpcCmd):
- if self.app['debug']: print "BackendDataNamecoin:", rpcCmd
+ if app['debug']: print "BackendDataNamecoin:", rpcCmd
if self.rpc is None:
self._loadRPCConfig()
return self.rpc.sendJson(rpcCmd)
View
@@ -0,0 +1,3 @@
+
+app = {}
+
@@ -23,7 +23,7 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
-# Modified by Khalahan in order ti include it in nmcontrol
+# Modified by Khalahan in order to include it in nmcontrol
# Modified by sonicrules1234 (Westly Ward) in order to have it work as a dns server for all domains rather than just one
# File originally named pymds
import sys
@@ -36,19 +36,15 @@
import threading
from utils import *
+from common import *
class DnsError(Exception):
pass
class DnsServer(threading.Thread):
daemon = True;
running = True
- app = None
udps = None
-
- def __init__(self, app):
- self.app = app
- threading.Thread.__init__(self)
def run(self):
self.serve()
@@ -57,8 +53,8 @@ def serve(self):
self.udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.udps.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
udps = self.udps
- listen_host = self.app['plugins']['dns'].conf['host']
- listen_port = int(self.app['plugins']['dns'].conf['port'])
+ listen_host = app['services']['dns'].conf['host']
+ listen_port = int(app['services']['dns'].conf['port'])
try:
udps.bind((listen_host, listen_port))
except socket.error as e:
@@ -83,7 +79,7 @@ def serve(self):
question = map(lambda x: x.lower(), question)
found = False
source_module = __import__("namecoindns", globals(), locals(), [])
- source_instance = source_module.Source(self.app)
+ source_instance = source_module.Source()
for config in [True]:
#if question[1:] == config['domain']:
#query = question[0]
@@ -106,7 +102,7 @@ def serve(self):
exception_rcode = 3
raise Exception("query is not for our domain: %s" % ".".join(question))
except:
- if self.app['debug']: traceback.print_exc()
+ if app['debug']: traceback.print_exc()
if not self.running:
continue
if qid:
@@ -253,8 +249,8 @@ def format_resource(resource, question):
# die("Usage: %s\n" % (cmd))
#config_files = {}
-listen_port = 1053
-listen_host = ''
+#listen_port = 1053
+#listen_host = ''
#try:
# options, filenames = getopt.getopt(sys.argv[1:], "p:h:")
@@ -1,5 +1,6 @@
import DNS
import json, base64, types, traceback
+from common import *
def lookup(sp, qdict) :
domain = qdict["domain"]
@@ -15,7 +16,7 @@ def lookup(sp, qdict) :
try:
item = json.loads(item)
except:
- if self.app['debug']: traceback.print_exc()
+ if app['debug']: traceback.print_exc()
return
if str(item[u"name"]) == "d/" + host :
@@ -6,11 +6,12 @@
import struct, listdns, base64, types, json, random
#from jsonrpc import ServiceProxy
from utils import *
+from common import *
class Source(object):
- def __init__(self, app):
- self.servers = app['plugins']['dns'].conf['resolver'].split(',')
- self.reqobj = DNS.Request()
+ #def __init__(self):
+ #self.servers = app['services']['dns'].conf['resolver'].split(',')
+ #self.reqobj = DNS.Request()
#jsonfile = open("config.json", "r")
#data = json.loads(jsonfile.read())
#jsonfile.close()
@@ -19,7 +20,7 @@ def __init__(self, app):
#password = str(data[u"password"])
#self.sp = ServiceProxy("http://%(user)s:%(passwd)s@127.0.0.1:%(port)d" % dict(user=username, passwd=password, port=port))
#elf.sp = rpcClient.rpcClientNamecoin('127.0.0.1', port, username, password)
- self.sp = app['plugins']['domain']
+ #self.sp = app['plugins']['domain']
# def _parse_file(self):
# f = open(self._filename, "r")
@@ -93,9 +94,13 @@ def get_response(self, query, domain, qtype, qclass, src_addr):
#answer = struct.pack("!I", ipstr2int(value))
reqtype = "AAAA"
else : reqtype = None
- if domain.endswith(".bit") :
+ answers = app['services']['dns'].lookup({"query":query, "domain":domain, "qtype":qtype, "qclass":qclass, "src_addr":src_addr})
+ #print 'domain:', domain
+ #print 'answers:', answers
+ if domain.endswith(".bit") or domain.endswith(".tor") :
#response = listdns.lookup(self.sp, {"query":query, "domain":domain, "qtype":qtype, "qclass":qclass, "src_addr":src_addr})
- response = self.sp.lookup({"query":query, "domain":domain, "qtype":qtype, "qclass":qclass, "src_addr":src_addr})
+ #response = self.sp.lookup({"query":query, "domain":domain, "qtype":qtype, "qclass":qclass, "src_addr":src_addr})
+ response = answers
results = []
if type(response) == types.DictType :
tempresults = {"qtype":response["type"], "qclass":response["class"], "ttl":response["ttl"]}
@@ -130,8 +135,8 @@ def get_response(self, query, domain, qtype, qclass, src_addr):
# if they asked for an A record and we didn't find one, check for a CNAME
#return self.get_response(query, domain, 5, qclass, src_addr)
else:
- server = self.servers[random.randrange(0, len(self.servers)-1)]
- answers = self.reqobj.req(name=domain, qtype=qtype, server=server).answers
+ #server = self.servers[random.randrange(0, len(self.servers)-1)]
+ #answers = self.reqobj.req(name=domain, qtype=qtype, server=server).answers
results = []
for response in answers :
tempresults = {"qtype":response["type"], "qclass":response["class"], "ttl":response["ttl"]}
View
@@ -1,3 +1,4 @@
+from common import *
import threading
import time
import os
@@ -10,52 +11,60 @@
class PluginThread(threading.Thread):
daemon = True
- app = None
name = None
+ mode = None
desc = None
running = False
options = {}
helps = {}
- depends = []
+ depends = {}
+ services = {}
#version = None
- def __init__(self, app):
+ def __init__(self, mode = 'plugin'):
if self.name is None:
raise Exception(str(self.__class__) + " : name not defined")
- self.app = app
- self.nameconf = 'plugin-' + self.name + '.conf'
- self.nameclass = 'plugin' + self.name.capitalize()
+ self.mode = mode
+ self.nameconf = self.mode + '-' + self.name + '.conf'
+ self.nameclass = self.mode + self.name.capitalize()
self.parser = app['parser']
self.conf = {}
self._loadconfig()
threading.Thread.__init__(self)
+ def start(self):
+ threading.Thread.start(self)
+
def run(self):
if self.running: return
self.start2()
def start2(self, arg = []):
- if self.app['debug']: print "Plugin %s parent starting" %(self.name)
+ if app['debug']: print "Plugin %s parent starting" %(self.name)
self.running = True
# start depends
if len(self.depends) > 0:
- for dep in self.depends:
- self.app['plugins'][dep].start()
+ if 'plugins' in self.depends:
+ for dep in self.depends['plugins']:
+ app['plugins'][dep].start()
+ if 'services' in self.depends:
+ for dep in self.depends['services']:
+ app['services'][dep].start()
return self.pStart()
def pStart(self, arg = []):
- if self.app['debug']: print "Plugin %s parent start" %(self.name)
+ if app['debug']: print "Plugin %s parent start" %(self.name)
#time.sleep(1)
return True
def stop(self, arg = []):
if not self.running: return
- if self.app['debug']: print "Plugin %s parent stopping" %(self.name)
+ if app['debug']: print "Plugin %s parent stopping" %(self.name)
self.running = False
return self.pStop()
def pStop(self, arg = []):
- if self.app['debug']: print "Plugin %s parent stop" %(self.name)
+ if app['debug']: print "Plugin %s parent stop" %(self.name)
print "Plugin %s stopped" %(self.name)
return True
@@ -67,20 +76,20 @@ def pStatus(self, arg = []):
return "Plugin " + self.name + " running"
def reload(self, arg = []):
- if self.app['debug']: print "Plugin %s parent reloading" %(self.name)
+ if app['debug']: print "Plugin %s parent reloading" %(self.name)
return self.pReload()
def pReload(self, arg = []):
- if self.app['debug']: print "Plugin %s parent reload" %(self.name)
+ if app['debug']: print "Plugin %s parent reload" %(self.name)
self.loadconfig()
return True
def restart(self, arg = []):
- if self.app['debug']: print "Plugin %s parent restarting" %(self.name)
+ if app['debug']: print "Plugin %s parent restarting" %(self.name)
return self.pRestart()
def pRestart(self, arg = []):
- if self.app['debug']: print "Plugin %s parent restart" %(self.name)
+ if app['debug']: print "Plugin %s parent restart" %(self.name)
self.stop()
self.start2()
return True
@@ -91,15 +100,15 @@ def help(self, arg = []):
def pHelp(self, arg = []):
#if arg[0] == 'help':
# help = '* Available plugins :\n'
- # for plugin in self.app['plugins']:
- # if self.app['plugins'][plugin].running == True:
+ # for plugin in app['plugins']:
+ # if app['plugins'][plugin].running == True:
# help += '\n' + plugin + ' help'
# return help
if len(arg[1]) > 1:
- if arg[1][1] in self.app['plugins'][arg[0]].helps:
- help = self.app['plugins'][arg[0]].helps[arg[1][1]][3]
- help += '\n' + arg[1][1] + ' ' + self.app['plugins'][arg[0]].helps[arg[1][1]][2]
+ if arg[1][1] in app['plugins'][arg[0]].helps:
+ help = app['plugins'][arg[0]].helps[arg[1][1]][3]
+ help += '\n' + arg[1][1] + ' ' + app['plugins'][arg[0]].helps[arg[1][1]][2]
return help
methods = self._getPluginMethods()
@@ -133,9 +142,15 @@ def _getPluginMethods(self):
return methods
def _loadconfig(self, arg = []):
+ # manage services
+ for service, value in self.services.iteritems():
+ if self.name not in app['services'][service].services:
+ app['services'][service].services = {}
+ app['services'][service].services[self.name] = value
+
# add command line args to the program options + build default configuration data
defaultConf = '[' + self.name + ']\n'
- group = OptionGroup(self.app['parser'], self.name.capitalize() + " Options", self.desc)
+ group = OptionGroup(app['parser'], self.name.capitalize() + " Options", self.desc)
if self.options.__class__ is dict:
tmp = []
for option, value in self.options.items():
@@ -157,13 +172,13 @@ def _loadconfig(self, arg = []):
else:
group.add_option('--' + self.name + '.' + option, type='str', help=help, metavar=str(value[1]))
self.conf[option] = value[1]
- self.app['parser'].add_option_group(group)
+ app['parser'].add_option_group(group)
# create default config if none
- userConfFile = self.app['path']['conf'] + self.nameconf
+ userConfFile = app['path']['conf'] + self.nameconf
if not os.path.exists(userConfFile):
- if not os.path.exists(self.app['path']['conf']):
- os.mkdir(self.app['path']['conf'])
+ if not os.path.exists(app['path']['conf']):
+ os.mkdir(app['path']['conf'])
fp = open(userConfFile, 'w')
fp.write(defaultConf)
fp.close()
Oops, something went wrong.

0 comments on commit 0abd8a3

Please sign in to comment.