LinuxApplication: making single deploy.sh script out of http_sources.sh, build.sh...
[nepi.git] / src / nepi / resources / linux / ccn / ccnd.py
index 35d4de2..d2358a4 100644 (file)
 
 from nepi.execution.attribute import Attribute, Flags, Types
 from nepi.execution.trace import Trace, TraceAttr
-from nepi.execution.resource import ResourceManager, clsinit_copy, ResourceState
+from nepi.execution.resource import ResourceManager, clsinit_copy, ResourceState, \
+    reschedule_delay
 from nepi.resources.linux.application import LinuxApplication
 from nepi.resources.linux.node import OSType
+from nepi.util.timefuncs import tnow, tdiffsec
 
-from nepi.util.sshfuncs import ProcStatus
-from nepi.util.timefuncs import strfnow, strfdiff
 import os
 
+# TODO: use ccndlogging to dynamically change the logging level
+
+
 @clsinit_copy
 class LinuxCCND(LinuxApplication):
     _rtype = "LinuxCCND"
@@ -46,6 +49,7 @@ class LinuxCCND(LinuxApplication):
             "  128 - face registration debugging \n"
             "  -1 - max logging \n"
             "  Or apply bitwise OR to these values to get combinations of them",
+            type = Types.Integer,
             flags = Flags.ExecReadOnly)
 
         port = Attribute("port", "Sets the CCN_LOCAL_PORT environmental variable. "
@@ -121,42 +125,91 @@ class LinuxCCND(LinuxApplication):
 
     def __init__(self, ec, guid):
         super(LinuxCCND, self).__init__(ec, guid)
-        # Marks whether daemon is running
-        self._running = False
-
-    def deploy(self):
-        if not self.get("command"):
-            self.set("command", self._default_command)
-        
-        if not self.get("depends"):
-            self.set("depends", self._default_dependencies)
-
-        if not self.get("sources"):
-            self.set("sources", self._default_sources)
+        self._home = "ccnd-%s" % self.guid
+        self._version = "ccnx"
 
-        if not self.get("build"):
-            self.set("build", self._default_build)
-
-        if not self.get("install"):
-            self.set("install", self._default_install)
+    @property
+    def version(self):
+        return self._version
 
-        if not self.get("env"):
-            self.set("env", self._default_environment)
+    @property
+    def path(self):
+        return "PATH=$PATH:${BIN}/%s/" % self.version 
 
-        super(LinuxCCND, self).deploy()
+    def deploy(self):
+        if not self.node or self.node.state < ResourceState.READY:
+            self.debug("---- RESCHEDULING DEPLOY ---- node state %s " % self.node.state )
+            
+            # ccnd needs to wait until node is deployed and running
+            self.ec.schedule(reschedule_delay, self.deploy)
+        else:
+            try:
+                if not self.get("command"):
+                    self.set("command", self._start_command)
+                
+                if not self.get("depends"):
+                    self.set("depends", self._dependencies)
+
+                if not self.get("sources"):
+                    self.set("sources", self._sources)
+
+                sources = self.get("sources")
+                source = sources.split(" ")[0]
+                basename = os.path.basename(source)
+                self._version = ( basename.strip().replace(".tar.gz", "")
+                        .replace(".tar","")
+                        .replace(".gz","")
+                        .replace(".zip","") )
+
+                if not self.get("build"):
+                    self.set("build", self._build)
+
+                if not self.get("install"):
+                    self.set("install", self._install)
+
+                if not self.get("env"):
+                    self.set("env", self._environment)
+
+                command = self.get("command")
+
+                self.info("Deploying command '%s' " % command)
+
+                self.discover()
+                self.provision()
+            except:
+                self.fail()
+                raise
+            self.debug("----- READY ---- ")
+            self._ready_time = tnow()
+            self._state = ResourceState.READY
+
+    def upload_start_command(self):
+        command = self.get("command")
+        env = self.get("env")
+
+        if command:
+            # We want to make sure the ccnd is running
+            # before the experiment starts.
+            # Run the command as a bash script in background,
+            # in the host ( but wait until the command has
+            # finished to continue )
+            env = self.replace_paths(env)
+            command = self.replace_paths(command)
 
-        # As soon as the ccnd sources are deployed, we launch the
-        # daemon ( we don't want to lose time launching the ccn 
-        # daemon later on )
+            shfile = os.path.join(self.app_home, "start.sh")
+            self.node.run_and_wait(command, self.run_home,
+                    shfile = shfile,
+                    overwrite = False,
+                    env = env,
+                    raise_on_error = True)
+    
+    def start(self):
         if self._state == ResourceState.READY:
-            self._start_in_background()
-            self._running = True
+            command = self.get("command")
+            self.info("Starting command '%s'" % command)
 
-    def start(self):
-        # CCND should already be started by now.
-        # Nothing to do but to set the state to STARTED
-        if self._running:
-            self._start_time = strfnow()
+            self._start_time = tnow()
             self._state = ResourceState.STARTED
         else:
             msg = " Failed to execute command '%s'" % command
@@ -179,43 +232,39 @@ class LinuxCCND(LinuxApplication):
             env = env and self.replace_paths(env)
 
             # Upload the command to a file, and execute asynchronously
-            self.node.run_and_wait(command, self.app_home,
-                        shfile = "ccndstop.sh",
+            shfile = os.path.join(self.app_home, "stop.sh")
+            self.node.run_and_wait(command, self.run_home,
+                        shfile = shfile,
+                        overwrite = False,
                         env = env,
                         pidfile = "ccndstop_pidfile", 
                         ecodefile = "ccndstop_exitcode", 
                         stdout = "ccndstop_stdout", 
                         stderr = "ccndstop_stderr")
 
-
-            super(LinuxCCND, self).stop()
-
+            self._stop_time = tnow()
+            self._state = ResourceState.STOPPED
+    
     @property
     def state(self):
         # First check if the ccnd has failed
-        if self._running and strfdiff(strfnow(), self._last_state_check) > state_check_delay:
-            state_check_delay = 0.5
-            (out, err), proc = self._cndstatus()
+        state_check_delay = 0.5
+        if self._state == ResourceState.STARTED and \
+                tdiffsec(tnow(), self._last_state_check) > state_check_delay:
+            (out, err), proc = self._ccndstatus
 
             retcode = proc.poll()
 
             if retcode == 1 and err.find("No such file or directory") > -1:
                 # ccnd is not running (socket not found)
-                self._running = False
                 self._state = ResourceState.FINISHED
             elif retcode:
                 # other errors ...
-                self._running = False
-                msg = " Failed to execute command '%s'" % command
+                msg = " Failed to execute command '%s'" % self.get("command")
                 self.error(msg, out, err)
                 self._state = ResourceState.FAILED
 
-            self._last_state_check = strfnow()
-
-        if self._state == ResourceState.READY:
-            # CCND is really deployed only when ccn daemon is running 
-            if not self._running:
-                return ResourceState.PROVISIONED
+            self._last_state_check = tnow()
 
         return self._state
 
@@ -223,68 +272,71 @@ class LinuxCCND(LinuxApplication):
     def _ccndstatus(self):
         env = self.get('env') or ""
         environ = self.node.format_environment(env, inline = True)
-        command = environ + "; ccndstatus"
+        command = environ + " ccndstatus"
         command = self.replace_paths(command)
     
         return self.node.execute(command)
 
     @property
-    def _default_command(self):
+    def _start_command(self):
         return "ccndstart"
 
     @property
-    def _default_dependencies(self):
-        if self.node.os in [ OSType.FEDORA_12 , OSType.FEDORA_14 ]:
+    def _dependencies(self):
+        if self.node.use_rpm:
             return ( " autoconf openssl-devel  expat-devel libpcap-devel "
                 " ecryptfs-utils-devel libxml2-devel automake gawk " 
                 " gcc gcc-c++ git pcre-devel make ")
-        elif self.node.os in [ OSType.UBUNTU , OSType.DEBIAN]:
+        elif self.node.use_deb:
             return ( " autoconf libssl-dev libexpat-dev libpcap-dev "
                 " libecryptfs0 libxml2-utils automake gawk gcc g++ "
                 " git-core pkg-config libpcre3-dev make ")
         return ""
 
     @property
-    def _default_sources(self):
-        return "http://www.ccnx.org/releases/ccnx-0.7.1.tar.gz"
+    def _sources(self):
+        return "http://www.ccnx.org/releases/ccnx-0.7.2.tar.gz"
 
     @property
-    def _default_build(self):
+    def _build(self):
         sources = self.get("sources").split(" ")[0]
         sources = os.path.basename(sources)
 
         return (
             # Evaluate if ccnx binaries are already installed
             " ( "
-                " test -f ${EXP_HOME}/ccnx/bin/ccnd && "
-                " echo 'sources found, nothing to do' "
+                " test -f ${BIN}/%(version)s/ccnd && "
+                " echo 'binaries found, nothing to do' "
             " ) || ( "
             # If not, untar and build
                 " ( "
-                    " mkdir -p ${SOURCES}/ccnx && "
-                    " tar xf ${SOURCES}/%(sources)s --strip-components=1 -C ${SOURCES}/ccnx "
+                    " mkdir -p ${SRC}/%(version)s && "
+                    " tar xf ${SRC}/%(sources)s --strip-components=1 -C ${SRC}/%(version)s "
                  " ) && "
-                    "cd ${SOURCES}/ccnx && "
+                    "cd ${SRC}/%(version)s && "
                     # Just execute and silence warnings...
                     " ( ./configure && make ) "
-             " )") % ({ 'sources': sources })
+             " )") % ({ 'sources': sources,
+                        'version': self.version
+                 })
 
     @property
-    def _default_install(self):
+    def _install(self):
         return (
             # Evaluate if ccnx binaries are already installed
             " ( "
-                " test -f ${EXP_HOME}/ccnx/bin/ccnd && "
-                " echo 'sources found, nothing to do' "
+                " test -f ${BIN}/%(version)s/ccnd && "
+                " echo 'binaries found, nothing to do' "
             " ) || ( "
             # If not, install
-                "  mkdir -p ${EXP_HOME}/ccnx/bin && "
-                "  cp -r ${SOURCES}/ccnx ${EXP_HOME}"
+                "  mkdir -p ${BIN}/%(version)s && "
+                "  mv ${SRC}/%(version)s/bin/* ${BIN}/%(version)s/ "
             " )"
-            )
+            ) % ({ 'version': self.version
+                 })
 
     @property
-    def _default_environment(self):
+    def _environment(self):
         envs = dict({
             "debug": "CCND_DEBUG",
             "port": "CCN_LOCAL_PORT",
@@ -301,12 +353,12 @@ class LinuxCCND(LinuxApplication):
             "prefix" : "CCND_PREFIX",
             })
 
-        env = "PATH=$PATH:${EXP_HOME}/ccnx/bin "
-        env += " ".join(map(lambda k: "%s=%s" % (envs.get(k), self.get(k)) \
+        env = self.path 
+        env += " ".join(map(lambda k: "%s=%s" % (envs.get(k), str(self.get(k))) \
             if self.get(k) else "", envs.keys()))
         
         return env            
-        
+
     def valid_connection(self, guid):
         # TODO: Validate!
         return True