def main(options, arguments):
    base_dir = os.path.dirname(sys.argv[0])
    if base_dir in [".", ""]: base_dir = os.getcwd()

    if os.path.isfile(os.path.join(base_dir, "metadata.json")):
        mfile = open(os.path.join(base_dir, "metadata.json"), "r")
        domain_metadata = eval(mfile.read())
        mfile.close()
    else:
        print "Mandatory file %s cannot be located in %s." % ("metadata.json",
                                                              base_dir)
        sys.exit(1)

    domain_home = options.get("-h")
    domain_name = options.get("--domain_name", os.path.basename(domain_home))
    shared_home = options.get("-s", domain_home)
    db_conn = options.get(
        "-c",
        domain_metadata.get("database").get("connect-string"))
    db_pass = options.get(
        "--db_password",
        domain_metadata.get("database").get("schema-password"))
    db_prfix = options.get("-m")
    nm_pass = options.get("--nm_password",
                          domain_metadata.get("wls").get("nm_password"))
    as_pass = options.get("--as_password",
                          domain_metadata.get("wls").get("as_password"))
    pwd_file = options.get("-w", "")
    nm_port = int(
        options.get("--nm_port",
                    domain_metadata.get("wls").get("nm-port")))
    as_port = int(
        options.get("--as_port",
                    domain_metadata.get("wls").get("as-port")))
    as_sport = int(
        options.get("--as_ssl_port",
                    domain_metadata.get("wls").get("as-ssl-port")))

    as_name = domain_metadata.get("wls").get("server-name")
    as_user = domain_metadata.get("wls").get("as-username")
    nm_user = domain_metadata.get("wls").get("nm-username")

    feature_set = LinkedHashSet(arguments)
    feature_set.retainAll(domain_metadata.keys())
    feature_set.remove("jdk")
    feature_set.remove("wcc")
    feature_set.remove("wcp")
    feature_set.remove("wcs")
    if feature_set.size() == 0: sys.exit(0)
    if not (feature_set.size() == 1 and "wls" in feature_set):
        feature_set.add("em")

    setShowLSResult(false)
    selected_features = []
    avail_tmplts = showAvailableTemplates()
    index1 = avail_tmplts.find(
        "20849: Currently available templates for loading:")
    index2 = avail_tmplts.find("20849: No action required.")
    avail_tmplts = [
        tmplt.split(":", 1)
        for tmplt in avail_tmplts[index1 + 50:index2 - 2].splitlines()
    ]
    avail_tmplts = dict(avail_tmplts)

    if not os.path.isfile(os.path.join(domain_home, "config", "config.xml")):
        if os.path.isfile(pwd_file):
            bfile = open(pwd_file, "r")
            fcontents = bfile.read().splitlines()
            bfile.close()
            db_pass = fcontents.pop()
            as_pass = fcontents.pop()
            nm_pass = fcontents.pop()

        selected_features.append("wls")
        feature_set.remove("wls")
        if "em" in feature_set and \
        domain_metadata.get("em").get("template-name") in avail_tmplts:
            selected_features.append("em")
            feature_set.remove("em")

        for feature in feature_set:
            if domain_metadata.get(feature).get(
                    "template-name") in avail_tmplts:
                selected_features.append(feature)
        if len(selected_features) == 0: return

        print "Creating the Domain."
        print "Loading Required Templates."
        for feature in selected_features:
            print "\t%s version %s" %(domain_metadata.get(feature).get("template-name"), \
                                      domain_metadata.get(feature).get("version"))
            selectTemplate(domain_metadata.get(feature).get("template-name"))
        loadTemplates()

        print "Setting Domain Options."
        start_mode = domain_metadata.get("wls").get("server-start-mode")
        setOption("AppDir", os.path.join(domain_home, "applications"))
        setOption("DomainName", domain_name)
        setOption("OverwriteDomain", "true")
        setOption("ServerStartMode", start_mode)

        selected_features.remove("wls")
        print "Configuring Admin Server."
        cd("/Servers/AdminServer")
        set("ListenAddress", socket.gethostname())
        set("ListenPort", as_port)
        set("Name", as_name)

        print "\tSSL"
        create(as_name, "SSL")
        cd("SSL/%s" % as_name)
        set("Enabled", "True")
        set("ListenPort", as_sport)
        set("HostnameVerificationIgnored", "true")
        set("HostnameVerifier", "None")

        print "\tServerStart"
        cd('/Servers/%s' % as_name)
        create(as_name, 'ServerStart')
        cd('ServerStart/NO_NAME_0')
        # set("Arguments", "-XX:+UnlockCommercialFeatures -XX:+ResourceManagement -Djava.security.egd=file:/dev/./urandom")
        set("Arguments", "-Djava.security.egd=file:/dev/./urandom")

        print "Configuring Admin User."
        cd("/Security/base_domain/User/weblogic")
        set("Name", as_user)
        set("Password", as_pass)

        print "Configuring Security Configuration."
        cd("/SecurityConfiguration/%s" % "base_domain")
        set("NodeManagerUsername", nm_user)
        set("NodeManagerPasswordEncrypted", nm_pass)

        print "Configuring Nodemanager."
        cd("/NMProperties")
        set("NodeManagerHome", os.path.join(domain_home, "nodemanager"))
        set("ListenAddress", socket.gethostname())
        set("ListenPort", nm_port)

        cluster_set = LinkedHashSet()
        for feature in selected_features:
            print "Configuring feature %s." % feature
            cluster_name = domain_metadata.get(feature).get("cluster-name")
            server_name = domain_metadata.get(feature).get("server-name")

            feature_credentials = domain_metadata.get(feature).get(
                "credentials", {})
            for credential in feature_credentials:
                for credkey in feature_credentials.get(credential, {}):
                    print "\tUpdating Key %s in Credential %s" % (credkey,
                                                                  credential)
                    cd("/Credential/TargetStore/%s/TargetKey/%s" %
                       (credential, credkey))
                    create(credkey, "Credential")
                    cd("Credential")
                    set(
                        "Username",
                        feature_credentials.get(credential).get(credkey).get(
                            "username"))
                    set(
                        "Password",
                        feature_credentials.get(credential).get(credkey).get(
                            "password"))

            for filestore in domain_metadata.get(feature).get(
                    "file-stores", []):
                print "\tUpdating Filestore %s" % filestore
                cd("/FileStore/%s" % filestore)
                set("Target", as_name)
                set("Directory", os.path.join(shared_home, get("Directory")))

            jms_system_resources = domain_metadata.get(feature).get(
                "jms-system-resources", [])
            for jmssr in jms_system_resources:
                subdeployments = ls("/JMSSystemResource/%s/SubDeployment" %
                                    jmssr,
                                    returnMap="true")
                for subdeployment in subdeployments:
                    cd("/JMSSystemResource/%s/SubDeployment/%s" %
                       (jmssr, subdeployment))
                    for jmsserver in get("Target"):
                        cd("/JMSServer/%s" % jmsserver.getName())
                        filestore = get("PersistentStore").getName()
                        m_servers = get("Target")
                        if m_servers[0].getName() == server_name:
                            print "\tUpdating Filestore %s" % filestore
                            cd("/FileStore/%s" % filestore)
                            set("Directory",
                                os.path.join(shared_home, get("Directory")))

            for ds in domain_metadata.get(feature).get("datasources", []):
                ds_name = ds.get("name")
                ds_scma = ds.get("schema")
                print "\tUpdating Data Source %s" % ds_name
                cd("/JDBCSystemResources/%s/JdbcResource/%s/JDBCDriverParams/NO_NAME_0"
                   % (ds_name, ds_name))
                set("DriverName", "oracle.jdbc.OracleDriver")
                set("URL", "jdbc:oracle:thin:@%s" % db_conn)
                set("PasswordEncrypted", db_pass)
                cd("Properties/NO_NAME_0/Property/user")
                set("Value", "%s_%s" % (db_prfix, ds_scma))
                cd("/JDBCSystemResources/%s/JdbcResource/%s" %
                   (ds_name, ds_name))
                create(ds_name, "JDBCOracleParams")
                cd("JDBCOracleParams/NO_NAME_0")
                set("FanEnabled", false)
                set("OnsNodeList", "")

            if cluster_name not in cluster_set and cluster_name is not None:
                cluster_set.add(cluster_name)
                print "\tCreating cluster %s" % cluster_name
                cd("/")
                create(cluster_name, "Cluster")
                cd("/Clusters/%s" % cluster_name)
                set("ClusterMessagingMode", "unicast")
                set("WeblogicPluginEnabled", 1)
                cd("/")
                print "\tTargeting resources to cluster %s" % cluster_name
                assign("Server", server_name, "Cluster", cluster_name)

        if len(selected_features) > 0:
            print "Data Sources Auto Config"
            getDatabaseDefaults()
            # setFEHostURL("plainurl", "sslurl", isDefaultPlain="True")

        print "Writing Domain Configuration."
        writeDomain(domain_home)

        print "Writing boot.properties."
        bootdir = File(
            os.path.join(domain_home, "servers", as_name, "security"))
        bootdir.mkdirs()
        bfile = open(
            os.path.join(domain_home, "servers", as_name, "security",
                         "boot.properties"), "w")
        bfile.write("username=%s\n" % as_user)
        bfile.write("password=%s\n" % as_pass)
        bfile.flush()
        bfile.close()

        print "Domain built successfully."
    else:
        print "Domain exists already."
