public PutMetricAlarmResponseType putMetricAlarm(PutMetricAlarmType request)
      throws CloudWatchException {
    PutMetricAlarmResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();

    try {
      // IAM Action Check
      checkActionPermission(PolicySpec.CLOUDWATCH_PUTMETRICALARM, ctx);

      final OwnerFullName ownerFullName = ctx.getUserFullName();
      final String accountId = ownerFullName.getAccountNumber();
      final Boolean actionsEnabled = validateActionsEnabled(request.getActionsEnabled(), true);
      final Map<String, String> dimensionMap =
          TransformationFunctions.DimensionsToMap.INSTANCE.apply(
              validateDimensions(request.getDimensions()));
      final Collection<String> alarmActions =
          validateActions(request.getAlarmActions(), dimensionMap, "AlarmActions");
      final String alarmDescription = validateAlarmDescription(request.getAlarmDescription());
      final String alarmName = validateAlarmName(request.getAlarmName(), true);
      final ComparisonOperator comparisonOperator =
          validateComparisonOperator(request.getComparisonOperator(), true);
      Integer evaluationPeriods = validateEvaluationPeriods(request.getEvaluationPeriods(), true);
      final Integer period = validatePeriod(request.getPeriod(), true);
      validatePeriodAndEvaluationPeriodsNotAcrossDays(period, evaluationPeriods);
      final Collection<String> insufficientDataActions =
          validateActions(
              request.getInsufficientDataActions(), dimensionMap, "InsufficientDataActions");
      final String metricName = validateMetricName(request.getMetricName(), true);
      final String namespace = validateNamespace(request.getNamespace(), true);
      final Collection<String> okActions =
          validateActions(request.getOkActions(), dimensionMap, "OKActions");
      final Statistic statistic = validateStatistic(request.getStatistic(), true);
      final Double threshold = validateThreshold(request.getThreshold(), true);
      final Units unit = validateUnits(request.getUnit(), true);
      if (AlarmManager.countMetricAlarms(accountId) >= 5000) {
        throw new LimitExceededException("The maximum limit of 5000 alarms would be exceeded.");
      }
      AlarmManager.putMetricAlarm(
          accountId,
          actionsEnabled,
          alarmActions,
          alarmDescription,
          alarmName,
          comparisonOperator,
          dimensionMap,
          evaluationPeriods,
          insufficientDataActions,
          metricName,
          getMetricTypeFromNamespace(namespace),
          namespace,
          okActions,
          period,
          statistic,
          threshold,
          unit);
    } catch (Exception ex) {
      handleException(ex);
    }
    return reply;
  }
  public PutMetricDataResponseType putMetricData(PutMetricDataType request)
      throws CloudWatchException {
    PutMetricDataResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();

    try {
      LOG.trace("put metric data called");
      // IAM Action Check
      checkActionPermission(PolicySpec.CLOUDWATCH_PUTMETRICDATA, ctx);

      final OwnerFullName ownerFullName = ctx.getUserFullName();
      final List<MetricDatum> metricData = validateMetricData(request.getMetricData());
      final String namespace = validateNamespace(request.getNamespace(), true);
      final Boolean isUserAccountAdmin =
          Principals.isSameUser(
              Principals.systemUser(), Wrappers.unwrap(Context.class, Contexts.lookup()).getUser());
      LOG.trace("Namespace=" + namespace);
      LOG.trace("metricData=" + metricData);
      MetricType metricType = getMetricTypeFromNamespace(namespace);
      if (metricType == MetricType.System && !isUserAccountAdmin) {
        throw new InvalidParameterValueException(
            "The value AWS/ for parameter Namespace is invalid.");
      }
      MetricDataQueue.getInstance()
          .insertMetricData(ownerFullName.getAccountNumber(), namespace, metricData, metricType);
    } catch (Exception ex) {
      handleException(ex);
    }
    return reply;
  }
  public DescribeAlarmsForMetricResponseType describeAlarmsForMetric(
      DescribeAlarmsForMetricType request) throws CloudWatchException {
    DescribeAlarmsForMetricResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();

    try {
      // IAM Action Check
      checkActionPermission(PolicySpec.CLOUDWATCH_DESCRIBEALARMSFORMETRIC, ctx);
      final OwnerFullName ownerFullName = ctx.getUserFullName();
      final String accountId = ownerFullName.getAccountNumber();
      final Map<String, String> dimensionMap =
          TransformationFunctions.DimensionsToMap.INSTANCE.apply(
              validateDimensions(request.getDimensions()));
      final String metricName = validateMetricName(request.getMetricName(), true);
      final String namespace = validateNamespace(request.getNamespace(), true);
      final Integer period = validatePeriod(request.getPeriod(), false);
      final Statistic statistic = validateStatistic(request.getStatistic(), false);
      final Units unit = validateUnits(request.getUnit(), true);
      Collection<AlarmEntity> results =
          AlarmManager.describeAlarmsForMetric(
              accountId, dimensionMap, metricName, namespace, period, statistic, unit);
      MetricAlarms metricAlarms = new MetricAlarms();
      metricAlarms.setMember(
          Lists.newArrayList(
              Collections2.<AlarmEntity, MetricAlarm>transform(
                  results, TransformationFunctions.AlarmEntityToMetricAlarm.INSTANCE)));
      reply.getDescribeAlarmsForMetricResult().setMetricAlarms(metricAlarms);
    } catch (Exception ex) {
      handleException(ex);
    }
    return reply;
  }
  public GetMetricStatisticsResponseType getMetricStatistics(GetMetricStatisticsType request)
      throws CloudWatchException {
    GetMetricStatisticsResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();
    try {
      // IAM Action Check
      checkActionPermission(PolicySpec.CLOUDWATCH_GETMETRICSTATISTICS, ctx);

      // TODO: parse statistics separately()?
      final OwnerFullName ownerFullName = ctx.getUserFullName();
      Statistics statistics = validateStatistics(request.getStatistics());
      final String namespace = validateNamespace(request.getNamespace(), true);
      final String metricName = validateMetricName(request.getMetricName(), true);
      final Date startTime =
          MetricManager.stripSeconds(validateStartTime(request.getStartTime(), true));
      final Date endTime = MetricManager.stripSeconds(validateEndTime(request.getEndTime(), true));
      final Integer period = validatePeriod(request.getPeriod(), true);
      validateDateOrder(startTime, endTime, "StartTime", "EndTime", true, true);
      validateNotTooManyDataPoints(startTime, endTime, period, 1440L);

      // TODO: null units here does not mean Units.NONE but basically a
      // wildcard.
      // Consider this case.
      final Units units = validateUnits(request.getUnit(), false);
      final Map<String, String> dimensionMap =
          TransformationFunctions.DimensionsToMap.INSTANCE.apply(
              validateDimensions(request.getDimensions()));
      Collection<MetricStatistics> metrics;
      metrics =
          MetricManager.getMetricStatistics(
              ownerFullName.getAccountNumber(),
              metricName,
              namespace,
              dimensionMap,
              getMetricTypeFromNamespace(namespace),
              units,
              startTime,
              endTime,
              period);
      reply.getGetMetricStatisticsResult().setLabel(metricName);
      ArrayList<Datapoint> datapoints = convertMetricStatisticsToDataoints(statistics, metrics);
      if (datapoints.size() > 0) {
        Datapoints datapointsReply = new Datapoints();
        datapointsReply.setMember(datapoints);
        reply.getGetMetricStatisticsResult().setDatapoints(datapointsReply);
      }
    } catch (Exception ex) {
      handleException(ex);
    }
    return reply;
  }
  public ListMetricsResponseType listMetrics(ListMetricsType request) throws CloudWatchException {
    ListMetricsResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();

    try {
      // IAM Action Check
      checkActionPermission(PolicySpec.CLOUDWATCH_LISTMETRICS, ctx);

      final OwnerFullName ownerFullName = ctx.getUserFullName();
      final String namespace = validateNamespace(request.getNamespace(), false);
      final String metricName = validateMetricName(request.getMetricName(), false);
      final Map<String, String> dimensionMap =
          TransformationFunctions.DimensionFiltersToMap.INSTANCE.apply(
              validateDimensionFilters(request.getDimensions()));

      // take all stats updated after two weeks ago
      final Date after = new Date(System.currentTimeMillis() - 2 * 7 * 24 * 60 * 60 * 1000L);
      final Date before = null; // no bound on time before stats are updated
      // (though maybe 'now')
      final Integer maxRecords = 500; // per the API docs
      final String nextToken = request.getNextToken();
      final List<ListMetric> results =
          ListMetricManager.listMetrics(
              ownerFullName.getAccountNumber(),
              metricName,
              namespace,
              dimensionMap,
              after,
              before,
              maxRecords,
              nextToken);

      final Metrics metrics = new Metrics();
      metrics.setMember(
          Lists.newArrayList(
              Collections2.<ListMetric, Metric>transform(
                  results, TransformationFunctions.ListMetricToMetric.INSTANCE)));
      final ListMetricsResult listMetricsResult = new ListMetricsResult();
      listMetricsResult.setMetrics(metrics);
      if (maxRecords != null && results.size() == maxRecords) {
        listMetricsResult.setNextToken(results.get(results.size() - 1).getNaturalId());
      }
      reply.setListMetricsResult(listMetricsResult);
    } catch (Exception ex) {
      handleException(ex);
    }
    return reply;
  }
 static void createDefault(final OwnerFullName ownerFullName) throws MetadataException {
   try {
     try {
       NetworkGroup net =
           Transactions.find(
               new NetworkGroup(
                   AccountFullName.getInstance(ownerFullName.getAccountNumber()),
                   NETWORK_DEFAULT_NAME));
       if (net == null) {
         create(ownerFullName, NETWORK_DEFAULT_NAME, "default group");
       }
     } catch (NoSuchElementException ex) {
       try {
         create(ownerFullName, NETWORK_DEFAULT_NAME, "default group");
       } catch (ConstraintViolationException ex1) {
       }
     } catch (TransactionException ex) {
       try {
         create(ownerFullName, NETWORK_DEFAULT_NAME, "default group");
       } catch (ConstraintViolationException ex1) {
       }
     }
   } catch (DuplicateMetadataException ex) {
   }
 }
  public DisableAlarmActionsResponseType disableAlarmActions(DisableAlarmActionsType request)
      throws EucalyptusCloudException {
    DisableAlarmActionsResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();

    try {
      // IAM Action Check
      checkActionPermission(PolicySpec.CLOUDWATCH_DISABLEALARMACTIONS, ctx);
      final OwnerFullName ownerFullName = ctx.getUserFullName();
      final String accountId = ownerFullName.getAccountNumber();
      Collection<String> alarmNames = validateAlarmNames(request.getAlarmNames(), true);
      AlarmManager.disableAlarmActions(accountId, alarmNames);
    } catch (Exception ex) {
      handleException(ex);
    }
    return reply;
  }
