Retire monasca-common repository

This repository is being retired as part of the Monasca project
retirement. The project content has been replaced with a retirement
notice.

Needed-By: I3cb522ce8f51424b64e93c1efaf0dfd1781cd5ac
Change-Id: I920e9712c72fbeb2be74590ee3beb3b8051b20a6
Signed-off-by: Goutham Pacha Ravi <gouthampravi@gmail.com>
This commit is contained in:
Goutham Pacha Ravi
2025-08-11 22:15:30 -07:00
parent 7f254364a0
commit eabf4150dc
272 changed files with 7 additions and 25405 deletions

View File

@@ -1,7 +0,0 @@
[run]
branch = True
source = monasca_common
omit = monasca_common/tests/*
[report]
ignore_errors = True

View File

@@ -1,4 +0,0 @@
[DEFAULT]
test_path=${OS_TEST_PATH:-./monasca_common/tests}
top_dir=./
group_regex=monasca_common\.tests(?:\.|_)([^_]+)

View File

@@ -1,103 +0,0 @@
- project:
queue: monasca
templates:
- check-requirements
- openstack-cover-jobs
- openstack-python3-jobs
check:
jobs:
- monasca-tempest-python3-influxdb:
voting: false
- monasca-tempest-python3-cassandra:
voting: false
- monasca-common-maven-build:
voting: false
- build-monasca-common-docker-base-image:
voting: false
gate:
jobs:
- monasca-tempest-python3-influxdb:
voting: false
- monasca-common-maven-build
post:
jobs:
- publish-monasca-common-docker-base-image
- monasca-common-localrepo-upload
periodic:
jobs:
- publish-monasca-common-docker-base-image
release:
jobs:
- publish-monasca-common-docker-base-image
- job:
name: monasca-common-localrepo-upload
parent: legacy-publish-openstack-artifacts
run: playbooks/legacy/monasca-common-localrepo-upload/run.yaml
post-run: playbooks/legacy/monasca-common-localrepo-upload/post.yaml
timeout: 1800
- job:
name: monasca-common-maven-build
parent: legacy-base
run: playbooks/legacy/monasca-common-maven-build/run.yaml
timeout: 1800
- job:
name: build-monasca-common-docker-base-image
run: playbooks/docker_build_base.yml
required-projects:
- openstack/monasca-common
attempts: 1
irrelevant-files:
- ^.*\.rst$
- ^.*\.md$
- ^doc/.*$
- job:
name: build-monasca-docker-image
run: playbooks/docker_build_service.yml
required-projects:
- openstack/monasca-common
attempts: 1
irrelevant-files:
- ^.*\.rst$
- ^.*\.md$
- ^doc/.*$
- job:
name: publish-monasca-common-docker-base-image
parent: build-monasca-common-docker-base-image
post-run: playbooks/publish.yml
required-projects:
- openstack/monasca-common
vars:
publisher: true
secrets:
- doker_hub_login
- secret:
name: doker_hub_login
data:
user: !encrypted/pkcs1-oaep
- j009sQOrpIAhTBhYHjmjcZNuZlb+mIAHT4rMzo0qAsruGhTAsL1AgHvkm/FLLtK9mT6w3
dAlHGC1Bba9n+H3INpkZbcNm0B2+PwIfjbB77lEcN/1D3XrXKje9S5IH3lWbBU+m4YIz0
+EsqkgciFXiFytW9dTT2oT58vu7TlD9N983UqoJ89Z5jxoSdbquR22er2oX0txb1XNIrC
M/7heQ/cigQtB9b04yEozhAUnZjFOPviCPv3R4aqbj5nmZ1w2UGc6HhZX0X0G4BRKlC+0
T6wYWbPgYMsdNlTnJqcji3IArbQeT89dY5Dcp5XbpYHd9U3h6wdSfcRihmCVF5bSdfzMW
E787kg0q81iFWPcCzbeQCsJexZ3osT7uoow/j4ddshbbQxM6aLRmK56prCXNTxFebSQJh
oqux2V7G+U9KCDya7dWe7Id3oMV0hxLIZI615evEtrzjjnsCVFRiOEn5AZdyfKe6uFxeD
fjTlM3y9gNpYV2wEcxm2+q8H9xCwlwA1IwZ+rTjCN1NJ53ded+Vs7CUpvkOlFEYMAUD4f
aHCyT9mPBDzVBw7TSqJTM6wn+LKkiV87b8QDFcYFZZT4aoIWNLU2dyS5Dk/qc0c3WUNxO
vQybCmnG2qIVh+Y4k/FNnPi0BvIyf9d78CEg5ZSTlG517zeqmohKybW3ynlYBM=
password: !encrypted/pkcs1-oaep
- Bvz5Lf62vqtUfneRd9IcZ+HcR3PG5r0xNk1aWRNVlJ+T4NSoLE9wQe3HLLkKIBG9pYIJN
60x+2EziPVYFrwMJloqOiuKHZmifjbYeNTK/FOlMHXxcQACYMc67ZDZO5VtIWtiCzM0aR
iN8f5n/kfVa0rPeHnKbabUd4XuTZv0PltT+GyYsLAcM+QqQcfWuYhx4ahiFMF+bpLMUEj
kJIFSKu7sk+6XHR6P5ppiUNl/yZzDztezkWS6HGGVaP0nV7nNaOd2hFIwl64iS4er1M6I
mc3XdOF1xJyU7IFrVsBlP8LYFS69wlSq3EuUoPYkR/7nk9cTKqmvXo/lThR7Yv9ZTbHxq
5pMAmURMQCVwZYDTDv6E1uQMhrGZliVjEsDmIpBG0Om61IpvEWIHm0WiS7OMG/e98IUOD
fhyjDMo9IzlsuilWH8xSwfh8f+UHaAwOF60bXEs9b2Zowwzvbi++AwtGbhoaidzaA1e6t
27YDErM/Ll8uawY+sLxO2JpE0AQM93lXVQmMg5npN0dlgIkCSohxCRlkiRrZ1DWx80ZiC
3nzYnRYQav/cRLp8mhVTLoLrBI5edu8uRw8kfMQWAbFpxvaCVwiii78izJsmJPmPelczS
YNZV98I1+pV7KW0PUS5EArkBCWDHLSZT4v4E8m4RfcXMlK7nWUQdN49sWDZg8A=

View File

@@ -1,19 +0,0 @@
The source repository for this project can be found at:
https://opendev.org/openstack/monasca-common
Pull requests submitted through GitHub are not monitored.
To start contributing to OpenStack, follow the steps in the contribution guide
to set up and use Gerrit:
https://docs.openstack.org/contributors/code-and-documentation/quick-start.html
Bugs should be filed on Storyboard:
https://storyboard.openstack.org/#!/project/865
For more specific information about contributing to this repository, see the
Monasca contributor guide:
https://docs.openstack.org/monasca-api/latest/contributor/contributing.html

View File

@@ -1,4 +0,0 @@
monasca_common Style Commandments
==================================
Read the OpenStack Style Commandments https://docs.openstack.org/hacking/latest/

View File

@@ -1,107 +1,9 @@
==============
monasca-common
==============
This project is no longer maintained.
.. image:: https://governance.openstack.org/tc/badges/monasca-common.svg
The contents of this repository are still available in the Git
source code management system. To see the contents of this
repository before it reached its end of life, please check out the
previous commit with "git checkout HEAD^1".
.. Change things from this point on
``monasca-common`` is a collection of modules containing reusable application
and platform code for building monitoring related services.
Python
======
To install the Python monasca-common modules, git clone the source and
run the following command:
::
$ sudo python setup.py install
To run the unit tests use:
::
$ tox -e py3
For information on contributing, see `Contribution Guidelines`_.
* License: Apache License, Version 2.0
* Source: https://opendev.org/openstack/monasca-common
* Bugs: https://storyboard.openstack.org/#!/project/865
.. _`Contribution Guidelines`: https://docs.openstack.org/monasca-api/latest/contributor/index.html
Java
====
Build Instructions
~~~~~~~~~~~~~~~~~~
Download and do mvn install.
::
$ cd java
$ mvn clean install
.. caution::
There is a pom.xml in the base directory but that should only be used
for the Zuul build.
The issue is that currently StackForges bare-precise system only has Maven 2
on it and at least one of the modules of monasca-common requires Maven 3.
In order to get around this problem, the pom.xml in the base directory
uses the exec-maven-plugin to run the script run_maven.sh. This script
checks if the version of mvn is Maven 3 and if it is not, it downloads
Maven 3 and then uses it to run the build in the java directory.
In addition, the run_maven.sh script copies the jar files that get built
from java/``*``/target directories to the target directory in the base
project directory. This is because the StackForge
“monasca-common-localrepo-upload” job uploads any jar files from that
directory to https://tarballs.opendev.org/openstack/ci/monasca-common.
Copying the jar files to that directory made it so there didnt have to
be changes made to the “monasca-common-localrepo-upload” job. The build
for monasca-thresh downloads the jars it depends on from that location on
tarballs.openstack.org.
A change has been submitted to StackForge to switch to bare-trusty for
this build in the hopes that those systems will have maven 3, but it is
not known how long that change will take to be accepted.
Application Specific Sub-Projects
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- `monasca-common-model`_ - Common domain and event models for
monitoring services.
Platform Sub-Projects
~~~~~~~~~~~~~~~~~~~~~
- `monasca-common-dropwizard`_ - Utilities for building and testing
dropwizard services.
- `monasca-common-hibernate`_ - Hibernate based model of Monasca SQL
schema
- `monasca-common-influxdb`_ - InfluxDB related utilities.
- `monasca-common-kafka`_ - Various utilities for working with Kafka.
- `monasca-common-persistence`_ - Persistence related infrastructure
and utilities.
- `monasca-common-streaming`_ - Streaming related utilities.
- `monasca-common-testing`_ - A set of testing related dependencies.
- `monasca-common-util`_ - Various utilities such as for serialization,
dependency injection, date and time, invocation retries, concurrency,
etc.
.. _monasca-common-model: https://opendev.org/openstack/monasca-common/src/branch/master/java/monasca-common-model
.. _monasca-common-dropwizard: https://opendev.org/openstack/monasca-common/src/branch/master/java/monasca-common-dropwizard
.. _monasca-common-hibernate: https://opendev.org/openstack/monasca-common/src/branch/master/java/monasca-common-hibernate
.. _monasca-common-influxdb: https://opendev.org/openstack/monasca-common/src/branch/master/java/monasca-common-influxdb
.. _monasca-common-kafka: https://opendev.org/openstack/monasca-common/src/branch/master/java/monasca-common-kafka
.. _monasca-common-persistence: https://opendev.org/openstack/monasca-common/src/branch/master/java/monasca-common-persistence
.. _monasca-common-streaming: https://opendev.org/openstack/monasca-common/src/branch/master/java/monasca-common-streaming
.. _monasca-common-testing: https://opendev.org/openstack/monasca-common/src/branch/master/java/monasca-common-testing
.. _monasca-common-util: https://opendev.org/openstack/monasca-common/src/branch/master/java/monasca-common-util
For any further questions, please email openstack-discuss@lists.openstack.org
or join #openstack-dev on OFTC.

View File

@@ -1,5 +0,0 @@
# This is is a cross-platform list tracking distribution packages needed for install and tests;
# see http://docs.openstack.org/infra/bindep/ for additional information.
maven
openjdk-8-jdk

View File

@@ -1,181 +0,0 @@
FROM python:3.10-alpine3.19
COPY wait_for.sh kafka_wait_for_topics.py mysql_check.py /
COPY ashrc /root/.ashrc
ENV \
ENV="/root/.ashrc" \
PIP_NO_CACHE_DIR="no" \
PIP_NO_COMPILE="no" \
PYTHONIOENCODING="utf-8"
ARG BASE_CREATION_TIME
ARG BASE_GIT_COMMIT
LABEL \
org.opencontainers.image.created="$BASE_CREATION_TIME" \
org.opencontainers.image.title="monasca-base" \
org.opencontainers.image.revision="$BASE_GIT_COMMIT" \
org.opencontainers.image.licenses="Apache-2.0"
RUN \
chmod +x /wait_for.sh /kafka_wait_for_topics.py /mysql_check.py && \
apk add --no-cache \
su-exec \
tini \
# We need this to allow users choose different time zone.
tzdata && \
printf "Monasca base build date: %s\\n" $BASE_CREATION_TIME >> /VERSIONS && \
printf "Monasca base revision: %s\\n" $BASE_GIT_COMMIT >> /VERSIONS && \
# Cleaning.
rm -rf /var/cache/apk/* && \
rm -rf /var/log/* && \
rm -rf /tmp/*
# Get values from child images
ONBUILD ARG CREATION_TIME
ONBUILD ARG DOCKER_IMAGE
ONBUILD ARG APP_REPO
ONBUILD ARG GITHUB_REPO
ONBUILD ARG REPO_VERSION
ONBUILD ARG GIT_COMMIT
ONBUILD ARG CONSTRAINTS_FILE
ONBUILD ARG EXTRA_DEPS
ONBUILD ARG COMMON_REPO
ONBUILD ARG COMMON_VERSION
ONBUILD ARG COMMON_GIT_COMMIT
# Build-time metadata as defined at
# https://github.com/opencontainers/image-spec/blob/master/annotations.md
ONBUILD LABEL \
org.opencontainers.image.created="$CREATION_TIME" \
org.opencontainers.image.title="$DOCKER_IMAGE" \
org.opencontainers.image.source="$APP_REPO" \
org.opencontainers.image.url="$GITHUB_REPO" \
org.opencontainers.image.version="$REPO_VERSION" \
org.opencontainers.image.revision="$GIT_COMMIT" \
org.opencontainers.image.licenses="Apache-2.0" \
org.openstack.constraints_uri="$CONSTRAINTS_FILE" \
org.openstack.monasca.python.extra_deps="$EXTRA_DEPS" \
org.openstack.monasca.common.source="$COMMON_REPO" \
org.openstack.monasca.common.version="$COMMON_VERSION" \
org.openstack.monasca.common.revision="$COMMON_GIT_COMMIT"
# Every child image need to provide starting and health check script.
# If they're not provided build will fail. We want that for uniformity.
ONBUILD COPY start.sh health_check.py /
ONBUILD WORKDIR /
ONBUILD SHELL ["/bin/ash", "-eo", "pipefail", "-c"]
ONBUILD RUN \
chmod +x /start.sh && \
apk add --no-cache --virtual .build-deps \
cairo \
g++ \
git \
libffi-dev \
openssl-dev \
libxml2-dev \
libxslt-dev \
linux-headers \
make \
rust && \
# For librdkafka bigger than v2.3.0 we need newer versions of some
# libraries.
apk add --no-cache --virtual .build-librdkafka \
--repository=http://dl-cdn.alpinelinux.org/alpine/edge/main \
--repository=http://dl-cdn.alpinelinux.org/alpine/edge/community && \
# Install librdkafka from source code.
apk add --no-cache curl bash && \
curl https://codeload.github.com/edenhill/librdkafka/tar.gz/v2.8.0 | tar xzf - -C /tmp/ && \
cd /tmp/librdkafka-2.8.0/ && \
./configure && \
make && \
make install && \
# Clone repository and checkout requested version.
# This many steps are needed to support gerrit patch sets.
mkdir -p /app && \
git -C /app init && \
git -C /app remote add origin "$APP_REPO" && \
echo "Cloning app in version: $REPO_VERSION" && \
git -C /app fetch origin "$REPO_VERSION" && \
git -C /app reset --hard FETCH_HEAD && \
wget --output-document /app/upper-constraints.txt \
"$CONSTRAINTS_FILE" && \
# Download monasca-common
mkdir -p /monasca-common && \
git -C /monasca-common init && \
git -C /monasca-common remote add origin "$COMMON_REPO" && \
echo "Cloning monasca-common in version: $COMMON_VERSION" && \
git -C /monasca-common fetch origin "$COMMON_VERSION" && \
git -C /monasca-common reset --hard FETCH_HEAD && \
# When creating image from master, stable branch or commit use
# monasca-common from git repository in /monasca-common,
# otherwise use the version from upper-constraints.txt
[ ! "$(git -C /monasca-common tag -l ${COMMON_VERSION})" ] && \
sed -i "s|monasca-common.*||" \
/app/requirements.txt || true && \
[ ! "$(git -C /monasca-common tag -l ${COMMON_VERSION})" ] && \
sed -i "s|monasca-common.*||" \
/app/upper-constraints.txt || true && \
[ $DOCKER_IMAGE = "monasca/client" ] && \
sed -i "s|python-monascaclient.*||" \
/app/upper-constraints.txt || true && \
[ $DOCKER_IMAGE = "monasca/statsd" ] && \
sed -i "s|monasca-statsd.*||" \
/app/upper-constraints.txt || true && \
pip3 install \
--editable /monasca-common \
--constraint /app/upper-constraints.txt && \
# Install packages needed by wait scripts and used for templating.
pip3 install \
pykafka \
PyMySQL \
Templer==1.1.4 \
--constraint /app/upper-constraints.txt && \
# Install our application with extra dependencies if provided.
pip3 install \
/app/. $EXTRA_DEPS \
--requirement /app/requirements.txt \
--constraint /app/upper-constraints.txt && \
# Save info about build to `/VERSIONS` file.
printf "App: %s\\n" "$DOCKER_IMAGE" >> /VERSIONS && \
printf "Repository: %s\\n" "$APP_REPO" >> /VERSIONS && \
printf "Version: %s\\n" "$REPO_VERSION" >> /VERSIONS && \
printf "Revision: %s\\n" "$GIT_COMMIT" >> /VERSIONS && \
printf "Build date: %s\\n" "$CREATION_TIME" >> /VERSIONS && \
printf "Revision: %s\\n" \
"$(git -C /app rev-parse FETCH_HEAD)" >> /VERSIONS && \
printf "Monasca-common version: %s\\n" "$COMMON_VERSION" \
>> /VERSIONS && \
printf "Monasca-common pip version: %s\\n" \
"$(pip3 freeze 2>&1 | grep 'monasca-common')" >> /VERSIONS && \
printf "Monasca-common revision: %s\\n" \
"$COMMON_GIT_COMMIT" >> /VERSIONS && \
printf "Constraints file: %s\\n" \
"$CONSTRAINTS_FILE" >> /VERSIONS && \
# Clean after instalation.
apk del .build-deps .build-librdkafka && \
rm -rf \
/app \
/root/.cache/ \
/monasca-common/java/ \
/tmp/* \
/var/cache/apk/* \
/var/log/* && \
# Remove all Python pyc and pyo files. Don't remove tempest tests.
find /usr/local -depth \
\( \
\( -type d -and \( \
-name test -or -name tests \
-not -path '*/monasca_tempest_tests/*' \) \) \
-or \
\( -type f -and \( \
-name '*.pyc' -or -name '*.pyo' \) \) \
\) -exec rm -rf '{}' +
ONBUILD HEALTHCHECK --interval=5s --timeout=2s \
CMD python3 health_check.py || exit 1
ENTRYPOINT ["/sbin/tini", "-s", "--"]

View File

@@ -1,78 +0,0 @@
======================================
Docker base image for Monasca services
======================================
This image is used as a starting point for images of all Monasca services.
Building monasca-base image
===========================
You need to have Docker installed (minimum tested version is ``17.09``).
Then you can build image inside of this folder by running:
``docker build --no-cache -t monasca-base:1.0.0 .``
Building child image
--------------------
In the ``example`` folder you can find samples of how to start building
new child image using ``monasca-base``.
Requirements
~~~~~~~~~~~~
Every child image has to provide two files:
start.sh
In this starting script provide all steps that lead to the proper service
start. Including usage of wait scripts and templating of configuration files.
You also could provide the ability to allow running container after service
died for easier debugging.
health_check.py
This file will be used for checking the status of the application running in
the container. It should be used to inform Docker that service is operating
and healthy. It will be useful for container orchestration like Kubernetes
or Docker Swarm to properly handle services that are still running but
stopped being responsive. Avoid using `curl` directly and instead, use
`health_check.py` written with specific service in mind. It will provide more
flexibility like when creating JSON request body.
Wait scripts
------------
Some Python libraries are already pre-installed: `pykafka` and `PyMySQL`. They
are used by wait scripts and in the process of creating the child image `pip3`
will reinstall them to use proper versions confronting the upper constraints
file.
These wait scripts will be available in every child image and can be used in
`start.sh` to avoid unnecessary errors and restarts of containers when they
are started.
::
python3 /kafka_wait_for_topics.py || exit 1
python3 /mysql_check.py || exit 1
/wait_for.sh 192.168.10.6:5000 || exit 1
Please, check the content of each of these files for documentation of what
environment variables are used and more usage examples.
Useful commands
---------------
List all labels of the image (you need to have ``jq`` installed):
``docker inspect monasca-api:master | jq .[].Config.Labels``
Get all steps of the Docker image build process history:
::
docker history --no-trunc <IMAGE_ID>
docker history --no-trunc monasca-base:1.0.0

View File

@@ -1,5 +0,0 @@
alias ll="ls -alp"
# Print versions on login to the container.
cat /VERSIONS
echo

View File

@@ -1,19 +0,0 @@
#!/bin/bash
set -x # Print each script step.
set -eo pipefail # Exit the script if any statement returns error.
REAL_PATH=$(python3 -c "import os,sys;print(os.path.realpath('$0'))")
cd "$(dirname "$REAL_PATH")/../docker/"
BASE_GIT_COMMIT=$(git rev-parse --verify HEAD)
[ -z "${BASE_GIT_COMMIT}" ] && echo "No git commit hash found" && exit 1
BASE_CREATION_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
: "${MONASCA_COMMON_TAG:="master"}"
docker build --no-cache \
--build-arg BASE_CREATION_TIME="$BASE_CREATION_TIME" \
--build-arg BASE_GIT_COMMIT="$BASE_GIT_COMMIT" \
--tag monasca/base:"$MONASCA_COMMON_TAG" .

View File

@@ -1,42 +0,0 @@
# Example Dockerfile for creating Docker image.
ARG DOCKER_IMAGE=monasca-api
ARG APP_REPO=https://review.opendev.org/openstack/monasca-api
# Branch, tag or git hash to build from.
ARG REPO_VERSION=master
ARG CONSTRAINTS_BRANCH=master
ARG COMMON_VERSION=master
# Extra Python3 dependencies.
ARG EXTRA_DEPS="gunicorn influxdb python-memcached"
# Always start from `monasca-base` image and use specific tag of it.
ARG BASE_TAG=1.0.0
FROM monasca/base:$BASE_TAG
# Environment variables used for our service or wait scripts.
ENV \
KAFKA_URI=kafka:9092 \
KAFKA_WAIT_FOR_TOPICS=alarm-state-transitions,metrics \
MYSQL_HOST=mysql \
MYSQL_USER=monapi \
MYSQL_PASSWORD=password \
MYSQL_DB=mon \
LOG_LEVEL=INFO \
STAY_ALIVE_ON_FAILURE="false"
# Copy all neccessary files to proper locations.
COPY config_1.yml.j2 config_2.yml.j2 /
# Run here all additionals steps your service need post installation.
# Stay with only one `RUN` and use `&& \` for next steps to don't create
# unnecessary image layers. Clean at the end to conserve space.
RUN \
echo "Some steps to do after main installation." && \
echo "Hello when building."
# Expose port for specific service.
EXPOSE 1234
# Implement start script in `start.sh` file.
CMD ["/start.sh"]

View File

@@ -1,11 +0,0 @@
====================
Docker example image
====================
Example image to show how to build child containers from `monasca-base` image.
+----------------------------+---------+----------------------------------------------------+
| Variable | Default | Description |
+============================+=========+====================================================+
| `STAY_ALIVE_ON_FAILURE` | `false` | If true, container runs 2 hours after service fail |
+----------------------------+---------+----------------------------------------------------+

View File

@@ -1,147 +0,0 @@
#!/bin/bash
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
# TODO(Dobroslaw): move this script to monasca-common/docker folder
# and leave here small script to download it and execute using env variables
# to minimize code duplication.
set -x # Print each script step.
set -eo pipefail # Exit the script if any statement returns error.
# This script is used for building Docker image with proper labels
# and proper version of monasca-common.
#
# Example usage:
# $ ./build_image.sh <repository_version> <upper_constains_branch> <common_version>
#
# Everything after `./build_image.sh` is optional and by default configured
# to get versions from `Dockerfile`.
#
# To build from master branch (default):
# $ ./build_image.sh
# To build specific version run this script in the following way:
# $ ./build_image.sh stable/queens
# Building from specific commit:
# $ ./build_image.sh cb7f226
# When building from a tag monasca-common will be used in version available
# in upper constraint file:
# $ ./build_image.sh 2.5.0
# To build image from Gerrit patch sets that is targeting branch stable/queens:
# $ ./build_image.sh refs/changes/51/558751/1 stable/queens
#
# If you want to build image with custom monasca-common version you need
# to provide it as in the following example:
# $ ./build_image.sh master master refs/changes/19/595719/3
[ -z "$DOCKER_IMAGE" ] && \
DOCKER_IMAGE=$(\grep DOCKER_IMAGE Dockerfile | cut -f2 -d"=")
: "${REPO_VERSION:=$1}"
[ -z "$REPO_VERSION" ] && \
REPO_VERSION=$(\grep REPO_VERSION Dockerfile | cut -f2 -d"=")
# Let's stick to more readable version and disable SC2001 here.
# shellcheck disable=SC2001
REPO_VERSION_CLEAN=$(echo "$REPO_VERSION" | sed 's|/|-|g')
[ -z "$APP_REPO" ] && APP_REPO=$(\grep APP_REPO Dockerfile | cut -f2 -d"=")
GITHUB_REPO=$(echo "$APP_REPO" | sed 's/review.opendev.org/github.com/' | \
sed 's/ssh:/https:/')
if [ -z "$CONSTRAINTS_FILE" ]; then
CONSTRAINTS_FILE=$(\grep CONSTRAINTS_FILE Dockerfile | cut -f2 -d"=") || true
: "${CONSTRAINTS_FILE:=http://opendev.org/openstack/requirements/raw/branch/master/upper-constraints.txt}"
fi
: "${CONSTRAINTS_BRANCH:=$2}"
[ -z "$CONSTRAINTS_BRANCH" ] && \
CONSTRAINTS_BRANCH=$(\grep CONSTRAINTS_BRANCH Dockerfile | cut -f2 -d"=")
# When using stable version of repository use same stable constraints file.
case "$REPO_VERSION" in
*stable*)
CONSTRAINTS_BRANCH_CLEAN="$REPO_VERSION"
CONSTRAINTS_FILE=${CONSTRAINTS_FILE/master/$CONSTRAINTS_BRANCH_CLEAN}
# Get monasca-common version from stable upper constraints file.
CONSTRAINTS_TMP_FILE=$(mktemp)
wget --output-document "$CONSTRAINTS_TMP_FILE" \
$CONSTRAINTS_FILE
UPPER_COMMON=$(\grep 'monasca-common' "$CONSTRAINTS_TMP_FILE")
# Get only version part from monasca-common.
UPPER_COMMON_VERSION="${UPPER_COMMON##*===}"
rm -rf "$CONSTRAINTS_TMP_FILE"
;;
*)
CONSTRAINTS_BRANCH_CLEAN="$CONSTRAINTS_BRANCH"
;;
esac
# Monasca-common variables.
if [ -z "$COMMON_REPO" ]; then
COMMON_REPO=$(\grep COMMON_REPO Dockerfile | cut -f2 -d"=") || true
: "${COMMON_REPO:=https://review.opendev.org/openstack/monasca-common}"
fi
: "${COMMON_VERSION:=$3}"
if [ -z "$COMMON_VERSION" ]; then
COMMON_VERSION=$(\grep COMMON_VERSION Dockerfile | cut -f2 -d"=") || true
if [ "$UPPER_COMMON_VERSION" ]; then
# Common from upper constraints file.
COMMON_VERSION="$UPPER_COMMON_VERSION"
fi
fi
# Clone project to temporary directory for getting proper commit number from
# branches and tags. We need this for setting proper image labels.
# Docker does not allow to get any data from inside of system when building
# image.
TMP_DIR=$(mktemp -d)
(
cd "$TMP_DIR"
# This many steps are needed to support gerrit patch sets.
git init
git remote add origin "$APP_REPO"
git fetch origin "$REPO_VERSION"
git reset --hard FETCH_HEAD
)
GIT_COMMIT=$(git -C "$TMP_DIR" rev-parse HEAD)
[ -z "${GIT_COMMIT}" ] && echo "No git commit hash found" && exit 1
rm -rf "$TMP_DIR"
# Do the same for monasca-common.
COMMON_TMP_DIR=$(mktemp -d)
(
cd "$COMMON_TMP_DIR"
# This many steps are needed to support gerrit patch sets.
git init
git remote add origin "$COMMON_REPO"
git fetch origin "$COMMON_VERSION"
git reset --hard FETCH_HEAD
)
COMMON_GIT_COMMIT=$(git -C "$COMMON_TMP_DIR" rev-parse HEAD)
[ -z "${COMMON_GIT_COMMIT}" ] && echo "No git commit hash found" && exit 1
rm -rf "$COMMON_TMP_DIR"
CREATION_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
docker build --no-cache \
--build-arg CREATION_TIME="$CREATION_TIME" \
--build-arg GITHUB_REPO="$GITHUB_REPO" \
--build-arg APP_REPO="$APP_REPO" \
--build-arg REPO_VERSION="$REPO_VERSION" \
--build-arg GIT_COMMIT="$GIT_COMMIT" \
--build-arg CONSTRAINTS_FILE="$CONSTRAINTS_FILE" \
--build-arg CONSTRAINTS_BRANCH="$CONSTRAINTS_BRANCH_CLEAN" \
--build-arg COMMON_REPO="$COMMON_REPO" \
--build-arg COMMON_VERSION="$COMMON_VERSION" \
--build-arg COMMON_GIT_COMMIT="$COMMON_GIT_COMMIT" \
--tag "$DOCKER_IMAGE":"$REPO_VERSION_CLEAN" .

View File

@@ -1 +0,0 @@
kafka_uri: {{ KAFKA_URI }}

View File

@@ -1,2 +0,0 @@
connection_string:
"mysql+pymysql://{{ MYSQL_USER }}:{{ MYSQL_PASSWORD }}@{{ MYSQL_HOST }}/{{ MYSQL_DB }}"

View File

@@ -1,20 +0,0 @@
#!/usr/bin/env python
# coding=utf-8
# (C) Copyright 2018 FUJITSU LIMITED
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Health check will returns 0 when service is working properly."""
# TODO(Dobroslaw): Fill me with health check magic.

View File

@@ -1,41 +0,0 @@
#!/bin/sh
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
# Starting script.
# All checks and configuration templating you need to do before service
# could be safely started should be added in this file.
set -eo pipefail # Exit the script if any statement returns error.
# Test services we need before starting our service.
echo "Start script: waiting for needed services"
python3 /kafka_wait_for_topics.py
python3 /mysql_check.py
# Template all config files before start, it will use env variables.
# Read usage examples: https://pypi.org/project/Templer/
echo "Start script: creating config files from templates"
templer /*.j2 /
# Start our service.
# gunicorn --args
echo "Start script: starting container"
# Allow server to stay alive in case of failure for 2 hours for debugging.
RESULT=$?
if [ $RESULT != 0 ] && [ "$STAY_ALIVE_ON_FAILURE" = "true" ]; then
echo "Service died, waiting 120 min before exiting"
sleep 7200
fi
exit $RESULT

View File

@@ -1,145 +0,0 @@
#!/usr/bin/env python
# coding=utf-8
# (C) Copyright 2017 Hewlett Packard Enterprise Development LP
# (C) Copyright 2018 FUJITSU LIMITED
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Wait for specific Kafka topics.
For using this script you need to set two environment variables:
* `KAFKA_URI` for connection string to Kafka together with port.
Example: `kafka:9092`, `192.168.10.6:9092`.
* `KAFKA_WAIT_FOR_TOPICS` that contain topics that should exist in Kafka
to consider it's working. Many topics should be separated with comma.
Example: `retry-notifications,alarm-state-transitions`.
After making sure that this environment variables are set you can simply
execute this script in the following way:
`python3 kafka_wait_for_topics.py && ./start_service.sh`
`python3 kafka_wait_for_topics.py || exit 1`
Additional environment variables available are:
* `LOG_LEVEL` - default to `INFO`
* `KAFKA_WAIT_RETRIES` - number of retries, default to `24`
* `KAFKA_WAIT_INTERVAL` - in seconds, default to `5`
"""
import logging
import os
import sys
import time
from pykafka.exceptions import NoBrokersAvailableError
from pykafka import KafkaClient
# Run this script only with Python 3
if sys.version_info.major != 3:
sys.stdout.write("Sorry, requires Python 3.x\n")
sys.exit(1)
LOG_LEVEL = logging.getLevelName(os.environ.get('LOG_LEVEL', 'INFO'))
logging.basicConfig(level=LOG_LEVEL)
logger = logging.getLogger(__name__)
KAFKA_HOSTS = os.environ.get('KAFKA_URI', 'kafka:9092')
REQUIRED_TOPICS = os.environ.get('KAFKA_WAIT_FOR_TOPICS', '') \
.encode('utf-8').split(b',')
KAFKA_WAIT_RETRIES = int(os.environ.get('KAFKA_WAIT_RETRIES', '24'))
KAFKA_WAIT_INTERVAL = int(os.environ.get('KAFKA_WAIT_INTERVAL', '5'))
class TopicNoPartition(Exception):
"""Raise when topic has no partitions."""
class TopicNotFound(Exception):
"""Raise when topic was not found."""
def retry(retries=KAFKA_WAIT_RETRIES, delay=KAFKA_WAIT_INTERVAL,
check_exceptions=()):
"""Retry decorator."""
def decorator(func):
"""Decorator."""
def f_retry(*args, **kwargs):
"""Retry running function on exception after delay."""
for i in range(1, retries + 1):
try:
return func(*args, **kwargs)
# pylint: disable=W0703
# We want to catch all exceptions here to retry.
except check_exceptions + (Exception,) as exc:
if i < retries:
logger.info('Connection attempt %d of %d failed',
i, retries)
if isinstance(exc, check_exceptions):
logger.debug('Caught known exception, retrying...',
exc_info=True)
else:
logger.warn(
'Caught unknown exception, retrying...',
exc_info=True)
else:
logger.exception('Failed after %d attempts', retries)
raise
# No exception so wait before retrying
time.sleep(delay)
return f_retry
return decorator
@retry(check_exceptions=(TopicNoPartition, TopicNotFound))
def check_topics(client, req_topics):
"""Check for existence of provided topics in Kafka."""
client.update_cluster()
logger.debug('Found topics: %r', client.topics.keys())
for req_topic in req_topics:
if req_topic not in client.topics.keys():
err_topic_not_found = 'Topic not found: {}'.format(req_topic)
logger.warning(err_topic_not_found)
raise TopicNotFound(err_topic_not_found)
topic = client.topics[req_topic]
if not topic.partitions:
err_topic_no_part = 'Topic has no partitions: {}'.format(req_topic)
logger.warning(err_topic_no_part)
raise TopicNoPartition(err_topic_no_part)
logger.info('Topic is ready: %s', req_topic)
@retry(check_exceptions=(NoBrokersAvailableError,))
def connect_kafka(hosts):
"""Connect to Kafka with retries."""
return KafkaClient(hosts=hosts)
def main():
"""Start main part of the wait script."""
logger.info('Checking for available topics: %r', repr(REQUIRED_TOPICS))
client = connect_kafka(hosts=KAFKA_HOSTS)
check_topics(client, REQUIRED_TOPICS)
if __name__ == '__main__':
main()

View File

@@ -1,132 +0,0 @@
#!/usr/bin/env python
# coding=utf-8
# (C) Copyright 2018 FUJITSU LIMITED
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Health check for MySQL returns 0 when all checks works properly.
It's checking if requested database already exists.
For using this script you need to set some environment variables:
* `MYSQL_HOST` for connection string to MySQL.
Example: `mysql`, `192.168.10.6`.
Default: `mysql`.
* `MYSQL_PORT` for connection string to MySQL port.
Default: `3306`.
* `MYSQL_USER` for user that is cappable to connect to MySQL.
Default: `monapi`.
* `MYSQL_PASSWORD` for user password.
Default: `password`.
* `MYSQL_DB` for database that you need to have before starting service.
Default: `mon`.
After making sure that this environment variables are set you can simply
execute this script in the following way:
`python3 mysql_check.py && ./start_service.sh`
`python3 mysql_check.py || exit 1`
Additional environment variables available are:
* `LOG_LEVEL` - default to `INFO`
* `MYSQL_WAIT_RETRIES` - number of retries, default to `24`
* `MYSQL_WAIT_INTERVAL` - in seconds, default to `5`
"""
import logging
import os
import sys
import time
import pymysql
# Run this script only with Python 3
if sys.version_info.major != 3:
sys.stdout.write("Sorry, requires Python 3.x\n")
sys.exit(1)
LOG_LEVEL = logging.getLevelName(os.environ.get('LOG_LEVEL', 'INFO'))
logging.basicConfig(level=LOG_LEVEL)
logger = logging.getLogger(__name__)
MYSQL_HOST = os.environ.get('MYSQL_HOST', 'mysql')
MYSQL_PORT = int(os.environ.get('MYSQL_PORT', 3306))
MYSQL_USER = os.environ.get('MYSQL_USER', 'monapi')
MYSQL_PASSWORD = os.environ.get('MYSQL_PASSWORD', 'password')
MYSQL_DB = os.environ.get('MYSQL_DB', 'mon')
MYSQL_WAIT_RETRIES = int(os.environ.get('MYSQL_WAIT_RETRIES', '24'))
MYSQL_WAIT_INTERVAL = int(os.environ.get('MYSQL_WAIT_INTERVAL', '5'))
def retry(retries=MYSQL_WAIT_RETRIES, delay=MYSQL_WAIT_INTERVAL,
check_exceptions=()):
"""Retry decorator."""
def decorator(func):
"""Decorator."""
def f_retry(*args, **kwargs):
"""Retry running function on exception after delay."""
for i in range(1, retries + 1):
try:
return func(*args, **kwargs)
# pylint: disable=W0703
# We want to catch all exceptions here to retry.
except check_exceptions + (Exception,) as exc:
if i < retries:
logger.info('Connection attempt %d of %d failed',
i, retries)
if isinstance(exc, check_exceptions):
logger.debug('Caught known exception, retrying...',
exc_info=True)
else:
logger.warn(
'Caught unknown exception, retrying...',
exc_info=True)
else:
logger.exception('Failed after %d attempts', retries)
raise
# No exception so wait before retrying
time.sleep(delay)
return f_retry
return decorator
@retry(check_exceptions=(pymysql.err.OperationalError,))
def connect_mysql(host, port, user, password, database):
"""Connect to MySQL with retries."""
return pymysql.connect(
host=host, port=port,
user=user, passwd=password,
db=database
)
def main():
"""Start main part of the wait script."""
logger.info('Waiting for database: `%s`', MYSQL_DB)
connect_mysql(
host=MYSQL_HOST, port=MYSQL_PORT,
user=MYSQL_USER, password=MYSQL_PASSWORD,
database=MYSQL_DB
)
logger.info('Database `%s` found', MYSQL_DB)
if __name__ == '__main__':
main()

View File

@@ -1,50 +0,0 @@
#!/bin/sh
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
# This script will return 0 when on specific address (like 192.168.10.6:5000)
# scanning will reveal that port is responding.
#
# Example usage:
# ./wait_for.sh 192.168.10.6:5000 && ./start_service.sh
# ./wait_for.sh 192.168.10.6:5000 || exit 1
#
# By default this script will check up to 24 times every 5 seconds.
# You can overwrite this values with environment variables:
# `WAIT_RETRIES`
# `WAIT_INTERVAL`
: "${WAIT_RETRIES:=24}"
: "${WAIT_INTERVAL:=5}"
wait_for() {
echo "Waiting for $1 to listen on $2..."
for i in $(seq $WAIT_RETRIES)
do
nc -z "$1" "$2" && return
echo "$1 not yet ready (attempt $i of $WAIT_RETRIES)"
sleep "$WAIT_INTERVAL"
done
echo "$1 failed to become ready, exiting..."
exit 1
}
for var in "$@"
do
# nc does not work with links containing http(s), remove trailing slash
clean_link=$(echo "$var" | sed -e "s/^http[s]*:\/\///" | sed 's:/*$::')
host=${clean_link%:*}
port=${clean_link#*:}
wait_for "$host" "$port"
done

View File

@@ -1,19 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>monasca-common</groupId>
<artifactId>monasca-common</artifactId>
<version>${computedVersion}</version>
</parent>
<artifactId>monasca-common-cassandra</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
</project>

View File

@@ -1,127 +0,0 @@
/*
* (c) Copyright 2017 SUSE LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
public class CassandraDbConfiguration {
@JsonProperty
int maxConnections;
public int getMaxConnections() {
return maxConnections;
}
@JsonProperty
int maxRequests;
public int getMaxRequests() {
return maxRequests;
}
@JsonProperty
int connectionTimeout;
public int getConnectionTimeout() {
return connectionTimeout;
}
@JsonProperty
int readTimeout;
public int getReadTimeout() {
return readTimeout;
}
@JsonProperty
String[] contactPoints;
public String[] getContactPoints() {
return contactPoints;
}
@JsonProperty
int port;
public int getPort() {
return port;
}
@JsonProperty
int readConsistencyLevel;
@JsonProperty
String consistencyLevel;
public String getConsistencyLevel() {
return consistencyLevel;
}
@JsonProperty
String keyspace;
public String getKeySpace() {
return keyspace;
}
@JsonProperty
String user;
public String getUser() {
return user;
}
@JsonProperty
String password;
public String getPassword() {
return password;
}
@JsonProperty
long maxDefinitionCacheSize;
public long getDefinitionMaxCacheSize() {
return maxDefinitionCacheSize;
}
@JsonProperty
int maxWriteRetries;
public int getMaxWriteRetries() {
return maxWriteRetries;
}
@JsonProperty
int maxBatches;
public int getMaxBatches() {
return maxBatches;
}
@JsonProperty
int retentionPolicy;
public int getRetentionPolicy() {
return retentionPolicy;
}
@JsonProperty
String localDataCenter;
public String getLocalDataCenter() {
return localDataCenter;
}
}

View File

@@ -1 +0,0 @@
/target

View File

@@ -1,72 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>monasca-common</groupId>
<artifactId>monasca-common</artifactId>
<version>${computedVersion}</version>
</parent>
<artifactId>monasca-common-dropwizard</artifactId>
<packaging>jar</packaging>
<properties>
<dropwizard.version>0.7.0</dropwizard.version>
</properties>
<dependencies>
<dependency>
<groupId>monasca-common</groupId>
<artifactId>monasca-common-util</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-core</artifactId>
<version>${dropwizard.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-db</artifactId>
<version>${dropwizard.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-jdbi</artifactId>
<version>${dropwizard.version}</version>
<scope>provided</scope>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>monasca-common</groupId>
<artifactId>monasca-common-testing</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-testing</artifactId>
<version>${dropwizard.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -1,59 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monasca.common.dropwizard.persistence;
import io.dropwizard.db.DataSourceFactory;
import io.dropwizard.jdbi.DBIFactory;
import io.dropwizard.setup.Environment;
import org.skife.jdbi.v2.DBI;
import com.google.inject.AbstractModule;
import com.google.inject.Provider;
import com.google.inject.ProvisionException;
import com.google.inject.Scopes;
/**
* Module that binds DBI types to a single database instance provided for the specified environment
* and database configuration.
*
* @author Jonathan Halterman
*/
public class DatabaseModule extends AbstractModule {
private final Environment environment;
private final DataSourceFactory config;
public DatabaseModule(Environment environment, DataSourceFactory config) {
this.environment = environment;
this.config = config;
}
@Override
protected void configure() {
bind(DataSourceFactory.class).toInstance(config);
bind(DBI.class).toProvider(new Provider<DBI>() {
@Override
public DBI get() {
try {
return new DBIFactory().build(environment, config, "platform");
} catch (ClassNotFoundException e) {
throw new ProvisionException("Failed to provision DBI", e);
}
}
}).in(Scopes.SINGLETON);
}
}