def main(options, arguments):
    base_dir = os.path.dirname(sys.argv[0])
    if base_dir in [".", ""]: base_dir = os.getcwd()

    if os.path.isfile(os.path.join(base_dir, "metadata.json")):
        mfile = open(os.path.join(base_dir, "metadata.json"), "r")
        domain_metadata = eval(mfile.read())
        mfile.close()
    else:
        print "Mandatory file %s cannot be located in %s." %("metadata.json", base_dir)
        sys.exit(1)

    domain_home = options.get("-h")
    domain_name = options.get("--domain_name", os.path.basename(domain_home))
    shared_home = options.get("-s", domain_home)
    db_conn = options.get("-c", domain_metadata.get("database").get("connect-string"))
    db_pass = options.get("--db_password", domain_metadata.get("database").get("schema-password"))
    db_prfix = options.get("-m")
    pwd_file = options.get("-w", "")

    feature_set = LinkedHashSet(arguments)
    feature_set.retainAll(domain_metadata.keys())
    if feature_set.size() == 0: sys.exit(0)
    if not(feature_set.size() == 1 and "wls" in feature_set): feature_set.add("em")

    setShowLSResult(false)
    used_tmplts = []
    available_clusters = LinkedHashSet()
    selected_features = []
    avail_tmplts = showAvailableTemplates()
    index1 = avail_tmplts.find("20849: Currently available templates for loading:")
    index2 = avail_tmplts.find("20849: No action required.")
    avail_tmplts = [tmplt.split(":", 1) for tmplt in avail_tmplts[index1 + 50:index2 - 2].splitlines()]
    avail_tmplts = dict(avail_tmplts)

    if os.path.isfile(os.path.join(domain_home, "config", "config.xml")):
        if os.path.isfile(pwd_file):
            bfile = open(pwd_file, "r")
            fcontents = bfile.read().splitlines()
            bfile.close()
            db_pass = fcontents.pop()

        print "Reading the Domain to gather information."
        readDomain(domain_home)
        used_tmplts = showTemplates()
        closeDomain()
        index1 = used_tmplts.find("20845: Previously applied templates:")
        index2 = used_tmplts.find("20845: No action required.")
        used_tmplts = [tmplt.split(":", 1) for tmplt in used_tmplts[index1 + 37:index2 - 2].splitlines()]
        used_tmplts = dict(used_tmplts)

        feature_set.remove("wls")
        if "em" in feature_set and \
        domain_metadata.get("em").get("template-name") not in used_tmplts and \
        domain_metadata.get("em").get("template-name") in avail_tmplts:
            selected_features.append("em")
            feature_set.remove("em")

        for feature in feature_set:
            if domain_metadata.get(feature).get("template-name") in used_tmplts:
                available_clusters.add(domain_metadata.get(feature).get("cluster-name"))
            else:
                if domain_metadata.get(feature).get("template-name") in avail_tmplts:
                    selected_features.append(feature)

        if len(selected_features) == 0: return

        print "Loading the Domain for update."
        readDomain(domain_home)
        print "Loading Required Templates."
        for feature in selected_features:
            print "\t%s version %s" %(domain_metadata.get(feature).get("template-name"), \
                                      domain_metadata.get(feature).get("version"))
            selectTemplate(domain_metadata.get(feature).get("template-name"))
        loadTemplates()

        print "Setting Domain Options."
        setOption("AppDir", os.path.join(domain_home, "applications"))

        cluster_set = LinkedHashSet()
        for feature in selected_features:
            print "Configuring feature %s." %feature
            cluster_name = domain_metadata.get(feature).get("cluster-name")
            server_name = domain_metadata.get(feature).get("server-name")

            feature_credentials = domain_metadata.get(feature).get("credentials", {})
            for credential in feature_credentials:
                for credkey in feature_credentials.get(credential, {}):
                    print "\tUpdating Key %s in Credential %s" %(credkey, credential)
                    cd("/Credential/TargetStore/%s/TargetKey/%s" %(credential, credkey))
                    create(credkey, "Credential")
                    cd("Credential")
                    set("Username", feature_credentials.get(credential).get(credkey).get("username"))
                    set("Password", feature_credentials.get(credential).get(credkey).get("password"))

            for filestore in domain_metadata.get(feature).get("file-stores", []):
                print "\tUpdating Filestore %s" %filestore
                cd("/FileStore/%s" %filestore)
                set("Target", as_name)
                set("Directory", os.path.join(shared_home, get("Directory")))

            jms_system_resources = domain_metadata.get(feature).get("jms-system-resources", [])
            for jmssr in jms_system_resources:
                subdeployments = ls("/JMSSystemResource/%s/SubDeployment" %jmssr, returnMap="true")
                for subdeployment in subdeployments:
                    cd("/JMSSystemResource/%s/SubDeployment/%s" %(jmssr, subdeployment))
                    for jmsserver in get("Target"):
                        cd("/JMSServer/%s" %jmsserver.getName())
                        filestore = get("PersistentStore").getName()
                        m_servers = get("Target")
                        if m_servers[0].getName() == server_name:
                            print "\tUpdating Filestore %s" %filestore
                            cd("/FileStore/%s" %filestore)
                            set("Directory", os.path.join(shared_home, get("Directory")))

            for ds in domain_metadata.get(feature).get("datasources", []):
                ds_name = ds.get("name")
                ds_scma = ds.get("schema")
                print "\tUpdating Data Source %s" %ds_name
                cd("/JDBCSystemResources/%s/JdbcResource/%s/JDBCDriverParams/NO_NAME_0" %(ds_name, ds_name))
                set("DriverName", "oracle.jdbc.OracleDriver")
                set("URL", "jdbc:oracle:thin:@%s" %db_conn)
                set("PasswordEncrypted", db_pass)
                cd("Properties/NO_NAME_0/Property/user")
                set("Value", "%s_%s" %(db_prfix, ds_scma))
                cd("/JDBCSystemResources/%s/JdbcResource/%s" %(ds_name, ds_name))
                create(ds_name, "JDBCOracleParams")
                cd("JDBCOracleParams/NO_NAME_0")
                set("FanEnabled", false)
                set("OnsNodeList", "")

            if cluster_name not in cluster_set and cluster_name is not None:
                cluster_set.add(cluster_name)
                print "\tCreating cluster %s" %cluster_name
                cd("/")
                create(cluster_name, "Cluster")
                cd("/Clusters/%s" %cluster_name)
                set("ClusterMessagingMode", "unicast")
                set("WeblogicPluginEnabled", 1)
                cd("/")
                print "\tTargeting resources to cluster %s" %cluster_name
                assign("Server", server_name, "Cluster", cluster_name)
                # print "\tDeleting server %s" %server_name
                # delete(server_name, "Server")

        if len(selected_features) > 0:
            print "Data Sources Auto Config"
            getDatabaseDefaults()
            # setFEHostURL("plainurl", "sslurl", isDefaultPlain="True")

        print "Writing Domain Configuration."
        updateDomain()
        closeDomain()

        print "Domain built successfully."
    else:
        print "Domain does not exist."