Beispiel #8
0
 private void fireUsageEvent(
     final OwnerFullName ownerFullName,
     final Supplier<EventActionInfo<AddressAction>> actionInfoSupplier) {
   if (!Principals.isFakeIdentityAccountNumber(ownerFullName.getAccountNumber())) {
     try {
       ListenerRegistry.getInstance()
           .fireEvent(
               AddressEvent.with(
                   getNaturalId(),
                   getDisplayName(),
                   ownerFullName,
                   Accounts.lookupAccountById(ownerFullName.getAccountNumber()).getName(),
                   actionInfoSupplier.get()));
     } catch (final Exception e) {
       LOG.error(e, e);
     }
   }
 }
  public DescribeAlarmsResponseType describeAlarms(DescribeAlarmsType request)
      throws CloudWatchException {
    DescribeAlarmsResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();

    try {
      // IAM Action Check
      checkActionPermission(PolicySpec.CLOUDWATCH_DESCRIBEALARMS, ctx);

      final OwnerFullName ownerFullName = ctx.getUserFullName();
      final String accountId = ownerFullName.getAccountNumber();
      final String actionPrefix = validateActionPrefix(request.getActionPrefix(), false);
      final String alarmNamePrefix = validateAlarmNamePrefix(request.getAlarmNamePrefix(), false);
      final Collection<String> alarmNames = validateAlarmNames(request.getAlarmNames(), false);
      validateNotBothAlarmNamesAndAlarmNamePrefix(alarmNames, alarmNamePrefix);
      final Integer maxRecords = validateMaxRecords(request.getMaxRecords());
      final String nextToken = request.getNextToken();
      final StateValue stateValue = validateStateValue(request.getStateValue(), false);
      List<AlarmEntity> results =
          AlarmManager.describeAlarms(
              accountId,
              actionPrefix,
              alarmNamePrefix,
              alarmNames,
              maxRecords,
              stateValue,
              nextToken);
      if (maxRecords != null && results.size() == maxRecords) {
        reply
            .getDescribeAlarmsResult()
            .setNextToken(results.get(results.size() - 1).getNaturalId());
      }
      MetricAlarms metricAlarms = new MetricAlarms();
      metricAlarms.setMember(
          Lists.newArrayList(
              Collections2.<AlarmEntity, MetricAlarm>transform(
                  results, TransformationFunctions.AlarmEntityToMetricAlarm.INSTANCE)));
      reply.getDescribeAlarmsResult().setMetricAlarms(metricAlarms);
    } catch (Exception ex) {
      handleException(ex);
    }
    return reply;
  }
  public SetAlarmStateResponseType setAlarmState(SetAlarmStateType request)
      throws CloudWatchException {
    SetAlarmStateResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();
    try {

      // IAM Action Check
      checkActionPermission(PolicySpec.CLOUDWATCH_SETALARMSTATE, ctx);
      final OwnerFullName ownerFullName = ctx.getUserFullName();
      final String accountId = ownerFullName.getAccountNumber();
      final String alarmName = validateAlarmName(request.getAlarmName(), true);
      final String stateReason = validateStateReason(request.getStateReason(), true);
      final String stateReasonData = validateStateReasonData(request.getStateReasonData(), false);
      final StateValue stateValue = validateStateValue(request.getStateValue(), true);
      AlarmManager.setAlarmState(accountId, alarmName, stateReason, stateReasonData, stateValue);
    } catch (Exception ex) {
      handleException(ex);
    }
    return reply;
  }
  public DescribeAlarmHistoryResponseType describeAlarmHistory(DescribeAlarmHistoryType request)
      throws CloudWatchException {
    DescribeAlarmHistoryResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();

    try {
      // IAM Action Check
      checkActionPermission(PolicySpec.CLOUDWATCH_DESCRIBEALARMHISTORY, ctx);

      final OwnerFullName ownerFullName = ctx.getUserFullName();
      final String accountId = ownerFullName.getAccountNumber();
      final String alarmName = validateAlarmName(request.getAlarmName(), false);
      final Date endDate = validateEndDate(request.getEndDate(), false);
      final Date startDate = validateStartDate(request.getStartDate(), false);
      validateDateOrder(startDate, endDate, "StartDate", "EndDate", false, false);
      final HistoryItemType historyItemType =
          validateHistoryItemType(request.getHistoryItemType(), false);
      final Integer maxRecords = validateMaxRecords(request.getMaxRecords());
      final String nextToken = request.getNextToken();
      List<AlarmHistory> results =
          AlarmManager.describeAlarmHistory(
              accountId, alarmName, endDate, historyItemType, maxRecords, startDate, nextToken);
      if (maxRecords != null && results.size() == maxRecords) {
        reply
            .getDescribeAlarmHistoryResult()
            .setNextToken(results.get(results.size() - 1).getNaturalId());
      }
      AlarmHistoryItems alarmHistoryItems = new AlarmHistoryItems();
      alarmHistoryItems.setMember(
          Lists.newArrayList(
              Collections2.<AlarmHistory, AlarmHistoryItem>transform(
                  results, TransformationFunctions.AlarmHistoryToAlarmHistoryItem.INSTANCE)));
      reply.getDescribeAlarmHistoryResult().setAlarmHistoryItems(alarmHistoryItems);
    } catch (Exception ex) {
      handleException(ex);
    }
    return reply;
  }
  public static NetworkGroup create(
      final OwnerFullName ownerFullName, final String groupName, final String groupDescription)
      throws MetadataException {
    UserFullName userFullName = null;
    if (ownerFullName instanceof UserFullName) {
      userFullName = (UserFullName) ownerFullName;
    } else {
      try {
        Account account = Accounts.lookupAccountById(ownerFullName.getAccountNumber());
        User admin =
            Iterables.find(
                account.getUsers(),
                new Predicate<User>() {

                  @Override
                  public boolean apply(User input) {
                    return input.isAccountAdmin();
                  }
                });
        userFullName = UserFullName.getInstance(admin);
      } catch (Exception ex) {
        LOG.error(ex, ex);
        throw new NoSuchMetadataException(
            "Failed to create group because owning user could not be identified.", ex);
      }
    }

    final EntityTransaction db = Entities.get(NetworkGroup.class);
    try {
      NetworkGroup net =
          Entities.uniqueResult(
              new NetworkGroup(
                  AccountFullName.getInstance(userFullName.getAccountNumber()), groupName));
      if (net == null) {
        final NetworkGroup entity =
            Entities.persist(new NetworkGroup(userFullName, groupName, groupDescription));
        db.commit();
        return entity;
      } else {
        db.rollback();
        throw new DuplicateMetadataException(
            "Failed to create group: " + groupName + " for " + userFullName.toString());
      }
    } catch (final NoSuchElementException ex) {
      final NetworkGroup entity =
          Entities.persist(new NetworkGroup(userFullName, groupName, groupDescription));
      db.commit();
      return entity;
    } catch (final ConstraintViolationException ex) {
      Logs.exhaust().error(ex);
      db.rollback();
      throw new DuplicateMetadataException(
          "Failed to create group: " + groupName + " for " + userFullName.toString(), ex);
    } catch (final Exception ex) {
      Logs.exhaust().error(ex, ex);
      db.rollback();
      throw new MetadataException(
          "Failed to create group: " + groupName + " for " + userFullName.toString(),
          PersistenceExceptions.transform(ex));
    }
  }