Index: fedd/.cvsignore
===================================================================
--- fedd/.cvsignore	(revision 8f4c36115b8c35b9d75ef03fb76a01a4ca93b657)
+++ fedd/.cvsignore	(revision 6679c1229f23e2cd02f0f411c4b107c08713c28b)
@@ -4,3 +4,4 @@
 fedd_services.py*
 fedd_services_types.py*
+fedd_internal_services.py*
 *.pyc
Index: fedd/fedd_create_experiment.py
===================================================================
--- fedd/fedd_create_experiment.py	(revision 6679c1229f23e2cd02f0f411c4b107c08713c28b)
+++ fedd/fedd_create_experiment.py	(revision 6679c1229f23e2cd02f0f411c4b107c08713c28b)
@@ -0,0 +1,923 @@
+#!/usr/local/bin/python
+
+import os,sys
+
+from ZSI import *
+from M2Crypto import SSL
+from M2Crypto.SSL.SSLServer import SSLServer
+import M2Crypto.httpslib
+
+import re
+import random
+import string
+import subprocess
+import tempfile
+import copy
+
+from subprocess import *
+
+from fedd_services import *
+from fedd_internal_services import *
+from fedd_util import *
+import parse_detail
+from service_error import *
+
+class fedd_create_experiment_local:
+    scripts = ["fed_bootstrap", "federate.sh", "smbmount.FreeBSD.pl",
+	"smbmount.Linux.pl", "make_hosts", "fed-tun.pl", "fed_evrepeater", 
+	"rc.accounts.patch"]
+    
+    def __init__(self, 
+	    cert_file=None,
+	    cert_pwd=None,
+	    muxmax=2,
+	    project_user = "faber",
+	    # scp_exec="/bin/echo",
+	    scp_exec="/usr/bin/scp",
+	    scripts_dir="./", 
+	    splitter=None,
+	    # ssh_exec="/bin/echo",
+	    ssh_exec="/usr/bin/ssh",
+	    ssh_identity_file=None,
+	    ssh_keygen="/usr/bin/ssh-keygen",
+	    ssh_pubkey_file=None,
+	    ssh_type="rsa",
+	    tbmap=None,
+	    tclsh="/usr/local/bin/otclsh",
+	    tcl_splitter="/usr/testbed/lib/ns2ir/parse.tcl",
+	    tmpdir="/tmp",
+	    trusted_certs=None,
+	    ):
+	self.scripts = fedd_create_experiment_local.scripts
+
+	self.cert_file = cert_file
+	self.cert_pwd = cert_pwd
+	self.muxmax = muxmax
+	self.project_user = project_user
+	self.scp_exec = scp_exec
+	self.scripts_dir = scripts_dir
+	self.splitter = splitter
+	self.ssh_exec=ssh_exec
+	self.ssh_keygen = ssh_keygen
+	self.ssh_identity_file = ssh_identity_file
+	self.ssh_type = ssh_type
+	self.tclsh = tclsh
+	self.tcl_splitter = tcl_splitter
+	self.tbmap = tbmap
+	self.tmpdir = tmpdir 
+	self.tmpdir += "/split%d/" % os.getpid()
+	self.trusted_certs=trusted_certs
+
+	self.def_expstart = \
+		"sudo -H /bin/sh FEDDIR/fed_bootstrap >& /tmp/federate";
+	self.def_mexpstart = "sudo -H FEDDIR/make_hosts FEDDIR/hosts";
+	self.def_gwstart = \
+		"sudo -H FEDDIR/fed-tun.pl -f GWCONF>& /tmp/bridge.log";
+	self.def_mgwstart = \
+		"sudo -H FEDDIR/fed-tun.pl -f GWCONF >& /tmp/bridge.log";
+	self.def_gwimage = "FBSD61-TUNNEL2";
+	self.def_gwtype = "pc";
+
+
+	if ssh_pubkey_file:
+	    try:
+		f = open(ssh_pubkey_file, 'r')
+		self.ssh_pubkey = f.read()
+		f.close()
+	    except IOError:
+		raise service_error(service_error.internal,
+			"Cannot read sshpubkey")
+
+	# Confirm federation scripts in the right place
+	for s in self.scripts:
+	    if not os.path.exists(self.scripts_dir + "/" + s):
+		raise service_error(service_error.server_config,
+			"%s/%s not in local script dir" % (self.scripts_dir, s))
+
+    def copy_file(self, src, dest, size=1024):
+	"""
+	Exceedingly simple file copy.
+	"""
+	s = open(src,'r')
+	d = open(dest, 'w')
+
+	buf = "x"
+	while buf != "":
+	    buf = s.read(size)
+	    d.write(buf)
+	s.close()
+	d.close()
+
+    def scp_file(self, file, user, host, dest=""):
+	"""
+	scp a file to the remote host.
+	"""
+	
+	rv = call([self.scp_exec, file, "%s@%s:%s" % (user, host, dest)])
+	if rv == 0:
+	    return True
+	else:
+	    # XXX
+	    print >>sys.stdout, "Failed to scp %s to %s@%s" % (file, user, host)
+	    return False
+
+    def ssh_cmd(self, user, host, cmd, wname=None, timeout=0):
+	# This should be done more carefully
+	sub = Popen("%s %s@%s %s" % (self.ssh_exec, user, host, cmd), 
+		shell=True)
+	return sub.wait() == 0
+
+    def ship_scripts(self, host, user, dest_dir):
+	if self.ssh_cmd(user, host, "mkdir -p %s" % dest_dir):
+	    for s in self.scripts:
+		if not self.scp_file("%s/%s" % (self.scripts_dir, s),
+			user, host, dest_dir):
+		    return False
+	    return True
+	else:
+	    return False
+
+    def ship_configs(self, host, user, src_dir, dest_dir):
+	if not self.ssh_cmd(user, host, "mkdir -p %s" % dest_dir):
+	    return False
+	if not self.ssh_cmd(user, host, "chmod 770 %s" % dest_dir):
+	    return False
+
+	for f in os.listdir(src_dir):
+	    if os.path.isdir(f):
+		if not self.ship_configs(host, user, "%s/%s" % (src_dir, f), 
+			"%s/%s" % (dest_dir, f)):
+		    return False
+	    else:
+		if not self.scp_file("%s/%s" % (src_dir, f), 
+			user, host, dest_dir):
+		    return False
+	return True
+
+    def start_segment(self, tb, eid, tbparams, timeout=0):
+	host = "%s%s" % (tbparams[tb]['host'], tbparams[tb]['domain'])
+	user = tbparams[tb]['user']
+	pid = tbparams[tb]['project']
+	# XXX
+	# base_confs = ( "hosts", "vtopo.xml", "viz.xml")
+	base_confs = ( "hosts", "vtopo.xml")
+	tclfile = "%s.%s.tcl" % (eid, tb)
+	expinfo_exec = "/usr/testbed/bin/expinfo"
+	proj_dir = "/proj/%s/exp/%s/tmp" % (pid, eid)
+	tarfiles_dir = "/proj/%s/tarfiles/%s" % (pid, eid)
+	rpms_dir = "/proj/%s/rpms/%s" % (pid, eid)
+	state_re = re.compile("State:\s+(\w+)")
+	state = "none"
+
+	status = Popen([self.ssh_exec, "%s@%s" % (user, host), 
+		expinfo_exec, pid, eid], stdout=PIPE)
+	for line in status.stdout:
+	    m = state_re.match(line)
+	    if m: state = m.group(1)
+	rv = status.wait()
+	if rv != 0:
+	    raise service_error(service_error.internal,
+		    "Cannot get status of segment %s:%s/%s" % (tb, pid, eid))
+	# XXX
+	print "%s: %s" % (tb, state)
+	print "transferring experiment to %s" % tb
+
+	if not self.scp_file("%s/%s/%s" % (self.tmpdir, tb, tclfile),
+		user, host):
+	    return False
+	# Clear and create the tarfiles and rpm directories
+	for d in (tarfiles_dir, rpms_dir):
+	    if not self.ssh_cmd(user, host, 
+		    "/bin/sh -c \"'/bin/rm -rf %s/*'\"" % d):
+		return False
+	    if not self.ssh_cmd(user, host, "mkdir -p %s" % d, 
+		    "create tarfiles"):
+		return False
+	
+	if state == 'active':
+	    # Remote experiment is active.  Modify it.
+	    for f in base_confs:
+		if not self.scp_file("%s/%s" % (self.tmpdir, f), user, host,
+			"%s/%s" % (proj_dir, f)):
+		    return False
+	    if not self.ship_scripts(host, user, proj_dir):
+		return False
+	    if not self.ship_configs(host, user, "%s/%s" % (self.tmpdir, tb),
+		    proj_dir):
+		return False
+	    if os.path.isdir("%s/tarfiles" % self.tmpdir):
+		if not self.ship_configs(host, user,
+			"%s/tarfiles" % self.tmpdir, tarfiles_dir):
+		    return False
+	    if os.path.isdir("%s/rpms" % self.tmpdir):
+		if not self.ship_configs(host, user,
+			"%s/rpms" % self.tmpdir, tarfiles_dir):
+		    return False
+	    print "Modifying %s on %s" % (eid, tb)
+	    if not self.ssh_cmd(user, host,
+		    "/usr/testbed/bin/modexp -r -s -w %s %s %s" % \
+			    (pid, eid, tclfile), "modexp"):
+		return False
+	    return True
+	elif state == "swapped":
+	    # Remote experiment swapped out.  Modify it and swap it in.
+	    for f in base_confs:
+		if not self.scp_file("%s/%s" % (self.tmpdir, f), user, host,
+			"%s/%s" % (proj_dir, f)):
+		    return False
+	    if not self.ship_scripts(host, user, proj_dir):
+		return False
+	    if not self.ship_configs(host, user, "%s/%s" % (self.tmpdir, tb),
+		    proj_dir):
+		return False
+	    if os.path.isdir("%s/tarfiles" % self.tmpdir):
+		if not self.ship_configs(host, user,
+			"%s/tarfiles" % self.tmpdir, tarfiles_dir):
+		    return False
+	    if os.path.isdir("%s/rpms" % self.tmpdir):
+		if not self.ship_configs(host, user,
+			"%s/rpms" % self.tmpdir, tarfiles_dir):
+		    return False
+	    print "Modifying %s on %s" % (eid, tb)
+	    if not self.ssh_cmd(user, host,
+		    "/usr/testbed/bin/modexp -w %s %s %s" % (pid, eid, tclfile),
+		    "modexp"):
+		return False
+	    print "Swapping %s in on %s" % (eid, tb)
+	    if not self.ssh_cmd(user, host,
+		    "/usr/testbed/bin/swapexp -w %s %s in" % (pid, eid),
+		    "swapexp", timeout):
+		return False
+	    return True
+	elif state == "none":
+	    # No remote experiment.  Create one.  We do this in 2 steps so we
+	    # can put the configuration files and scripts into the new
+	    # experiment directories.
+
+	    # Tarfiles must be present for creation to work
+	    if os.path.isdir("%s/tarfiles" % self.tmpdir):
+		if not self.ship_configs(host, user,
+			"%s/tarfiles" % self.tmpdir, tarfiles_dir):
+		    return False
+	    if os.path.isdir("%s/rpms" % self.tmpdir):
+		if not self.ship_configs(host, user,
+			"%s/rpms" % self.tmpdir, tarfiles_dir):
+		    return False
+	    print "Creating %s on %s" % (eid, tb)
+	    if not self.ssh_cmd(user, host,
+		    "/usr/testbed/bin/startexp -i -f -w -p %s -e %s %s" % \
+			    (pid, eid, tclfile), "startexp", timeout):
+		return False
+	    # After startexp the per-experiment directories exist
+	    for f in base_confs:
+		if not self.scp_file("%s/%s" % (self.tmpdir, f), user, host,
+			"%s/%s" % (proj_dir, f)):
+		    return False
+	    if not self.ship_scripts(host, user, proj_dir):
+		return False
+	    if not self.ship_configs(host, user, "%s/%s" % (self.tmpdir, tb),
+		    proj_dir):
+		return False
+	    print "Swapping %s in on %s" % (eid, tb)
+	    if not self.ssh_cmd(user, host,
+		    "/usr/testbed/bin/swapexp -w %s %s in" % (pid, eid),
+		    "swapexp", timeout):
+		return False
+	    return True
+	else:
+	    # XXX
+	    print "unknown state %s" % state
+	    return False
+
+    def stop_segment(self, tb, eid, tbparams):
+	user = tbparams[tb]['user']
+	host = "%s%s" % (tbparams[tb]['host'], tbparams[tb]['domain'])
+	pid = tbparams[tb]['project']
+
+	# XXX: 
+	print "Stopping %s on %s" % (eid, tb)
+	return self.ssh_cmd(user, host,
+		"/usr/testbed/bin/swapexp -w %d %d out" % (pid, eid))
+
+	
+    def generate_ssh_keys(self, dest, type="rsa" ):
+	"""
+	Generate a set of keys for the gateways to use to talk.
+
+	Keys are of type type and are stored in the required dest file.
+	"""
+	valid_types = ("rsa", "dsa")
+	t = type.lower();
+	if t not in valid_types: raise ValueError
+	# May raise CalledProcessError
+	rv = call([self.ssh_keygen, '-t', t, '-N', '', '-f', dest])
+	if rv != 0:
+	    raise service_error(service_error.internal, 
+		    "Cannot generate nonce ssh keys.  %s return code %d" \
+			    % (self.ssh_keygen, rv))
+
+    def genviz(self, topo_file, viz_file): pass
+
+    def get_access(self, tb, nodes, user, tbparam):
+	"""
+	Get access to testbed through fedd and set the parameters for that tb
+	"""
+
+	translate_attr = {
+	    'slavenodestartcmd': 'expstart',
+	    'slaveconnectorstartcmd': 'gwstart',
+	    'masternodestartcmd': 'mexpstart',
+	    'masterconnectorstartcmd': 'mgwstart',
+	    'connectorimage': 'gwimage',
+	    'connectortype': 'gwtype',
+	    'tunnelcfg': 'tun',
+	}
+
+	# XXX multi-level access
+	uri = self.tbmap.get(tb, None)
+	if not uri:
+	    raise service_error(serice_error.server_config, 
+		    "Unknown testbed: %s" % tb)
+
+	# The basic request
+	req = {\
+		'destinationTestbed' : { 'uri' : uri },
+		'user':  user,
+		'allocID' : { 'username': 'test' },
+		'access' : [ { 'sshPubkey' : self.ssh_pubkey } ]
+	    }
+	
+	# node resources if any
+	if nodes != None and len(nodes) > 0:
+	    rnodes = [ ]
+	    for n in nodes:
+		rn = { }
+		image, hw, count = n.split(":")
+		if image: rn['image'] = [ image ]
+		if hw: rn['hardware'] = [ hw ]
+		if count: rn['count'] = int(count)
+		rnodes.append(rn)
+	    req['resources']= { }
+	    req['resources']['node'] = rnodes
+
+	# No retry loop here.  Proxy servers must correctly authenticate
+	# themselves without help
+	try:
+	    ctx = fedd_ssl_context(self.cert_file, 
+		    self.trusted_certs, password=self.cert_pwd)
+	except SSL.SSLError:
+	    raise service_error(service_error.server_config, 
+		    "Server certificates misconfigured")
+
+	loc = feddServiceLocator();
+	port = loc.getfeddPortType(uri,
+		transport=M2Crypto.httpslib.HTTPSConnection, 
+		transdict={ 'ssl_context' : ctx })
+
+	# Reconstruct the full request message
+	msg = RequestAccessRequestMessage()
+	msg.set_element_RequestAccessRequestBody(
+		pack_soap(msg, "RequestAccessRequestBody", req))
+	try:
+	    resp = port.RequestAccess(msg)
+	except ZSI.ParseException, e:
+	    raise service_error(service_error.req,
+		    "Bad format message (XMLRPC??): %s" %
+		    str(e))
+	r = unpack_soap(resp)
+
+	if r.has_key('RequestAccessResponseBody'):
+	    r = r['RequestAccessResponseBody']
+	else:
+	    raise service_error(service_error.proxy,
+		    "Bad proxy response")
+
+
+	e = r['emulab']
+	p = e['project']
+	tbparam[tb] = { 
+		"boss": e['boss'],
+		"host": e['ops'],
+		"domain": e['domain'],
+		"fs": e['fileServer'],
+		"eventserver": e['eventServer'],
+		"project": unpack_id(p['name'])
+		}
+
+	for u in p['user']:
+	    tbparam[tb]['user'] = unpack_id(u['userID'])
+
+	for a in e['fedAttr']:
+	    if a['attribute']:
+		key = translate_attr.get(a['attribute'].lower(), None)
+		if key:
+		    tbparam[tb][key]= a['value']
+	
+    class current_testbed:
+	def __init__(self, eid, tmpdir):
+	    self.begin_testbed = re.compile("^#\s+Begin\s+Testbed\s+\((\w+)\)")
+	    self.end_testbed = re.compile("^#\s+End\s+Testbed\s+\((\w+)\)")
+	    self.current_testbed = None
+	    self.testbed_file = None
+
+	    self.def_expstart = \
+		    "sudo -H /bin/sh FEDDIR/fed_bootstrap >& /tmp/federate";
+	    self.def_mexpstart = "sudo -H FEDDIR/make_hosts FEDDIR/hosts";
+	    self.def_gwstart = \
+		    "sudo -H FEDDIR/fed-tun.pl -f GWCONF>& /tmp/bridge.log";
+	    self.def_mgwstart = \
+		    "sudo -H FEDDIR/fed-tun.pl -f GWCONF >& /tmp/bridge.log";
+	    self.def_gwimage = "FBSD61-TUNNEL2";
+	    self.def_gwtype = "pc";
+
+	    self.eid = eid
+	    self.tmpdir = tmpdir
+
+	def __call__(self, line, master, allocated, tbparams):
+	    # Capture testbed topology descriptions
+	    if self.current_testbed == None:
+		m = self.begin_testbed.match(line)
+		if m != None:
+		    self.current_testbed = m.group(1)
+		    if self.current_testbed == None:
+			raise service_error(service_error.req,
+				"Bad request format (unnamed testbed)")
+		    allocated[self.current_testbed] = \
+			    allocated.get(self.current_testbed,0) + 1
+		    tb_dir = "%s/%s" % (self.tmpdir, self.current_testbed)
+		    if not os.path.exists(tb_dir):
+			try:
+			    os.mkdir(tb_dir)
+			except IOError:
+			    raise service_error(service_error.internal,
+				    "Cannot create %s" % tb_dir)
+		    try:
+			self.testbed_file = open("%s/%s.%s.tcl" %
+				(tb_dir, self.eid, self.current_testbed), 'w')
+		    except IOError:
+			self.testbed_file = None
+		    return True
+		else: return False
+	    else:
+		m = self.end_testbed.match(line)
+		if m != None:
+		    if m.group(1) != self.current_testbed:
+			raise service_error(service_error.internal, 
+				"Mismatched testbed markers!?")
+		    if self.testbed_file != None: 
+			self.testbed_file.close()
+			self.testbed_file = None
+		    self.current_testbed = None
+		elif self.testbed_file:
+		    # Substitute variables and put the line into the local
+		    # testbed file.
+		    gwtype = tbparams[self.current_testbed].get('gwtype', 
+			    self.def_gwtype)
+		    gwimage = tbparams[self.current_testbed].get('gwimage', 
+			    self.def_gwimage)
+		    mgwstart = tbparams[self.current_testbed].get('mgwstart', 
+			    self.def_mgwstart)
+		    mexpstart = tbparams[self.current_testbed].get('mexpstart', 
+			    self.def_mexpstart)
+		    gwstart = tbparams[self.current_testbed].get('gwstart', 
+			    self.def_gwstart)
+		    expstart = tbparams[self.current_testbed].get('expstart', 
+			    self.def_expstart)
+		    project = tbparams[self.current_testbed].get('project')
+		    line = re.sub("GWTYPE", gwtype, line)
+		    line = re.sub("GWIMAGE", gwimage, line)
+		    if self.current_testbed == master:
+			line = re.sub("GWSTART", mgwstart, line)
+			line = re.sub("EXPSTART", mexpstart, line)
+		    else:
+			line = re.sub("GWSTART", gwstart, line)
+			line = re.sub("EXPSTART", expstart, line)
+		    # XXX: does `` embed without doing enything else?
+		    line = re.sub("GWCONF", "FEDDIR`hostname`.gw.conf", line)
+		    line = re.sub("PROJDIR", "/proj/%s/" % project, line)
+		    line = re.sub("EID", self.eid, line)
+		    line = re.sub("FEDDIR", "/proj/%s/exp/%s/tmp/" % \
+			    (project, self.eid), line)
+		    print >>self.testbed_file, line
+		return True
+
+    class allbeds:
+	def __init__(self, get_access):
+	    self.begin_allbeds = re.compile("^#\s+Begin\s+Allbeds")
+	    self.end_allbeds = re.compile("^#\s+End\s+Allbeds")
+	    self.in_allbeds = False
+	    self.get_access = get_access
+
+	def __call__(self, line, user, tbparams):
+	    # Testbed access parameters
+	    if not self.in_allbeds:
+		if self.begin_allbeds.match(line):
+		    self.in_allbeds = True
+		    return True
+		else:
+		    return False
+	    else:
+		if self.end_allbeds.match(line):
+		    self.in_allbeds = False
+		else:
+		    nodes = line.split('|')
+		    tb = nodes.pop(0)
+		    self.get_access(tb, nodes, user, tbparams)
+		return True
+
+    class gateways:
+	def __init__(self, eid, smbshare, master, tmpdir, gw_pubkey,
+		gw_secretkey, copy_file):
+	    self.begin_gateways = \
+		    re.compile("^#\s+Begin\s+gateways\s+\((\w+)\)")
+	    self.end_gateways = re.compile("^#\s+End\s+gateways\s+\((\w+)\)")
+	    self.current_gateways = None
+	    self.control_gateway = None
+	    self.active_end = { }
+
+	    self.eid = eid
+	    self.smbshare = smbshare
+	    self.master = master
+	    self.tmpdir = tmpdir
+	    self.gw_pubkey_base = gw_pubkey
+	    self.gw_secretkey_base = gw_secretkey
+
+	    self.copy_file = copy_file
+
+
+	def gateway_conf_file(self, gw, master, eid, pubkey, privkey,
+		active_end, tbparams, dtb, myname, desthost, type):
+	    """
+	    Produce a gateway configuration file from a line of the gateways section
+	    """
+
+	    sproject = tbparams[gw].get('project', 'project')
+	    dproject = tbparams[dtb].get('project', 'project')
+	    sdomain = ".%s.%s%s" % (eid, sproject,
+		    tbparams[gw].get('domain', ".example.com"))
+	    ddomain = ".%s.%s%s" % (eid, dproject,
+		    tbparams[dtb].get('domain', ".example.com"))
+	    boss = tbparams[master].get('boss', "boss")
+	    fs = tbparams[master].get('fs', "fs")
+	    event_server = "%s%s" % \
+		    (tbparams[master].get('eventserver', "event_server"),
+			    tbparams[master].get('domain', "example.com"))
+	    remote_event_server = "%s%s" % \
+		    (tbparams[dtb].get('eventserver', "event_server"),
+			    tbparams[dtb].get('domain', "example.com"))
+
+	    remote_script_dir = "/proj/%s/exp/%s/tmp" % ( dproject, eid)
+	    local_script_dir = "/proj/%s/exp/%s/tmp" % ( sproject, eid)
+	    tunnel_cfg = tbparams[gw].get("tun", "false")
+
+	    conf_file = "%s%s.gw.conf" % (myname, sdomain)
+	    remote_conf_file = "%s%s.gw.conf" % (desthost, ddomain)
+
+	    # translate to lower case so the `hostname` hack for specifying
+	    # configuration files works.
+	    conf_file = conf_file.lower();
+	    remote_conf_file = remote_conf_file.lower();
+
+	    if dtb == master:
+		active = "false"
+	    elif gw == master:
+		active = "true"
+	    elif active_end.has_key['%s-%s' % (dtb, gw)]:
+		active = "false"
+	    else:
+		active_end['%s-%s' % (gw, dtb)] = 1
+		active = "true"
+
+	    gwconfig = open("%s/%s/%s" % (self.tmpdir, gw, conf_file), "w")
+	    print >>gwconfig, "Active: %s" % active
+	    print >>gwconfig, "TunnelCfg: %s" % tunnel_cfg
+	    print >>gwconfig, "BossName: %s" % boss
+	    print >>gwconfig, "FsName: %s" % fs
+	    print >>gwconfig, "EventServerName: %s" % event_server
+	    print >>gwconfig, "RemoteEventServerName: %s" % remote_event_server
+	    print >>gwconfig, "Type: %s" % type
+	    print >>gwconfig, "RemoteScriptDir: %s" % remote_script_dir
+	    print >>gwconfig, "EventRepeater: %s/fed_evrepeater" % \
+		    local_script_dir
+	    print >>gwconfig, "RemoteExperiment: %s/%s" % (dproject, eid)
+	    print >>gwconfig, "LocalExperiment: %s/%s" % (sproject, eid)
+	    print >>gwconfig, "RemoteConfigFile: %s/%s" % \
+		    (remote_script_dir, remote_conf_file)
+	    print >>gwconfig, "Peer: %s%s" % (desthost, ddomain)
+	    print >>gwconfig, "Pubkeys: %s/%s" % (local_script_dir, pubkey)
+	    print >>gwconfig, "Privkeys: %s/%s" % (local_script_dir, privkey)
+	    gwconfig.close()
+
+	    return active == "true"
+
+	def __call__(self, line, allocated, tbparams):
+	    # Process gateways
+	    if not self.current_gateways:
+		m = self.begin_gateways.match(line)
+		if m:
+		    self.current_gateways = m.group(1)
+		    if allocated.has_key(self.current_gateways):
+			# This test should always succeed
+			tb_dir = "%s/%s" % (self.tmpdir, self.current_gateways)
+			if not os.path.exists(tb_dir):
+			    try:
+				os.mkdir(tb_dir)
+			    except IOError:
+				raise service_error(service_error.internal,
+					"Cannot create %s" % tb_dir)
+		    else:
+			# XXX
+			print >>sys.stderr, \
+			    "Ignoring gateways for unknown testbed %s" \
+				    % self.current_gateways
+			self.current_gateways = None
+		    return True
+		else:
+		    return False
+	    else:
+		m = self.end_gateways.match(line)
+		if m :
+		    if m.group(1) != self.current_gateways:
+			raise service_error(service_error.internal,
+				"Mismatched gateway markers!?")
+		    if self.control_gateway:
+			try:
+			    cc = open("%s/%s/client.conf" %
+				    (self.tmpdir, self.current_gateways), 'w')
+			    print >>cc, "ControlGateway: %s" % \
+				    self.control_gateway
+			    print >>cc, "SMBSHare: %s" % self.smbshare
+			    print >>cc, "ProjectUser: %s" % \
+				    tbparams[self.current_gateways]['user']
+			    print >>cc, "ProjectName: %s" % \
+				    tbparams[self.master]['project']
+			    cc.close()
+			except IOError:
+			    raise service_error(service_error.internal,
+				    "Error creating client config")
+		    else:
+			# XXX
+			print >>sys.stderr, "No control gateway for %s" %\
+				self.current_gateways
+		    self.current_gateways = None
+		else:
+		    dtb, myname, desthost, type = line.split(" ")
+
+		    if type == "control" or type == "both":
+			self.control_gateway = "%s.%s.%s%s" % (myname, 
+				self.eid, 
+				tbparams[self.current_gateways]['project'],
+				tbparams[self.current_gateways]['domain'])
+		    try:
+			active = self.gateway_conf_file(self.current_gateways,
+				self.master, self.eid, self.gw_pubkey_base,
+				self.gw_secretkey_base,
+				self.active_end, tbparams, dtb, myname,
+				desthost, type)
+		    except IOError, e:
+			raise service_error(service_error.internal,
+				"Failed to write config file for %s" % \
+					self.current_gateway)
+	    
+		    gw_pubkey = "%s/keys/%s" % \
+			    (self.tmpdir, self.gw_pubkey_base)
+		    gw_secretkey = "%s/keys/%s" % \
+			    (self.tmpdir, self.gw_secretkey_base)
+
+		    pkfile = "%s/%s/%s" % \
+			    ( self.tmpdir, self.current_gateways, 
+				    self.gw_pubkey_base)
+		    skfile = "%s/%s/%s" % \
+			    ( self.tmpdir, self.current_gateways, 
+				    self.gw_secretkey_base)
+
+		    if not os.path.exists(pkfile):
+			try:
+			    self.copy_file(gw_pubkey, pkfile)
+			except IOError:
+			    service_error(service_error.internal,
+				    "Failed to copy pubkey file")
+
+		    if active and not os.path.exists(skfile):
+			try:
+			    self.copy_file(gw_secretkey, skfile)
+			except IOError:
+			    service_error(service_error.internal,
+				    "Failed to copy secretkey file")
+		return True
+
+    class shunt_to_file:
+	def __init__(self, begin, end, filename):
+	    self.begin = re.compile(begin)
+	    self.end = re.compile(end)
+	    self.in_shunt = False
+	    self.file = None
+	    self.filename = filename
+
+	def __call__(self, line):
+	    if not self.in_shunt:
+		if self.begin.match(line):
+		    self.in_shunt = True
+		    try:
+			self.file = open(self.filename, "w")
+		    except:
+			self.file = None
+			raise
+		    return True
+		else:
+		    return False
+	    else:
+		if self.end.match(line):
+		    if self.file: 
+			self.file.close()
+			self.file = None
+		    self.in_shunt = False
+		else:
+		    if self.file:
+			print >>self.file, line
+		return True
+
+    class shunt_to_list:
+	def __init__(self, begin, end):
+	    self.begin = re.compile(begin)
+	    self.end = re.compile(end)
+	    self.in_shunt = False
+	    self.list = [ ]
+	
+	def __call__(self, line):
+	    if not self.in_shunt:
+		if self.begin.match(line):
+		    self.in_shunt = True
+		    return True
+		else:
+		    return False
+	    else:
+		if self.end.match(line):
+		    self.in_shunt = False
+		else:
+		    self.list.append(line)
+		return True
+
+    def create_experiment(self, req, fid):
+	gw_pubkey_base = "fed.%s.pub" % self.ssh_type
+	gw_secretkey_base = "fed.%s" % self.ssh_type
+	gw_pubkey = self.tmpdir + "/keys/" + gw_pubkey_base
+	gw_secretkey = self.tmpdir + "/keys/" + gw_secretkey_base
+	tclfile = self.tmpdir + "/experiment.tcl"
+	tbparams = { }
+
+	pid = "dummy"
+	gid = "dummy"
+	# XXX
+	eid = "faber-splitter"
+	# XXX
+	master = "deter"
+	# XXX
+	smbshare="USERS"
+	# XXX
+	fail_soft = False
+	# XXX
+	startem = True
+
+	try:
+	    os.mkdir(self.tmpdir)
+	    os.mkdir(self.tmpdir+"/keys")
+	except OSError:
+	    raise service_error(service_error.internal,
+		    "Can't make temporary dir")
+
+	# The tcl parser needs to read a file so put the content into that file
+	file_content=req.get('experimentdescription', None)
+	if file_content != None:
+	    try:
+		f = open(tclfile, 'w')
+		f.write(file_content)
+		f.close()
+	    except IOError:
+		raise service_error(service_error.internal,
+			"Cannot write temp experiment description")
+	else:
+	    raise service_error(service_error.req, "No experiment description")
+
+	try:
+	    self.generate_ssh_keys(gw_secretkey, self.ssh_type)
+	except ValueError:
+	    raise service_error(service_error.server_config, 
+		    "Bad key type (%s)" % self.ssh_type)
+
+	user = req.get('user', None)
+	if user == None:
+	    raise service_error(service_error.req, "No user")
+	
+	
+	tclcmd = [self.tclsh, self.tcl_splitter, '-s', '-x', 
+	    str(self.muxmax), '-m', master, pid, gid, eid, tclfile]
+	tclparser = Popen(tclcmd, stdout=PIPE)
+
+	allocated = { }
+	started = { }
+
+	parse_current_testbed = self.current_testbed(eid, self.tmpdir)
+	parse_allbeds = self.allbeds(self.get_access)
+	parse_gateways = self.gateways(eid, smbshare, master, self.tmpdir,
+		gw_pubkey_base, gw_secretkey_base, self.copy_file)
+	parse_vtopo = self.shunt_to_file("^#\s+Begin\s+Vtopo",
+		    "^#\s+End\s+Vtopo", self.tmpdir + "/vtopo.xml")
+	parse_hostnames = self.shunt_to_file("^#\s+Begin\s+hostnames",
+		    "^#\s+End\s+hostnames", self.tmpdir + "/hosts")
+	parse_tarfiles = self.shunt_to_list("^#\s+Begin\s+tarfiles",
+		"^#\s+End\s+tarfiles")
+	parse_rpms = self.shunt_to_list("^#\s+Begin\s+rpms",
+		"^#\s+End\s+rpms")
+
+	for line in tclparser.stdout:
+	    line = line.rstrip()
+	    if parse_current_testbed(line, master, allocated, tbparams):
+		continue
+	    elif parse_allbeds(line, user, tbparams):
+		continue
+	    elif parse_gateways(line, allocated, tbparams):
+		continue
+	    elif parse_vtopo(line):
+		continue
+	    elif parse_hostnames(line):
+		continue
+	    elif parse_tarfiles(line):
+		continue
+	    elif parse_rpms(line):
+		continue
+	    else:
+		raise service_error(service_error.internal, 
+			"Bad tcl parse? %s" % line)
+
+	if not startem: return True
+
+	# Copy tarfiles and rpms needed at remote sites into a staging area
+	try:
+	    for t in parse_tarfiles.list:
+		if not os.path.exists("%s/tarfiles" % self.tmpdir):
+		    os.mkdir("%s/tarfiles" % self.tmpdir)
+		self.copy_file(t, "%s/tarfiles/%s" % \
+			(self.tmpdir, os.path.basename(t)))
+	    for r in parse_rpms.list:
+		if not os.path.exists("%s/rpms" % self.tmpdir):
+		    os.mkdir("%s/rpms" % self.tmpdir)
+		self.copy_file(r, "%s/rpms/%s" % \
+			(self.tmpdir, os.path.basename(r)))
+	except IOError, e:
+	    raise service_error(service_error.internal, 
+		    "Cannot stage tarfile/rpm: %s" % e.strerror)
+	
+	# XXX: more parallelism
+	for tb in allocated.iterkeys():
+	    if tb != master:
+		if self.start_segment(tb, eid, tbparams, 0):
+		    started[tb] = True
+		else:
+		    break
+
+	if len(started) == len(allocated)-1:
+	    if self.start_segment(master, eid, tbparams):
+		started[master] = True
+	
+	if not fail_soft and  len(allocated) != len(started):
+	    for tb in started.iterkeys():
+		self.stop_segment(tb, eid, tbparams)
+	else:
+	    print "Experiment started"
+
+	# XXX: return value
+
+if __name__ == '__main__':
+    from optparse import OptionParser
+    
+    parser = OptionParser()
+    parser.add_option('-f', '--file', dest='tcl', help='tcl file to parse')
+    opts, args  = parser.parse_args()
+
+    if opts.tcl != None:
+	try:
+	    f = open(opts.tcl, 'r')
+	    content = ''.join(f)
+	    f.close()
+	except IOError, e:
+	    sys.exit("Can't read %s: %s" % (opts.tcl, e))
+    else:
+	sys.exit("Must specify a file name")
+
+    obj = fedd_create_experiment_local(
+	    scripts_dir="/users/faber/testbed/federation",
+	    cert_file="./fedd_client.pem", cert_pwd="faber", 
+	    ssh_pubkey_file='/users/faber/.ssh/id_rsa.pub',
+	    trusted_certs="./cacert.pem",
+	    tbmap = { 
+		'deter':'https://users.isi.deterlab.net:23235',
+		'emulab':'https://users.isi.deterlab.net:23236',
+		'ucb':'https://users.isi.deterlab.net:23237',
+		},
+	) 
+    obj.create_experiment( {\
+	    'experimentdescription' : content, 
+	    'user': [ {'userID' : { 'username' : 'faber' } } ],
+	    },
+	    None)
Index: fedd/fedd_types.xsd
===================================================================
--- fedd/fedd_types.xsd	(revision 8f4c36115b8c35b9d75ef03fb76a01a4ca93b657)
+++ fedd/fedd_types.xsd	(revision 6679c1229f23e2cd02f0f411c4b107c08713c28b)
@@ -111,4 +111,18 @@
   </xsd:complexType>
 
