1 Star 0 Fork 0

阿布/api

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

Hygieia Api

Build Status Quality Gate Status Total alertsLanguage grade: JavaMaven Central License Gitter Chat

All About Hygieia API - Learn how to install and configure Hygieia API

Hygieia API layer contains all the typical REST API services that work with the source system data (collected by service tasks). The Hygieia API layer is an abstraction of the local and source system data layer. All API REST controllers are generic to their purpose - they are not specific to any given source system.

For detailed information on APIs, see the Swagger documentation available at http://[your-domain].com/api/swagger/index.html#.

Hygieia uses Spring Boot to package the API as an executable JAR file with dependencies.

Table of Contents

Setup Instructions

  • Step 1 - Artifact Preparation:

    Please review the two options in Step 1 to find the best fit for you.

    Option 1 - Download the artifact:

    You can download the SNAPSHOTs from the SNAPSHOT directory here or from the maven central repository here.

    Option 2 - Build locally:

    To configure the Hygieia API layer, git clone the api repo. Then, execute the following steps:

    To package the API source code into an executable JAR file, run the Maven build from the \api directory of your source code installation:

    mvn install
    

    The output file api.jar is generated in the \api\target folder.

    Once you have chosen an option in Step 1, please proceed:

  • Step 2: Set Parameters in the API Properties File

    Set the configurable parameters in the api.properties section to connect to the Dashboard MongoDB database instance, including properties required by the API module. To configure the parameters, refer to the API properties section.

    For more information about the server configuration, see the Spring Boot documentation.

  • Step 3: Run the API

    To run the executable file, change directory to 'api\target' and then execute the following command from the command prompt:

    java -jar api.jar --spring.config.location=C:\[path to api.properties file] -Djasypt.encryptor.password=hygieiasecret
    

    Verify API access from the web browser using the url: http://localhost:8080/api/ping.

    By default, the server starts at port 8080 and uses the context path \api. You can configure these values in the api.properties file for the following properties:

    server.contextPath=/api
    server.port=8080
    

    Note: The 'jasypt.encryptor.password' system property is used to decrypt the database password.

API Properties Section

The sample api.properties lists parameters with sample values to configure the API layer. Set the parameters based on your environment setup.

# api.properties
dbname=dashboarddb
dbusername=dashboarduser[MogoDB Database Username, defaults to empty]
dbpassword=dbpassword[MongoDB Database Password, defaults to empty]
dbhost=[Host on which MongoDB is running, defaults to localhost]
dbport=[Port on which MongoDB is listening, defaults to 27017]
dbreplicaset=[false if you are not using MongoDB replicaset]
dbhostport=[host1:port1,host2:port2,host3:port3]
server.contextPath=[Web Context path, if any]
server.port=[Web server port - default is 8080]
logRequest=false
logSplunkRequest=false
corsEnabled=false
corsWhitelist=http://domain1.com:port,http://domain2.com:port
version.number=@application.version.number@

auth.expirationTime=[JWT expiration time in milliseconds]
auth.secret=[Secret Key used to validate the JWT tokens]
auth.authenticationProviders=[Authentication types you would like to enable, defaults to STANDARD, ex: STANDARD,LDAP]
auth.ldapServerUrl=[LDAP Server URL, including port of your LDAP server]
auth.ldapUserDnPattern=[LDAP User Dn Pattern, where the username is replaced with '{0}']

