LimitsCheckingWorkspaceManager extends WorkspaceManager { @VisibleForTesting void checkMaxEnvironmentRam(WorkspaceConfig config) throws ServerException { if (maxRamPerEnvMB < 0) { return; } if (config.getEnvironments().isEmpty()) { return; } for (Map.Entry<String, ? extends Environment> envEntry : config.getEnvironments().entrySet()) { Environment env = envEntry.getValue(); final long workspaceRam = environmentRamCalculator.calculate(env); if (workspaceRam > maxRamPerEnvMB) { throw new LimitExceededException( format("You are only allowed to use %d mb. RAM per workspace.", maxRamPerEnvMB), ImmutableMap.of( "environment_max_ram", Long.toString(maxRamPerEnvMB), "environment_max_ram_unit", "mb", "environment_ram", Long.toString(workspaceRam), "environment_ram_unit", "mb")); } } } @Inject  LimitsCheckingWorkspaceManager(
      WorkspaceDao workspaceDao,
      WorkspaceRuntimes runtimes,
      EventService eventService,
      AccountManager accountManager,
      PreferenceManager preferenceManager,
      WorkspaceValidator workspaceValidator,
      // own injects
      @Named("che.limits.workspace.env.ram") String maxRamPerEnv,
      EnvironmentRamCalculator environmentRamCalculator,
      ResourceManager resourceManager,
      ResourcesLocks resourcesLocks,
      DevfileIntegrityValidator devfileIntegrityValidator); @Override @Traced WorkspaceImpl createWorkspace(
      WorkspaceConfig config, String namespace, @Nullable Map<String, String> attributes); @Override WorkspaceImpl startWorkspace(
      String workspaceId, @Nullable String envName, @Nullable Map<String, String> options); @Override WorkspaceImpl startWorkspace(
      WorkspaceConfig config, String namespace, boolean isTemporary, Map<String, String> options); @Override WorkspaceImpl updateWorkspace(String id, Workspace update);  }
@Test( expectedExceptions = LimitExceededException.class, expectedExceptionsMessageRegExp = "You are only allowed to use 2048 mb. RAM per workspace.") public void shouldNotBeAbleToCreateWorkspaceWhichExceedsRamLimit() throws Exception { when(environmentRamCalculator.calculate(any(Environment.class))).thenReturn(3072L); final WorkspaceConfig config = createConfig("3gb"); final LimitsCheckingWorkspaceManager manager = managerBuilder() .setMaxRamPerEnv("2gb") .setEnvironmentRamCalculator(environmentRamCalculator) .build(); manager.checkMaxEnvironmentRam(config); }
@Test public void shouldNotCheckWorkspaceRamLimitIfItIsSetToMinusOne() throws Exception { final WorkspaceConfig config = createConfig("3gb"); final LimitsCheckingWorkspaceManager manager = managerBuilder() .setMaxRamPerEnv("-1") .setEnvironmentRamCalculator(environmentRamCalculator) .build(); manager.checkMaxEnvironmentRam(config); verify(environmentRamCalculator, never()).calculate(any(Environment.class)); }