Beispiel #1
0
    def execute(self):
        # Run the job queue service
        path = self.kwargs.get("path")

        plugin_dir = Environment.get_plugin_dir()
        path = path.replace("${TACTIC_PLUGIN_DIR}", plugin_dir)

        cmd_list = []
        cmd_list.append(python)
        cmd_list.append(path)

        program = subprocess.Popen(cmd_list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
        #program.wait()

        buffer = []
        while 1:
            char = program.stdout.read(1)
            if not char:
                break

            if char == "\n":
                line = "".join(buffer)
                #print(line)

            buffer.append(char)
Beispiel #2
0
    def execute(my):
        # Run the job queue service
        path = my.kwargs.get("path")

        plugin_dir = Environment.get_plugin_dir()
        path = path.replace("${TACTIC_PLUGIN_DIR}", plugin_dir)

        cmd_list = []
        cmd_list.append(python)
        cmd_list.append(path)

        program = subprocess.Popen(cmd_list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
        #program.wait()

        buffer = []
        while 1:
            char = program.stdout.read(1)
            if not char:
                break

            if char == "\n":
                line = "".join(buffer)
                print line

            buffer.append(char)
Beispiel #3
0
    def filter_xml(my, xml):
        dirname = os.path.dirname(my.rel_path)

        # filter images
        img_nodes = xml.get_nodes("//img")
        install_dir = Environment.get_install_dir()
        for node in img_nodes:
            src = xml.get_attribute(node, "src")

            if src.startswith("/tactic/plugins/"):
                plugin_dir = Environment.get_plugin_dir()
                path = "%s/%s" % (plugin_dir,
                                  src.replace("/tactic/plugins/", ""))
            elif src.startswith("/tactic/builtin_plugins/"):
                plugin_dir = Environment.get_builtin_plugin_dir()
                path = "%s/%s" % (plugin_dir,
                                  src.replace("/tactic/builtin_plugins/", ""))

            elif src.startswith("/"):
                path = "%s/src%s" % (install_dir, src)
            else:
                path = "%s/doc/%s/%s" % (install_dir, dirname, src)

            size = (0, 0)
            try:
                from PIL import Image
                im = Image.open(path)
                size = im.size
            except IOError, e:
                print "Error importing Image: ", e

            except:
Beispiel #4
0
    def filter_xml(my, xml):
        dirname = os.path.dirname(my.rel_path)


        # filter images
        img_nodes = xml.get_nodes("//img")
        install_dir = Environment.get_install_dir()
        for node in img_nodes:
            src = xml.get_attribute(node, "src")

            if src.startswith("/tactic/plugins/"):
                plugin_dir = Environment.get_plugin_dir()
                path = "%s/%s" % (plugin_dir, src.replace("/tactic/plugins/", "") )
            elif src.startswith("/tactic/builtin_plugins/"):
                plugin_dir = Environment.get_builtin_plugin_dir()
                path = "%s/%s" % (plugin_dir, src.replace("/tactic/builtin_plugins/", "") )



            elif src.startswith("/"):
                path = "%s/src%s" % (install_dir, src)
            else:
                path = "%s/doc/%s/%s" % (install_dir, dirname, src)

            size = (0,0)
            try:
                from PIL import Image 
                im = Image.open(path)
                size = im.size
            except IOError, e:
                print "Error importing Image: ", e
                
            except:
Beispiel #5
0
    def get_display(my):

        alias = my.kwargs.get("alias")

        my.rel_path = my.kwargs.get("rel_path")
        if not my.rel_path:
            from tactic_client_lib import TacticServerStub

            server = TacticServerStub.get(protocol="local")
            my.rel_path = server.get_doc_link(alias)

        if not my.rel_path or my.rel_path == "none_found":
            # raise TacticException("Help alias [%s] does not exist" % alias)
            layout = DivWdg()
            layout.add(HelpCreateWdg(alias=alias))
            layout.add(HelpDocFilterWdg(alias="main"))
            return layout

        # special condition for plugins path
        if my.rel_path.startswith("/plugins/"):
            plugin_dir = Environment.get_plugin_dir()
            rel_path = my.rel_path.replace("/plugins/", "")
            path = "%s/%s" % (plugin_dir, rel_path)
        elif my.rel_path.startswith("/builtin_plugins/"):
            plugin_dir = Environment.get_builtin_plugin_dir()
            rel_path = my.rel_path.replace("/builtin_plugins/", "")
            path = "%s/%s" % (plugin_dir, rel_path)
        elif my.rel_path.startswith("/assets/"):
            asset_dir = Environment.get_asset_dir()
            rel_path = my.rel_path.replace("/assets/", "")
            path = "%s/%s" % (asset_dir, rel_path)
        else:

            # see if there is an override
            doc_dir = os.environ.get("TACTIC_DOC_DIR")
            if not doc_dir:
                doc_dir = Config.get_value("install", "doc_dir")
            if not doc_dir:
                install_dir = Environment.get_install_dir()
                doc_dir = "%s/doc" % install_dir

            path = "%s/%s" % (doc_dir, my.rel_path)

        html = []
        try:
            f = open(path, "r")
            count = 0
            for line in f:
                line = my.filter_line(line, count)
                html.append(line)
                count += 1
            f.close()
        except Exception, e:
            print "Error processing: ", e
            html.append("Error processing document: %s<br/><br/>" % str(e))
Beispiel #6
0
    def __init__(self, project_code=None, login_code=None, site=None):
        self.set_app_server("batch")

        if not site:
            # if not explicitly set, keep the current site
           site = Site.get_site() 


        plugin_dir = Environment.get_plugin_dir()
        if plugin_dir not in sys.path:
            sys.path.insert(0, plugin_dir)

        super(Batch,self).__init__()

        self.login_code = login_code

        # clear the main container
        Container.create()

        if site:
            Site.set_site(site)

        # set this as the environment
        if not project_code:
            self.context = self.get_default_context()
        else:
            self.context = project_code

        Environment.set_env_object( self )

        # set up the security object
        security = Security()
        Environment.set_security(security)

        self._do_login()
        site_dir = Environment.get_site_dir()
        if site_dir not in sys.path:
            sys.path.insert(0, site_dir)

        # set the project
        from pyasm.biz import Project

        if self.context == "batch":
            Project.set_project("admin")
        else:
            Project.set_project(self.context)

        self.initialize_python_path()


        # start workflow engine
        #from pyasm.command import Workflow
        #Workflow().init()

        DbContainer.commit_thread_sql()
Beispiel #7
0
    def get_display(my):

        alias = my.kwargs.get("alias")

        my.rel_path = my.kwargs.get("rel_path")
        if not my.rel_path:
            from tactic_client_lib import TacticServerStub
            server = TacticServerStub.get(protocol='local')
            my.rel_path = server.get_doc_link(alias)

        if not my.rel_path or my.rel_path == 'none_found':
            #raise TacticException("Help alias [%s] does not exist" % alias)
            layout = DivWdg()
            layout.add(HelpCreateWdg(alias=alias))
            layout.add(HelpDocFilterWdg(alias='main'))
            return layout

        # special condition for plugins path
        if my.rel_path.startswith("/plugins/"):
            plugin_dir = Environment.get_plugin_dir()
            rel_path = my.rel_path.replace("/plugins/", "")
            path = "%s/%s" % (plugin_dir, rel_path)
        elif my.rel_path.startswith("/builtin_plugins/"):
            plugin_dir = Environment.get_builtin_plugin_dir()
            rel_path = my.rel_path.replace("/builtin_plugins/", "")
            path = "%s/%s" % (plugin_dir, rel_path)
        elif my.rel_path.startswith("/assets/"):
            asset_dir = Environment.get_asset_dir()
            rel_path = my.rel_path.replace("/assets/", "")
            path = "%s/%s" % (asset_dir, rel_path)
        else:

            # see if there is an override
            doc_dir = os.environ.get("TACTIC_DOC_DIR")
            if not doc_dir:
                doc_dir = Config.get_value("install", "doc_dir")
            if not doc_dir:
                install_dir = Environment.get_install_dir()
                doc_dir = "%s/doc" % install_dir

            path = "%s/%s" % (doc_dir, my.rel_path)

        html = []
        try:
            f = open(path, 'r')
            count = 0
            for line in f:
                line = my.filter_line(line, count)
                html.append(line)
                count += 1
            f.close()
        except Exception, e:
            print "Error processing: ", e
            html.append("Error processing document: %s<br/><br/>" % str(e))
Beispiel #8
0
    def __init__(my, num_processes=None):
        my.check_interval = 120
        my.num_processes = num_processes
        my.dev_mode = False

        import sys
        plugin_dir = Environment.get_plugin_dir()
        sys.path.insert(0, plugin_dir)

        sql = DbContainer.get("sthpw")
        # before batch, clean up the ticket with a NULL code
        sql.do_update('DELETE from "ticket" where "code" is NULL;')
Beispiel #9
0
    def __init__(my, num_processes=None):
        my.check_interval = 120
        my.num_processes = num_processes
        my.dev_mode = False

        import sys
        plugin_dir = Environment.get_plugin_dir()
        sys.path.insert(0, plugin_dir)

        sql = DbContainer.get("sthpw")
        # before batch, clean up the ticket with a NULL code
        sql.do_update('DELETE from "ticket" where "code" is NULL;')
Beispiel #10
0
    def __init__(self, num_processes=None):
        self.check_interval = 120
        self.startup = True
        self.num_processes = num_processes
        self.dev_mode = False

        import sys
        plugin_dir = Environment.get_plugin_dir()
        sys.path.insert(0, plugin_dir)

        sql = DbContainer.get("sthpw")
        # before batch, clean up the ticket with a NULL code
        sql.do_update('DELETE from "ticket" where "code" is NULL;')

        self.tactic_threads = []
        self.mode = 'normal'
Beispiel #11
0
def import_schema(plugin_code):
    from pyasm.search import Transaction
    transaction = Transaction.get(create=True)

    install_dir = Environment.get_install_dir()
    base_dir = Environment.get_plugin_dir()
    template_dir = "%s/%s" % (base_dir, plugin_code)
    manifest_path = "%s/manifest.xml" % (template_dir)
    print "Reading manifest: ", manifest_path

    xml = Xml()
    xml.read_file(manifest_path)

    # create a new project
    installer = PluginInstaller(base_dir=base_dir, manifest=xml.to_string() )
    installer.execute()
Beispiel #12
0
    def __init__(self, num_processes=None):
        self.check_interval = 120
        self.startup = True
        self.num_processes = num_processes
        self.dev_mode = False

        import sys
        plugin_dir = Environment.get_plugin_dir()
        sys.path.insert(0, plugin_dir)

        sql = DbContainer.get("sthpw")
        # before batch, clean up the ticket with a NULL code
        sql.do_update('DELETE from "ticket" where "code" is NULL;')

        self.tactic_threads = []
        self.mode = 'normal'
Beispiel #13
0
def import_schema(plugin_code):
    from pyasm.search import Transaction
    transaction = Transaction.get(create=True)

    install_dir = Environment.get_install_dir()
    base_dir = Environment.get_plugin_dir()
    template_dir = "%s/%s" % (base_dir, plugin_code)
    manifest_path = "%s/manifest.xml" % (template_dir)
    print "Reading manifest: ", manifest_path

    xml = Xml()
    xml.read_file(manifest_path)

    # create a new project
    installer = PluginInstaller(base_dir=base_dir, manifest=xml.to_string())
    installer.execute()
Beispiel #14
0
    def __init__(my, project_code=None, login_code=None, site=None):
        my.set_app_server("batch")

        plugin_dir = Environment.get_plugin_dir()
        if plugin_dir not in sys.path:
            sys.path.insert(0, plugin_dir)

        super(Batch,my).__init__()

        my.login_code = login_code

        # clear the main container
        Container.create()

        if site:
            Site.set_site(site)

        # set this as the environment
        if not project_code:
            my.context = my.get_default_context()
        else:
            my.context = project_code

        Environment.set_env_object( my )

        # set up the security object
        security = Security()
        Environment.set_security(security)

        my._do_login()
        site_dir = Environment.get_site_dir()
        if site_dir not in sys.path:
            sys.path.insert(0, site_dir)

        # set the project
        from pyasm.biz import Project

        if my.context == "batch":
            Project.set_project("admin")
        else:
            Project.set_project(my.context)

        my.initialize_python_path()

        DbContainer.commit_thread_sql()
Beispiel #15
0
    def __init__(my, project_code=None, login_code=None, site=None):
        my.set_app_server("batch")

        plugin_dir = Environment.get_plugin_dir()
        if plugin_dir not in sys.path:
            sys.path.insert(0, plugin_dir)

        super(Batch, my).__init__()

        my.login_code = login_code

        # clear the main container
        Container.create()

        if site:
            Site.set_site(site)

        # set this as the environment
        if not project_code:
            my.context = my.get_default_context()
        else:
            my.context = project_code

        Environment.set_env_object(my)

        # set up the security object
        security = Security()
        Environment.set_security(security)

        my._do_login()
        site_dir = Environment.get_site_dir()
        if site_dir not in sys.path:
            sys.path.insert(0, site_dir)

        # set the project
        from pyasm.biz import Project

        if my.context == "batch":
            Project.set_project("admin")
        else:
            Project.set_project(my.context)

        my.initialize_python_path()

        DbContainer.commit_thread_sql()
Beispiel #16
0
def import_bootstrap():
    print "Importing bootstrap ..."
    vendor = "PostgreSQL"

    plugin_dir = Environment.get_plugin_dir()
    sys.path.insert(0, plugin_dir)

    impl = DatabaseImpl.get(vendor)
    impl.create_database("sthpw")


    upgrade_dir = Environment.get_upgrade_dir()

    for category in ['bootstrap', 'sthpw', 'config']:
        f = open("%s/%s/%s_schema.sql" % (upgrade_dir, vendor.lower(), category) )
        data = f.read()
        f.close()

        data = data.split(";")

        cmds = []
        for cmd in data:
            lines = cmd.split("\n")
            lines2 = []
            for line in lines:
                if line.startswith("--"):
                    continue
                lines2.append(line)
            cmd = "\n".join(lines2)

            cmd = cmd.strip()
            if cmd == '':
                continue
            cmds.append(cmd)

        from pyasm.search import DbContainer, DbResource
        sql = DbContainer.get("sthpw")
        for cmd in cmds:
            sql.do_update(cmd)
Beispiel #17
0
def import_bootstrap():
    print "Importing bootstrap ..."
    vendor = "PostgreSQL"

    plugin_dir = Environment.get_plugin_dir()
    sys.path.insert(0, plugin_dir)

    impl = DatabaseImpl.get(vendor)
    impl.create_database("sthpw")

    upgrade_dir = Environment.get_upgrade_dir()

    for category in ['bootstrap', 'sthpw', 'config']:
        f = open("%s/%s/%s_schema.sql" %
                 (upgrade_dir, vendor.lower(), category))
        data = f.read()
        f.close()

        data = data.split(";")

        cmds = []
        for cmd in data:
            lines = cmd.split("\n")
            lines2 = []
            for line in lines:
                if line.startswith("--"):
                    continue
                lines2.append(line)
            cmd = "\n".join(lines2)

            cmd = cmd.strip()
            if cmd == '':
                continue
            cmds.append(cmd)

        from pyasm.search import DbContainer
        sql = DbContainer.get("sthpw")
        for cmd in cmds:
            sql.do_update(cmd)
Beispiel #18
0
    def __init__(my, port=''):

        # It is possible on startup that the database is not running.
        from pyasm.common import Environment
        from pyasm.search import DbContainer, DatabaseException, Sql
        plugin_dir = Environment.get_plugin_dir()
        sys.path.insert(0, plugin_dir)

        try:
            sql = DbContainer.get("sthpw")
            if sql.get_database_type() != "MongoDb":
                # before batch, clean up the ticket with a NULL code
                if os.getenv('TACTIC_MODE') != 'production':
                    sql.do_update('DELETE from "ticket" where "code" is NULL;')
                else:
                    start_port = Config.get_value("services", "start_port")
                    if start_port:
                        start_port = int(start_port)
                    else:
                        start_port = 8081
                    if port and int(port) == start_port:
                        sql.do_update(
                            'DELETE from "ticket" where "code" is NULL;')
        except DatabaseException, e:
            # TODO: need to work on this
            print "ERROR: could not connect to [sthpw] database"
            #os.environ["TACTIC_CONFIG_PATH"] = Config.get_default_config_path()
            #Sql.set_default_vendor("Sqlite")

            Config.set_tmp_config()
            Config.reload_config()

            # try connecting again
            try:
                sql = DbContainer.get("sthpw")
            except:
                print "Could not connect to the database."
                raise
Beispiel #19
0
    def __init__(my, port=''):

        # It is possible on startup that the database is not running.
        from pyasm.common import Environment
        from pyasm.search import DbContainer, DatabaseException, Sql
        plugin_dir = Environment.get_plugin_dir()
        sys.path.insert(0, plugin_dir)

        try:
            sql = DbContainer.get("sthpw")
            if sql.get_database_type() != "MongoDb":
                # before batch, clean up the ticket with a NULL code
                if os.getenv('TACTIC_MODE') != 'production':
                    sql.do_update('DELETE from "ticket" where "code" is NULL;')
                else:
                    start_port = Config.get_value("services", "start_port")
                    if start_port:
                        start_port = int(start_port)
                    else:
                        start_port = 8081
                    if port and int(port) == start_port:
                         sql.do_update('DELETE from "ticket" where "code" is NULL;')
        except DatabaseException, e:
            # TODO: need to work on this
            print "ERROR: could not connect to [sthpw] database"
            #os.environ["TACTIC_CONFIG_PATH"] = Config.get_default_config_path()
            #Sql.set_default_vendor("Sqlite")

            Config.set_tmp_config()
            Config.reload_config()

            # try connecting again
            try:
                sql = DbContainer.get("sthpw")
            except:
                print "Could not connect to the database."
                raise
Beispiel #20
0
    def create_theme(my, theme):

        # get a built-in plugin
        plugin_base_dir = Environment.get_plugin_dir()
        zip_path = "%s/%s.zip" % (plugin_base_dir, theme)
        manifest_path = "%s/%s/manifest.xml" % (plugin_base_dir, theme)

        plugin_base_dir2 = Environment.get_builtin_plugin_dir()
        zip_path2 = "%s/%s.zip" % (plugin_base_dir2, theme)
        manifest_path2 = "%s/%s/manifest.xml" % (plugin_base_dir2, theme)

        # install the theme
        from tactic.command import PluginInstaller
        if os.path.exists(manifest_path):
            plugin_dir = "%s/%s" % (plugin_base_dir, theme)
            installer = PluginInstaller(plugin_dir=plugin_dir, register=True)
            installer.execute()
            is_builtin = False
        elif os.path.exists(zip_path):
            installer = PluginInstaller(zip_path=zip_path, register=True)
            installer.execute()
            is_builtin = False
        elif os.path.exists(manifest_path2):
            plugin_dir = "%s/%s" % (plugin_base_dir2, theme)
            installer = PluginInstaller(plugin_dir=plugin_dir, register=True)
            installer.execute()
            is_builtin = True
        elif os.path.exists(zip_path2):
            installer = PluginInstaller(zip_path=zip_path2, register=True)
            installer.execute()
            is_builtin = True
        else:
            raise Exception("Installation error: cannot find %s theme" % theme)

        from pyasm.biz import PluginUtil
        if is_builtin:
            plugin_util = PluginUtil(base_dir=plugin_base_dir2)
        else:
            plugin_util = PluginUtil()
        data = plugin_util.get_plugin_data(theme)

        # if the theme does not have the url defined (which it likely
        # shouldn't, but just in case ...
        search = Search("config/url")
        search.add_filter("url", "/index")
        url = search.get_sobject()
        if not url:

            index_view = data.get("index_view")
            if not index_view:
                # don't use the folder in the theme
                base = os.path.basename(theme)
                index_view = "%s/index" % base

            # set this as the default index
            search = SearchType.create("config/url")
            search.set_value("url", "/index")
            search.set_value(
                "widget", '''
<element name='index'>
  <display class='tactic.ui.panel.CustomLayoutWdg'>
    <view>%s</view>
  </display>
</element>
            ''' % index_view)
            search.set_value("description", "Index Page")
            search.commit()
Beispiel #21
0
    def get_display(my):

        alias = my.kwargs.get("alias")

        my.rel_path = my.kwargs.get("rel_path")
        if not my.rel_path:
            from tactic_client_lib import TacticServerStub
            server = TacticServerStub.get(protocol='local')
            my.rel_path = server.get_doc_link(alias)

        if not my.rel_path or my.rel_path == 'none_found':
            #raise TacticException("Help alias [%s] does not exist" % alias)
            layout = DivWdg()
            layout.add(HelpCreateWdg(alias=alias))
            layout.add(HelpDocFilterWdg(alias='main'))
            return layout 

        # special condition for plugins path
        if my.rel_path.startswith("/plugins/"):
            plugin_dir = Environment.get_plugin_dir()
            rel_path = my.rel_path.replace("/plugins/", "")
            path = "%s/%s" % (plugin_dir,rel_path)
        elif my.rel_path.startswith("/builtin_plugins/"):
            plugin_dir = Environment.get_builtin_plugin_dir()
            rel_path = my.rel_path.replace("/builtin_plugins/", "")
            path = "%s/%s" % (plugin_dir,rel_path)
        elif my.rel_path.startswith("/assets/"):
            asset_dir = Environment.get_asset_dir()
            rel_path = my.rel_path.replace("/assets/", "")
            path = "%s/%s" % (asset_dir,rel_path)
        else:

            # see if there is an override
            doc_dir = os.environ.get("TACTIC_DOC_DIR") 
            if not doc_dir:
                doc_dir = Config.get_value("install", "doc_dir")
            if not doc_dir:
                install_dir = Environment.get_install_dir()
                doc_dir = "%s/doc" % install_dir

            path = "%s/%s" % (doc_dir, my.rel_path)

        html = []
        try:
            paths = path.split('#')
            anchor = ''
            if len(paths) > 1:
                anchor = paths[-1]
                path = paths[0]
                read = False
            else:
                read = True

            
            f = open(path, 'r')
            count = 0
            idx = 0 
            anchor_str = '<a id="%s"></a>'%anchor
            div_str = '<div class="titlepage">'
            strip_count = 0
            for line in f:
                if anchor and not read:
                    tmp_line = line.decode('utf-8','ignore')
                    div_idx = tmp_line.find(div_str)
                    idx = tmp_line.find(anchor_str)
                    if idx != -1:
                        # use the div above the anchor
                        line = line[div_idx:-1]
                        
                        # in case it doesn't get it right on
                        while strip_count < 30 and not line.startswith('<div class="titlepage">'):
                            line = line[1:-1]
                            strip_count +=  1

                        read = True
                
                if read:
                    line = my.filter_line(line, count)
                    html.append(line)
                    count += 1
            f.close()
        except Exception, e:
            print "Error processing: ", e
            html.append("Error processing document: %s<br/><br/>" % str(e))
Beispiel #22
0
 def __init__(self, **kwargs):
     self.base_dir = kwargs.get("base_dir")
     if not self.base_dir:
         self.base_dir = Environment.get_plugin_dir()
Beispiel #23
0
    def copy_start(self):

        data_dir = Environment.get_data_dir(manual=True)

        # check to see if the data folder already exists
        print
        print "Data Directory [%s]" % data_dir
        install_dir = Environment.get_install_dir()

        # find criteria for initializing
        initialize = False
        if data_dir and not os.path.exists(data_dir):
            initialize = True

        if data_dir and not os.path.exists("%s/config" % data_dir):
            initialize = True

        if initialize:
            # copy the template over.  This should exist even if it is not used
            print "... not found: initializing\n"
            install_data_path = "%s/src/install/start" % (install_dir)
            if os.path.exists(install_data_path):
                dirnames = os.listdir(install_data_path)
                for dirname in dirnames:
                    to_dir = "%s/%s" % (data_dir, dirname)
                    if os.path.exists(to_dir):
                        print "WARNING: path [%s] exists ... skipping copying" % to_dir
                        continue
                    print "Copying to [%s]" % to_dir
                    from_dir = "%s/%s" % (install_data_path, dirname)
                    shutil.copytree(from_dir, to_dir)
            else:
                shutil.copytree(install_data_path, data_dir)

            # create the dist folder
            to_dir = "%s/dist" % (data_dir)
            if not os.path.exists(to_dir):
                os.makedirs(to_dir)

            # copy the appropriate config file
            if os.name == 'nt':
                filename = 'standalone_win32-conf.xml'
            else:
                filename = 'standalone_linux-conf.xml'
            install_config_path = "%s/src/install/config/%s" % (install_dir,
                                                                filename)
            to_config_path = "%s/config/tactic-conf.xml" % data_dir

            if not os.path.exists(to_config_path):
                dirname = os.path.dirname(to_config_path)
                if not os.path.exists(dirname):
                    os.makedirs(dirname)
                shutil.copy(install_config_path, to_config_path)

        # some backwards compatibility issues
        old_config_path = "%s/config/tactic_linux-conf.xml" % data_dir
        if os.path.exists(old_config_path):
            new_config_path = "%s/config/tactic-conf.xml" % data_dir
            shutil.move(old_config_path, new_config_path)

        config_path = Config.get_config_path()
        config_exists = False
        if os.path.exists(config_path):
            config_exists = True

        # insert the plugin path to run get_asset_dir()
        plugin_dir = Environment.get_plugin_dir()
        sys.path.insert(0, plugin_dir)

        asset_dir = Environment.get_asset_dir()
        print "Asset Directory [%s]" % asset_dir

        tmp_dir = Environment.get_tmp_dir()
        print "Temp Directory [%s]" % tmp_dir

        # check if there is a config path already exists. If it does,
        # then don't do anything further.  This is likely a previous
        # installation
        if config_exists:
            print "Config path [%s]" % config_path
            return
        else:
            # if there is no config, retrieve data_dir in non-manual mode
            data_dir = Environment.get_data_dir()
            f = open("%s/first_run" % data_dir, 'w')
            f.write("")
            f.close()

        return
Beispiel #24
0
    def get_display(my):

        alias = my.kwargs.get("alias")

        my.rel_path = my.kwargs.get("rel_path")
        if not my.rel_path:
            from tactic_client_lib import TacticServerStub
            server = TacticServerStub.get(protocol='local')
            my.rel_path = server.get_doc_link(alias)

        if not my.rel_path or my.rel_path == 'none_found':
            #raise TacticException("Help alias [%s] does not exist" % alias)
            layout = DivWdg()
            layout.add(HelpCreateWdg(alias=alias))
            layout.add(HelpDocFilterWdg(alias='main'))
            return layout 

        # special condition for plugins path
        if my.rel_path.startswith("/plugins/"):
            plugin_dir = Environment.get_plugin_dir()
            rel_path = my.rel_path.replace("/plugins/", "")
            path = "%s/%s" % (plugin_dir,rel_path)
        elif my.rel_path.startswith("/builtin_plugins/"):
            plugin_dir = Environment.get_builtin_plugin_dir()
            rel_path = my.rel_path.replace("/builtin_plugins/", "")
            path = "%s/%s" % (plugin_dir,rel_path)
        elif my.rel_path.startswith("/assets/"):
            asset_dir = Environment.get_asset_dir()
            rel_path = my.rel_path.replace("/assets/", "")
            path = "%s/%s" % (asset_dir,rel_path)
        else:

            # see if there is an override
            doc_dir = os.environ.get("TACTIC_DOC_DIR") 
            if not doc_dir:
                doc_dir = Config.get_value("install", "doc_dir")
            if not doc_dir:
                install_dir = Environment.get_install_dir()
                doc_dir = "%s/doc" % install_dir

            path = "%s/%s" % (doc_dir, my.rel_path)

        html = []
        try:
            paths = path.split('#')
            anchor = ''
            if len(paths) > 1:
                anchor = paths[-1]
                path = paths[0]
                read = False
            else:
                read = True

            
            f = open(path, 'r')
            count = 0
            idx = 0 
            anchor_str = '<a id="%s"></a>'%anchor
            div_str = '<div class="titlepage">'
            strip_count = 0
            for line in f:
                if anchor and not read:
                    tmp_line = line.decode('utf-8','ignore')
                    div_idx = tmp_line.find(div_str)
                    idx = tmp_line.find(anchor_str)
                    if idx != -1:
                        # use the div above the anchor
                        line = line[div_idx:-1]
                        
                        # in case it doesn't get it right on
                        while strip_count < 30 and not line.startswith('<div class="titlepage">'):
                            line = line[1:-1]
                            strip_count +=  1

                        read = True
                
                if read:
                    line = my.filter_line(line, count)
                    html.append(line)
                    count += 1
            f.close()
        except Exception, e:
            print "Error processing: ", e
            html.append("Error processing document: %s<br/><br/>" % str(e))
    def setup_sites(my):

        context_path = "%s/src/context" % my.install_dir
        doc_dir = "%s/doc" % my.install_dir
        plugin_dir = Environment.get_plugin_dir()
        builtin_plugin_dir = Environment.get_builtin_plugin_dir()
        dist_dir = Environment.get_dist_dir()

        log_dir = "%s/log" % Environment.get_tmp_dir()

        config = {
            
            'global': {
                'server.socket_host': '127.0.0.1',
                'server.socket_port': 80,
                'log.screen': False,
                'request.show_tracebacks': True,
                'tools.log_headers.on': True,
                'server.log_file': "%s/tactic_log" % log_dir,
                'server.max_request_body_size': 0,
                #'server.socket_timeout': 60,
                'response.timeout': 3600,

                'tools.encode.on': True,
                'tools.encode.encoding': 'utf-8',
                'tools.decode.on': True,
                'tools.decode.encoding': 'utf-8',
                #'encoding_filter.on': True,
                #'decoding_filter.on': True
            }
            ,
            '/context': {'tools.staticdir.on': True,
                         'tools.staticdir.dir': context_path,
                         # Need to do this because on windows servers, jar files
                         # are served as text/html
                         'tools.staticdir.content_types': {
                             'jar': 'application/java-archive'
                         }
                        },
            '/assets':  {'tools.staticdir.on': True,
                         'tools.staticdir.dir': Environment.get_asset_dir()
                        },
            '/doc':     {'tools.staticdir.on': True,
                         'tools.staticdir.dir': doc_dir,
                         'tools.staticdir.index': "index.html"
                        },
            # NOTE: expose the entire plugins directory
            '/tactic/plugins': {
                         'tools.staticdir.on': True,
                         'tools.staticdir.dir': plugin_dir,
                        },
            '/tactic/builtin_plugins': {
                         'tools.staticdir.on': True,
                         'tools.staticdir.dir': builtin_plugin_dir,
                        },
            '/tactic/dist': {
                        'tools.staticdir.on': True,
                        'tools.staticdir.dir': dist_dir,
                        }
 

        }

      

        # set up the root directory
        cherrypy.root = Root()
        cherrypy.tree.mount( cherrypy.root, config=config)



        from pyasm.search import Search
        search = Search("sthpw/project")
        search.add_filter("type", "resource", op="!=")
        projects = search.get_sobjects()


        # find out if one of the projects is the root
        root_initialized = False
        """
        for project in projects:
            project_code = project.get_code()
            if False:
                from tactic.ui.app import SitePage
                cherrypy.root.tactic = SitePage(project_code)
                cherrypy.root.projects = SitePage(project_code)
                root_initialized = True
                break
        """

        if not root_initialized:
            project_code = Project.get_default_project()
            if project_code and project_code !='default':
                from tactic.ui.app import SitePage
                cherrypy.root.tactic = SitePage(project_code)
                cherrypy.root.projects = SitePage(project_code)
                root_initialized = True


        if not root_initialized:
            # load in the base site at root
            from tactic_sites.default.context.Index import Index
            cherrypy.root.tactic = Index()
            cherrypy.root.projects = Index()


        for project in projects:
            project_code = project.get_code()
            my.register_site(project_code, config)
        my.register_site("default", config)

        return config
Beispiel #26
0
    def __init__(self, port=''):

        # It is possible on startup that the database is not running.
        from pyasm.common import Environment
        from pyasm.search import DbContainer, DatabaseException, Sql
        plugin_dir = Environment.get_plugin_dir()
        sys.path.insert(0, plugin_dir)

        try:
            sql = DbContainer.get("sthpw")
            if sql.get_database_type() != "MongoDb":
                # before batch, clean up the ticket with a NULL code
                if os.getenv('TACTIC_MODE') != 'production':
                    sql.do_update('DELETE from "ticket" where "code" is NULL')
                else:
                    start_port = Config.get_value("services", "start_port")
                    if start_port:
                        start_port = int(start_port)
                    else:
                        start_port = 8081
                    if port and int(port) == start_port:
                        sql.do_update(
                            'DELETE from "ticket" where "code" is NULL')
        except DatabaseException as e:
            # TODO: need to work on this
            print("ERROR: could not connect to [sthpw] database")
            #os.environ["TACTIC_CONFIG_PATH"] = Config.get_default_config_path()
            #Sql.set_default_vendor("Sqlite")

            Config.set_tmp_config()
            Config.reload_config()

            # try connecting again
            try:
                sql = DbContainer.get("sthpw")
            except:
                print "Could not connect to the database."
                raise

        # is it CherryPyStartup's responsibility to start batch?
        from pyasm.security import Batch
        Batch()

        self.site_dir = os.getenv("TACTIC_SITE_DIR")
        self.install_dir = os.getenv("TACTIC_INSTALL_DIR")

        # set up a simple environment.  May need a more complex one later
        self.env = Environment()

        self.setup_env()
        self.config = self.setup_sites()

        self.init_only = False

        cherrypy.startup = self

        # this initializes the web.
        # - sets up virtual implied tiggers
        from web_init import WebInit
        WebInit().execute()

        # Windows should handle fine
        #start up the caching system if it's not windows
        cache_mode = Config.get_value("install", "cache_mode")
        if not cache_mode:
            cache_mode = 'complete'
            if os.name == 'nt':
                cache_mode = 'basic'

        from cache_startup import CacheStartup
        cmd = CacheStartup(mode=cache_mode)
        cmd.execute()
        cmd.init_scheduler()

        # DEPRECATED (but keeping it around"
        """
        # start up the queue system ...
        if Config.get_value("sync", "enabled") == "true":
            # start up the sync system ...
            print("Starting Transaction Sync ...")
            from tactic.command import TransactionQueueManager
            TransactionQueueManager.start()

            # start up the sync system ...
            print("Starting Watch Folder Service ...")
            from tactic.command import WatchServerFolderTask
            WatchServerFolderTask.start()
        """

        # start up scheduled triggers
        #from tactic.command import ScheduledTriggerMonitor
        #ScheduledTriggerMonitor.start()

        #from pyasm.web import Translation
        #Translation.install()

        # close all the threads in this startup thread
        from pyasm.search import DbContainer
        DbContainer.close_thread_sql()

        version = Environment.get_release_version()
        print("")
        print("Starting TACTIC v%s ..." % version)
        print("")
Beispiel #27
0
    def copy_start(self):

        data_dir = Environment.get_data_dir(manual=True)

        # check to see if the data folder already exists
        print
        print "Data Directory [%s]" % data_dir
        install_dir = Environment.get_install_dir()

        # find criteria for initializing
        initialize = False
        if data_dir and not os.path.exists(data_dir):
            initialize = True

        if data_dir and not os.path.exists("%s/config" % data_dir):
            initialize = True


        if initialize:
            # copy the template over.  This should exist even if it is not used
            print "... not found: initializing\n"
            install_data_path = "%s/src/install/start" % (install_dir)
            if os.path.exists(install_data_path):
                dirnames = os.listdir(install_data_path)
                for dirname in dirnames:
                    to_dir = "%s/%s" % (data_dir, dirname)
                    if os.path.exists(to_dir):
                        print "WARNING: path [%s] exists ... skipping copying" % to_dir
                        continue
                    print "Copying to [%s]" % to_dir
                    from_dir = "%s/%s" % (install_data_path, dirname)
                    shutil.copytree(from_dir, to_dir)
            else:
                shutil.copytree(install_data_path, data_dir)


            # create the dist folder
            to_dir = "%s/dist" % (data_dir)
            if not os.path.exists(to_dir):
                os.makedirs(to_dir)


            # copy the appropriate config file
            if os.name == 'nt':
                filename = 'standalone_win32-conf.xml'
            else:
                filename = 'standalone_linux-conf.xml'
            install_config_path = "%s/src/install/config/%s" % (install_dir,filename)
            to_config_path = "%s/config/tactic-conf.xml" % data_dir

            if not os.path.exists(to_config_path):
                dirname = os.path.dirname(to_config_path)
                if not os.path.exists(dirname):
                    os.makedirs(dirname)
                shutil.copy(install_config_path, to_config_path)

        # some backwards compatibility issues
        old_config_path = "%s/config/tactic_linux-conf.xml" % data_dir
        if os.path.exists(old_config_path):
            new_config_path = "%s/config/tactic-conf.xml" % data_dir
            shutil.move(old_config_path, new_config_path)



        config_path = Config.get_config_path()
        config_exists = False
        if os.path.exists(config_path):
            config_exists = True

        # insert the plugin path to run get_asset_dir()
        plugin_dir = Environment.get_plugin_dir()
        sys.path.insert(0, plugin_dir)

        asset_dir = Environment.get_asset_dir()
        print "Asset Directory [%s]" % asset_dir

        tmp_dir = Environment.get_tmp_dir()
        print "Temp Directory [%s]" % tmp_dir

        # check if there is a config path already exists. If it does,
        # then don't do anything further.  This is likely a previous
        # installation
        if config_exists:
            print "Config path [%s]" % config_path
            return
        else:
            # if there is no config, retrieve data_dir in non-manual mode
            data_dir = Environment.get_data_dir()
            f = open("%s/first_run" % data_dir, 'w')
            f.write("")
            f.close()

        return
Beispiel #28
0
 def __init__(my, **kwargs):
     my.base_dir = kwargs.get("base_dir")
     if not my.base_dir:
         my.base_dir = Environment.get_plugin_dir()
Beispiel #29
0
    def setup_sites(my):

        context_path = "%s/src/context" % my.install_dir
        doc_dir = "%s/doc" % my.install_dir
        plugin_dir = Environment.get_plugin_dir()
        builtin_plugin_dir = Environment.get_builtin_plugin_dir()
        dist_dir = Environment.get_dist_dir()

        log_dir = "%s/log" % Environment.get_tmp_dir()

        config = {
            'global': {
                'server.socket_host': '127.0.0.1',
                'server.socket_port': 80,
                'log.screen': False,
                'request.show_tracebacks': True,
                'tools.log_headers.on': True,
                'server.log_file': "%s/tactic_log" % log_dir,
                'server.max_request_body_size': 0,
                #'server.socket_timeout': 60,
                'response.timeout': 3600,
                'tools.encode.on': True,
                'tools.encode.encoding': 'utf-8',
                'tools.decode.on': True,
                'tools.decode.encoding': 'utf-8',
                #'encoding_filter.on': True,
                #'decoding_filter.on': True
            },
            '/context': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': context_path,
                # Need to do this because on windows servers, jar files
                # are served as text/html
                'tools.staticdir.content_types': {
                    'jar': 'application/java-archive'
                }
            },
            '/assets': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': Environment.get_asset_dir()
            },
            '/doc': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': doc_dir,
                'tools.staticdir.index': "index.html"
            },
            # NOTE: expose the entire plugins directory
            '/tactic/plugins': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': plugin_dir,
            },
            '/tactic/builtin_plugins': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': builtin_plugin_dir,
            },
            '/tactic/dist': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': dist_dir,
            }
        }

        # set up the root directory
        cherrypy.root = Root()
        cherrypy.tree.mount(cherrypy.root, config=config)

        from pyasm.search import Search
        search = Search("sthpw/project")
        search.add_filter("type", "resource", op="!=")
        projects = search.get_sobjects()

        # find out if one of the projects is the root
        root_initialized = False
        for project in projects:
            project_code = project.get_code()
            if False:
                from tactic.ui.app import SitePage
                cherrypy.root.tactic = SitePage(project_code)
                cherrypy.root.projects = SitePage(project_code)
                root_initialized = True
                break

        if not root_initialized:
            project_code = Config.get_value("install", "default_project")
            if project_code and project_code != 'default':
                from tactic.ui.app import SitePage
                cherrypy.root.tactic = SitePage(project_code)
                cherrypy.root.projects = SitePage(project_code)
                root_initialized = True

        if not root_initialized:
            # load in the base site at root
            from tactic_sites.default.context.Index import Index
            cherrypy.root.tactic = Index()
            cherrypy.root.projects = Index()

        for project in projects:
            project_code = project.get_code()
            my.register_site(project_code, config)
        my.register_site("default", config)

        return config