# LDAP Server URL, including port of your LDAP server
auth.ldapServerUrl=[ldap://company.com:389]

# If using standard LDAP
# LDAP User Dn Pattern, where the username is replaced with '{0}'
auth.ldapUserDnPattern=[uid={0},OU=Users,dc=your,dc=company,dc=com]

# If using ActiveDirectory
# This will be the domain part of your userPrincipalName
auth.adDomain=[company.com]
# This will be your root dn
auth.adRootDn=[dc=your,dc=company,dc=com]
# This will be your active directory URL (required for AD)
auth.adUrl=[Need an example]

monitor.proxy.host=[hostname of proxy server]
monitor.proxy.type=[http|socks|direct]
monitor.proxy.port=[port enabled on proxy server]
monitor.proxy.username=[proxy username]
monitor.proxy.password=[proxy password]

# This will be the page size for pagination on Hygieia landing page. If this property is not set, the default value is set to 10.
pageSize=[Integer value]

# API token generated for basic authentication to secure APIs.
key=[api token]

# SSO properties with header values from UI layer
auth.userEid=[name of the header containing EID]
auth.userEmail=[name of the header containing user's email]
auth.userFirstName=[name of the header containing user's first name]
auth.userLastName=[name of the header containing user's last name]
auth.userMiddelInitials=[name of the header containing user's middle name]
auth.userDisplayName=[name of the header containing user's display name]

# Github sync api settings 

# List of not built commits
githubSyncSettings.notBuiltCommits;

# Maximum history of days to sync from current time. Default to 60 days
githubSyncSettings.firstRunHistoryDays;

# Offset time from last updated // 10 mins default
githubSyncSettings.offsetMinutes;

# Total fetch count // Default to 100
githubSyncSettings.fetchCount;

# Commits and pull sync time // Default to 86400000ms - 1 day in milliseconds
githubSyncSettings.commitPullSyncTime;

In addition to these properties, add in any additional parameters that your environment may need. We used Github sync api settings as an example, but you will customize based on your setup.

All values in the api.properties file are optional. For instance, if you have MongoDB installed with no authorization, you must be able to run the API even without the properties file.

Note the following:

  • in the api.properties file, if you do not define the value of dbusername, then Hygieia skips the MongoDB authorization process.
  • Specify the Expiration Time to see content on your dashboard. If you do not specify a value for Expiration Time, then the token permanently expires, and users will not be able to see any content on the dashboard. However, the application start-up is not impacted by this action.
  • If you do not enter a value for the secret password, then the system generates a random key. To allow multiple instances of the API to validate the same JWT token, provide the same key for each running instance of the API.
  • If you do not provide values for the LDAP parameters, then LDAP is not available as an authentication provider for your application.
  • When enabling proxy support for the monitor widget, if you do not specify, then system ignores the rest of the monitor.proxy arguments. If you are using Docker, then by default, the port is 80 and the type is HTTP. When you run the application locally, you must specify the values for these properties (i.e., for the port and the type).

Docker Image for API

You can install Hygieia by using a docker image from docker hub. This section gives detailed instructions on how to download and run with Docker.

  • Step 1: Download

    Navigate to the api docker hub location here and download the latest image (most recent version is preferred). Tags can also be used, if needed.

  • Step 2: Run with Docker

    Docker run -e SKIP_PROPERTIES_BUILDER=true -v properties_location:/hygieia/config image_name

    • -e SKIP_PROPERTIES_BUILDER=true
      indicates whether you want to supply a properties file for the java application. If false/omitted, the script will build a properties file with default values
    • -v properties_location:/hygieia/config
      if you want to use your own properties file that located outside of docker container, supply the path here.
      • Example: -v /Home/User/Document/application.properties:/hygieia/config

Basic Authentication for Secure APIs

To carry out basic authentication for secure APIs, execute the following steps:

  1. From the admin menu, generate an 'apiToken' for an 'apiUser'.

  2. Create a POST request with the following two headers and make a REST call for secured API.

    • Add Authorization header
    String passwordIsAuthToken = "PasswordIsAuthToken:{\"apiKey\":\"" + <generated apitoken> + "\"}";
    byte[] encodedAuth = Base64.encodeBase64(passwordIsAuthToken.getBytes(StandardCharsets.US_ASCII));
    String authHeader = "apiToken " + new String(encodedAuth);
    Authorization: <authHeader>
    
    • Add apiUser header
    apiUser <apiuser>
    

Rundeck Webhook Integration

Hygieia supports registering deployments using the Rundeck webhook. In the Rundeck job configuration, select Send Notification? and check the on success and on failure webhook checkboxes. Configure the URL as http://<apihost>:<apiport>/api/deploy/rundeck. To provide configurability, a few additional features can be added to the webhook URL to locate the proper data for registering the deployment.

You can add additional request parameters to the webhook URL to provide input on locating this data. You can specify these parameters as optionName=<value> or optionNameParam=<value>. When the webhook URL provides a parameter in the form optionName=<value>, it will use the value provided in the parameter for the field in Hygieia. When the webhook URL provides a request parameter in the form optionNameParam=<value>, the option named <value> is queried and the value of that option in the job is used to populate that field. Otherwise, the default values are used.

You can add additional request parameters for the following options:

  • appName
  • envName (required)
  • artifactName (required)
  • artifactGroup
  • artifactVersion
  • niceName - Name that appears for the collector in Hygieia UI.

For example, to set the artifactName based on the deploymentUnit option in the Rundeck job, the webhook URL is: http://<apihost>:<apiport>/api/deploy/rundeck?artifactNameParam=deploymentUnit. To set the envName to be QA every time this job runs, the webhook URL is: http://<apihost>:<apiport>/api/deploy/rundeck?envName=QA.

If these values are not provided, the webhook first queries the job to see if it has an option that matches the name of the field. If not, it will look through the following possibilities:

  • appName
    • hygieiaAppName
  • envName
    • environment
    • env
    • hygieiaEnvName
  • artifactName
    • artifactId
    • hygieiaArtifactName
  • artfactGroup
    • group
    • hygieiaArtifactGroup
  • niceName
    • hygieiaNiceName

For the required fields, if the methods to locate values is exhausted, the webhook endpoint fails and deployment is not registered. An exception appears in the Hygieia API log with the field name that is missing from the job. If appName is not set, it is set based on the Rundeck project name.

Troubleshooting Instructions

Scenario 1

The API module fails to launch with the following error:

Error creating bean with name 'dashboardRepository': Invocation of init method failed; nested exception is org.springframework.dao.DuplicateKeyException: Write failed with error code 11000 and error message 'null'

In this case, execute the following steps:

  • Step 1 : Save the following lines to a file called fixdups.js:

    var dupsExist = false;
    db.dashboards.aggregate([
      { $group: {
    	_id: { firstField: "$title"},
    	uniqueIds: { $addToSet: "$_id" },
    	count: { $sum: 1 }
      }},
      { $match: {
    	count: { $gt: 1 }
      }}
    ]).forEach(
    	function(myDoc) {
    		dupsExist = true;
    		print(myDoc.count + " dashboards have the same title " + myDoc._id.firstField);
    		var arr = myDoc.uniqueIds;
    		for(i=0; i<arr.length; i++) {
    			var oneDash = db.dashboards.findOne({_id: arr[i]});
    			var newTitle = oneDash.title + "_" + oneDash.owner + "_" + i;
    			print("Rename " + oneDash.title + " to " + newTitle);
    			db.dashboards.update({_id: arr[i]},{$set:{title: newTitle}});
    		}
    	}
    );
    
    if (!dupsExist) {
    	print("No duplicate title dashboards found.");
    }
    
  • Step 2 : Run the following in the command line:

    mongo <dbhost>:<dbport>/<dbname> fixdups.js
    

Scenario 2

The Hygieia dashboard does not show up for a specific login type you created, before introducing Auth type as 'STANDARD' or 'LDAP'.

In this case, execute the following steps:

  • Step 1 : Save the following lines to a file called fixAuths.js

    var count = 0;
    db.dashboards.aggregate([{$match:{"owners.authType": {$exists : false}}}]).forEach(
    	function(myDoc) {
    		var ownerName = myDoc.owner;
    		print("Updating owner information for dashboard title --"+ myDoc.title+ "  owner name --"+myDoc.owner);
    		db.dashboards.update(
    			{ _id: myDoc._id},
    			{
    				$push: {
    					owners: {
    						$each: [{username: ownerName, authType: "STANDARD"}]
    					}
    				}
    			}
    		)
    		db.dashboards.update({_id: myDoc._id},{$unset: {owner:1}},{multi: true});
    		count++;
    	}
    );
    print(count+" dashboards updated successfully");
    
  • Step 2 : Run the following in command line:

    mongo <dbhost>:<dbport>/<dbname> fixAuths.js
    
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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.

简介

Hygieia api layer (pre Spring 5) 展开 收起
README
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yingmingzongyu/api.git
git@gitee.com:yingmingzongyu/api.git
yingmingzongyu
api
api
master

搜索帮助