View File

@@ -1,136 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.dropwizard;
import io.dropwizard.Application;
import io.dropwizard.Configuration;
import io.dropwizard.cli.ServerCommand;
import io.dropwizard.lifecycle.ServerLifecycleListener;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import io.dropwizard.testing.junit.ConfigOverride;
import java.util.Enumeration;
import net.sourceforge.argparse4j.inf.Namespace;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
/**
* Support class for testing applications. Starts and stops the server once for the test suite.
*
* @param <C> configuration type
*/
@Test
public abstract class AbstractAppTest<C extends Configuration> {
private final Class<? extends Application<C>> applicationClass;
private final String configPath;
private C configuration;
private Application<C> application;
private Environment environment;
private Server jettyServer;
public AbstractAppTest(Class<? extends Application<C>> applicationClass, String configPath,
ConfigOverride... configOverrides) {
this.applicationClass = applicationClass;
this.configPath = configPath;
for (ConfigOverride configOverride : configOverrides) {
configOverride.addToSystemProperties();
}
}
@BeforeSuite
protected void startServer() throws Exception {
startIfRequired();
}
@AfterSuite
protected void stopServer() throws Exception {
resetConfigOverrides();
jettyServer.stop();
}
private void resetConfigOverrides() {
for (Enumeration<?> props = System.getProperties().propertyNames(); props.hasMoreElements();) {
String keyString = (String) props.nextElement();
if (keyString.startsWith("dw.")) {
System.clearProperty(keyString);
}
}
}
private void startIfRequired() {
if (jettyServer != null) {
return;
}
try {
application = newApplication();
final Bootstrap<C> bootstrap = new Bootstrap<C>(application) {
@Override
public void run(C configuration, Environment environment) throws Exception {
environment.lifecycle().addServerLifecycleListener(new ServerLifecycleListener() {
@Override
public void serverStarted(Server server) {
jettyServer = server;
}
});
AbstractAppTest.this.configuration = configuration;
AbstractAppTest.this.environment = environment;
super.run(configuration, environment);
}
};
application.initialize(bootstrap);
final ServerCommand<C> command = new ServerCommand<>(application);
final Namespace namespace = new Namespace(ImmutableMap.<String, Object>of("file", configPath));
command.run(bootstrap, namespace);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public C getConfiguration() {
return configuration;
}
public int getLocalPort() {
return ((ServerConnector) jettyServer.getConnectors()[0]).getLocalPort();
}
public Application<C> newApplication() {
try {
return applicationClass.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
public <A extends Application<C>> A getApplication() {
return (A) application;
}
public Environment getEnvironment() {
return environment;
}
}

View File

@@ -1,146 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.dropwizard;
import io.dropwizard.Configuration;
import io.dropwizard.configuration.ConfigurationFactory;
import io.dropwizard.jackson.Jackson;
import io.dropwizard.jersey.DropwizardResourceConfig;
import io.dropwizard.jersey.jackson.JacksonMessageBodyProvider;
import io.dropwizard.logging.LoggingFactory;
import io.dropwizard.setup.Environment;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Map;
import java.util.Set;
import javax.validation.Validation;
import javax.validation.Validator;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import com.beust.jcommander.internal.Maps;
import com.codahale.metrics.MetricRegistry;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import com.google.common.io.Resources;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.test.framework.AppDescriptor;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.LowLevelAppDescriptor;
/**
* Support class for testing resources.
*/
public abstract class AbstractResourceTest {
private final Set<Object> singletons = Sets.newHashSet();
private final Set<Class<?>> providers = Sets.newHashSet();
private final Map<String, Boolean> features = Maps.newHashMap();
private final Map<String, Object> properties = Maps.newHashMap();
protected final ObjectMapper objectMapper = Jackson.newObjectMapper();
protected final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
protected final MetricRegistry metricRegistry = new MetricRegistry();
protected final Environment environment = new Environment("test", objectMapper, validator,
metricRegistry, Thread.currentThread().getContextClassLoader());
private JerseyTest test;
static {
LoggingFactory.bootstrap();
}
public void addFeature(String feature, Boolean value) {
features.put(feature, value);
}
public void addProperty(String property, Object value) {
properties.put(property, value);
}
public void addProviders(Class<?>... providers) {
for (Class<?> provider : providers)
this.providers.add(provider);
}
public void addResources(Object... resources) {
for (Object resource : resources)
singletons.add(resource);
}
public void addSingletons(Object... providers) {
for (Object provider : providers)
singletons.add(provider);
}
public Client client() {
return test.client();
}
public JerseyTest getJerseyTest() {
return test;
}
@AfterMethod
protected void afterTestCase() throws Exception {
if (test != null)
test.tearDown();
}
@BeforeMethod
protected void beforeTestCase() throws Exception {
singletons.clear();
providers.clear();
features.clear();
properties.clear();
setupResources();
test = new JerseyTest() {
@Override
protected AppDescriptor configure() {
final DropwizardResourceConfig config = DropwizardResourceConfig.forTesting(metricRegistry);
for (Class<?> provider : providers)
config.getClasses().add(provider);
for (Map.Entry<String, Boolean> feature : features.entrySet())
config.getFeatures().put(feature.getKey(), feature.getValue());
for (Map.Entry<String, Object> property : properties.entrySet())
config.getProperties().put(property.getKey(), property.getValue());
config.getSingletons().add(new JacksonMessageBodyProvider(objectMapper, validator));
config.getSingletons().addAll(singletons);
return new LowLevelAppDescriptor.Builder(config).build();
}
};
test.setUp();
}
/**
* Returns a configuration object read in from the {@code fileName}.
*/
protected <T extends Configuration> T getConfiguration(String filename,
Class<T> configurationClass) throws Exception {
final ConfigurationFactory<T> configurationFactory = new ConfigurationFactory<>(
configurationClass, validator, objectMapper, "dw");
if (filename != null) {
final File file = new File(Resources.getResource(filename).getFile());
if (!file.exists())
throw new FileNotFoundException("File " + file + " not found");
return configurationFactory.build(file);
}
return configurationFactory.build();
}
protected abstract void setupResources() throws Exception;
}

View File

@@ -1,95 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.dropwizard;
import io.dropwizard.testing.FixtureHelpers;
import java.io.IOException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* A set of helper methods for testing the serialization and deserialization of classes to and from
* JSON.
* <p>
* For example, a test for reading and writing a {@code Person} object as JSON:
* </p>
*
* <pre><code>
* assertThat("writing a person as JSON produces the appropriate JSON object",
* asJson(person),
* is(jsonFixture("fixtures/person.json"));
*
* assertThat("reading a JSON object as a person produces the appropriate person",
* fromJson(jsonFixture("fixtures/person.json"), Person.class),
* is(person));
* </code></pre>
*/
public class JsonHelpers {
private static final ObjectMapper MAPPER = new ObjectMapper();
private JsonHelpers() { /* singleton */
}
/**
* Converts the given object into a canonical JSON string.
*
* @param object an object
* @return {@code object} as a JSON string
* @throws IllegalArgumentException if there is an error encoding {@code object}
*/
public static String asJson(Object object) throws IOException {
return MAPPER.writeValueAsString(object);
}
/**
* Converts the given JSON string into an object of the given type.
*
* @param json a JSON string
* @param klass the class of the type that {@code json} should be converted to
* @param <T> the type that {@code json} should be converted to
* @return {@code json} as an instance of {@code T}
* @throws IOException if there is an error reading {@code json} as an instance of {@code T}
*/
public static <T> T fromJson(String json, Class<T> klass) throws IOException {
return MAPPER.readValue(json, klass);
}
/**
* Converts the given JSON string into an object of the given type.
*
* @param json a JSON string
* @param reference a reference of the type that {@code json} should be converted to
* @param <T> the type that {@code json} should be converted to
* @return {@code json} as an instance of {@code T}
* @throws IOException if there is an error reading {@code json} as an instance of {@code T}
*/
public static <T> T fromJson(String json, TypeReference<T> reference) throws IOException {
return MAPPER.readValue(json, reference);
}
/**
* Loads the given fixture resource as a normalized JSON string.
*
* @param filename the filename of the fixture
* @return the contents of {@code filename} as a normalized JSON string
* @throws IOException if there is an error parsing {@code filename}
*/
public static String jsonFixture(String filename) throws IOException {
return MAPPER.writeValueAsString(MAPPER.readValue(FixtureHelpers.fixture(filename),
JsonNode.class));
}
}

View File

@@ -1,35 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>monasca-common</groupId>
<artifactId>monasca-common</artifactId>
<version>${computedVersion}</version>
</parent>
<artifactId>monasca-common-hibernate</artifactId>
<packaging>jar</packaging>
<properties>
<hibernate-core.version>5.0.1.Final</hibernate-core.version>
</properties>
<dependencies>
<dependency>
<groupId>monasca-common</groupId>
<artifactId>monasca-common-model</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate-core.version}</version>
</dependency>
<dependency>
<groupId>monasca-common</groupId>
<artifactId>monasca-common-testing</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -1,114 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.configuration;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;
public class HibernateDbConfiguration {
private static final String DEFAULT_HBM2DDL_AUTO_VALUE = "validate";
@NotNull
@JsonProperty
boolean supportEnabled;
@NotEmpty
@JsonProperty
String providerClass;
@NotEmpty
@JsonProperty
String dataSourceClassName;
@NotEmpty
@JsonProperty
String user;
@NotEmpty
@JsonProperty
String password;
@JsonProperty
String initialConnections;
@JsonProperty
String maxConnections;
@JsonProperty
String autoConfig;
@JsonProperty
String dataSourceUrl;
@JsonProperty
String serverName;
@JsonProperty
String portNumber;
@JsonProperty
String databaseName;
public String getDataSourceUrl() {
return this.dataSourceUrl;
}
public boolean getSupportEnabled() {
return supportEnabled;
}
public String getProviderClass() {
return providerClass;
}
public void setProviderClass(String providerClass) {
this.providerClass = providerClass;
}
public String getDataSourceClassName() {
return dataSourceClassName;
}
public String getServerName() {
return serverName;
}
public String getPortNumber() {
return portNumber;
}
public String getDatabaseName() {
return databaseName;
}
public String getUser() {
return user;
}
public String getPassword() {
return password;
}
public String getInitialConnections() {
return initialConnections;
}
public String getMaxConnections() {
return maxConnections;
}
/**
* Returns {@code hbm2ddl.auto} telling hibernate how to handle schema. By default will return {@code validate}.
* For more information how each of the possible value works refer to official Hibernate documentation.
*
* @return {@link String} hbm2ddl.auto value
* @see <a href="https://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html/ch03.html#configuration-optional">3.7. Miscellaneous Properties</a>
*/
public String getAutoConfig() {
return this.autoConfig == null ? DEFAULT_HBM2DDL_AUTO_VALUE : this.autoConfig;
}
}

View File

@@ -1,55 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.core;
import java.io.Serializable;
import org.joda.time.DateTime;
public interface AuditablePersistable<T extends Serializable>
extends Persistable<T> {
/**
* Returns {@link DateTime} when an entity was created
*
* @return creation time
*/
DateTime getCreatedAt();
/**
* Allows to set {@code createdAt} {@link DateTime}
*
* @param createdAt date instance
*
* @return {@code self}
*/
AuditablePersistable setCreatedAt(DateTime createdAt);
/**
* Returns {@link DateTime} when an entity was updated
*
* @return most recent update time
*/
DateTime getUpdatedAt();
/**
* Allows to set {@code updatedAt} {@link DateTime}
*
* @param updatedAt date instance
*
* @return {@code self}
*/
AuditablePersistable setUpdatedAt(DateTime updatedAt);
}

View File

@@ -1,50 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.core;
import java.io.Serializable;
/**
* Persistable class.
*
* Defines most basic interface <b>Hibernate</b> entities should implement.
*/
public interface Persistable<T extends Serializable>
extends Serializable {
/**
* Returns {@code is} of an entity
*
* @return ID of an entity
*/
T getId();
/**
* Allows to set {@code id}
*
* @param id primary key
*
* @return {@code self}
*/
Persistable setId(T id);
/**
* Evaluates if an entity is new or not.
* Returns {@link Boolean#FALSE} if entity was persisted at least once
*
* @return true if new, false otherwise
*/
boolean isNew();
}

View File

@@ -1,161 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.db;
import java.io.Serializable;
import java.util.Date;
import javax.annotation.Nullable;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;
import com.google.common.base.Objects;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import monasca.common.hibernate.core.AuditablePersistable;
/**
* <b>Abstract</b> implementation for {@link AuditablePersistable}.
*
* Defines auditable information such as:
* <ol>
* <li>{@link #createdAt} - creation date for entity</li>
* <li>{@link #updatedAt} - last update date for entity</li>
* </ol>
*
* @param <T> primary key type
*
* @see AbstractPersistable
*/
@DynamicInsert
@DynamicUpdate
@MappedSuperclass
abstract class AbstractAuditablePersistable<T extends Serializable>
extends AbstractPersistable<T>
implements AuditablePersistable<T> {
private static final long serialVersionUID = 2335373173379564615L;
@Column(name = "created_at", nullable = false)
private Date createdAt;
@Version
@Column(name = "updated_at", nullable = false)
private Date updatedAt;
AbstractAuditablePersistable() {
this(null, null, null);
}
AbstractAuditablePersistable(final T id) {
this(id, null, null);
}
AbstractAuditablePersistable(final T id,
final DateTime createdAt,
final DateTime updatedAt) {
super(id);
this.setDates(createdAt, updatedAt);
}
/**
* Null-safe method that transform {@link DateTime} into plain {@link java.util.Date}
*
* @param value DateTime instance
*
* @return plain Date
*
* @see #nullSafeGetDate(Date)
*/
static Date nullSafeSetDate(@Nullable final DateTime value) {
if (value == null) {
return null;
}
return value.toDateTime(DateTimeZone.UTC).toDate();
}
/**
* Null-safe method that transform {@link Date} into plain {@link DateTime}
*
* @param value Date instance
*
* @return DateTime
*
* @see #nullSafeSetDate(DateTime)
*/
static DateTime nullSafeGetDate(@Nullable final Date value) {
if (value == null) {
return null;
}
return new DateTime(value.getTime(), DateTimeZone.UTC);
}
@Override
public DateTime getCreatedAt() {
return nullSafeGetDate(this.createdAt);
}
@Override
public AuditablePersistable<T> setCreatedAt(DateTime createdAt) {
this.createdAt = nullSafeSetDate(createdAt);
return this;
}
@Override
public DateTime getUpdatedAt() {
return nullSafeGetDate(this.updatedAt);
}
@Override
public AuditablePersistable<T> setUpdatedAt(DateTime updatedAt) {
this.updatedAt = nullSafeSetDate(updatedAt);
return this;
}
/**
* Ensures that both {@link #createdAt} and {@link #updatedAt} will be
* set to the earliest possible value in case passed values are {@code NULL}
*
* @param createdAt created date
* @param updatedAt updated date
*/
private void setDates(final DateTime createdAt,
final DateTime updatedAt) {
final Date date = DateTime.now(DateTimeZone.UTC).toDate();
if (createdAt == null) {
this.createdAt = date;
} else {
this.createdAt = createdAt.toDateTime(DateTimeZone.UTC).toDate();
}
if (updatedAt == null) {
this.updatedAt = date;
} else {
this.updatedAt = updatedAt.toDateTime(DateTimeZone.UTC).toDate();
}
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("id", id)
.add("createdAt", createdAt)
.add("updatedAt", updatedAt)
.toString();
}
}

View File

@@ -1,98 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.db;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import com.google.common.base.Objects;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import monasca.common.hibernate.core.Persistable;
/**
* <b>Abstract</b> implementation for {@link Persistable}.
*
* Defines primary key of a specific entity.
* Primary key may take any arbitrary type that
* is required by specific case.
*
* @param <T> primary key type
*
* @see AbstractAuditablePersistable
*/
@DynamicInsert
@DynamicUpdate
@MappedSuperclass
abstract class AbstractPersistable<T extends Serializable>
implements Persistable<T> {
private static final long serialVersionUID = -4841075518435739989L;
@Id
@Column(name = "id", length = 36)
protected T id;
AbstractPersistable() {
super();
}
AbstractPersistable(final T id) {
this();
this.id = id;
}
@Override
public T getId() {
return id;
}
@Override
public Persistable<T> setId(final T id) {
this.id = id;
return this;
}
@Override
public boolean isNew() {
return this.id == null;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AbstractPersistable that = (AbstractPersistable) o;
return Objects.equal(this.id, that.id);
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("id", id)
.toString();
}
}

View File

@@ -1,97 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.db;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import com.google.common.base.Objects;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import monasca.common.hibernate.core.Persistable;
import monasca.common.hibernate.type.BinaryId;
import monasca.common.hibernate.type.BinaryIdType;
@DynamicInsert
@DynamicUpdate
@MappedSuperclass
@TypeDef(
name = "monasca.common.hibernate.type.BinaryId",
typeClass = BinaryIdType.class
)
abstract class AbstractUUIDPersistable
implements Persistable<BinaryId> {
private static final long serialVersionUID = 6192850092568538880L;
@Id
@Type(type = "monasca.common.hibernate.type.BinaryId")
@Column(name = "id", length = 20, updatable = false, nullable = false)
protected BinaryId id;
AbstractUUIDPersistable() {
super();
this.id = null;
}
AbstractUUIDPersistable(final BinaryId id) {
this.id = id;
}
protected AbstractUUIDPersistable(final byte[] id) {
this(new BinaryId(id));
}
@Override
public BinaryId getId() {
return this.id;
}
@Override
public Persistable<BinaryId> setId(final BinaryId id) {
this.id = id;
return this;
}
@Override
public boolean isNew() {
return this.id == null || this.id.getBytes() == null;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AbstractUUIDPersistable that = (AbstractUUIDPersistable) o;
return Objects.equal(this.id, that.id);
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("id", id)
.toString();
}
}

View File

@@ -1,128 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.db;
import java.io.Serializable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import com.google.common.base.Objects;
import monasca.common.model.alarm.AlarmState;
@Entity
@Table(name = "alarm_action")
@NamedQueries({
@NamedQuery(
name = AlarmActionDb.Queries.DELETE_BY_ALARMDEFINITION_ID,
query = "delete AlarmActionDb aa " +
"where aa.alarmActionId.alarmDefinition.id = :id"
),
@NamedQuery(
name = AlarmActionDb.Queries.DELETE_BY_ALARMDEFINITION_ID_AND_ALARMSTATE,
query = "delete AlarmActionDb aa " +
"where aa.alarmActionId.alarmDefinition.id = :id " +
"and aa.alarmActionId.alarmState = :alarmState"
),
@NamedQuery(
name = AlarmActionDb.Queries.FIND_BY_TENANT_ID_AND_ALARMDEFINITION_ID_DISTINCT,
query = "select distinct aa from AlarmActionDb aa, AlarmDefinitionDb ad " +
"where ad.id=aa.alarmActionId.alarmDefinition.id " +
"and ad.deletedAt is null " +
"and ad.tenantId= :tenantId " +
"and ad.id= :alarmDefId"
)
})
public class AlarmActionDb
implements Serializable {
private static final long serialVersionUID = -8138171887172601911L;
@EmbeddedId
private AlarmActionId alarmActionId;
public AlarmActionDb() {
this(null, AlarmState.UNDETERMINED, null);
}
public AlarmActionDb(final AlarmDefinitionDb alarmDefinition,
final AlarmState alarmState,
final String actionId) {
super();
this.alarmActionId = new AlarmActionId(alarmDefinition, alarmState, actionId);
}
public AlarmActionId getAlarmActionId() {
return alarmActionId;
}
public AlarmActionDb setAlarmActionId(AlarmActionId alarmActionId) {
this.alarmActionId = alarmActionId;
return this;
}
public boolean isInAlarmState(final AlarmState state) {
return this.alarmActionId != null && this.alarmActionId.getAlarmState().equals(state);
}
public AlarmActionDb setAlarmState(final AlarmState alarmState) {
this.requireAlarmActionId().setAlarmState(alarmState);
return this;
}
public AlarmActionDb setActionId(final String actionId) {
this.requireAlarmActionId().setActionId(actionId);
return this;
}
public AlarmActionDb setAlarmDefinition(final AlarmDefinitionDb alarmDefinition) {
this.requireAlarmActionId().setAlarmDefinition(alarmDefinition);
return this;
}
public AlarmState getAlarmState() {
return this.requireAlarmActionId().getAlarmState();
}
public AlarmDefinitionDb getAlarmDefinition() {
return this.requireAlarmActionId().getAlarmDefinition();
}
public String getActionId() {
return this.requireAlarmActionId().getActionId();
}
private AlarmActionId requireAlarmActionId() {
if (this.alarmActionId == null) {
this.alarmActionId = new AlarmActionId();
}
return this.alarmActionId;
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("alarmActionId", alarmActionId)
.toString();
}
public interface Queries {
String DELETE_BY_ALARMDEFINITION_ID = "AlarmAction.deleteByAlarmDefinitionId";
String DELETE_BY_ALARMDEFINITION_ID_AND_ALARMSTATE = "AlarmAction.deleteByAlarmDefinitionIdAndAlarmState";
String FIND_BY_TENANT_ID_AND_ALARMDEFINITION_ID_DISTINCT = "AlarmAction.findByTenantIdAndAlarmDefinitionId.Distinct";
}
}

View File

@@ -1,101 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.db;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.google.common.base.Objects;
import monasca.common.model.alarm.AlarmState;
@Embeddable
public class AlarmActionId
implements Serializable {
private static final long serialVersionUID = 919758576421181247L;
@JoinColumn(name = "alarm_definition_id", nullable = false)
@ManyToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY, optional = false)
private AlarmDefinitionDb alarmDefinition;
@Column(name = "alarm_state", nullable = false)
@Enumerated(EnumType.STRING)
private AlarmState alarmState;
@Column(name = "action_id", length = 36, nullable = false)
private String actionId;
public AlarmActionId() {
super();
}
public AlarmActionId(AlarmDefinitionDb alarmDefinition, AlarmState alarmState, String actionId) {
super();
this.alarmDefinition = alarmDefinition;
this.alarmState = alarmState;
this.actionId = actionId;
}
public AlarmActionId setAlarmDefinition(final AlarmDefinitionDb alarmDefinition) {
this.alarmDefinition = alarmDefinition;
return this;
}
public AlarmActionId setAlarmState(final AlarmState alarmState) {
this.alarmState = alarmState;
return this;
}
public AlarmActionId setActionId(final String actionId) {
this.actionId = actionId;
return this;
}
public AlarmDefinitionDb getAlarmDefinition() {
return this.alarmDefinition;
}
public AlarmState getAlarmState() {
return this.alarmState;
}
public String getActionId() {
return this.actionId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AlarmActionId that = (AlarmActionId) o;
return Objects.equal(this.alarmDefinition, that.alarmDefinition) &&
Objects.equal(this.alarmState, that.alarmState) &&
Objects.equal(this.actionId, that.actionId);
}
@Override
public int hashCode() {
return Objects.hashCode(alarmDefinition, alarmState, actionId);
}
}

View File

@@ -1,264 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.db;
import java.util.Collection;
import java.util.Date;
import javax.annotation.Nullable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Sets;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.joda.time.DateTime;
import monasca.common.model.alarm.AlarmState;
@Entity
@Table(name = "alarm")
@NamedQueries({
@NamedQuery(
name = AlarmDb.Queries.DELETE_BY_ALARMDEFINITION_ID,
query = "delete from AlarmDb a where a.alarmDefinition.id = :alarmDefinitionId"
),
@NamedQuery(
name = AlarmDb.Queries.DELETE_BY_ID,
query = "delete from AlarmDb a where a.id = :id"
),
@NamedQuery(
name = AlarmDb.Queries.FIND_BY_ID,
query = "from AlarmDb a where a.id = :id"
)
})
public class AlarmDb
extends AbstractAuditablePersistable<String> {
private static final long serialVersionUID = -9084263584287898881L;
@JoinColumn(name = "alarm_definition_id", nullable = false)
@ManyToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY, optional = false)
private AlarmDefinitionDb alarmDefinition;
@Column(name = "state")
@Enumerated(EnumType.STRING)
private AlarmState state;
@Column(name = "lifecycle_state", length = 50)
private String lifecycleState;
@Column(name = "link", length = 512)
private String link;
@Column(name = "state_updated_at")
private Date stateUpdatedAt;
@OneToMany(mappedBy = "alarmMetricId.alarm", fetch = FetchType.LAZY, cascade = {
CascadeType.PERSIST,
CascadeType.REFRESH,
CascadeType.REMOVE
})
@OnDelete(action = OnDeleteAction.CASCADE)
private Collection<AlarmMetricDb> alarmMetrics;
@OneToMany(mappedBy = "alarm", fetch = FetchType.LAZY, cascade = {
CascadeType.PERSIST,
CascadeType.REFRESH,
CascadeType.REMOVE
})
@OnDelete(action = OnDeleteAction.CASCADE)
private Collection<SubAlarmDb> subAlarms;
public AlarmDb() {
super();
}
public AlarmDb(
String id,
AlarmDefinitionDb alarmDefinition,
AlarmState state,
String lifecycleState,
String link,
DateTime stateUpdatedAt,
DateTime created_at,
DateTime updated_at) {
super(id, created_at, updated_at);
this.setAlarmDefinition(alarmDefinition);
this.link = link;
this.state = state;
this.lifecycleState = lifecycleState;
this.setStateUpdatedAt(stateUpdatedAt);
}
public AlarmState getState() {
return state;
}
public AlarmDb setState(AlarmState state) {
this.state = state;
return this;
}
public String getLifecycleState() {
return lifecycleState;
}
public AlarmDb setLifecycleState(String lifecycleState) {
this.lifecycleState = lifecycleState;
return this;
}
public String getLink() {
return link;
}
public AlarmDb setLink(String link) {
this.link = link;
return this;
}
public DateTime getStateUpdatedAt() {
return nullSafeGetDate(this.stateUpdatedAt);
}
public AlarmDb setStateUpdatedAt(DateTime stateUpdatedAt) {
this.stateUpdatedAt = nullSafeSetDate(stateUpdatedAt);
return this;
}
public AlarmDefinitionDb getAlarmDefinition() {
return alarmDefinition;
}
public AlarmDb setAlarmDefinition(final AlarmDefinitionDb alarmDefinition) {
if (!alarmDefinition.hasAlarm(this)) {
alarmDefinition.addAlarm(this);
}
this.alarmDefinition = alarmDefinition;
return this;
}
public Collection<AlarmMetricDb> getAlarmMetrics() {
return this.alarmMetrics != null ? this.alarmMetrics : (this.alarmMetrics = Sets.newHashSet());
}
public AlarmDb setAlarmMetrics(final Collection<AlarmMetricDb> alarmMetrics) {
if (alarmMetrics == null || alarmMetrics.isEmpty()) {
return this;
}
final AlarmDb self = this;
this.alarmMetrics = Sets.newHashSetWithExpectedSize(alarmMetrics.size());
FluentIterable.from(alarmMetrics)
.transform(new Function<AlarmMetricDb, AlarmMetricDb>() {
@Nullable
@Override
public AlarmMetricDb apply(@Nullable final AlarmMetricDb input) {
assert input != null;
input.setAlarm(self);
return input;
}
})
.copyInto(this.alarmMetrics);
return this;
}
public AlarmDb addAlarmMetric(final AlarmMetricDb alarmMetric) {
if (alarmMetric == null || this.hasAlarmMetric(alarmMetric)) {
return this;
}
this.getAlarmMetrics().add(alarmMetric);
alarmMetric.setAlarm(this);
return this;
}
public AlarmDb removeAlarmMetric(final AlarmMetricDb alarmDb) {
if (alarmDb == null || this.alarmMetrics == null) {
return this;
}
this.alarmMetrics.remove(alarmDb);
return this;
}
public boolean hasAlarmMetric(final AlarmMetricDb alarm) {
return alarm != null && (this.alarmMetrics != null && this.alarmMetrics.contains(alarm));
}
public Collection<SubAlarmDb> getSubAlarms() {
return this.subAlarms != null ? this.subAlarms : (this.subAlarms = Sets.newHashSet());
}
public AlarmDb setSubAlarms(final Collection<SubAlarmDb> subAlarms) {
if (subAlarms == null || subAlarms.isEmpty()) {
return this;
}
final AlarmDb self = this;
this.subAlarms = Sets.newHashSetWithExpectedSize(subAlarms.size());
FluentIterable.from(subAlarms)
.transform(new Function<SubAlarmDb, SubAlarmDb>() {
@Nullable
@Override
public SubAlarmDb apply(@Nullable final SubAlarmDb input) {
assert input != null;
input.setAlarm(self);
return input;
}
})
.copyInto(this.subAlarms);
return this;
}
public AlarmDb addSubAlarm(final SubAlarmDb subAlarm) {
if (subAlarm == null || this.hasSubAlarm(subAlarm)) {
return this;
}
this.getSubAlarms().add(subAlarm);
subAlarm.setAlarm(this);
return this;
}
public AlarmDb removeSubAlarm(final SubAlarmDb subAlarm) {
if (subAlarm == null || this.subAlarms == null) {
return this;
}
this.subAlarms.remove(subAlarm);
return this;
}
public boolean hasSubAlarm(final SubAlarmDb subAlarm) {
return subAlarm != null && (this.subAlarms != null && this.subAlarms.contains(subAlarm));
}
public interface Queries {
String DELETE_BY_ALARMDEFINITION_ID = "Alarm.deleteByAlarmDefinitionId";
String DELETE_BY_ID = "Alarm.deleteById";
String FIND_BY_ID = "Alarm.findById";
}
}

View File

@@ -1,266 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.db;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import javax.annotation.Nullable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.Index;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Type;
import org.joda.time.DateTime;
import monasca.common.model.alarm.AlarmSeverity;
@Entity
@Table(name = "alarm_definition", indexes = {
@Index(name = "tenant_id", columnList = "tenant_id"),
@Index(name = "deleted_at", columnList = "deleted_at")
})
@NamedQueries({
@NamedQuery(
name = AlarmDefinitionDb.Queries.FIND_BY_TENANT_AND_ID_NOT_DELETED,
query = "from AlarmDefinitionDb ad " +
"where ad.tenantId = :tenant_id " +
"and ad.id = :id " +
"and ad.deletedAt is NULL " +
"group by ad.id"
),
@NamedQuery(
name = AlarmDefinitionDb.Queries.FIND_BY_TENANT_ID_AND_ID,
query = "from AlarmDefinitionDb alarm_definition " +
"where alarm_definition.tenantId=:tenantId " +
"and alarm_definition.id= :id"
)
})
public class AlarmDefinitionDb
extends AbstractAuditablePersistable<String> {
private static final long serialVersionUID = 2566210444329934008L;
private static final String DEFAULT_MATCH_BY = "";
private static final String DEFAULT_NAME = "";
private static final boolean DEFAULT_ACTIONS_ENABLED = true;
@Column(name = "tenant_id", length = 36, nullable = false)
private String tenantId;
@Column(name = "name", length = 255, nullable = false)
private String name = DEFAULT_NAME;
@Column(name = "description", length = 255)
private String description;
@Lob
@Type(type = "text")
@Basic(fetch = FetchType.LAZY)
@Column(name = "expression", nullable = false, length = 16777215)
private String expression;
@Column(name = "severity", nullable = false)
@Enumerated(EnumType.STRING)
private AlarmSeverity severity;
@Column(name = "match_by", length = 255)
private String matchBy = DEFAULT_MATCH_BY;
@Column(name = "actions_enabled", length = 1, nullable = false)
private boolean actionsEnabled = DEFAULT_ACTIONS_ENABLED;
@Column(name = "deleted_at")
private Date deletedAt;
@BatchSize(size = 50)
@OneToMany(mappedBy = "alarmDefinition", fetch = FetchType.LAZY)
private Collection<AlarmDb> alarms;
public AlarmDefinitionDb() {
super();
}
public AlarmDefinitionDb(String id,
String tenantId,
String name,
String description,
String expression,
AlarmSeverity severity,
String matchBy,
boolean actionsEnabled,
DateTime created_at,
DateTime updated_at,
DateTime deletedAt) {
super(id, created_at, updated_at);
this.id = id;
this.tenantId = tenantId;
this.name = name;
this.description = description;
this.expression = expression;
this.severity = severity;
this.matchBy = matchBy;
this.actionsEnabled = actionsEnabled;
this.setDeletedAt(deletedAt);
}
public AlarmDefinitionDb(String id,
String tenantId,
String expression,
AlarmSeverity severity,
DateTime created_at,
DateTime updated_at) {
this(id, tenantId, null, null, expression, severity, DEFAULT_MATCH_BY, DEFAULT_ACTIONS_ENABLED, created_at, updated_at, null);
}
public AlarmDefinitionDb setDeletedAt(final DateTime deletedAt) {
this.deletedAt = nullSafeSetDate(deletedAt);
return this;
}
public AlarmDefinitionDb setTenantId(final String tenantId) {
this.tenantId = tenantId;
return this;
}
public AlarmDefinitionDb setName(final String name) {
this.name = name;
return this;
}
public AlarmDefinitionDb setDescription(final String description) {
this.description = description;
return this;
}
public AlarmDefinitionDb setExpression(final String expression) {
this.expression = expression;
return this;
}
public AlarmDefinitionDb setSeverity(final AlarmSeverity severity) {
this.severity = severity;
return this;
}
public AlarmDefinitionDb setMatchBy(final String matchBy) {
this.matchBy = matchBy;
return this;
}
public AlarmDefinitionDb setActionsEnabled(final boolean actionsEnabled) {
this.actionsEnabled = actionsEnabled;
return this;
}
public String getTenantId() {
return tenantId;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getExpression() {
return expression;
}
public AlarmSeverity getSeverity() {
return severity;
}
public String getMatchBy() {
return matchBy;
}
public Collection<String> getMatchByAsCollection() {
if (this.matchBy == null) {
return Collections.emptyList();
}
return Lists.newArrayList(this.matchBy.split(","));
}
public boolean isActionsEnabled() {
return actionsEnabled;
}
public DateTime getDeletedAt() {
return nullSafeGetDate(this.deletedAt);
}
public boolean hasAlarm(final AlarmDb alarm) {
return alarm != null && (this.alarms != null && this.alarms.contains(alarm));
}
public Collection<AlarmDb> getAlarms() {
return this.alarms != null ? this.alarms : (this.alarms = Sets.newHashSet());
}
public AlarmDefinitionDb setAlarms(final Collection<AlarmDb> alarms) {
final AlarmDefinitionDb self = this;
this.alarms = Sets.newHashSetWithExpectedSize(alarms.size());
FluentIterable.from(alarms)
.transform(new Function<AlarmDb, AlarmDb>() {
@Nullable
@Override
public AlarmDb apply(@Nullable final AlarmDb input) {
assert input != null;
input.setAlarmDefinition(self);
return input;
}
})
.copyInto(this.alarms);
return this;
}
public AlarmDefinitionDb addAlarm(final AlarmDb alarmDb) {
if (alarmDb == null || this.hasAlarm(alarmDb)) {
return this;
}
this.getAlarms().add(alarmDb);
alarmDb.setAlarmDefinition(this);
return this;
}
public AlarmDefinitionDb removeAlarm(final AlarmDb alarmDb) {
if (alarmDb == null || this.alarms == null) {
return this;
}
this.getAlarms().remove(alarmDb);
return this;
}
public interface Queries {
String FIND_BY_TENANT_AND_ID_NOT_DELETED = "AlarmDefinition.byTenantAndIdNotDeleted";
String FIND_BY_TENANT_ID_AND_ID = "AlarmDefinition.byTenantIdAndId";
}
}

View File

@@ -1,88 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.db;
import java.io.Serializable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Index;
import javax.persistence.Table;
import com.google.common.base.Objects;
@Entity
@Table(name = "alarm_metric", indexes = {
@Index(name = "metric_definition_dimensions_id", columnList = "metric_definition_dimensions_id"),
@Index(name = "alarm_id", columnList = "alarm_id")
})
public class AlarmMetricDb
implements Serializable {
private static final long serialVersionUID = 2852204906043180958L;
@EmbeddedId
private AlarmMetricId alarmMetricId;
public AlarmMetricDb() {
super();
}
public AlarmMetricDb(AlarmMetricId alarmMetricId) {
this();
this.alarmMetricId = alarmMetricId;
this.alarmMetricId.getAlarm().addAlarmMetric(this);
}
public AlarmMetricDb(final AlarmDb alarm, MetricDefinitionDimensionsDb mdd) {
this(new AlarmMetricId(alarm, mdd));
}
public AlarmMetricId getAlarmMetricId() {
return alarmMetricId;
}
public AlarmMetricDb setAlarmMetricId(AlarmMetricId alarmMetricId) {
this.alarmMetricId = alarmMetricId;
return this;
}
public AlarmMetricDb setAlarm(final AlarmDb alarm) {
if (alarm != null) {
if (!alarm.hasAlarmMetric(this)) {
alarm.addAlarmMetric(this);
}
this.requireAlarmMetricId().setAlarm(alarm);
}
return this;
}
public AlarmMetricDb setMetricDefinitionDimensionsId(final MetricDefinitionDimensionsDb mdd) {
this.requireAlarmMetricId().setMetricDefinitionDimensions(mdd);
return this;
}
private AlarmMetricId requireAlarmMetricId() {
if (this.alarmMetricId == null) {
this.alarmMetricId = new AlarmMetricId();
}
return this.alarmMetricId;
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("alarmMetricId", alarmMetricId)
.toString();
}
}

View File

@@ -1,107 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.db;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Embeddable;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.google.common.base.Objects;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
@Embeddable
public class AlarmMetricId
implements Serializable {
private static final long serialVersionUID = -7672930363327018974L;
@JoinColumn(name = "metric_definition_dimensions_id", referencedColumnName = "id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
@ManyToOne(cascade = {
CascadeType.PERSIST,
CascadeType.REFRESH,
CascadeType.REMOVE
})
private MetricDefinitionDimensionsDb metricDefinitionDimensions;
@JoinColumn(name = "alarm_id", referencedColumnName = "id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
@ManyToOne(cascade = {
CascadeType.PERSIST,
CascadeType.REFRESH,
CascadeType.REMOVE
}, fetch = FetchType.LAZY, optional = false)
private AlarmDb alarm;
public AlarmMetricId() {
this(null, null);
}
public AlarmMetricId(final AlarmDb alarm,
MetricDefinitionDimensionsDb metricDefinitionDimensionsId) {
super();
this.alarm = alarm;
this.metricDefinitionDimensions = metricDefinitionDimensionsId;
}
public AlarmMetricId(final AlarmDb alarm) {
this(alarm, null);
}
public AlarmDb getAlarm() {
return alarm;
}
public AlarmMetricId setAlarm(final AlarmDb alarm) {
this.alarm = alarm;
return this;
}
public MetricDefinitionDimensionsDb getMetricDefinitionDimensions() {
return metricDefinitionDimensions;
}
public AlarmMetricId setMetricDefinitionDimensions(final MetricDefinitionDimensionsDb metricDefinitionDimensions) {
this.metricDefinitionDimensions = metricDefinitionDimensions;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AlarmMetricId that = (AlarmMetricId) o;
return Objects.equal(this.metricDefinitionDimensions, that.metricDefinitionDimensions) &&
Objects.equal(this.alarm, that.alarm);
}
@Override
public int hashCode() {
return Objects.hashCode(metricDefinitionDimensions, alarm);
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("alarm", alarm)
.toString();
}
}

View File

@@ -1,80 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.db;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import monasca.common.hibernate.type.BinaryId;
@Entity
@Table(name = "metric_definition")
public class MetricDefinitionDb
extends AbstractUUIDPersistable {
private static final long serialVersionUID = 292896181025585969L;
@Column(name = "name", length = 255, nullable = false)
private String name;
@Column(name = "tenant_id", length = 36, nullable = false)
private String tenantId;
@Column(name = "region", length = 255, nullable = false)
private String region;
public MetricDefinitionDb() {
super();
}
public MetricDefinitionDb(BinaryId id, String name, String tenantId, String region) {
super(id);
this.name = name;
this.tenantId = tenantId;
this.region = region;
}
public MetricDefinitionDb(byte[] id, String name, String tenantId, String region) {
this(new BinaryId(id), name, tenantId, region);
}
public MetricDefinitionDb setRegion(final String region) {
this.region = region;
return this;
}
public MetricDefinitionDb setTenantId(final String tenantId) {
this.tenantId = tenantId;
return this;
}
public MetricDefinitionDb setName(final String name) {
this.name = name;
return this;
}
public String getName() {
return this.name;
}
public String getTenantId() {
return this.tenantId;
}
public String getRegion() {
return this.region;
}
}

View File

@@ -1,98 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.db;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.hibernate.annotations.Type;
import monasca.common.hibernate.type.BinaryId;
@Entity
@Table(
name = "metric_definition_dimensions",
indexes = {
@Index(name = "metric_definition_id", columnList = "metric_definition_id"),
@Index(name = "metric_dimension_set_id", columnList = "metric_dimension_set_id")
}
)
public class MetricDefinitionDimensionsDb
extends AbstractUUIDPersistable {
private static final long serialVersionUID = -4902748436802939703L;
@JoinColumn(name = "metric_definition_id", referencedColumnName = "id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
@ManyToOne(cascade = {
CascadeType.REMOVE,
CascadeType.PERSIST,
CascadeType.REFRESH
}, fetch = FetchType.LAZY, optional = false)
private MetricDefinitionDb metricDefinition;
@Type(type = "monasca.common.hibernate.type.BinaryId")
@Column(name = "metric_dimension_set_id", length = 20, nullable = false)
private BinaryId metricDimensionSetId;
public MetricDefinitionDimensionsDb() {
super();
}
public MetricDefinitionDimensionsDb(final BinaryId id,
final MetricDefinitionDb metricDefinition,
final BinaryId metricDimensionSetId) {
super(id);
this.metricDefinition = metricDefinition;
this.metricDimensionSetId = metricDimensionSetId;
}
public MetricDefinitionDimensionsDb(final byte[] id,
final MetricDefinitionDb metricDefinition,
final BinaryId metricDimensionSetId) {
this(new BinaryId(id), metricDefinition, metricDimensionSetId);
}
public MetricDefinitionDimensionsDb(final byte[] id,
final MetricDefinitionDb metricDefinition,
final byte[] metricDimensionSetId) {
this(new BinaryId(id), metricDefinition, new BinaryId(metricDimensionSetId));
}
public MetricDefinitionDb getMetricDefinition() {
return metricDefinition;
}
public MetricDefinitionDimensionsDb setMetricDefinition(MetricDefinitionDb metricDefinition) {
this.metricDefinition = metricDefinition;
return this;
}
public BinaryId getMetricDimensionSetId() {
return metricDimensionSetId;
}
public MetricDefinitionDimensionsDb setMetricDimensionSetId(final BinaryId metricDimensionSetId) {
this.metricDimensionSetId = metricDimensionSetId;
return this;
}
}

View File

@@ -1,114 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.db;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Index;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import com.google.common.base.Objects;
import monasca.common.hibernate.type.BinaryId;
@Entity
@Table(
name = "metric_dimension",
indexes = {
@Index(name = "dimension_set_id", columnList = "dimension_set_id")
},
uniqueConstraints = {
@UniqueConstraint(name = "metric_dimension_key", columnNames = {
"dimension_set_id",
"name"
})
}
)
public class MetricDimensionDb
implements Serializable {
private static final long serialVersionUID = 4261654453776857159L;
@EmbeddedId
private MetricDimensionDbId id;
@Column(name = "value", length = 255, nullable = false)
private String value;
public MetricDimensionDb() {
super();
}
public MetricDimensionDb(final byte[] dimensionSetId, final String name) {
this(dimensionSetId, name, null);
}
public MetricDimensionDb(final byte[] dimensionSetId, final String name, final String value) {
this(new BinaryId(dimensionSetId), name, value);
}
public MetricDimensionDb(final BinaryId dimensionSetId, final String name, final String value) {
this(new MetricDimensionDbId(dimensionSetId, name), value);
}
public MetricDimensionDb(final MetricDimensionDbId id, final String value) {
this.id = id;
this.value = value;
}
public MetricDimensionDb setId(final MetricDimensionDbId id) {
this.id = id;
return this;
}
public MetricDimensionDbId getId() {
return id;
}
public String getValue() {
return value;
}
public MetricDimensionDb setValue(String value) {
this.value = value;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MetricDimensionDb that = (MetricDimensionDb) o;
return Objects.equal(this.id, that.id);
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("id", id)
.add("value", value)
.toString();
}
}

View File

@@ -1,94 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.db;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import com.google.common.base.Objects;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import monasca.common.hibernate.type.BinaryId;
import monasca.common.hibernate.type.BinaryIdType;
@Embeddable
@TypeDef(
name = "monasca.common.hibernate.type.BinaryId",
typeClass = BinaryIdType.class
)
public class MetricDimensionDbId
implements Serializable {
private static final long serialVersionUID = -594428923583460707L;
@Type(type = "monasca.common.hibernate.type.BinaryId")
@Column(name = "dimension_set_id", length = 20, nullable = false)
private BinaryId dimensionSetId;
@Column(name = "name", length = 255, nullable = false)
private String name;
public MetricDimensionDbId() {
}
public MetricDimensionDbId(final BinaryId dimensionSetId, final String name) {
this.dimensionSetId = dimensionSetId;
this.name = name;
}
public MetricDimensionDbId setDimensionSetId(final BinaryId dimensionSetId) {
this.dimensionSetId = dimensionSetId;
return this;
}
public MetricDimensionDbId setName(final String name) {
this.name = name;
return this;
}
public String getName() {
return name;
}
public BinaryId getDimensionSetId() {
return dimensionSetId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MetricDimensionDbId that = (MetricDimensionDbId) o;
return Objects.equal(this.dimensionSetId, that.dimensionSetId) &&
Objects.equal(this.name, that.name);
}
@Override
public int hashCode() {
return Objects.hashCode(dimensionSetId, name);
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("dimensionSetId", dimensionSetId)
.add("name", name)
.toString();
}
}

View File

@@ -1,150 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
* (C) Copyright 2016 Hewlett Packard Enterprise Development LP
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.db;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import org.joda.time.DateTime;
import monasca.common.model.alarm.AlarmNotificationMethodType;
@Entity
@Table(name = "notification_method")
@NamedQueries({
@NamedQuery(
name = NotificationMethodDb.Queries.NOTIFICATION_BY_TENANT_ID_AND_NAME,
query = "from NotificationMethodDb where tenant_id = :tenantId and name = :name"
),
@NamedQuery(
name = NotificationMethodDb.Queries.FIND_BY_TENANT_ID_AND_ID,
query = "from NotificationMethodDb where tenant_id = :tenantId and id = :id"
),
@NamedQuery(
name = NotificationMethodDb.Queries.DELETE_BY_ID,
query = "delete from NotificationMethodDb where id = :id"
)
})
public class NotificationMethodDb
extends AbstractAuditablePersistable<String> {
private static final long serialVersionUID = 106455752028781371L;
@Column(name = "tenant_id", length = 36, nullable = false)
private String tenantId;
@Column(name = "name", length = 250)
private String name;
@Column(name = "type", nullable = false)
private String type;
@Column(name = "address", length = 512, nullable = false)
private String address;
@Column(name = "period", nullable = false)
private Integer period;
public NotificationMethodDb() {
super();
}
public NotificationMethodDb(String id,
String tenantId,
String name,
String type,
String address,
Integer period,
DateTime created_at,
DateTime updated_at) {
super(id, created_at, updated_at);
this.tenantId = tenantId;
this.name = name;
this.type = type;
this.address = address;
this.period = period;
}
public NotificationMethodDb(String id,
String tenantId,
String name,
String type,
String address,
DateTime created_at,
DateTime updated_at) {
super(id, created_at, updated_at);
this.tenantId = tenantId;
this.name = name;
this.type = type;
this.address = address;
this.period = 0;
}
public NotificationMethodDb setAddress(final String address) {
this.address = address;
return this;
}
public NotificationMethodDb setType(final String type) {
this.type = type;
return this;
}
public NotificationMethodDb setName(final String name) {
this.name = name;
return this;
}
public NotificationMethodDb setTenantId(final String tenantId) {
this.tenantId = tenantId;
return this;
}
public NotificationMethodDb setPeriod(final Integer period) {
this.period = period;
return this;
}
public String getTenantId() {
return this.tenantId;
}
public String getName() {
return this.name;
}
public String getType() {
return this.type;
}
public String getAddress() {
return this.address;
}
public Integer getPeriod() {
return this.period;
}
public interface Queries {
String NOTIFICATION_BY_TENANT_ID_AND_NAME = "NotificationMethod.finByTenantIdAndName";
String DELETE_BY_ID = "NotificationMethod.deleteById";
String FIND_BY_TENANT_ID_AND_ID = "NotificationMethod.findByTenantIdAndId";
}
}

View File

@@ -1,55 +0,0 @@
/*
* (C) Copyright 2016 Hewlett Packard Enterprise Development LP
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.db;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import org.joda.time.DateTime;
import monasca.common.model.alarm.AlarmNotificationMethodType;
@Entity
@Table(name = "notification_method_type")
public class NotificationMethodTypesDb {
private static final long serialVersionUID = 106453452028781371L;
@Id
@Column(name = "name", length = 20)
private String name;
public NotificationMethodTypesDb() {
}
public NotificationMethodTypesDb(String name){
this.name = name;
}
public void setName(final String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}

View File

@@ -1,171 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
* (C) Copyright 2016 Hewlett Packard Enterprise Development LP
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.db;
import monasca.common.model.alarm.AlarmState;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.hibernate.annotations.Type;
import org.joda.time.DateTime;
@Entity
@Table(name = "sub_alarm")
@NamedQueries({
@NamedQuery(
name = SubAlarmDb.Queries.BY_ALARMDEFINITION_ID,
query = "select sa from SubAlarmDb as sa, AlarmDb as a where sa.alarm.id=a.id and a.alarmDefinition.id = :id"
),
@NamedQuery(
name = SubAlarmDb.Queries.BY_ALARM_ID,
query = "from SubAlarmDb where alarm_id = :id"
),
@NamedQuery(
name = SubAlarmDb.Queries.UPDATE_EXPRESSION_BY_SUBEXPRESSION_ID,
query = "update SubAlarmDb set expression=:expression where subExpression.id=:alarmSubExpressionId"
)
})
public class SubAlarmDb
extends AbstractAuditablePersistable<String> {
private static final long serialVersionUID = 5719744905744636511L;
private static final String DEFAULT_EXPRESSION = "";
@JoinColumn(name = "alarm_id", nullable = false)
@ManyToOne(cascade = {CascadeType.REMOVE}, fetch = FetchType.LAZY, optional = false)
@OnDelete(action = OnDeleteAction.CASCADE)
private AlarmDb alarm;
@JoinColumn(name = "sub_expression_id")
@ManyToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
private SubAlarmDefinitionDb subExpression;
@Lob
@Type(type = "text")
@Basic(fetch = FetchType.LAZY)
@Column(name = "expression", nullable = false, length = 16777215)
private String expression = DEFAULT_EXPRESSION;
@Column(name = "state")
@Enumerated(EnumType.STRING)
private AlarmState state;
public SubAlarmDb() {
super();
}
/** This constructor will be deleted once the API tests have changed to no longer use it */
public SubAlarmDb(String id,
AlarmDb alarm,
String expression,
DateTime created_at,
DateTime updated_at) {
this(id, alarm, null, expression, AlarmState.OK, created_at, updated_at);
}
public SubAlarmDb(String id,
AlarmDb alarm,
String expression,
AlarmState state,
DateTime created_at,
DateTime updated_at) {
this(id, alarm, null, expression, state, created_at, updated_at);
}
/** This constructor will be deleted once the API tests have changed to no longer use it */
public SubAlarmDb(String id,
AlarmDb alarm,
SubAlarmDefinitionDb subExpression,
String expression,
DateTime created_at,
DateTime updated_at) {
this(id, alarm, subExpression, expression, AlarmState.OK, created_at, updated_at);
}
public SubAlarmDb(String id,
AlarmDb alarm,
SubAlarmDefinitionDb subExpression,
String expression,
AlarmState state,
DateTime created_at,
DateTime updated_at) {
super(id, created_at, updated_at);
this.alarm = alarm;
this.subExpression = subExpression;
this.expression = expression;
this.state = state;
}
public SubAlarmDb setExpression(final String expression) {
this.expression = expression;
return this;
}
public SubAlarmDb setSubExpression(final SubAlarmDefinitionDb subExpression) {
this.subExpression = subExpression;
return this;
}
public SubAlarmDb setAlarm(final AlarmDb alarm) {
if (alarm != null) {
if (!alarm.hasSubAlarm(this)) {
alarm.addSubAlarm(this);
}
this.alarm = alarm;
}
return this;
}
public AlarmDb getAlarm() {
return this.alarm;
}
public SubAlarmDefinitionDb getSubExpression() {
return this.subExpression;
}
public String getExpression() {
return this.expression;
}
public AlarmState getState() {
return state;
}
public SubAlarmDb setState(AlarmState state) {
this.state = state;
return this;
}
public interface Queries {
String BY_ALARMDEFINITION_ID = "SubAlarm.byAlarmDefinitionId";
String BY_ALARM_ID = "SubAlarm.byAlarmId";
String UPDATE_EXPRESSION_BY_SUBEXPRESSION_ID = "SubAlarm.updateExpressionBySubexpressionId";
}
}

View File

@@ -1,209 +0,0 @@
/*
* Copyright 2015-2016 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.db;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.joda.time.DateTime;
import monasca.common.model.alarm.AlarmOperator;
import monasca.common.model.alarm.AlarmSubExpression;
@Entity
@Table(name = "sub_alarm_definition")
@NamedQueries({
@NamedQuery(
name = SubAlarmDefinitionDb.Queries.BY_ALARMDEFINITION_ID,
query = "from SubAlarmDefinitionDb sad where sad.alarmDefinition.id = :id order by sad.id"
),
@NamedQuery(
name = SubAlarmDefinitionDb.Queries.BY_ALARMDEFINITIONDIMENSION_SUBEXPRESSION_ID,
query = "SELECT sadd from " +
"SubAlarmDefinitionDb sad, " +
"SubAlarmDefinitionDimensionDb sadd " +
"where sadd.subAlarmDefinitionDimensionId.subExpression.id = sad.id " +
"AND sad.alarmDefinition.id = :id"
),
@NamedQuery(
name = SubAlarmDefinitionDb.Queries.DELETE_BY_IDS,
query = "delete SubAlarmDefinitionDb where id in :ids"
)
})
public class SubAlarmDefinitionDb
extends AbstractAuditablePersistable<String> {
private static final long serialVersionUID = 8898225134690206198L;
@JoinColumn(name = "alarm_definition_id", nullable = false)
@ManyToOne(cascade = {
CascadeType.REMOVE,
CascadeType.PERSIST,
CascadeType.REFRESH
}, fetch = FetchType.LAZY, optional = false)
@OnDelete(action = OnDeleteAction.CASCADE)
private AlarmDefinitionDb alarmDefinition;
@Column(name = "function", length = 10, nullable = false)
private String function;
@Column(name = "metric_name", length = 100)
private String metricName;
@Column(name = "operator", length = 5, nullable = false)
private String operator;
@Column(name = "threshold", nullable = false)
private Double threshold;
@Column(name = "period", length = 11, nullable = false)
private Integer period;
@Column(name = "periods", length = 11, nullable = false)
private Integer periods;
@Column(name = "is_deterministic", length = 1, nullable = false)
private boolean deterministic = AlarmSubExpression.DEFAULT_DETERMINISTIC;
public SubAlarmDefinitionDb() {
super();
}
public SubAlarmDefinitionDb(String id,
AlarmDefinitionDb alarmDefinition,
String function,
String metricName,
String operator,
Double threshold,
Integer period,
Integer periods,
DateTime created_at,
DateTime updated_at) {
this(id, alarmDefinition, function, metricName, operator, threshold, period, periods, created_at,
updated_at, AlarmSubExpression.DEFAULT_DETERMINISTIC);
}
public SubAlarmDefinitionDb(String id,
AlarmDefinitionDb alarmDefinition,
String function,
String metricName,
String operator,
Double threshold,
Integer period,
Integer periods,
DateTime created_at,
DateTime updated_at,
boolean deterministic) {
super(id, created_at, updated_at);
this.alarmDefinition = alarmDefinition;
this.function = function;
this.metricName = metricName;
this.operator = operator;
this.threshold = threshold;
this.period = period;
this.periods = periods;
this.deterministic = deterministic;
}
public SubAlarmDefinitionDb setPeriods(final Integer periods) {
this.periods = periods;
return this;
}
public SubAlarmDefinitionDb setPeriod(final Integer period) {
this.period = period;
return this;
}
public SubAlarmDefinitionDb setThreshold(final Double threshold) {
this.threshold = threshold;
return this;
}
public SubAlarmDefinitionDb setOperator(final String operator) {
this.operator = operator;
return this;
}
public SubAlarmDefinitionDb setOperator(final AlarmOperator operator) {
return this.setOperator(operator.name().toUpperCase());
}
public SubAlarmDefinitionDb setMetricName(final String metricName) {
this.metricName = metricName;
return this;
}
public SubAlarmDefinitionDb setFunction(final String function) {
this.function = function;
return this;
}
public SubAlarmDefinitionDb setAlarmDefinition(final AlarmDefinitionDb alarmDefinition) {
this.alarmDefinition = alarmDefinition;
return this;
}
public AlarmDefinitionDb getAlarmDefinition() {
return this.alarmDefinition;
}
public String getFunction() {
return this.function;
}
public String getMetricName() {
return this.metricName;
}
public String getOperator() {
return this.operator;
}
public Double getThreshold() {
return this.threshold;
}
public Integer getPeriod() {
return this.period;
}
public Integer getPeriods() {
return this.periods;
}
public boolean isDeterministic() {
return this.deterministic;
}
public SubAlarmDefinitionDb setDeterministic(final boolean isDeterministic) {
this.deterministic = isDeterministic;
return this;
}
public interface Queries {
String BY_ALARMDEFINITION_ID = "SubAlarmDefinition.byAlarmDefinitionId";
String BY_ALARMDEFINITIONDIMENSION_SUBEXPRESSION_ID = "SubAlarmDefinition.byAlarmDefinitionDimension.subExpressionId";
String DELETE_BY_IDS = "SubAlarmDefinition.deleteByIds";
}
}

View File

@@ -1,124 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.db;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.google.common.base.Objects;
@Entity
@Table(name = "sub_alarm_definition_dimension")
public class SubAlarmDefinitionDimensionDb
implements Serializable {
private static final long serialVersionUID = -692669756593028956L;
@EmbeddedId
private SubAlarmDefinitionDimensionId subAlarmDefinitionDimensionId;
@Column(name = "value", length = 255, nullable = true)
private String value;
public SubAlarmDefinitionDimensionDb() {
this(null, "", null);
}
public SubAlarmDefinitionDimensionDb(SubAlarmDefinitionDimensionId subAlarmDefinitionDimensionId) {
super();
this.subAlarmDefinitionDimensionId = subAlarmDefinitionDimensionId;
}
public SubAlarmDefinitionDimensionDb(SubAlarmDefinitionDb subExpression,
String dimension_name,
String value) {
super();
this.subAlarmDefinitionDimensionId = new SubAlarmDefinitionDimensionId(subExpression, dimension_name);
this.value = value;
}
public SubAlarmDefinitionDimensionDb(SubAlarmDefinitionDimensionId subAlarmDefinitionDimensionId, String value) {
super();
this.subAlarmDefinitionDimensionId = subAlarmDefinitionDimensionId;
this.value = value;
}
public SubAlarmDefinitionDimensionId getSubAlarmDefinitionDimensionId() {
return subAlarmDefinitionDimensionId;
}
public SubAlarmDefinitionDimensionDb setSubAlarmDefinitionDimensionId(SubAlarmDefinitionDimensionId subAlarmDefinitionDimensionId) {
this.subAlarmDefinitionDimensionId = subAlarmDefinitionDimensionId;
return this;
}
public String getDimensionName() {
return this.requireId().getDimensionName();
}
public SubAlarmDefinitionDb getSubExpression() {
return this.requireId().getSubExpression();
}
public SubAlarmDefinitionDimensionDb setDimensionName(final String dimensionName) {
this.requireId().setDimensionName(dimensionName);
return this;
}
public SubAlarmDefinitionDimensionDb setSubExpression(final SubAlarmDefinitionDb subExpression) {
this.requireId().setSubExpression(subExpression);
return this;
}
public String getValue() {
return value;
}
public SubAlarmDefinitionDimensionDb setValue(String value) {
this.value = value;
return this;
}
private SubAlarmDefinitionDimensionId requireId() {
if (this.subAlarmDefinitionDimensionId == null) {
this.subAlarmDefinitionDimensionId = new SubAlarmDefinitionDimensionId();
}
return this.subAlarmDefinitionDimensionId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SubAlarmDefinitionDimensionDb that = (SubAlarmDefinitionDimensionDb) o;
return Objects.equal(this.subAlarmDefinitionDimensionId, that.subAlarmDefinitionDimensionId);
}
@Override
public int hashCode() {
return Objects.hashCode(subAlarmDefinitionDimensionId);
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("subAlarmDefinitionDimensionId", subAlarmDefinitionDimensionId)
.add("value", value)
.toString();
}
}

View File

@@ -1,87 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.db;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.google.common.base.Objects;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
@Embeddable
public class SubAlarmDefinitionDimensionId
implements Serializable {
private static final long serialVersionUID = -233531731474459939L;
@JoinColumn(name = "sub_alarm_definition_id", nullable = false)
@ManyToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY, optional = false)
@OnDelete(action = OnDeleteAction.CASCADE)
private SubAlarmDefinitionDb subExpression;
@Column(name = "dimension_name", length = 255, nullable = false)
private String dimensionName;
public SubAlarmDefinitionDimensionId() {
this(null, "");
}
public SubAlarmDefinitionDimensionId(SubAlarmDefinitionDb subExpression,
String dimensionName) {
super();
this.subExpression = subExpression;
this.dimensionName = dimensionName;
}
public SubAlarmDefinitionDimensionId setSubExpression(final SubAlarmDefinitionDb subExpression) {
this.subExpression = subExpression;
return this;
}
public SubAlarmDefinitionDimensionId setDimensionName(final String dimensionName) {
this.dimensionName = dimensionName;
return this;
}
public SubAlarmDefinitionDb getSubExpression() {
return this.subExpression;
}
public String getDimensionName() {
return this.dimensionName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SubAlarmDefinitionDimensionId that = (SubAlarmDefinitionDimensionId) o;
return Objects.equal(this.subExpression, that.subExpression) &&
Objects.equal(this.dimensionName, that.dimensionName);
}
@Override
public int hashCode() {
return Objects.hashCode(subExpression, dimensionName);
}
}

View File

@@ -1,89 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.type;
import java.io.Serializable;
import java.util.Arrays;
import javax.annotation.Nonnull;
import com.google.common.collect.ComparisonChain;
public class BinaryId
implements Serializable, Comparable<BinaryId> {
private static final long serialVersionUID = -4185721060467793903L;
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
private final byte[] bytes;
private transient String hexBytes = null;
public BinaryId(final byte[] bytes) {
this.bytes = bytes;
}
private static String bytesToHex(byte[] bytes) {
final char[] hexChars = new char[bytes.length * 2];
int j, v;
for (j = 0; j < bytes.length; j++) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
public byte[] getBytes() {
return this.bytes;
}
public String toHexString() {
return this.convertToHex();
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof BinaryId)) return false;
final BinaryId binaryId = (BinaryId) o;
return Arrays.equals(bytes, binaryId.bytes);
}
@Override
public int hashCode() {
return Arrays.hashCode(bytes);
}
@Override
public String toString() {
return this.convertToHex();
}
private String convertToHex() {
if (this.hexBytes == null) {
this.hexBytes = bytesToHex(this.bytes);
}
return this.hexBytes;
}
@Override
public int compareTo(@Nonnull final BinaryId binaryId) {
return ComparisonChain
.start()
.compare(this.toString(), binaryId.toString())
.result();
}
}

View File

@@ -1,104 +0,0 @@
/*
* Copyright 2015 FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package monasca.common.hibernate.type;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Arrays;
import java.util.Objects;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.usertype.UserType;
public class BinaryIdType
implements UserType {
private static final int[] SQL_TYPES = new int[]{Types.BINARY};
@Override
public int[] sqlTypes() {
return SQL_TYPES;
}
@Override
public Class returnedClass() {
return BinaryId.class;
}
@Override
public boolean isMutable() {
return true;
}
@Override
public Object deepCopy(final Object value) throws HibernateException {
final BinaryId binaryId = (BinaryId) value;
final byte[] bytes = binaryId.getBytes();
if (bytes != null) {
return new BinaryId(
Arrays.copyOf(bytes, bytes.length)
);
}
return value;
}
@Override
public Object nullSafeGet(final ResultSet rs, final String[] names, final SessionImplementor session, final Object owner) throws HibernateException, SQLException {
byte[] bytes = rs.getBytes(names[0]);
if (rs.wasNull()) {
return null;
}
return new BinaryId(bytes);
}
@Override
public void nullSafeSet(final PreparedStatement st, final Object value, final int index, final SessionImplementor session) throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, Types.VARBINARY);
} else {
st.setBytes(index, ((BinaryId) value).getBytes());
}
}
@Override
public Serializable disassemble(final Object value) throws HibernateException {
return (Serializable) this.deepCopy(value);
}
@Override
public Object assemble(final Serializable cached, final Object owner) throws HibernateException {
return this.deepCopy(cached);
}
@Override
public Object replace(final Object original, final Object target, final Object owner) throws HibernateException {
return this.deepCopy(original);
}
@Override
public boolean equals(final Object x, final Object y) throws HibernateException {
return Objects.deepEquals(x, y);
}
@Override
public int hashCode(final Object x) throws HibernateException {
return Objects.hashCode(x);
}
}

View File

@@ -1,19 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>monasca-common</groupId>
<artifactId>monasca-common</artifactId>
<version>${computedVersion}</version>
</parent>
<artifactId>monasca-common-influxdb</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
</project>

View File

@@ -1,30 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monasca.common.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
public class DatabaseConfiguration {
@JsonProperty
String databaseType;
public String getDatabaseType() {
return databaseType;
}
}

View File

@@ -1,89 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
public class InfluxDbConfiguration {
@JsonProperty
String version;
public String getVersion() {
return version;
}
/**
* Used only for Influxdb V9.
*/
@JsonProperty
int maxHttpConnections;
public int getMaxHttpConnections() {
return maxHttpConnections;
}
/**
* Used only for Influxdb V9.
*/
@JsonProperty
boolean gzip;
public boolean getGzip() {
return gzip;
}
@JsonProperty
String name;
public String getName() {
return name;
}
@JsonProperty
int replicationFactor;
public int getReplicationFactor() {
return replicationFactor;
}
@JsonProperty
String url;
public String getUrl() {
return url;
}
@JsonProperty
String user;
public String getUser() {
return user;
}
@JsonProperty
String password;
public String getPassword() {
return password;
}
@JsonProperty
String retentionPolicy;
public String getRetentionPolicy() {
return retentionPolicy;
}
}

View File

@@ -1,68 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>monasca-common</groupId>
<artifactId>monasca-common</artifactId>
<version>${computedVersion}</version>
</parent>
<artifactId>monasca-common-kafka</artifactId>
<packaging>jar</packaging>
<properties>
<metrics.version>3.0.1</metrics.version>
<jackson.version>2.3.0</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>monasca-common</groupId>
<artifactId>monasca-common-util</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.codahale.metrics</groupId>
<artifactId>metrics-core</artifactId>
<version>${metrics.version}</version>
</dependency>
<dependency>
<groupId>com.codahale.metrics</groupId>
<artifactId>metrics-healthchecks</artifactId>
<version>${metrics.version}</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.11</artifactId>
<version>0.8.2.2</version>
<exclusions>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>monasca-common</groupId>
<artifactId>monasca-common-testing</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -1,181 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monasca.common.configuration;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonProperty;
public class KafkaConsumerConfiguration implements Serializable {
private static final long serialVersionUID = -1666706655354785832L;
@JsonProperty
String topic;
@JsonProperty
Integer numThreads;
@JsonProperty
String groupId;
@JsonProperty
String zookeeperConnect;
@JsonProperty
String consumerId;
@JsonProperty
Integer socketTimeoutMs;
@JsonProperty
Integer socketReceiveBufferBytes;
@JsonProperty
Integer fetchMessageMaxBytes;
@JsonProperty
Boolean autoCommitEnable;
@JsonProperty
Integer autoCommitIntervalMs;
@JsonProperty
Integer queuedMaxMessageChunks;
@JsonProperty
Integer rebalanceMaxRetries;
@JsonProperty
Integer fetchMinBytes;
@JsonProperty
Integer fetchWaitMaxMs;
@JsonProperty
Integer rebalanceBackoffMs;
@JsonProperty
Integer refreshLeaderBackoffMs;
@JsonProperty
String autoOffsetReset;
@JsonProperty
Integer consumerTimeoutMs;
@JsonProperty
String clientId;
@JsonProperty
Integer zookeeperSessionTimeoutMs;
@JsonProperty
Integer zookeeperConnectionTimeoutMs;
@JsonProperty
Integer zookeeperSyncTimeMs;
public String getTopic() {
return topic;
}
public Integer getNumThreads() {
return numThreads;
}
public String getGroupId() {
return groupId;
}
public String getZookeeperConnect() {
return zookeeperConnect;
}
public String getConsumerId() {
return consumerId;
}
public Integer getSocketTimeoutMs() {
return socketTimeoutMs;
}
public Integer getSocketReceiveBufferBytes() {
return socketReceiveBufferBytes;
}
public Integer getFetchMessageMaxBytes() {
return fetchMessageMaxBytes;
}
public Boolean getAutoCommitEnable() {
return autoCommitEnable;
}
public Integer getAutoCommitIntervalMs() {
return autoCommitIntervalMs;
}
public Integer getQueuedMaxMessageChunks() {
return queuedMaxMessageChunks;
}
public Integer getRebalanceMaxRetries() {
return rebalanceMaxRetries;
}
public Integer getFetchMinBytes() {
return fetchMinBytes;
}
public Integer getFetchWaitMaxMs() {
return fetchWaitMaxMs;
}
public Integer getRebalanceBackoffMs() {
return rebalanceBackoffMs;
}
public Integer getRefreshLeaderBackoffMs() {
return refreshLeaderBackoffMs;
}
public String getAutoOffsetReset() {
return autoOffsetReset;
}
public Integer getConsumerTimeoutMs() {
return consumerTimeoutMs;
}
public String getClientId() {
return clientId;
}
public Integer getZookeeperSessionTimeoutMs() {
return zookeeperSessionTimeoutMs;
}
public Integer getZookeeperConnectionTimeoutMs() {
return zookeeperConnectionTimeoutMs;
}
public Integer getZookeeperSyncTimeMs() {
return zookeeperSyncTimeMs;
}
}

View File

@@ -1,52 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monasca.common.configuration;
import java.io.Serializable;
import java.util.Properties;
public class KafkaConsumerProperties implements Serializable {
private static final long serialVersionUID = 2369697347070190744L;
public static Properties createKafkaProperties(KafkaConsumerConfiguration kafkaConfiguration) {
Properties properties = new Properties();
properties.put("group.id", kafkaConfiguration.getGroupId());
properties.put("zookeeper.connect", kafkaConfiguration.getZookeeperConnect());
properties.put("consumer.id", kafkaConfiguration.getConsumerId());
properties.put("socket.timeout.ms", kafkaConfiguration.getSocketTimeoutMs().toString());
properties.put("socket.receive.buffer.bytes", kafkaConfiguration.getSocketReceiveBufferBytes().toString());
properties.put("fetch.message.max.bytes", kafkaConfiguration.getFetchMessageMaxBytes().toString());
properties.put("auto.commit.enable", kafkaConfiguration.getAutoCommitEnable().toString());
properties.put("auto.commit.interval.ms", kafkaConfiguration.getAutoCommitIntervalMs().toString());
properties.put("queued.max.message.chunks", kafkaConfiguration.getQueuedMaxMessageChunks().toString());
properties.put("rebalance.max.retries", kafkaConfiguration.getRebalanceMaxRetries().toString());
properties.put("fetch.min.bytes", kafkaConfiguration.getFetchMinBytes().toString());
properties.put("fetch.wait.max.ms", kafkaConfiguration.getFetchWaitMaxMs().toString());
properties.put("rebalance.backoff.ms", kafkaConfiguration.getRebalanceBackoffMs().toString());
properties.put("refresh.leader.backoff.ms", kafkaConfiguration.getRefreshLeaderBackoffMs().toString());
properties.put("auto.offset.reset", kafkaConfiguration.getAutoOffsetReset());
properties.put("consumer.timeout.ms", kafkaConfiguration.getConsumerTimeoutMs().toString());
properties.put("client.id", kafkaConfiguration.getClientId());
properties.put("zookeeper.session.timeout.ms", kafkaConfiguration.getZookeeperSessionTimeoutMs().toString());
properties.put("zookeeper.connection.timeout.ms", kafkaConfiguration.getZookeeperConnectionTimeoutMs().toString());
properties.put("zookeeper.sync.time.ms", kafkaConfiguration.getZookeeperSyncTimeMs().toString());
return properties;
}
}

View File

@@ -1,162 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monasca.common.configuration;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonProperty;
public class KafkaProducerConfiguration implements Serializable {
private static final long serialVersionUID = 7930028723426594128L;
@JsonProperty
String topic;
@JsonProperty
String metadataBrokerList;
@JsonProperty
Integer requestRequiredAcks;
@JsonProperty
Integer requestTimeoutMs;
@JsonProperty
String producerType;
@JsonProperty
String serializerClass;
@JsonProperty
String keySerializerClass;
@JsonProperty
String partitionerClass;
@JsonProperty
String compressionCodec;
@JsonProperty
String compressedTopics;
@JsonProperty
Integer messageSendMaxRetries;
@JsonProperty
Integer retryBackoffMs;
@JsonProperty
Integer topicMetadataRefreshIntervalMs;
@JsonProperty
Integer queueBufferingMaxMs;
@JsonProperty
Integer queueBufferingMaxMessages;
@JsonProperty
Integer queueEnqueueTimeoutMs;
@JsonProperty
Integer batchNumMessages;
@JsonProperty
Integer sendBufferBytes;
@JsonProperty
String clientId;
public String getTopic() {
return topic;
}
public String getMetadataBrokerList() {
return metadataBrokerList;
}
public Integer getRequestRequiredAcks() {
return requestRequiredAcks;
}
public Integer getRequestTimeoutMs() {
return requestTimeoutMs;
}
public String getProducerType() {
return producerType;
}
public String getSerializerClass() {
return serializerClass;
}
public String getKeySerializerClass() {
return keySerializerClass;
}
public String getPartitionerClass() {
return partitionerClass;
}
public String getCompressionCodec() {
return compressionCodec;
}
public String getCompressedTopics() {
return compressedTopics;
}
public Integer getMessageSendMaxRetries() {
return messageSendMaxRetries;
}
public Integer getRetryBackoffMs() {
return retryBackoffMs;
}
public Integer getTopicMetadataRefreshIntervalMs() {
return topicMetadataRefreshIntervalMs;
}
public Integer getQueueBufferingMaxMs() {
return queueBufferingMaxMs;
}
public Integer getQueueBufferingMaxMessages() {
return queueBufferingMaxMessages;
}
public Integer getQueueEnqueueTimeoutMs() {
return queueEnqueueTimeoutMs;
}
public Integer getBatchNumMessages() {
return batchNumMessages;
}
public Integer getSendBufferBytes() {
return sendBufferBytes;
}
public String getClientId() {
return clientId;
}
}

View File

@@ -1,53 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monasca.common.configuration;
import java.util.Properties;
public class KafkaProducerProperties {
public static Properties createKafkaProperties(KafkaProducerConfiguration kafkaProducerConfiguration) {
Properties properties = new Properties();
properties.put("metadata.broker.list", kafkaProducerConfiguration.getMetadataBrokerList());
properties.put("request.required.acks", kafkaProducerConfiguration.getRequestRequiredAcks().toString());
properties.put("request.timeout.ms", kafkaProducerConfiguration.getRequestTimeoutMs().toString());
properties.put("producer.type", kafkaProducerConfiguration.getProducerType());
properties.put("serializer.class", kafkaProducerConfiguration.getSerializerClass());
setIfHasValue("key.serializer.class", kafkaProducerConfiguration.getKeySerializerClass(), properties);
setIfHasValue("partitioner.class", kafkaProducerConfiguration.getPartitionerClass(), properties);
properties.put("compression.codec", kafkaProducerConfiguration.getCompressionCodec());
properties.put("compressed.topics", kafkaProducerConfiguration.getCompressedTopics());
properties.put("message.send.max.retries", kafkaProducerConfiguration.getMessageSendMaxRetries().toString());
properties.put("retry.backoff.ms", kafkaProducerConfiguration.getRetryBackoffMs().toString());
properties.put("topic.metadata.refresh.interval.ms", kafkaProducerConfiguration.getTopicMetadataRefreshIntervalMs().toString());
properties.put("queue.buffering.max.ms", kafkaProducerConfiguration.getQueueBufferingMaxMs().toString());
properties.put("queue.buffering.max.messages", kafkaProducerConfiguration.getQueueBufferingMaxMessages().toString());
properties.put("queue.enqueue.timeout.ms", kafkaProducerConfiguration.getQueueEnqueueTimeoutMs().toString());
properties.put("batch.num.messages", kafkaProducerConfiguration.getBatchNumMessages().toString());
properties.put("send.buffer.bytes", kafkaProducerConfiguration.getSendBufferBytes().toString());
properties.put("client.id", kafkaProducerConfiguration.getClientId());
return properties;
}
private static void setIfHasValue(final String name, final String value, final Properties properties) {
if ((value != null) && !value.isEmpty()) {
properties.setProperty(name, value);
}
}
}

View File

@@ -1,25 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monasca.common.messaging.kafka;
import org.hibernate.validator.constraints.NotEmpty;
public class KafkaConfiguration {
@NotEmpty public String[] zookeeperUris;
@NotEmpty public String[] brokerUris;
@NotEmpty public String healthCheckTopic;
}

View File

@@ -1,135 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monasca.common.messaging.kafka;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import kafka.consumer.Consumer;
import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.javaapi.consumer.ConsumerConnector;
import kafka.javaapi.producer.Producer;
import kafka.message.MessageAndMetadata;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
import com.codahale.metrics.health.HealthCheck;
import com.google.common.base.Joiner;
/**
* Kafka health check implementation. Currently assumes that one and only one message is queued in
* the topic.
*
* TODO re-work the implementation to scan the topic for the single health check message that was
* sent, and consume only that message.
*/
public class KafkaHealthCheck extends HealthCheck {
private final KafkaConfiguration config;
public KafkaHealthCheck(KafkaConfiguration config) {
this.config = config;
}
@Override
protected Result check() throws Exception {
Producer<String, String> producer = null;
ConsumerConnector consumer = null;
ExecutorService executor = null;
try {
producer = createProducer();
consumer = createConsumer();
// Send
KeyedMessage<String, String> keyedMessage = new KeyedMessage<>(config.healthCheckTopic, null,
"test");
producer.send(keyedMessage);
// Receive
Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
topicCountMap.put(config.healthCheckTopic, Integer.valueOf(1));
final ConsumerIterator<byte[], byte[]> streamIterator = consumer.createMessageStreams(
topicCountMap)
.get(config.healthCheckTopic)
.get(0)
.iterator();
final Thread mainThread = Thread.currentThread();
executor = Executors.newSingleThreadExecutor();
executor.execute(new Runnable() {
@Override
public void run() {
while (streamIterator.hasNext()) {
MessageAndMetadata<byte[], byte[]> data = streamIterator.next();
String msg = new String(data.message());
System.out.println("Received " + msg);
if (msg.equals("test")) {
mainThread.interrupt();
return;
}
}
}
});
try {
Thread.sleep(5000);
} catch (InterruptedException ignore) {
}
return Result.healthy();
} catch (Exception e) {
return Result.unhealthy(e);
} finally {
if (executor != null)
executor.shutdownNow();
if (producer != null)
try {
producer.close();
} catch (Exception ignore) {
}
if (consumer != null) {
consumer.commitOffsets();
try {
consumer.shutdown();
} catch (Exception ignore) {
}
}
}
}
Producer<String, String> createProducer() {
Properties props = new Properties();
props.put("metadata.broker.list", Joiner.on(',').join(config.brokerUris));
props.put("serializer.class", "kafka.serializer.StringEncoder");
props.put("request.required.acks", "1");
ProducerConfig config = new ProducerConfig(props);
return new Producer<>(config);
}
ConsumerConnector createConsumer() {
Properties props = new Properties();
props.put("zookeeper.connect", Joiner.on(',').join(config.zookeeperUris));
props.put("group.id", "test");
props.put("auto.offset.reset", "largest");
ConsumerConfig config = new ConsumerConfig(props);
return Consumer.createJavaConsumerConnector(config);
}
}

View File

@@ -1,25 +0,0 @@
#Kafka settings.
kafkaConfiguration:
# See http://kafka.apache.org/documentation.html#api for semantics and defaults.
topic: test
numThreads: 1
groupId: 1
zookeeperConnect: localhost:2181
consumerId: 1
socketTimeoutMs: 30000
socketReceiveBufferBytes : 65536
fetchMessageMaxBytes: 1048576
autoCommitEnable: true
autoCommitIntervalMs: 60000
queuedMaxMessageChunks: 10
rebalanceMaxRetries: 4
fetchMinBytes: 1
fetchWaitMaxMs: 100
rebalanceBackoffMs: 2000
refreshLeaderBackoffMs: 200
autoOffsetReset: largest
consumerTimeoutMs: -1
clientId : 1
zookeeperSessionTimeoutMs : 6000
zookeeperConnectionTimeoutMs : 6000
zookeeperSyncTimeMs: 2000

View File

@@ -1,33 +0,0 @@
# See http://kafkaapacheorg/documentationhtml#api for semantics and defaults
# Required
metadataBrokerList: localhost:9092
# Required
requestRequiredAcks: 1
#requestTimeoutMs:
# Required
# async | sync
producerType: sync
# Required
serializerClass: kafkaserializerStringEncoder
#keyserializerclass:
#Required
partitionerClass: monascaSimplePartitioner
#compressionCodec:
#compressedTopics :
#messageSendMaxRetries:
#retryBackoffMs:
#topicMetadataRefreshIntervalMs:
#queueBufferingMaxMs:
#queueBufferingMaxMessages:
#queueEnqueueTimeoutMs:
#batchNumMessages:
#sendBufferBytes:
#clientId:

View File

@@ -1,41 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.messaging.kafka;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.codahale.metrics.health.HealthCheck.Result;
@Test(groups = "integration")
public class KafkaHealthCheckTest {
KafkaConfiguration config;
@BeforeTest
protected void beforeTest() {
config = new KafkaConfiguration();
config.zookeeperUris = new String[] { "192.168.10.10:2181" };
config.brokerUris = new String[] { "192.168.10.10:9092" };
}
public void shouldCheckHealth() throws Exception {
Result result = new KafkaHealthCheck(config).check();
if (!result.isHealthy() && result.getClass() != null)
fail(result.getMessage(), result.getError());
assertTrue(result.isHealthy(), result.getMessage());
}
}

View File

@@ -1,8 +0,0 @@
log4j.rootLogger=INFO, console
log4j.logger.monasca.common.configuration=DEBUG
log4j.logger.monasca.common.messaging=DEBUG
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%-5p [%d{ISO8601}] [%.18t] %c{1}: %m%n

View File

@@ -1,16 +0,0 @@
.swp
*.iml
.DS_Store
.cache
.classpath
.idea
.project
.target/
debs/*
.settings/
target/
test-output/
logs/
log/
*config*.yml
db/config.yml

View File

@@ -1,103 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>monasca-common</groupId>
<artifactId>monasca-common</artifactId>
<version>${computedVersion}</version>
</parent>
<artifactId>monasca-common-middleware</artifactId>
<packaging>jar</packaging>
<properties>
</properties>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>17.0</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet-tester</artifactId>
<version>7.0.0.M2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<scope>provided</scope>
<version>2.5</version>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>monasca-common</groupId>
<artifactId>monasca-common-testing</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>monasca-common</groupId>
<artifactId>monasca-common-util</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>clojars.org</id>
<url>https://repo.clojars.org</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -1,31 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.middleware;
/**
* An exception to indicate authentication error on the Admin
*
*/
public class AdminAuthException extends RuntimeException {
private static final long serialVersionUID = 9192863663767343364L;
public AdminAuthException(String msg) {
super(msg);
}
public AdminAuthException(String msg, Exception e) {
super(msg, e);
}
}

View File

@@ -1,28 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.middleware;
import org.apache.http.client.ClientProtocolException;
import org.apache.thrift.TException;
/**
* A client that can communicate to an authentication server for authentication.
*
* @author liemmn
*/
public interface AuthClient {
public String validateTokenForServiceEndpointV3(String token) throws TException, ClientProtocolException;
}

View File

@@ -1,137 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.middleware;
import org.apache.commons.pool.impl.GenericObjectPool;
/**
* A factory for building {@link AuthClient}s.
*
* @author liemmn
*/
public abstract class AuthClientFactory {
private static AuthClientFactory instance = null;
protected static GenericObjectPool<AuthClient> pool;
/**
* Build a AuthClientFactory. Singleton.
*
* @param host Auth host
* @param port Auth port
* @param timeout Auth connection timeout
* @param clientAuth 2-way SSL (if false, 1-way SSL is used)
* @param keyStore Keystore
* @param keyPass Keystore password
* @param trustStore Truststore
* @param trustPass Truststore password
* @param maxActive Maximum number of objects that can be allocated by the pool
* (checked out to clients, or idle awaiting checkout) at a given
* time. When non-positive, there is no limit to the number of
* objects that can be managed by the pool at one time. When
* maxActive is reached, the pool is said to be exhausted. The
* default setting for this parameter is 8.
* @param maxIdle Maximum number of objects that can sit idle in the pool at any
* time. When negative, there is no limit to the number of
* objects that may be idle at one time. The default setting for
* this parameter is 8.
* @param timeBetweenEvictionRunsMillis How long the eviction thread should sleep before "runs" of
* examining idle objects. When non-positive, no eviction thread
* will be launched. The default setting for this parameter is -1
* (i.e., idle object eviction is disabled by default).
* @param minEvictableIdleTimeMillis Minimum amount of time that an object may sit idle in the pool
* before it is eligible for eviction due to idle time. When
* non-positive, no object will be dropped from the pool due to
* idle time alone. This setting has no effect unless
* timeBetweenEvictionRunsMillis > 0. The default setting for
* this parameter is 30 minutes.
* @param adminToken Admin token for use with vanilla Keystone.
* @return AuthClientFactory singleton.
* @throws Exception
*/
public static synchronized AuthClientFactory build(String host, int port, boolean useHttps,
int timeout, boolean clientAuth, String keyStore, String keyPass,
String trustStore, String trustPass, int maxActive, int maxIdle,
long timeBetweenEvictionRunsMillis,
long minEvictableIdleTimeMillis, String adminToken)
throws Exception {
if (instance == null) {
instance = new HttpClientFactory(host, port, useHttps, timeout,
clientAuth, keyStore, keyPass, trustStore, trustPass,
adminToken, maxActive, timeBetweenEvictionRunsMillis,
minEvictableIdleTimeMillis);
// Pool tweaking
pool.setMaxActive(maxActive);
pool.setMaxIdle(maxIdle);
pool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
pool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
}
return instance;
}
/**
* Get a client. Don't forget to {@link #recycleClient(Client)} after you
* are done using it, successfully or not.
*
* @return Client
* @throws Exception
*/
public AuthClient getClient() {
try {
return (AuthClient) pool.borrowObject();
} catch (Exception e) {
throw new AuthConnectionException("Failed to get a client " + e.getMessage(), e);
}
}
/**
* Recycle the client for next usage.
*
* @param client Client to recycle
* @throws Exception
*/
public void recycle(AuthClient client) {
try {
pool.returnObject(client);
} catch (Exception e) {
throw new AuthConnectionException("Failed to recycle client", e);
}
}
/**
* Call this if the client is unusable (i.e., exception).
*
* @param client Client to discard.
*/
public void discard(AuthClient client) {
try {
pool.invalidateObject(client);
} catch (Exception e) {
System.out.println("AuthConnection problem destorying");
throw new AuthConnectionException("Failed to destroy client", e);
}
}
/**
* Shut down this factory.
*/
public void shutdown() {
try {
pool.close();
} catch (Exception e) {
throw new AuthConnectionException("Failed to close client pool", e);
}
}
}

View File

@@ -1,31 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.middleware;
/**
* An exception to indicate any connection issue.
*
* @author liemmn
*
*/
public class AuthConnectionException extends RuntimeException {
private static final long serialVersionUID = 4318025130590973448L;
public AuthConnectionException(String msg) {
super(msg);
}
public AuthConnectionException(String msg, Exception e) {
super(msg, e);
}
}

View File

@@ -1,253 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.middleware;
public interface AuthConstants {
/**
* 'Confirmed' or 'Invalid'
*/
public static enum IdentityStatus {
Confirmed, Invalid
}
// =============================== TOKEN ===================================
/**
* Credential (token) header
*/
public static final String TOKEN = "X-AUTH-TOKEN";
/**
* Auth status parameter
*/
public static final String AUTH_IDENTITY_STATUS = "X-IDENTITY-STATUS";
/**
* Auth user Id parameter
*/
public static final String AUTH_USER_ID = "X-USER-ID";
/**
* Auth user name parameter
*/
public static final String AUTH_USER_NAME = "X-USER-NAME";
/**
* Auth user roles parameter, comma-separated roles
*/
public static final String AUTH_ROLES = "X-ROLES";
/**
* json encoded keystone service catalog
*/
public static final String AUTH_SERVICE_CATALOG = "X-SERVICE-CATALOG";
/**
* Service Ids initialization parameter
*/
public static final String SERVICE_IDS = "ServiceIds";
/**
* Endpoint Ids initialization parameter
*/
public static final String ENDPOINT_IDS = "EndpointIds";
/**
* Keystone admin token for use in vanilla Keystone
*/
public static final String ADMIN_TOKEN = "AdminToken";
// ============================ CONNECTION =================================
/**
* Auth server initialization parameter
*/
public static final String SERVER_VIP = "ServerVIP";
/**
* Auth server port: 9543 for Thrift, 35357 for HTTP.
*/
public static final String SERVER_PORT = "ServerPort";
/*
* Use https to connect to SERVER_VIP and SERVER_PORT if true
*/
public static final String USE_HTTPS = "UseHttps";
/**
* connection timeout initialization parameter
*/
public static final String CONN_TIMEOUT = "ConnTimeout";
/**
* 2-way SSL initialization parameter: True or False
*/
public static final String CONN_SSL_CLIENT_AUTH = "ConnSSLClientAuth";
/**
* SSL keystore initialization parameter
*/
public static final String KEYSTORE = "Keystore";
/**
* SSL keystore password initialization parameter
*/
public static final String KEYSTORE_PASS = "KeystorePass";
/**
* SSL truststore initialization parameter
*/
public static final String TRUSTSTORE = "Truststore";
/**
* SSL truststore password initialization parameter
*/
public static final String TRUSTSTORE_PASS = "TruststorePass";
// ============================== POOLING ==================================
/**
* Maximum number of objects that can be allocated by the pool (checked out
* to clients, or idle awaiting checkout) at a given time. When
* non-positive, there is no limit to the number of objects that can be
* managed by the pool at one time. When maxActive is reached, the pool is
* said to be exhausted. The default setting for this parameter is 8.
*/
public static final String CONN_POOL_MAX_ACTIVE = "ConnPoolMaxActive";
/**
* Maximum number of objects that can sit idle in the pool at any time. When
* negative, there is no limit to the number of objects that may be idle at
* one time. The default setting for this parameter is 8.
*/
public static final String CONN_POOL_MAX_IDLE = "ConnPoolMaxIdle";
/**
* How long the eviction thread should sleep before "runs" of examining idle
* objects. When non-positive, no eviction thread will be launched. The
* default setting for this parameter is -1 (i.e., idle object eviction is
* disabled by default).
*/
public static final String CONN_POOL_EVICT_PERIOD = "ConnPoolEvictPeriod";
/**
* Minimum amount of time that an object may sit idle in the pool before it
* is eligible for eviction due to idle time. When non-positive, no object
* will be dropped from the pool due to idle time alone. This setting has no
* effect unless ConnPoolEvictPeriod > 0. The default setting for this
* parameter is 30 minutes.
*/
public static final String CONN_POOL_MIN_IDLE_TIME = "ConnPoolMinIdleTime";
// ============================== CACHING ==================================
public static final String TIME_TO_CACHE_TOKEN = "TimeToCacheToken";
public static final String MAX_TOKEN_CACHE_SIZE = "MaxTokenCacheSize";
/**
* Number of connection timeout retries *
*/
public static final String CONN_TIMEOUT_RETRIES = "ConnRetryTimes";
/**
* Number of connection timeout retries *
*/
public static final String PAUSE_BETWEEN_RETRIES = "ConnRetryInterval";
/**
* Authentication decision is forwarded to next filter *
*/
public static final String DELAY_AUTH_DECISION = "DelayAuthDecision";
/**
* Version of CS to authenticate the credentials *
*/
public static final String AUTH_VERSION = "AuthVersion";
/**
* Include Service Catalog as part of Authentication Response *
*/
public static final String INCLUDE_SERVICE_CATALOG = "IncludeServiceCatalog";
/**
* Identity service managed unique identifier, string. Only present if this
* is a project-scoped v3 token, or a tenant-scoped v2 token.
*/
public static final String AUTH_PROJECT_ID = "X-PROJECT-ID";
/**
* Project name, unique within owning domain, string. Only present if this
* is a project-scoped v3 token, or a tenant-scoped v2 token.
*/
public static final String AUTH_PROJECT_NAME = "X-PROJECT-NAME";
/**
* Identity service managed unique identifier of owning domain of project,
* string. Only present if this is a project-scoped v3 token. If this
* variable is set, this indicates that the PROJECT_NAME can only be assumed
* to be unique within this domain.
*/
public static final String AUTH_PROJECT_DOMAIN_ID = "X-PROJECT-DOMAIN-ID";
/**
* Name of owning domain of project, string. Only present if this is a
* project-scoped v3 token. If this variable is set, this indicates that the
* PROJECT_NAME can only be assumed to be unique within this domain.
*/
public static final String AUTH_PROJECT_DOMAIN_NAME = "X-PROJECT-DOMAIN-NAME";
/**
* Identity service managed unique identifier of owning domain of user,
* string. If this variable is set, this indicates that the USER_NAME can
* only be assumed to be unique within this domain.
*/
public static final String AUTH_USER_DOMAIN_ID = "X-USER-DOMAIN-ID";
/**
* Name of owning domain of user, string. If this variable is set, this
* indicates that the USER_NAME can only be assumed to be unique within this
* domain.
*/
public static final String AUTH_USER_DOMAIN_NAME = "X-USER-DOMAIN-NAME";
/**
* Identity service managed unique identifier, string. Only present if this
* is a domain-scoped v3 token.
*/
public static final String AUTH_DOMAIN_ID = "X-DOMAIN-ID";
/**
* Unique domain name, string. Only present if this is a domain-scoped v3
* token.
*/
public static final String AUTH_DOMAIN_NAME = "X-DOMAIN-NAME";
public static final String AUTH_HP_IDM_ROLES = "X-HP-IDM-Non-Tenant-Roles";
public static final String REMOTE_HOST = "RemoteHost";
public static final String REMOTE_ADDR = "RemoteAddress";
// Depracated Headers.
/**
* Auth user roles parameter, comma-separated roles
*/
public static final String AUTH_ROLE = "X-ROLE";
/**
* Auth tenant Id parameter
*/
public static final String AUTH_TENANT_ID = "X-TENANT-ID";
/**
* Auth tenant name parameter
*/
public static final String AUTH_TENANT_NAME = "X-TENANT-NAME";
/**
* Auth tenant name parameter
*/
public static final String AUTH_TENANT = "X-TENANT";
/**
* *Deprecated* in favor of HTTP_X_USER_ID and HTTP_X_USER_NAME User name,
* unique within owning domain, string
*/
public static final String AUTH_USER = "X-USER";
public static final String AUTH_SUBJECT_TOKEN = "X-Subject-Token";
public static final String ADMIN_USER = "AdminUser";
public static final String ADMIN_PASSWORD = "AdminPassword";
public static final String ADMIN_AUTH_METHOD = "AdminAuthMethod";
public static final String ADMIN_ACCESS_KEY = "AdminAccessKey";
public static final String ADMIN_SECRET_KEY = "AdminSecretKey";
public static final String ADMIN_PROJECT_ID = "AdminProjectId";
public static final String ADMIN_PROJECT_NAME = "AdminProjectName";
public static final String ADMIN_USER_DOMAIN_ID = "AdminUserDomainId";
public static final String ADMIN_USER_DOMAIN_NAME = "AdminUserDomainName";
public static final String ADMIN_PROJECT_DOMAIN_ID = "AdminProjectDomainId";
public static final String ADMIN_PROJECT_DOMAIN_NAME = "AdminProjectDomainName";
}

View File

@@ -1,33 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.middleware;
/**
* An exception to indicate any authentication error.
*
* @author liemmn
*
*/
public class AuthException extends RuntimeException {
private static final long serialVersionUID = 5860956829821067827L;
public AuthException(String msg) {
super(msg);
}
public AuthException(String msg, Exception e) {
super(msg, e);
}
}

View File

@@ -1,294 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.middleware;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Config implements AuthConstants {
// Thee faithful logger
private static final Logger logger = LoggerFactory
.getLogger(Config.class);
private static final Config instance = new Config();
public static final String TOKEN = "token";
public static final String PASSWORD = "password";
// Application wide init param -- ServletContext
private ServletContext context = null;
private TokenCache client = null;
// Auth client factory
private AuthClientFactory factory = null;
//the time to cache token
private long timeToCacheToken;
// flag to set if auth decision can be delegated to next filter
private boolean delayAuthDecision;
// retries and pauseTime configuration for retry logic
private int retries;
private int pauseTime;
// flag to include catalog in the response
private boolean includeCatalog;
// configuration for admin authentication method to be used for 2-way SSL
private String adminAuthMethod;
// configuration for admin default project
private String adminProjectId;
private String adminProjectName;
private String adminUserDomainId;
private String adminUserDomainName;
private String adminProjectDomainId;
private String adminProjectDomainName;
// flag to indicate if the filter is already intialized with required parameters
private volatile boolean initialized = false;
//context is not getting properly filed so will use FilterConfig
private FilterConfig filterConfig;
private Config() {
}
public static Config getInstance() {
return instance;
}
public synchronized void initialize(FilterConfig config, ServletRequest req) throws ServletException {
this.context = config.getServletContext();
this.filterConfig = config;
try {
// Initialize auth server connection parameters...
String host = filterConfig.getInitParameter(SERVER_VIP);
int port = Integer.parseInt(filterConfig.getInitParameter(SERVER_PORT));
// Initialize Certificates
String keyStore = filterConfig.getInitParameter(KEYSTORE);
String keyPass = filterConfig.getInitParameter(KEYSTORE_PASS);
String trustStore = filterConfig.getInitParameter(TRUSTSTORE);
String trustPass = filterConfig.getInitParameter(TRUSTSTORE_PASS);
String adminToken = getValue(ADMIN_TOKEN, "");
final boolean useHttps = getValue(USE_HTTPS, false);
int timeout = getValue(CONN_TIMEOUT, 0);
boolean clientAuth = getValue(CONN_SSL_CLIENT_AUTH, true);
int maxActive = getValue(CONN_POOL_MAX_ACTIVE, 3);
int maxIdle = getValue(CONN_POOL_MAX_IDLE, 3);
long evictPeriod = getValue(CONN_POOL_EVICT_PERIOD, 60000L);
long minIdleTime = getValue(CONN_POOL_MIN_IDLE_TIME, 90000L);
retries = getValue(CONN_TIMEOUT_RETRIES, 3);
pauseTime = getValue(PAUSE_BETWEEN_RETRIES, 100);
delayAuthDecision = getValue(DELAY_AUTH_DECISION, false);
includeCatalog = getValue(INCLUDE_SERVICE_CATALOG, true);
adminAuthMethod = getValue(ADMIN_AUTH_METHOD, "");
adminProjectId = getValue(ADMIN_PROJECT_ID, "");
adminProjectName = getValue(ADMIN_PROJECT_NAME, "");
adminUserDomainId = getValue(ADMIN_USER_DOMAIN_ID, "");
adminUserDomainName = getValue(ADMIN_USER_DOMAIN_NAME, "");
adminProjectDomainId = getValue(ADMIN_PROJECT_DOMAIN_ID, "");
adminProjectDomainName = getValue(ADMIN_PROJECT_DOMAIN_NAME, "");
timeToCacheToken = getValue(TIME_TO_CACHE_TOKEN, 600);
long maxTokenCacheSize = getValue(MAX_TOKEN_CACHE_SIZE, 1048576);
this.factory = AuthClientFactory.build(host, port, useHttps, timeout,
clientAuth, keyStore, keyPass, trustStore, trustPass,
maxActive, maxIdle, evictPeriod, minIdleTime, adminToken);
verifyRequiredParamsForAuthMethod();
this.client = new TokenCache(maxTokenCacheSize, timeToCacheToken);
logger.info("Using https {}", useHttps);
if (useHttps) {
logger.info("Auth host (2-way SSL: " + clientAuth + "): " + host);
}
logger.info("Read Servlet Initialization Parameters ");
initialized = true;
} catch (Throwable t) {
logger.error("Failure initializing connection to authentication endpoint : {}",
t.getMessage());
throw new ServletException(
"Failure initializing connection to authentication endpoint :: "
+ t.getMessage(), t);
}
}
private boolean isEmpty(final String value) {
return value == null || value.isEmpty();
}
public boolean isInitialized() {
return initialized;
}
protected String getAdminProjectId() {
return adminProjectId;
}
protected String getAdminProjectName(){
return adminProjectName;
}
protected String getAdminUserDomainId(){
return adminUserDomainId;
}
protected String getAdminUserDomainName(){
return adminUserDomainName;
}
protected String getAdminProjectDomainId(){
return adminProjectDomainId;
}
protected String getAdminProjectDomainName(){
return adminProjectDomainName;
}
protected String getAdminAccessKey() {
if (context.getAttribute(ADMIN_ACCESS_KEY) != null) {
return (String) context.getAttribute(ADMIN_ACCESS_KEY);
} else {
return getValue(ADMIN_ACCESS_KEY, "");
}
}
protected String getAdminSecretKey() {
if (context.getAttribute(ADMIN_SECRET_KEY) != null) {
return (String) context.getAttribute(ADMIN_SECRET_KEY);
} else {
return getValue(ADMIN_SECRET_KEY, "");
}
}
protected String getAdminToken() {
return getValue(ADMIN_TOKEN, "");
}
protected String getAdminAuthMethod() {
return adminAuthMethod;
}
protected String getAdminUser() {
if (context.getAttribute(ADMIN_USER) != null) {
return (String) context.getAttribute(ADMIN_USER);
} else {
return getValue(ADMIN_USER, "");
}
}
protected String getAdminPassword() {
if (context.getAttribute(ADMIN_PASSWORD) != null) {
String password = (String) context.getAttribute(ADMIN_PASSWORD);
return password;
} else {
return getValue(ADMIN_PASSWORD, "");
}
}
protected boolean isIncludeCatalog() {
return includeCatalog;
}
protected ServletContext getConfig() {
return context;
}
protected TokenCache getClient() {
return client;
}
protected AuthClientFactory getFactory() {
return factory;
}
protected boolean isDelayAuthDecision() {
return delayAuthDecision;
}
protected int getRetries() {
return retries;
}
protected int getPauseTime() {
return pauseTime;
}
public long getTimeToCacheToken() {
return timeToCacheToken;
}
public void setTimeToCacheToken(long timeToCachedToken) {
this.timeToCacheToken = timeToCachedToken;
}
public void setClient(TokenCache client) {
this.client = client;
}
@SuppressWarnings("unchecked")
private <T> T getValue(String paramName, T defaultValue) {
Class<?> type = defaultValue.getClass();
String initparamValue = filterConfig.getInitParameter(paramName);
if (!isEmpty(initparamValue)) {
if (type.equals(Integer.class)) {
int paramValue = Integer.parseInt(initparamValue);
return (T) type.cast(paramValue);
} else if (type.equals(Long.class)) {
long paramValue = Long.parseLong(initparamValue);
return (T) type.cast(paramValue);
} else if (type.equals(Boolean.class)) {
boolean paramValue = Boolean.parseBoolean(initparamValue);
return (T) type.cast(paramValue);
} else if (type.equals(String.class)) {
return (T) type.cast(initparamValue);
}
}
return defaultValue;
}
private void verifyRequiredParamsForAuthMethod() {
if (isEmpty(getAdminAuthMethod()) || getAdminAuthMethod().equalsIgnoreCase(TOKEN)) {
if (isEmpty(getAdminToken())) {
throw new AdminAuthException(String.format(
"adminToken must be set if adminAuthMethod is %s.", TOKEN));
}
} else if (getAdminAuthMethod().equalsIgnoreCase(PASSWORD)) {
if (isEmpty(getAdminUser()) || isEmpty(getAdminPassword())) {
throw new AdminAuthException(String.format(
"adminUser and adminPassword must be set if adminAuthMethod is %s.", PASSWORD));
}
} else {
throw new AdminAuthException(String.format(
"Unrecognized value '%s' for adminAuthMethod. Valid values are %s or %s",
getAdminAuthMethod(), TOKEN, PASSWORD));
}
}
}

View File

@@ -1,47 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.middleware;
public class ExceptionHandlerUtil {
public final static String SERVICE_UNAVAILABLE = "Service Unavailable";
public final static String UNAUTHORIZED_TOKEN = "Unauthorized Token";
public final static String INTERNAL_SERVER_ERROR = "Internal Server Error";
private ExceptionHandlerUtil() {
}
public static String getStatusText(int errorCode) {
if (errorCode == 401) {
return UNAUTHORIZED_TOKEN;
}
if (errorCode == 503) {
return SERVICE_UNAVAILABLE;
}
if (errorCode == 500) {
return INTERNAL_SERVER_ERROR;
}
return "Unknown Error";
}
public static TokenExceptionHandler lookUpTokenException(Exception ex) {
try {
return TokenExceptionHandler.valueOf(ex.getClass().getSimpleName());
} catch (IllegalArgumentException iae) {
return TokenExceptionHandler.valueOf("ResourceException");
}
}
}

View File

@@ -1,195 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.middleware;
import static monasca.common.middleware.AuthConstants.AUTH_IDENTITY_STATUS;
import static monasca.common.middleware.AuthConstants.AUTH_ROLES;
import static monasca.common.middleware.AuthConstants.AUTH_USER_ID;
import static monasca.common.middleware.AuthConstants.AUTH_DOMAIN_ID;
import static monasca.common.middleware.AuthConstants.AUTH_DOMAIN_NAME;
import static monasca.common.middleware.AuthConstants.AUTH_PROJECT_ID;
import static monasca.common.middleware.AuthConstants.AUTH_PROJECT_NAME;
import static monasca.common.middleware.AuthConstants.AUTH_USER_NAME;
import static monasca.common.middleware.AuthConstants.IdentityStatus;
import static monasca.common.middleware.AuthConstants.AUTH_PROJECT_DOMAIN_ID;
import static monasca.common.middleware.AuthConstants.AUTH_PROJECT_DOMAIN_NAME;
import static monasca.common.middleware.AuthConstants.AUTH_USER_DOMAIN_ID;
import static monasca.common.middleware.AuthConstants.AUTH_USER_DOMAIN_NAME;
import static monasca.common.middleware.AuthConstants.AUTH_HP_IDM_ROLES;
import static monasca.common.middleware.AuthConstants.AUTH_SERVICE_CATALOG;
import java.io.IOException;
import java.util.Iterator;
import javax.servlet.ServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class FilterUtils {
private FilterUtils() {
}
private static final Config appConfig = Config.getInstance();
// Thee faithful logger
private static final Logger logger = LoggerFactory
.getLogger(FilterUtils.class);
public static void destroyFilter() {
TokenCache client = appConfig.getClient();
if (client != null)
appConfig.setClient(null);
AuthClientFactory factory = appConfig.getFactory();
// Shutdown factory
if (factory != null) {
factory.shutdown();
}
}
public static ServletRequest wrapRequestFromHttpResponse(
ServletRequest req, String data) {
wrapRequestFromHttpV3Response(req, data);
return req;
}
private static void wrapRequestFromHttpV3Response(ServletRequest req,
String data) {
StringBuilder tenants = new StringBuilder();
StringBuilder nonTenants = new StringBuilder();
JsonParser jp = new JsonParser();
JsonObject token = jp.parse(data).getAsJsonObject().get("token")
.getAsJsonObject();
// Domain Scoped Token
if (token.get("domain") != null) {
JsonObject domain = token.get("domain").getAsJsonObject();
req.setAttribute(AUTH_DOMAIN_ID, domain.get("id").getAsString());
if (domain.get("name") != null) {
req.setAttribute(AUTH_DOMAIN_NAME, domain.get("name")
.getAsString());
}
}
// Project Scoped Token
if (token.get("project") != null) {
JsonObject project = token.get("project").getAsJsonObject();
req.setAttribute(AUTH_PROJECT_ID, project.get("id").getAsString());
req.setAttribute(AUTH_PROJECT_NAME, project.get("name")
.getAsString());
JsonObject projectDomain = project.get("domain").getAsJsonObject();
// special case where the value of id is null and the
// projectDomain.get("id") != null
if (!projectDomain.get("id").equals(JsonNull.INSTANCE)) {
req.setAttribute(AUTH_PROJECT_DOMAIN_ID, projectDomain
.get("id").getAsString());
}
if (projectDomain.get("name") != null) {
req.setAttribute(AUTH_PROJECT_DOMAIN_NAME,
projectDomain.get("name"));
}
}
// User info
if (token.get("user") != null) {
JsonObject user = token.get("user").getAsJsonObject();
req.setAttribute(AUTH_USER_ID, user.get("id").getAsString());
req.setAttribute(AUTH_USER_NAME, user.get("name").getAsString());
JsonObject userDomain = user.get("domain").getAsJsonObject();
if (userDomain.get("id") != null) {
req.setAttribute(AUTH_USER_DOMAIN_ID, userDomain.get("id")
.getAsString());
}
if (userDomain.get("name") != null) {
req.setAttribute(AUTH_USER_DOMAIN_NAME, userDomain.get("name")
.getAsString());
}
}
// Roles
JsonArray roles = token.getAsJsonArray("roles");
if (roles != null) {
Iterator<JsonElement> it = roles.iterator();
StringBuilder roleBuilder = new StringBuilder();
while (it.hasNext()) {
//Changed to meet my purposes
JsonObject role = it.next().getAsJsonObject();
String currentRole = role.get("name").getAsString();
roleBuilder.append(currentRole).append(",");
}
//My changes to meet my needs
req.setAttribute(AUTH_ROLES, roleBuilder.toString());
}
String tenantRoles = (tenants.length() > 0) ? tenants.substring(1)
: tenants.toString();
String nonTenantRoles = (nonTenants.length() > 0) ? nonTenants
.substring(1) : nonTenants.toString();
if (!tenantRoles.equals("")) {
req.setAttribute(AUTH_ROLES, tenantRoles);
}
if (!nonTenantRoles.equals("")) {
req.setAttribute(AUTH_HP_IDM_ROLES, nonTenantRoles);
}
// Catalog
if (token.get("catalog") != null && appConfig.isIncludeCatalog()) {
JsonArray catalog = token.get("catalog").getAsJsonArray();
req.setAttribute(AUTH_SERVICE_CATALOG, catalog.toString());
}
}
public static ServletRequest wrapRequest(ServletRequest req, Object data) {
if (data == null) {
req.setAttribute(AUTH_IDENTITY_STATUS,
IdentityStatus.Invalid.toString());
logger.debug("Failed Authentication. Setting identity status header to Invalid");
}
req.setAttribute(AUTH_IDENTITY_STATUS,
IdentityStatus.Confirmed.toString());
if (data instanceof String) {
wrapRequestFromHttpResponse(req, ((String) data));
}
return req;
}
// Insert token into cache
public static void cacheToken(String token, Object auth) {
appConfig.getClient().put(token, (String) auth);
}
// Get token from cache
public static Object getCachedToken(String token) throws IOException {
return appConfig.getClient().getToken(token);
}
public static void pause(long pauseTime) {
try {
Thread.sleep(pauseTime * 1000);
} catch (InterruptedException e) {
logger.debug("Thread is interrupted while sleeping before "
+ pauseTime + " seconds. ");
}
}
}

View File

@@ -1,351 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.middleware;
import static monasca.common.middleware.AuthConstants.TOKEN;
import static monasca.common.middleware.AuthConstants.AUTH_SUBJECT_TOKEN;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
public class HttpAuthClient implements AuthClient {
private static final Logger logger = LoggerFactory.getLogger(HttpAuthClient.class);
private static final int DELTA_TIME_IN_SEC = 30;
private static final String APPLICATION_JSON = "application/json";
// SimpleDateFormat is not thread safe, so use ThreadLocal
private static ThreadLocal<SimpleDateFormat> expiryFormat = new ThreadLocal<>();
private final Config appConfig = Config.getInstance();
private HttpClient client;
private String adminToken;
private String adminTokenExpiry;
private URI uri;
public HttpAuthClient(HttpClient client, URI uri) {
this.client = client;
this.uri = uri;
}
@Override
public String validateTokenForServiceEndpointV3(String token) throws ClientProtocolException {
String newUri = uri.toString() + "/v3/auth/tokens/";
Header[] header = new Header[]{new BasicHeader(AUTH_SUBJECT_TOKEN, token)};
return verifyUUIDToken(token, newUri, header);
}
private String verifyUUIDToken(String token, String newUri,
Header[] headers)
throws ClientProtocolException {
HttpGet httpGet = new HttpGet(newUri);
try {
httpGet.setHeader("Accept", APPLICATION_JSON);
httpGet.setHeader("Content-Type", APPLICATION_JSON);
if (headers != null) {
for (Header header : headers) {
httpGet.setHeader(header);
}
}
HttpResponse response = sendGet(httpGet);
HttpEntity entity = response.getEntity();
int code = response.getStatusLine().getStatusCode();
InputStream instream;
try {
if (code == 404) {
instream = entity.getContent();
instream.close();
//
// Don't log the whole token, just the last ten characters
//
throw new AuthException("Authorization failed for user token ending with: "
+ token.substring(token.length() - 10));
}
if (code != 200) {
adminToken = null;
instream = entity.getContent();
instream.close();
String reasonPhrase = response.getStatusLine().getReasonPhrase();
throw new AuthException("Failed to validate via HTTP " + code + " " + reasonPhrase);
}
} catch (IOException e) {
throw new ClientProtocolException("IO Exception: problem closing stream ", e);
}
return parseResponse(response);
} finally {
httpGet.releaseConnection();
}
}
private HttpResponse sendPost(HttpPost httpPost)
throws ClientProtocolException {
HttpResponse response;
try {
response = client.execute(httpPost);
int code = response.getStatusLine().getStatusCode();
if (!(code == 201 || code == 200 || code == 203)) {
adminToken = null;
throw new AdminAuthException(
"Failed to authenticate admin credentials " + code
+ response.getStatusLine().getReasonPhrase());
}
} catch (IOException e) {
final String message;
if ((e.getMessage() == null) && (e.getCause() != null)) {
message = e.getCause().getMessage();
} else {
message = e.getMessage();
}
logger.error("Failure authenticating adminUser: {}", message);
httpPost.abort();
throw new AdminAuthException(
"Failure authenticating adminUser :" + message, e);
}
return response;
}
private HttpResponse sendGet(HttpGet httpGet)
throws ClientProtocolException {
HttpResponse response;
if (appConfig.getAdminAuthMethod().equalsIgnoreCase(Config.TOKEN)) {
httpGet.setHeader(new BasicHeader(TOKEN, appConfig.getAdminToken()));
} else {
httpGet.setHeader(new BasicHeader(TOKEN, getAdminToken()));
}
try {
response = client.execute(httpGet);
} catch (ConnectException c) {
httpGet.abort();
throw new ServiceUnavailableException(c.getMessage());
} catch (IOException e) {
httpGet.abort();
throw new ClientProtocolException(
"IO Exception during GET request ", e);
}
return response;
}
private String parseResponse(HttpResponse response) {
StringBuffer json = new StringBuffer();
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream;
try {
instream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(instream));
String line = reader.readLine();
while (line != null) {
json.append(line);
line = reader.readLine();
}
instream.close();
reader.close();
} catch (Exception e) {
throw new AuthException("Failed to parse Http Response ", e);
}
}
return json.toString();
}
private String getAdminToken() throws ClientProtocolException {
if (adminTokenExpiry != null) {
if (isExpired(adminTokenExpiry)) {
adminToken = null;
}
}
if (adminToken == null) {
String authUri = uri + "/v3/auth/tokens";
HttpPost httpPost = new HttpPost(authUri);
try {
StringEntity params = getUnscopedV3AdminTokenRequest();
httpPost.setHeader("Accept", APPLICATION_JSON);
httpPost.setHeader("Content-Type", APPLICATION_JSON);
httpPost.setEntity(params);
HttpResponse response = sendPost(httpPost);
adminToken = response.getFirstHeader(AUTH_SUBJECT_TOKEN).getValue();
String json = parseResponse(response);
JsonObject
token =
new JsonParser().parse(json).getAsJsonObject().get("token").getAsJsonObject();
adminTokenExpiry = token.get("expires_at").getAsString();
} finally {
httpPost.releaseConnection();
}
}
return adminToken;
}
private String buildAuth(final String userName, final String password,
final String projectId, final String projectName,
final String userDomainId, final String userDomainName,
final String projectDomainId, final String projectDomainName) {
final JsonObject UserDomain = new JsonObject();
if (!userDomainId.isEmpty()) {
UserDomain.addProperty("id", userDomainId);
} else if (!userDomainName.isEmpty()) {
UserDomain.addProperty("name", userDomainName);
} else {
UserDomain.addProperty("id", "default");
}
final JsonObject user = new JsonObject();
user.addProperty("name", userName);
user.addProperty("password", password);
user.add("domain", UserDomain);
final JsonObject passwordHolder = new JsonObject();
passwordHolder.add("user", user);
final JsonArray methods = new JsonArray();
methods.add(new JsonPrimitive("password"));
final JsonObject identity = new JsonObject();
identity.add("methods", methods);
identity.add("password", passwordHolder);
boolean scopeDefined = false;
final JsonObject project = new JsonObject();
// If project id is available, it is preferred
if (!projectId.isEmpty()) {
project.addProperty("id", projectId);
scopeDefined = true;
} else if (!projectName.isEmpty()) {
final JsonObject ProjectDomain = new JsonObject();
if (!projectDomainId.isEmpty()) {
ProjectDomain.addProperty("id", projectDomainId);
} else if (!projectDomainName.isEmpty()) {
ProjectDomain.addProperty("name", projectDomainName);
} else {
ProjectDomain.addProperty("id", "default");
}
project.add("domain", ProjectDomain);
project.addProperty("name", projectName);
scopeDefined = true;
}
final JsonObject auth = new JsonObject();
auth.add("identity", identity);
if (scopeDefined) {
final JsonObject scope = new JsonObject();
scope.add("project", project);
auth.add("scope", scope);
}
final JsonObject outer = new JsonObject();
outer.add("auth", auth);
return outer.toString();
}
private StringEntity getUnscopedV3AdminTokenRequest() {
final String body;
if (appConfig.getAdminAuthMethod().equalsIgnoreCase(Config.PASSWORD)) {
body = buildAuth(appConfig.getAdminUser(), appConfig.getAdminPassword(),
appConfig.getAdminProjectId(), appConfig.getAdminProjectName(),
appConfig.getAdminUserDomainId(), appConfig.getAdminUserDomainName(),
appConfig.getAdminProjectDomainId(), appConfig.getAdminProjectDomainName());
} else {
String
msg =
String.format("Admin auth method %s not supported", appConfig.getAdminAuthMethod());
throw new AdminAuthException(msg);
}
try {
return new StringEntity(body);
} catch (UnsupportedEncodingException e) {
throw new AdminAuthException("Invalid V3 authentication request " + e);
}
}
private boolean isExpired(String expires) {
Date tokenExpiryDate;
if (expiryFormat.get() == null) {
expiryFormat.set(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"));
expiryFormat.get().setTimeZone(TimeZone.getTimeZone("UTC"));
}
try {
// The date looks like: 2014-11-13T02:34:59.953729Z
// SimpleDateFormat can't handle the microseconds so take them off
final String tmp = expires.replaceAll("\\.[\\d]+Z", "Z");
tokenExpiryDate = expiryFormat.get().parse(tmp);
} catch (ParseException e) {
logger.warn("Failure parsing Admin Token expiration date: {}", e.getMessage());
return true;
}
Date current = new Date();
return tokenExpiryDate.getTime() < (current.getTime() + DELTA_TIME_IN_SEC * 1000);
}
public void reset() {
}
}

View File

@@ -1,42 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.middleware;
import org.apache.commons.pool.impl.GenericObjectPool;
/**
* An HTTP factory.
*
* @author liemmn
*/
public class HttpClientFactory extends AuthClientFactory {
private HttpClientPoolFactory clientPool;
HttpClientFactory(String host, int port, boolean useHttps, int timeout, boolean clientAuth,
String keyStore, String keyPass, String trustStore,
String trustPass, String adminToken, int maxActive,
long timeBetweenEvictionRunsMillis, long minEvictableIdleTimeMillis) {
clientPool = new HttpClientPoolFactory(host, port, useHttps, timeout, clientAuth,
keyStore, keyPass, trustStore, trustPass, adminToken,
maxActive, timeBetweenEvictionRunsMillis,
minEvictableIdleTimeMillis);
pool = new GenericObjectPool(clientPool);
}
@Override
public void shutdown() {
clientPool.shutDown();
super.shutdown();
}
}

View File

@@ -1,157 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.middleware;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URI;
import java.security.KeyStore;
import java.util.concurrent.TimeUnit;
import org.apache.commons.pool.BasePoolableObjectFactory;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A Http request pool factory. Based on Apache Commons Pool. Singleton.
* Note that the Apache HttpClient maintains its own connection pool and
* does not participate in Apache Commons pool' lifecycle other than creating
* HTTPRequests.
*
* @author liemmn
*/
public class HttpClientPoolFactory extends BasePoolableObjectFactory<Object> {
private static final Logger logger = LoggerFactory
.getLogger(HttpClientPoolFactory.class);
private URI uri;
private PoolingClientConnectionManager connMgr;
private HttpPoolCleaner cleaner;
private HttpClient client;
HttpClientPoolFactory(String host, int port, boolean useHttps, int timeout,
boolean clientAuth, String keyStore, String keyPass,
String trustStore, String trustPass, String adminToken,
int maxActive, long timeBetweenEvictionRunsMillis,
long minEvictableIdleTimeMillis) {
// Setup auth URL
String protocol = useHttps ? "https://" : "http://";
String urlStr = protocol + host + ":" + port;
uri = URI.create(urlStr);
// Setup connection pool
SchemeRegistry schemeRegistry = new SchemeRegistry();
if (protocol.startsWith("https")) {
SSLSocketFactory sslf = sslFactory(keyStore, keyPass, trustStore,
trustPass, clientAuth);
schemeRegistry.register(new Scheme("https", port, sslf));
} else {
schemeRegistry.register(new Scheme("http", port, PlainSocketFactory
.getSocketFactory()));
}
connMgr = new PoolingClientConnectionManager(schemeRegistry,
minEvictableIdleTimeMillis, TimeUnit.MILLISECONDS);
connMgr.setMaxTotal(maxActive);
connMgr.setDefaultMaxPerRoute(maxActive);
// Http connection timeout
HttpParams params = new BasicHttpParams();
params.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
// Create a single client
client = new DefaultHttpClient(connMgr, params);
// Create and start the connection pool cleaner
cleaner = new HttpPoolCleaner(connMgr, timeBetweenEvictionRunsMillis,
minEvictableIdleTimeMillis);
new Thread(cleaner).start();
}
@Override
public Object makeObject() throws Exception {
return new HttpAuthClient(client, uri);
}
@Override
public void passivateObject(Object obj) throws Exception {
((HttpAuthClient) obj).reset();
}
@Override
public void destroyObject(Object obj) throws Exception {
((HttpAuthClient) obj).reset();
obj = null;
}
public void shutDown() {
// Shutdown all connections
connMgr.shutdown();
// Shutdown connection pool cleaner
cleaner.shutdown();
}
// get a socket factory
private static SSLSocketFactory sslFactory(String keyStore, String keyPass,
String trustStore, String trustPass, boolean clientAuth) {
try {
// keystore
KeyStore ks = null;
if (clientAuth) {
ks = loadKeystore("keystore", keyStore, keyPass);
}
// truststore
KeyStore ts = loadKeystore("truststore", trustStore, trustPass);
SSLSocketFactory sslf = new SSLSocketFactory(ks, keyPass, ts);
return sslf;
} catch (Exception e) {
throw new AuthConnectionException(
"Failed to create SSLSocketFactory: " + e.getMessage(), e);
}
}
private static KeyStore loadKeystore(String type, String keyStore, String keyPass) throws Exception {
final KeyStore ks = KeyStore.getInstance("jks");
if ((keyStore != null) && !keyStore.isEmpty()) {
File keystoreFile = new File(keyStore);
if (!keystoreFile.canRead()) {
throw new FileNotFoundException(String.format("%s '%s' is not readable", type, keyStore));
}
try (FileInputStream is1 = new FileInputStream(keystoreFile)) {
ks.load(is1, keyPass.toCharArray());
}
catch (Exception e) {
String errorMessage = String.format("Unable to open %s '%s': %s", type, keyStore, e.getMessage());
logger.error(errorMessage);
throw new Exception(errorMessage, e);
}
}
else {
ks.load(null, null);
}
return ks;
}
}

View File

@@ -1,69 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.middleware;
import java.util.concurrent.TimeUnit;
import org.apache.http.conn.ClientConnectionManager;
/**
* A runner to clean the connection pool! There should only be one!
*
* @author liemmn
*
*/
public class HttpPoolCleaner implements Runnable {
private final ClientConnectionManager connMgr;
private long timeBetweenEvictionRunsMillis, minEvictableIdleTimeMillis;
private volatile boolean shutdown;
public HttpPoolCleaner(ClientConnectionManager connMgr,
long timeBetweenEvictionRunsMillis, long minEvictableIdleTimeMillis) {
this.connMgr = connMgr;
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
/**
* Start the cleaner.
*/
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(timeBetweenEvictionRunsMillis);
// Close expired connections
connMgr.closeExpiredConnections();
// Close connections that have been idle longer than x sec
connMgr.closeIdleConnections(minEvictableIdleTimeMillis,
TimeUnit.MILLISECONDS);
}
}
} catch (InterruptedException ex) {
// terminate
}
}
/**
* Shutdown the cleaner.
*/
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}