Beispiel #30
0
 def __init__(my, **kwargs):
     my.base_dir = kwargs.get("base_dir")
     if not my.base_dir:
         my.base_dir = Environment.get_plugin_dir()
Beispiel #31
0
    def __init__(my, **kwargs):
        super(PluginBase,my).__init__(**kwargs)

        # plugin sobject (Not really used anymore?)
        my.search_key = my.kwargs.get("search_key")

        zip_path = my.kwargs.get("zip_path")
        upload_file_name = my.kwargs.get("upload_file_name")

        my.base_dir = my.kwargs.get("base_dir")

        my.plugin_dir = my.kwargs.get("plugin_dir")
        my.manifest = my.kwargs.get("manifest")
        my.code = my.kwargs.get("code")
        my.version = my.kwargs.get("version")

        relative_dir = my.kwargs.get("relative_dir")

        my.verbose = my.kwargs.get("verbose") not in [False, 'false']
        # at the end of this, the following variables are needed in order to
        # define the plugin
        #
        #   version: the version of the plugin
        #   plugin_dir: the directory where the plugin definition is located
        #   manifest: the description of what is in the plugin

        if zip_path:

            # assume the zip path is the same as the basename
            basename = os.path.basename(zip_path)
            basename, ext = os.path.splitext(basename)
            assert ext == '.zip'

            tmp_dir = Environment.get_tmp_dir()

            unzip_dir = "%s/%s" % (tmp_dir, basename)
            if os.path.exists(unzip_dir):
               shutil.rmtree(unzip_dir)


            # unzip the file in to the tmp_dir or plugin_dir (for install)
            zip_util = ZipUtil()
            zip_util.extract(zip_path, base_dir=tmp_dir)


            # assume zip path
            my.plugin_dir, ext = os.path.splitext(zip_path)

            # mv from temp
            if my.plugin_dir != unzip_dir:
                if os.path.exists(my.plugin_dir):
                    shutil.rmtree(my.plugin_dir)
                shutil.move(unzip_dir, my.plugin_dir)

            manifest_path = "%s/manifest.xml" % my.plugin_dir
            f = open(manifest_path, 'r')
            my.manifest = f.read()
            f.close()


        elif upload_file_name:
            # The path is moved to the plugin dir, if this process is taking
            # "local" file (such as one uploaded)
            upload_dir = Environment.get_upload_dir()
            upload_path = "%s/%s" % (upload_dir, upload_file_name)
            plugin_base_dir = Environment.get_plugin_dir()
            dist_dir = Environment.get_dist_dir()
            if not os.path.exists(dist_dir):
                os.makedirs(dist_dir)

            basename = os.path.basename(upload_path)
            #if os.path.exists("%s/%s" % (plugin_base_dir, basename)):
            #    os.unlink("%s/%s" % (plugin_base_dir, basename) )
            #shutil.move(upload_path, plugin_base_dir)


            # copy to dist folder
            if os.path.exists("%s/%s" % (dist_dir, basename)):
                os.unlink("%s/%s" % (dist_dir, basename) )
            shutil.move(upload_path, dist_dir)

            zip_path = "%s/%s" % (dist_dir, upload_file_name)

            zip_util = ZipUtil()
            zip_util.extract(zip_path, base_dir=plugin_base_dir)

            my.plugin_dir = "%s/%s" % (plugin_base_dir, basename)
            my.plugin_dir = my.plugin_dir[:-4]
            manifest_path = "%s/manifest.xml" % (my.plugin_dir)

            if os.path.exists(manifest_path):
                f = open(manifest_path, 'r')
                my.manifest = f.read()
                f.close()
            else:
                # when uploading, this will likely not be needed
                my.manifest = "<manifest/>"
                return



        elif relative_dir:
            plugin_base_dir = Environment.get_plugin_dir()
            my.plugin_dir = "%s/%s" % (plugin_base_dir, relative_dir)
            manifest_path = "%s/manifest.xml" % my.plugin_dir
            if not os.path.exists(manifest_path):
                plugin_base_dir = Environment.get_builtin_plugin_dir()
                my.plugin_dir = "%s/%s" % (plugin_base_dir, relative_dir)
                manifest_path = "%s/manifest.xml" % my.plugin_dir

            f = open(manifest_path, 'r')
            my.manifest = f.read()
            f.close()

        elif my.plugin_dir:
            manifest_path = "%s/manifest.xml" % (my.plugin_dir)

            f = open(manifest_path, 'r')
            my.manifest = f.read()
            f.close()


        # get the plugin sobject
        elif my.search_key:
            plugin = SearchKey.get_by_search_key(my.search_key)
            my.manifest = plugin.get_value("manifest")
            my.code = plugin.get_code()
            my.version = plugin.get_value("version")


        elif my.manifest:
            # everything is extracted from the manifest later
            pass


        elif my.code:
            search = Search("config/plugin")
            search.add_filter("code", my.code)
            plugin = search.get_sobject()
            # In case there is extra plugins folder which is the case when the user 
            # is developing. 
            relative_dir = plugin.get_value("rel_dir")
             
            plugin_base_dir = Environment.get_plugin_dir()
            my.plugin_dir = "%s/%s" % (plugin_base_dir, relative_dir)
            
            # TODO: fix the ZipUtil.zip_dir()
            manifest_path = "%s/manifest.xml" % my.plugin_dir
            if not os.path.exists(manifest_path):
                plugin_base_dir = Environment.get_builtin_plugin_dir()
                my.plugin_dir = "%s/%s" % (plugin_base_dir, relative_dir)
                manifest_path = "%s/manifest.xml" % my.plugin_dir
                
            if os.path.exists(manifest_path):
                f = open(manifest_path, 'r')
                my.manifest = f.read()
                f.close()
            else:
                # this condition happens likely for a versioned installed plugin from a zip file
                # where it starts with an extra folder "plugins" and the rel_dir has not been recorded properly
                my.manifest = plugin.get_value("manifest") 
            
            my.code = plugin.get_code()
            my.version = plugin.get_value("version")

        else:
            raise Exception("No plugin found")


        # assertions
        assert my.manifest


        # read the xml
        my.xml = Xml()
        my.xml.read_string(my.manifest)


        # if code is passed in, then use that.
        if not my.code:
            my.code = my.xml.get_value("manifest/data/code")
            # old implementation
            if not my.code:
                my.code = my.xml.get_value("manifest/@code")
        if not my.version:
            my.version = my.xml.get_value("manifest/data/version")

        assert my.code


        if not my.base_dir:
            if my.code.startswith("TACTIC"):
                my.base_dir = Environment.get_builtin_plugin_dir()
            else:
                my.base_dir = Environment.get_plugin_dir()

        # set the base directory for this particular plugin
        if not my.plugin_dir:
            if my.version:
                my.plugin_dir = "%s/%s-%s" % (my.base_dir, my.code, my.version)
            else:
                my.plugin_dir = "%s/%s" % (my.base_dir, my.code)
    def create_theme(my, theme):

        # get a built-in plugin
        plugin_base_dir = Environment.get_plugin_dir()
        zip_path = "%s/%s.zip" % (plugin_base_dir, theme)
        manifest_path = "%s/%s/manifest.xml" % (plugin_base_dir, theme)

        plugin_base_dir2 = Environment.get_builtin_plugin_dir()
        zip_path2 = "%s/%s.zip" % (plugin_base_dir2, theme)
        manifest_path2 = "%s/%s/manifest.xml" % (plugin_base_dir2, theme)

        # install the theme
        from tactic.command import PluginInstaller

        if os.path.exists(manifest_path):
            plugin_dir = "%s/%s" % (plugin_base_dir, theme)
            installer = PluginInstaller(plugin_dir=plugin_dir, register=True)
            installer.execute()
            is_builtin = False
        elif os.path.exists(zip_path):
            installer = PluginInstaller(zip_path=zip_path, register=True)
            installer.execute()
            is_builtin = False
        elif os.path.exists(manifest_path2):
            plugin_dir = "%s/%s" % (plugin_base_dir2, theme)
            installer = PluginInstaller(plugin_dir=plugin_dir, register=True)
            installer.execute()
            is_builtin = True
        elif os.path.exists(zip_path2):
            installer = PluginInstaller(zip_path=zip_path2, register=True)
            installer.execute()
            is_builtin = True
        else:
            raise Exception("Installation error: cannot find %s theme" % theme)

        from pyasm.biz import PluginUtil

        if is_builtin:
            plugin_util = PluginUtil(base_dir=plugin_base_dir2)
        else:
            plugin_util = PluginUtil()
        data = plugin_util.get_plugin_data(theme)

        # if the theme does not have the url defined (which it likely
        # shouldn't, but just in case ...
        search = Search("config/url")
        search.add_filter("url", "/index")
        url = search.get_sobject()
        if not url:

            index_view = data.get("index_view")
            if not index_view:
                # don't use the folder in the theme
                base = os.path.basename(theme)
                index_view = "%s/index" % base

            # set this as the default index
            search = SearchType.create("config/url")
            search.set_value("url", "/index")
            search.set_value(
                "widget",
                """
<element name='index'>
  <display class='tactic.ui.panel.CustomLayoutWdg'>
    <view>%s</view>
  </display>
</element>
            """
                % index_view,
            )
            search.set_value("description", "Index Page")
            search.commit()