def main(options, arguments):
    base_dir = os.path.dirname(sys.argv[0])
    if base_dir in [".", ""]: base_dir = os.getcwd()

    if os.path.isfile(os.path.join(base_dir, "metadata.json")):
        mfile = open(os.path.join(base_dir, "metadata.json"), "r")
        domain_metadata = eval(mfile.read())
        mfile.close()
    else:
        print "Mandatory file %s cannot be located in %s." %("metadata.json", base_dir)
        sys.exit(1)

    domain_home = options.get("-h")
    domain_name = options.get("--domain_name", os.path.basename(domain_home))
    shared_home = options.get("-s", domain_home)
    db_conn = options.get("-c", domain_metadata.get("database").get("connect-string"))
    db_pass = options.get("--db_password", domain_metadata.get("database").get("schema-password"))
    db_prfix = options.get("-m")
    nm_pass = options.get("--nm_password", domain_metadata.get("wls").get("nm_password"))
    as_pass = options.get("--as_password", domain_metadata.get("wls").get("as_password"))
    pwd_file = options.get("-w", "")
    nm_port = int(options.get("--nm_port", domain_metadata.get("wls").get("nm-port")))
    as_port = int(options.get("--as_port", domain_metadata.get("wls").get("as-port")))
    as_sport = int(options.get("--as_ssl_port", domain_metadata.get("wls").get("as-ssl-port")))
    
    as_name = domain_metadata.get("wls").get("server-name")
    as_user = domain_metadata.get("wls").get("as-username")
    nm_user = domain_metadata.get("wls").get("nm-username")

    feature_set = LinkedHashSet(arguments)
    feature_set.retainAll(domain_metadata.keys())
    feature_set.remove("jdk")
    feature_set.remove("wcc")
    feature_set.remove("wcp")
    feature_set.remove("wcs")
    if feature_set.size() == 0: sys.exit(0)
    if not(feature_set.size() == 1 and "wls" in feature_set): feature_set.add("em")

    setShowLSResult(false)
    selected_features = []
    avail_tmplts = showAvailableTemplates()
    index1 = avail_tmplts.find("20849: Currently available templates for loading:")
    index2 = avail_tmplts.find("20849: No action required.")
    avail_tmplts = [tmplt.split(":", 1) for tmplt in avail_tmplts[index1 + 50:index2 - 2].splitlines()]
    avail_tmplts = dict(avail_tmplts)

    if not os.path.isfile(os.path.join(domain_home, "config", "config.xml")):
        if os.path.isfile(pwd_file):
            bfile = open(pwd_file, "r")
            fcontents = bfile.read().splitlines()
            bfile.close()
            db_pass = fcontents.pop()
            as_pass = fcontents.pop()
            nm_pass = fcontents.pop()
        
        selected_features.append("wls")
        feature_set.remove("wls")
        if "em" in feature_set and \
        domain_metadata.get("em").get("template-name") in avail_tmplts:
            selected_features.append("em")
            feature_set.remove("em")

        for feature in feature_set:
            if domain_metadata.get(feature).get("template-name") in avail_tmplts:
                selected_features.append(feature)
        if len(selected_features) == 0: return

        print "Creating the Domain."
        print "Loading Required Templates."
        for feature in selected_features:
            print "\t%s version %s" %(domain_metadata.get(feature).get("template-name"), \
                                      domain_metadata.get(feature).get("version"))
            selectTemplate(domain_metadata.get(feature).get("template-name"))
        loadTemplates()

        print "Setting Domain Options."
        start_mode = domain_metadata.get("wls").get("server-start-mode")
        setOption("AppDir", os.path.join(domain_home, "applications"))
        setOption("DomainName", domain_name)
        setOption("OverwriteDomain", "true")
        setOption("ServerStartMode", start_mode)

        selected_features.remove("wls")
        print "Configuring Admin Server."
        cd("/Servers/AdminServer")
        set("ListenAddress", socket.gethostname())
        set("ListenPort", as_port)
        set("Name", as_name)

        print "\tSSL"
        create(as_name, "SSL")
        cd("SSL/%s" %as_name)
        set("Enabled", "True")
        set("ListenPort", as_sport)
        set("HostnameVerificationIgnored", "true")
        set("HostnameVerifier", "None")

        print "\tServerStart"
        cd('/Servers/%s' %as_name)
        create(as_name, 'ServerStart')
        cd('ServerStart/NO_NAME_0')
        # set("Arguments", "-XX:+UnlockCommercialFeatures -XX:+ResourceManagement -Djava.security.egd=file:/dev/./urandom")
        set("Arguments", "-Djava.security.egd=file:/dev/./urandom")

        print "Configuring Admin User."
        cd("/Security/base_domain/User/weblogic")
        set("Name", as_user)
        set("Password", as_pass)

        print "Configuring Security Configuration."
        cd("/SecurityConfiguration/%s"  %"base_domain")
        set("NodeManagerUsername", nm_user)
        set("NodeManagerPasswordEncrypted", nm_pass)

        print "Configuring Nodemanager."
        cd("/NMProperties")
        set("NodeManagerHome", os.path.join(domain_home, "nodemanager"))
        set("ListenAddress", socket.gethostname())
        set("ListenPort", nm_port)

        cluster_set = LinkedHashSet()
        for feature in selected_features:
            print "Configuring feature %s." %feature
            cluster_name = domain_metadata.get(feature).get("cluster-name")
            server_name = domain_metadata.get(feature).get("server-name")

            feature_credentials = domain_metadata.get(feature).get("credentials", {})
            for credential in feature_credentials:
                for credkey in feature_credentials.get(credential, {}):
                    print "\tUpdating Key %s in Credential %s" %(credkey, credential)
                    cd("/Credential/TargetStore/%s/TargetKey/%s" %(credential, credkey))
                    create(credkey, "Credential")
                    cd("Credential")
                    set("Username", feature_credentials.get(credential).get(credkey).get("username"))
                    set("Password", feature_credentials.get(credential).get(credkey).get("password"))

            for filestore in domain_metadata.get(feature).get("file-stores", []):
                print "\tUpdating Filestore %s" %filestore
                cd("/FileStore/%s" %filestore)
                set("Target", as_name)
                set("Directory", os.path.join(shared_home, get("Directory")))

            jms_system_resources = domain_metadata.get(feature).get("jms-system-resources", [])
            for jmssr in jms_system_resources:
                subdeployments = ls("/JMSSystemResource/%s/SubDeployment" %jmssr, returnMap="true")
                for subdeployment in subdeployments:
                    cd("/JMSSystemResource/%s/SubDeployment/%s" %(jmssr, subdeployment))
                    for jmsserver in get("Target"):
                        cd("/JMSServer/%s" %jmsserver.getName())
                        filestore = get("PersistentStore").getName()
                        m_servers = get("Target")
                        if m_servers[0].getName() == server_name:
                            print "\tUpdating Filestore %s" %filestore
                            cd("/FileStore/%s" %filestore)
                            set("Directory", os.path.join(shared_home, get("Directory")))

            for ds in domain_metadata.get(feature).get("datasources", []):
                ds_name = ds.get("name")
                ds_scma = ds.get("schema")
                print "\tUpdating Data Source %s" %ds_name
                cd("/JDBCSystemResources/%s/JdbcResource/%s/JDBCDriverParams/NO_NAME_0" %(ds_name, ds_name))
                set("DriverName", "oracle.jdbc.OracleDriver")
                set("URL", "jdbc:oracle:thin:@%s" %db_conn)
                set("PasswordEncrypted", db_pass)
                cd("Properties/NO_NAME_0/Property/user")
                set("Value", "%s_%s" %(db_prfix, ds_scma))
                cd("/JDBCSystemResources/%s/JdbcResource/%s" %(ds_name, ds_name))
                create(ds_name, "JDBCOracleParams")
                cd("JDBCOracleParams/NO_NAME_0")
                set("FanEnabled", false)
                set("OnsNodeList", "")

            if cluster_name not in cluster_set and cluster_name is not None:
                cluster_set.add(cluster_name)
                print "\tCreating cluster %s" %cluster_name
                cd("/")
                create(cluster_name, "Cluster")
                cd("/Clusters/%s" %cluster_name)
                set("ClusterMessagingMode", "unicast")
                set("WeblogicPluginEnabled", 1)
                cd("/")
                print "\tTargeting resources to cluster %s" %cluster_name
                assign("Server", server_name, "Cluster", cluster_name)

        if len(selected_features) > 0:
            print "Data Sources Auto Config"
            getDatabaseDefaults()
            # setFEHostURL("plainurl", "sslurl", isDefaultPlain="True")

        print "Writing Domain Configuration."
        writeDomain(domain_home)

        print "Writing boot.properties."
        bootdir = File(os.path.join(domain_home, "servers", as_name, "security"))
        bootdir.mkdirs()
        bfile = open(os.path.join(domain_home, "servers", as_name, "security", "boot.properties"), "w")
        bfile.write("username=%s\n" %as_user)
        bfile.write("password=%s\n" %as_pass)
        bfile.flush()
        bfile.close()

        print "Domain built successfully."
    else:
        print "Domain exists already."
