├── .gitattributes
├── assembly
├── bin
│ ├── keystore
│ ├── version-map.yaml
│ ├── stop-all.sh
│ ├── backup.sh
│ ├── clear.sh
│ ├── schedule-backup.sh
│ ├── start-all.sh
│ ├── hugegraph
│ ├── deploy.sh
│ ├── release.sh
│ └── util.sh
├── conf
│ └── hugegraph.truststore
├── travis
│ ├── conf
│ │ ├── rest-server.properties
│ │ ├── graphs
│ │ │ └── hugegraph.properties
│ │ └── gremlin-server.yaml
│ └── install-hugegraph-from-source.sh
└── descriptor
│ └── assembly.xml
├── src
├── test
│ ├── resources
│ │ └── auth
│ │ │ ├── auth_groups.txt
│ │ │ ├── auth_users.txt
│ │ │ ├── auth_belongs.txt
│ │ │ ├── auth_users_conflict.txt
│ │ │ ├── auth_accesses.txt
│ │ │ └── auth_targets.txt
│ └── java
│ │ └── com
│ │ └── baidu
│ │ └── hugegraph
│ │ └── test
│ │ ├── functional
│ │ ├── FuncTestSuite.java
│ │ ├── AuthTest.java
│ │ ├── AuthBackupTest.java
│ │ ├── CommandTest.java
│ │ └── AuthRestoreTest.java
│ │ └── util
│ │ └── FileUtil.java
└── main
│ ├── java
│ └── com
│ │ └── baidu
│ │ └── hugegraph
│ │ ├── constant
│ │ ├── Constants.java
│ │ └── AuthRestoreConflictStrategy.java
│ │ ├── formatter
│ │ ├── JsonFormatter.java
│ │ ├── Formatter.java
│ │ └── kgdumper
│ │ │ ├── ComputeSign.java
│ │ │ ├── DumpKGFormatter.java
│ │ │ └── SignFS64.java
│ │ ├── exception
│ │ ├── ToolsException.java
│ │ └── ExitException.java
│ │ ├── base
│ │ ├── Directory.java
│ │ ├── ToolManager.java
│ │ ├── Printer.java
│ │ ├── RetryManager.java
│ │ ├── ToolClient.java
│ │ ├── LocalDirectory.java
│ │ └── HdfsDirectory.java
│ │ ├── manager
│ │ ├── GraphsManager.java
│ │ ├── GremlinManager.java
│ │ ├── TasksManager.java
│ │ ├── DumpGraphManager.java
│ │ ├── RestoreManager.java
│ │ └── BackupRestoreBaseManager.java
│ │ ├── util
│ │ └── ToolUtil.java
│ │ └── structure
│ │ └── JsonGraph.java
│ └── resources
│ └── log4j2.xml
├── .gitignore
├── .github
├── ISSUE_TEMPLATE
│ ├── config.yml
│ ├── feature_request.yml
│ ├── bug_report.yml
│ └── question_ask.yml
└── workflows
│ ├── stale.yml
│ └── ci.yml
├── .travis.yml
├── ci.yml
├── README.md
├── checkstyle.xml
└── LICENSE
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text=auto !eol
2 |
--------------------------------------------------------------------------------
/assembly/bin/keystore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/apache/incubator-hugegraph-tools/HEAD/assembly/bin/keystore
--------------------------------------------------------------------------------
/assembly/conf/hugegraph.truststore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/apache/incubator-hugegraph-tools/HEAD/assembly/conf/hugegraph.truststore
--------------------------------------------------------------------------------
/src/test/resources/auth/auth_groups.txt:
--------------------------------------------------------------------------------
1 | {"id":"-66:test_group6","group_name":"test_group6","group_description":"user is conflict check user restore test test","group_create":"2020-11-27 20:08:21.270","group_update":"2020-11-27 20:08:21.270","group_creator":"admin"}
--------------------------------------------------------------------------------
/src/test/resources/auth/auth_users.txt:
--------------------------------------------------------------------------------
1 | {"id":"-66:test_user1","user_name":"test_user1","user_password":"$2a$04$vXkz8UYV7Gwagj6zA1ifNuSQfAmzuYb2tXdqDoWKEG.nYVc186JXO","user_create":"2020-11-30 22:26:42.225","user_update":"2020-11-30 22:26:42.225","user_creator":"admin"}
--------------------------------------------------------------------------------
/src/test/resources/auth/auth_belongs.txt:
--------------------------------------------------------------------------------
1 | {"id":"S-66:test_user1>-82>>S-66:test_group6","user":"-66:test_user1","group":"-66:test_group6","belong_description":"restore test","belong_create":"2020-12-01 09:44:40.117","belong_update":"2020-12-01 09:44:40.117","belong_creator":"admin"}
--------------------------------------------------------------------------------
/src/test/resources/auth/auth_users_conflict.txt:
--------------------------------------------------------------------------------
1 | {"id":"-63:admin","user_name":"admin","user_phone":"13255447788","user_password":"$2a$04$1tl1IKTncjcmMojLdt2qO.EAJ1w0TGunAZ5IJXWwBgPLvTPk366Ly","user_create":"2020-11-11 11:41:12.254","user_update":"2020-11-11 11:41:12.254","user_creator":"system"}
--------------------------------------------------------------------------------
/src/test/resources/auth/auth_accesses.txt:
--------------------------------------------------------------------------------
1 | {"id":"S-66:test_group6>-88>11>S-66:test_target1","group":"-66:test_group6","target":"-66:test_target1","access_permission":"READ","access_description":"test","access_create":"2020-11-11 15:54:54.008","access_update":"2020-11-18 15:01:13.518","access_creator":"admin"}
--------------------------------------------------------------------------------
/src/test/resources/auth/auth_targets.txt:
--------------------------------------------------------------------------------
1 | {"id":"-66:test_target1","target_name":"test_target1","target_graph":"hugegraph","target_url":"127.0.0.1:8080","target_resources":[{"type":"ALL","label":"*","properties":null}],"target_create":"2020-11-11 15:32:01.192","target_update":"2020-11-11 15:32:01.192","target_creator":"admin"}
--------------------------------------------------------------------------------
/assembly/bin/version-map.yaml:
--------------------------------------------------------------------------------
1 | version-0.6: {
2 | server: 0.6.1,
3 | studio: 0.6.1
4 | },
5 | version-0.7: {
6 | server: 0.7.4,
7 | studio: 0.7.0
8 | },
9 | version-0.8: {
10 | server: 0.8.0,
11 | studio: 0.8.0
12 | },
13 | version-0.9: {
14 | server: 0.9.2,
15 | studio: 0.9.0
16 | },
17 | version-0.10: {
18 | server: 0.10.4,
19 | studio: 0.10.0
20 | }
21 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # maven ignore
2 | target/
3 | output/
4 | # *.jar
5 | *.war
6 | *.zip
7 | *.tar
8 | *.tar.gz
9 | tree.txt
10 |
11 | # eclipse ignore
12 | .settings/
13 | .project
14 | .classpath
15 |
16 | # idea ignore
17 | .idea/
18 | *.ipr
19 | *.iml
20 | *.iws
21 |
22 | # temp ignore
23 | *.log
24 | *.cache
25 | *.diff
26 | *.patch
27 | *.tmp
28 |
29 | # system ignore
30 | .DS_Store
31 | Thumbs.db
32 |
33 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/config.yml:
--------------------------------------------------------------------------------
1 | blank_issues_enabled: false
2 |
3 | # 设置提 issue 前的参考文档
4 | contact_links:
5 | - name: HugeGraph Tools Doc
6 | url: https://hugegraph.github.io/hugegraph-doc/quickstart/hugegraph-tools.html
7 | about: Please search question here before opening a new issue
8 | - name: HugeGraph API Doc
9 | url: https://hugegraph.github.io/hugegraph-doc/clients/hugegraph-api.html
10 | about: Please search usage here before opening a new issue
11 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.yml:
--------------------------------------------------------------------------------
1 | name: Feature request (新需求 / 功能)
2 | description: Give an idea for HugeGraph
3 | title: '[Feature] describe the new feature'
4 | labels:
5 | - feature
6 |
7 | body:
8 | - type: textarea
9 | attributes:
10 | label: Feature Description (功能描述)
11 | description: |
12 | > 请简要描述新功能 / 需求的使用场景或上下文, 最好能给个具体的例子说明
13 | placeholder: type the feature description here
14 | validations:
15 | required: true
16 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 |
3 | jdk:
4 | - openjdk8
5 |
6 | sudo: required
7 |
8 | branches:
9 | only:
10 | - master
11 | - /^release-.*$/
12 | - /^test-.*$/
13 |
14 | install: mvn compile -Dmaven.javadoc.skip=true | grep -v "Downloading\|Downloaded"
15 |
16 | before_script:
17 | - $TRAVIS_DIR/install-hugegraph.sh $TRAVIS_BRANCH | grep -v "Downloading\|Downloaded"
18 |
19 | script:
20 | - mvn test -Dtest=FuncTestSuite
21 |
22 | after_success:
23 | - bash <(curl -s https://codecov.io/bash)
24 |
25 | env:
26 | global:
27 | - TRAVIS_DIR=assembly/travis
28 |
--------------------------------------------------------------------------------
/ci.yml:
--------------------------------------------------------------------------------
1 | Global:
2 | tool : build_submitter
3 | languages:
4 | # Java Version: 1.7, 1.8, 9, 10
5 | - language : java
6 | version : 1.8
7 | envs:
8 | # Maven Version: 3.0.4, 3.1.1, 3.2.5, 3.3.9, 3.5.3
9 | - env : maven
10 | version : 3.3.9
11 | Default:
12 | profile : [dev]
13 | Profiles:
14 | - profile:
15 | name : dev
16 | env : CENTOS6U3
17 | command : sh ./build.sh
18 | release : false
19 | - profile:
20 | name : publish
21 | env : cmc_standard
22 | command : mvn -U clean deploy -Prelease
23 | release : true
--------------------------------------------------------------------------------
/assembly/bin/stop-all.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | function abs_path() {
4 | SOURCE="${BASH_SOURCE[0]}"
5 | while [ -h "$SOURCE" ]; do
6 | DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
7 | SOURCE="$(readlink "$SOURCE")"
8 | [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
9 | done
10 | echo "$( cd -P "$( dirname "$SOURCE" )" && pwd )"
11 | }
12 |
13 | BIN=`abs_path`
14 | cd $BIN
15 |
16 | . util.sh
17 |
18 | SLEEP_INTERVAL_S=2
19 | SHUTDOWN_TIMEOUT_S=10
20 |
21 | kill_process 'HugeGraphServer'
22 | wait_for_shutdown 'HugeGraphServer' $SHUTDOWN_TIMEOUT_S
23 | kill_process 'HugeGraphStudio'
24 | wait_for_shutdown 'HugeGraphStudio' $SHUTDOWN_TIMEOUT_S
25 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # HugeGraph-Tools
2 |
3 | HugeGraph-Tools is a customizable command line utility for deploying, managing and backing up/restoring graphs from HugeGraph database.
4 |
5 | ## Main Functions
6 |
7 | - Deploy and clear HugeGraph-Server and HugeGraph-Studio automatically.
8 | - Manage graphs and query with Gremlin from multiple HugeGraph databases essily.
9 | - Backup/restore graph schema and graph data from/to HugeGraph databases conveniently, also support backup periodically
10 |
11 | ## Learn More
12 |
13 | The [project homepage](https://hugegraph.github.io/hugegraph-doc/quickstart/hugegraph-tools.html) contains more information about HugeGraph-Tools.
14 |
15 | ## License
16 |
17 | HugeGraph-Tools is licensed under Apache 2.0 License.
--------------------------------------------------------------------------------
/assembly/bin/backup.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | function abs_path() {
4 | SOURCE="${BASH_SOURCE[0]}"
5 | while [ -h "$SOURCE" ]; do
6 | DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
7 | SOURCE="$(readlink "$SOURCE")"
8 | [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
9 | done
10 | echo "$( cd -P "$( dirname "$SOURCE" )" && pwd )"
11 | }
12 |
13 | BIN=`abs_path`
14 | cd $BIN
15 |
16 | # do backup
17 | bash $BIN/hugegraph ${*:1:$(($#-2))}"/hugegraph-backup-`date +%y%m%d%H%M`/"
18 |
19 | DIR=`eval echo '${'$(($#-2))'}'`
20 | NUM=`eval echo '${'$#'}'`
21 | # delete redundant backups if needed
22 | for i in `ls -lt $DIR | grep -v "total" | grep "hugegraph-backup-" | awk -v awkNum="$NUM" '{if(NR>awkNum){print $9}}'`
23 | do
24 | rm -fr "$DIR/$i"
25 | done
26 |
--------------------------------------------------------------------------------
/src/test/java/com/baidu/hugegraph/test/functional/FuncTestSuite.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.test.functional;
21 |
22 | import org.junit.runner.RunWith;
23 | import org.junit.runners.Suite;
24 |
25 | @RunWith(Suite.class)
26 | @Suite.SuiteClasses({
27 | AuthBackupTest.class,
28 | AuthRestoreTest.class,
29 | CommandTest.class
30 | })
31 | public class FuncTestSuite {
32 | }
33 |
--------------------------------------------------------------------------------
/.github/workflows/stale.yml:
--------------------------------------------------------------------------------
1 | name: Mark stale issues and pull requests
2 |
3 | on:
4 | schedule:
5 | - cron: "0 21 * * *"
6 |
7 | jobs:
8 | stale:
9 |
10 | runs-on: ubuntu-latest
11 | permissions:
12 | issues: write
13 | pull-requests: write
14 |
15 | steps:
16 | - uses: actions/stale@v3
17 | with:
18 | repo-token: ${{ secrets.GITHUB_TOKEN }}
19 | stale-issue-message: 'Due to the lack of activity, the current issue is marked as stale and will be closed after 20 days, any update will remove the stale label'
20 | stale-pr-message: 'Due to the lack of activity, the current pr is marked as stale and will be closed after 180 days, any update will remove the stale label'
21 | stale-issue-label: 'inactive'
22 | stale-pr-label: 'inactive'
23 | exempt-issue-labels: 'feature,bug,enhancement,improvement,wontfix,todo'
24 |
25 | days-before-issue-stale: 15
26 | days-before-issue-close: 20
27 | days-before-pr-stale: 30
28 | days-before-pr-close: 180
29 | operations-per-run: 10
30 | start-date: '2018-12-01T00:00:00Z'
31 |
32 | exempt-all-assignees: true
33 | remove-stale-when-updated: true
34 | exempt-all-pr-milestones: true
35 | delete-branch: false
36 | enable-statistics: true
37 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/hugegraph/constant/Constants.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.constant;
21 |
22 | public final class Constants {
23 |
24 | public static final int EXIT_CODE_ERROR = -1;
25 | public static final int EXIT_CODE_NORMAL = 0;
26 |
27 | public static final String INPUT_YES = "yes";
28 | public static final String INPUT_Y= "y";
29 | public static final String COMMAND_HELP = "help";
30 | public static final String COMMAND_THROW_MODE = "--throw-mode";
31 | }
32 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: hugegraph-tools ci
2 | on:
3 | push:
4 | branches:
5 | - master
6 | - /^release-.*$/
7 | - /^test-.*$/
8 | pull_request:
9 | branches:
10 | - master
11 | - /^release-.*$/
12 | - /^test-.*$/
13 | jobs:
14 | build:
15 | runs-on: ubuntu-20.04
16 | env:
17 | TRAVIS_DIR: assembly/travis
18 | COMMIT_ID: 1d031c5905cbef008dd5fb468576b0e6a9445181
19 | steps:
20 | - name: Install JDK 8
21 | uses: actions/setup-java@v2
22 | with:
23 | java-version: '8'
24 | distribution: 'zulu'
25 | - name: Cache Maven packages
26 | uses: actions/cache@v2
27 | with:
28 | path: ~/.m2
29 | key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
30 | restore-keys: ${{ runner.os }}-m2
31 | - name: Checkout
32 | uses: actions/checkout@v2
33 | with:
34 | fetch-depth: 2
35 | - name: Compile
36 | run: |
37 | mvn compile -Dmaven.javadoc.skip=true
38 | - name: Prepare env and service
39 | run: |
40 | $TRAVIS_DIR/install-hugegraph-from-source.sh $COMMIT_ID
41 | - name: Run test
42 | run: |
43 | mvn test -Dtest=FuncTestSuite
44 | - name: Upload coverage to Codecov
45 | uses: codecov/codecov-action@v1
46 | with:
47 | file: target/jacoco.xml
48 |
--------------------------------------------------------------------------------
/assembly/travis/conf/rest-server.properties:
--------------------------------------------------------------------------------
1 | # bind url
2 | restserver.url=http://127.0.0.1:8080
3 | # gremlin server url, need to be consistent with host and port in gremlin-server.yaml
4 | #gremlinserver.url=http://127.0.0.1:8182
5 |
6 | graphs=./conf/graphs
7 |
8 | # The maximum thread ratio for batch writing, only take effect if the batch.max_write_threads is 0
9 | batch.max_write_ratio=80
10 | batch.max_write_threads=0
11 |
12 | # authentication configs
13 | # choose 'com.baidu.hugegraph.auth.StandardAuthenticator' or 'com.baidu.hugegraph.auth.ConfigAuthenticator'
14 | auth.authenticator=com.baidu.hugegraph.auth.StandardAuthenticator
15 |
16 | # for StandardAuthenticator mode
17 | #auth.graph_store=hugegraph
18 | # auth client config
19 | #auth.remote_url=127.0.0.1:8899,127.0.0.1:8898,127.0.0.1:8897
20 |
21 | # for ConfigAuthenticator mode
22 | #auth.admin_token=
23 | #auth.user_tokens=[]
24 |
25 | # rpc group configs of multi graph servers
26 | # rpc server configs
27 | rpc.server_host=127.0.0.1
28 | rpc.server_port=8090
29 | #rpc.server_timeout=30
30 |
31 | # rpc client configs (like enable to keep cache consistency)
32 | rpc.remote_url=127.0.0.1:8090
33 | #rpc.client_connect_timeout=20
34 | #rpc.client_reconnect_period=10
35 | #rpc.client_read_timeout=40
36 | #rpc.client_retries=3
37 | #rpc.client_load_balancer=consistentHash
38 |
39 | # lightweight load balancing (beta)
40 | server.id=server-1
41 | server.role=master
42 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/hugegraph/formatter/JsonFormatter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.formatter;
21 |
22 | import com.baidu.hugegraph.structure.JsonGraph.JsonVertex;
23 | import com.fasterxml.jackson.databind.ObjectMapper;
24 |
25 | public class JsonFormatter implements Formatter {
26 |
27 | private final ObjectMapper mapper = new ObjectMapper();
28 |
29 | @Override
30 | public String dump(JsonVertex vertex) throws Exception {
31 | return this.mapper.writeValueAsString(vertex);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/assembly/travis/install-hugegraph-from-source.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -ev
3 | if [[ $# -ne 1 ]]; then
4 | echo "Must pass commit id of hugegraph repo"
5 | exit 1
6 | fi
7 |
8 | COMMIT_ID=$1
9 | HUGEGRAPH_GIT_URL="https://github.com/hugegraph/hugegraph.git"
10 | GIT_DIR=hugegraph
11 |
12 | # download code and compile
13 | git clone --depth 100 ${HUGEGRAPH_GIT_URL}
14 | cd "${GIT_DIR}"
15 | git checkout ${COMMIT_ID}
16 | mvn package -DskipTests
17 |
18 | TAR=$(echo hugegraph-*.tar.gz)
19 | tar -zxvf "${TAR}" -C ../
20 | cd ../
21 | rm -rf "${GIT_DIR}"
22 |
23 | HTTP_SERVER_DIR=$(echo hugegraph-*)
24 | HTTPS_SERVER_DIR="hugegraph_https"
25 |
26 | cp -r "${HTTP_SERVER_DIR}" "${HTTPS_SERVER_DIR}"
27 |
28 | # config auth options just for http server (must keep '/.')
29 | cp -rf "${TRAVIS_DIR}"/conf/. "${HTTP_SERVER_DIR}"/conf/
30 |
31 | # start HugeGraphServer with http protocol
32 | cd "${HTTP_SERVER_DIR}"
33 | echo -e "pa" | bin/init-store.sh || exit 1
34 | bin/start-hugegraph.sh || exit 1
35 |
36 | # config options for https server
37 | cd ../"${HTTPS_SERVER_DIR}"
38 | REST_SERVER_CONFIG="conf/rest-server.properties"
39 | GREMLIN_SERVER_CONFIG="conf/gremlin-server.yaml"
40 | sed -i "s?http://127.0.0.1:8080?https://127.0.0.1:8443?g" "$REST_SERVER_CONFIG"
41 | sed -i "s/#port: 8182/port: 8282/g" "$GREMLIN_SERVER_CONFIG"
42 | echo "gremlinserver.url=http://127.0.0.1:8282" >> ${REST_SERVER_CONFIG}
43 | # start HugeGraphServer with https protocol
44 | bin/init-store.sh
45 | bin/start-hugegraph.sh
46 | cd ../
47 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/hugegraph/exception/ToolsException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.exception;
21 |
22 | public class ToolsException extends RuntimeException {
23 |
24 | public ToolsException(String message) {
25 | super(message);
26 | }
27 |
28 | public ToolsException(String message, Throwable cause) {
29 | super(message, cause);
30 | }
31 |
32 | public ToolsException(String message, Object... args) {
33 | super(String.format(message, args));
34 | }
35 |
36 | public ToolsException(String message, Throwable cause, Object... args) {
37 | super(String.format(message, args), cause);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/test/java/com/baidu/hugegraph/test/functional/AuthTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.test.functional;
21 |
22 | public class AuthTest {
23 |
24 | public static final String DEFAULT_URL = "./auth-backup-restore/";
25 | public static final String DEFAULT_TEST_URL = "/auth/";
26 | public static final String USER_NAME = "admin";
27 | public static final String USER_PASSWORD = "pa";
28 | public static final String URL = "http://127.0.0.1:8080";
29 | public static final String GRAPH = "hugegraph";
30 | public static final Integer TIME_OUT = 30;
31 | public static final String TRUST_STORE_FILE = "";
32 | public static final String TRUST_STORE_PASSWORD = "";
33 | }
34 |
--------------------------------------------------------------------------------
/assembly/travis/conf/graphs/hugegraph.properties:
--------------------------------------------------------------------------------
1 | # gremlin entrence to create graph
2 | gremlin.graph=com.baidu.hugegraph.auth.HugeFactoryAuthProxy
3 |
4 | # cache config
5 | #schema.cache_capacity=100000
6 | # vertex-cache default is 1000w, 10min expired
7 | #vertex.cache_capacity=10000000
8 | #vertex.cache_expire=600
9 | # edge-cache default is 100w, 10min expired
10 | #edge.cache_capacity=1000000
11 | #edge.cache_expire=600
12 |
13 |
14 | # schema illegal name template
15 | #schema.illegal_name_regex=\s+|~.*
16 |
17 | #vertex.default_label=vertex
18 |
19 | backend=rocksdb
20 | serializer=binary
21 |
22 | store=hugegraph
23 |
24 | search.text_analyzer=jieba
25 | search.text_analyzer_mode=INDEX
26 |
27 | # rocksdb backend config
28 | #rocksdb.data_path=/path/to/disk
29 | #rocksdb.wal_path=/path/to/disk
30 |
31 |
32 | # cassandra backend config
33 | cassandra.host=localhost
34 | cassandra.port=9042
35 | cassandra.username=
36 | cassandra.password=
37 | #cassandra.connect_timeout=5
38 | #cassandra.read_timeout=20
39 | #cassandra.keyspace.strategy=SimpleStrategy
40 | #cassandra.keyspace.replication=3
41 |
42 | # hbase backend config
43 | #hbase.hosts=localhost
44 | #hbase.port=2181
45 | #hbase.znode_parent=/hbase
46 | #hbase.threads_max=64
47 |
48 | # mysql backend config
49 | #jdbc.driver=com.mysql.jdbc.Driver
50 | #jdbc.url=jdbc:mysql://127.0.0.1:3306
51 | #jdbc.username=root
52 | #jdbc.password=
53 | #jdbc.reconnect_max_times=3
54 | #jdbc.reconnect_interval=3
55 | #jdbc.sslmode=false
56 |
57 | # palo backend config
58 | #palo.host=127.0.0.1
59 | #palo.poll_interval=10
60 | #palo.temp_dir=./palo-data
61 | #palo.file_limit_size=32
62 |
--------------------------------------------------------------------------------
/assembly/descriptor/assembly.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 | distribution
6 | false
7 |
8 |
9 | dir
10 |
11 |
12 |
13 |
14 | ${assembly.dir}/bin
15 | bin
16 |
17 | *
18 |
19 | 755
20 |
21 |
22 | ${assembly.dir}/conf
23 | conf
24 |
25 | *
26 |
27 | 755
28 |
29 |
30 | ${project.build.directory}
31 | lib
32 |
33 | *.jar
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 | /lib
42 | false
43 | runtime
44 | false
45 |
46 | *:*:jar:*
47 |
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/src/main/resources/log4j2.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/hugegraph/formatter/Formatter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.formatter;
21 |
22 | import com.baidu.hugegraph.structure.JsonGraph.JsonVertex;
23 |
24 | public interface Formatter {
25 |
26 | // Serialize a vertex(with edge and property) to string
27 | public String dump(JsonVertex vertex) throws Exception;
28 |
29 | public static final String PACKAGE = Formatter.class.getPackage().getName();
30 |
31 | public static Formatter loadFormatter(String formatter) {
32 | String classPath = String.format("%s.%s", PACKAGE, formatter);
33 | ClassLoader loader = Formatter.class.getClassLoader();
34 | try {
35 | // Check subclass
36 | Class> clazz = loader.loadClass(classPath);
37 | if (!Formatter.class.isAssignableFrom(clazz)) {
38 | throw new RuntimeException("Invalid formatter: " + formatter);
39 | }
40 | // New instance of formatter
41 | return (Formatter) clazz.newInstance();
42 | } catch (Exception e) {
43 | throw new RuntimeException("Can't load formatter: " + formatter, e);
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/assembly/bin/clear.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | INSTALL_PATH=""
4 |
5 | function print_usage() {
6 | echo "USAGE: $0 -p {install-path}"
7 | echo "eg : $0 -p ."
8 | }
9 |
10 | while getopts "p:" arg; do
11 | case ${arg} in
12 | p) INSTALL_PATH="$OPTARG" ;;
13 | ?) print_usage && exit 1 ;;
14 | esac
15 | done
16 |
17 | if [ "$INSTALL_PATH" = "" ]; then
18 | print_usage
19 | exit 1
20 | fi
21 |
22 | # Check path exist
23 | if [ ! -d "${INSTALL_PATH}" ]; then
24 | echo "Package storage directory '${INSTALL_PATH}' doesn't exist"
25 | fi
26 | # Check for write permission
27 | if [ ! -w "${INSTALL_PATH}" ]; then
28 | echo "No write permission on directory '${INSTALL_PATH}'"
29 | exit 1
30 | fi
31 |
32 | INSTALL_PATH="$(cd ${INSTALL_PATH} && pwd)"
33 |
34 | function abs_path() {
35 | SOURCE="${BASH_SOURCE[0]}"
36 | while [ -h "$SOURCE" ]; do
37 | DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
38 | SOURCE="$(readlink "$SOURCE")"
39 | [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
40 | done
41 | echo "$( cd -P "$( dirname "$SOURCE" )" && pwd )"
42 | }
43 |
44 | BIN=`abs_path`
45 | . ${BIN}/util.sh
46 |
47 | cd ${BIN}
48 |
49 | SERVER_RELEASE_PREFIX="hugegraph"
50 | STUDIO_RELEASE_PREFIX="hugegraph-studio"
51 |
52 | function ensure_no_process() {
53 | local path=$1
54 | local prefix=$2
55 |
56 | for file in `ls ${path}`; do
57 | file=${path}/${file}
58 | if [[ -d "${file}" && "${file}" =~ "${prefix}" ]]; then
59 | p_name=${file}
60 | process_status "${p_name}" >/dev/null
61 | if [ $? -eq 0 ]; then
62 | echo "Exist process corresponding to the directory '${file}', please stop it before clearing"
63 | exit 1
64 | fi
65 | fi
66 | done
67 | }
68 |
69 | ensure_no_process ${INSTALL_PATH} ${SERVER_RELEASE_PREFIX}
70 | ensure_no_process ${INSTALL_PATH} ${STUDIO_RELEASE_PREFIX}
71 |
72 | for file in ${INSTALL_PATH}/${SERVER_RELEASE_PREFIX}*; do
73 | remove_with_prompt "${file}"
74 | done
75 |
76 | for file in ${INSTALL_PATH}/${STUDIO_RELEASE_PREFIX}*; do
77 | remove_with_prompt "${file}"
78 | done
79 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/hugegraph/base/Directory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.base;
21 |
22 | import java.io.Closeable;
23 | import java.io.InputStream;
24 | import java.io.OutputStream;
25 | import java.util.List;
26 |
27 | import com.baidu.hugegraph.util.E;
28 |
29 | public abstract class Directory {
30 |
31 | private final String directory;
32 |
33 | public Directory(String directory) {
34 | E.checkArgument(directory != null && !directory.isEmpty(),
35 | "Directory can't be null or empty");
36 | this.directory = directory;
37 | }
38 |
39 | public String directory() {
40 | return this.directory;
41 | }
42 |
43 | public abstract List files();
44 |
45 | public abstract String suffix(boolean compress);
46 |
47 | public abstract void ensureDirectoryExist(boolean create);
48 |
49 | public abstract void removeDirectory();
50 |
51 | public abstract InputStream inputStream(String path);
52 |
53 | public abstract OutputStream outputStream(String path, boolean compress,
54 | boolean override);
55 |
56 | public static void closeAndIgnoreException(Closeable stream) {
57 | if (stream == null) {
58 | return;
59 | }
60 | try {
61 | stream.close();
62 | } catch (Exception ignored) {
63 | // Ignore
64 | }
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/hugegraph/constant/AuthRestoreConflictStrategy.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.constant;
21 |
22 | public enum AuthRestoreConflictStrategy {
23 |
24 | STOP(1, "stop"),
25 | IGNORE(2, "ignore");
26 |
27 | private int code;
28 | private String name = null;
29 |
30 | AuthRestoreConflictStrategy(int code, String name) {
31 | assert code < 256;
32 | this.code = code;
33 | this.name = name;
34 | }
35 |
36 | public int code() {
37 | return this.code;
38 | }
39 |
40 | public String string() {
41 | return this.name;
42 | }
43 |
44 | public boolean isStopStrategy() {
45 | return this == AuthRestoreConflictStrategy.STOP;
46 | }
47 |
48 | public boolean isIgnoreStrategy() {
49 | return this == AuthRestoreConflictStrategy.IGNORE;
50 | }
51 |
52 | public static boolean matchStrategy(String strategy) {
53 | if (AuthRestoreConflictStrategy.STOP.string().equals(strategy) ||
54 | AuthRestoreConflictStrategy.IGNORE.string().equals(strategy)) {
55 | return true;
56 | }
57 | return false;
58 | }
59 |
60 | public static AuthRestoreConflictStrategy fromName(String name) {
61 | AuthRestoreConflictStrategy[] restoreStrategys = AuthRestoreConflictStrategy.values();
62 | for (AuthRestoreConflictStrategy strategy : restoreStrategys) {
63 | if (strategy.string().equals(name)) {
64 | return strategy;
65 | }
66 | }
67 | return null;
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/hugegraph/manager/GraphsManager.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.manager;
21 |
22 | import java.util.List;
23 | import java.util.Map;
24 |
25 | import com.baidu.hugegraph.base.ToolClient;
26 | import com.baidu.hugegraph.base.ToolManager;
27 | import com.baidu.hugegraph.structure.constant.GraphMode;
28 |
29 | public class GraphsManager extends ToolManager {
30 |
31 | public GraphsManager(ToolClient.ConnectionInfo info) {
32 | super(info, "graphs");
33 | }
34 |
35 | public Map create(String name, String config) {
36 | return this.client.graphs().createGraph(name, config);
37 | }
38 |
39 | public Map clone(String name, String cloneGraphName) {
40 | return this.client.graphs().cloneGraph(name, cloneGraphName);
41 | }
42 |
43 | public List list() {
44 | return this.client.graphs().listGraph();
45 | }
46 |
47 | public Map get(String graph) {
48 | return this.client.graphs().getGraph(graph);
49 | }
50 |
51 | public void clear(String graph, String confirmMessage) {
52 | this.client.graphs().clearGraph(graph, confirmMessage);
53 | }
54 |
55 | public void drop(String graph, String confirmMessage) {
56 | this.client.graphs().dropGraph(graph, confirmMessage);
57 | }
58 |
59 | public void mode(String graph, GraphMode mode) {
60 | this.client.graphs().mode(graph, mode);
61 | }
62 |
63 | public GraphMode mode(String graph) {
64 | return this.client.graphs().mode(graph);
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/hugegraph/manager/GremlinManager.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.manager;
21 |
22 | import java.util.Map;
23 |
24 | import com.baidu.hugegraph.api.gremlin.GremlinRequest;
25 | import com.baidu.hugegraph.base.ToolClient;
26 | import com.baidu.hugegraph.base.ToolManager;
27 | import com.baidu.hugegraph.structure.gremlin.ResultSet;
28 |
29 | public class GremlinManager extends ToolManager {
30 |
31 | public GremlinManager(ToolClient.ConnectionInfo info) {
32 | super(info, "gremlin");
33 | }
34 |
35 | public ResultSet execute(String gremlin, Map bindings,
36 | String language, Map aliases) {
37 | GremlinRequest.Builder builder = this.client.gremlin().gremlin(gremlin);
38 | for (Map.Entry entry : aliases.entrySet()) {
39 | builder.alias(entry.getKey(), entry.getValue());
40 | }
41 | for (Map.Entry entry : bindings.entrySet()) {
42 | builder.binding(entry.getKey(), entry.getValue());
43 | }
44 | builder.language(language);
45 | return builder.execute();
46 | }
47 |
48 | public long executeAsTask(String gremlin, Map bindings,
49 | String language) {
50 | GremlinRequest.Builder builder = this.client.gremlin().gremlin(gremlin);
51 | for (Map.Entry entry : bindings.entrySet()) {
52 | builder.binding(entry.getKey(), entry.getValue());
53 | }
54 | builder.language(language);
55 | return builder.executeAsTask();
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/hugegraph/base/ToolManager.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.base;
21 |
22 | import java.io.IOException;
23 | import java.util.List;
24 |
25 | import com.baidu.hugegraph.rest.SerializeException;
26 | import com.fasterxml.jackson.databind.JavaType;
27 | import com.fasterxml.jackson.databind.JsonNode;
28 | import com.fasterxml.jackson.databind.ObjectMapper;
29 |
30 | public class ToolManager {
31 |
32 | protected final ToolClient client;
33 | private final String type;
34 |
35 | public ToolManager(ToolClient.ConnectionInfo info, String type) {
36 | this.client = new ToolClient(info);
37 | this.type = type;
38 | }
39 |
40 | protected String type() {
41 | return this.type;
42 | }
43 |
44 | protected String graph() {
45 | return this.client.graph().graph();
46 | }
47 |
48 | @SuppressWarnings("unchecked")
49 | protected List readList(String key, Class clazz,
50 | String content) {
51 | ObjectMapper mapper = this.client.mapper();
52 | try {
53 | JsonNode root = mapper.readTree(content);
54 | JsonNode element = root.get(key);
55 | if(element == null) {
56 | throw new SerializeException(
57 | "Can't find value of the key: %s in json.", key);
58 | } else {
59 | JavaType t = mapper.getTypeFactory()
60 | .constructParametricType(List.class, clazz);
61 | return (List) mapper.readValue(element.toString(), t);
62 | }
63 | } catch (IOException e) {
64 | throw new SerializeException(
65 | "Failed to deserialize %s", e, content);
66 | }
67 | }
68 |
69 | public void close () {
70 | this.client.close();
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/hugegraph/base/Printer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.base;
21 |
22 | import java.util.List;
23 | import java.util.Map;
24 | import java.util.Set;
25 |
26 | public class Printer {
27 |
28 | public static void print(String content) {
29 | System.out.println(content);
30 | }
31 |
32 | public static void print(String content, Object ... objects) {
33 | System.out.println(String.format(content, objects));
34 | }
35 |
36 | public static void printKV(String key, Object value) {
37 | System.out.println(key + ": " + value);
38 | }
39 |
40 | public static void printSet(String name, Set> set) {
41 | System.out.println(name + ": (");
42 | for (Object object : set) {
43 | System.out.println("\t" + object + ",");
44 | }
45 | System.out.println(")");
46 | }
47 |
48 | public static void printList(String name, List> list) {
49 | System.out.println(name + ": [");
50 | for (Object object : list) {
51 | System.out.println("\t" + object + ",");
52 | }
53 | System.out.println("]");
54 | }
55 |
56 | public static void printMap(String name, Map, ?> map) {
57 | System.out.println(name + ": {");
58 | for (Map.Entry, ?> entry : map.entrySet()) {
59 | System.out.println("\t" + entry.getKey() + ": " +
60 | entry.getValue() + ",");
61 | }
62 | System.out.println("}");
63 | }
64 |
65 | public static void printInBackward(String message) {
66 | System.out.print(message);
67 | printInBackward(0L);
68 | }
69 |
70 | public static void printInBackward(long count) {
71 | System.out.print(String.format("%d%s", count, backward(count)));
72 | }
73 |
74 | public static String backward(long word) {
75 | StringBuilder backward = new StringBuilder();
76 | for (int i = 0, len = String.valueOf(word).length(); i < len; i++) {
77 | backward.append("\b");
78 | }
79 | return backward.toString();
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/assembly/bin/schedule-backup.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | function abs_path() {
4 | SOURCE="${BASH_SOURCE[0]}"
5 | while [ -h "$SOURCE" ]; do
6 | DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
7 | SOURCE="$(readlink "$SOURCE")"
8 | [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
9 | done
10 | echo "$( cd -P "$( dirname "$SOURCE" )" && pwd )"
11 | }
12 |
13 | BIN=`abs_path`
14 | TOP=`dirname $BIN`
15 | cd $BIN
16 |
17 | if [ -n "$JAVA_HOME" ]; then
18 | JAVA="$JAVA_HOME"/bin/java
19 | else
20 | JAVA=java
21 | fi
22 |
23 | function parse_interval() {
24 | INTERVAL="${1//\\/} ${2//\\/} ${3//\\/} ${4//\\/} ${5//\\/}"
25 | }
26 |
27 | for((i=1;i<=$#;i+=2));
28 | do
29 | current=`eval echo '${'$i'}'`
30 | case "$current" in
31 | "--url")
32 | URL=`eval echo '${'$(($i+1))'}'`
33 | URL_ARG="--url "$URL
34 | ;;
35 | "--graph")
36 | GRAPH=`eval echo '${'$(($i+1))'}'`
37 | GRAPH_ARG="--graph "$GRAPH
38 | ;;
39 | "--user")
40 | USERNAME=`eval echo '${'$(($i+1))'}'`
41 | USERNAME_ARG="--user "$USERNAME
42 | ;;
43 | "--password")
44 | PASSWORD=`eval echo '${'$(($i+1))'}'`
45 | PASSWORD_ARG="--password "$PASSWORD
46 | ;;
47 | "--timeout")
48 | TIMEOUT=`eval echo '${'$(($i+1))'}'`
49 | TIMEOUT_ARG="--timeout "$TIMEOUT
50 | ;;
51 | "--interval")
52 | position=$(($i+1))
53 | INTERVAL=${@:$position:5}
54 | INTERVAL=${INTERVAL//\\/}
55 | let i+=4
56 | ;;
57 | "--backup-num")
58 | NUM=`eval echo '${'$(($i+1))'}'`
59 | ;;
60 | "--directory"|"-d")
61 | DIR=`eval echo '${'$(($i+1))'}'`
62 | ;;
63 | *)
64 | echo "Invalid argument: $current"
65 | bash $BIN/hugegraph
66 | exit 1
67 | esac
68 | done
69 |
70 | if [ -z "$DIR" ]; then
71 | echo "Must provide backup directory"
72 | exit 1
73 | else
74 | if [ ${DIR:0:1} != "/" ]; then
75 | DIR=$TOP"/"$DIR
76 | fi
77 | fi
78 |
79 | DIR=`dirname $DIR`/`basename $DIR`
80 |
81 | if [ -z "$GRAPH" ]; then
82 | GRAPH="hugegraph"
83 | fi
84 | GRAPH_DIR=$DIR/$GRAPH
85 |
86 | if [ -d $GRAPH_DIR -o -f $GRAPH_DIR ]; then
87 | echo "Error: Directory/file $GRAPH already exists in $DIR"
88 | exit 1
89 | fi
90 |
91 | mkdir "$GRAPH_DIR"
92 | if [ $? -ne 0 ]; then
93 | echo "Failed to create directory $GRAPH_DIR"
94 | exit 1
95 | fi
96 |
97 | if [ -z "$NUM" ]; then
98 | NUM=3
99 | elif [ ! "$NUM" -gt 0 ] 2>/dev/null ;then
100 | echo "Number of backups must be positive number."
101 | exit 1
102 | fi
103 |
104 | if [ -z "$INTERVAL" ]; then
105 | INTERVAL="0 0 * * *"
106 | fi
107 |
108 | CRONTAB_JOB="$INTERVAL export JAVA_HOME=$JAVA_HOME && bash $BIN/backup.sh $URL_ARG $GRAPH_ARG $USERNAME_ARG $PASSWORD_ARG $TIMEOUT_ARG backup -t all -d $GRAPH_DIR --backup-num $NUM"
109 |
110 | . $BIN/util.sh
111 |
112 | crontab_append "$CRONTAB_JOB"
113 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.yml:
--------------------------------------------------------------------------------
1 | name: Bug report (反馈 Bug)
2 | description: Create a bug report to help HugeGraph improve
3 | title: '[Bug] describe the main problem'
4 | labels:
5 | - bug
6 |
7 | body:
8 | - type: markdown
9 | attributes:
10 | value: >-
11 | ### Note (特别注意) :
12 |
13 | > 1. 请先**搜索**现有的[Server-Issues](https://github.com/hugegraph/hugegraph/issues) 与
14 | [Tools-Issues](https://github.com/hugegraph/hugegraph-tools/issues) 中没有与您相同
15 | / 相关的问题 (请勿重复提交)
16 |
17 | > 2. 我们需要尽可能**详细**的信息来**复现**问题, 越详细的信息 (包括**日志 / 截图 / 配置**等)
18 | 会**越快**被响应和处理
19 |
20 | > 3. Issue 标题请保持原有模板分类(例如:`[Bug]`), 长段描述之间可以增加`空行`或使用`序号`标记, 保持排版清晰
21 |
22 | > 4. 请在对应的模块提交 issue, 缺乏有效信息 / 长时间 (> 14 天) 没有回复的 issue 可能会被 **关闭**
23 | (更新时会再开启)
24 |
25 | - type: dropdown
26 | attributes:
27 | label: Bug Type (问题类型)
28 | options:
29 | - exception / error (异常报错)
30 | - data inconsistency (备份 / 迁移后不合预期)
31 | - logic (逻辑设计问题)
32 | - others (please edit later)
33 |
34 | - type: checkboxes
35 | attributes:
36 | label: Before submit
37 | options:
38 | - label: 我已经确认现有的 [Server-Issues](https://github.com/hugegraph/hugegraph/issues) 与 [Tools-Issues](https://github.com/hugegraph/hugegraph-tools/issues) 中没有相同 / 重复问题
39 | required: true
40 |
41 | - type: textarea
42 | attributes:
43 | label: Environment (环境信息)
44 | description: |
45 | > server version could get from [rest-api](https://hugegraph.github.io/hugegraph-doc/clients/restful-api/other.html) (http://localhost:8080/versions)
46 | value: |
47 | - Server Version: v0.11.x
48 | - Tools Version: v1.x
49 | - Data Size: xx vertices, xx edges
50 | validations:
51 | required: true
52 |
53 | - type: textarea
54 | attributes:
55 | label: Expected & Actual behavior (期望与实际表现)
56 | description: |
57 | > we can refer [How to create a minimal reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) (如何提供最简的可复现用例)
58 | > if possible, please provide screenshots or GIF (请提供清晰的截图, 动图录屏更佳)
59 | placeholder: |
60 | type the main problem here
61 |
62 | ```java
63 | // Exception / Error info (尽可能详细的日志 + 完整异常栈)
64 |
65 | ```
66 | validations:
67 | required: true
68 |
69 | - type: textarea
70 | attributes:
71 | label: Vertex/Edge example (问题点 / 边数据举例)
72 | description: |
73 | > 如果问题与具体的点 / 边数据相关, 请提供完整的`原始数据 + REST-API 查询结果`
74 | placeholder: |
75 | // Origin data
76 | tom 18 boy HK
77 |
78 | // JSON of Vertex / Edge
79 | {
80 | "vertex": { "id": "xxx" }
81 | }
82 | render: javascript
83 |
84 | - type: textarea
85 | attributes:
86 | label: Schema [VertexLabel, EdgeLabel, IndexLabel] (元数据结构)
87 | description: |
88 | > 如果问题与具体的点类型 / 边类型 / 索引类型相关, 请提供完整的 `Schema 返回 JSON 结果`
89 | placeholder: |
90 | // Query URL
91 | GET http://localhost:8080/graphs/hugegraph/schema/vertexlabels
92 |
93 | // JSON of GraphSchema
94 | {
95 | "vertex": { "id": "xxx" }
96 | }
97 | render: javascript
98 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/hugegraph/manager/TasksManager.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.manager;
21 |
22 | import java.util.List;
23 | import java.util.Set;
24 |
25 | import com.baidu.hugegraph.base.ToolClient;
26 | import com.baidu.hugegraph.base.ToolManager;
27 | import com.baidu.hugegraph.structure.Task;
28 | import com.google.common.collect.ImmutableSet;
29 |
30 | public class TasksManager extends ToolManager {
31 |
32 | public static final Set TASK_STATUSES = ImmutableSet.of(
33 | "UNKNOWN", "NEW", "QUEUED", "RESTORING", "RUNNING",
34 | "SUCCESS", "CANCELLED", "FAILED"
35 | );
36 |
37 | private static final Set UNCOMPLETED_STATUSES = ImmutableSet.of(
38 | "UNKNOWN", "NEW", "QUEUED", "RESTORING", "RUNNING"
39 | );
40 |
41 | private static final Set COMPLETED_STATUSES = ImmutableSet.of(
42 | "SUCCESS", "CANCELLED", "FAILED"
43 | );
44 |
45 | private static long TASK_LIMIT = 10000;
46 |
47 | public TasksManager(ToolClient.ConnectionInfo info) {
48 | super(info, "tasks");
49 | }
50 |
51 | public List list(String status, long limit) {
52 | return this.client.tasks().list(status, limit);
53 | }
54 |
55 | public Task get(long taskId) {
56 | return this.client.tasks().get(taskId);
57 | }
58 |
59 | public void delete(long taskId) {
60 | this.client.tasks().delete(taskId);
61 | }
62 |
63 | public void cancel(long taskId) {
64 | this.client.tasks().cancel(taskId);
65 | }
66 |
67 | public void clear(boolean force) {
68 | if (force) {
69 | // Cancel all uncompleted tasks
70 | for (String status : UNCOMPLETED_STATUSES) {
71 | do {
72 | List tasks = this.list(status, TASK_LIMIT);
73 | tasks.forEach(t -> this.cancel(t.id()));
74 | if (tasks.size() < TASK_LIMIT) {
75 | break;
76 | }
77 | } while (true);
78 | }
79 | }
80 |
81 | // Delete all completed tasks
82 | for (String status : COMPLETED_STATUSES) {
83 | do {
84 | List tasks = this.list(status, TASK_LIMIT);
85 | tasks.forEach(t -> this.delete(t.id()));
86 | if (tasks.size() < TASK_LIMIT) {
87 | break;
88 | }
89 | } while (true);
90 | }
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/question_ask.yml:
--------------------------------------------------------------------------------
1 | name: Ask question (提问)
2 | description: Question about usage or configs in HugeGraph
3 | title: '[Question] describe your problem'
4 |
5 | body:
6 | - type: markdown
7 | attributes:
8 | value: >-
9 | ### Note (特别注意) :
10 |
11 | > 1. 请先**搜索**现有的[Server-Issues](https://github.com/hugegraph/hugegraph/issues) 与
12 | [Tools-Issues](https://github.com/hugegraph/hugegraph-tools/issues) 中没有与您相同
13 | / 相关的问题 (请勿重复提交)
14 |
15 | > 2. 我们需要尽可能**详细**的信息来**复现**问题, 越详细的信息 (包括**日志 / 截图 / 配置**等)
16 | 会**越快**被响应和处理
17 |
18 | > 3. Issue 标题请保持原有模板分类(例如:`[Bug]`), 长段描述之间可以增加`空行`或使用`序号`标记, 保持排版清晰
19 |
20 | > 4. 请在对应的模块提交 issue, 缺乏有效信息 / 长时间 (> 14 天) 没有回复的 issue 可能会被 **关闭**
21 | (更新时会再开启)
22 |
23 | - type: dropdown
24 | attributes:
25 | label: Problem Type (问题类型)
26 | options:
27 | - exception / error (异常报错)
28 | - data inconsistency (备份 / 迁移后不合预期)
29 | - logic (逻辑设计问题)
30 | - configs (配置项 / 文档相关)
31 | - performence (性能优化)
32 | - others (please edit later)
33 |
34 | - type: checkboxes
35 | attributes:
36 | label: Before submit
37 | options:
38 | - label: 我已经确认现有的 [Server-Issues](https://github.com/hugegraph/hugegraph/issues) 与 [Tools-Issues](https://github.com/hugegraph/hugegraph-tools/issues) 中没有相同 / 重复问题
39 | required: true
40 |
41 | - type: textarea
42 | attributes:
43 | label: Environment (环境信息)
44 | description: |
45 | > server version could get from [rest-api](https://hugegraph.github.io/hugegraph-doc/clients/restful-api/other.html) (http://localhost:8080/versions)
46 | value: |
47 | - Server Version: v0.11.x
48 | - Tools Version: v1.x
49 | - Data Size: xx vertices, xx edges
50 | validations:
51 | required: true
52 |
53 | - type: textarea
54 | attributes:
55 | label: Your Question (问题描述)
56 | description: |
57 | > 图使用 / 配置相关问题,请优先参考 [REST-API 文档](https://hugegraph.github.io/hugegraph-doc/clients/hugegraph-api.html), 以及 [Server 配置文档](https://hugegraph.github.io/hugegraph-doc/config/config-option.html)
58 | > if possible, please provide screenshots or GIF (请提供清晰的截图, 动图录屏更佳)
59 | placeholder: |
60 | type the main problem here
61 |
62 | ```java
63 | // Exception / Error info (尽可能详细的日志 + 完整异常栈)
64 |
65 | ```
66 | validations:
67 | required: true
68 |
69 | - type: textarea
70 | attributes:
71 | label: Vertex/Edge example (问题点 / 边数据举例)
72 | description: |
73 | > 如果问题与具体的点 / 边数据相关, 请提供完整的`原始数据 + REST-API 查询结果`
74 | placeholder: |
75 | // Origin data
76 | tom 18 boy HK
77 |
78 | // JSON of Vertex / Edge
79 | {
80 | "vertex": { "id": "xxx" }
81 | }
82 | render: javascript
83 |
84 | - type: textarea
85 | attributes:
86 | label: Schema [VertexLabel, EdgeLabel, IndexLabel] (元数据结构)
87 | description: |
88 | > 如果问题与具体的点类型 / 边类型 / 索引类型相关, 请提供完整的 `Schema 返回 JSON 结果`
89 | placeholder: |
90 | // Query URL
91 | GET http://localhost:8080/graphs/hugegraph/schema/vertexlabels
92 |
93 | // JSON of GraphSchema
94 | {
95 | "vertex": { "id": "xxx" }
96 | }
97 | render: javascript
98 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/hugegraph/exception/ExitException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.exception;
21 |
22 | import com.baidu.hugegraph.constant.Constants;
23 |
24 | public class ExitException extends RuntimeException {
25 |
26 | private final String details;
27 | private final Integer exitCode;
28 |
29 | public ExitException(String details, String reason) {
30 | super(reason);
31 | this.details = details;
32 | this.exitCode = Constants.EXIT_CODE_NORMAL;
33 | }
34 |
35 | public ExitException(String details, String reason,
36 | Object... args) {
37 | super(String.format(reason, args));
38 | this.details = details;
39 | this.exitCode = Constants.EXIT_CODE_NORMAL;
40 | }
41 |
42 | public ExitException(Integer exitCode, String details,
43 | String reason) {
44 | super(reason);
45 | this.details = details;
46 | this.exitCode = exitCode;
47 | }
48 |
49 | public ExitException(Integer exitCode, String details,
50 | String reason, Throwable cause) {
51 | super(reason, cause);
52 | this.details = details;
53 | this.exitCode = exitCode;
54 | }
55 |
56 | public ExitException(Integer exitCode, String details,
57 | String reason, Object... args) {
58 | super(String.format(reason, args));
59 | this.details = details;
60 | this.exitCode = exitCode;
61 | }
62 |
63 | public ExitException(Integer exitCode, String details,
64 | String reason, Throwable cause,
65 | Object... args) {
66 | super(String.format(reason, args), cause);
67 | this.details = details;
68 | this.exitCode = exitCode;
69 | }
70 |
71 | public String details() {
72 | return this.details;
73 | }
74 |
75 | public Integer exitCode() {
76 | return this.exitCode;
77 | }
78 |
79 | public static ExitException exception(String details, String reason,
80 | Object... args) {
81 | return new ExitException(Constants.EXIT_CODE_ERROR,
82 | details, reason, args);
83 | }
84 |
85 | public static ExitException normal(String details, String reason,
86 | Object... args) {
87 | return new ExitException(Constants.EXIT_CODE_NORMAL,
88 | details, reason, args);
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/checkstyle.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
--------------------------------------------------------------------------------
/assembly/bin/start-all.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | VERSION=""
4 | INSTALL_PATH=""
5 |
6 | function print_usage() {
7 | echo "USAGE: $0 -v {hugegraph-version} -p {install-path}"
8 | echo "eg : $0 -v 0.8 -p ."
9 | }
10 |
11 | while getopts "v:p:" arg; do
12 | case ${arg} in
13 | v) VERSION="$OPTARG" ;;
14 | p) INSTALL_PATH="$OPTARG" ;;
15 | ?) print_usage && exit 1 ;;
16 | esac
17 | done
18 |
19 | if [[ "$VERSION" = "" || "$INSTALL_PATH" = "" ]]; then
20 | print_usage
21 | exit 1
22 | fi
23 |
24 | function abs_path() {
25 | SOURCE="${BASH_SOURCE[0]}"
26 | while [ -h "$SOURCE" ]; do
27 | DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
28 | SOURCE="$(readlink "$SOURCE")"
29 | [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
30 | done
31 | echo "$( cd -P "$( dirname "$SOURCE" )" && pwd )"
32 | }
33 |
34 | BIN=`abs_path`
35 | . ${BIN}/util.sh
36 |
37 | `ensure_path_writable ${INSTALL_PATH}`
38 |
39 | # Convert to absolute path
40 | INSTALL_PATH="$(cd ${INSTALL_PATH} && pwd)"
41 |
42 | cd ${BIN}
43 |
44 | # Check input version can be found in version-map.yaml
45 | OPTIONAL_VERSIONS=`cat version-map.yaml | grep 'version' | awk -F ':' '{print $1}' | xargs`
46 | if [[ ! "$OPTIONAL_VERSIONS" =~ "$VERSION" ]]; then
47 | echo "Invalid version '${VERSION}' for hugegraph, the optional values are [$OPTIONAL_VERSIONS]"
48 | exit 1
49 | fi
50 |
51 | # Parse module version from 'version-map.yaml'
52 | SERVER_VERSION=`parse_yaml version-map.yaml "${VERSION}" "server"`
53 | if [ "$SERVER_VERSION" = "" ]; then
54 | echo "Please check the format and content of file 'version-map.yaml' is normal"
55 | exit 1
56 | fi
57 | STUDIO_VERSION=`parse_yaml version-map.yaml "${VERSION}" "studio"`
58 | if [ "$STUDIO_VERSION" = "" ]; then
59 | echo "Please check the format and content of file 'version-map.yaml' is normal"
60 | exit 1
61 | fi
62 |
63 | SERVER_DIR="${INSTALL_PATH}/hugegraph-${SERVER_VERSION}"
64 | STUDIO_DIR="${INSTALL_PATH}/hugegraph-studio-${STUDIO_VERSION}"
65 |
66 | if [ ! -d "${SERVER_DIR}" ]; then
67 | echo "The server dir ${SERVER_DIR} doesn't exist"
68 | exit 1
69 | fi
70 |
71 | if [ ! -d "${STUDIO_DIR}" ]; then
72 | echo "The studio dir ${STUDIO_DIR} doesn't exist"
73 | exit 1
74 | fi
75 |
76 | function start_hugegraph_server() {
77 | $SERVER_DIR/bin/start-hugegraph.sh
78 | if [ $? -ne 0 ]; then
79 | echo "Failed to start HugeGraphServer, please check the logs under '$SERVER_DIR/logs' for details"
80 | exit 1
81 | fi
82 | }
83 |
84 | function start_hugegraph_studio() {
85 | # TODO: Let hugegraph-studio.sh can execute in any directory instead of $STUDIO_DIR
86 | cd $STUDIO_DIR
87 |
88 | local server_host=`read_property "conf/hugegraph-studio.properties" "studio.server.host"`
89 | local server_port=`read_property "conf/hugegraph-studio.properties" "studio.server.port"`
90 | local server_url="http://${server_host}:${server_port}"
91 | local start_timeout_s=20
92 |
93 | echo "Starting HugeGraphStudio..."
94 | bin/hugegraph-studio.sh >/dev/null 2>&1 &
95 |
96 | pid="$!"
97 | trap '$BIN/stop-all.sh; exit' SIGHUP SIGINT SIGQUIT SIGTERM
98 |
99 | wait_for_startup 'HugeGraphStudio' "$server_url" $start_timeout_s || {
100 | echo "Failed to start HugeGraphStudio, please check the logs under '$STUDIO_DIR/logs' for details"
101 | $SERVER_DIR/bin/stop-hugegraph.sh
102 | exit 1
103 | }
104 | cd ..
105 | }
106 |
107 | start_hugegraph_server
108 | start_hugegraph_studio
109 |
110 | echo "[OK] Started HugeGraphServer and HugeGraphStudio"
111 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/hugegraph/util/ToolUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.util;
21 |
22 | import java.util.Map;
23 | import java.util.Scanner;
24 |
25 | import com.baidu.hugegraph.base.Printer;
26 | import com.baidu.hugegraph.constant.Constants;
27 | import com.baidu.hugegraph.exception.ExitException;
28 | import com.beust.jcommander.JCommander;
29 |
30 | public final class ToolUtil {
31 |
32 | public static void printOrThrow(Throwable e, boolean throwMode) {
33 | Printer.print("Failed to execute %s", e.getMessage());
34 | if (throwMode) {
35 | if (e instanceof RuntimeException) {
36 | throw (RuntimeException) e;
37 | }
38 | throw new RuntimeException(e);
39 | }
40 | printExceptionStackIfNeeded(e);
41 | }
42 |
43 | public static void printExceptionStackIfNeeded(Throwable e) {
44 | System.out.println("Type y(yes) to print exception stack[default n]?");
45 | Scanner scan = new Scanner(System.in);
46 | String inputInfomation = scan.nextLine();
47 |
48 | if (inputInfomation.equalsIgnoreCase(Constants.INPUT_YES) ||
49 | inputInfomation.equalsIgnoreCase(Constants.INPUT_Y)) {
50 | e.printStackTrace();
51 | }
52 | }
53 |
54 | public static void exitOrThrow(ExitException e, boolean throwMode) {
55 | if (throwMode) {
56 | throw e;
57 | }
58 |
59 | if(e.exitCode() != Constants.EXIT_CODE_NORMAL) {
60 | Printer.print(e.getMessage());
61 | }
62 | Printer.print(e.details());
63 | }
64 |
65 | public static String commandsCategory(JCommander jCommander) {
66 | StringBuffer sb = new StringBuffer();
67 | sb.append("================================================");
68 | sb.append("\n");
69 | sb.append("Warning : must provide one sub-command");
70 | sb.append("\n");
71 | sb.append("================================================");
72 | sb.append("\n");
73 | sb.append("Here are some sub-command :");
74 | sb.append("\n");
75 | Map subCommandes = jCommander.getCommands();
76 | for (String subCommand : subCommandes.keySet()) {
77 | sb.append("|");
78 | sb.append(subCommand);
79 | sb.append("\n");
80 | }
81 | sb.append("================================================");
82 | sb.append("\n");
83 | sb.append("Please use 'hugegraph help' to get detail help info " +
84 | "of all sub-commands or 'hugegraph help {sub-command}' " +
85 | "to get detail help info of one sub-command");
86 | sb.append("\n");
87 | sb.append("================================================");
88 |
89 | return sb.toString();
90 | }
91 |
92 | public static String commandUsage(JCommander jCommander) {
93 | StringBuilder sb = new StringBuilder();
94 | jCommander.usage(sb);
95 |
96 | return sb.toString();
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/src/test/java/com/baidu/hugegraph/test/functional/AuthBackupTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.test.functional;
21 |
22 | import java.util.List;
23 |
24 | import org.junit.Before;
25 | import org.junit.Test;
26 |
27 | import com.baidu.hugegraph.cmd.HugeGraphCommand;
28 | import com.baidu.hugegraph.test.util.FileUtil;
29 | import com.baidu.hugegraph.testutil.Assert;
30 |
31 | public class AuthBackupTest extends AuthTest {
32 |
33 | @Before
34 | public void init() {
35 | FileUtil.clearDirectories(DEFAULT_URL);
36 | }
37 |
38 | @Test
39 | public void testAuthBackup() {
40 | String[] args = new String[]{
41 | "--throw-mode", "true",
42 | "--user", USER_NAME,
43 | "--password", USER_PASSWORD,
44 | "auth-backup"
45 | };
46 |
47 | HugeGraphCommand.main(args);
48 |
49 | Assert.assertTrue(FileUtil.checkFileExists(DEFAULT_URL));
50 | List fileNames = FileUtil.subdirectories(DEFAULT_URL);
51 | Assert.assertTrue(fileNames.size() == 5);
52 | }
53 |
54 | @Test
55 | public void testAuthBackupByTypes() {
56 | String[] args = new String[]{
57 | "--throw-mode", "true",
58 | "--user", USER_NAME,
59 | "--password", USER_PASSWORD,
60 | "auth-backup",
61 | "--types", "user,group"
62 | };
63 |
64 | HugeGraphCommand.main(args);
65 |
66 | Assert.assertTrue(FileUtil.checkFileExists(DEFAULT_URL));
67 | List fileNames = FileUtil.subdirectories(DEFAULT_URL);
68 | Assert.assertTrue(fileNames.size() == 2);
69 | }
70 |
71 | @Test
72 | public void testAuthBackupWithWrongType() {
73 | String[] args = new String[]{
74 | "--throw-mode", "true",
75 | "--user", USER_NAME,
76 | "--password", USER_PASSWORD,
77 | "auth-backup",
78 | "--types", "user,group,test"
79 | };
80 |
81 | Assert.assertThrows(IllegalArgumentException.class, () -> {
82 | HugeGraphCommand.main(args);
83 | }, e -> {
84 | Assert.assertContains("valid value is 'all' or combination of " +
85 | "[user,group,target,belong,access]",
86 | e.getMessage());
87 | });
88 | }
89 |
90 | @Test
91 | public void testAuthBackupByDirectory() {
92 | String directory = "./backup";
93 | String[] args = new String[]{
94 | "--throw-mode", "true",
95 | "--user", USER_NAME,
96 | "--password", USER_PASSWORD,
97 | "auth-backup",
98 | "--directory", directory
99 | };
100 |
101 | HugeGraphCommand.main(args);
102 |
103 | Assert.assertTrue(FileUtil.checkFileExists(directory));
104 | List fileNames = FileUtil.subdirectories(directory);
105 | Assert.assertTrue(fileNames.size() == 5);
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/assembly/bin/hugegraph:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Set environment here if needed
4 | #export HUGEGRAPH_URL=
5 | #export HUGEGRAPH_GRAPH=
6 | #export HUGEGRAPH_USERNAME=
7 | #export HUGEGRAPH_PASSWORD=
8 | #export HUGEGRAPH_TIMEOUT=
9 | #export HUGEGRAPH_TRUST_STORE_FILE=
10 | #export HUGEGRAPH_TRUST_STORE_PASSWORD=
11 |
12 | abs_path() {
13 | SOURCE="${BASH_SOURCE[0]}"
14 | while [ -h "$SOURCE" ]; do
15 | DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
16 | SOURCE="$(readlink "$SOURCE")"
17 | [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
18 | done
19 | echo "$( cd -P "$( dirname "$SOURCE" )" && pwd )"
20 | }
21 |
22 | BIN=`abs_path`
23 | TOP="$(cd $BIN/../ && pwd)"
24 | LIB=$TOP/lib:$JAVA_HOME/lib/ext:$JAVA_HOME/jre/lib/ext
25 |
26 | . $BIN/util.sh
27 |
28 | MAX_MEM=$[96*1024]
29 | MIN_MEM=512
30 |
31 | if [ -n "$JAVA_HOME" ]; then
32 | JAVA="$JAVA_HOME"/bin/java
33 | else
34 | JAVA=java
35 | echo "Warning: please set JAVA_HOME variable, otherwise some libraries related to https may be missing"
36 | fi
37 |
38 | if [ "$1" == "deploy" ]; then
39 | shift
40 | bash $BIN/deploy.sh $@
41 | exit $?
42 | fi
43 |
44 | if [ "$1" == "start-all" ]; then
45 | shift
46 | bash $BIN/start-all.sh $@
47 | exit $?
48 | fi
49 |
50 | if [ "$1" == "clear" ]; then
51 | shift
52 | bash $BIN/clear.sh $@
53 | exit $?
54 | fi
55 |
56 | if [ "$1" == "stop-all" ]; then
57 | bash $BIN/stop-all.sh
58 | exit $?
59 | fi
60 |
61 | # Set default environment variables if not exist
62 | echo $* | grep "\--url" > /dev/null 2>&1
63 | if [ $? -ne 0 -a -n "$HUGEGRAPH_URL" ]; then
64 | URL_ARG="--url $HUGEGRAPH_URL"
65 | else
66 | URL_ARG=""
67 | fi
68 |
69 | echo $* | grep "\--graph " > /dev/null 2>&1
70 | if [ $? -ne 0 -a -n "$HUGEGRAPH_GRAPH" ]; then
71 | GRAPH_ARG="--graph $HUGEGRAPH_GRAPH"
72 | else
73 | GRAPH_ARG=""
74 | fi
75 |
76 | echo $* | grep "\--user" > /dev/null 2>&1
77 | if [ $? -ne 0 -a -n "$HUGEGRAPH_USERNAME" ]; then
78 | USER_ARG="--user $HUGEGRAPH_USERNAME"
79 | else
80 | USER_ARG=""
81 | fi
82 |
83 | echo $* | grep "\--password" > /dev/null 2>&1
84 | if [ $? -ne 0 -a -n "$HUGEGRAPH_PASSWORD" ]; then
85 | PASSWORD_ARG="--password $HUGEGRAPH_PASSWORD"
86 | else
87 | PASSWORD_ARG=""
88 | fi
89 |
90 | echo $* | grep "\--timeout" > /dev/null 2>&1
91 | if [ $? -ne 0 -a -n "$HUGEGRAPH_TIMEOUT" ]; then
92 | TIMEOUT_ARG="--timeout $HUGEGRAPH_TIMEOUT"
93 | else
94 | TIMEOUT_ARG=""
95 | fi
96 |
97 | echo $* | grep "\--trust-store-file" > /dev/null 2>&1
98 | if [ $? -ne 0 -a -n "$HUGEGRAPH_TRUST_STORE_FILE" ]; then
99 | TRUST_STORE_FILE_ARG="--trust-store-file $HUGEGRAPH_TRUST_STORE_FILE"
100 | else
101 | TRUST_STORE_FILE_ARG=""
102 | fi
103 |
104 | echo $* | grep "\--trust-store-password" > /dev/null 2>&1
105 | if [ $? -ne 0 -a -n "$HUGEGRAPH_TRUST_STORE_PASSWORD" ]; then
106 | TRUST_STORE_PASSWORD_ARG="--trust-store-password $HUGEGRAPH_TRUST_STORE_PASSWORD"
107 | else
108 | TRUST_STORE_PASSWORD_ARG=""
109 | fi
110 |
111 | for ((i=1;i<=$#;i++));
112 | do
113 | if [ "`eval echo '$'"$i"`" == "schedule-backup" ]; then
114 | ARGS=${*//schedule-backup/}
115 | bash $BIN/schedule-backup.sh $URL_ARG $GRAPH_ARG $USER_ARG $PASSWORD_ARG $TIMEOUT_ARG $TRUST_STORE_FILE_ARG $TRUST_STORE_PASSWORD_ARG ${ARGS//'*'/'\*'}
116 | exit $?
117 | fi
118 | done
119 |
120 | # Set Java options
121 | if [ "$JAVA_OPTIONS" = "" ] ; then
122 | XMX=`calc_xmx $MIN_MEM $MAX_MEM`
123 | if [ $? -ne 0 ]; then
124 | echo "Failed to run bin/hugegraph, requires at least ${MIN_MEM}m free memory"
125 | exit 1
126 | fi
127 | JAVA_OPTIONS="-Xms${MIN_MEM}m -Xmx${XMX}m"
128 | fi
129 |
130 | exec $JAVA -Dtools.home.path=${TOP} $JAVA_OPTIONS -cp $LIB/hugegraph-tools-*.jar -Djava.ext.dirs=$LIB/ \
131 | com.baidu.hugegraph.cmd.HugeGraphCommand $URL_ARG $GRAPH_ARG $USER_ARG $PASSWORD_ARG $TIMEOUT_ARG $TRUST_STORE_FILE_ARG $TRUST_STORE_PASSWORD_ARG "$@"
132 |
--------------------------------------------------------------------------------
/assembly/bin/deploy.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | VERSION=""
4 | INSTALL_PATH=""
5 | DOWNLOAD_LINK_PREFIX=""
6 | DEFAULT_DOWNLOAD_LINK_PREFIX="https://github.com/hugegraph"
7 | DOWNLOAD_LINK_PREFIX_CONFIG=`env | grep ^HOME= | cut -c 6-`"/hugegraph-download-url-prefix"
8 |
9 | function print_usage() {
10 | echo "USAGE: $0 -v {hugegraph-version} -p {install-path} [-u {download-path-prefix}]"
11 | echo "eg : $0 -v 0.8 -p ./ [-u http://xxx]"
12 | }
13 |
14 | while getopts "v:p:u:" arg; do
15 | case ${arg} in
16 | v) VERSION="$OPTARG" ;;
17 | p) INSTALL_PATH="$OPTARG" ;;
18 | u) DOWNLOAD_LINK_PREFIX="$OPTARG" ;;
19 | ?) print_usage && exit 1 ;;
20 | esac
21 | done
22 |
23 | if [[ "$VERSION" = "" || "$INSTALL_PATH" = "" ]]; then
24 | print_usage
25 | exit 1
26 | fi
27 |
28 | if [[ "$DOWNLOAD_LINK_PREFIX" = "" ]]; then
29 | if [ -f ${DOWNLOAD_LINK_PREFIX_CONFIG} ]; then
30 | DOWNLOAD_LINK_PREFIX=`sed -n "1p" ${DOWNLOAD_LINK_PREFIX_CONFIG}`
31 | else
32 | DOWNLOAD_LINK_PREFIX=${DEFAULT_DOWNLOAD_LINK_PREFIX}
33 | fi
34 | else
35 | echo ${DOWNLOAD_LINK_PREFIX} > ${DOWNLOAD_LINK_PREFIX_CONFIG}
36 | fi
37 |
38 | function abs_path() {
39 | SOURCE="${BASH_SOURCE[0]}"
40 | while [ -h "$SOURCE" ]; do
41 | DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
42 | SOURCE="$(readlink "$SOURCE")"
43 | [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
44 | done
45 | echo "$( cd -P "$( dirname "$SOURCE" )" && pwd )"
46 | }
47 |
48 | BIN=`abs_path`
49 | . ${BIN}/util.sh
50 |
51 | `ensure_path_writable ${INSTALL_PATH}`
52 |
53 | # Convert to absolute path
54 | INSTALL_PATH="$(cd ${INSTALL_PATH} && pwd)"
55 |
56 | cd ${BIN}
57 |
58 | # Check input version can be found in version-map.yaml
59 | OPTIONAL_VERSIONS=`cat version-map.yaml | grep 'version' | awk -F ':' '{print $1}' | xargs`
60 | if [[ ! "$OPTIONAL_VERSIONS" =~ "$VERSION" ]]; then
61 | echo "Invalid version '${VERSION}' for hugegraph, the optional values are [$OPTIONAL_VERSIONS]"
62 | exit 1
63 | fi
64 |
65 | # Parse module version from 'version-map.yaml'
66 | SERVER_VERSION=`parse_yaml version-map.yaml "${VERSION}" "server"`
67 | if [ "$SERVER_VERSION" = "" ]; then
68 | echo "Not found the key '$VERSION.server' in version-map.yaml"
69 | exit 1
70 | fi
71 | STUDIO_VERSION=`parse_yaml version-map.yaml "${VERSION}" "studio"`
72 | if [ "$STUDIO_VERSION" = "" ]; then
73 | echo "Not found the key '$VERSION.studio' in version-map.yaml"
74 | exit 1
75 | fi
76 |
77 | # Download and unzip
78 | ARCHIVE_FORMAT=".tar.gz"
79 |
80 | # HugeGraphServer dir and tar package name
81 | SERVER_DIR="hugegraph-${SERVER_VERSION}"
82 | SERVER_TAR=${SERVER_DIR}${ARCHIVE_FORMAT}
83 |
84 | # HugeGraphStudio dir and tar package name
85 | STUDIO_DIR="hugegraph-studio-${STUDIO_VERSION}"
86 | STUDIO_TAR=${STUDIO_DIR}${ARCHIVE_FORMAT}
87 |
88 | SERVER_DOWNLOAD_URL="${DOWNLOAD_LINK_PREFIX}/hugegraph/releases/download/v${SERVER_VERSION}/${SERVER_TAR}"
89 | STUDIO_DOWNLOAD_URL="${DOWNLOAD_LINK_PREFIX}/hugegraph-studio/releases/download/v${STUDIO_VERSION}/${STUDIO_TAR}"
90 |
91 | ensure_package_exist $INSTALL_PATH $SERVER_DIR $SERVER_TAR $SERVER_DOWNLOAD_URL
92 | ensure_package_exist $INSTALL_PATH $STUDIO_DIR $STUDIO_TAR $STUDIO_DOWNLOAD_URL
93 |
94 | IP=`get_ip`
95 |
96 | function config_hugegraph_server() {
97 | local rest_server_conf="$SERVER_DIR/conf/rest-server.properties"
98 | local server_url="http://$IP:8080"
99 |
100 | write_property $rest_server_conf "restserver\.url" $server_url
101 | }
102 |
103 | function config_hugegraph_studio() {
104 | local studio_server_conf="$STUDIO_DIR/conf/hugegraph-studio.properties"
105 |
106 | write_property $studio_server_conf "studio\.server\.host" $IP
107 | write_property $studio_server_conf "graph\.server\.host" $IP
108 | }
109 |
110 | cd ${INSTALL_PATH}
111 | config_hugegraph_server
112 | config_hugegraph_studio
113 |
114 | ${SERVER_DIR}/bin/init-store.sh
115 |
116 | ${BIN}/start-all.sh -v ${VERSION} -p ${INSTALL_PATH}
117 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/hugegraph/base/RetryManager.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.base;
21 |
22 | import java.util.Queue;
23 | import java.util.concurrent.ConcurrentLinkedQueue;
24 | import java.util.concurrent.ExecutionException;
25 | import java.util.concurrent.ExecutorService;
26 | import java.util.concurrent.Executors;
27 | import java.util.concurrent.Future;
28 | import java.util.concurrent.TimeUnit;
29 | import java.util.function.Supplier;
30 |
31 | import com.baidu.hugegraph.exception.ToolsException;
32 |
33 | public class RetryManager extends ToolManager {
34 |
35 | private int CPUS = Runtime.getRuntime().availableProcessors();
36 | private int threadsNum = Math.min(10, Math.max(4, CPUS / 2));
37 | private ExecutorService pool;
38 | private final Queue> futures = new ConcurrentLinkedQueue<>();
39 | private int retry = 0;
40 |
41 | public RetryManager(ToolClient.ConnectionInfo info, String type) {
42 | super(info, type);
43 | }
44 |
45 | public void initExecutors() {
46 | Printer.print("Init %s executors", this.threadsNum);
47 | this.pool = Executors.newFixedThreadPool(this.threadsNum);
48 | }
49 |
50 | public R retry(Supplier supplier, String description) {
51 | int retries = 0;
52 | R r = null;
53 | do {
54 | try {
55 | r = supplier.get();
56 | } catch (Exception e) {
57 | if (retries == this.retry) {
58 | throw new ToolsException(
59 | "Exception occurred while %s(after %s retries)",
60 | e, description, this.retry);
61 | }
62 | // Ignore exception and retry
63 | continue;
64 | }
65 | break;
66 | } while (retries++ < this.retry);
67 | return r;
68 | }
69 |
70 | public void submit(Runnable task) {
71 | this.futures.add(this.pool.submit(task));
72 | }
73 |
74 | public void awaitTasks() {
75 | Future> future;
76 | while ((future = this.futures.poll()) != null) {
77 | try {
78 | future.get();
79 | } catch (InterruptedException | ExecutionException e) {
80 | e.printStackTrace();
81 | }
82 | }
83 | }
84 |
85 | public void shutdown(String taskType) {
86 | if (this.pool == null) {
87 | return;
88 | }
89 | this.pool.shutdown();
90 | try {
91 | this.pool.awaitTermination(24, TimeUnit.HOURS);
92 | } catch (InterruptedException e) {
93 | throw new ToolsException(
94 | "Exception appears in %s threads", e, taskType);
95 | }
96 | }
97 |
98 | public int retry() {
99 | return this.retry;
100 | }
101 |
102 | public void retry(int retry) {
103 | this.retry = retry;
104 | }
105 |
106 | public int threadsNum() {
107 | return this.threadsNum;
108 | }
109 |
110 | public void threadsNum(int threadsNum) {
111 | if (threadsNum > 0) {
112 | this.threadsNum = threadsNum;
113 | }
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/hugegraph/formatter/kgdumper/ComputeSign.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.formatter.kgdumper;
21 |
22 | import java.io.File;
23 | import java.io.FileInputStream;
24 | import java.io.IOException;
25 | import java.io.UnsupportedEncodingException;
26 | import java.util.ArrayList;
27 | import java.util.HashMap;
28 | import java.util.LinkedHashMap;
29 | import java.util.List;
30 | import java.util.Map;
31 |
32 | public class ComputeSign {
33 |
34 | private Map tradeValue2Num;
35 | private LinkedHashMap entPlain2Id;
36 | private String inputEncoding;
37 |
38 | public ComputeSign(String tradeValueFile, String inputEncode)
39 | throws IOException {
40 |
41 | File file = new File(tradeValueFile);
42 | Long fileLen = file.length();
43 | byte[] fileBytes = new byte[fileLen.intValue()];
44 | try (FileInputStream in = new FileInputStream(file)) {
45 | in.read(fileBytes);
46 | }
47 |
48 | tradeValue2Num = new HashMap<>();
49 | String fileContent = new String(fileBytes);
50 | String[] lines = fileContent.split("\n");
51 | for (int i = 0; i < lines.length; i++) {
52 | String[] cols = lines[i].split("\t");
53 | if (cols.length >= 2) {
54 | tradeValue2Num.put(cols[0], Integer.valueOf(cols[1]));
55 | }
56 | }
57 | inputEncoding = inputEncode;
58 |
59 | final int cacheSize = 1000;
60 | final int capacity = (int) Math.ceil(cacheSize / 0.75f) + 1;
61 | entPlain2Id = new LinkedHashMap(capacity, 0.75f, true) {
62 | @Override
63 | protected boolean removeEldestEntry(Map.Entry e) {
64 | return size() > cacheSize;
65 | }
66 | };
67 | }
68 |
69 | public synchronized String computeSeqNum(String entPlain)
70 | throws UnsupportedEncodingException {
71 | String seqNum = "0";
72 | if (entPlain2Id.containsKey(entPlain)) {
73 | seqNum = entPlain2Id.get(entPlain);
74 | return seqNum;
75 | }
76 |
77 | String[] entSpa = entPlain.split("__");
78 | if (entSpa.length != 3) {
79 | return seqNum;
80 | }
81 | List trans = new ArrayList<>();
82 | if (tradeValue2Num.containsKey(entSpa[0])) {
83 | trans.add(tradeValue2Num.get(entSpa[0]).toString());
84 | } else {
85 | trans.add(entSpa[0]);
86 | }
87 | trans.add(entSpa[1]);
88 | if (entSpa[1].contains("trade") &&
89 | tradeValue2Num.containsKey(entSpa[2])) {
90 | trans.add(tradeValue2Num.get(entSpa[2]).toString());
91 | } else {
92 | trans.add(entSpa[2]);
93 | }
94 | if (trans.contains("common") && trans.contains("regioncode")) {
95 | seqNum = trans.get(2);
96 | } else {
97 | String text = String.join("__", trans);
98 | seqNum = SignFS64.createSignFs64(text, inputEncoding);
99 | }
100 | entPlain2Id.put(entPlain, seqNum);
101 | return seqNum;
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/src/test/java/com/baidu/hugegraph/test/functional/CommandTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.test.functional;
21 |
22 | import org.junit.Test;
23 |
24 | import com.baidu.hugegraph.cmd.HugeGraphCommand;
25 | import com.baidu.hugegraph.exception.ExitException;
26 | import com.baidu.hugegraph.testutil.Assert;
27 |
28 | public class CommandTest extends AuthTest {
29 |
30 | @Test
31 | public void testHelpCommand() {
32 | String[] args = new String[]{
33 | "--throw-mode", "true",
34 | "--user", USER_NAME,
35 | "--password", USER_PASSWORD,
36 | "help"
37 | };
38 |
39 | Assert.assertThrows(ExitException.class, () -> {
40 | HugeGraphCommand.main(args);
41 | }, e -> {
42 | ExitException exception = (ExitException) e;
43 | Assert.assertContains("Command : hugegragh help",
44 | exception.getMessage());
45 | Assert.assertContains("Usage: hugegraph [options] [command]",
46 | exception.details());
47 | });
48 | }
49 |
50 | @Test
51 | public void testHelpSubCommand() {
52 | String[] args = new String[]{
53 | "--throw-mode", "true",
54 | "--user", USER_NAME,
55 | "--password", USER_PASSWORD,
56 | "help", "auth-backup"
57 | };
58 |
59 | Assert.assertThrows(ExitException.class, () -> {
60 | HugeGraphCommand.main(args);
61 | }, e -> {
62 | ExitException exception = (ExitException) e;
63 | Assert.assertContains("Command : hugegragh help auth-backup",
64 | exception.getMessage());
65 | Assert.assertContains("Usage: auth-backup [options]",
66 | exception.details());
67 | });
68 | }
69 |
70 | @Test
71 | public void testBadHelpSubCommandException() {
72 | String badCommand = "asd";
73 | String[] args = new String[]{
74 | "--throw-mode", "true",
75 | "--user", USER_NAME,
76 | "--password", USER_PASSWORD,
77 | "help", badCommand
78 | };
79 |
80 | Assert.assertThrows(ExitException.class, () -> {
81 | HugeGraphCommand.main(args);
82 | }, e -> {
83 | ExitException exception = (ExitException) e;
84 | Assert.assertContains(String.format(
85 | "Unexpected help sub-command %s",
86 | badCommand), exception.getMessage());
87 | Assert.assertContains("Here are some sub-command ",
88 | exception.details());
89 | });
90 | }
91 |
92 | @Test
93 | public void testEmptyCommandException() {
94 | String[] args = new String[]{
95 | "--throw-mode", "true",
96 | "--user", USER_NAME,
97 | "--password", USER_PASSWORD
98 | };
99 |
100 | Assert.assertThrows(ExitException.class, () -> {
101 | HugeGraphCommand.main(args);
102 | }, e -> {
103 | ExitException exception = (ExitException) e;
104 | Assert.assertContains("No sub-command found",
105 | exception.getMessage());
106 | Assert.assertContains("Warning : must provide one sub-command",
107 | exception.details());
108 | });
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/src/test/java/com/baidu/hugegraph/test/util/FileUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.test.util;
21 |
22 | import java.io.BufferedReader;
23 | import java.io.ByteArrayOutputStream;
24 | import java.io.File;
25 | import java.io.FileInputStream;
26 | import java.io.FileOutputStream;
27 | import java.io.IOException;
28 | import java.io.InputStream;
29 | import java.io.InputStreamReader;
30 | import java.nio.file.Paths;
31 | import java.util.List;
32 |
33 | import org.apache.commons.collections.ListUtils;
34 |
35 | import com.baidu.hugegraph.api.API;
36 | import com.baidu.hugegraph.exception.ToolsException;
37 | import com.google.common.collect.Lists;
38 |
39 | public class FileUtil {
40 |
41 | protected static final int LBUF_SIZE = 1024;
42 | protected static final String CONFIG_PATH = "src/test/resources";
43 |
44 | public static String configPath(String fileName) {
45 | return Paths.get(CONFIG_PATH, fileName).toString();
46 | }
47 |
48 | public static boolean checkFileExists(String filePath) {
49 | File file = new File(filePath);
50 | if (file.exists()) {
51 | return true;
52 | }
53 | return false;
54 | }
55 |
56 | public static List subdirectories(String filePath) {
57 | File file = new File(filePath);
58 | if (!file.exists()) {
59 | return ListUtils.EMPTY_LIST;
60 | }
61 | String[] files = file.list();
62 | List list = Lists.newArrayList();
63 | for (int i = 0; i < files.length; i++) {
64 | File fileDir = new File(file, files[i]);
65 | list.add(fileDir.getName());
66 | }
67 |
68 | return list;
69 | }
70 |
71 | public static void clearDirectories(String filePath) {
72 | File file = new File(filePath);
73 | if (file.exists()) {
74 | String[] files = file.list();
75 | for (int i = 0; i < files.length; i++) {
76 | File fileDir = new File(file, files[i]);
77 | fileDir.delete();
78 | }
79 | }
80 | }
81 |
82 | public static long writeTestRestoreData(String filePath, List> list) {
83 | long count = 0L;
84 | try (FileOutputStream os = new FileOutputStream(filePath);
85 | ByteArrayOutputStream baos = new ByteArrayOutputStream(LBUF_SIZE)) {
86 | StringBuilder builder = new StringBuilder(LBUF_SIZE);
87 | for (Object e : list) {
88 | count++;
89 | builder.append(e).append("\n");
90 | }
91 | baos.write(builder.toString().getBytes(API.CHARSET));
92 | os.write(baos.toByteArray());
93 | } catch (IOException e) {
94 | throw new ToolsException("Failed write file path is %s",
95 | e, filePath);
96 | }
97 |
98 | return count;
99 | }
100 |
101 | public static List readTestRestoreData(String filePath) {
102 | List results = Lists.newArrayList();
103 | try (InputStream is = new FileInputStream(filePath);
104 | InputStreamReader isr = new InputStreamReader(is, API.CHARSET)) {
105 | BufferedReader reader = new BufferedReader(isr);
106 | String line;
107 | while ((line = reader.readLine()) != null) {
108 | results.add(line);
109 | }
110 | } catch (IOException e) {
111 | throw new ToolsException("Failed read file path is %s",
112 | e, filePath);
113 | }
114 |
115 | return results;
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/hugegraph/manager/DumpGraphManager.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.manager;
21 |
22 | import java.io.BufferedOutputStream;
23 | import java.io.OutputStream;
24 | import java.util.Collection;
25 | import java.util.List;
26 |
27 | import com.baidu.hugegraph.api.API;
28 | import com.baidu.hugegraph.base.LocalDirectory;
29 | import com.baidu.hugegraph.base.Printer;
30 | import com.baidu.hugegraph.base.ToolClient;
31 | import com.baidu.hugegraph.cmd.SubCommands;
32 | import com.baidu.hugegraph.formatter.Formatter;
33 | import com.baidu.hugegraph.structure.JsonGraph;
34 | import com.baidu.hugegraph.structure.JsonGraph.JsonVertex;
35 | import com.baidu.hugegraph.structure.constant.HugeType;
36 | import com.baidu.hugegraph.structure.graph.Edge;
37 | import com.baidu.hugegraph.structure.graph.Vertex;
38 |
39 | public class DumpGraphManager extends BackupManager {
40 |
41 | private static final byte[] EOF = "\n".getBytes();
42 |
43 | private final JsonGraph graph;
44 |
45 | private Formatter dumpFormatter;
46 |
47 | public DumpGraphManager(ToolClient.ConnectionInfo info) {
48 | this(info, "JsonFormatter");
49 | }
50 |
51 | public DumpGraphManager(ToolClient.ConnectionInfo info, String formatter) {
52 | super(info);
53 | this.graph = new JsonGraph();
54 | this.dumpFormatter = Formatter.loadFormatter(formatter);
55 | }
56 |
57 | public void dumpFormatter(String formatter) {
58 | this.dumpFormatter = Formatter.loadFormatter(formatter);
59 | }
60 |
61 | public void init(SubCommands.DumpGraph dump) {
62 | assert dump.retry() > 0;
63 | this.retry(dump.retry());
64 | LocalDirectory.ensureDirectoryExist(dump.logDir());
65 | this.logDir(dump.logDir());
66 | this.directory(dump.directory(), dump.hdfsConf());
67 | this.removeShardsFilesIfExists();
68 | this.ensureDirectoryExist(true);
69 | this.splitSize(dump.splitSize());
70 | }
71 |
72 | public void dump() {
73 | this.startTimer();
74 | try {
75 | // Fetch data to JsonGraph
76 | this.backupVertices();
77 | this.backupEdges();
78 |
79 | // Dump to file
80 | for (String table : this.graph.tables()) {
81 | this.submit(() -> dump(table, this.graph.table(table).values()));
82 | }
83 | } catch (Throwable e) {
84 | throw e;
85 | } finally {
86 | this.shutdown(this.type());
87 | }
88 |
89 | this.printSummary("dump graph");
90 | }
91 |
92 | private void dump(String file, Collection vertices) {
93 | try (OutputStream os = this.outputStream(file, false);
94 | BufferedOutputStream bos = new BufferedOutputStream(os)) {
95 | for (JsonVertex vertex : vertices) {
96 | String content = this.dumpFormatter.dump(vertex);
97 | bos.write(content.getBytes(API.CHARSET));
98 | bos.write(EOF);
99 | }
100 | } catch (Throwable e) {
101 | Printer.print("Failed to write vertex: %s", e);
102 | }
103 | }
104 |
105 | @Override
106 | protected long write(String file, HugeType type,
107 | List> list, boolean compress) {
108 | switch (type) {
109 | case VERTEX:
110 | for (Object vertex : list) {
111 | this.graph.put((Vertex) vertex);
112 | }
113 | break;
114 | case EDGE:
115 | for (Object edge : list) {
116 | this.graph.put((Edge) edge);
117 | }
118 | break;
119 | default:
120 | throw new AssertionError("Invalid type " + type);
121 | }
122 | return list.size();
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/assembly/travis/conf/gremlin-server.yaml:
--------------------------------------------------------------------------------
1 | # host and port of gremlin server, need to be consistent with host and port in rest-server.properties
2 | #host: 127.0.0.1
3 | #port: 8182
4 |
5 | # timeout in ms of gremlin query
6 | scriptEvaluationTimeout: 30000
7 |
8 | channelizer: org.apache.tinkerpop.gremlin.server.channel.WsAndHttpChannelizer
9 | # don't set graph at here, this happens after support for dynamically adding graph
10 | graphs: {
11 | }
12 | scriptEngines: {
13 | gremlin-groovy: {
14 | plugins: {
15 | com.baidu.hugegraph.plugin.HugeGraphGremlinPlugin: {},
16 | org.apache.tinkerpop.gremlin.server.jsr223.GremlinServerGremlinPlugin: {},
17 | org.apache.tinkerpop.gremlin.jsr223.ImportGremlinPlugin: {
18 | classImports: [
19 | java.lang.Math,
20 | com.baidu.hugegraph.backend.id.IdGenerator,
21 | com.baidu.hugegraph.type.define.Directions,
22 | com.baidu.hugegraph.type.define.NodeRole,
23 | com.baidu.hugegraph.traversal.algorithm.CollectionPathsTraverser,
24 | com.baidu.hugegraph.traversal.algorithm.CountTraverser,
25 | com.baidu.hugegraph.traversal.algorithm.CustomizedCrosspointsTraverser,
26 | com.baidu.hugegraph.traversal.algorithm.CustomizePathsTraverser,
27 | com.baidu.hugegraph.traversal.algorithm.FusiformSimilarityTraverser,
28 | com.baidu.hugegraph.traversal.algorithm.HugeTraverser,
29 | com.baidu.hugegraph.traversal.algorithm.JaccardSimilarTraverser,
30 | com.baidu.hugegraph.traversal.algorithm.KneighborTraverser,
31 | com.baidu.hugegraph.traversal.algorithm.KoutTraverser,
32 | com.baidu.hugegraph.traversal.algorithm.MultiNodeShortestPathTraverser,
33 | com.baidu.hugegraph.traversal.algorithm.NeighborRankTraverser,
34 | com.baidu.hugegraph.traversal.algorithm.PathsTraverser,
35 | com.baidu.hugegraph.traversal.algorithm.PersonalRankTraverser,
36 | com.baidu.hugegraph.traversal.algorithm.SameNeighborTraverser,
37 | com.baidu.hugegraph.traversal.algorithm.ShortestPathTraverser,
38 | com.baidu.hugegraph.traversal.algorithm.SingleSourceShortestPathTraverser,
39 | com.baidu.hugegraph.traversal.algorithm.SubGraphTraverser,
40 | com.baidu.hugegraph.traversal.algorithm.TemplatePathsTraverser,
41 | com.baidu.hugegraph.traversal.algorithm.steps.EdgeStep,
42 | com.baidu.hugegraph.traversal.algorithm.steps.RepeatEdgeStep,
43 | com.baidu.hugegraph.traversal.algorithm.steps.WeightedEdgeStep,
44 | com.baidu.hugegraph.traversal.optimize.Text,
45 | com.baidu.hugegraph.traversal.optimize.TraversalUtil,
46 | com.baidu.hugegraph.util.DateUtil
47 | ],
48 | methodImports: [java.lang.Math#*]
49 | },
50 | org.apache.tinkerpop.gremlin.jsr223.ScriptFileGremlinPlugin: {
51 | files: [scripts/empty-sample.groovy]
52 | }
53 | }
54 | }
55 | }
56 | serializers:
57 | - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphBinaryMessageSerializerV1,
58 | config: {
59 | serializeResultToString: false,
60 | ioRegistries: [com.baidu.hugegraph.io.HugeGraphIoRegistry]
61 | }
62 | }
63 | - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV1d0,
64 | config: {
65 | serializeResultToString: false,
66 | ioRegistries: [com.baidu.hugegraph.io.HugeGraphIoRegistry]
67 | }
68 | }
69 | - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV2d0,
70 | config: {
71 | serializeResultToString: false,
72 | ioRegistries: [com.baidu.hugegraph.io.HugeGraphIoRegistry]
73 | }
74 | }
75 | - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV3d0,
76 | config: {
77 | serializeResultToString: false,
78 | ioRegistries: [com.baidu.hugegraph.io.HugeGraphIoRegistry]
79 | }
80 | }
81 | metrics: {
82 | consoleReporter: {enabled: false, interval: 180000},
83 | csvReporter: {enabled: false, interval: 180000, fileName: ./metrics/gremlin-server-metrics.csv},
84 | jmxReporter: {enabled: false},
85 | slf4jReporter: {enabled: false, interval: 180000},
86 | gangliaReporter: {enabled: false, interval: 180000, addressingMode: MULTICAST},
87 | graphiteReporter: {enabled: false, interval: 180000}
88 | }
89 | maxInitialLineLength: 4096
90 | maxHeaderSize: 8192
91 | maxChunkSize: 8192
92 | maxContentLength: 65536
93 | maxAccumulationBufferComponents: 1024
94 | resultIterationBatchSize: 64
95 | writeBufferLowWaterMark: 32768
96 | writeBufferHighWaterMark: 65536
97 | ssl: {
98 | enabled: false
99 | }
100 | authentication: {
101 | authenticator: com.baidu.hugegraph.auth.StandardAuthenticator,
102 | authenticationHandler: com.baidu.hugegraph.auth.WsAndHttpBasicAuthHandler,
103 | config: {tokens: conf/rest-server.properties}
104 | }
105 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/hugegraph/base/ToolClient.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.base;
21 |
22 | import java.nio.file.Paths;
23 |
24 | import org.apache.commons.lang3.StringUtils;
25 |
26 | import com.baidu.hugegraph.driver.AuthManager;
27 | import com.baidu.hugegraph.driver.GraphManager;
28 | import com.baidu.hugegraph.driver.GremlinManager;
29 | import com.baidu.hugegraph.driver.HugeClient;
30 | import com.baidu.hugegraph.driver.SchemaManager;
31 | import com.baidu.hugegraph.driver.TaskManager;
32 | import com.baidu.hugegraph.driver.TraverserManager;
33 | import com.baidu.hugegraph.util.E;
34 | import com.fasterxml.jackson.databind.ObjectMapper;
35 |
36 | public class ToolClient {
37 |
38 | private static final String DEFAULT_TRUST_STORE_FILE =
39 | "conf/hugegraph.truststore";
40 | private static final String DEFAULT_TRUST_STORE_PASSWORD = "hugegraph";
41 |
42 | private HugeClient client;
43 | private ObjectMapper mapper;
44 |
45 | public ToolClient(ConnectionInfo info) {
46 | if (info.username == null) {
47 | info.username = "";
48 | info.password = "";
49 | }
50 | String trustStoreFile, trustStorePassword;
51 | if (info.url.startsWith("https")) {
52 | if (info.trustStoreFile == null || info.trustStoreFile.isEmpty()) {
53 | trustStoreFile = Paths.get(homePath(), DEFAULT_TRUST_STORE_FILE)
54 | .toString();
55 | trustStorePassword = DEFAULT_TRUST_STORE_PASSWORD;
56 | } else {
57 | E.checkArgumentNotNull(info.trustStorePassword,
58 | "The trust store password can't be " +
59 | "null when use https");
60 | trustStoreFile = info.trustStoreFile;
61 | trustStorePassword = info.trustStorePassword;
62 | }
63 | } else {
64 | assert info.url.startsWith("http");
65 | E.checkArgument(info.trustStoreFile == null,
66 | "Can't set --trust-store-file when use http");
67 | E.checkArgument(info.trustStorePassword == null,
68 | "Can't set --trust-store-password when use http");
69 | trustStoreFile = info.trustStoreFile;
70 | trustStorePassword = info.trustStorePassword;
71 | }
72 | this.client = HugeClient.builder(info.url, info.graph)
73 | .configUser(info.username, info.password)
74 | .configTimeout(info.timeout)
75 | .configSSL(trustStoreFile, trustStorePassword)
76 | .build();
77 |
78 | this.mapper = new ObjectMapper();
79 | }
80 |
81 | public TraverserManager traverser() {
82 | return this.client.traverser();
83 | }
84 |
85 | public GraphManager graph() {
86 | return this.client.graph();
87 | }
88 |
89 | public SchemaManager schema() {
90 | return this.client.schema();
91 | }
92 |
93 | public com.baidu.hugegraph.driver.GraphsManager graphs() {
94 | return this.client.graphs();
95 | }
96 |
97 | public TaskManager tasks() {
98 | return this.client.task();
99 | }
100 |
101 | public GremlinManager gremlin() {
102 | return this.client.gremlin();
103 | }
104 |
105 | public ObjectMapper mapper() {
106 | return this.mapper;
107 | }
108 |
109 | public static String homePath() {
110 | String homePath = System.getProperty("tools.home.path");
111 | E.checkArgument(StringUtils.isNotEmpty(homePath),
112 | "The system property 'tools.home.path' " +
113 | "can't be empty when enable https protocol");
114 | return homePath;
115 | }
116 |
117 | public AuthManager authManager() {
118 | return this.client.auth();
119 | }
120 |
121 | public void close() {
122 | if (this.client != null) {
123 | this.client.close();
124 | }
125 | }
126 |
127 | public static class ConnectionInfo {
128 |
129 | private String url;
130 | private String graph;
131 | private String username;
132 | private String password;
133 | private Integer timeout;
134 | private String trustStoreFile;
135 | private String trustStorePassword;
136 |
137 | public ConnectionInfo(String url, String graph,
138 | String username, String password,
139 | Integer timeout,
140 | String trustStoreFile,
141 | String trustStorePassword) {
142 | this.url = url;
143 | this.graph = graph;
144 | this.username = username;
145 | this.password = password;
146 | this.timeout = timeout;
147 | this.trustStoreFile = trustStoreFile;
148 | this.trustStorePassword = trustStorePassword;
149 | }
150 | }
151 | }
152 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/hugegraph/structure/JsonGraph.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 HugeGraph Authors
3 | *
4 | * Licensed to the Apache Software Foundation (ASF) under one or more
5 | * contributor license agreements. See the NOTICE file distributed with this
6 | * work for additional information regarding copyright ownership. The ASF
7 | * licenses this file to You under the Apache License, Version 2.0 (the
8 | * "License"); you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | * License for the specific language governing permissions and limitations
17 | * under the License.
18 | */
19 |
20 | package com.baidu.hugegraph.structure;
21 |
22 | import java.util.Map;
23 | import java.util.Set;
24 | import java.util.concurrent.ConcurrentHashMap;
25 |
26 | import org.eclipse.jetty.util.ConcurrentHashSet;
27 |
28 | import com.baidu.hugegraph.structure.graph.Edge;
29 | import com.baidu.hugegraph.structure.graph.Vertex;
30 | import com.baidu.hugegraph.util.JsonUtil;
31 | import com.fasterxml.jackson.annotation.JsonRawValue;
32 |
33 | public class JsonGraph {
34 |
35 | private static final int INIT_VERTEX_CAPACITY = 1_000_000;
36 |
37 | private Map> tables;
38 |
39 | public JsonGraph() {
40 | this.tables = new ConcurrentHashMap<>();
41 | }
42 |
43 | public Set tables() {
44 | return this.tables.keySet();
45 | }
46 |
47 | public void put(Vertex vertex) {
48 | // Add vertex to table of `label`
49 | Map