Beispiel #33
0
    def __init__(my, **kwargs):
        super(PluginBase,my).__init__(**kwargs)

        # plugin sobject (Not really used anymore?)
        my.search_key = my.kwargs.get("search_key")

        zip_path = my.kwargs.get("zip_path")
        upload_file_name = my.kwargs.get("upload_file_name")

        my.base_dir = my.kwargs.get("base_dir")

        my.plugin_dir = my.kwargs.get("plugin_dir")
        my.manifest = my.kwargs.get("manifest")
        my.code = my.kwargs.get("code")
        my.version = my.kwargs.get("version")

        relative_dir = my.kwargs.get("relative_dir")

        my.verbose = my.kwargs.get("verbose") not in [False, 'false']
        # at the end of this, the following variables are needed in order to
        # define the plugin
        #
        #   version: the version of the plugin
        #   plugin_dir: the directory where the plugin definition is located
        #   manifest: the description of what is in the plugin

        if zip_path:

            # assume the zip path is the same as the basename
            basename = os.path.basename(zip_path)
            basename, ext = os.path.splitext(basename)
            assert ext == '.zip'

            tmp_dir = Environment.get_tmp_dir()

            unzip_dir = "%s/%s" % (tmp_dir, basename)
            if os.path.exists(unzip_dir):
               shutil.rmtree(unzip_dir)


            # unzip the file in to the tmp_dir or plugin_dir (for install)
            zip_util = ZipUtil()
            zip_util.extract(zip_path, base_dir=tmp_dir)


            # assume zip path
            my.plugin_dir, ext = os.path.splitext(zip_path)

            # mv from temp
            if my.plugin_dir != unzip_dir:
                if os.path.exists(my.plugin_dir):
                    shutil.rmtree(my.plugin_dir)
                shutil.move(unzip_dir, my.plugin_dir)

            manifest_path = "%s/manifest.xml" % my.plugin_dir
            f = open(manifest_path, 'r')
            my.manifest = f.read()
            f.close()


        elif upload_file_name:
            # The path is moved to the plugin dir, if this process is taking
            # "local" file (such as one uploaded)
            upload_dir = Environment.get_upload_dir()
            upload_path = "%s/%s" % (upload_dir, upload_file_name)
            plugin_base_dir = Environment.get_plugin_dir()
            dist_dir = Environment.get_dist_dir()
            if not os.path.exists(dist_dir):
                os.makedirs(dist_dir)

            basename = os.path.basename(upload_path)
            #if os.path.exists("%s/%s" % (plugin_base_dir, basename)):
            #    os.unlink("%s/%s" % (plugin_base_dir, basename) )
            #shutil.move(upload_path, plugin_base_dir)


            # copy to dist folder
            if os.path.exists("%s/%s" % (dist_dir, basename)):
                os.unlink("%s/%s" % (dist_dir, basename) )
            shutil.move(upload_path, dist_dir)

            zip_path = "%s/%s" % (dist_dir, upload_file_name)

            zip_util = ZipUtil()
            zip_util.extract(zip_path, base_dir=plugin_base_dir)

            my.plugin_dir = "%s/%s" % (plugin_base_dir, basename)
            my.plugin_dir = my.plugin_dir[:-4]
            manifest_path = "%s/manifest.xml" % (my.plugin_dir)

            if os.path.exists(manifest_path):
                f = open(manifest_path, 'r')
                my.manifest = f.read()
                f.close()
            else:
                # when uploading, this will likely not be needed
                my.manifest = "<manifest/>"
                return



        elif relative_dir:
            plugin_base_dir = Environment.get_plugin_dir()
            my.plugin_dir = "%s/%s" % (plugin_base_dir, relative_dir)
            manifest_path = "%s/manifest.xml" % my.plugin_dir
            if not os.path.exists(manifest_path):
                plugin_base_dir = Environment.get_builtin_plugin_dir()
                my.plugin_dir = "%s/%s" % (plugin_base_dir, relative_dir)
                manifest_path = "%s/manifest.xml" % my.plugin_dir

            f = open(manifest_path, 'r')
            my.manifest = f.read()
            f.close()

        elif my.plugin_dir:
            manifest_path = "%s/manifest.xml" % (my.plugin_dir)

            f = open(manifest_path, 'r')
            my.manifest = f.read()
            f.close()


        # get the plugin sobject
        elif my.search_key:
            plugin = SearchKey.get_by_search_key(my.search_key)
            my.manifest = plugin.get_value("manifest")
            my.code = plugin.get_code()
            my.version = plugin.get_value("version")


        elif my.manifest:
            # everything is extracted from the manifest later
            pass


        elif my.code:
            search = Search("config/plugin")
            search.add_filter("code", my.code)
            plugin = search.get_sobject()
            # In case there is extra plugins folder which is the case when the user 
            # is developing. 
            relative_dir = plugin.get_value("rel_dir")
             
            plugin_base_dir = Environment.get_plugin_dir()
            my.plugin_dir = "%s/%s" % (plugin_base_dir, relative_dir)
            
            # TODO: fix the ZipUtil.zip_dir()
            manifest_path = "%s/manifest.xml" % my.plugin_dir
            if not os.path.exists(manifest_path):
                plugin_base_dir = Environment.get_builtin_plugin_dir()
                my.plugin_dir = "%s/%s" % (plugin_base_dir, relative_dir)
                manifest_path = "%s/manifest.xml" % my.plugin_dir
                
            if os.path.exists(manifest_path):
                f = open(manifest_path, 'r')
                my.manifest = f.read()
                f.close()
            else:
                # this condition happens likely for a versioned installed plugin from a zip file
                # where it starts with an extra folder "plugins" and the rel_dir has not been recorded properly
                my.manifest = plugin.get_value("manifest") 
            
            my.code = plugin.get_code()
            my.version = plugin.get_value("version")

        else:
            raise Exception("No plugin found")


        # assertions
        assert my.manifest


        # read the xml
        my.xml = Xml()
        my.xml.read_string(my.manifest)


        # if code is passed in, then use that.
        if not my.code:
            my.code = my.xml.get_value("manifest/data/code")
            # old implementation
            if not my.code:
                my.code = my.xml.get_value("manifest/@code")
        if not my.version:
            my.version = my.xml.get_value("manifest/data/version")

        assert my.code


        if not my.base_dir:
            if my.code.startswith("TACTIC"):
                my.base_dir = Environment.get_builtin_plugin_dir()
            else:
                my.base_dir = Environment.get_plugin_dir()

        # set the base directory for this particular plugin
        if not my.plugin_dir:
            if my.version:
                my.plugin_dir = "%s/%s-%s" % (my.base_dir, my.code, my.version)
            else:
                my.plugin_dir = "%s/%s" % (my.base_dir, my.code)