Ejemplo n.º 4
0
def main(options, arguments):
    base_dir = os.path.dirname(sys.argv[0])
    if base_dir in [".", ""]: base_dir = os.getcwd()

    if os.path.isfile(os.path.join(base_dir, "metadata.json")):
        mfile = open(os.path.join(base_dir, "metadata.json"), "r")
        domain_metadata = eval(mfile.read())
        mfile.close()
    else:
        print "Mandatory file %s cannot be located in %s." % ("metadata.json",
                                                              base_dir)
        sys.exit(1)

    admin_host = options.get("-a")
    domain_home = options.get("-h")
    shared_home = options.get("-s", domain_home)
    as_username = options.get("--as_username",
                              domain_metadata.get("wls").get("as-username"))
    as_password = options.get("--as_password",
                              domain_metadata.get("wls").get("as_password"))
    nm_port = int(
        options.get("--nm_port",
                    domain_metadata.get("wls").get("nm-port")))
    pwd_file = options.get("-w", "")
    if "--use_plain" not in options:
        as_port = int(
            options.get("--as_port",
                        domain_metadata.get("wls").get("as-ssl-port")))
        admin_url = "t3s://%s:%s" % (admin_host, as_port)
    else:
        as_port = int(
            options.get("--as_port",
                        domain_metadata.get("wls").get("as-port")))
        admin_url = "t3://%s:%s" % (admin_host, as_port)
    if "--overwrite" in options:
        overwrite = True
    else:
        overwrite = False

    wait = int(options.get("--wait", 300000))
    timeout = int(options.get("--timeout", -1))
    feature_set = LinkedHashSet(arguments)
    feature_set.retainAll(domain_metadata.keys())
    if feature_set.size() == 0: return

    if not os.path.isdir(domain_home) or overwrite:
        if os.path.isfile(pwd_file):
            bfile = open(pwd_file, "r")
            fcontents = bfile.read().splitlines()
            bfile.close()
            as_password = fcontents.pop()

        # Using IP for listen address
        # Revert back when Docker Networking is better
        host_name = socket.gethostname()
        machine_name = host_name.split(".")[0]
        host_name = socket.gethostbyname(host_name)
        connect(as_username, as_password, admin_url)
        edit()
        startEdit(waitTimeInMillis=wait,
                  timeOutInMillis=timeout,
                  exclusive="true")
        try:
            dtop_cmo = getMBean("/")
            if machine_name not in [
                    mb.getName() for mb in dtop_cmo.getMachines()
            ]:
                print "Creating Machine %s." % machine_name
                machine = create(machine_name, "UnixMachine")
                cd("/Machines/%s/NodeManager/%s" %
                   (machine_name, machine_name))
                set("DebugEnabled", "true")
                set("ListenAddress", host_name)
                set("ListenPort", int(nm_port))
            else:
                machine = getMBean("/Machines/%s" % machine_name)

            for feature in feature_set:
                server_name = domain_metadata.get(feature).get("server-name")
                server_port = domain_metadata.get(feature).get("server-port")
                server_ssl_port = domain_metadata.get(feature).get(
                    "server-ssl-port")
                cluster_name = domain_metadata.get(feature).get("cluster-name")
                # server_name = "%s_%s" %(feature, machine_name)
                today = datetime.datetime.now().strftime("%m%d%Y%H%M%S")

                mserver = getMBean("/Servers/%s" % server_name)
                if mserver.getListenAddress() in (None, ""):
                    print "Configuring Server %s." % server_name
                    mserver.setMachine(machine)
                    mserver.setListenAddress(host_name)
                    mserver.setListenPort(int(server_port))
                    mserver_ssl = mserver.getSSL()
                    mserver_ssl.setEnabled(True)
                    mserver_ssl.setListenPort(int(server_ssl_port))
                    mserver_ssl.setHostnameVerificationIgnored(True)
                    mserver_ssl.setHostnameVerifier("None")
                    mserver_svs = mserver.getServerStart()
                    # mserver_svs.setArguments("-Djava.security.egd=file:/dev/./urandom -XX:+UnlockCommercialFeatures -XX:+ResourceManagement")
                    mserver_svs.setArguments(
                        "-Djava.security.egd=file:/dev/./urandom")
                else:
                    counter = 2
                    mserver_list = [
                        mb.getName() for mb in dtop_cmo.getServers()
                    ]
                    while True:
                        if "%s%i" % (server_name[:-1],
                                     counter) in mserver_list:
                            counter = counter + 1
                        else:
                            server_name = "%s%i" % (server_name[:-1], counter)
                            break
                    cluster = getMBean("/Clusters/%s" % cluster_name)
                    print "Creating Server %s." % server_name
                    cd("/")
                    mserver = create(server_name, "Server")
                    mserver.setMachine(machine)
                    mserver.setCluster(cluster)
                    mserver.setListenAddress(host_name)
                    mserver.setListenPort(int(server_port))
                    mserver_ssl = mserver.getSSL()
                    mserver_ssl.setEnabled(True)
                    mserver_ssl.setListenPort(int(server_ssl_port))
                    mserver_ssl.setHostnameVerificationIgnored(True)
                    mserver_ssl.setHostnameVerifier("None")
                    mserver_svs = mserver.getServerStart()
                    mserver_svs.setArguments(
                        "-Djava.security.egd=file:/dev/./urandom -XX:+UnlockCommercialFeatures -XX:+ResourceManagement"
                    )

                    jms_resources = domain_metadata.get(feature).get(
                        "jms-system-resources", [])
                    for resource in jms_resources:
                        cd("/")
                        fs_name = "%sFileStore%s" % (feature, today)
                        print "Creating FileStore %s." % fs_name
                        filestore = create(fs_name, "FileStore")
                        filestore.setDirectory(
                            os.path.join(shared_home, fs_name))
                        filestore.addTarget(mserver)
                        js_name = "%sJmsServer%s" % (feature, today)
                        print "Creating JMSServer %s." % js_name
                        jmsserver = create(js_name, "JMSServer")
                        jmsserver.addTarget(mserver)
                        cd("/JMSSystemResources/%s" % resource)
                        print "Creating SubDeployment %s." % js_name
                        deployment = create(js_name, "SubDeployment")
                        deployment.addTarget(jmsserver)
                        cd("JMSResource/%s" % resource)
                        jmsmodule = getMBean(
                            "/JMSSystemResources/%s/JMSResource/%s" %
                            (resource, resource))
                        for dqueue in jmsmodule.getDistributedQueues():
                            print "Updating DistributedQueue %s." % dqueue.getName(
                            )
                            dqueue.setSubDeploymentName(deployment.getName())
                        for queue in jmsmodule.getQueues():
                            print "Updating Queue %s." % queue.getName()
                            queue.setSubDeploymentName(deployment.getName())
                        for udqueue in jmsmodule.getUniformDistributedQueues():
                            print "Updating UniformDistributedQueue %s." % udqueue.getName(
                            )
                            udqueue.setSubDeploymentName(deployment.getName())
                        for dtopic in jmsmodule.getDistributedTopics():
                            print "Updating DistributedTopic %s." % dtopic.getName(
                            )
                            dtopic.setSubDeploymentName(deployment.getName())
                        for topic in jmsmodule.getTopics():
                            print "Updating Topic %s." % topic.getName()
                            topic.setSubDeploymentName(deployment.getName())
                        for udtopic in jmsmodule.getUniformDistributedTopics():
                            print "Updating UniformDistributedTopic %s." % udtopic.getName(
                            )
                            udtopic.setSubDeploymentName(deployment.getName())
        except:
            undo(defaultAnswer="y", unactivatedChanges="true")
            # cancelEdit("y")
            stopEdit("y")
            serverConfig()
            disconnect()
        else:
            save()
            activate(block="true")
            serverConfig()
            print "Writing domain to a template."
            domain_template = tempfile.mktemp() + ".jar"
            writeTemplate(domain_template)
            disconnect()
            print "Loading the template."
            selectCustomTemplate(domain_template)
            loadTemplates()
            setOption("AppDir", os.path.join(domain_home, "applications"))
            setOption("OverwriteDomain", "true")
            print "Configuring Nodemanager."
            cd("/NMProperties")
            set("NodeManagerHome", os.path.join(domain_home, "nodemanager"))
            set("ListenAddress", host_name)
            set("ListenPort", nm_port)
            print "Writing Domain Configuration."
            writeDomain(domain_home)
            os.unlink(domain_template)
            print "Writing boot.properties."
            bootdir = File(
                os.path.join(domain_home, "servers", server_name, "security"))
            bootdir.mkdirs()
            bfile = open(
                os.path.join(domain_home, "servers", server_name, "security",
                             "boot.properties"), "w")
            bfile.write("username=%s\n" % as_username)
            bfile.write("password=%s\n" % as_password)
            bfile.flush()
            bfile.close()
            print "Managed Domain built successfully."
