Esempio n. 1
0
 private void process() {
   Object ob = configContext.getProperty(JsonConstant.XMLNODES);
   if (ob != null) {
     Map<QName, XmlNode> nodeMap = (Map<QName, XmlNode>) ob;
     XmlNode requesNode = nodeMap.get(elementQname);
     if (requesNode != null) {
       xmlNodeGenerator = new XmlNodeGenerator();
       schemaList = xmlNodeGenerator.getSchemaList(requesNode);
     } else {
       xmlNodeGenerator = new XmlNodeGenerator(xmlSchemaList, elementQname);
       mainXmlNode = xmlNodeGenerator.getMainXmlNode();
       schemaList = xmlNodeGenerator.getSchemaList(mainXmlNode);
       nodeMap.put(elementQname, mainXmlNode);
       configContext.setProperty(JsonConstant.XMLNODES, nodeMap);
     }
   } else {
     Map<QName, XmlNode> newNodeMap = new HashMap<QName, XmlNode>();
     xmlNodeGenerator = new XmlNodeGenerator(xmlSchemaList, elementQname);
     mainXmlNode = xmlNodeGenerator.getMainXmlNode();
     schemaList = xmlNodeGenerator.getSchemaList(mainXmlNode);
     newNodeMap.put(elementQname, mainXmlNode);
     configContext.setProperty(JsonConstant.XMLNODES, newNodeMap);
   }
   isProcessed = true;
 }
  /**
   * Create a Axis2 Based Server Environment
   *
   * @param serverConfigurationInformation ServerConfigurationInformation instance
   */
  private void createNewInstance(ServerConfigurationInformation serverConfigurationInformation) {

    try {
      configurationContext =
          ConfigurationContextFactory.createConfigurationContextFromFileSystem(
              serverConfigurationInformation.getAxis2RepoLocation(),
              serverConfigurationInformation.getAxis2Xml());

      configurationContext.setProperty(AddressingConstants.ADDR_VALIDATE_ACTION, Boolean.FALSE);

      startJmxAdapter();

      listenerManager = configurationContext.getListenerManager();
      if (listenerManager == null) {

        // create and initialize the listener manager but do not start
        listenerManager = new ListenerManager();
        listenerManager.init(configurationContext);
      }

      // do not use the listener manager shutdown hook, because it clashes with the
      // SynapseServer shutdown hook.
      listenerManager.setShutdownHookRequired(false);

    } catch (Throwable t) {
      handleFatal("Failed to create a new Axis2 instance...", t);
    }
  }
 private void initThrottle(ConfigurationContext cc) {
   Object entryValue = null;
   if (throttle == null) {
     entryValue = ThrottleUtils.lookup(APIManagerConstants.APPLICATION_THROTTLE_POLICY_KEY);
   }
   if (isClusteringEnable && concurrentAccessController != null && throttle != null) {
     concurrentAccessController = null; // set null ,
     // because need to reload
   }
   if (throttle == null) {
     try {
       throttle =
           ThrottleFactory.createMediatorThrottle(PolicyEngine.getPolicy((OMElement) entryValue));
       // For non-clustered  environment , must re-initiates
       // For  clustered  environment,
       // concurrent access controller is null ,
       // then must re-initiates
       if (throttle != null && (concurrentAccessController == null || !isClusteringEnable)) {
         concurrentAccessController = throttle.getConcurrentAccessController();
         if (concurrentAccessController != null) {
           cc.setProperty(key, concurrentAccessController);
         } else {
           cc.removeProperty(key);
         }
       }
     } catch (ThrottleException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
   }
 }
  /**
   * @param request -Httpservlet request
   * @param accessToken
   * @return
   * @throws APIFaultException
   */
  public boolean doThrottle(HttpServletRequest request, String accessToken)
      throws APIFaultException {

    String apiName = request.getContextPath();
    String apiVersion = APIManagetInterceptorUtils.getAPIVersion(request);
    String apiIdentifier = apiName + "-" + apiVersion;

    APIThrottleHandler throttleHandler = null;
    ConfigurationContext cc = DataHolder.getServerConfigContext();

    if (cc.getProperty(apiIdentifier) == null) {
      throttleHandler = new APIThrottleHandler();
      /* Add the Throttle handler to ConfigContext against API Identifier */
      cc.setProperty(apiIdentifier, throttleHandler);
    } else {
      throttleHandler = (APIThrottleHandler) cc.getProperty(apiIdentifier);
    }

    if (throttleHandler.doThrottle(request, apiKeyValidationDTO, accessToken)) {
      return true;
    } else {
      throw new APIFaultException(
          APIManagerErrorConstants.API_THROTTLE_OUT, "You have exceeded your quota");
    }
  }
Esempio n. 5
0
 /**
  * Get the current server status
  *
  * @return The current server status
  * @throws AxisFault If an error occurs while getting the ConfigurationContext
  */
 public static String getCurrentStatus() {
   ConfigurationContext configCtx = CarbonConfigurationContextFactory.getConfigurationContext();
   String currentStatus = (String) configCtx.getProperty(CURRENT_SERVER_STATUS);
   if (currentStatus == null) {
     configCtx.setProperty(CURRENT_SERVER_STATUS, STATUS_RUNNING);
     return STATUS_RUNNING;
   }
   return currentStatus;
 }
 /**
  * Get all the tenant ConfigurationContexts
  *
  * @param mainConfigCtx Super-tenant Axis2 ConfigurationContext
  * @return the tenant ConfigurationContexts as a Map of "tenant domain -> ConfigurationContext"
  */
 @SuppressWarnings("unchecked")
 public static Map<String, ConfigurationContext> getTenantConfigurationContexts(
     ConfigurationContext mainConfigCtx) {
   Map<String, ConfigurationContext> tenantConfigContexts =
       (Map<String, ConfigurationContext>)
           mainConfigCtx.getProperty(TENANT_CONFIGURATION_CONTEXTS);
   if (tenantConfigContexts == null) {
     tenantConfigContexts = new ConcurrentHashMap<String, ConfigurationContext>();
     mainConfigCtx.setProperty(TENANT_CONFIGURATION_CONTEXTS, tenantConfigContexts);
   }
   return tenantConfigContexts;
 }
Esempio n. 7
0
 private void processSchemaUpdates(
     QName elementQname, List<XmlSchema> xmlSchemaList, ConfigurationContext configContext) {
   Object ob = configContext.getProperty(JsonConstant.CURRENT_XML_SCHEMA);
   if (ob != null) {
     Map<QName, XmlSchema> schemaMap = (Map<QName, XmlSchema>) ob;
     if (schemaMap != null) {
       XmlSchema currentXmlSchema = schemaMap.get(elementQname);
       for (XmlSchema xmlSchema : xmlSchemaList) {
         if (xmlSchema.getTargetNamespace().equals(elementQname.getNamespaceURI())) {
           if (currentXmlSchema != xmlSchema) {
             schemaMap.put(elementQname, xmlSchema);
             configContext.setProperty(JsonConstant.XMLNODES, null);
             if (log.isDebugEnabled()) {
               log.debug(
                   "Updating message schema. [Current:"
                       + currentXmlSchema
                       + ", New:"
                       + xmlSchema
                       + "]");
             }
           }
           break;
         }
       }
     }
   } else {
     Map<QName, XmlSchema> schemaMap = new HashMap<QName, XmlSchema>();
     for (XmlSchema xmlSchema : xmlSchemaList) {
       if (xmlSchema.getTargetNamespace().equals(elementQname.getNamespaceURI())) {
         schemaMap.put(elementQname, xmlSchema);
         configContext.setProperty(JsonConstant.CURRENT_XML_SCHEMA, schemaMap);
         break;
       }
     }
   }
 }
  @Override
  public InvocationResponse invoke(MessageContext messageContext) throws AxisFault {

    // get the counter property from the configuration context
    ConfigurationContext configurationContext = messageContext.getConfigurationContext();
    Integer count = (Integer) configurationContext.getProperty(OUTGOING_MESSAGE_COUNT_KEY);
    // increment the counter
    count = Integer.valueOf(count.intValue() + 1 + "");
    // set the new count back to the configuration context
    configurationContext.setProperty(OUTGOING_MESSAGE_COUNT_KEY, count);
    // print it out

    logger.info("The outgoing message count is now " + count);

    logger.info(messageContext.getEnvelope().toString());
    return InvocationResponse.CONTINUE;
  }
  public static ConfigurationContext getTenantConfigurationContext(
      String tenantDomain, ConfigurationContext mainConfigCtx) {
    ConfigurationContext tenantConfigCtx;

    Boolean isTenantActive;
    try {
      isTenantActive =
          CarbonCoreDataHolder.getInstance()
              .getRealmService()
              .getTenantManager()
              .isTenantActive(getTenantId(tenantDomain));
    } catch (Exception e) {
      throw new RuntimeException("Error while getting tenant activation status.", e);
    }

    if (!isTenantActive) {
      throw new RuntimeException("Trying to access inactive tenant domain : " + tenantDomain);
    }

    if (tenantReadWriteLocks.get(tenantDomain) == null) {
      synchronized (tenantDomain.intern()) {
        if (tenantReadWriteLocks.get(tenantDomain) == null) {
          tenantReadWriteLocks.put(tenantDomain, new ReentrantReadWriteLock());
        }
      }
    }
    Lock tenantReadLock = tenantReadWriteLocks.get(tenantDomain).readLock();
    try {
      tenantReadLock.lock();
      Map<String, ConfigurationContext> tenantConfigContexts =
          getTenantConfigurationContexts(mainConfigCtx);
      tenantConfigCtx = tenantConfigContexts.get(tenantDomain);
      if (tenantConfigCtx == null) {
        try {
          tenantConfigCtx = createTenantConfigurationContext(mainConfigCtx, tenantDomain);
        } catch (Exception e) {
          throw new RuntimeException(
              "Cannot create tenant ConfigurationContext for tenant " + tenantDomain, e);
        }
      }
      tenantConfigCtx.setProperty(MultitenantConstants.LAST_ACCESSED, System.currentTimeMillis());
    } finally {
      tenantReadLock.unlock();
    }
    return tenantConfigCtx;
  }
Esempio n. 10
0
  /**
   * Helper method for handling role based Access throttling
   *
   * @param messageContext MessageContext - message level states
   * @return true if access is allowed through concurrent throttling ,o.w false
   */
  private boolean doRoleBasedAccessThrottling(
      Throttle throttle, MessageContext messageContext, boolean isClusteringEnable)
      throws AxisFault, ThrottleException {

    boolean canAccess = true;
    ConfigurationContext cc = messageContext.getConfigurationContext();
    String throttleId = throttle.getId();

    String key = null;
    ConcurrentAccessController cac = null;
    if (isClusteringEnable) {
      // for clustered  env.,gets it from axis configuration context
      key = ThrottleConstants.THROTTLE_PROPERTY_PREFIX + throttleId + ThrottleConstants.CAC_SUFFIX;
      cac = (ConcurrentAccessController) cc.getProperty(key);
    }

    if (messageContext.getFLOW() == MessageContext.IN_FLOW) {
      // gets the remote caller role name
      String consumerKey = null;
      boolean isAuthenticated = false;
      String roleID = null;
      HttpServletRequest request =
          (HttpServletRequest)
              messageContext.getPropertyNonReplicable(HTTPConstants.MC_HTTP_SERVLETREQUEST);
      if (request != null) {
        String oAuthHeader = request.getHeader("OAuth");
        //                consumerKey = Utils.extractCustomerKeyFromAuthHeader(oAuthHeader);
        //                roleID = Utils.extractCustomerKeyFromAuthHeader(oAuthHeader);
        DummyAuthenticator authFuture = new DummyAuthenticator(oAuthHeader);
        consumerKey = authFuture.getAPIKey();
        new DummyHandler().authenticateUser(authFuture);
        roleID = (String) authFuture.getAuthorizedRoles().get(0);
        isAuthenticated = authFuture.isAuthenticated();
      }

      if (!isAuthenticated) {
        throw new AxisFault(
            " Access deny for a "
                + "caller with consumer Key: "
                + consumerKey
                + " "
                + " : Reason : Authentication failure");
      }
      // Domain name based throttling
      // check whether a configuration has been defined for this role name or not
      String consumerRoleID = null;
      if (consumerKey != null && isAuthenticated) {
        // loads the ThrottleContext
        ThrottleContext context =
            throttle.getThrottleContext(ThrottleConstants.ROLE_BASED_THROTTLE_KEY);
        if (context != null) {
          // Loads the ThrottleConfiguration
          ThrottleConfiguration config = context.getThrottleConfiguration();
          if (config != null) {
            // check for configuration for this caller
            consumerRoleID = config.getConfigurationKeyOfCaller(roleID);
            if (consumerRoleID != null) {
              // If this is a clustered env.
              if (isClusteringEnable) {
                context.setConfigurationContext(cc);
                context.setThrottleId(throttleId);
              }
              AccessInformation infor =
                  roleBasedAccessController.canAccess(context, consumerKey, consumerRoleID);
              StatCollector.collect(infor, consumerKey, ThrottleConstants.ROLE_BASE);
              // check for the permission for access
              if (!infor.isAccessAllowed()) {

                // In the case of both of concurrency throttling and
                // rate based throttling have enabled ,
                // if the access rate less than maximum concurrent access ,
                // then it is possible to occur death situation.To avoid that reset,
                // if the access has denied by rate based throttling
                if (cac != null) {
                  cac.incrementAndGet();
                  // set back if this is a clustered env
                  if (isClusteringEnable) {
                    cc.setProperty(key, cac);
                    // replicate the current state of ConcurrentAccessController
                    try {
                      if (debugOn) {
                        log.debug(
                            "Going to replicates the "
                                + "states of the ConcurrentAccessController"
                                + " with key : "
                                + key);
                      }
                      Replicator.replicate(cc, new String[] {key});
                    } catch (ClusteringFault clusteringFault) {
                      log.error("Error during replicating states ", clusteringFault);
                    }
                  }
                }
                throw new AxisFault(
                    " Access deny for a "
                        + "caller with Domain "
                        + consumerKey
                        + " "
                        + " : Reason : "
                        + infor.getFaultReason());
              }
            } else {
              if (debugOn) {
                log.debug(
                    "Could not find the Throttle Context for role-Based "
                        + "Throttling for role name "
                        + consumerKey
                        + " Throttling for this "
                        + "role name may not be configured from policy");
              }
            }
          }
        }
      } else {
        if (debugOn) {
          log.debug("Could not find the role of the caller - role based throttling NOT applied");
        }
      }
    }
    return canAccess;
  }
Esempio n. 11
0
  /**
   * processing through the throttle 1) concurrent throttling 2) access rate based throttling -
   * domain or ip
   *
   * @param throttle The Throttle object - holds all configuration and state data of the throttle
   * @param messageContext The MessageContext , that holds all data per message basis
   * @throws AxisFault Throws when access must deny for caller
   * @throws ThrottleException ThrottleException
   */
  public void process(Throttle throttle, MessageContext messageContext)
      throws ThrottleException, AxisFault {

    String throttleId = throttle.getId();
    ConfigurationContext cc = messageContext.getConfigurationContext();

    // check the env - whether clustered  or not
    boolean isClusteringEnable = false;
    ClusteringAgent clusteringAgent = null;
    if (cc != null) {
      clusteringAgent = cc.getAxisConfiguration().getClusteringAgent();
    }
    if (clusteringAgent != null && clusteringAgent.getStateManager() != null) {
      isClusteringEnable = true;
    }

    // Get the concurrent access controller
    ConcurrentAccessController cac;
    String key = null;
    if (isClusteringEnable) {
      // for clustered  env.,gets it from axis configuration context
      key = ThrottleConstants.THROTTLE_PROPERTY_PREFIX + throttleId + ThrottleConstants.CAC_SUFFIX;
      cac = (ConcurrentAccessController) cc.getProperty(key);
    } else {
      // for non-clustered  env.,gets it from axis configuration context
      cac = throttle.getConcurrentAccessController();
    }

    // check for concurrent access
    boolean canAccess = doConcurrentThrottling(cac, messageContext);

    if (canAccess) {
      // if the concurrent access is success then
      // do the access rate based throttling

      if (messageContext.getFLOW() == MessageContext.IN_FLOW) {
        // gets the remote caller domain name
        String domain = null;
        HttpServletRequest request =
            (HttpServletRequest)
                messageContext.getPropertyNonReplicable(HTTPConstants.MC_HTTP_SERVLETREQUEST);
        if (request != null) {
          domain = request.getRemoteHost();
        }

        // Domain name based throttling
        // check whether a configuration has been defined for this domain name or not
        String callerId = null;
        if (domain != null) {
          // loads the ThrottleContext
          ThrottleContext context =
              throttle.getThrottleContext(ThrottleConstants.DOMAIN_BASED_THROTTLE_KEY);
          if (context != null) {
            // Loads the ThrottleConfiguration
            ThrottleConfiguration config = context.getThrottleConfiguration();
            if (config != null) {
              // check for configuration for this caller
              callerId = config.getConfigurationKeyOfCaller(domain);
              if (callerId != null) {
                // If this is a clustered env.
                if (isClusteringEnable) {
                  context.setConfigurationContext(cc);
                  context.setThrottleId(throttleId);
                }
                AccessInformation infor =
                    accessRateController.canAccess(
                        context, callerId, ThrottleConstants.DOMAIN_BASE);
                StatCollector.collect(infor, domain, ThrottleConstants.DOMAIN_BASE);

                // check for the permission for access
                if (!infor.isAccessAllowed()) {

                  // In the case of both of concurrency throttling and
                  // rate based throttling have enabled ,
                  // if the access rate less than maximum concurrent access ,
                  // then it is possible to occur death situation.To avoid that reset,
                  // if the access has denied by rate based throttling
                  if (cac != null) {
                    cac.incrementAndGet();
                    // set back if this is a clustered env
                    if (isClusteringEnable) {
                      cc.setProperty(key, cac);
                      // replicate the current state of ConcurrentAccessController
                      try {
                        if (debugOn) {
                          log.debug(
                              "Going to replicates the "
                                  + "states of the ConcurrentAccessController"
                                  + " with key : "
                                  + key);
                        }
                        Replicator.replicate(cc, new String[] {key});
                      } catch (ClusteringFault clusteringFault) {
                        log.error("Error during replicating states ", clusteringFault);
                      }
                    }
                  }
                  throw new AxisFault(
                      " Access deny for a "
                          + "caller with Domain "
                          + domain
                          + " "
                          + " : Reason : "
                          + infor.getFaultReason());
                }
              } else {
                if (debugOn) {
                  log.debug(
                      "Could not find the Throttle Context for domain-Based "
                          + "Throttling for domain name "
                          + domain
                          + " Throttling for this "
                          + "domain name may not be configured from policy");
                }
              }
            }
          }
        } else {
          if (debugOn) {
            log.debug("Could not find the domain of the caller - IP-based throttling may occur");
          }
        }

        // IP based throttling - Only if there is no configuration for caller domain name

        if (callerId == null) {
          String ip = (String) messageContext.getProperty(MessageContext.REMOTE_ADDR);
          if (ip != null) {
            // loads IP based throttle context
            ThrottleContext context =
                throttle.getThrottleContext(ThrottleConstants.IP_BASED_THROTTLE_KEY);
            if (context != null) {
              // Loads the ThrottleConfiguration
              ThrottleConfiguration config = context.getThrottleConfiguration();
              if (config != null) {
                // check for configuration for this ip
                callerId = config.getConfigurationKeyOfCaller(ip);
                if (callerId != null) {
                  // for clustered env.
                  if (isClusteringEnable) {
                    context.setConfigurationContext(cc);
                    context.setThrottleId(throttleId);
                  }
                  AccessInformation infor =
                      accessRateController.canAccess(context, callerId, ThrottleConstants.IP_BASE);
                  // check for the permission for access
                  StatCollector.collect(infor, ip, ThrottleConstants.IP_BASE);
                  if (!infor.isAccessAllowed()) {

                    // In the case of both of concurrency throttling and
                    // rate based throttling have enabled ,
                    // if the access rate less than maximum concurrent access ,
                    // then it is possible to occur death situation.To avoid that reset,
                    // if the access has denied by rate based throttling
                    if (cac != null) {
                      cac.incrementAndGet();
                      // set back if this is a clustered env
                      if (isClusteringEnable) {
                        cc.setProperty(key, cac);
                        // replicate the current state of ConcurrentAccessController
                        try {
                          if (debugOn) {
                            log.debug(
                                "Going to replicates the "
                                    + "states of the ConcurrentAccessController"
                                    + " with key : "
                                    + key);
                          }
                          Replicator.replicate(cc, new String[] {key});
                        } catch (ClusteringFault clusteringFault) {
                          log.error("Error during replicating states ", clusteringFault);
                        }
                      }
                    }
                    throw new AxisFault(
                        " Access deny for a "
                            + "caller with IP "
                            + ip
                            + " "
                            + " : Reason : "
                            + infor.getFaultReason());
                  }
                }
              }
            } else {
              if (debugOn) {
                log.debug("Could not find the throttle Context for IP-Based throttling");
              }
            }
          } else {
            if (debugOn) {
              log.debug(
                  "Could not find the IP address of the caller " + "- throttling will not occur");
            }
          }
        }
      }
      // all the replication functionality of the access rate based throttling handles by itself
      // just replicate the current state of ConcurrentAccessController
      if (isClusteringEnable && cac != null) {
        try {
          if (debugOn) {
            log.debug(
                "Going to replicates the states of the ConcurrentAccessController"
                    + " with key : "
                    + key);
          }
          Replicator.replicate(cc, new String[] {key});
        } catch (ClusteringFault clusteringFault) {
          log.error("Error during replicating states ", clusteringFault);
        }
      }

      // finally engage rolebased access throttling if available
      doRoleBasedAccessThrottling(throttle, messageContext, isClusteringEnable);
    } else {
      // replicate the current state of ConcurrentAccessController
      if (isClusteringEnable) {
        try {
          if (debugOn) {
            log.debug(
                "Going to replicates the states of the ConcurrentAccessController"
                    + " with key : "
                    + key);
          }
          Replicator.replicate(cc, new String[] {key});
        } catch (ClusteringFault clusteringFault) {
          log.error("Error during replicating states ", clusteringFault);
        }
      }
      throw new AxisFault(
          "Access has currently been denied since " + " maximum concurrent access have exceeded");
    }
  }
  public void createdConfigurationContext(ConfigurationContext configurationContext) {
    ServerContextInformation contextInfo;
    String tenantDomain =
        SuperTenantCarbonContext.getCurrentContext(configurationContext).getTenantDomain();

    log.info("Intializing the ESB Configuration for the tenant domain : " + tenantDomain);

    try {
      // first check which configuration should be active
      org.wso2.carbon.registry.core.Registry registry =
          (org.wso2.carbon.registry.core.Registry)
              SuperTenantCarbonContext.getCurrentContext(configurationContext)
                  .getRegistry(RegistryType.SYSTEM_CONFIGURATION);

      AxisConfiguration axisConfig = configurationContext.getAxisConfiguration();

      // initialize the lock
      Lock lock = new ReentrantLock();
      axisConfig.addParameter(ServiceBusConstants.SYNAPSE_CONFIG_LOCK, lock);

      // creates the synapse configuration directory hierarchy if not exists
      // useful at the initial tenant creation
      File tenantAxis2Repo =
          new File(configurationContext.getAxisConfiguration().getRepository().getFile());
      File synapseConfigsDir = new File(tenantAxis2Repo, ServiceBusConstants.SYNAPSE_CONFIGS);
      if (!synapseConfigsDir.exists()) {
        if (!synapseConfigsDir.mkdir()) {
          log.fatal(
              "Couldn't create the synapse-config root on the file system "
                  + "for the tenant domain : "
                  + tenantDomain);
          return;
        }
      }

      String synapseConfigsDirLocation = synapseConfigsDir.getAbsolutePath();

      // set the required configuration parameters to initialize the ESB
      axisConfig.addParameter(
          SynapseConstants.Axis2Param.SYNAPSE_CONFIG_LOCATION, synapseConfigsDirLocation);

      // init the multiple configuration tracker
      ConfigurationManager manger =
          new ConfigurationManager((UserRegistry) registry, configurationContext);
      manger.init();

      File synapseConfigDir =
          new File(synapseConfigsDir, manger.getTracker().getCurrentConfigurationName());
      if (!synapseConfigDir.exists()) {
        createTenantSynapseConfigHierarchy(synapseConfigDir, tenantDomain);
      }

      axisConfig.addParameter(
          SynapseConstants.Axis2Param.SYNAPSE_HOME, tenantAxis2Repo.getAbsolutePath());
      axisConfig.addParameter(
          SynapseConstants.Axis2Param.SYNAPSE_SERVER_NAME, "synapse." + tenantDomain);
      axisConfig.addParameter(
          SynapseConstants.Axis2Param.SYNAPSE_RESOLVE_ROOT, tenantAxis2Repo.getAbsolutePath());

      // Initialize Synapse
      contextInfo =
          initESB(manger.getTracker().getCurrentConfigurationName(), configurationContext);

      if (contextInfo == null) {
        handleFatal("Failed to intilize the ESB for tenent:" + tenantDomain);
      }

      initPersistence(
          manger.getTracker().getCurrentConfigurationName(), configurationContext, contextInfo);

      configurationContext.setProperty(ConfigurationManager.CONFIGURATION_MANAGER, manger);

      int tenantId = SuperTenantCarbonContext.getCurrentContext(configurationContext).getTenantId();
      // populate the SynapseEnv service and SynapseConfig OSGI Services so that other
      // components get to know about the availability of the new synapse configuration
      Properties props = new Properties();
      SynapseConfigurationService synCfgSvc =
          new SynapseConfigurationServiceImpl(
              contextInfo.getSynapseConfiguration(), tenantId, configurationContext);

      ServiceRegistration confRegistration =
          ConfigurationHolder.getInstance()
              .getBundleContext()
              .registerService(SynapseConfigurationService.class.getName(), synCfgSvc, props);

      props = new Properties();
      SynapseEnvironmentService synEnvSvc =
          new SynapseEnvironmentServiceImpl(
              contextInfo.getSynapseEnvironment(), tenantId, configurationContext);
      ServiceRegistration envRegistration =
          ConfigurationHolder.getInstance()
              .getBundleContext()
              .registerService(SynapseEnvironmentService.class.getName(), synEnvSvc, props);

      props = new Properties();
      SynapseRegistrationsService synRegistrationsSvc =
          new SynapseRegistrationsServiceImpl(
              confRegistration, envRegistration, tenantId, configurationContext);
      ServiceRegistration synapseRegistration =
          ConfigurationHolder.getInstance()
              .getBundleContext()
              .registerService(
                  SynapseRegistrationsService.class.getName(), synRegistrationsSvc, props);

      ConfigurationTrackingService trackingService =
          ServiceBusInitializer.getConfigurationTrackingService();
      if (trackingService != null) {
        trackingService.setSynapseConfiguration(contextInfo.getSynapseConfiguration());
      }

      // set the event broker as a property for tenants
      EventBroker eventBroker = ServiceBusInitializer.getEventBroker();
      if (eventBroker != null) {
        configurationContext.setProperty("mediation.event.broker", eventBroker);
      }

      ConfigurationHolder.getInstance().addSynapseRegistration(tenantId, synapseRegistration);

    } catch (Exception e) {
      handleFatal("Couldn't initialize the ESB for tenant:" + tenantDomain, e);
    } catch (Throwable t) {
      log.fatal("Failed to initialize ESB for tenant:" + tenantDomain + "due to a fatal error", t);
    }
  }
  private ServerContextInformation initESB(
      String configurationName, ConfigurationContext configurationContext) throws AxisFault {
    ServerConfigurationInformation configurationInformation =
        ServerConfigurationInformationFactory.createServerConfigurationInformation(
            configurationContext.getAxisConfiguration());
    // ability to specify the SynapseServerName as a system property
    if (System.getProperty("SynapseServerName") != null) {
      configurationInformation.setServerName(System.getProperty("SynapseServerName"));
    }

    // for now we override the default configuration location with the value in registry
    String repoPath = configurationContext.getAxisConfiguration().getRepository().getPath();
    configurationInformation.setSynapseXMLLocation(
        repoPath
            + File.separator
            + ServiceBusConstants.SYNAPSE_CONFIGS
            + File.separator
            + configurationName);

    configurationInformation.setCreateNewInstance(false);
    configurationInformation.setServerControllerProvider(CarbonSynapseController.class.getName());
    if (isRunningSamplesMode()) {
      configurationInformation.setSynapseXMLLocation(
          "repository"
              + File.separator
              + "samples"
              + File.separator
              + "synapse_sample_"
              + System.getProperty(ServiceBusConstants.ESB_SAMPLE_SYSTEM_PROPERTY)
              + ".xml");
    }

    ServerManager serverManager = new ServerManager();
    ServerContextInformation contextInfo =
        new ServerContextInformation(configurationContext, configurationInformation);

    /*if (dataSourceInformationRepositoryService != null) {
        DataSourceInformationRepository repository =
                dataSourceInformationRepositoryService.getDataSourceInformationRepository();
        contextInfo.addProperty(DataSourceConstants.DATA_SOURCE_INFORMATION_REPOSITORY,
                repository);
    }*/

    TaskScheduler scheduler;
    if (configurationContext.getProperty(ServiceBusConstants.CARBON_TASK_SCHEDULER) == null) {
      scheduler = new TaskScheduler(TaskConstants.TASK_SCHEDULER);
      configurationContext.setProperty(ServiceBusConstants.CARBON_TASK_SCHEDULER, scheduler);
    } else {
      scheduler =
          (TaskScheduler)
              configurationContext.getProperty(ServiceBusConstants.CARBON_TASK_SCHEDULER);
    }
    contextInfo.addProperty(TaskConstants.TASK_SCHEDULER, scheduler);

    TaskDescriptionRepository repository;
    if (configurationContext.getProperty(ServiceBusConstants.CARBON_TASK_REPOSITORY) == null) {
      repository = new TaskDescriptionRepository();
      configurationContext.setProperty(ServiceBusConstants.CARBON_TASK_REPOSITORY, repository);
    } else {
      repository =
          (TaskDescriptionRepository)
              configurationContext.getProperty(ServiceBusConstants.CARBON_TASK_REPOSITORY);
    }
    contextInfo.addProperty(TaskConstants.TASK_DESCRIPTION_REPOSITORY, repository);

    /* if (secretCallbackHandlerService != null) {
        contextInfo.addProperty(SecurityConstants.PROP_SECRET_CALLBACK_HANDLER,
                secretCallbackHandlerService.getSecretCallbackHandler());
    }*/

    AxisConfiguration axisConf = configurationContext.getAxisConfiguration();
    axisConf.addParameter(
        new Parameter(ServiceBusConstants.SYNAPSE_CURRENT_CONFIGURATION, configurationName));

    serverManager.init(configurationInformation, contextInfo);
    serverManager.start();

    AxisServiceGroup serviceGroup = axisConf.getServiceGroup(SynapseConstants.SYNAPSE_SERVICE_NAME);
    serviceGroup.addParameter("hiddenService", "true");

    addDeployers(configurationContext);

    return contextInfo;
  }
  /**
   * Create Tenant Axis2 ConfigurationContexts & add them to the main Axis2 ConfigurationContext
   *
   * @param mainConfigCtx Super-tenant Axis2 ConfigurationContext
   * @param tenantDomain Tenant domain (e.g. foo.com)
   * @return The newly created Tenant ConfigurationContext
   * @throws Exception If an error occurs while creating tenant ConfigurationContext
   */
  private static ConfigurationContext createTenantConfigurationContext(
      ConfigurationContext mainConfigCtx, String tenantDomain) throws Exception {
    synchronized (tenantDomain.intern()) { // lock based on tenant domain
      Map<String, ConfigurationContext> tenantConfigContexts =
          getTenantConfigurationContexts(mainConfigCtx);
      ConfigurationContext tenantConfigCtx = tenantConfigContexts.get(tenantDomain);
      if (tenantConfigCtx != null) {
        return tenantConfigCtx;
      }
      long tenantLoadingStartTime = System.currentTimeMillis();
      int tenantId = getTenantId(tenantDomain);
      if (tenantId == MultitenantConstants.SUPER_TENANT_ID
          || tenantId == MultitenantConstants.INVALID_TENANT_ID) {
        throw new Exception("Tenant " + tenantDomain + " does not exist");
      }
      PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
      carbonContext.setTenantId(tenantId);
      carbonContext.setTenantDomain(tenantDomain);

      tenantConfigCtx = tenantConfigContexts.get(tenantDomain);
      if (tenantConfigCtx != null) {
        return tenantConfigCtx;
      }

      AxisConfiguration mainAxisConfig = mainConfigCtx.getAxisConfiguration();

      dataHolder.getTenantRegistryLoader().loadTenantRegistry(tenantId);

      try {
        UserRegistry tenantConfigRegistry =
            dataHolder.getRegistryService().getConfigSystemRegistry(tenantId);
        UserRegistry tenantLocalUserRegistry =
            dataHolder.getRegistryService().getLocalRepository(tenantId);
        TenantAxisConfigurator tenantAxisConfigurator =
            new TenantAxisConfigurator(
                mainAxisConfig,
                tenantDomain,
                tenantId,
                tenantConfigRegistry,
                tenantLocalUserRegistry);
        doPreConfigContextCreation(tenantId);
        tenantConfigCtx =
            ConfigurationContextFactory.createConfigurationContext(tenantAxisConfigurator);

        AxisConfiguration tenantAxisConfig = tenantConfigCtx.getAxisConfiguration();

        tenantConfigCtx.setServicePath(CarbonUtils.getAxis2ServicesDir(tenantAxisConfig));
        tenantConfigCtx.setContextRoot("local:/");

        TenantTransportSender transportSender = new TenantTransportSender(mainConfigCtx);
        // Adding transport senders
        HashMap<String, TransportOutDescription> transportSenders =
            mainAxisConfig.getTransportsOut();
        if (transportSenders != null && !transportSenders.isEmpty()) {
          for (String strTransport : transportSenders.keySet()) {
            TransportOutDescription outDescription = new TransportOutDescription(strTransport);
            outDescription.setSender(transportSender);
            tenantAxisConfig.addTransportOut(outDescription);
          }
        }

        // Set the work directory
        tenantConfigCtx.setProperty(
            ServerConstants.WORK_DIR, mainConfigCtx.getProperty(ServerConstants.WORK_DIR));
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
        new TransportPersistenceManager(tenantAxisConfig)
            .updateEnabledTransports(
                tenantAxisConfig.getTransportsIn().values(),
                tenantAxisConfig.getTransportsOut().values());

        // Notify all observers
        BundleContext bundleContext = dataHolder.getBundleContext();
        if (bundleContext != null) {
          ServiceTracker tracker =
              new ServiceTracker(
                  bundleContext, Axis2ConfigurationContextObserver.class.getName(), null);
          tracker.open();
          Object[] services = tracker.getServices();
          if (services != null) {
            for (Object service : services) {
              ((Axis2ConfigurationContextObserver) service)
                  .createdConfigurationContext(tenantConfigCtx);
            }
          }
          tracker.close();
        }
        tenantConfigCtx.setProperty(MultitenantConstants.LAST_ACCESSED, System.currentTimeMillis());

        // Register Capp deployer for this tenant
        Utils.addCAppDeployer(tenantAxisConfig);

        // deploy the services since all the deployers are initialized by now.
        tenantAxisConfigurator.deployServices();

        // tenant config context must only be made after the tenant is fully loaded, and all its
        // artifacts
        // are deployed.
        // -- THIS SHOULD BE THE LAST OPERATION OF THIS METHOD --
        tenantConfigContexts.put(tenantDomain, tenantConfigCtx);

        log.info(
            "Loaded tenant "
                + tenantDomain
                + " in "
                + (System.currentTimeMillis() - tenantLoadingStartTime)
                + " ms");

        return tenantConfigCtx;
      } catch (Exception e) {
        String msg = "Error occurred while running deployment for tenant ";
        log.error(msg + tenantDomain, e);
        throw new Exception(msg, e);
      }
    }
  }
Esempio n. 15
0
 /**
  * Set server to shutting-down mode
  *
  * @throws AxisFault If an error occurs while getting the ConfigurationContext
  */
 public static void setServerShuttingDown() throws AxisFault {
   ConfigurationContext configCtx = CarbonConfigurationContextFactory.getConfigurationContext();
   configCtx.setProperty(CURRENT_SERVER_STATUS, STATUS_SHUTTING_DOWN);
 }
Esempio n. 16
0
 /**
  * Set server to restarting-down mode
  *
  * @throws AxisFault If an error occurs while getting the ConfigurationContext
  */
 public static void setServerRestarting() throws AxisFault {
   ConfigurationContext configCtx = CarbonConfigurationContextFactory.getConfigurationContext();
   configCtx.setProperty(CURRENT_SERVER_STATUS, STATUS_RESTARTING);
 }
  /**
   * {@inheritDoc}
   *
   * @param serverConfigurationInformation ServerConfigurationInformation Instance
   * @param serverContextInformation Server Context if the Axis2 Based Server Environment has been
   *     already set up.
   */
  public void init(
      ServerConfigurationInformation serverConfigurationInformation,
      ServerContextInformation serverContextInformation) {

    log.info("Initializing Synapse at : " + new Date());
    if (serverConfigurationInformation == null) {
      throw new IllegalArgumentException("ServerConfigurationInformation cannot be null");
    }

    if (serverContextInformation == null) {
      throw new IllegalArgumentException("ServerContextInformation cannot be null");
    }

    this.serverConfigurationInformation = serverConfigurationInformation;
    this.serverContextInformation = serverContextInformation;
    /* If no system property for the JMX agent is specified from outside, use a default one
    to show all MBeans (including the Axis2-MBeans) within the Synapse tree */
    if (System.getProperty(JMX_AGENT_NAME) == null) {
      System.setProperty(JMX_AGENT_NAME, "org.apache.synapse");
    }

    if (serverContextInformation.getServerContext() == null
        || serverConfigurationInformation.isCreateNewInstance()) {

      if (log.isDebugEnabled()) {
        log.debug("Initializing Synapse in a new axis2 server environment instance");
      }
      createNewInstance(serverConfigurationInformation);
    } else {
      Object context = serverContextInformation.getServerContext();
      if (context instanceof ConfigurationContext) {
        if (log.isDebugEnabled()) {
          log.debug(
              "Initializing Synapse in an already existing " + "axis2 server environment instance");
        }
        configurationContext = (ConfigurationContext) context;
        configurationContext.setProperty(AddressingConstants.ADDR_VALIDATE_ACTION, Boolean.FALSE);
      } else {
        handleFatal(
            "Synapse startup initialization failed : Provided server context is"
                + " invalid, expected an Axis2 ConfigurationContext instance");
      }
    }
    // set the configuration context
    serverContextInformation.setServerContext(configurationContext);

    // set the ServerContextInformation as a parameter
    Parameter serverContextParameter =
        new Parameter(SynapseConstants.SYNAPSE_SERVER_CTX_INFO, serverContextInformation);
    // set the ServerConfiguration as a parameter
    Parameter serverConfigParameter =
        new Parameter(SynapseConstants.SYNAPSE_SERVER_CONFIG_INFO, serverConfigurationInformation);
    try {
      configurationContext.getAxisConfiguration().addParameter(serverContextParameter);
      configurationContext.getAxisConfiguration().addParameter(serverConfigParameter);
    } catch (AxisFault ignored) {
      log.fatal("Error adding the parameter to the Axis Configuration");
    }

    // we retrieve these properties to initialize the task scheduler in the environment
    Object repo = serverContextInformation.getProperty(TaskConstants.TASK_DESCRIPTION_REPOSITORY);
    Object taskScheduler = serverContextInformation.getProperty(TaskConstants.TASK_SCHEDULER);

    if (repo != null && (repo instanceof TaskDescriptionRepository)) {
      this.taskDescriptionRepository = (TaskDescriptionRepository) repo;
    }

    if (taskScheduler != null && (taskScheduler instanceof TaskScheduler)) {
      this.taskScheduler = (TaskScheduler) taskScheduler;
    }

    addDefaultBuildersAndFormatters(configurationContext.getAxisConfiguration());
    initDataSourceHelper(serverContextInformation);
    initSharedSecretCallbackHandlerCache(serverContextInformation);
    initEnterpriseBeanstalkHolder(serverContextInformation);
    initialized = true;
  }
  @Test(groups = {"wso2.greg"})
  public void testPaginate() throws Exception {
    try {
      Registry gov = GovernanceUtils.getGovernanceUserRegistry(registry, "admin");
      // Should be load the governance artifact.
      GovernanceUtils.loadGovernanceArtifacts((UserRegistry) gov);
      addServices(gov);
      // Initialize the pagination context.
      // Top five services, sortBy name , and sort order descending.
      PaginationContext.init(0, 5, "DES", "overview_name", 100);
      WSRegistrySearchClient wsRegistrySearchClient = new WSRegistrySearchClient();
      // This should be execute to initialize the AttributeSearchService.
      ConfigurationContext configContext;
      String axis2Repo = FrameworkPathUtil.getSystemResourceLocation() + "client";
      String axis2Conf =
          FrameworkPathUtil.getSystemResourceLocation()
              + "axis2config"
              + File.separator
              + "axis2_client.xml";
      TestFrameworkUtils.setKeyStoreProperties(automationContext);
      configContext =
          ConfigurationContextFactory.createConfigurationContextFromFileSystem(
              axis2Repo, axis2Conf);
      configContext.setProperty(HTTPConstants.CONNECTION_TIMEOUT, TIME_OUT_VALUE);

      wsRegistrySearchClient.init(cookie, backendURL, configContext);

      //            wsRegistrySearchClient.authenticate(configContext, getServiceURL(),
      //                    automationContext.getContextTenant().getContextUser().getUserName(),
      //                    automationContext.getContextTenant().getContextUser().getPassword());

      // Initialize the GenericArtifactManager
      GenericArtifactManager artifactManager = new GenericArtifactManager(gov, "service");
      Map<String, List<String>> listMap = new HashMap<String, List<String>>();
      // Create the search attribute map
      listMap.put(
          "lcName",
          new ArrayList<String>() {
            {
              add("ServiceLifeCycle");
            }
          });
      listMap.put(
          "lcState",
          new ArrayList<String>() {
            {
              add("Development");
            }
          });
      // Find the results.
      GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
      assertTrue(genericArtifacts.length > 0, "No any service found");
      assertTrue(genericArtifacts.length == 5, "Filtered service count should be 5");
      assertTrue(
          genericArtifacts[0].getQName().getLocalPart().equals("FlightService9"),
          "filter results are not sorted");
      assertTrue(
          genericArtifacts[4].getQName().getLocalPart().equals("FlightService5"),
          "filter results are not sorted");
    } finally {
      PaginationContext.destroy();
    }
  }
Esempio n. 19
0
 /**
  * Set server to maintenace mode
  *
  * @throws AxisFault If an error occurs while getting the ConfigurationContext
  */
 public static void setServerInMaintenance() throws AxisFault {
   ConfigurationContext configCtx = CarbonConfigurationContextFactory.getConfigurationContext();
   configCtx.setProperty(CURRENT_SERVER_STATUS, STATUS_IN_MAINTENANCE);
 }