Beispiel #34
0
 def __init__(self, **kwargs):
     self.base_dir = kwargs.get("base_dir")
     if not self.base_dir:
         self.base_dir = Environment.get_plugin_dir()
Beispiel #35
0
    def setup_sites(my):

        context_path = "%s/src/context" % my.install_dir
        doc_dir = "%s/doc" % my.install_dir
        plugin_dir = Environment.get_plugin_dir()
        builtin_plugin_dir = Environment.get_builtin_plugin_dir()
        dist_dir = Environment.get_dist_dir()

        log_dir = "%s/log" % Environment.get_tmp_dir()



        def CORS():
            #cherrypy.response.headers["Access-Control-Allow-Origin"] = "http://192.168.0.15:8100"
            cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
            cherrypy.response.headers["Access-Control-Allow-Headers"] = "Origin, X-Requested-With, Content-Type, Accept"
        cherrypy.tools.CORS = cherrypy.Tool('before_handler', CORS)


        config = {
            
            'global': {
                'server.socket_host': '127.0.0.1',
                'server.socket_port': 80,
                'log.screen': False,
                'request.show_tracebacks': True,
                'tools.log_headers.on': True,
                'server.log_file': "%s/tactic_log" % log_dir,
                'server.max_request_body_size': 0,
                #'server.socket_timeout': 60,
                'response.timeout': 3600,

                'tools.encode.on': True,
                'tools.encode.encoding': 'utf-8',
                'tools.decode.on': True,
                'tools.decode.encoding': 'utf-8',
                #'encoding_filter.on': True,
                #'decoding_filter.on': True
                'tools.CORS.on': True

                },
            '/context': {'tools.staticdir.on': True,
                         'tools.staticdir.dir': context_path,
                         # Need to do this because on windows servers, jar files
                         # are served as text/html
                         'tools.staticdir.content_types': {
                             'jar': 'application/java-archive'
                         }
                        },
            '/assets':  {'tools.staticdir.on': True,
                         'tools.staticdir.dir': Environment.get_asset_dir()
                        },
            '/doc':     {'tools.staticdir.on': True,
                         'tools.staticdir.dir': doc_dir,
                         'tools.staticdir.index': "index.html"
                        },
            # NOTE: expose the entire plugins directory
            '/tactic/plugins': {
                         'tools.staticdir.on': True,
                         'tools.staticdir.dir': plugin_dir,
                        },
            '/tactic/builtin_plugins': {
                         'tools.staticdir.on': True,
                         'tools.staticdir.dir': builtin_plugin_dir,
                        },
            '/tactic/dist': {
                        'tools.staticdir.on': True,
                        'tools.staticdir.dir': dist_dir,
                        },
             '/plugins': {
                         'tools.staticdir.on': True,
                         'tools.staticdir.dir': plugin_dir,
                        },
            '/builtin_plugins': {
                         'tools.staticdir.on': True,
                         'tools.staticdir.dir': builtin_plugin_dir,
                        },
            '/dist': {
                        'tools.staticdir.on': True,
                        'tools.staticdir.dir': dist_dir,
                        },
 

 

        }


        # set up the root directory
        cherrypy.root = Root()
        cherrypy.tree.mount( cherrypy.root, config=config)



        from pyasm.search import Search
        search = Search("sthpw/project")
        search.add_filter("type", "resource", op="!=")
        projects = search.get_sobjects()


        # find out if one of the projects is the root
        root_initialized = False

        if not root_initialized:
            project_code = Project.get_default_project()
            if project_code and project_code !='default':
                from tactic.ui.app import SitePage
                cherrypy.root.tactic = SitePage(project_code)
                cherrypy.root.projects = SitePage(project_code)
                root_initialized = True


        if not root_initialized:
            # load in the base site at root
            from tactic_sites.default.context.Index import Index
            cherrypy.root.tactic = Index()
            cherrypy.root.projects = Index()


        for project in projects:
            project_code = project.get_code()
            my.register_project(project_code, config)
        my.register_project("default", config)

        print


        from pyasm.security import Site
        site_obj = Site.get()
        site_obj.register_sites(my, config)
 

        #my.register_project("vfx", config, site="vfx_demo")
        #my.register_project("default", config, site="vfx_demo")
        return config