def main(options, arguments):
    base_dir = os.path.dirname(sys.argv[0])
    if base_dir in [".", ""]: base_dir = os.getcwd()

    if os.path.isfile(os.path.join(base_dir, "metadata.json")):
        mfile = open(os.path.join(base_dir, "metadata.json"), "r")
        domain_metadata = eval(mfile.read())
        mfile.close()
    else:
        print "Mandatory file %s cannot be located in %s." %("metadata.json", base_dir)
        sys.exit(1)

    admin_host = options.get("-a")
    domain_home = options.get("-h")
    shared_home = options.get("-s", domain_home)
    as_username = options.get("--as_username", domain_metadata.get("wls").get("as-username"))
    as_password = options.get("--as_password", domain_metadata.get("wls").get("as_password"))
    nm_port = int(options.get("--nm_port", domain_metadata.get("wls").get("nm-port")))
    pwd_file = options.get("-w", "")
    if "--use_plain" not in options:
        as_port = int(options.get("--as_port", domain_metadata.get("wls").get("as-ssl-port")))
        admin_url = "t3s://%s:%s" %(admin_host, as_port)
    else:
        as_port = int(options.get("--as_port", domain_metadata.get("wls").get("as-port")))
        admin_url = "t3://%s:%s" %(admin_host, as_port)
    if "--overwrite" in options:
        overwrite = True
    else:
        overwrite = False

    wait = int(options.get("--wait", 300000))
    timeout = int(options.get("--timeout", -1))
    feature_set = LinkedHashSet(arguments)
    feature_set.retainAll(domain_metadata.keys())
    if feature_set.size() == 0: return

    if not os.path.isdir(domain_home) or overwrite:
        if os.path.isfile(pwd_file):
            bfile = open(pwd_file, "r")
            fcontents = bfile.read().splitlines()
            bfile.close()
            as_password = fcontents.pop()

        # Using IP for listen address
        # Revert back when Docker Networking is better
        host_name = socket.gethostname()
        machine_name = host_name.split(".")[0]
        host_name = socket.gethostbyname(host_name)
        connect(as_username, as_password, admin_url)
        edit()
        startEdit(waitTimeInMillis=wait, timeOutInMillis=timeout, exclusive="true")
        try:
            dtop_cmo = getMBean("/")
            if machine_name not in [mb.getName() for mb in dtop_cmo.getMachines()]:
                print "Creating Machine %s." %machine_name
                machine = create(machine_name, "UnixMachine")
                cd("/Machines/%s/NodeManager/%s" %(machine_name, machine_name))
                set("DebugEnabled", "true")
                set("ListenAddress", host_name)
                set("ListenPort", int(nm_port))
            else:
                machine = getMBean("/Machines/%s" %machine_name)

            for feature in feature_set:
                server_name = domain_metadata.get(feature).get("server-name")
                server_port = domain_metadata.get(feature).get("server-port")
                server_ssl_port = domain_metadata.get(feature).get("server-ssl-port")
                cluster_name = domain_metadata.get(feature).get("cluster-name")
                # server_name = "%s_%s" %(feature, machine_name)
                today = datetime.datetime.now().strftime("%m%d%Y%H%M%S")

                mserver = getMBean("/Servers/%s" %server_name)
                if mserver.getListenAddress() in (None, ""):
                    print "Configuring Server %s." %server_name
                    mserver.setMachine(machine)
                    mserver.setListenAddress(host_name)
                    mserver.setListenPort(int(server_port))
                    mserver_ssl = mserver.getSSL()
                    mserver_ssl.setEnabled(True)
                    mserver_ssl.setListenPort(int(server_ssl_port))
                    mserver_ssl.setHostnameVerificationIgnored(True)
                    mserver_ssl.setHostnameVerifier("None")
                    mserver_svs = mserver.getServerStart()
                    # mserver_svs.setArguments("-Djava.security.egd=file:/dev/./urandom -XX:+UnlockCommercialFeatures -XX:+ResourceManagement")
                    mserver_svs.setArguments("-Djava.security.egd=file:/dev/./urandom")
                else:
                    counter = 2
                    mserver_list = [mb.getName() for mb in dtop_cmo.getServers()]
                    while True:
                        if "%s%i" %(server_name[:-1], counter) in mserver_list:
                            counter = counter + 1
                        else:
                            server_name = "%s%i" %(server_name[:-1], counter)
                            break
                    cluster = getMBean("/Clusters/%s" %cluster_name)
                    print "Creating Server %s." %server_name
                    cd("/")
                    mserver = create(server_name, "Server")
                    mserver.setMachine(machine)
                    mserver.setCluster(cluster)
                    mserver.setListenAddress(host_name)
                    mserver.setListenPort(int(server_port))
                    mserver_ssl = mserver.getSSL()
                    mserver_ssl.setEnabled(True)
                    mserver_ssl.setListenPort(int(server_ssl_port))
                    mserver_ssl.setHostnameVerificationIgnored(True)
                    mserver_ssl.setHostnameVerifier("None")
                    mserver_svs = mserver.getServerStart()
                    mserver_svs.setArguments("-Djava.security.egd=file:/dev/./urandom -XX:+UnlockCommercialFeatures -XX:+ResourceManagement")

                    jms_resources = domain_metadata.get(feature).get("jms-system-resources", [])
                    for resource in jms_resources:
                        cd("/")
                        fs_name = "%sFileStore%s" %(feature, today)
                        print "Creating FileStore %s." %fs_name
                        filestore = create(fs_name, "FileStore")
                        filestore.setDirectory(os.path.join(shared_home, fs_name))
                        filestore.addTarget(mserver)
                        js_name = "%sJmsServer%s" %(feature, today)
                        print "Creating JMSServer %s." %js_name
                        jmsserver = create(js_name, "JMSServer")
                        jmsserver.addTarget(mserver)
                        cd("/JMSSystemResources/%s" %resource)
                        print "Creating SubDeployment %s." %js_name
                        deployment = create(js_name, "SubDeployment")
                        deployment.addTarget(jmsserver)
                        cd("JMSResource/%s" %resource)
                        jmsmodule = getMBean("/JMSSystemResources/%s/JMSResource/%s" %(resource, resource))
                        for dqueue in jmsmodule.getDistributedQueues():
                            print "Updating DistributedQueue %s." %dqueue.getName()
                            dqueue.setSubDeploymentName(deployment.getName())
                        for queue in jmsmodule.getQueues():
                            print "Updating Queue %s." %queue.getName()
                            queue.setSubDeploymentName(deployment.getName())
                        for udqueue in jmsmodule.getUniformDistributedQueues():
                            print "Updating UniformDistributedQueue %s." %udqueue.getName()
                            udqueue.setSubDeploymentName(deployment.getName())
                        for dtopic in jmsmodule.getDistributedTopics():
                            print "Updating DistributedTopic %s." %dtopic.getName()
                            dtopic.setSubDeploymentName(deployment.getName())
                        for topic in jmsmodule.getTopics():
                            print "Updating Topic %s." %topic.getName()
                            topic.setSubDeploymentName(deployment.getName())
                        for udtopic in jmsmodule.getUniformDistributedTopics():
                            print "Updating UniformDistributedTopic %s." %udtopic.getName()
                            udtopic.setSubDeploymentName(deployment.getName())
        except:
            undo(defaultAnswer="y", unactivatedChanges="true")
            # cancelEdit("y")
            stopEdit("y")
            serverConfig()
            disconnect()
        else:
            save()
            activate(block="true")
            serverConfig()
            print "Writing domain to a template."
            domain_template = tempfile.mktemp() + ".jar"
            writeTemplate(domain_template)
            disconnect()
            print "Loading the template."
            selectCustomTemplate(domain_template)
            loadTemplates()
            setOption("AppDir", os.path.join(domain_home, "applications"))
            setOption("OverwriteDomain", "true")
            print "Configuring Nodemanager."
            cd("/NMProperties")
            set("NodeManagerHome", os.path.join(domain_home, "nodemanager"))
            set("ListenAddress", host_name)
            set("ListenPort", nm_port)
            print "Writing Domain Configuration."
            writeDomain(domain_home)
            os.unlink(domain_template)
            print "Writing boot.properties."
            bootdir = File(os.path.join(domain_home, "servers", server_name, "security"))
            bootdir.mkdirs()
            bfile = open(os.path.join(domain_home, "servers", server_name, "security", "boot.properties"), "w")
            bfile.write("username=%s\n" %as_username)
            bfile.write("password=%s\n" %as_password)
            bfile.flush()
            bfile.close()
            print "Managed Domain built successfully."