+  <xsd:complexType name="mapType">
+    <xsd:annotation>
+      <xsd:documentation>
+	Explicit translation of testbed attribute in a federated experiment
+	description.  Used in a creation request.
+      </xsd:documentation>
+    </xsd:annotation>
+    <xsd:sequence>
+      <xsd:element name="testbed" type="tns:IDType"/>
+      <xsd:element name="uri" type="xsd:string"/>
+    </xsd:sequence>
+  </xsd:complexType>
+
+
   <xsd:complexType name="projectType">
     <xsd:annotation>
@@ -118,4 +132,6 @@
     </xsd:annotation>
     <xsd:sequence>
+      <xsd:element name="testbed" type="tns:IDType" minOccurs="0"
+	maxOccurs="1"/>
       <xsd:element name="name" type="tns:IDType" minOccurs="0" maxOccurs="1"/>
       <xsd:element name="user" type="tns:userType" minOccurs="0"
@@ -204,4 +220,31 @@
       <xsd:element name="until" type="xsd:dateTime" minOccurs="0" 
 	maxOccurs="1"/>
+    </xsd:sequence>
+  </xsd:complexType>
+
+  <xsd:complexType name="createRequestType">
+    <xsd:annotation>
+      <xsd:documentation>
+	A request to embed a federated experiment across testbeds
+      </xsd:documentation>
+    </xsd:annotation>
+    <xsd:sequence>
+      <xsd:element name="testbedmap" type="tns:mapType" minOccurs="0"
+	maxOccurs="unbounded"/>
+      <xsd:element name="user" type="tns:userType" minOccurs="1"
+	maxOccurs="unbounded"/>
+      <xsd:element name="experimentdescription" type="xsd:base64Binary"/>
+    </xsd:sequence>
+  </xsd:complexType>
+
+  <xsd:complexType name="createResponseType">
+    <xsd:annotation>
+      <xsd:documentation>
+	A request to embed a federated experiment across testbeds
+      </xsd:documentation>
+    </xsd:annotation>
+    <xsd:sequence>
+      <xsd:element name="project" type="projectType" minOccurs="1" 
+	maxOccurs="unbounded"/>
     </xsd:sequence>
   </xsd:complexType>