Beispiel #36
0
    def __init__(self, port=''):

        # It is possible on startup that the database is not running.
        from pyasm.common import Environment
        from pyasm.search import DbContainer, DatabaseException, Sql
        plugin_dir = Environment.get_plugin_dir()
        sys.path.insert(0, plugin_dir)

        try:
            sql = DbContainer.get("sthpw")
            if sql.get_database_type() != "MongoDb":
                # before batch, clean up the ticket with a NULL code
                if os.getenv('TACTIC_MODE') != 'production':
                    sql.do_update('DELETE from "ticket" where "code" is NULL')
                else:
                    start_port = Config.get_value("services", "start_port")
                    if start_port:
                        start_port = int(start_port)
                    else:
                        start_port = 8081
                    if port and int(port) == start_port:
                         sql.do_update('DELETE from "ticket" where "code" is NULL')
        except DatabaseException as e:
            # TODO: need to work on this
            print("ERROR: could not connect to [sthpw] database")
            #os.environ["TACTIC_CONFIG_PATH"] = Config.get_default_config_path()
            #Sql.set_default_vendor("Sqlite")

            Config.set_tmp_config()
            Config.reload_config()

            # try connecting again
            try:
                sql = DbContainer.get("sthpw")
            except:
                print "Could not connect to the database."
                raise


        # is it CherryPyStartup's responsibility to start batch?
        from pyasm.security import Batch
        Batch()

        self.site_dir = os.getenv("TACTIC_SITE_DIR")
        self.install_dir = os.getenv("TACTIC_INSTALL_DIR")

        # set up a simple environment.  May need a more complex one later
        self.env = Environment()


        self.setup_env()
        self.config = self.setup_sites()

        self.init_only = False

        cherrypy.startup = self


        # this initializes the web.
        # - sets up virtual implied tiggers 
        from web_init import WebInit
        WebInit().execute()

        # Windows should handle fine
        #start up the caching system if it's not windows
        cache_mode = Config.get_value("install", "cache_mode")
        if not cache_mode:
            cache_mode = 'complete'
            if os.name == 'nt':
                cache_mode = 'basic'
            
        from cache_startup import CacheStartup
        cmd = CacheStartup(mode=cache_mode)
        cmd.execute()
        cmd.init_scheduler()

        # DEPRECATED (but keeping it around"
        """
        # start up the queue system ...
        if Config.get_value("sync", "enabled") == "true":
            # start up the sync system ...
            print("Starting Transaction Sync ...")
            from tactic.command import TransactionQueueManager
            TransactionQueueManager.start()

            # start up the sync system ...
            print("Starting Watch Folder Service ...")
            from tactic.command import WatchServerFolderTask
            WatchServerFolderTask.start()
        """

        # start up scheduled triggers
        #from tactic.command import ScheduledTriggerMonitor
        #ScheduledTriggerMonitor.start()

        #from pyasm.web import Translation
        #Translation.install()


        # close all the threads in this startup thread
        from pyasm.search import DbContainer
        DbContainer.close_thread_sql()

        version = Environment.get_release_version()
        print("")
        print("Starting TACTIC v%s ..." % version)
        print("")