View File

@@ -1,30 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.middleware;
/**
* Created by johnderr on 6/25/14.
*/
public class ServiceUnavailableException extends RuntimeException {
private static final long serialVersionUID = -2353922744077869466L;
public ServiceUnavailableException(String msg) {
super(msg);
}
public ServiceUnavailableException(String msg, Exception e) {
super(msg, e);
}
}

View File

@@ -1,167 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.middleware;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.common.util.concurrent.UncheckedExecutionException;
import org.apache.http.client.ClientProtocolException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A token-based authentication filter. This filter uses Thrift protocol to
* communicate with the CS server. The token to validate is set via the header
* {@link #TOKEN}.
* <p/>
* A token is required to validate. However, if no token is presented, the
* filter will set the {@link #AUTH_IDENTITY_STATUS} request parameter to
* <code>Invalid</code> and let any other filter downstream to decide what to
* do. For instance, if a downstream filter knows how to deal with signature
* rather than tokens, then it will go ahead and validate with signatures.
* <p/>
* Upon successful validation, all the Auth request parameters will be
* populated, including information such as tenant, user and user roles, and
* passed down to the next filter downstream.
* <p/>
* Upon unsuccessful validation, this filter will terminate the request by
* returning a 401 (unauthorized).
*
* @author liemmn
*/
public class TokenAuth implements Filter, monasca.common.middleware.AuthConstants {
private static final String TOKEN_NOTFOUND = "Bad Request: Token not found in the request";
private final monasca.common.middleware.Config appConfig = Config.getInstance();
private FilterConfig filterConfig;
// Thee faithful logger
private static final Logger logger = LoggerFactory
.getLogger(TokenAuth.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
/**
* {@inheritDoc}
*/
public void destroy() {
FilterUtils.destroyFilter();
}
/**
* {@inheritDoc}
*/
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
// According to CORS spec OPTIONS method does not pass auth info
if (((HttpServletRequest) req).getMethod().equals("OPTIONS")) {
chain.doFilter(req, resp);
return;
}
Object auth = null;
int numberOfTries = 0;
if (!appConfig.isInitialized()) {
appConfig.initialize(filterConfig, req);
}
int retries = appConfig.getRetries();
long pauseTime = appConfig.getPauseTime();
// Extract credential
String token = ((HttpServletRequest) req).getHeader(TOKEN);
if (token == null) {
if (!appConfig.isDelayAuthDecision()) {
logger.debug(HttpServletResponse.SC_UNAUTHORIZED
+ " No token found.");
((HttpServletResponse) resp).sendError(
HttpServletResponse.SC_UNAUTHORIZED, TOKEN_NOTFOUND);
return;
} else {
logger.info("No token found...Skipping");
}
} else {
do {
try {
auth = FilterUtils.getCachedToken(token);
} catch (ServiceUnavailableException e) {
if (numberOfTries < retries) {
FilterUtils.pause(pauseTime);
logger.debug("Retrying connection after "
+ pauseTime + " seconds.");
numberOfTries++;
continue;
} else {
logger.debug("Exhausted retries..");
TokenExceptionHandler handler = TokenExceptionHandler
.valueOf("ServiceUnavailableException");
handler.onException(e, resp, token);
}
return;
} catch (ClientProtocolException e) {
if (numberOfTries < retries) {
FilterUtils.pause(pauseTime);
logger.debug("Retrying connection after "
+ pauseTime + " seconds.");
numberOfTries++;
continue;
} else {
logger.debug("Exhausted retries..");
TokenExceptionHandler handler = TokenExceptionHandler
.valueOf("ClientProtocolException");
handler.onException(e, resp, token);
}
return;
} catch (UncheckedExecutionException e) {
final TokenExceptionHandler handler;
final Exception toHandle;
if ((e.getCause() != null) && e.getCause() instanceof AdminAuthException) {
toHandle = (AdminAuthException)e.getCause();
handler = TokenExceptionHandler.valueOf("AdminAuthException");
}
else if ((e.getCause() != null) && e.getCause() instanceof AuthException) {
toHandle = (AuthException)e.getCause();
handler = TokenExceptionHandler.valueOf("AuthException");
}
else {
toHandle = e;
handler = TokenExceptionHandler.valueOf("UncheckedExecutionException");
}
handler.onException(toHandle, resp, token);
return;
}
} while (auth == null && numberOfTries <= retries);
}
req = FilterUtils.wrapRequest(req, auth);
logger.debug("TokenAuth: Forwarding down stream to next filter/servlet");
// Forward downstream...
chain.doFilter(req, resp);
}
}

View File

@@ -1,80 +0,0 @@
/*
* (C) Copyright 2014,2016 Hewlett Packard Enterprise Development LP
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.middleware;
import com.google.common.cache.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class TokenCache {
private final LoadingCache<String, String> cache;
private final Config appConfig = Config.getInstance();
private AuthClientFactory factory;
private static final Logger logger = LoggerFactory
.getLogger(TokenCache.class);
public TokenCache(final long maxSize, final long timeToExpire) {
factory = appConfig.getFactory();
cache = CacheBuilder.newBuilder().maximumSize(maxSize)
.expireAfterWrite(timeToExpire, TimeUnit.SECONDS)
.build(new CacheLoader<String, String>() {
public String load(String key) throws TException, ClientProtocolException {
String value = null;
AuthClient client = null;
boolean discarded = false;
try {
client = factory.getClient();
value = client.validateTokenForServiceEndpointV3(key);
} catch (ClientProtocolException e) {
factory.discard(client);
logger.warn("Validate token failed with ClientProtocolException. Discarding AuthClient connection from pool to create a new connection.");
logger.warn("ClientProtocolException " + e.getMessage() + " " + e);
discarded = true;
throw e;
} finally {
if (client != null && !discarded)
factory.recycle(client);
}
return value;
}
});
}
public String getToken(String key) throws ClientProtocolException {
String value = null;
try {
value = cache.get(key);
} catch (ExecutionException e) {
logger.info("Failed to get token", e);
throw new ClientProtocolException(e.getMessage(), e);
}
return value;
}
public void put(String key, String value) {
cache.put(key, value);
}
}

View File

@@ -1,154 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.middleware;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.thrift.TException;
import com.google.common.util.concurrent.UncheckedExecutionException;
public enum TokenExceptionHandler {
AuthConnectionException {
@Override
public void onException(Exception e, ServletResponse resp, String token) {
AuthConnectionException ae = (AuthConnectionException) e;
logger.error(ae.getMessage() + " " + ae);
try {
((HttpServletResponse) resp).sendError(
HttpServletResponse.SC_UNAUTHORIZED,
ExceptionHandlerUtil.getStatusText(HttpServletResponse.SC_UNAUTHORIZED)
+ " " + token);
} catch (IOException ie) {
logger.debug("Error in writing the HTTP response "
+ ie.getMessage() + " " + ie);
}
}
},
TException {
@Override
public void onException(Exception e, ServletResponse resp, String token) {
TException t = (TException) e;
logger.error("Thrift Exception " + t.getMessage() + " " + t);
try {
((HttpServletResponse) resp).sendError(
HttpServletResponse.SC_UNAUTHORIZED,
ExceptionHandlerUtil.getStatusText(HttpServletResponse.SC_UNAUTHORIZED)
+ " " + token);
} catch (IOException ie) {
logger.debug("Error in writing the HTTP response "
+ ie.getMessage() + " " + ie);
}
}
},
ClientProtocolException {
@Override
public void onException(Exception e, ServletResponse resp, String token) {
ClientProtocolException t = (ClientProtocolException) e;
logger.error("Http Client Exception " + t.getMessage() + " " + t);
try {
((HttpServletResponse) resp).sendError(
HttpServletResponse.SC_UNAUTHORIZED,
ExceptionHandlerUtil.getStatusText(HttpServletResponse.SC_UNAUTHORIZED)
+ " " + token);
} catch (IOException ie) {
logger.debug("Error in writing the HTTP response "
+ ie.getMessage() + " " + ie);
}
}
},UncheckedExecutionException {
@Override
public void onException(Exception e, ServletResponse resp, String token) {
UncheckedExecutionException t = (UncheckedExecutionException) e;
logger.error("Http Client Exception " + t.getMessage() + " " + t);
try {
((HttpServletResponse) resp).sendError(
HttpServletResponse.SC_UNAUTHORIZED,
ExceptionHandlerUtil.getStatusText(HttpServletResponse.SC_UNAUTHORIZED)
+ " " + token);
} catch (IOException ie) {
logger.debug("Error in writing the HTTP response "
+ ie.getMessage() + " " + ie);
}
}
}
,
AdminAuthException {
@Override
public void onException(Exception e, ServletResponse resp, String token) {
AdminAuthException ae = (AdminAuthException) e;
logger.error(ae.getMessage() + " " + ae);
// Don't want to send any information about the admin auth to clients
String statusText = ExceptionHandlerUtil.getStatusText(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
try {
((HttpServletResponse) resp).sendError(
HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
statusText);
} catch (IOException ie) {
logger.debug("Error in writing the HTTP response "
+ ie.getMessage() + " " + ie);
}
}
}
,
AuthException {
@Override
public void onException(Exception e, ServletResponse resp, String token) {
AuthException ae = (AuthException) e;
logger.info(ae.getMessage() + " " + ae);
String statusText = ae.getMessage();
if (statusText == null || statusText.isEmpty()) {
statusText = ExceptionHandlerUtil.getStatusText(HttpServletResponse.SC_UNAUTHORIZED);
}
try {
((HttpServletResponse) resp).sendError(
HttpServletResponse.SC_UNAUTHORIZED,
statusText + " " + token);
} catch (IOException ie) {
logger.debug("Error in writing the HTTP response "
+ ie.getMessage() + " " + ie);
}
}
}, ServiceUnavailableException {
@Override
public void onException(Exception e, ServletResponse resp, String token) {
ServiceUnavailableException ae = (ServiceUnavailableException) e;
logger.error(ae.getMessage() + " " + ae);
String statusText = ae.getMessage();
if (statusText == null || statusText.isEmpty()) {
statusText = ExceptionHandlerUtil.getStatusText(HttpServletResponse.SC_UNAUTHORIZED);
}
try {
((HttpServletResponse) resp).sendError(
HttpServletResponse.SC_UNAUTHORIZED,
statusText + " " + token);
} catch (IOException ie) {
logger.debug("Error in writing the HTTP response "
+ ie.getMessage() + " " + ie);
}
}
};
final Logger logger = LoggerFactory.getLogger(TokenExceptionHandler.class);
abstract void onException(Exception e, ServletResponse resp, String token);
}

View File

@@ -1,30 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.common.middleware;
/**
* Created by johnderr on 6/25/14.
*/
public class UnavailableException extends RuntimeException {
private static final long serialVersionUID = -2353922744077869466L;
public UnavailableException(String msg) {
super(msg);
}
public UnavailableException(String msg, Exception e) {
super(msg, e);
}
}

View File

@@ -1 +0,0 @@
/target

View File

@@ -1,150 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>monasca-common</groupId>
<artifactId>monasca-common</artifactId>
<version>${computedVersion}</version>
</parent>
<artifactId>monasca-common-model</artifactId>
<packaging>jar</packaging>
<properties>
<antlr.version>4.2</antlr.version>
<jackson.version>2.3.1</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>monasca-common</groupId>
<artifactId>monasca-common-util</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr4-runtime</artifactId>
<version>${antlr.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.2.1</version>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>monasca-common</groupId>
<artifactId>monasca-common-testing</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.antlr</groupId>
<artifactId>antlr4-maven-plugin</artifactId>
<version>${antlr.version}</version>
<configuration>
<sourceDirectory>src/main/resources</sourceDirectory>
<outputDirectory>${project.build.directory}/generated-sources</outputDirectory>
<grammars>AlarmParser.g4</grammars>
</configuration>
<executions>
<execution>
<id>antlr</id>
<phase>generate-sources</phase>
<goals>
<goal>antlr4</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.8</version>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>${project.build.directory}/generated-sources</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludedGroups>performance,functional,integration,database,slow</excludedGroups>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<configuration>
<groups>performance,functional,integration,database,slow</groups>
<skipTests>${skipITs}</skipTests>
</configuration>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
</goals>
<configuration>
<includes>
<include>**/*.class</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-scm-plugin</artifactId>
<configuration>
<tag>${project.version}</tag>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -1,52 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monasca.common.model;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import com.google.common.collect.Sets;
/**
* Compute namespace info.
*/
class ComputeServiceInfo implements ServiceInfo {
private final Set<String> supportedMetricNames = Sets.newHashSet("cpu_time", "cpu_utilization",
"disk_read_ops", "disk_read_ops_count", "disk_write_ops", "disk_write_ops_count",
"disk_read_bytes", "disk_read_bytes_count", "disk_write_bytes", "disk_write_bytes_count",
"net_in_bytes", "net_in_bytes_count", "net_out_bytes", "net_out_bytes_count",
"net_in_packets", "net_in_packets_count", "net_out_packets", "net_out_packets_count",
"net_in_dropped", "net_in_dropped_count", "net_out_dropped", "net_out_dropped_count",
"net_in_errors", "net_in_errors_count", "net_out_errors", "net_out_errors_count");
private final List<String> supportedDims = Arrays.asList("instance_id");
@Override
public String getResourceIdDimension() {
return "instance_id";
}
@Override
public List<String> getSupportedDimensions() {
return supportedDims;
}
@Override
public Set<String> getSupportedMetricNames() {
return supportedMetricNames;
}
}

View File

@@ -1,52 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monasca.common.model;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import com.google.common.collect.Sets;
/**
* Object-store namespace info.
*/
class ObjectStoreServiceInfo implements ServiceInfo {
private final Set<String> supportedMetricNames = Sets.newHashSet("project_write_bytes",
"project_read_bytes", "project_put_ops", "project_get_ops", "container_write_bytes",
"container_read_bytes", "container_put_ops", "container_get_ops",
"container_write_bytes_proxy", "container_read_bytes_proxy", "container_put_ops_proxy",
"container_get_ops_proxy", "project_bytes_used", "container_bytes_used", "number_of_objects",
"number_of_containers", "projects_bytes_used_replica", "container_bytes_used_replica",
"number_of_objects_replica", "number_of_containers_replica");
private final List<String> supportedDims = Arrays.asList("container");
@Override
public String getResourceIdDimension() {
return "container";
}
@Override
public List<String> getSupportedDimensions() {
return supportedDims;
}
@Override
public Set<String> getSupportedMetricNames() {
return supportedMetricNames;
}
}

View File

@@ -1,40 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monasca.common.model;
import java.util.List;
import java.util.Set;
/**
* Provides information for a service.
*/
interface ServiceInfo {
/**
* Returns the dimension name that represents the resource id, else {@code null}.
*/
String getResourceIdDimension();
/**
* Returns the supported dimensions.
*/
List<String> getSupportedDimensions();
/**
* Returns the supported metric names.
*/
Set<String> getSupportedMetricNames();
}

View File

@@ -1,74 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monasca.common.model;
import java.util.HashMap;
import java.util.Map;
/**
* Utilities for working with services.
*/
public class Services {
// HPCS namespace constants
public static final String COMPUTE_SERVICE = "hpcs.compute";
public static final String VOLUME_SERVICE = "hpcs.volume";
public static final String OBJECT_STORE_SERVICE = "hpcs.object-store";
// Other constants
public static final String SERVICE_DIMENSION = "service";
public static final Map<String, ServiceInfo> INFO;
public static final String RESERVED_SERVICE_PREFIX = "hpcs.";
static {
INFO = new HashMap<>();
INFO.put(COMPUTE_SERVICE, new ComputeServiceInfo());
INFO.put(VOLUME_SERVICE, new VolumeServiceInfo());
INFO.put(OBJECT_STORE_SERVICE, new ObjectStoreServiceInfo());
}
/**
* Returns the dimension name that represents the resource id for the {@code service}, else
* {@code null}.
*/
public static String getResourceIdDimension(String service) {
ServiceInfo serviceInfo = INFO.get(service);
return serviceInfo == null ? null : serviceInfo.getResourceIdDimension();
}
/**
* Returns whether the {@code service} is reserved (hpcs).
*/
public static boolean isReserved(String service) {
return service.toLowerCase().startsWith(RESERVED_SERVICE_PREFIX);
}
/**
* Returns whether the {@code dimensionName} is supported for the {@code service}.
*/
public static boolean isValidDimensionName(String service, String dimensionName) {
ServiceInfo serviceInfo = INFO.get(service);
return serviceInfo == null || serviceInfo.getSupportedDimensions().contains(dimensionName);
}
/**
* Returns whether the {@code metricName} is supported for the {@code service}.
*/
public static boolean isValidMetricName(String service, String metricName) {
ServiceInfo serviceInfo = INFO.get(service);
return serviceInfo == null || serviceInfo.getSupportedMetricNames().contains(metricName);
}
}

View File

@@ -1,48 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monasca.common.model;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import com.google.common.collect.Sets;
/**
* Compute namespace info.
*/
class VolumeServiceInfo implements ServiceInfo {
private final Set<String> supportedMetricNames = Sets.newHashSet("volume_read_ops",
"volume_write_ops", "volume_read_bytes", "volume_write_bytes", "volume_read_time",
"volume_write_time", "volume_idle_time");
private final List<String> supportedDims = Arrays.asList("instance_id", "disk");
@Override
public String getResourceIdDimension() {
return "container";
}
@Override
public List<String> getSupportedDimensions() {
return supportedDims;
}
@Override
public Set<String> getSupportedMetricNames() {
return supportedMetricNames;
}
}

View File

@@ -1,57 +0,0 @@
/*
* (C) Copyright 2014, 2016 Hewlett Packard Enterprise Development LP
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monasca.common.model.alarm;
import com.fasterxml.jackson.annotation.JsonCreator;
import monasca.common.util.stats.Statistic;
import monasca.common.util.stats.Statistics.Average;
import monasca.common.util.stats.Statistics.Count;
import monasca.common.util.stats.Statistics.Last;
import monasca.common.util.stats.Statistics.Max;
import monasca.common.util.stats.Statistics.Min;
import monasca.common.util.stats.Statistics.Sum;
public enum AggregateFunction {
MIN, MAX, SUM, COUNT, AVG, LAST;
@JsonCreator
public static AggregateFunction fromJson(String text) {
return valueOf(text.toUpperCase());
}
@Override
public String toString() {
return name().toLowerCase();
}
public Class<? extends Statistic> toStatistic() {
if (AggregateFunction.AVG.equals(this))
return Average.class;
if (AggregateFunction.COUNT.equals(this))
return Count.class;
if (AggregateFunction.SUM.equals(this))
return Sum.class;
if (AggregateFunction.MIN.equals(this))
return Min.class;
if (AggregateFunction.MAX.equals(this))
return Max.class;
if (AggregateFunction.LAST.equals(this))
return Last.class;
return null;
}
}

View File

@@ -1,198 +0,0 @@
/*
* (C) Copyright 2014, 2016 Hewlett Packard Enterprise Development LP
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monasca.common.model.alarm;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import monasca.common.util.Stack;
/**
* Alarm expression value object.
*/
public class AlarmExpression {
private final String expression;
/** Postfix list of expression elements. */
private final List<Object> elements;
private volatile List<AlarmSubExpression> subExpressions;
/**
* Creates an AlarmExpression for the {@code expression} string.
*
* @throws IllegalArgumentException if the {@code expression} is invalid
*/
public AlarmExpression(String expression) {
this.expression = expression;
AlarmExpressionParser parser = new AlarmExpressionParser(new CommonTokenStream(
new AlarmExpressionLexer(new ANTLRInputStream(expression))));
parser.removeErrorListeners();
parser.addErrorListener(new AlarmExpressionErrorListener());
parser.setBuildParseTree(true);
ParserRuleContext tree = parser.start();
AlarmSubExpressionListener listener = new AlarmSubExpressionListener(false);
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(listener, tree);
elements = listener.getElements();
}
/**
* Creates an AlarmExpression for the {@code expression} string.
*
* @throws IllegalArgumentException if the {@code expression} is invalid
*/
@JsonCreator
public static AlarmExpression of(String expression) {
return new AlarmExpression(expression);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AlarmExpression other = (AlarmExpression) obj;
if (elements == null) {
if (other.elements != null)
return false;
} else if (!elements.equals(other.elements))
return false;
return true;
}
/**
* Evaluates the {@code subExpressionValues} against the expression, returning true if the values
* evaluate to true for the expression, else false.
*
* @throws IllegalArgumentException if any of the expected sub-expressions cannot be found in
* {@code subExpressionValues}
*/
public boolean evaluate(Map<AlarmSubExpression, Boolean> subExpressionValues) {
Stack<Object> stack = new Stack<Object>();
for (Object element : elements) {
if (element instanceof AlarmSubExpression) {
Boolean value = subExpressionValues.get(element);
if (value == null)
throw new IllegalArgumentException("Expected sub-expression was not found for " + element);
stack.push(value);
} else {
BooleanOperator operator = (BooleanOperator) element;
Boolean operandA = (Boolean) stack.pop();
Boolean operandB = (Boolean) stack.pop();
stack.push(operator.evaluate(operandA, operandB));
}
}
return (Boolean) stack.pop();
}
/**
* Returns the alarm's expression.
*/
@JsonIgnore
public String getExpression() {
return expression;
}
/** Returns a boolean tree representation of the alarm expression. */
@JsonIgnore
public Object getExpressionTree() {
Stack<Object> stack = new Stack<Object>();
for (Object element : elements) {
if (element instanceof AlarmSubExpression) {
stack.push(element);
} else {
BooleanOperator operator = (BooleanOperator) element;
Object operandA = stack.pop();
Object operandB = stack.pop();
BooleanExpression expr = null;
if (operandB instanceof BooleanExpression
&& ((BooleanExpression) operandB).operator.equals(operator)) {
expr = (BooleanExpression) operandB;
expr.operands.add(operandA);
} else
expr = new BooleanExpression(operator, operandB, operandA);
stack.push(expr);
}
}
return stack.pop();
}
/**
* Returns the sub expressions for the expression in the order that they appear.
*/
public List<AlarmSubExpression> getSubExpressions() {
if (subExpressions != null)
return subExpressions;
List<AlarmSubExpression> subExpressions = new ArrayList<>(elements.size());
for (Object element : elements)
if (element instanceof AlarmSubExpression)
subExpressions.add((AlarmSubExpression) element);
this.subExpressions = subExpressions;
return subExpressions;
}
/**
* Returns if expression is deterministic or non-deterministic.
*
* All {@link AlarmSubExpression} must be deterministic in order for entire expression
* to be such. Otherwise expression is non-deterministic.
*
* @return true/false
*
* @see #getSubExpressions()
* @see AlarmSubExpression#DEFAULT_DETERMINISTIC
*/
public boolean isDeterministic() {
final List<AlarmSubExpression> subExpressions = this.getSubExpressions();
if (subExpressions == null || subExpressions.isEmpty()) {
return AlarmSubExpression.DEFAULT_DETERMINISTIC;
}
for (final AlarmSubExpression alarmSubExpression : subExpressions) {
if (!alarmSubExpression.isDeterministic()) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((elements == null) ? 0 : elements.hashCode());
return result;
}
@Override
public String toString() {
return String.format("AlarmExpression [elements=%s]", elements);
}
}

View File

@@ -1,30 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monasca.common.model.alarm;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
class AlarmExpressionErrorListener extends BaseErrorListener {
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
int charPositionInLine, String msg, RecognitionException e) {
throw new IllegalArgumentException(String.format("Syntax Error [%d] %s: %s",
charPositionInLine, msg, offendingSymbol));
}
}

View File

@@ -1,29 +0,0 @@
/*
* (C) Copyright 2014,2016 Hewlett Packard Enterprise Development LP
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monasca.common.model.alarm;
public class AlarmNotificationMethodType {
public static final String EMAIL = "EMAIL";
public static final String WEBHOOK = "WEBHOOK";
public static final String PAGERDUTY = "PAGERDUTY";
public static String valueOf(String alarmType)
{
return alarmType.toUpperCase();
}
}

View File

@@ -1,67 +0,0 @@
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monasca.common.model.alarm;
import com.fasterxml.jackson.annotation.JsonCreator;
/**
* Alarm operator.
*/
public enum AlarmOperator {
LT("<"), LTE("<="), GT(">"), GTE(">=");
private final String operatorSymbols;
private AlarmOperator(String operatorSymbols) {
this.operatorSymbols = operatorSymbols;
}
@JsonCreator
public static AlarmOperator fromJson(String text) {
return valueOf(text.toUpperCase());
}
public static AlarmOperator reverseOperator(AlarmOperator op) {
if (op == LT)
return GT;
if (op == GT)
return LT;
if (op == LTE)
return GTE;
return LTE;
}
public boolean evaluate(double lhs, double rhs) {
switch (this) {
case LT:
return lhs < rhs;
case LTE:
return lhs <= rhs;
case GT:
return lhs > rhs;
case GTE:
return lhs >= rhs;
default:
return false;
}
}
@Override
public String toString() {
return operatorSymbols;
}
}

Some files were not shown because too many files have changed in this diff Show More