Compare commits
7 commits
master
...
support/v0
Author | SHA1 | Date | |
---|---|---|---|
71b40185a9 | |||
|
e1de48ff67 | ||
|
14377dff9a | ||
af73636125 | |||
|
ec921e75dd | ||
|
f27e2e10e1 | ||
b4c1600fd3 |
126 changed files with 4763 additions and 12149 deletions
|
@ -1,20 +0,0 @@
|
||||||
---
|
|
||||||
name: Feature request
|
|
||||||
about: Suggest an idea for this project
|
|
||||||
title: ''
|
|
||||||
labels: community, triage
|
|
||||||
assignees: ''
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Is your feature request related to a problem? Please describe.
|
|
||||||
<!--- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->
|
|
||||||
|
|
||||||
## Describe the solution you'd like
|
|
||||||
<!--- A clear and concise description of what you want to happen. -->
|
|
||||||
|
|
||||||
## Describe alternatives you've considered
|
|
||||||
<!--- A clear and concise description of any alternative solutions or features you've considered. -->
|
|
||||||
|
|
||||||
## Additional context
|
|
||||||
<!--- Add any other context or screenshots about the feature request here. -->
|
|
|
@ -1,70 +0,0 @@
|
||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<!-- Generator: Adobe Illustrator 25.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
|
||||||
<svg version="1.1" id="Слой_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
|
||||||
viewBox="0 0 184.2 51.8" style="enable-background:new 0 0 184.2 51.8;" xml:space="preserve">
|
|
||||||
<style type="text/css">
|
|
||||||
.st0{display:none;}
|
|
||||||
.st1{display:inline;}
|
|
||||||
.st2{fill:#01E397;}
|
|
||||||
.st3{display:inline;fill:#010032;}
|
|
||||||
.st4{display:inline;fill:#00E599;}
|
|
||||||
.st5{display:inline;fill:#00AF92;}
|
|
||||||
.st6{fill:#00C3E5;}
|
|
||||||
</style>
|
|
||||||
<g id="Layer_2">
|
|
||||||
<g id="Layer_1-2" class="st0">
|
|
||||||
<g class="st1">
|
|
||||||
<path class="st2" d="M146.6,18.3v7.2h10.9V29h-10.9v10.7h-4V14.8h18v3.5H146.6z"/>
|
|
||||||
<path class="st2" d="M180,15.7c1.7,0.9,3,2.2,4,3.8l-3,2.7c-0.6-1.3-1.5-2.4-2.6-3.3c-1.3-0.7-2.8-1-4.3-1
|
|
||||||
c-1.4-0.1-2.8,0.3-4,1.1c-0.9,0.5-1.5,1.5-1.4,2.6c0,1,0.5,1.9,1.4,2.4c1.5,0.8,3.2,1.3,4.9,1.5c1.9,0.3,3.7,0.8,5.4,1.6
|
|
||||||
c1.2,0.5,2.2,1.3,2.9,2.3c0.6,1,1,2.2,0.9,3.4c0,1.4-0.5,2.7-1.3,3.8c-0.9,1.2-2.1,2.1-3.5,2.6c-1.7,0.6-3.4,0.9-5.2,0.8
|
|
||||||
c-5,0-8.6-1.6-10.7-5l2.9-2.8c0.7,1.4,1.8,2.5,3.1,3.3c1.5,0.7,3.1,1.1,4.7,1c1.5,0.1,2.9-0.2,4.2-0.9c0.9-0.5,1.5-1.5,1.5-2.6
|
|
||||||
c0-0.9-0.5-1.8-1.3-2.2c-1.5-0.7-3.1-1.2-4.8-1.5c-1.9-0.3-3.7-0.8-5.5-1.5c-1.2-0.5-2.2-1.4-3-2.4c-0.6-1-1-2.2-0.9-3.4
|
|
||||||
c0-1.4,0.4-2.7,1.2-3.8c0.8-1.2,2-2.2,3.3-2.8c1.6-0.7,3.4-1.1,5.2-1C176.1,14.3,178.2,14.8,180,15.7z"/>
|
|
||||||
</g>
|
|
||||||
<path class="st3" d="M73.3,16.3c1.9,1.9,2.9,4.5,2.7,7.1v15.9h-4V24.8c0-2.6-0.5-4.5-1.6-5.7c-1.2-1.2-2.8-1.8-4.5-1.7
|
|
||||||
c-1.3,0-2.5,0.3-3.7,0.8c-1.2,0.7-2.2,1.7-2.9,2.9c-0.8,1.5-1.1,3.2-1.1,4.9v13.3h-4V15.1l3.6,1.5v1.7c0.8-1.5,2.1-2.6,3.6-3.3
|
|
||||||
c1.5-0.8,3.2-1.2,4.9-1.1C68.9,13.8,71.3,14.7,73.3,16.3z"/>
|
|
||||||
<path class="st3" d="M104.4,28.3H85.6c0.1,2.2,1,4.3,2.5,5.9c1.5,1.4,3.5,2.2,5.6,2.1c1.6,0.1,3.2-0.2,4.6-0.9
|
|
||||||
c1.1-0.6,2-1.6,2.5-2.8l3.3,1.8c-0.9,1.7-2.3,3.1-4,4c-2,1-4.2,1.5-6.4,1.4c-3.7,0-6.7-1.1-8.8-3.4s-3.2-5.5-3.2-9.6s1-7.2,3-9.5
|
|
||||||
s5-3.4,8.7-3.4c2.1-0.1,4.2,0.5,6.1,1.5c1.6,1,3,2.5,3.8,4.2c0.9,1.8,1.3,3.9,1.3,5.9C104.6,26.4,104.6,27.4,104.4,28.3z
|
|
||||||
M88.1,19.3c-1.4,1.5-2.2,3.4-2.4,5.5h15.1c-0.2-2-1-3.9-2.3-5.5c-1.4-1.3-3.2-2-5.1-1.9C91.5,17.3,89.6,18,88.1,19.3z"/>
|
|
||||||
<path class="st3" d="M131,17.3c2.2,2.3,3.2,5.5,3.2,9.5s-1,7.3-3.2,9.6s-5.1,3.4-8.8,3.4s-6.7-1.1-8.9-3.4s-3.2-5.5-3.2-9.6
|
|
||||||
s1.1-7.2,3.2-9.5s5.1-3.4,8.9-3.4S128.9,15,131,17.3z M116.2,19.9c-1.5,2-2.2,4.4-2.1,6.9c-0.2,2.5,0.6,5,2.1,7
|
|
||||||
c1.5,1.7,3.7,2.7,6,2.6c2.3,0.1,4.4-0.9,5.9-2.6c1.5-2,2.3-4.5,2.1-7c0.1-2.5-0.6-4.9-2.1-6.9c-1.5-1.7-3.6-2.7-5.9-2.6
|
|
||||||
C119.9,17.2,117.7,18.2,116.2,19.9z"/>
|
|
||||||
<polygon class="st4" points="0,9.1 0,43.7 22.5,51.8 22.5,16.9 46.8,7.9 24.8,0 "/>
|
|
||||||
<polygon class="st5" points="24.3,17.9 24.3,36.8 46.8,44.9 46.8,9.6 "/>
|
|
||||||
</g>
|
|
||||||
<g>
|
|
||||||
<g>
|
|
||||||
<path class="st6" d="M41.6,17.5H28.2v6.9h10.4v3.3H28.2v10.2h-3.9V14.2h17.2V17.5z"/>
|
|
||||||
<path class="st6" d="M45.8,37.9v-18h3.3l0.4,3.2c0.5-1.2,1.2-2.1,2.1-2.7c0.9-0.6,2.1-0.9,3.5-0.9c0.4,0,0.7,0,1.1,0.1
|
|
||||||
c0.4,0.1,0.7,0.2,0.9,0.3l-0.5,3.4c-0.3-0.1-0.6-0.2-0.9-0.2C55.4,23,54.9,23,54.4,23c-0.7,0-1.5,0.2-2.2,0.6
|
|
||||||
c-0.7,0.4-1.3,1-1.8,1.8s-0.7,1.8-0.7,3v9.5H45.8z"/>
|
|
||||||
<path class="st6" d="M68.6,19.6c1.8,0,3.3,0.4,4.6,1.1c1.3,0.7,2.4,1.8,3.1,3.2s1.1,3.1,1.1,5c0,1.9-0.4,3.6-1.1,5
|
|
||||||
c-0.8,1.4-1.8,2.5-3.1,3.2c-1.3,0.7-2.9,1.1-4.6,1.1s-3.3-0.4-4.6-1.1c-1.3-0.7-2.4-1.8-3.2-3.2c-0.8-1.4-1.2-3.1-1.2-5
|
|
||||||
c0-1.9,0.4-3.6,1.2-5s1.8-2.5,3.2-3.2C65.3,19.9,66.8,19.6,68.6,19.6z M68.6,22.6c-1.1,0-2,0.2-2.8,0.7c-0.8,0.5-1.3,1.2-1.7,2.1
|
|
||||||
s-0.6,2.1-0.6,3.5c0,1.3,0.2,2.5,0.6,3.4s1,1.7,1.7,2.2s1.7,0.7,2.8,0.7c1.1,0,2-0.2,2.7-0.7c0.7-0.5,1.3-1.2,1.7-2.2
|
|
||||||
s0.6-2.1,0.6-3.4c0-1.4-0.2-2.5-0.6-3.5s-1-1.6-1.7-2.1C70.6,22.8,69.6,22.6,68.6,22.6z"/>
|
|
||||||
<path class="st6" d="M89.2,38.3c-1.8,0-3.4-0.3-4.9-1c-1.5-0.7-2.7-1.7-3.5-3l2.7-2.3c0.5,1,1.3,1.8,2.3,2.4
|
|
||||||
c1,0.6,2.2,0.9,3.6,0.9c1.1,0,2-0.2,2.6-0.6c0.6-0.4,1-0.9,1-1.6c0-0.5-0.2-0.9-0.5-1.2s-0.9-0.6-1.7-0.8l-3.8-0.8
|
|
||||||
c-1.9-0.4-3.3-1-4.1-1.9c-0.8-0.9-1.2-1.9-1.2-3.3c0-1,0.3-1.9,0.9-2.7c0.6-0.8,1.4-1.5,2.5-2s2.5-0.8,4-0.8c1.8,0,3.3,0.3,4.6,1
|
|
||||||
c1.3,0.6,2.2,1.5,2.9,2.7l-2.7,2.2c-0.5-1-1.1-1.7-2-2.1c-0.9-0.5-1.8-0.7-2.8-0.7c-0.8,0-1.4,0.1-2,0.3c-0.6,0.2-1,0.5-1.3,0.8
|
|
||||||
c-0.3,0.3-0.4,0.7-0.4,1.2c0,0.5,0.2,0.9,0.5,1.3s1,0.6,1.9,0.8l4.1,0.9c1.7,0.3,2.9,0.9,3.7,1.7c0.7,0.8,1.1,1.8,1.1,2.9
|
|
||||||
c0,1.2-0.3,2.2-0.9,3c-0.6,0.9-1.5,1.6-2.6,2C92.1,38.1,90.7,38.3,89.2,38.3z"/>
|
|
||||||
<path class="st6" d="M112.8,19.9v3H99.3v-3H112.8z M106.6,14.6v17.9c0,0.9,0.2,1.5,0.7,1.9c0.5,0.4,1.1,0.6,1.9,0.6
|
|
||||||
c0.6,0,1.2-0.1,1.7-0.3c0.5-0.2,0.9-0.5,1.3-0.8l0.9,2.8c-0.6,0.5-1.2,0.9-2,1.1c-0.8,0.3-1.7,0.4-2.7,0.4c-1,0-2-0.2-2.8-0.5
|
|
||||||
s-1.5-0.9-2-1.6c-0.5-0.8-0.7-1.7-0.8-3V15.7L106.6,14.6z"/>
|
|
||||||
<path d="M137.9,17.5h-13.3v6.9h10.4v3.3h-10.4v10.2h-3.9V14.2h17.2V17.5z"/>
|
|
||||||
<path d="M150.9,13.8c2.1,0,4,0.4,5.5,1.2c1.6,0.8,2.9,2,4,3.5l-2.6,2.5c-0.9-1.4-1.9-2.4-3.1-3c-1.1-0.6-2.5-0.9-4-0.9
|
|
||||||
c-1.2,0-2.1,0.2-2.8,0.5c-0.7,0.3-1.3,0.7-1.6,1.2c-0.3,0.5-0.5,1.1-0.5,1.7c0,0.7,0.3,1.4,0.8,1.9c0.5,0.6,1.5,1,2.9,1.3
|
|
||||||
l4.8,1.1c2.3,0.5,3.9,1.3,4.9,2.3c1,1,1.4,2.3,1.4,3.9c0,1.5-0.4,2.7-1.2,3.8c-0.8,1.1-1.9,1.9-3.3,2.5s-3.1,0.9-5,0.9
|
|
||||||
c-1.7,0-3.2-0.2-4.5-0.6c-1.3-0.4-2.5-1-3.5-1.8c-1-0.7-1.8-1.6-2.5-2.6l2.7-2.7c0.5,0.8,1.1,1.6,1.9,2.2
|
|
||||||
c0.8,0.7,1.7,1.2,2.7,1.5c1,0.4,2.2,0.5,3.4,0.5c1.1,0,2.1-0.1,2.9-0.4c0.8-0.3,1.4-0.7,1.8-1.2c0.4-0.5,0.6-1.1,0.6-1.9
|
|
||||||
c0-0.7-0.2-1.3-0.7-1.8c-0.5-0.5-1.3-0.9-2.6-1.2l-5.2-1.2c-1.4-0.3-2.6-0.8-3.6-1.3c-0.9-0.6-1.6-1.3-2.1-2.1s-0.7-1.8-0.7-2.8
|
|
||||||
c0-1.3,0.4-2.6,1.1-3.7c0.7-1.1,1.8-2,3.2-2.6C147.3,14.1,148.9,13.8,150.9,13.8z"/>
|
|
||||||
</g>
|
|
||||||
</g>
|
|
||||||
</g>
|
|
||||||
</svg>
|
|
Before Width: | Height: | Size: 5.5 KiB |
|
@ -1,27 +0,0 @@
|
||||||
on:
|
|
||||||
pull_request:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- master
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
builds:
|
|
||||||
name: Builds
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
strategy:
|
|
||||||
matrix:
|
|
||||||
go_versions: [ '1.22', '1.23' ]
|
|
||||||
fail-fast: false
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Set up Go
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: '${{ matrix.go_versions }}'
|
|
||||||
|
|
||||||
- name: Build binary
|
|
||||||
run: make
|
|
||||||
|
|
||||||
- name: Check dirty suffix
|
|
||||||
run: if [[ $(make version) == *"dirty"* ]]; then echo "Version has dirty suffix" && exit 1; fi
|
|
|
@ -1,20 +0,0 @@
|
||||||
on: [pull_request]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
dco:
|
|
||||||
name: DCO
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: '1.23'
|
|
||||||
|
|
||||||
- name: Run commit format checker
|
|
||||||
uses: https://git.frostfs.info/TrueCloudLab/dco-go@v3
|
|
||||||
with:
|
|
||||||
from: 'origin/${{ github.event.pull_request.base.ref }}'
|
|
|
@ -1,27 +0,0 @@
|
||||||
on:
|
|
||||||
pull_request:
|
|
||||||
push:
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
image:
|
|
||||||
name: OCI image
|
|
||||||
runs-on: docker
|
|
||||||
container: git.frostfs.info/truecloudlab/env:oci-image-builder-bookworm
|
|
||||||
steps:
|
|
||||||
- name: Clone git repo
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Build OCI image
|
|
||||||
run: make image
|
|
||||||
|
|
||||||
- name: Push image to OCI registry
|
|
||||||
run: |
|
|
||||||
echo "$REGISTRY_PASSWORD" \
|
|
||||||
| docker login --username truecloudlab --password-stdin git.frostfs.info
|
|
||||||
make image-push
|
|
||||||
if: >-
|
|
||||||
startsWith(github.ref, 'refs/tags/v') &&
|
|
||||||
(github.event_name == 'workflow_dispatch' || github.event_name == 'push')
|
|
||||||
env:
|
|
||||||
REGISTRY_PASSWORD: ${{secrets.FORGEJO_OCI_REGISTRY_PUSH_TOKEN}}
|
|
|
@ -1,61 +0,0 @@
|
||||||
on:
|
|
||||||
pull_request:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- master
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
lint:
|
|
||||||
name: Lint
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Set up Go
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: '1.23'
|
|
||||||
cache: true
|
|
||||||
|
|
||||||
- name: Install linters
|
|
||||||
run: make lint-install
|
|
||||||
|
|
||||||
- name: Run linters
|
|
||||||
run: make lint
|
|
||||||
|
|
||||||
tests:
|
|
||||||
name: Tests
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
strategy:
|
|
||||||
matrix:
|
|
||||||
go_versions: [ '1.22', '1.23' ]
|
|
||||||
fail-fast: false
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Set up Go
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: '${{ matrix.go_versions }}'
|
|
||||||
|
|
||||||
- name: Update Go modules
|
|
||||||
run: make dep
|
|
||||||
|
|
||||||
- name: Run tests
|
|
||||||
run: make test
|
|
||||||
|
|
||||||
integration:
|
|
||||||
name: Integration tests
|
|
||||||
runs-on: oci-runner
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Set up Go
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: '1.23'
|
|
||||||
|
|
||||||
- name: Run integration tests
|
|
||||||
run: |-
|
|
||||||
podman-service.sh
|
|
||||||
make integration-test
|
|
|
@ -1,25 +0,0 @@
|
||||||
on:
|
|
||||||
pull_request:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- master
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
vulncheck:
|
|
||||||
name: Vulncheck
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: '1.22.12'
|
|
||||||
|
|
||||||
- name: Install govulncheck
|
|
||||||
run: go install golang.org/x/vuln/cmd/govulncheck@latest
|
|
||||||
|
|
||||||
- name: Run govulncheck
|
|
||||||
run: govulncheck ./...
|
|
1
.github/CODEOWNERS
vendored
Normal file
1
.github/CODEOWNERS
vendored
Normal file
|
@ -0,0 +1 @@
|
||||||
|
* @alexvanin @masterSplinter01 @KirillovDenis
|
|
@ -2,7 +2,7 @@
|
||||||
name: Bug report
|
name: Bug report
|
||||||
about: Create a report to help us improve
|
about: Create a report to help us improve
|
||||||
title: ''
|
title: ''
|
||||||
labels: community, triage, bug
|
labels: community, triage
|
||||||
assignees: ''
|
assignees: ''
|
||||||
|
|
||||||
---
|
---
|
||||||
|
@ -18,17 +18,17 @@ assignees: ''
|
||||||
<!--- If suggesting a change/improvement, explain the difference from current behavior -->
|
<!--- If suggesting a change/improvement, explain the difference from current behavior -->
|
||||||
|
|
||||||
## Possible Solution
|
## Possible Solution
|
||||||
<!-- Not obligatory
|
<!--- Not obligatory, but suggest a fix/reason for the bug, -->
|
||||||
If no reason/fix/additions for the bug can be suggested,
|
<!--- or ideas how to implement the addition or change -->
|
||||||
uncomment the following phrase:
|
|
||||||
|
|
||||||
<-- No fix can be suggested by a QA engineer. Further solutions shall be up to developers. -->
|
|
||||||
|
|
||||||
## Steps to Reproduce (for bugs)
|
## Steps to Reproduce (for bugs)
|
||||||
<!--- Provide a link to a live example, or an unambiguous set of steps to -->
|
<!--- Provide a link to a live example, or an unambiguous set of steps to -->
|
||||||
<!--- reproduce this bug. -->
|
<!--- reproduce this bug. -->
|
||||||
|
|
||||||
1.
|
1.
|
||||||
|
2.
|
||||||
|
3.
|
||||||
|
4.
|
||||||
|
|
||||||
## Context
|
## Context
|
||||||
<!--- How has this issue affected you? What are you trying to accomplish? -->
|
<!--- How has this issue affected you? What are you trying to accomplish? -->
|
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
---
|
||||||
|
name: Feature request
|
||||||
|
about: Suggest an idea for this project
|
||||||
|
title: ''
|
||||||
|
labels: community, triage
|
||||||
|
assignees: ''
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Is your feature request related to a problem? Please describe.**
|
||||||
|
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||||
|
|
||||||
|
**Describe the solution you'd like**
|
||||||
|
A clear and concise description of what you want to happen.
|
||||||
|
|
||||||
|
**Describe alternatives you've considered**
|
||||||
|
A clear and concise description of any alternative solutions or features you've considered.
|
||||||
|
|
||||||
|
**Additional context**
|
||||||
|
Add any other context or screenshots about the feature request here.
|
129
.github/logo.svg
vendored
Normal file
129
.github/logo.svg
vendored
Normal file
|
@ -0,0 +1,129 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||||
|
<svg
|
||||||
|
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||||
|
xmlns:cc="http://creativecommons.org/ns#"
|
||||||
|
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||||
|
xmlns:svg="http://www.w3.org/2000/svg"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||||
|
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||||
|
sodipodi:docname="logo_fs.svg"
|
||||||
|
inkscape:version="1.0 (4035a4fb49, 2020-05-01)"
|
||||||
|
id="svg57"
|
||||||
|
version="1.1"
|
||||||
|
viewBox="0 0 105 25"
|
||||||
|
height="25mm"
|
||||||
|
width="105mm">
|
||||||
|
<defs
|
||||||
|
id="defs51">
|
||||||
|
<clipPath
|
||||||
|
clipPathUnits="userSpaceOnUse"
|
||||||
|
id="clipPath434">
|
||||||
|
<path
|
||||||
|
d="M 0,0 H 1366 V 768 H 0 Z"
|
||||||
|
id="path432" />
|
||||||
|
</clipPath>
|
||||||
|
</defs>
|
||||||
|
<sodipodi:namedview
|
||||||
|
inkscape:window-maximized="0"
|
||||||
|
inkscape:window-y="0"
|
||||||
|
inkscape:window-x="130"
|
||||||
|
inkscape:window-height="1040"
|
||||||
|
inkscape:window-width="1274"
|
||||||
|
height="50mm"
|
||||||
|
units="mm"
|
||||||
|
showgrid="false"
|
||||||
|
inkscape:document-rotation="0"
|
||||||
|
inkscape:current-layer="layer1"
|
||||||
|
inkscape:document-units="mm"
|
||||||
|
inkscape:cy="344.49897"
|
||||||
|
inkscape:cx="468.64708"
|
||||||
|
inkscape:zoom="0.7"
|
||||||
|
inkscape:pageshadow="2"
|
||||||
|
inkscape:pageopacity="0.0"
|
||||||
|
borderopacity="1.0"
|
||||||
|
bordercolor="#666666"
|
||||||
|
pagecolor="#ffffff"
|
||||||
|
id="base" />
|
||||||
|
<metadata
|
||||||
|
id="metadata54">
|
||||||
|
<rdf:RDF>
|
||||||
|
<cc:Work
|
||||||
|
rdf:about="">
|
||||||
|
<dc:format>image/svg+xml</dc:format>
|
||||||
|
<dc:type
|
||||||
|
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||||
|
<dc:title></dc:title>
|
||||||
|
</cc:Work>
|
||||||
|
</rdf:RDF>
|
||||||
|
</metadata>
|
||||||
|
<g
|
||||||
|
id="layer1"
|
||||||
|
inkscape:groupmode="layer"
|
||||||
|
inkscape:label="Layer 1">
|
||||||
|
<g
|
||||||
|
id="g424"
|
||||||
|
transform="matrix(0.35277777,0,0,-0.35277777,63.946468,10.194047)">
|
||||||
|
<path
|
||||||
|
d="m 0,0 v -8.093 h 12.287 v -3.94 H 0 V -24.067 H -4.534 V 3.898 H 15.677 V 0 Z"
|
||||||
|
style="fill:#00e396;fill-opacity:1;fill-rule:nonzero;stroke:none"
|
||||||
|
id="path426" />
|
||||||
|
</g>
|
||||||
|
<g
|
||||||
|
transform="matrix(0.35277777,0,0,-0.35277777,-315.43002,107.34005)"
|
||||||
|
id="g428">
|
||||||
|
<g
|
||||||
|
id="g430"
|
||||||
|
clip-path="url(#clipPath434)">
|
||||||
|
<g
|
||||||
|
id="g436"
|
||||||
|
transform="translate(1112.874,278.2981)">
|
||||||
|
<path
|
||||||
|
d="M 0,0 C 1.822,-0.932 3.354,-2.359 4.597,-4.28 L 1.165,-7.373 c -0.791,1.695 -1.779,2.924 -2.966,3.686 -1.186,0.763 -2.768,1.145 -4.745,1.145 -1.949,0 -3.461,-0.389 -4.534,-1.166 -1.074,-0.777 -1.61,-1.772 -1.61,-2.987 0,-1.13 0.523,-2.027 1.568,-2.69 1.045,-0.664 2.909,-1.236 5.593,-1.716 2.514,-0.452 4.512,-1.024 5.995,-1.716 1.483,-0.693 2.564,-1.554 3.242,-2.585 0.677,-1.031 1.016,-2.309 1.016,-3.834 0,-1.639 -0.466,-3.079 -1.398,-4.322 -0.932,-1.243 -2.239,-2.197 -3.919,-2.86 -1.681,-0.664 -3.623,-0.996 -5.826,-0.996 -5.678,0 -9.689,1.892 -12.033,5.678 l 3.178,3.178 c 0.903,-1.695 2.068,-2.939 3.495,-3.729 1.426,-0.791 3.199,-1.186 5.318,-1.186 2.005,0 3.58,0.345 4.724,1.038 1.144,0.692 1.716,1.674 1.716,2.945 0,1.017 -0.516,1.835 -1.547,2.457 -1.031,0.621 -2.832,1.172 -5.402,1.653 -2.571,0.479 -4.618,1.073 -6.143,1.779 -1.526,0.706 -2.635,1.582 -3.326,2.627 -0.693,1.045 -1.039,2.316 -1.039,3.813 0,1.582 0.438,3.023 1.314,4.322 0.875,1.299 2.14,2.33 3.792,3.093 1.653,0.763 3.58,1.144 5.783,1.144 C -4.018,1.398 -1.822,0.932 0,0"
|
||||||
|
style="fill:#00e396;fill-opacity:1;fill-rule:nonzero;stroke:none"
|
||||||
|
id="path438" />
|
||||||
|
</g>
|
||||||
|
<g
|
||||||
|
id="g440"
|
||||||
|
transform="translate(993.0239,277.5454)">
|
||||||
|
<path
|
||||||
|
d="m 0,0 c 2.054,-1.831 3.083,-4.465 3.083,-7.902 v -17.935 h -4.484 v 16.366 c 0,2.914 -0.626,5.024 -1.877,6.332 -1.253,1.308 -2.924,1.962 -5.016,1.962 -1.495,0 -2.896,-0.327 -4.204,-0.981 -1.308,-0.654 -2.381,-1.719 -3.222,-3.194 -0.841,-1.477 -1.261,-3.335 -1.261,-5.576 v -14.909 h -4.484 V 1.328 l 4.086,-1.674 0.118,-1.84 c 0.933,1.681 2.222,2.923 3.867,3.727 1.643,0.803 3.493,1.205 5.548,1.205 C -4.671,2.746 -2.055,1.83 0,0"
|
||||||
|
style="fill:#000033;fill-opacity:1;fill-rule:nonzero;stroke:none"
|
||||||
|
id="path442" />
|
||||||
|
</g>
|
||||||
|
<g
|
||||||
|
id="g444"
|
||||||
|
transform="translate(1027.9968,264.0386)">
|
||||||
|
<path
|
||||||
|
d="m 0,0 h -21.128 c 0.261,-2.84 1.205,-5.044 2.83,-6.613 1.625,-1.57 3.727,-2.355 6.305,-2.355 2.054,0 3.763,0.356 5.128,1.065 1.363,0.71 2.288,1.738 2.774,3.083 l 3.755,-1.961 c -1.121,-1.981 -2.616,-3.495 -4.484,-4.54 -1.868,-1.046 -4.259,-1.569 -7.173,-1.569 -4.223,0 -7.538,1.289 -9.948,3.867 -2.41,2.578 -3.615,6.146 -3.615,10.704 0,4.558 1.149,8.127 3.447,10.705 2.298,2.578 5.557,3.867 9.779,3.867 2.615,0 4.876,-0.58 6.782,-1.738 1.905,-1.158 3.343,-2.728 4.315,-4.707 C -0.262,7.827 0.224,5.605 0.224,3.139 0.224,2.092 0.149,1.046 0,0 m -18.298,10.144 c -1.513,-1.457 -2.438,-3.512 -2.775,-6.165 h 16.982 c -0.3,2.615 -1.159,4.661 -2.578,6.137 -1.42,1.476 -3.307,2.214 -5.661,2.214 -2.466,0 -4.455,-0.728 -5.968,-2.186"
|
||||||
|
style="fill:#000033;fill-opacity:1;fill-rule:nonzero;stroke:none"
|
||||||
|
id="path446" />
|
||||||
|
</g>
|
||||||
|
<g
|
||||||
|
id="g448"
|
||||||
|
transform="translate(1057.8818,276.4246)">
|
||||||
|
<path
|
||||||
|
d="m 0,0 c 2.41,-2.578 3.615,-6.147 3.615,-10.705 0,-4.558 -1.205,-8.126 -3.615,-10.704 -2.41,-2.578 -5.726,-3.867 -9.948,-3.867 -4.222,0 -7.537,1.289 -9.947,3.867 -2.41,2.578 -3.615,6.146 -3.615,10.704 0,4.558 1.205,8.127 3.615,10.705 2.41,2.578 5.725,3.867 9.947,3.867 C -5.726,3.867 -2.41,2.578 0,0 m -16.617,-2.858 c -1.607,-1.906 -2.41,-4.522 -2.41,-7.847 0,-3.326 0.803,-5.94 2.41,-7.846 1.607,-1.905 3.83,-2.858 6.669,-2.858 2.839,0 5.063,0.953 6.67,2.858 1.606,1.906 2.41,4.52 2.41,7.846 0,3.325 -0.804,5.941 -2.41,7.847 C -4.885,-0.953 -7.109,0 -9.948,0 c -2.839,0 -5.062,-0.953 -6.669,-2.858"
|
||||||
|
style="fill:#000033;fill-opacity:1;fill-rule:nonzero;stroke:none"
|
||||||
|
id="path450" />
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
<g
|
||||||
|
id="g452"
|
||||||
|
transform="matrix(0.35277777,0,0,-0.35277777,5.8329581,6.5590171)">
|
||||||
|
<path
|
||||||
|
d="m 0,0 0.001,-38.946 25.286,-9.076 V -8.753 L 52.626,1.321 27.815,10.207 Z"
|
||||||
|
style="fill:#00e599;fill-opacity:1;fill-rule:nonzero;stroke:none"
|
||||||
|
id="path454" />
|
||||||
|
</g>
|
||||||
|
<g
|
||||||
|
id="g456"
|
||||||
|
transform="matrix(0.35277777,0,0,-0.35277777,15.479008,10.041927)">
|
||||||
|
<path
|
||||||
|
d="M 0,0 V -21.306 L 25.293,-30.364 25.282,9.347 Z"
|
||||||
|
style="fill:#00b091;fill-opacity:1;fill-rule:nonzero;stroke:none"
|
||||||
|
id="path458" />
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
</svg>
|
After Width: | Height: | Size: 6.5 KiB |
67
.github/workflows/builds.yml
vendored
Normal file
67
.github/workflows/builds.yml
vendored
Normal file
|
@ -0,0 +1,67 @@
|
||||||
|
name: Builds
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
- 'support/*'
|
||||||
|
types: [opened, synchronize]
|
||||||
|
paths-ignore:
|
||||||
|
- '**/*.md'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build_cli:
|
||||||
|
name: Build CLI
|
||||||
|
runs-on: ubuntu-20.04
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v2
|
||||||
|
with:
|
||||||
|
go-version: 1.19
|
||||||
|
|
||||||
|
- name: Restore Go modules from cache
|
||||||
|
uses: actions/cache@v2
|
||||||
|
with:
|
||||||
|
path: /home/runner/go/pkg/mod
|
||||||
|
key: deps-${{ hashFiles('go.sum') }}
|
||||||
|
|
||||||
|
- name: Update Go modules
|
||||||
|
run: make dep
|
||||||
|
|
||||||
|
- name: Build CLI
|
||||||
|
run: make
|
||||||
|
|
||||||
|
- name: Check version
|
||||||
|
run: if [[ $(make version) == *"dirty"* ]]; then exit 1; fi
|
||||||
|
|
||||||
|
build_image:
|
||||||
|
needs: build_cli
|
||||||
|
name: Build Docker image
|
||||||
|
runs-on: ubuntu-20.04
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v2
|
||||||
|
with:
|
||||||
|
go-version: 1.19
|
||||||
|
|
||||||
|
- name: Restore Go modules from cache
|
||||||
|
uses: actions/cache@v2
|
||||||
|
with:
|
||||||
|
path: /home/runner/go/pkg/mod
|
||||||
|
key: deps-${{ hashFiles('go.sum') }}
|
||||||
|
|
||||||
|
- name: Update Go modules
|
||||||
|
run: make dep
|
||||||
|
|
||||||
|
- name: Build Docker image
|
||||||
|
run: make image
|
67
.github/workflows/codeql-analysis.yml
vendored
Normal file
67
.github/workflows/codeql-analysis.yml
vendored
Normal file
|
@ -0,0 +1,67 @@
|
||||||
|
# For most projects, this workflow file will not need changing; you simply need
|
||||||
|
# to commit it to your repository.
|
||||||
|
#
|
||||||
|
# You may wish to alter this file to override the set of languages analyzed,
|
||||||
|
# or to provide custom queries or build logic.
|
||||||
|
#
|
||||||
|
# ******** NOTE ********
|
||||||
|
# We have attempted to detect the languages in your repository. Please check
|
||||||
|
# the `language` matrix defined below to confirm you have the correct set of
|
||||||
|
# supported CodeQL languages.
|
||||||
|
#
|
||||||
|
name: "CodeQL"
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ master, 'support/*' ]
|
||||||
|
pull_request:
|
||||||
|
# The branches below must be a subset of the branches above
|
||||||
|
branches: [ master, 'support/*' ]
|
||||||
|
schedule:
|
||||||
|
- cron: '35 8 * * 1'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
analyze:
|
||||||
|
name: Analyze
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
language: [ 'go' ]
|
||||||
|
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
|
||||||
|
# Learn more:
|
||||||
|
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
# Initializes the CodeQL tools for scanning.
|
||||||
|
- name: Initialize CodeQL
|
||||||
|
uses: github/codeql-action/init@v2
|
||||||
|
with:
|
||||||
|
languages: ${{ matrix.language }}
|
||||||
|
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||||
|
# By default, queries listed here will override any specified in a config file.
|
||||||
|
# Prefix the list here with "+" to use these queries and those in the config file.
|
||||||
|
# queries: ./path/to/local/query, your-org/your-repo/queries@main
|
||||||
|
|
||||||
|
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||||
|
# If this step fails, then you should remove it and run the build manually (see below)
|
||||||
|
- name: Autobuild
|
||||||
|
uses: github/codeql-action/autobuild@v2
|
||||||
|
|
||||||
|
# ℹ️ Command-line programs to run using the OS shell.
|
||||||
|
# 📚 https://git.io/JvXDl
|
||||||
|
|
||||||
|
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
|
||||||
|
# and modify them (or add more) to build your code if your project
|
||||||
|
# uses a compiled language
|
||||||
|
|
||||||
|
#- run: |
|
||||||
|
# make bootstrap
|
||||||
|
# make release
|
||||||
|
|
||||||
|
- name: Perform CodeQL Analysis
|
||||||
|
uses: github/codeql-action/analyze@v2
|
22
.github/workflows/dco.yml
vendored
Normal file
22
.github/workflows/dco.yml
vendored
Normal file
|
@ -0,0 +1,22 @@
|
||||||
|
name: DCO check
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
- 'support/*'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
commits_check_job:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
name: Commits Check
|
||||||
|
steps:
|
||||||
|
- name: Get PR Commits
|
||||||
|
id: 'get-pr-commits'
|
||||||
|
uses: tim-actions/get-pr-commits@master
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
- name: DCO Check
|
||||||
|
uses: tim-actions/dco@master
|
||||||
|
with:
|
||||||
|
commits: ${{ steps.get-pr-commits.outputs.commits }}
|
86
.github/workflows/tests.yml
vendored
Normal file
86
.github/workflows/tests.yml
vendored
Normal file
|
@ -0,0 +1,86 @@
|
||||||
|
name: Tests
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
- 'support/*'
|
||||||
|
types: [opened, synchronize]
|
||||||
|
paths-ignore:
|
||||||
|
- '**/*.md'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
lint:
|
||||||
|
name: Lint
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
- name: golangci-lint
|
||||||
|
uses: golangci/golangci-lint-action@v2
|
||||||
|
with:
|
||||||
|
version: latest
|
||||||
|
|
||||||
|
cover:
|
||||||
|
name: Coverage
|
||||||
|
runs-on: ubuntu-20.04
|
||||||
|
|
||||||
|
env:
|
||||||
|
CGO_ENABLED: 1
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v2
|
||||||
|
with:
|
||||||
|
go-version: 1.19
|
||||||
|
|
||||||
|
- name: Restore Go modules from cache
|
||||||
|
uses: actions/cache@v2
|
||||||
|
with:
|
||||||
|
path: /home/runner/go/pkg/mod
|
||||||
|
key: deps-${{ hashFiles('go.sum') }}
|
||||||
|
|
||||||
|
- name: Update Go modules
|
||||||
|
run: make dep
|
||||||
|
|
||||||
|
- name: Test and write coverage profile
|
||||||
|
run: make cover
|
||||||
|
|
||||||
|
- name: Upload coverage results to Codecov
|
||||||
|
uses: codecov/codecov-action@v1
|
||||||
|
with:
|
||||||
|
fail_ci_if_error: false
|
||||||
|
path_to_write_report: ./coverage.txt
|
||||||
|
verbose: true
|
||||||
|
|
||||||
|
tests:
|
||||||
|
name: Tests
|
||||||
|
runs-on: ubuntu-20.04
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
go_versions: [ '1.17', '1.18', '1.19' ]
|
||||||
|
fail-fast: false
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v2
|
||||||
|
with:
|
||||||
|
go-version: '${{ matrix.go_versions }}'
|
||||||
|
|
||||||
|
- name: Restore Go modules from cache
|
||||||
|
uses: actions/cache@v2
|
||||||
|
with:
|
||||||
|
path: /home/runner/go/pkg/mod
|
||||||
|
key: deps-${{ hashFiles('go.sum') }}
|
||||||
|
|
||||||
|
- name: Update Go modules
|
||||||
|
run: make dep
|
||||||
|
|
||||||
|
- name: Run tests
|
||||||
|
run: make test
|
2
.gitignore
vendored
2
.gitignore
vendored
|
@ -10,7 +10,7 @@ temp
|
||||||
test.sh
|
test.sh
|
||||||
testfile
|
testfile
|
||||||
.blast.yml
|
.blast.yml
|
||||||
.frostfs-cli.yml
|
.neofs-cli.yml
|
||||||
|
|
||||||
.cache
|
.cache
|
||||||
|
|
||||||
|
|
11
.gitlint
11
.gitlint
|
@ -1,11 +0,0 @@
|
||||||
[general]
|
|
||||||
fail-without-commits=True
|
|
||||||
regex-style-search=True
|
|
||||||
contrib=CC1
|
|
||||||
|
|
||||||
[title-match-regex]
|
|
||||||
regex=^\[\#[0-9Xx]+\]\s
|
|
||||||
|
|
||||||
[ignore-by-title]
|
|
||||||
regex=^Release(.*)
|
|
||||||
ignore=title-match-regex
|
|
|
@ -4,7 +4,7 @@
|
||||||
# options for analysis running
|
# options for analysis running
|
||||||
run:
|
run:
|
||||||
# timeout for analysis, e.g. 30s, 5m, default is 1m
|
# timeout for analysis, e.g. 30s, 5m, default is 1m
|
||||||
timeout: 15m
|
timeout: 5m
|
||||||
|
|
||||||
# include test files or not, default is true
|
# include test files or not, default is true
|
||||||
tests: true
|
tests: true
|
||||||
|
@ -12,8 +12,7 @@ run:
|
||||||
# output configuration options
|
# output configuration options
|
||||||
output:
|
output:
|
||||||
# colored-line-number|line-number|json|tab|checkstyle|code-climate, default is "colored-line-number"
|
# colored-line-number|line-number|json|tab|checkstyle|code-climate, default is "colored-line-number"
|
||||||
formats:
|
format: tab
|
||||||
- format: tab
|
|
||||||
|
|
||||||
# all available settings of specific linters
|
# all available settings of specific linters
|
||||||
linters-settings:
|
linters-settings:
|
||||||
|
@ -25,16 +24,6 @@ linters-settings:
|
||||||
govet:
|
govet:
|
||||||
# report about shadowed variables
|
# report about shadowed variables
|
||||||
check-shadowing: false
|
check-shadowing: false
|
||||||
custom:
|
|
||||||
truecloudlab-linters:
|
|
||||||
path: bin/external_linters.so
|
|
||||||
original-url: git.frostfs.info/TrueCloudLab/linters.git
|
|
||||||
settings:
|
|
||||||
noliteral:
|
|
||||||
enable: true
|
|
||||||
target-methods: ["Fatal"]
|
|
||||||
disable-packages: ["req", "r"]
|
|
||||||
constants-package: "git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/logs"
|
|
||||||
|
|
||||||
linters:
|
linters:
|
||||||
enable:
|
enable:
|
||||||
|
@ -43,12 +32,15 @@ linters:
|
||||||
- revive
|
- revive
|
||||||
|
|
||||||
# some default golangci-lint linters
|
# some default golangci-lint linters
|
||||||
|
- deadcode
|
||||||
- errcheck
|
- errcheck
|
||||||
- gosimple
|
- gosimple
|
||||||
- ineffassign
|
- ineffassign
|
||||||
- staticcheck
|
- staticcheck
|
||||||
|
- structcheck
|
||||||
- typecheck
|
- typecheck
|
||||||
- unused
|
- unused
|
||||||
|
- varcheck
|
||||||
|
|
||||||
# extra linters
|
# extra linters
|
||||||
- exhaustive
|
- exhaustive
|
||||||
|
@ -56,7 +48,6 @@ linters:
|
||||||
- gofmt
|
- gofmt
|
||||||
- whitespace
|
- whitespace
|
||||||
- goimports
|
- goimports
|
||||||
- truecloudlab-linters
|
|
||||||
disable-all: true
|
disable-all: true
|
||||||
fast: false
|
fast: false
|
||||||
|
|
||||||
|
|
|
@ -1,52 +0,0 @@
|
||||||
ci:
|
|
||||||
autofix_prs: false
|
|
||||||
|
|
||||||
repos:
|
|
||||||
- repo: https://github.com/jorisroovers/gitlint
|
|
||||||
rev: v0.19.1
|
|
||||||
hooks:
|
|
||||||
- id: gitlint
|
|
||||||
stages: [commit-msg]
|
|
||||||
- id: gitlint-ci
|
|
||||||
|
|
||||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
|
||||||
rev: v4.4.0
|
|
||||||
hooks:
|
|
||||||
- id: check-added-large-files
|
|
||||||
- id: check-case-conflict
|
|
||||||
- id: check-executables-have-shebangs
|
|
||||||
- id: check-shebang-scripts-are-executable
|
|
||||||
- id: check-merge-conflict
|
|
||||||
- id: check-json
|
|
||||||
- id: check-xml
|
|
||||||
- id: check-yaml
|
|
||||||
- id: trailing-whitespace
|
|
||||||
args: [--markdown-linebreak-ext=md]
|
|
||||||
- id: end-of-file-fixer
|
|
||||||
exclude: ".key$"
|
|
||||||
|
|
||||||
- repo: https://github.com/shellcheck-py/shellcheck-py
|
|
||||||
rev: v0.9.0.2
|
|
||||||
hooks:
|
|
||||||
- id: shellcheck
|
|
||||||
|
|
||||||
- repo: local
|
|
||||||
hooks:
|
|
||||||
- id: make-lint-install
|
|
||||||
name: install linters
|
|
||||||
entry: make lint-install
|
|
||||||
language: system
|
|
||||||
pass_filenames: false
|
|
||||||
|
|
||||||
- id: make-lint
|
|
||||||
name: run linters
|
|
||||||
entry: make lint
|
|
||||||
language: system
|
|
||||||
pass_filenames: false
|
|
||||||
|
|
||||||
- id: go-unit-tests
|
|
||||||
name: go unit tests
|
|
||||||
entry: make test
|
|
||||||
pass_filenames: false
|
|
||||||
types: [go]
|
|
||||||
language: system
|
|
341
CHANGELOG.md
341
CHANGELOG.md
|
@ -4,206 +4,247 @@ This document outlines major changes between releases.
|
||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
### Added
|
## [0.25.1] - 2022-11-30
|
||||||
- Add handling quota limit reached error (#187)
|
|
||||||
- Add slash clipping for FileName attribute (#174)
|
|
||||||
|
|
||||||
## [0.32.3] - 2025-02-05
|
|
||||||
|
|
||||||
### Added
|
|
||||||
- Add slash clipping for FileName attribute (#174)
|
|
||||||
|
|
||||||
## [0.32.2] - 2025-02-03
|
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
- Possible memory leak in gRPC client (#202)
|
- Download zip archive when `FilePath` is invalid (#222)
|
||||||
|
- Only one peer must be healthy to init pool (#233)
|
||||||
## [0.32.1] - 2025-01-27
|
|
||||||
|
|
||||||
### Fixed
|
|
||||||
- SIGHUP panic (#198)
|
|
||||||
|
|
||||||
## [0.32.0] - Khumbu - 2024-12-20
|
|
||||||
|
|
||||||
### Fixed
|
|
||||||
- Getting S3 object with FrostFS Object ID-like key (#166)
|
|
||||||
- Ignore delete marked objects in versioned bucket in index page (#181)
|
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
- Metric of dropped logs by log sampler (#150)
|
- Debian packaging (#223)
|
||||||
- Fallback FileName attribute search during FilePath attribute search (#174)
|
- Timeout for individual operations in streaming RPC (#234)
|
||||||
|
|
||||||
|
## [0.25.0] - 2022-10-31
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Config reloading on SIGHUP (#200, #208)
|
||||||
|
- Stop pool dial on SIGINT (#212)
|
||||||
|
- Makefile help (#213)
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
- Updated tree service pool without api-go dependency (#178)
|
- Update NeoFS error handling (#206)
|
||||||
|
- GitHub actions updates (#205, #209)
|
||||||
|
- Unified system attribute format for GET and HEAD (#213)
|
||||||
|
|
||||||
## [0.31.0] - Rongbuk - 2024-11-20
|
## [0.24.0] - 2022-09-14
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
- Docker warnings during image build (#126)
|
- Fix expiration epoch calculation (#198)
|
||||||
- `trace_id` parameter in logs (#148)
|
- Fix panic on go1.19 (#188)
|
||||||
- SIGHUP support for `tracing.enabled` config parameter (#157)
|
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
- Vulnerability report document (#123)
|
- Exposure of pool metrics (#179, #194)
|
||||||
- Root CA configuration for tracing (#139)
|
|
||||||
- Log sampling policy configuration (#147)
|
|
||||||
- Index page support for buckets and containers (#137, #151)
|
|
||||||
- CORS support (#158)
|
|
||||||
- Source IP binding configuration for FrostFS requests (#160)
|
|
||||||
- Tracing attributes (#164)
|
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
- Updated Go version to 1.22 (#132)
|
- Help doesn't print empty parameters (#186)
|
||||||
|
- Update version calculation (#190, #199)
|
||||||
|
- Update neofs-sdk-go (#196)
|
||||||
|
- Update go version in CI and docker (#197, #202)
|
||||||
|
|
||||||
### Removed
|
## [0.23.0] - 2022-08-02
|
||||||
- Duplicated NNS Resolver code (#129)
|
|
||||||
|
|
||||||
## [0.30.3] - 2024-10-18
|
|
||||||
|
|
||||||
### Fixed
|
|
||||||
- Get response on S3 multipart object (#142)
|
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
- Support percent-encoding for GET queries (#134)
|
- New param to configure pool error threshold (#184)
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
- Split `FrostFS` interface into separate read methods (#127)
|
- Pprof and prometheus metrics configuration (#171)
|
||||||
|
- Drop GO111MODULES from builds (#182)
|
||||||
|
|
||||||
## [0.30.2] - 2024-09-03
|
### Updating from v0.22.0
|
||||||
|
1. To enable pprof use `pprof.enabled` instead of `pprof` in config.
|
||||||
|
To enable prometheus metrics use `prometheus.enabled` instead of `metrics` in config.
|
||||||
|
If you are using the command line flags you can skip this step.
|
||||||
|
|
||||||
|
## [0.22.0] - 2022-07-25
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
- Fuzzing tests (#135)
|
- Default params documentation (#172)
|
||||||
|
- Health metric (#175)
|
||||||
## [0.30.1] - 2024-08-20
|
|
||||||
|
|
||||||
### Fixed
|
|
||||||
- Error counting in pool component before connection switch (#131)
|
|
||||||
|
|
||||||
### Added
|
|
||||||
- Log of endpoint address during tree pool errors (#131)
|
|
||||||
|
|
||||||
## [0.30.0] - Kangshung - 2024-07-22
|
|
||||||
|
|
||||||
### Fixed
|
|
||||||
- Handle query unescape and invalid bearer token errors (#107)
|
|
||||||
- Fix HTTP/2 requests (#110)
|
|
||||||
|
|
||||||
### Added
|
|
||||||
- Add new `reconnect_interval` config param (#100)
|
|
||||||
- Erasure coding support in placement policy (#114)
|
|
||||||
- HTTP Header canonicalizer for well-known headers (#121)
|
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
- Improve test coverage (#112, #117)
|
- Version output (#169)
|
||||||
- Bumped vulnerable dependencies (#115)
|
- Updated SDK Version (#178)
|
||||||
- Replace extended ACL examples with policies in README (#118)
|
|
||||||
|
|
||||||
### Removed
|
## [0.21.0] - 2022-06-20
|
||||||
|
|
||||||
## [0.29.0] - Zemu - 2024-05-27
|
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
- Fix possibility of panic during SIGHUP (#99)
|
- Downloading ZIP archive using streaming (#163)
|
||||||
- Handle query unescape and invalid bearer token errors (#108)
|
|
||||||
- Fix log-level change on SIGHUP (#105)
|
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
- Support client side object cut (#70)
|
- New make target to build app in docker (#159)
|
||||||
- Add `frostfs.client_cut` config param
|
|
||||||
- Add `frostfs.buffer_max_size_for_put` config param
|
|
||||||
- Add bucket/container caching
|
|
||||||
- Disable homomorphic hash for PUT if it's disabled in container itself
|
|
||||||
- Add new `logger.destination` config param with journald support (#89, #104)
|
|
||||||
- Add support namespaces (#91)
|
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
- Replace atomics with mutex for reloadable params (#74)
|
- Increased buffer size for file uploading (#148)
|
||||||
|
- Updated linter version to v1.46.2 (#161)
|
||||||
|
- Updated CodeQL version to v2 (#158)
|
||||||
|
|
||||||
## [0.28.1] - 2024-01-24
|
|
||||||
|
|
||||||
### Added
|
## [0.20.0] - 2022-04-29
|
||||||
- Tree pool traversal limit (#92)
|
|
||||||
|
|
||||||
### Update from 0.28.0
|
|
||||||
See new `frostfs.tree_pool_max_attempts` config parameter.
|
|
||||||
|
|
||||||
## [0.28.0] - Academy of Sciences - 2023-12-07
|
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
- `grpc` schemas in tree configuration (#62)
|
- Get rid of data race on server shutdown (#145)
|
||||||
- `GetSubTree` failures (#67)
|
- Improved English in docs and comments (#153)
|
||||||
- Debian packaging (#69, #90)
|
- Use `FilePath` to download zip (#150)
|
||||||
- Get latest version of tree node (#85)
|
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
- Support dump metrics descriptions (#29)
|
- Support container name NNS resolving (#142)
|
||||||
- Support impersonate bearer token (#40, #45)
|
|
||||||
- Tracing support (#20, #44, #60)
|
|
||||||
- Object name resolving with tree service (#30)
|
|
||||||
- Metrics for current endpoint status (#77)
|
|
||||||
- Soft memory limit with `runtime.soft_memory_limit` (#72)
|
|
||||||
- Add selection of the node of the latest version of the object (#85)
|
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
- Update prometheus to v1.15.0 (#35)
|
- Updated docs (#133, #140)
|
||||||
- Update go version to 1.19 (#50)
|
- Increased default read/write timeouts (#154)
|
||||||
- Finish rebranding (#2)
|
- Updated SDK (#137, #139)
|
||||||
- Use gate key to form object owner (#66)
|
- Updated go version to 1.17 (#143)
|
||||||
- Move log messages to constants (#36)
|
- Improved error messages (#144)
|
||||||
- Uploader and downloader refactor (#73)
|
|
||||||
|
|
||||||
### Removed
|
## [0.19.0] - 2022-03-16
|
||||||
- Drop `tree.service` param (now endpoints from `peers` section are used) (#59)
|
|
||||||
|
|
||||||
## [0.27.0] - Karpinsky - 2023-07-12
|
|
||||||
|
|
||||||
This is a first FrostFS HTTP Gateway release named after
|
|
||||||
[Karpinsky glacier](https://en.wikipedia.org/wiki/Karpinsky_Glacier).
|
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
- Require only one healthy storage server to start (#7)
|
- Uploading object with zero payload (#122)
|
||||||
- Enable gate metrics (#38)
|
- Different headers format in GET and HEAD (#125)
|
||||||
- `Too many pings` error (#61)
|
- Fixed project name in docs (#120)
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
- Multiple configs support (#12)
|
- Support object attributes with spaces (#123)
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
- Repository rebranding (#1)
|
- Updated fasthttp to v1.34.0 (#129)
|
||||||
- Update neo-go to v0.101.0 (#8)
|
- Updated NeoFS SDK to v1.0.0-rc.3 (#126, #132)
|
||||||
- Update viper to v1.15.0 (#8)
|
- Refactored content type detecting (#128)
|
||||||
- Update go version to 1.18 (#9)
|
|
||||||
- Errors have become more detailed (#18)
|
|
||||||
- Update system attribute names (#22)
|
|
||||||
- Separate integration tests with build tags (#24)
|
|
||||||
- Changed values for `frostfs_http_gw_state_health` metric (#32)
|
|
||||||
|
|
||||||
### Updating from neofs-http-gw v0.26.0
|
|
||||||
|
|
||||||
To set system attributes use updated headers
|
## [0.18.0] - 2021-12-10
|
||||||
(you can use old ones for now, but their support will be dropped in the future releases):
|
|
||||||
|
|
||||||
* `X-Attribute-Neofs-*` -> `X-Attribute-System-*`
|
### Fixed
|
||||||
* `X-Attribute-NEOFS-*` -> `X-Attribute-SYSTEM-*`
|
- System headers format (#111)
|
||||||
* `X-Attribute-neofs-*` -> `X-Attribute-system-*`
|
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Different formats to set object's expiration: in epoch, duration, timestamp,
|
||||||
|
RFC3339 (#108)
|
||||||
|
- Support of nodes priority (#115)
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Updated testcontainers dependency (#100)
|
||||||
|
|
||||||
|
## [0.17.0] - 2021-11-15
|
||||||
|
|
||||||
|
Support of bulk file download with zip streams and various bug fixes.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Allow canonical `X-Attribute-Neofs-*` headers (#87)
|
||||||
|
- Responses with error message now end with `\n` character (#105)
|
||||||
|
- Application does not require all neofs endpoints to be healthy at start now
|
||||||
|
(#103)
|
||||||
|
- Application now tracks session token errors and recreates tokens in runtime
|
||||||
|
(#95)
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Integration tests with [all-in-one](https://github.com/nspcc-dev/neofs-aio/)
|
||||||
|
test containers (#85, #94)
|
||||||
|
- Bulk download support with zip streams (#92, #96)
|
||||||
|
|
||||||
|
## 0.16.1 (28 Jul 2021)
|
||||||
|
|
||||||
|
New features:
|
||||||
|
* logging requests (#77)
|
||||||
|
* HEAD methods for download routes (#76)
|
||||||
|
|
||||||
|
Improvements:
|
||||||
|
* updated sdk-go dependency (#82)
|
||||||
|
|
||||||
|
Bugs fixed:
|
||||||
|
* wrong NotFound status was used (#30)
|
||||||
|
|
||||||
|
## 0.16.0 (29 Jun 2021)
|
||||||
|
|
||||||
|
We update HTTP gateway with NEP-6 wallets support, YAML configuration files
|
||||||
|
and small fixes.
|
||||||
|
|
||||||
|
New features:
|
||||||
|
* YAML configuration file (#71)
|
||||||
|
|
||||||
|
Behavior changes:
|
||||||
|
* gateway key needs to be stored in a proper NEP-6 wallet now, `-k` option is
|
||||||
|
no longer available, see `-w` and `-a` (#68)
|
||||||
|
|
||||||
|
Bugs fixed:
|
||||||
|
* downloads were not streamed leading to excessive memory usage (#67)
|
||||||
|
* Last-Modified header incorrectly used local time (#75)
|
||||||
|
|
||||||
|
## 0.15.2 (22 Jun 2021)
|
||||||
|
|
||||||
|
New features:
|
||||||
|
* Content-Type returned for object GET requests can now be taken from
|
||||||
|
attributes (overriding autodetection, #65)
|
||||||
|
|
||||||
|
Behavior changes:
|
||||||
|
* grpc keepalive options can no longer be changed (#60)
|
||||||
|
|
||||||
|
Improvements:
|
||||||
|
* code refactoring (more reuse between different gateways, moved some code to
|
||||||
|
sdk-go, #47, #46, #51, #62, #63)
|
||||||
|
* documentation updates and fixes (#53, #49, #55, #59)
|
||||||
|
* updated api-go dependency (#57)
|
||||||
|
|
||||||
|
Bugs fixed:
|
||||||
|
* `-k` option wasn't accepted for key although it was documented (#50)
|
||||||
|
|
||||||
|
## 0.15.1 (24 May 2021)
|
||||||
|
|
||||||
|
This important release makes HTTP gateway compatible with NeoFS node version
|
||||||
|
0.20.0.
|
||||||
|
|
||||||
|
Behavior changes:
|
||||||
|
* neofs-api-go was updated to 1.26.1, which contains some incompatible
|
||||||
|
changes in underlying components (#39, #44)
|
||||||
|
* `neofs-http-gw` is consistently used now for repository, binary and image
|
||||||
|
names (#43)
|
||||||
|
|
||||||
|
Improvements:
|
||||||
|
* minor code cleanups based on stricter set of linters (#41)
|
||||||
|
* updated README (#42)
|
||||||
|
|
||||||
|
## 0.15.0 (30 Apr 2021)
|
||||||
|
|
||||||
|
This is the first public release incorporating latest NeoFS protocol support
|
||||||
|
and fixing some bugs.
|
||||||
|
|
||||||
|
New features:
|
||||||
|
* upload support (#14, #13, #29)
|
||||||
|
* ephemeral keys (#26)
|
||||||
|
* TLS server support (#28)
|
||||||
|
|
||||||
|
Behavior changes:
|
||||||
|
* node weights can now be specified as simple numbers instead of percentages
|
||||||
|
and gateway will calculate the proportion automatically (#27)
|
||||||
|
* attributes are converted now to `X-Attribute-*` headers when retrieving
|
||||||
|
object from gate instead of `X-*` (#29)
|
||||||
|
|
||||||
|
Improvements:
|
||||||
|
* better Makefile (#16, #24, #33, #34)
|
||||||
|
* updated documentation (#16, #29, #35, #36)
|
||||||
|
* updated neofs-api-go to v1.25.0 (#17, #20)
|
||||||
|
* updated fasthttp to v1.23.0+ (#17, #29)
|
||||||
|
* refactoring, eliminating some dependencies (#20, #29)
|
||||||
|
|
||||||
|
Bugs fixed:
|
||||||
|
* gateway attempted to work with no NeoFS peers configured (#29)
|
||||||
|
* some invalid headers could be sent for attributes using non-ASCII or
|
||||||
|
non-printable characters (#29)
|
||||||
|
|
||||||
## Older versions
|
## Older versions
|
||||||
|
|
||||||
This project is a fork of [NeoFS HTTP Gateway](https://github.com/nspcc-dev/neofs-http-gw) from version v0.26.0.
|
Please refer to [Github
|
||||||
To see CHANGELOG for older versions, refer to https://github.com/nspcc-dev/neofs-http-gw/blob/master/CHANGELOG.md.
|
releases](https://github.com/nspcc-dev/neofs-http-gw/releases/) for older
|
||||||
|
releases.
|
||||||
|
|
||||||
[0.27.0]: https://git.frostfs.info/TrueCloudLab/frostfs-http-gw/compare/72734ab4...v0.27.0
|
[0.17.0]: https://github.com/nspcc-dev/neofs-http-gw/compare/v0.16.1...v0.17.0
|
||||||
[0.28.0]: https://git.frostfs.info/TrueCloudLab/frostfs-http-gw/compare/v0.27.0...v0.28.0
|
[0.18.0]: https://github.com/nspcc-dev/neofs-http-gw/compare/v0.17.0...v0.18.0
|
||||||
[0.28.1]: https://git.frostfs.info/TrueCloudLab/frostfs-http-gw/compare/v0.28.0...v0.28.1
|
[0.19.0]: https://github.com/nspcc-dev/neofs-http-gw/compare/v0.18.0...v0.19.0
|
||||||
[0.29.0]: https://git.frostfs.info/TrueCloudLab/frostfs-http-gw/compare/v0.28.1...v0.29.0
|
[0.20.0]: https://github.com/nspcc-dev/neofs-http-gw/compare/v0.19.0...v0.20.0
|
||||||
[0.30.0]: https://git.frostfs.info/TrueCloudLab/frostfs-http-gw/compare/v0.29.0...v0.30.0
|
[0.21.0]: https://github.com/nspcc-dev/neofs-http-gw/compare/v0.20.0...v0.21.0
|
||||||
[0.30.1]: https://git.frostfs.info/TrueCloudLab/frostfs-http-gw/compare/v0.30.0...v0.30.1
|
[0.22.0]: https://github.com/nspcc-dev/neofs-http-gw/compare/v0.21.0...v0.22.0
|
||||||
[0.30.2]: https://git.frostfs.info/TrueCloudLab/frostfs-http-gw/compare/v0.30.1...v0.30.2
|
[0.23.0]: https://github.com/nspcc-dev/neofs-http-gw/compare/v0.22.0...v0.23.0
|
||||||
[0.30.3]: https://git.frostfs.info/TrueCloudLab/frostfs-http-gw/compare/v0.30.2...v0.30.3
|
[0.24.0]: https://github.com/nspcc-dev/neofs-http-gw/compare/v0.23.0...v0.24.0
|
||||||
[0.31.0]: https://git.frostfs.info/TrueCloudLab/frostfs-http-gw/compare/v0.30.3...v0.31.0
|
[0.25.0]: https://github.com/nspcc-dev/neofs-http-gw/compare/v0.24.0...v0.25.0
|
||||||
[0.32.0]: https://git.frostfs.info/TrueCloudLab/frostfs-http-gw/compare/v0.31.0...v0.32.0
|
[0.25.1]: https://github.com/nspcc-dev/neofs-http-gw/compare/v0.25.0...v0.25.1
|
||||||
[0.32.1]: https://git.frostfs.info/TrueCloudLab/frostfs-http-gw/compare/v0.32.0...v0.32.1
|
[Unreleased]: https://github.com/nspcc-dev/neofs-http-gw/compare/v0.25.1...master
|
||||||
[0.32.2]: https://git.frostfs.info/TrueCloudLab/frostfs-http-gw/compare/v0.32.1...v0.32.2
|
|
||||||
[0.32.3]: https://git.frostfs.info/TrueCloudLab/frostfs-http-gw/compare/v0.32.2...v0.32.3
|
|
||||||
[Unreleased]: https://git.frostfs.info/TrueCloudLab/frostfs-http-gw/compare/v0.32.3...master
|
|
||||||
|
|
|
@ -1,3 +0,0 @@
|
||||||
.* @TrueCloudLab/storage-services-developers @TrueCloudLab/storage-services-committers
|
|
||||||
.forgejo/.* @potyarkin
|
|
||||||
Makefile @potyarkin
|
|
|
@ -3,8 +3,8 @@
|
||||||
First, thank you for contributing! We love and encourage pull requests from
|
First, thank you for contributing! We love and encourage pull requests from
|
||||||
everyone. Please follow the guidelines:
|
everyone. Please follow the guidelines:
|
||||||
|
|
||||||
- Check the open [issues](https://git.frostfs.info/TrueCloudLab/frostfs-http-gw/issues) and
|
- Check the open [issues](https://github.com/nspcc-dev/neofs-http-gw/issues) and
|
||||||
[pull requests](https://git.frostfs.info/TrueCloudLab/frostfs-http-gw/pulls) for existing
|
[pull requests](https://github.com/nspcc-dev/neofs-http-gw/pulls) for existing
|
||||||
discussions.
|
discussions.
|
||||||
|
|
||||||
- Open an issue first, to discuss a new feature or enhancement.
|
- Open an issue first, to discuss a new feature or enhancement.
|
||||||
|
@ -23,24 +23,24 @@ everyone. Please follow the guidelines:
|
||||||
|
|
||||||
## Development Workflow
|
## Development Workflow
|
||||||
|
|
||||||
Start by forking the `frostfs-http-gw` repository, make changes in a branch and then
|
Start by forking the `neofs-http-gw` repository, make changes in a branch and then
|
||||||
send a pull request. We encourage pull requests to discuss code changes. Here
|
send a pull request. We encourage pull requests to discuss code changes. Here
|
||||||
are the steps in details:
|
are the steps in details:
|
||||||
|
|
||||||
### Set up your git repository
|
### Set up your GitHub Repository
|
||||||
Fork [FrostFS HTTP Gateway
|
Fork [NeoFS HTTP Gateway
|
||||||
upstream](https://git.frostfs.info/repo/fork/8) source repository
|
upstream](https://github.com/nspcc-dev/neofs-http-gw/fork) source repository
|
||||||
to your own personal repository. Copy the URL of your fork (you will need it for
|
to your own personal repository. Copy the URL of your fork (you will need it for
|
||||||
the `git clone` command below).
|
the `git clone` command below).
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
$ git clone https://git.frostfs.info/<username>/frostfs-http-gw.git
|
$ git clone https://github.com/nspcc-dev/neofs-http-gw
|
||||||
```
|
```
|
||||||
|
|
||||||
### Set up git remote as ``upstream``
|
### Set up git remote as ``upstream``
|
||||||
```sh
|
```sh
|
||||||
$ cd frostfs-http-gw
|
$ cd neofs-http-gw
|
||||||
$ git remote add upstream https://git.frostfs.info/TrueCloudLab/frostfs-http-gw.git
|
$ git remote add upstream https://github.com/nspcc-dev/neofs-http-gw
|
||||||
$ git fetch upstream
|
$ git fetch upstream
|
||||||
$ git merge upstream/master
|
$ git merge upstream/master
|
||||||
...
|
...
|
||||||
|
@ -90,8 +90,8 @@ $ git push origin feature/123-something_awesome
|
||||||
```
|
```
|
||||||
|
|
||||||
### Create a Pull Request
|
### Create a Pull Request
|
||||||
Pull requests can be created via Forgejo. Refer to [this
|
Pull requests can be created via GitHub. Refer to [this
|
||||||
document](https://docs.codeberg.org/collaborating/pull-requests-and-git-flow/) for
|
document](https://help.github.com/articles/creating-a-pull-request/) for
|
||||||
detailed steps on how to create a pull request. After a Pull Request gets peer
|
detailed steps on how to create a pull request. After a Pull Request gets peer
|
||||||
reviewed and approved, it will be merged.
|
reviewed and approved, it will be merged.
|
||||||
|
|
||||||
|
@ -107,7 +107,7 @@ contributors".
|
||||||
To sign your work, just add a line like this at the end of your commit message:
|
To sign your work, just add a line like this at the end of your commit message:
|
||||||
|
|
||||||
```
|
```
|
||||||
Signed-off-by: Samii Sakisaka <samii@frostfs.info>
|
Signed-off-by: Samii Sakisaka <samii@nspcc.ru>
|
||||||
```
|
```
|
||||||
|
|
||||||
This can be easily done with the `--signoff` option to `git commit`.
|
This can be easily done with the `--signoff` option to `git commit`.
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
FROM golang:1.22-alpine AS basebuilder
|
FROM golang:1.19-alpine as basebuilder
|
||||||
RUN apk add --update make bash ca-certificates
|
RUN apk add --update make bash ca-certificates
|
||||||
|
|
||||||
FROM basebuilder AS builder
|
FROM basebuilder as builder
|
||||||
ENV GOGC=off
|
ENV GOGC off
|
||||||
ENV CGO_ENABLED=0
|
ENV CGO_ENABLED 0
|
||||||
ARG BUILD=now
|
ARG BUILD=now
|
||||||
ARG VERSION=dev
|
ARG VERSION=dev
|
||||||
ARG REPO=repository
|
ARG REPO=repository
|
||||||
|
@ -18,6 +18,6 @@ FROM scratch
|
||||||
WORKDIR /
|
WORKDIR /
|
||||||
|
|
||||||
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
|
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
|
||||||
COPY --from=builder /src/bin/frostfs-http-gw /bin/frostfs-http-gw
|
COPY --from=builder /src/bin/neofs-http-gw /bin/neofs-http-gw
|
||||||
|
|
||||||
ENTRYPOINT ["/bin/frostfs-http-gw"]
|
ENTRYPOINT ["/bin/neofs-http-gw"]
|
|
@ -3,6 +3,6 @@ RUN apk add --update --no-cache bash ca-certificates
|
||||||
|
|
||||||
WORKDIR /
|
WORKDIR /
|
||||||
|
|
||||||
COPY bin/frostfs-http-gw /bin/frostfs-http-gw
|
COPY bin/neofs-http-gw /bin/neofs-http-gw
|
||||||
|
|
||||||
CMD ["frostfs-http-gw"]
|
CMD ["neofs-http-gw"]
|
107
Makefile
Executable file → Normal file
107
Makefile
Executable file → Normal file
|
@ -2,47 +2,36 @@
|
||||||
|
|
||||||
REPO ?= $(shell go list -m)
|
REPO ?= $(shell go list -m)
|
||||||
VERSION ?= $(shell git describe --tags --match "v*" --dirty --always --abbrev=8 2>/dev/null || cat VERSION 2>/dev/null || echo "develop")
|
VERSION ?= $(shell git describe --tags --match "v*" --dirty --always --abbrev=8 2>/dev/null || cat VERSION 2>/dev/null || echo "develop")
|
||||||
GO_VERSION ?= 1.22
|
GO_VERSION ?= 1.19
|
||||||
LINT_VERSION ?= 1.60.3
|
LINT_VERSION ?= 1.49.0
|
||||||
TRUECLOUDLAB_LINT_VERSION ?= 0.0.6
|
|
||||||
BUILD ?= $(shell date -u --iso=seconds)
|
BUILD ?= $(shell date -u --iso=seconds)
|
||||||
|
|
||||||
HUB_IMAGE ?= git.frostfs.info/truecloudlab/frostfs-http-gw
|
HUB_IMAGE ?= nspccdev/neofs-http-gw
|
||||||
HUB_TAG ?= "$(shell echo ${VERSION} | sed 's/^v//')"
|
HUB_TAG ?= "$(shell echo ${VERSION} | sed 's/^v//')"
|
||||||
|
|
||||||
METRICS_DUMP_OUT ?= ./metrics-dump.json
|
|
||||||
|
|
||||||
OUTPUT_LINT_DIR ?= $(shell pwd)/bin
|
|
||||||
LINT_DIR = $(OUTPUT_LINT_DIR)/golangci-lint-$(LINT_VERSION)-v$(TRUECLOUDLAB_LINT_VERSION)
|
|
||||||
TMP_DIR := .cache
|
|
||||||
|
|
||||||
# List of binaries to build. For now just one.
|
# List of binaries to build. For now just one.
|
||||||
BINDIR = bin
|
BINDIR = bin
|
||||||
CMDS = $(addprefix frostfs-, $(notdir $(wildcard cmd/*)))
|
DIRS = $(BINDIR)
|
||||||
BINS = $(addprefix $(BINDIR)/, $(CMDS))
|
BINS = $(BINDIR)/neofs-http-gw
|
||||||
|
|
||||||
.PHONY: all $(BINS) $(DIRS) dep docker/ test cover fmt image image-push dirty-image lint docker/lint pre-commit unpre-commit version clean
|
.PHONY: all $(BINS) $(DIRS) dep docker/ test cover fmt image image-push dirty-image lint docker/lint version clean
|
||||||
|
|
||||||
# .deb package versioning
|
# .deb package versioning
|
||||||
OS_RELEASE = $(shell lsb_release -cs)
|
OS_RELEASE = $(shell lsb_release -cs)
|
||||||
PKG_VERSION ?= $(shell echo $(VERSION) | sed "s/^v//" | \
|
PKG_VERSION ?= $(shell echo $(VERSION) | sed "s/^v//" | \
|
||||||
sed -E "s/(.*)-(g[a-fA-F0-9]{6,8})(.*)/\1\3~\2/" | \
|
sed -E "s/(.*)-(g[a-fA-F0-9]{6,8})(.*)/\1\3~\2/" | \
|
||||||
sed "s/-/~/")-${OS_RELEASE}
|
sed "s/-/~/")-${OS_RELEASE}
|
||||||
.PHONY: debpackage debclean
|
.PHONY: debpackage debclean
|
||||||
|
|
||||||
FUZZ_NGFUZZ_DIR ?= ""
|
|
||||||
FUZZ_TIMEOUT ?= 30
|
|
||||||
FUZZ_FUNCTIONS ?= "all"
|
|
||||||
FUZZ_AUX ?= ""
|
|
||||||
|
|
||||||
# Make all binaries
|
# Make all binaries
|
||||||
all: $(BINS)
|
all: $(BINS)
|
||||||
$(BINS): $(DIRS) dep
|
|
||||||
|
$(BINS): $(DIRS) dep
|
||||||
@echo "⇒ Build $@"
|
@echo "⇒ Build $@"
|
||||||
CGO_ENABLED=0 \
|
CGO_ENABLED=0 \
|
||||||
go build -v -trimpath \
|
go build -v -trimpath \
|
||||||
-ldflags "-X main.Version=$(VERSION)" \
|
-ldflags "-X main.Version=$(VERSION)" \
|
||||||
-o $@ ./cmd/$(subst frostfs-,,$(notdir $@))
|
-o $@ ./
|
||||||
|
|
||||||
$(DIRS):
|
$(DIRS):
|
||||||
@echo "⇒ Ensure dir: $@"
|
@echo "⇒ Ensure dir: $@"
|
||||||
|
@ -73,45 +62,11 @@ docker/%:
|
||||||
test:
|
test:
|
||||||
@go test ./... -cover
|
@go test ./... -cover
|
||||||
|
|
||||||
# Run integration tests
|
|
||||||
.PHONY: integration-test
|
|
||||||
integration-test:
|
|
||||||
@go test ./... -cover --tags=integration
|
|
||||||
|
|
||||||
# Run tests with race detection and produce coverage output
|
# Run tests with race detection and produce coverage output
|
||||||
cover:
|
cover:
|
||||||
@go test -v -race ./... -coverprofile=coverage.txt -covermode=atomic
|
@go test -v -race ./... -coverprofile=coverage.txt -covermode=atomic
|
||||||
@go tool cover -html=coverage.txt -o coverage.html
|
@go tool cover -html=coverage.txt -o coverage.html
|
||||||
|
|
||||||
# Run fuzzing
|
|
||||||
CLANG := $(shell which clang-17 2>/dev/null)
|
|
||||||
.PHONY: check-clang all
|
|
||||||
check-clang:
|
|
||||||
ifeq ($(CLANG),)
|
|
||||||
@echo "clang-17 is not installed. Please install it before proceeding - https://apt.llvm.org/llvm.sh "
|
|
||||||
@exit 1
|
|
||||||
endif
|
|
||||||
|
|
||||||
.PHONY: check-ngfuzz all
|
|
||||||
check-ngfuzz:
|
|
||||||
@if [ -z "$(FUZZ_NGFUZZ_DIR)" ]; then \
|
|
||||||
echo "Please set a variable FUZZ_NGFUZZ_DIR to specify path to the ngfuzz"; \
|
|
||||||
exit 1; \
|
|
||||||
fi
|
|
||||||
|
|
||||||
.PHONY: install-fuzzing-deps
|
|
||||||
install-fuzzing-deps: check-clang check-ngfuzz
|
|
||||||
|
|
||||||
.PHONY: fuzz
|
|
||||||
fuzz: install-fuzzing-deps
|
|
||||||
@START_PATH=$$(pwd); \
|
|
||||||
ROOT_PATH=$$(realpath --relative-to=$(FUZZ_NGFUZZ_DIR) $$START_PATH) ; \
|
|
||||||
cd $(FUZZ_NGFUZZ_DIR) && \
|
|
||||||
./ngfuzz -clean && \
|
|
||||||
./ngfuzz -fuzz $(FUZZ_FUNCTIONS) -rootdir $$ROOT_PATH -timeout $(FUZZ_TIMEOUT) $(FUZZ_AUX) && \
|
|
||||||
./ngfuzz -report
|
|
||||||
|
|
||||||
|
|
||||||
# Reformat code
|
# Reformat code
|
||||||
fmt:
|
fmt:
|
||||||
@echo "⇒ Processing gofmt check"
|
@echo "⇒ Processing gofmt check"
|
||||||
|
@ -119,12 +74,12 @@ fmt:
|
||||||
|
|
||||||
# Build clean Docker image
|
# Build clean Docker image
|
||||||
image:
|
image:
|
||||||
@echo "⇒ Build FrostFS HTTP Gateway docker image "
|
@echo "⇒ Build NeoFS HTTP Gateway docker image "
|
||||||
@docker build \
|
@docker build \
|
||||||
--build-arg REPO=$(REPO) \
|
--build-arg REPO=$(REPO) \
|
||||||
--build-arg VERSION=$(VERSION) \
|
--build-arg VERSION=$(VERSION) \
|
||||||
--rm \
|
--rm \
|
||||||
-f .docker/Dockerfile \
|
-f Dockerfile \
|
||||||
-t $(HUB_IMAGE):$(HUB_TAG) .
|
-t $(HUB_IMAGE):$(HUB_TAG) .
|
||||||
|
|
||||||
# Push Docker image to the hub
|
# Push Docker image to the hub
|
||||||
|
@ -134,31 +89,17 @@ image-push:
|
||||||
|
|
||||||
# Build dirty Docker image
|
# Build dirty Docker image
|
||||||
dirty-image:
|
dirty-image:
|
||||||
@echo "⇒ Build FrostFS HTTP Gateway dirty docker image "
|
@echo "⇒ Build NeoFS HTTP Gateway dirty docker image "
|
||||||
@docker build \
|
@docker build \
|
||||||
--build-arg REPO=$(REPO) \
|
--build-arg REPO=$(REPO) \
|
||||||
--build-arg VERSION=$(VERSION) \
|
--build-arg VERSION=$(VERSION) \
|
||||||
--rm \
|
--rm \
|
||||||
-f .docker/Dockerfile.dirty \
|
-f Dockerfile.dirty \
|
||||||
-t $(HUB_IMAGE)-dirty:$(HUB_TAG) .
|
-t $(HUB_IMAGE)-dirty:$(HUB_TAG) .
|
||||||
|
|
||||||
# Install linters
|
|
||||||
lint-install:
|
|
||||||
@mkdir -p $(TMP_DIR)
|
|
||||||
@rm -rf $(TMP_DIR)/linters
|
|
||||||
@git -c advice.detachedHead=false clone --branch v$(TRUECLOUDLAB_LINT_VERSION) https://git.frostfs.info/TrueCloudLab/linters.git $(TMP_DIR)/linters
|
|
||||||
@@make -C $(TMP_DIR)/linters lib CGO_ENABLED=1 OUT_DIR=$(OUTPUT_LINT_DIR)
|
|
||||||
@rm -rf $(TMP_DIR)/linters
|
|
||||||
@rmdir $(TMP_DIR) 2>/dev/null || true
|
|
||||||
@CGO_ENABLED=1 GOBIN=$(LINT_DIR) go install github.com/golangci/golangci-lint/cmd/golangci-lint@v$(LINT_VERSION)
|
|
||||||
|
|
||||||
# Run linters
|
# Run linters
|
||||||
lint:
|
lint:
|
||||||
@if [ ! -d "$(LINT_DIR)" ]; then \
|
@golangci-lint --timeout=5m run
|
||||||
echo "Run make lint-install"; \
|
|
||||||
exit 1; \
|
|
||||||
fi
|
|
||||||
$(LINT_DIR)/golangci-lint --timeout=5m run
|
|
||||||
|
|
||||||
# Run linters in Docker
|
# Run linters in Docker
|
||||||
docker/lint:
|
docker/lint:
|
||||||
|
@ -168,14 +109,6 @@ docker/lint:
|
||||||
--env HOME=/src \
|
--env HOME=/src \
|
||||||
golangci/golangci-lint:v$(LINT_VERSION) bash -c 'cd /src/ && make lint'
|
golangci/golangci-lint:v$(LINT_VERSION) bash -c 'cd /src/ && make lint'
|
||||||
|
|
||||||
# Activate pre-commit hooks
|
|
||||||
pre-commit:
|
|
||||||
pre-commit install -t pre-commit -t commit-msg
|
|
||||||
|
|
||||||
# Deactivate pre-commit hooks
|
|
||||||
unpre-commit:
|
|
||||||
pre-commit uninstall -t pre-commit -t commit-msg
|
|
||||||
|
|
||||||
# Print version
|
# Print version
|
||||||
version:
|
version:
|
||||||
@echo $(VERSION)
|
@echo $(VERSION)
|
||||||
|
@ -183,11 +116,11 @@ version:
|
||||||
# Clean up
|
# Clean up
|
||||||
clean:
|
clean:
|
||||||
rm -rf vendor
|
rm -rf vendor
|
||||||
rm -rf $(BINDIR)
|
rm -rf $(BINDIR)
|
||||||
|
|
||||||
# Package for Debian
|
# Package for Debian
|
||||||
debpackage:
|
debpackage:
|
||||||
dch --package frostfs-http-gw \
|
dch --package neofs-http-gw \
|
||||||
--controlmaint \
|
--controlmaint \
|
||||||
--newversion $(PKG_VERSION) \
|
--newversion $(PKG_VERSION) \
|
||||||
--distribution $(OS_RELEASE) \
|
--distribution $(OS_RELEASE) \
|
||||||
|
@ -197,10 +130,4 @@ debpackage:
|
||||||
debclean:
|
debclean:
|
||||||
dh clean
|
dh clean
|
||||||
|
|
||||||
# Dump metrics (use METRICS_DUMP_OUT variable to override default out file './metrics-dump.json')
|
|
||||||
.PHONY: dump-metrics
|
|
||||||
dump-metrics:
|
|
||||||
@go test ./metrics -run TestDescribeAll --tags=dump_metrics --out=$(abspath $(METRICS_DUMP_OUT))
|
|
||||||
|
|
||||||
|
|
||||||
include help.mk
|
include help.mk
|
||||||
|
|
366
README.md
366
README.md
|
@ -1,30 +1,28 @@
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="./.forgejo/logo.svg" width="500px" alt="FrostFS logo">
|
<img src="./.github/logo.svg" width="500px" alt="NeoFS">
|
||||||
</p>
|
</p>
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://frostfs.info">FrostFS</a> is a decentralized distributed object storage integrated with the <a href="https://neo.org">NEO Blockchain</a>.
|
<a href="https://fs.neo.org">NeoFS</a> is a decentralized distributed object storage integrated with the <a href="https://neo.org">NEO Blockchain</a>.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
---
|
---
|
||||||
[![Report](https://goreportcard.com/badge/git.frostfs.info/TrueCloudLab/frostfs-http-gw)](https://goreportcard.com/report/git.frostfs.info/TrueCloudLab/frostfs-http-gw)
|
[![Report](https://goreportcard.com/badge/github.com/nspcc-dev/neofs-http-gw)](https://goreportcard.com/report/github.com/nspcc-dev/neofs-http-gw)
|
||||||
![Release](https://img.shields.io/badge/dynamic/json.svg?label=release&url=https://git.frostfs.info/api/v1/repos/TrueCloudLab/frostfs-http-gw/releases&query=$[0].tag_name&color=orange)
|
![GitHub release (latest SemVer)](https://img.shields.io/github/v/release/nspcc-dev/neofs-http-gw?sort=semver)
|
||||||
![License](https://img.shields.io/badge/license-GPL--3.0-orange.svg)
|
![License](https://img.shields.io/github/license/nspcc-dev/neofs-http-gw.svg?style=popout)
|
||||||
|
|
||||||
# FrostFS HTTP Gateway
|
# NeoFS HTTP Gateway
|
||||||
|
|
||||||
FrostFS HTTP Gateway bridges FrostFS internal protocol and HTTP standard.
|
NeoFS HTTP Gateway bridges NeoFS internal protocol and HTTP standard.
|
||||||
- you can download one file per request from the FrostFS Network
|
- you can download one file per request from the NeoFS Network
|
||||||
- you can upload one file per request into the FrostFS Network
|
- you can upload one file per request into the NeoFS Network
|
||||||
|
|
||||||
See available routes in [specification](./docs/api.md).
|
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
```go install git.frostfs.info/TrueCloudLab/frostfs-http-gw```
|
```go install github.com/nspcc-dev/neofs-http-gw```
|
||||||
|
|
||||||
Or you can call `make` to build it from the cloned repository (the binary will
|
Or you can call `make` to build it from the cloned repository (the binary will
|
||||||
end up in `bin/frostfs-http-gw`). To build frostfs-http-gw binary in clean docker
|
end up in `bin/neofs-http-gw`). To build neofs-http-gw binary in clean docker
|
||||||
environment, call `make docker/bin/frostfs-http-gw`.
|
environment, call `make docker/bin/neofs-http-gw`.
|
||||||
|
|
||||||
Other notable make targets:
|
Other notable make targets:
|
||||||
|
|
||||||
|
@ -38,32 +36,32 @@ version Show current version
|
||||||
```
|
```
|
||||||
|
|
||||||
Or you can also use a [Docker
|
Or you can also use a [Docker
|
||||||
image](https://git.frostfs.info/TrueCloudLab/-/packages/container/frostfs-http-gw) provided for the released
|
image](https://hub.docker.com/r/nspccdev/neofs-http-gw) provided for the released
|
||||||
(and occasionally unreleased) versions of the gateway (`:latest` points to the
|
(and occasionally unreleased) versions of the gateway (`:latest` points to the
|
||||||
latest stable release).
|
latest stable release).
|
||||||
|
|
||||||
## Execution
|
## Execution
|
||||||
|
|
||||||
HTTP gateway itself is not a FrostFS node, so to access FrostFS it uses node's
|
HTTP gateway itself is not a NeoFS node, so to access NeoFS it uses node's
|
||||||
gRPC interface and you need to provide some node that it will connect to. This
|
gRPC interface and you need to provide some node that it will connect to. This
|
||||||
can be done either via `-p` parameter or via `HTTP_GW_PEERS_<N>_ADDRESS` and
|
can be done either via `-p` parameter or via `HTTP_GW_PEERS_<N>_ADDRESS` and
|
||||||
`HTTP_GW_PEERS_<N>_WEIGHT` environment variables (the gate supports multiple
|
`HTTP_GW_PEERS_<N>_WEIGHT` environment variables (the gate supports multiple
|
||||||
FrostFS nodes with weighted load balancing).
|
NeoFS nodes with weighted load balancing).
|
||||||
|
|
||||||
If you launch HTTP gateway in bundle with [frostfs-dev-env](https://git.frostfs.info/TrueCloudLab/frostfs-dev-env),
|
If you launch HTTP gateway in bundle with [neofs-dev-env](https://github.com/nspcc-dev/neofs-dev-env),
|
||||||
you can get the IP address of the node in the output of `make hosts` command
|
you can get the IP address of the node in the output of `make hosts` command
|
||||||
(with s0*.frostfs.devenv name).
|
(with s0*.neofs.devenv name).
|
||||||
|
|
||||||
These two commands are functionally equivalent, they run the gate with one
|
These two commands are functionally equivalent, they run the gate with one
|
||||||
backend node (and otherwise default settings):
|
backend node (and otherwise default settings):
|
||||||
```
|
```
|
||||||
$ frostfs-http-gw -p 192.168.130.72:8080
|
$ neofs-http-gw -p 192.168.130.72:8080
|
||||||
$ HTTP_GW_PEERS_0_ADDRESS=192.168.130.72:8080 frostfs-http-gw
|
$ HTTP_GW_PEERS_0_ADDRESS=192.168.130.72:8080 neofs-http-gw
|
||||||
```
|
```
|
||||||
It's also possible to specify uri scheme (grpc or grpcs) when using `-p`:
|
It's also possible to specify uri scheme (grpc or grpcs) when using `-p`:
|
||||||
```
|
```
|
||||||
$ frostfs-http-gw -p grpc://192.168.130.72:8080
|
$ neofs-http-gw -p grpc://192.168.130.72:8080
|
||||||
$ HTTP_GW_PEERS_0_ADDRESS=grpcs://192.168.130.72:8080 frostfs-http-gw
|
$ HTTP_GW_PEERS_0_ADDRESS=grpcs://192.168.130.72:8080 neofs-http-gw
|
||||||
```
|
```
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
@ -74,11 +72,11 @@ environment variables (see [example](./config/config.env)), so they're not speci
|
||||||
|
|
||||||
### Nodes: weights and priorities
|
### Nodes: weights and priorities
|
||||||
|
|
||||||
You can specify multiple `-p` options to add more FrostFS nodes, this will make
|
You can specify multiple `-p` options to add more NeoFS nodes, this will make
|
||||||
gateway spread requests equally among them (using weight 1 and priority 1 for every node):
|
gateway spread requests equally among them (using weight 1 and priority 1 for every node):
|
||||||
|
|
||||||
```
|
```
|
||||||
$ frostfs-http-gw -p 192.168.130.72:8080 -p 192.168.130.71:8080
|
$ neofs-http-gw -p 192.168.130.72:8080 -p 192.168.130.71:8080
|
||||||
```
|
```
|
||||||
If you want some specific load distribution proportions, use weights and priorities:
|
If you want some specific load distribution proportions, use weights and priorities:
|
||||||
|
|
||||||
|
@ -86,21 +84,21 @@ If you want some specific load distribution proportions, use weights and priorit
|
||||||
$ HTTP_GW_PEERS_0_ADDRESS=192.168.130.71:8080 HTTP_GW_PEERS_0_WEIGHT=1 HTTP_GW_PEERS_0_PRIORITY=1 \
|
$ HTTP_GW_PEERS_0_ADDRESS=192.168.130.71:8080 HTTP_GW_PEERS_0_WEIGHT=1 HTTP_GW_PEERS_0_PRIORITY=1 \
|
||||||
HTTP_GW_PEERS_1_ADDRESS=192.168.130.72:8080 HTTP_GW_PEERS_1_WEIGHT=9 HTTP_GW_PEERS_1_PRIORITY=2 \
|
HTTP_GW_PEERS_1_ADDRESS=192.168.130.72:8080 HTTP_GW_PEERS_1_WEIGHT=9 HTTP_GW_PEERS_1_PRIORITY=2 \
|
||||||
HTTP_GW_PEERS_2_ADDRESS=192.168.130.73:8080 HTTP_GW_PEERS_2_WEIGHT=1 HTTP_GW_PEERS_2_PRIORITY=2 \
|
HTTP_GW_PEERS_2_ADDRESS=192.168.130.73:8080 HTTP_GW_PEERS_2_WEIGHT=1 HTTP_GW_PEERS_2_PRIORITY=2 \
|
||||||
frostfs-http-gw
|
neofs-http-gw
|
||||||
```
|
```
|
||||||
This command will make gateway use 192.168.130.71 while it is healthy. Otherwise, it will make the gateway use
|
This command will make gateway use 192.168.130.71 while it is healthy. Otherwise, it will make the gateway use
|
||||||
192.168.130.72 for 90% of requests and 192.168.130.73 for remaining 10%.
|
192.168.130.72 for 90% of requests and 192.168.130.73 for remaining 10%.
|
||||||
|
|
||||||
### Keys
|
### Keys
|
||||||
You can provide a wallet via `--wallet` or `-w` flag. You can also specify the account address using `--address`
|
You can provide a wallet via `--wallet` or `-w` flag. You can also specify the account address using `--address`
|
||||||
(if no address provided default one will be used). If wallet is used, you need to set `HTTP_GW_WALLET_PASSPHRASE` variable to decrypt the wallet.
|
(if no address provided default one will be used). If wallet is used, you need to set `HTTP_GW_WALLET_PASSPHRASE` variable to decrypt the wallet.
|
||||||
If no wallet provided, the gateway autogenerates a key pair it will use for FrostFS requests.
|
If no wallet provided, the gateway autogenerates a key pair it will use for NeoFS requests.
|
||||||
```
|
```
|
||||||
$ frostfs-http-gw -p $FROSTFS_NODE -w $WALLET_PATH --address $ACCOUNT_ADDRESS
|
$ neofs-http-gw -p $NEOFS_NODE -w $WALLET_PATH --address $ACCOUNT_ADDRESS
|
||||||
```
|
```
|
||||||
Example:
|
Example:
|
||||||
```
|
```
|
||||||
$ frostfs-http-gw -p 192.168.130.72:8080 -w wallet.json --address NfgHwwTi3wHAS8aFAN243C5vGbkYDpqLHP
|
$ neofs-http-gw -p 192.168.130.72:8080 -w wallet.json --address NfgHwwTi3wHAS8aFAN243C5vGbkYDpqLHP
|
||||||
```
|
```
|
||||||
|
|
||||||
### Binding and TLS
|
### Binding and TLS
|
||||||
|
@ -116,7 +114,7 @@ external redirecting solution.
|
||||||
Example to bind to `192.168.130.130:443` and serve TLS there:
|
Example to bind to `192.168.130.130:443` and serve TLS there:
|
||||||
|
|
||||||
```
|
```
|
||||||
$ frostfs-http-gw -p 192.168.130.72:8080 --listen_address 192.168.130.130:443 \
|
$ neofs-http-gw -p 192.168.130.72:8080 --listen_address 192.168.130.130:443 \
|
||||||
--tls_key=key.pem --tls_certificate=cert.pem
|
--tls_key=key.pem --tls_certificate=cert.pem
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -134,12 +132,12 @@ request with data stream after timeout.
|
||||||
|
|
||||||
`HTTP_GW_WEB_STREAM_REQUEST_BODY` environment variable can be used to disable
|
`HTTP_GW_WEB_STREAM_REQUEST_BODY` environment variable can be used to disable
|
||||||
request body streaming (effectively it'll make the gateway accept the file completely
|
request body streaming (effectively it'll make the gateway accept the file completely
|
||||||
first and only then try sending it to FrostFS).
|
first and only then try sending it to NeoFS).
|
||||||
|
|
||||||
`HTTP_GW_WEB_MAX_REQUEST_BODY_SIZE` controls maximum request body size
|
`HTTP_GW_WEB_MAX_REQUEST_BODY_SIZE` controls maximum request body size
|
||||||
limiting uploads to files slightly lower than this limit.
|
limiting uploads to files slightly lower than this limit.
|
||||||
|
|
||||||
### FrostFS parameters
|
### NeoFS parameters
|
||||||
|
|
||||||
Gateway can automatically set timestamps for uploaded files based on local
|
Gateway can automatically set timestamps for uploaded files based on local
|
||||||
time source, use `HTTP_GW_UPLOAD_HEADER_USE_DEFAULT_TIMESTAMP` environment
|
time source, use `HTTP_GW_UPLOAD_HEADER_USE_DEFAULT_TIMESTAMP` environment
|
||||||
|
@ -164,7 +162,7 @@ All timing options accept values with suffixes, so "15s" is 15 seconds and
|
||||||
"2m" is 2 minutes.
|
"2m" is 2 minutes.
|
||||||
|
|
||||||
### Zip streaming
|
### Zip streaming
|
||||||
The gateway supports downloading files by common prefix (like dir) in zip format. You can enable compression
|
The gateway supports downloading files by common prefix (like dir) in zip format. You can enable compression
|
||||||
using config or `HTTP_GW_ZIP_COMPRESSION=true` environment variable.
|
using config or `HTTP_GW_ZIP_COMPRESSION=true` environment variable.
|
||||||
|
|
||||||
### Logging
|
### Logging
|
||||||
|
@ -174,42 +172,25 @@ HTTP_GW_LOGGER_LEVEL=debug
|
||||||
```
|
```
|
||||||
|
|
||||||
### Yaml file
|
### Yaml file
|
||||||
Configuration file is optional and can be used instead of environment variables/other parameters.
|
Configuration file is optional and can be used instead of environment variables/other parameters.
|
||||||
It can be specified with `--config` parameter:
|
It can be specified with `--config` parameter:
|
||||||
```
|
```
|
||||||
$ frostfs-http-gw --config your-config.yaml
|
$ neofs-http-gw --config your-config.yaml
|
||||||
```
|
```
|
||||||
|
|
||||||
See [config](./config/config.yaml) and [defaults](./docs/gate-configuration.md) for example.
|
See [config](./config/config.yaml) and [defaults](./docs/gate-configuration.md) for example.
|
||||||
|
|
||||||
#### Multiple configs
|
|
||||||
|
|
||||||
You can use several config files when running application. It allows you to split configuration into parts.
|
|
||||||
For example, you can use separate yaml file for pprof and prometheus section in config (see [config examples](./config)).
|
|
||||||
You can either provide several files with repeating `--config` flag or provide path to the dir that contains all configs using `--config-dir` flag.
|
|
||||||
Also, you can combine these flags:
|
|
||||||
|
|
||||||
```shell
|
|
||||||
$ frostfs-http-gw --config ./config/config.yaml --config /your/partial/config.yaml --config-dir ./config/dir
|
|
||||||
```
|
|
||||||
|
|
||||||
**Note:** next file in `--config` flag overwrites values from the previous one.
|
|
||||||
Files from `--config-dir` directory overwrite values from `--config` files.
|
|
||||||
So the command above run `frostfs-http-gw` to listen on `0.0.0.0:8080` address (value from `./config/config.yaml`),
|
|
||||||
applies parameters from `/your/partial/config.yaml`,
|
|
||||||
enable pprof (value from `./config/dir/pprof.yaml`) and prometheus (value from `./config/dir/prometheus.yaml`).
|
|
||||||
|
|
||||||
## HTTP API provided
|
## HTTP API provided
|
||||||
|
|
||||||
This gateway intentionally provides limited feature set and doesn't try to
|
This gateway intentionally provides limited feature set and doesn't try to
|
||||||
substitute (or completely wrap) regular gRPC FrostFS interface. You can download
|
substitute (or completely wrap) regular gRPC NeoFS interface. You can download
|
||||||
and upload objects with it, but deleting, searching, managing ACLs, creating
|
and upload objects with it, but deleting, searching, managing ACLs, creating
|
||||||
containers and other activities are not supported and not planned to be
|
containers and other activities are not supported and not planned to be
|
||||||
supported.
|
supported.
|
||||||
|
|
||||||
### Preparation
|
### Preparation
|
||||||
|
|
||||||
Before uploading or downloading a file make sure you have a prepared container.
|
Before uploading or downloading a file make sure you have a prepared container.
|
||||||
You can create it with instructions below.
|
You can create it with instructions below.
|
||||||
|
|
||||||
Also, in case of downloading, you need to have a file inside a container.
|
Also, in case of downloading, you need to have a file inside a container.
|
||||||
|
@ -217,41 +198,74 @@ Also, in case of downloading, you need to have a file inside a container.
|
||||||
### NNS
|
### NNS
|
||||||
|
|
||||||
In all download/upload routes you can use container name instead of its id (`$CID`).
|
In all download/upload routes you can use container name instead of its id (`$CID`).
|
||||||
Read more about it in [docs/nns.md](./docs/nns.md).
|
|
||||||
|
|
||||||
|
Steps to start using name resolving:
|
||||||
|
|
||||||
|
1. Enable NNS resolving in config (`rpc_endpoint` must be a valid neo rpc node, see [configs](./config) for other examples):
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
rpc_endpoint: http://morph-chain.neofs.devenv:30333
|
||||||
|
resolve_order:
|
||||||
|
- nns
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Make sure your container is registered in NNS contract. If you use [neofs-dev-env](https://github.com/nspcc-dev/neofs-dev-env)
|
||||||
|
you can check if your container (e.g. with `container-name` name) is registered in NNS:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
$ curl -s --data '{"id":1,"jsonrpc":"2.0","method":"getcontractstate","params":[1]}' \
|
||||||
|
http://morph-chain.neofs.devenv:30333 | jq -r '.result.hash'
|
||||||
|
|
||||||
|
0x8e6c3cd4b976b28e84a3788f6ea9e2676c15d667
|
||||||
|
|
||||||
|
$ docker exec -it morph_chain neo-go \
|
||||||
|
contract testinvokefunction \
|
||||||
|
-r http://morph-chain.neofs.devenv:30333 0x8e6c3cd4b976b28e84a3788f6ea9e2676c15d667 \
|
||||||
|
resolve string:container-name.container int:16 \
|
||||||
|
| jq -r '.stack[0].value | if type=="array" then .[0].value else . end' \
|
||||||
|
| base64 -d && echo
|
||||||
|
|
||||||
|
7f3vvkw4iTiS5ZZbu5BQXEmJtETWbi3uUjLNaSs29xrL
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Use container name instead of its `$CID`. For example:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
$ curl http://localhost:8082/get_by_attribute/container-name/FileName/object-name
|
||||||
|
```
|
||||||
|
|
||||||
#### Create a container
|
#### Create a container
|
||||||
|
|
||||||
You can create a container via [frostfs-cli](https://git.frostfs.info/TrueCloudLab/frostfs-node/releases):
|
You can create a container via [neofs-cli](https://github.com/nspcc-dev/neofs-node/releases):
|
||||||
```
|
```
|
||||||
$ frostfs-cli -r $FROSTFS_NODE -w $WALLET container create --policy $POLICY --basic-acl $ACL
|
$ neofs-cli -r $NEOFS_NODE -w $WALLET container create --policy $POLICY --basic-acl $ACL
|
||||||
```
|
```
|
||||||
where `$WALLET` is a path to user wallet,
|
where `$WALLET` is a path to user wallet,
|
||||||
`$ACL` -- hex encoded basic ACL value or keywords 'private, 'public-read', 'public-read-write' and
|
`$ACL` -- hex encoded basic ACL value or keywords 'private, 'public-read', 'public-read-write' and
|
||||||
`$POLICY` -- QL-encoded or JSON-encoded placement policy or path to file with it
|
`$POLICY` -- QL-encoded or JSON-encoded placement policy or path to file with it
|
||||||
|
|
||||||
For example:
|
For example:
|
||||||
```
|
```
|
||||||
$ frostfs-cli -r 192.168.130.72:8080 -w ./wallet.json container create --policy "REP 3" --basic-acl public --await
|
$ neofs-cli -r 192.168.130.72:8080 -w ./wallet.json container create --policy "REP 3" --basic-acl public --await
|
||||||
```
|
```
|
||||||
|
|
||||||
If you have launched nodes via [frostfs-dev-env](https://git.frostfs.info/TrueCloudLab/frostfs-dev-env),
|
If you have launched nodes via [neofs-dev-env](https://github.com/nspcc-dev/neofs-dev-env),
|
||||||
you can get the key value from `wallets/wallet.json` or write the path to
|
you can get the key value from `wallets/wallet.json` or write the path to
|
||||||
the file `wallets/wallet.key`.
|
the file `wallets/wallet.key`.
|
||||||
|
|
||||||
#### Prepare a file in a container
|
#### Prepare a file in a container
|
||||||
|
|
||||||
To create a file via [frostfs-cli](https://git.frostfs.info/TrueCloudLab/frostfs-node/releases), run a command below:
|
To create a file via [neofs-cli](https://github.com/nspcc-dev/neofs-node/releases), run a command below:
|
||||||
```
|
```
|
||||||
$ frostfs-cli -r $FROSTFS_NODE -k $KEY object put --file $FILENAME --cid $CID
|
$ neofs-cli -r $NEOFS_NODE -k $KEY object put --file $FILENAME --cid $CID
|
||||||
```
|
```
|
||||||
where
|
where
|
||||||
`$KEY` -- the key, please read the information [above](#create-a-container),
|
`$KEY` -- the key, please read the information [above](#create-a-container),
|
||||||
`$CID` -- container ID.
|
`$CID` -- container ID.
|
||||||
|
|
||||||
For example:
|
For example:
|
||||||
```
|
```
|
||||||
$ frostfs-cli -r 192.168.130.72:8080 -w ./wallet.json object put --file cat.png --cid Dxhf4PNprrJHWWTG5RGLdfLkJiSQ3AQqit1MSnEPRkDZ --attributes img_type=cat,my_attr=cute
|
$ neofs-cli -r 192.168.130.72:8080 -w ./wallet.json object put --file cat.png --cid Dxhf4PNprrJHWWTG5RGLdfLkJiSQ3AQqit1MSnEPRkDZ --attributes img_type=cat,my_attr=cute
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
@ -259,13 +273,13 @@ $ frostfs-cli -r 192.168.130.72:8080 -w ./wallet.json object put --file cat.png
|
||||||
|
|
||||||
#### Requests
|
#### Requests
|
||||||
|
|
||||||
The following requests support GET/HEAD methods.
|
The following requests support GET/HEAD methods.
|
||||||
|
|
||||||
##### By IDs
|
##### By IDs
|
||||||
|
|
||||||
Basic downloading involves container ID and object ID and is done via GET
|
Basic downloading involves container ID and object ID and is done via GET
|
||||||
requests to `/get/$CID/$OID` path, where `$CID` is a container ID or its name if NNS is enabled,
|
requests to `/get/$CID/$OID` path, where `$CID` is a container ID or its name if NNS is enabled,
|
||||||
`$OID` is an object's (i.e. your file's) ID.
|
`$OID` is an object's (i.e. your file's) ID.
|
||||||
|
|
||||||
For example:
|
For example:
|
||||||
|
|
||||||
|
@ -286,14 +300,13 @@ can be used as well. The generic syntax for it looks like this:
|
||||||
|
|
||||||
```/get_by_attribute/$CID/$ATTRIBUTE_NAME/$ATTRIBUTE_VALUE```
|
```/get_by_attribute/$CID/$ATTRIBUTE_NAME/$ATTRIBUTE_VALUE```
|
||||||
|
|
||||||
where
|
where
|
||||||
`$CID` is a container ID or its name if NNS is enabled,
|
`$CID` is a container ID or its name if NNS is enabled,
|
||||||
`$ATTRIBUTE_NAME` is the name of the attribute we want to use,
|
`$ATTRIBUTE_NAME` is the name of the attribute we want to use,
|
||||||
`$ATTRIBUTE_VALUE` is the value of this attribute that the target object should have.
|
`$ATTRIBUTE_VALUE` is the value of this attribute that the target object should have.
|
||||||
|
|
||||||
**NB!** The attribute key and value should be url encoded, i.e., if you want to download an object with the attribute value
|
**NB!** The attribute key and value must be url encoded, i.e., if you want to download an object with the attribute value
|
||||||
`a cat`, the value in the request must be `a+cat`. In the same way with the attribute key. If you don't escape such values
|
`a cat`, the value in the request must be `a+cat`. In the same way with the attribute key.
|
||||||
everything can still work (for example you can use `d@ta` without encoding) but it's HIGHLY RECOMMENDED to encode all your attributes.
|
|
||||||
|
|
||||||
If multiple objects have specified attribute with specified value, then the
|
If multiple objects have specified attribute with specified value, then the
|
||||||
first one of them is returned (and you can't get others via this interface).
|
first one of them is returned (and you can't get others via this interface).
|
||||||
|
@ -315,7 +328,7 @@ Some other user-defined attributes:
|
||||||
$ wget http://localhost:8082/get_by_attribute/Dxhf4PNprrJHWWTG5RGLdfLkJiSQ3AQqit1MSnEPRkDZ/Ololo/100500
|
$ wget http://localhost:8082/get_by_attribute/Dxhf4PNprrJHWWTG5RGLdfLkJiSQ3AQqit1MSnEPRkDZ/Ololo/100500
|
||||||
```
|
```
|
||||||
|
|
||||||
Or when the attribute includes special symbols:
|
Or when the attribute includes special symbols:
|
||||||
```
|
```
|
||||||
$ wget http://localhost:8082/get_by_attribute/Dxhf4PNprrJHWWTG5RGLdfLkJiSQ3AQqit1MSnEPRkDZ/Olo%2Blo/100500 # means Olo+lo
|
$ wget http://localhost:8082/get_by_attribute/Dxhf4PNprrJHWWTG5RGLdfLkJiSQ3AQqit1MSnEPRkDZ/Olo%2Blo/100500 # means Olo+lo
|
||||||
```
|
```
|
||||||
|
@ -334,7 +347,7 @@ You can download some dir (files with the same prefix) in zip (it will be compre
|
||||||
$ wget http://localhost:8082/zip/Dxhf4PNprrJHWWTG5RGLdfLkJiSQ3AQqit1MSnEPRkDZ/common/prefix
|
$ wget http://localhost:8082/zip/Dxhf4PNprrJHWWTG5RGLdfLkJiSQ3AQqit1MSnEPRkDZ/common/prefix
|
||||||
```
|
```
|
||||||
|
|
||||||
**Note:** the objects must have a valid `FilePath` attribute (it should not contain trailing `/`),
|
**Note:** the objects must have a valid `FilePath` attribute (it should not contain trailing `/`),
|
||||||
otherwise they will not be in the zip archive. You can upload file with this attribute using `curl`:
|
otherwise they will not be in the zip archive. You can upload file with this attribute using `curl`:
|
||||||
|
|
||||||
```
|
```
|
||||||
|
@ -356,15 +369,10 @@ set of reply headers generated using the following rules:
|
||||||
* `x-container-id` contains container ID
|
* `x-container-id` contains container ID
|
||||||
* `x-object-id` contains object ID
|
* `x-object-id` contains object ID
|
||||||
* `x-owner-id` contains owner address
|
* `x-owner-id` contains owner address
|
||||||
* all the other FrostFS attributes are converted to `X-Attribute-*` headers (but only
|
* all the other NeoFS attributes are converted to `X-Attribute-*` headers (but only
|
||||||
if they can be safely represented in HTTP header), for example `FileName`
|
if they can be safely represented in HTTP header), for example `FileName`
|
||||||
attribute becomes `X-Attribute-FileName` header
|
attribute becomes `X-Attribute-FileName` header
|
||||||
|
|
||||||
##### Caching strategy
|
|
||||||
|
|
||||||
HTTP Gateway doesn't control caching (doesn't anything with the `Cache-Control` header). Caching strategy strictly
|
|
||||||
depends on application use case. So it should be carefully done by proxy server.
|
|
||||||
|
|
||||||
### Uploading
|
### Uploading
|
||||||
|
|
||||||
You can POST files to `/upload/$CID` path where `$CID` is a container ID or its name if NNS is enabled. The
|
You can POST files to `/upload/$CID` path where `$CID` is a container ID or its name if NNS is enabled. The
|
||||||
|
@ -393,12 +401,12 @@ You can also add some attributes to your file using the following rules:
|
||||||
"X-Attribute-" prefix stripped, that is if you add "X-Attribute-Ololo:
|
"X-Attribute-" prefix stripped, that is if you add "X-Attribute-Ololo:
|
||||||
100500" header to your request the resulting object will get "Ololo:
|
100500" header to your request the resulting object will get "Ololo:
|
||||||
100500" attribute
|
100500" attribute
|
||||||
* "X-Attribute-SYSTEM-*" headers are special
|
* "X-Attribute-NEOFS-*" headers are special
|
||||||
(`-SYSTEM-` part can also be `-system-` or`-System-` (and even legacy `-Neofs-` for some next releases)), they're used to set internal
|
(`-NEOFS-` part can also be `-neofs-` or`-Neofs-`), they're used to set internal
|
||||||
FrostFS attributes starting with `__SYSTEM__` prefix, for these attributes all
|
NeoFS attributes starting with `__NEOFS__` prefix, for these attributes all
|
||||||
dashes get converted to underscores and all letters are capitalized. For
|
dashes get converted to underscores and all letters are capitalized. For
|
||||||
example, you can use "X-Attribute-SYSTEM-Expiration-Epoch" header to set
|
example, you can use "X-Attribute-NEOFS-Expiration-Epoch" header to set
|
||||||
`__SYSTEM__EXPIRATION_EPOCH` attribute
|
`__NEOFS__EXPIRATION_EPOCH` attribute
|
||||||
* `FileName` attribute is set from multipart's `filename` if not set
|
* `FileName` attribute is set from multipart's `filename` if not set
|
||||||
explicitly via `X-Attribute-FileName` header
|
explicitly via `X-Attribute-FileName` header
|
||||||
* `Timestamp` attribute can be set using gateway local time if using
|
* `Timestamp` attribute can be set using gateway local time if using
|
||||||
|
@ -408,13 +416,13 @@ You can also add some attributes to your file using the following rules:
|
||||||
---
|
---
|
||||||
**NOTE**
|
**NOTE**
|
||||||
|
|
||||||
There are some reserved headers type of `X-Attribute-SYSTEM-*` (headers are arranged in descending order of priority):
|
There are some reserved headers type of `X-Attribute-NEOFS-*` (headers are arranged in descending order of priority):
|
||||||
1. `X-Attribute-System-Expiration-Epoch: 100`
|
1. `X-Attribute-Neofs-Expiration-Epoch: 100`
|
||||||
2. `X-Attribute-System-Expiration-Duration: 24h30m`
|
2. `X-Attribute-Neofs-Expiration-Duration: 24h30m`
|
||||||
3. `X-Attribute-System-Expiration-Timestamp: 1637574797`
|
3. `X-Attribute-Neofs-Expiration-Timestamp: 1637574797`
|
||||||
4. `X-Attribute-System-Expiration-RFC3339: 2021-11-22T09:55:49Z`
|
4. `X-Attribute-Neofs-Expiration-RFC3339: 2021-11-22T09:55:49Z`
|
||||||
|
|
||||||
which transforms to `X-Attribute-System-Expiration-Epoch`. So you can provide expiration any convenient way.
|
which transforms to `X-Attribute-Neofs-Expiration-Epoch`. So you can provide expiration any convenient way.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
@ -429,37 +437,149 @@ object ID, like this:
|
||||||
|
|
||||||
#### Authentication
|
#### Authentication
|
||||||
|
|
||||||
Read more about request authentication in [docs/authentication.md](./docs/authemtnication.md)
|
You can always upload files to public containers (open for anyone to put
|
||||||
|
objects into), but for restricted containers you need to explicitly allow PUT
|
||||||
|
operations for a request signed with your HTTP Gateway keys.
|
||||||
|
|
||||||
|
If your don't want to manage gateway's secret keys and adjust eACL rules when
|
||||||
|
gateway configuration changes (new gate, key rotation, etc) or you plan to use
|
||||||
|
public services, there is an option to let your application backend (or you) to
|
||||||
|
issue Bearer Tokens ans pass them from the client via gate down to NeoFS level
|
||||||
|
to grant access.
|
||||||
|
|
||||||
|
NeoFS Bearer Token basically is a container owner-signed ACL data (refer to NeoFS
|
||||||
|
documentation for more details). There are two options to pass them to gateway:
|
||||||
|
* "Authorization" header with "Bearer" type and base64-encoded token in
|
||||||
|
credentials field
|
||||||
|
* "Bearer" cookie with base64-encoded token contents
|
||||||
|
|
||||||
|
For example, you have a mobile application frontend with a backend part storing
|
||||||
|
data in NeoFS. When a user authorizes in the mobile app, the backend issues a NeoFS
|
||||||
|
Bearer token and provides it to the frontend. Then, the mobile app may generate
|
||||||
|
some data and upload it via any available NeoFS HTTP Gateway by adding
|
||||||
|
the corresponding header to the upload request. Accessing the ACL protected data
|
||||||
|
works the same way.
|
||||||
|
|
||||||
|
##### Example
|
||||||
|
In order to generate a bearer token, you need to know the container owner key and
|
||||||
|
the address of the sender who will do the request to NeoFS (in our case, it's a gateway wallet address).
|
||||||
|
|
||||||
|
Suppose we have:
|
||||||
|
* **KxDgvEKzgSBPPfuVfw67oPQBSjidEiqTHURKSDL1R7yGaGYAeYnr** (container owner key)
|
||||||
|
* **NhVtreTTCoqsMQV5Wp55fqnriiUCpEaKm3** (token owner address)
|
||||||
|
* **BJeErH9MWmf52VsR1mLWKkgF3pRm3FkubYxM7TZkBP4K** (container id)
|
||||||
|
|
||||||
|
Firstly, we need to encode the container id and the sender address to base64 (now it's base58).
|
||||||
|
So use **base58** and **base64** utils.
|
||||||
|
|
||||||
|
1. Encoding container id:
|
||||||
|
```
|
||||||
|
$ echo 'BJeErH9MWmf52VsR1mLWKkgF3pRm3FkubYxM7TZkBP4K' | base58 --decode | base64
|
||||||
|
# output: mRnZWzewzxjzIPa7Fqlfqdl3TM1KpJ0YnsXsEhafJJg=
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Encoding token owner id:
|
||||||
|
```
|
||||||
|
$ echo 'NhVtreTTCoqsMQV5Wp55fqnriiUCpEaKm3' | base58 --decode | base64
|
||||||
|
# output: NezFK4ujidF+X7bB88uzREQzRQeAvdj3Gg==
|
||||||
|
```
|
||||||
|
|
||||||
|
Now, we can form a Bearer token (10000 is liftetime expiration in epoch) and save it to **bearer.json**:
|
||||||
|
```
|
||||||
|
{
|
||||||
|
"body": {
|
||||||
|
"eaclTable": {
|
||||||
|
"version": {
|
||||||
|
"major": 0,
|
||||||
|
"minor": 0
|
||||||
|
},
|
||||||
|
"containerID": {
|
||||||
|
"value": "mRnZWzewzxjzIPa7Fqlfqdl3TM1KpJ0YnsXsEhafJJg="
|
||||||
|
},
|
||||||
|
"records": []
|
||||||
|
},
|
||||||
|
"ownerID": {
|
||||||
|
"value": "NezFK4ujidF+X7bB88uzREQzRQeAvdj3Gg=="
|
||||||
|
},
|
||||||
|
"lifetime": {
|
||||||
|
"exp": "10000",
|
||||||
|
"nbf": "0",
|
||||||
|
"iat": "0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"signature": null
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Next, sign it with the container owner key:
|
||||||
|
```
|
||||||
|
$ neofs-cli util sign bearer-token --from bearer.json --to signed.json -w ./wallet.json
|
||||||
|
```
|
||||||
|
Encoding to base64 to use via the header:
|
||||||
|
```
|
||||||
|
$ base64 -w 0 signed.json
|
||||||
|
# output: Ck4KKgoECAIQBhIiCiCZGdlbN7DPGPMg9rsWqV+p2XdMzUqknRiexewSFp8kmBIbChk17MUri6OJ0X5ftsHzy7NERDNFB4C92PcaGgMIkE4SZgohAxpsb7vfAso1F0X6hrm6WpRS14WsT3/Ct1SMoqRsT89KEkEEGxKi8GjKSf52YqhppgaOTQHbUsL3jn7SHLqS3ndAQ7NtAATnmRHleZw2V2xRRSRBQdjDC05KK83LhdSax72Fsw==
|
||||||
|
```
|
||||||
|
|
||||||
|
After that, the Bearer token can be used:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ curl -F 'file=@cat.jpeg;filename=cat.jpeg' -H "Authorization: Bearer Ck4KKgoECAIQBhIiCiCZGdlbN7DPGPMg9rsWqV+p2XdMzUqknRiexewSFp8kmBIbChk17MUri6OJ0X5ftsHzy7NERDNFB4C92PcaGgMIkE4SZgohAxpsb7vfAso1F0X6hrm6WpRS14WsT3/Ct1SMoqRsT89KEkEEGxKi8GjKSf52YqhppgaOTQHbUsL3jn7SHLqS3ndAQ7NtAATnmRHleZw2V2xRRSRBQdjDC05KK83LhdSax72Fsw==" \
|
||||||
|
http://localhost:8082/upload/BJeErH9MWmf52VsR1mLWKkgF3pRm3FkubYxM7TZkBP4K
|
||||||
|
# output:
|
||||||
|
# {
|
||||||
|
# "object_id": "DhfES9nVrFksxGDD2jQLunGADfrXExxNwqXbDafyBn9X",
|
||||||
|
# "container_id": "BJeErH9MWmf52VsR1mLWKkgF3pRm3FkubYxM7TZkBP4K"
|
||||||
|
# }
|
||||||
|
```
|
||||||
|
|
||||||
|
##### Note
|
||||||
|
For the token to work correctly, you need to create a container with a basic ACL that:
|
||||||
|
1. Allow PUT operation to others
|
||||||
|
2. Doesn't set "final" bit
|
||||||
|
|
||||||
|
For example:
|
||||||
|
```
|
||||||
|
$ neofs-cli -w ./wallet.json --basic-acl 0x0FFFCFFF -r 192.168.130.72:8080 container create --policy "REP 3" --await
|
||||||
|
```
|
||||||
|
|
||||||
|
To deny access to a container without a token, set the eACL rules:
|
||||||
|
```
|
||||||
|
$ neofs-cli -w ./wallet.json -r 192.168.130.72:8080 container set-eacl --table eacl.json --await --cid BJeErH9MWmf52VsR1mLWKkgF3pRm3FkubYxM7TZkBP4K
|
||||||
|
```
|
||||||
|
|
||||||
|
File **eacl.json**:
|
||||||
|
```
|
||||||
|
{
|
||||||
|
"version": {
|
||||||
|
"major": 0,
|
||||||
|
"minor": 0
|
||||||
|
},
|
||||||
|
"containerID": {
|
||||||
|
"value": "mRnZWzewzxjzIPa7Fqlfqdl3TM1KpJ0YnsXsEhafJJg="
|
||||||
|
},
|
||||||
|
"records": [
|
||||||
|
{
|
||||||
|
"operation": "PUT",
|
||||||
|
"action": "DENY",
|
||||||
|
"filters": [],
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"role": "OTHERS",
|
||||||
|
"keys": []
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### Metrics and Pprof
|
### Metrics and Pprof
|
||||||
|
|
||||||
If enabled, Prometheus metrics are available at `localhost:8084` endpoint
|
If enabled, Prometheus metrics are available at `localhost:8084` endpoint
|
||||||
and Pprof at `localhost:8083/debug/pprof` by default. Host and port can be configured.
|
and Pprof at `localhost:8083/debug/pprof` by default. Host and port can be configured.
|
||||||
See [configuration](./docs/gate-configuration.md).
|
See [configuration](./docs/gate-configuration.md).
|
||||||
|
|
||||||
## Credits
|
## Credits
|
||||||
|
|
||||||
Please see [CREDITS](CREDITS.md) for details.
|
Please see [CREDITS](CREDITS.md) for details.
|
||||||
|
|
||||||
## Fuzzing
|
|
||||||
|
|
||||||
To run fuzzing tests use the following command:
|
|
||||||
|
|
||||||
```shell
|
|
||||||
$ make fuzz
|
|
||||||
```
|
|
||||||
|
|
||||||
This command will install dependencies for the fuzzing process and run existing fuzzing tests.
|
|
||||||
|
|
||||||
You can also use the following arguments:
|
|
||||||
|
|
||||||
```
|
|
||||||
FUZZ_TIMEOUT - time to run each fuzzing test (default 30)
|
|
||||||
FUZZ_FUNCTIONS - fuzzing tests that will be started (default "all")
|
|
||||||
FUZZ_AUX - additional parameters for the fuzzer (for example, "-debug")
|
|
||||||
FUZZ_NGFUZZ_DIR - path to ngfuzz tool
|
|
||||||
````
|
|
||||||
|
|
||||||
## Credits
|
|
||||||
|
|
||||||
Please see [CREDITS](CREDITS.md) for details.
|
|
||||||
|
|
26
SECURITY.md
26
SECURITY.md
|
@ -1,26 +0,0 @@
|
||||||
# Security Policy
|
|
||||||
|
|
||||||
|
|
||||||
## How To Report a Vulnerability
|
|
||||||
|
|
||||||
If you think you have found a vulnerability in this repository, please report it to us through coordinated disclosure.
|
|
||||||
|
|
||||||
**Please do not report security vulnerabilities through public issues, discussions, or change requests.**
|
|
||||||
|
|
||||||
Instead, you can report it using one of the following ways:
|
|
||||||
|
|
||||||
* Contact the [TrueCloudLab Security Team](mailto:security@frostfs.info) via email
|
|
||||||
|
|
||||||
Please include as much of the information listed below as you can to help us better understand and resolve the issue:
|
|
||||||
|
|
||||||
* The type of issue (e.g., buffer overflow, or cross-site scripting)
|
|
||||||
* Affected version(s)
|
|
||||||
* Impact of the issue, including how an attacker might exploit the issue
|
|
||||||
* Step-by-step instructions to reproduce the issue
|
|
||||||
* The location of the affected source code (tag/branch/commit or direct URL)
|
|
||||||
* Full paths of source file(s) related to the manifestation of the issue
|
|
||||||
* Any special configuration required to reproduce the issue
|
|
||||||
* Any log files that are related to this issue (if possible)
|
|
||||||
* Proof-of-concept or exploit code (if possible)
|
|
||||||
|
|
||||||
This information will help us triage your report more quickly.
|
|
2
VERSION
2
VERSION
|
@ -1 +1 @@
|
||||||
v0.32.3
|
v0.25.1
|
||||||
|
|
545
app.go
Normal file
545
app.go
Normal file
|
@ -0,0 +1,545 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"strconv"
|
||||||
|
"sync"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"github.com/fasthttp/router"
|
||||||
|
"github.com/nspcc-dev/neo-go/cli/flags"
|
||||||
|
"github.com/nspcc-dev/neo-go/cli/input"
|
||||||
|
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||||
|
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||||
|
"github.com/nspcc-dev/neo-go/pkg/wallet"
|
||||||
|
"github.com/nspcc-dev/neofs-http-gw/downloader"
|
||||||
|
"github.com/nspcc-dev/neofs-http-gw/metrics"
|
||||||
|
"github.com/nspcc-dev/neofs-http-gw/resolver"
|
||||||
|
"github.com/nspcc-dev/neofs-http-gw/response"
|
||||||
|
"github.com/nspcc-dev/neofs-http-gw/uploader"
|
||||||
|
"github.com/nspcc-dev/neofs-http-gw/utils"
|
||||||
|
"github.com/nspcc-dev/neofs-sdk-go/pool"
|
||||||
|
"github.com/nspcc-dev/neofs-sdk-go/user"
|
||||||
|
"github.com/spf13/viper"
|
||||||
|
"github.com/valyala/fasthttp"
|
||||||
|
"go.uber.org/zap"
|
||||||
|
)
|
||||||
|
|
||||||
|
type (
|
||||||
|
app struct {
|
||||||
|
log *zap.Logger
|
||||||
|
logLevel zap.AtomicLevel
|
||||||
|
pool *pool.Pool
|
||||||
|
owner *user.ID
|
||||||
|
cfg *viper.Viper
|
||||||
|
webServer *fasthttp.Server
|
||||||
|
webDone chan struct{}
|
||||||
|
resolver *resolver.ContainerResolver
|
||||||
|
metrics *gateMetrics
|
||||||
|
services []*metrics.Service
|
||||||
|
settings *appSettings
|
||||||
|
}
|
||||||
|
|
||||||
|
appSettings struct {
|
||||||
|
Uploader *uploader.Settings
|
||||||
|
Downloader *downloader.Settings
|
||||||
|
TLSProvider *certProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
// App is an interface for the main gateway function.
|
||||||
|
App interface {
|
||||||
|
Wait()
|
||||||
|
Serve(context.Context)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Option is an application option.
|
||||||
|
Option func(a *app)
|
||||||
|
|
||||||
|
gateMetrics struct {
|
||||||
|
logger *zap.Logger
|
||||||
|
provider GateMetricsProvider
|
||||||
|
mu sync.RWMutex
|
||||||
|
enabled bool
|
||||||
|
}
|
||||||
|
|
||||||
|
GateMetricsProvider interface {
|
||||||
|
SetHealth(int32)
|
||||||
|
Unregister()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// WithLogger returns Option to set a specific logger.
|
||||||
|
func WithLogger(l *zap.Logger, lvl zap.AtomicLevel) Option {
|
||||||
|
return func(a *app) {
|
||||||
|
if l == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
a.log = l
|
||||||
|
a.logLevel = lvl
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithConfig returns Option to use specific Viper configuration.
|
||||||
|
func WithConfig(c *viper.Viper) Option {
|
||||||
|
return func(a *app) {
|
||||||
|
if c == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
a.cfg = c
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newApp(ctx context.Context, opt ...Option) App {
|
||||||
|
var (
|
||||||
|
key *ecdsa.PrivateKey
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
|
||||||
|
a := &app{
|
||||||
|
log: zap.L(),
|
||||||
|
cfg: viper.GetViper(),
|
||||||
|
webServer: new(fasthttp.Server),
|
||||||
|
webDone: make(chan struct{}),
|
||||||
|
}
|
||||||
|
for i := range opt {
|
||||||
|
opt[i](a)
|
||||||
|
}
|
||||||
|
|
||||||
|
// -- setup FastHTTP server --
|
||||||
|
a.webServer.Name = "neofs-http-gw"
|
||||||
|
a.webServer.ReadBufferSize = a.cfg.GetInt(cfgWebReadBufferSize)
|
||||||
|
a.webServer.WriteBufferSize = a.cfg.GetInt(cfgWebWriteBufferSize)
|
||||||
|
a.webServer.ReadTimeout = a.cfg.GetDuration(cfgWebReadTimeout)
|
||||||
|
a.webServer.WriteTimeout = a.cfg.GetDuration(cfgWebWriteTimeout)
|
||||||
|
a.webServer.DisableHeaderNamesNormalizing = true
|
||||||
|
a.webServer.NoDefaultServerHeader = true
|
||||||
|
a.webServer.NoDefaultContentType = true
|
||||||
|
a.webServer.MaxRequestBodySize = a.cfg.GetInt(cfgWebMaxRequestBodySize)
|
||||||
|
a.webServer.DisablePreParseMultipartForm = true
|
||||||
|
a.webServer.StreamRequestBody = a.cfg.GetBool(cfgWebStreamRequestBody)
|
||||||
|
// -- -- -- -- -- -- -- -- -- -- -- -- -- --
|
||||||
|
key, err = getNeoFSKey(a)
|
||||||
|
if err != nil {
|
||||||
|
a.log.Fatal("failed to get neofs credentials", zap.Error(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
var owner user.ID
|
||||||
|
user.IDFromKey(&owner, key.PublicKey)
|
||||||
|
a.owner = &owner
|
||||||
|
|
||||||
|
var prm pool.InitParameters
|
||||||
|
prm.SetKey(key)
|
||||||
|
prm.SetNodeDialTimeout(a.cfg.GetDuration(cfgConTimeout))
|
||||||
|
prm.SetNodeStreamTimeout(a.cfg.GetDuration(cfgStreamTimeout))
|
||||||
|
prm.SetHealthcheckTimeout(a.cfg.GetDuration(cfgReqTimeout))
|
||||||
|
prm.SetClientRebalanceInterval(a.cfg.GetDuration(cfgRebalance))
|
||||||
|
prm.SetErrorThreshold(a.cfg.GetUint32(cfgPoolErrorThreshold))
|
||||||
|
|
||||||
|
for i := 0; ; i++ {
|
||||||
|
address := a.cfg.GetString(cfgPeers + "." + strconv.Itoa(i) + ".address")
|
||||||
|
weight := a.cfg.GetFloat64(cfgPeers + "." + strconv.Itoa(i) + ".weight")
|
||||||
|
priority := a.cfg.GetInt(cfgPeers + "." + strconv.Itoa(i) + ".priority")
|
||||||
|
if address == "" {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if weight <= 0 { // unspecified or wrong
|
||||||
|
weight = 1
|
||||||
|
}
|
||||||
|
if priority <= 0 { // unspecified or wrong
|
||||||
|
priority = 1
|
||||||
|
}
|
||||||
|
prm.AddNode(pool.NewNodeParam(priority, address, weight))
|
||||||
|
a.log.Info("add connection", zap.String("address", address),
|
||||||
|
zap.Float64("weight", weight), zap.Int("priority", priority))
|
||||||
|
}
|
||||||
|
|
||||||
|
a.pool, err = pool.NewPool(prm)
|
||||||
|
if err != nil {
|
||||||
|
a.log.Fatal("failed to create connection pool", zap.Error(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
err = a.pool.Dial(ctx)
|
||||||
|
if err != nil {
|
||||||
|
a.log.Fatal("failed to dial pool", zap.Error(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
a.initAppSettings()
|
||||||
|
a.initResolver()
|
||||||
|
a.initMetrics()
|
||||||
|
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) initAppSettings() {
|
||||||
|
a.settings = &appSettings{
|
||||||
|
Uploader: &uploader.Settings{},
|
||||||
|
Downloader: &downloader.Settings{},
|
||||||
|
TLSProvider: &certProvider{Enabled: a.cfg.IsSet(cfgTLSCertificate) || a.cfg.IsSet(cfgTLSKey)},
|
||||||
|
}
|
||||||
|
|
||||||
|
a.updateSettings()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) initResolver() {
|
||||||
|
var err error
|
||||||
|
a.resolver, err = resolver.NewContainerResolver(a.getResolverConfig())
|
||||||
|
if err != nil {
|
||||||
|
a.log.Fatal("failed to create resolver", zap.Error(err))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) getResolverConfig() ([]string, *resolver.Config) {
|
||||||
|
resolveCfg := &resolver.Config{
|
||||||
|
NeoFS: resolver.NewNeoFSResolver(a.pool),
|
||||||
|
RPCAddress: a.cfg.GetString(cfgRPCEndpoint),
|
||||||
|
}
|
||||||
|
|
||||||
|
order := a.cfg.GetStringSlice(cfgResolveOrder)
|
||||||
|
if resolveCfg.RPCAddress == "" {
|
||||||
|
order = remove(order, resolver.NNSResolver)
|
||||||
|
a.log.Warn(fmt.Sprintf("resolver '%s' won't be used since '%s' isn't provided", resolver.NNSResolver, cfgRPCEndpoint))
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(order) == 0 {
|
||||||
|
a.log.Info("container resolver will be disabled because of resolvers 'resolver_order' is empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
return order, resolveCfg
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) initMetrics() {
|
||||||
|
gateMetricsProvider := metrics.NewGateMetrics(a.pool)
|
||||||
|
a.metrics = newGateMetrics(a.log, gateMetricsProvider, a.cfg.GetBool(cfgPrometheusEnabled))
|
||||||
|
}
|
||||||
|
|
||||||
|
func newGateMetrics(logger *zap.Logger, provider GateMetricsProvider, enabled bool) *gateMetrics {
|
||||||
|
if !enabled {
|
||||||
|
logger.Warn("metrics are disabled")
|
||||||
|
}
|
||||||
|
return &gateMetrics{
|
||||||
|
logger: logger,
|
||||||
|
provider: provider,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *gateMetrics) SetEnabled(enabled bool) {
|
||||||
|
if !enabled {
|
||||||
|
m.logger.Warn("metrics are disabled")
|
||||||
|
}
|
||||||
|
|
||||||
|
m.mu.Lock()
|
||||||
|
m.enabled = enabled
|
||||||
|
m.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *gateMetrics) SetHealth(status int32) {
|
||||||
|
m.mu.RLock()
|
||||||
|
if !m.enabled {
|
||||||
|
m.mu.RUnlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
m.mu.RUnlock()
|
||||||
|
|
||||||
|
m.provider.SetHealth(status)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *gateMetrics) Shutdown() {
|
||||||
|
m.mu.Lock()
|
||||||
|
if m.enabled {
|
||||||
|
m.provider.SetHealth(0)
|
||||||
|
m.enabled = false
|
||||||
|
}
|
||||||
|
m.provider.Unregister()
|
||||||
|
m.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func remove(list []string, element string) []string {
|
||||||
|
for i, item := range list {
|
||||||
|
if item == element {
|
||||||
|
return append(list[:i], list[i+1:]...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return list
|
||||||
|
}
|
||||||
|
|
||||||
|
func getNeoFSKey(a *app) (*ecdsa.PrivateKey, error) {
|
||||||
|
walletPath := a.cfg.GetString(cfgWalletPath)
|
||||||
|
|
||||||
|
if len(walletPath) == 0 {
|
||||||
|
a.log.Info("no wallet path specified, creating ephemeral key automatically for this run")
|
||||||
|
key, err := keys.NewPrivateKey()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &key.PrivateKey, nil
|
||||||
|
}
|
||||||
|
w, err := wallet.NewWalletFromFile(walletPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var password *string
|
||||||
|
if a.cfg.IsSet(cfgWalletPassphrase) {
|
||||||
|
pwd := a.cfg.GetString(cfgWalletPassphrase)
|
||||||
|
password = &pwd
|
||||||
|
}
|
||||||
|
|
||||||
|
address := a.cfg.GetString(cfgWalletAddress)
|
||||||
|
|
||||||
|
return getKeyFromWallet(w, address, password)
|
||||||
|
}
|
||||||
|
|
||||||
|
func getKeyFromWallet(w *wallet.Wallet, addrStr string, password *string) (*ecdsa.PrivateKey, error) {
|
||||||
|
var addr util.Uint160
|
||||||
|
var err error
|
||||||
|
|
||||||
|
if addrStr == "" {
|
||||||
|
addr = w.GetChangeAddress()
|
||||||
|
} else {
|
||||||
|
addr, err = flags.ParseAddress(addrStr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid address")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
acc := w.GetAccount(addr)
|
||||||
|
if acc == nil {
|
||||||
|
return nil, fmt.Errorf("couldn't find wallet account for %s", addrStr)
|
||||||
|
}
|
||||||
|
|
||||||
|
if password == nil {
|
||||||
|
pwd, err := input.ReadPassword("Enter password > ")
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("couldn't read password")
|
||||||
|
}
|
||||||
|
password = &pwd
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := acc.Decrypt(*password, w.Scrypt); err != nil {
|
||||||
|
return nil, fmt.Errorf("couldn't decrypt account: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &acc.PrivateKey().PrivateKey, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) Wait() {
|
||||||
|
a.log.Info("starting application", zap.String("app_name", "neofs-http-gw"), zap.String("version", Version))
|
||||||
|
|
||||||
|
a.setHealthStatus()
|
||||||
|
|
||||||
|
<-a.webDone // wait for web-server to be stopped
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) setHealthStatus() {
|
||||||
|
a.metrics.SetHealth(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
type certProvider struct {
|
||||||
|
Enabled bool
|
||||||
|
|
||||||
|
mu sync.RWMutex
|
||||||
|
certPath string
|
||||||
|
keyPath string
|
||||||
|
cert *tls.Certificate
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *certProvider) GetCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||||
|
if !p.Enabled {
|
||||||
|
return nil, errors.New("cert provider: disabled")
|
||||||
|
}
|
||||||
|
|
||||||
|
p.mu.RLock()
|
||||||
|
defer p.mu.RUnlock()
|
||||||
|
return p.cert, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *certProvider) UpdateCert(certPath, keyPath string) error {
|
||||||
|
if !p.Enabled {
|
||||||
|
return fmt.Errorf("tls disabled")
|
||||||
|
}
|
||||||
|
|
||||||
|
cert, err := tls.LoadX509KeyPair(certPath, keyPath)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("cannot load TLS key pair from certFile '%s' and keyFile '%s': %w", certPath, keyPath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
p.mu.Lock()
|
||||||
|
p.certPath = certPath
|
||||||
|
p.keyPath = keyPath
|
||||||
|
p.cert = &cert
|
||||||
|
p.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) Serve(ctx context.Context) {
|
||||||
|
uploadRoutes := uploader.New(ctx, a.AppParams(), a.settings.Uploader)
|
||||||
|
downloadRoutes := downloader.New(ctx, a.AppParams(), a.settings.Downloader)
|
||||||
|
|
||||||
|
// Configure router.
|
||||||
|
a.configureRouter(uploadRoutes, downloadRoutes)
|
||||||
|
|
||||||
|
a.startServices()
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
var err error
|
||||||
|
defer func() {
|
||||||
|
if err != nil {
|
||||||
|
a.log.Fatal("could not start server", zap.Error(err))
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
bind := a.cfg.GetString(cfgListenAddress)
|
||||||
|
|
||||||
|
if a.settings.TLSProvider.Enabled {
|
||||||
|
if err = a.settings.TLSProvider.UpdateCert(a.cfg.GetString(cfgTLSCertificate), a.cfg.GetString(cfgTLSKey)); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var lnConf net.ListenConfig
|
||||||
|
var ln net.Listener
|
||||||
|
if ln, err = lnConf.Listen(ctx, "tcp4", bind); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
lnTLS := tls.NewListener(ln, &tls.Config{
|
||||||
|
GetCertificate: a.settings.TLSProvider.GetCertificate,
|
||||||
|
})
|
||||||
|
|
||||||
|
a.log.Info("running web server (TLS-enabled)", zap.String("address", bind))
|
||||||
|
err = a.webServer.Serve(lnTLS)
|
||||||
|
} else {
|
||||||
|
a.log.Info("running web server", zap.String("address", bind))
|
||||||
|
err = a.webServer.ListenAndServe(bind)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
sigs := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(sigs, syscall.SIGHUP)
|
||||||
|
|
||||||
|
LOOP:
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
break LOOP
|
||||||
|
case <-sigs:
|
||||||
|
a.configReload()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
a.log.Info("shutting down web server", zap.Error(a.webServer.Shutdown()))
|
||||||
|
|
||||||
|
a.metrics.Shutdown()
|
||||||
|
a.stopServices()
|
||||||
|
|
||||||
|
close(a.webDone)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) configReload() {
|
||||||
|
a.log.Info("SIGHUP config reload started")
|
||||||
|
if !a.cfg.IsSet(cmdConfig) {
|
||||||
|
a.log.Warn("failed to reload config because it's missed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := readConfig(a.cfg); err != nil {
|
||||||
|
a.log.Warn("failed to reload config", zap.Error(err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if lvl, err := getLogLevel(a.cfg); err != nil {
|
||||||
|
a.log.Warn("log level won't be updated", zap.Error(err))
|
||||||
|
} else {
|
||||||
|
a.logLevel.SetLevel(lvl)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := a.resolver.UpdateResolvers(a.getResolverConfig()); err != nil {
|
||||||
|
a.log.Warn("failed to update resolvers", zap.Error(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
a.stopServices()
|
||||||
|
a.startServices()
|
||||||
|
|
||||||
|
a.updateSettings()
|
||||||
|
|
||||||
|
a.metrics.SetEnabled(a.cfg.GetBool(cfgPrometheusEnabled))
|
||||||
|
a.setHealthStatus()
|
||||||
|
|
||||||
|
a.log.Info("SIGHUP config reload completed")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) updateSettings() {
|
||||||
|
a.settings.Uploader.SetDefaultTimestamp(a.cfg.GetBool(cfgUploaderHeaderEnableDefaultTimestamp))
|
||||||
|
a.settings.Downloader.SetZipCompression(a.cfg.GetBool(cfgZipCompression))
|
||||||
|
|
||||||
|
if err := a.settings.TLSProvider.UpdateCert(a.cfg.GetString(cfgTLSCertificate), a.cfg.GetString(cfgTLSKey)); err != nil {
|
||||||
|
a.log.Warn("failed to reload TLS certs", zap.Error(err))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) startServices() {
|
||||||
|
pprofConfig := metrics.Config{Enabled: a.cfg.GetBool(cfgPprofEnabled), Address: a.cfg.GetString(cfgPprofAddress)}
|
||||||
|
pprofService := metrics.NewPprofService(a.log, pprofConfig)
|
||||||
|
a.services = append(a.services, pprofService)
|
||||||
|
go pprofService.Start()
|
||||||
|
|
||||||
|
prometheusConfig := metrics.Config{Enabled: a.cfg.GetBool(cfgPrometheusEnabled), Address: a.cfg.GetString(cfgPrometheusAddress)}
|
||||||
|
prometheusService := metrics.NewPrometheusService(a.log, prometheusConfig)
|
||||||
|
a.services = append(a.services, prometheusService)
|
||||||
|
go prometheusService.Start()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) stopServices() {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), defaultShutdownTimeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
for _, svc := range a.services {
|
||||||
|
svc.ShutDown(ctx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) configureRouter(uploadRoutes *uploader.Uploader, downloadRoutes *downloader.Downloader) {
|
||||||
|
r := router.New()
|
||||||
|
r.RedirectTrailingSlash = true
|
||||||
|
r.NotFound = func(r *fasthttp.RequestCtx) {
|
||||||
|
response.Error(r, "Not found", fasthttp.StatusNotFound)
|
||||||
|
}
|
||||||
|
r.MethodNotAllowed = func(r *fasthttp.RequestCtx) {
|
||||||
|
response.Error(r, "Method Not Allowed", fasthttp.StatusMethodNotAllowed)
|
||||||
|
}
|
||||||
|
r.POST("/upload/{cid}", a.logger(uploadRoutes.Upload))
|
||||||
|
a.log.Info("added path /upload/{cid}")
|
||||||
|
r.GET("/get/{cid}/{oid}", a.logger(downloadRoutes.DownloadByAddress))
|
||||||
|
r.HEAD("/get/{cid}/{oid}", a.logger(downloadRoutes.HeadByAddress))
|
||||||
|
a.log.Info("added path /get/{cid}/{oid}")
|
||||||
|
r.GET("/get_by_attribute/{cid}/{attr_key}/{attr_val:*}", a.logger(downloadRoutes.DownloadByAttribute))
|
||||||
|
r.HEAD("/get_by_attribute/{cid}/{attr_key}/{attr_val:*}", a.logger(downloadRoutes.HeadByAttribute))
|
||||||
|
a.log.Info("added path /get_by_attribute/{cid}/{attr_key}/{attr_val:*}")
|
||||||
|
r.GET("/zip/{cid}/{prefix:*}", a.logger(downloadRoutes.DownloadZipped))
|
||||||
|
a.log.Info("added path /zip/{cid}/{prefix}")
|
||||||
|
|
||||||
|
a.webServer.Handler = r.Handler
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) logger(h fasthttp.RequestHandler) fasthttp.RequestHandler {
|
||||||
|
return func(ctx *fasthttp.RequestCtx) {
|
||||||
|
a.log.Info("request", zap.String("remote", ctx.RemoteAddr().String()),
|
||||||
|
zap.ByteString("method", ctx.Method()),
|
||||||
|
zap.ByteString("path", ctx.Path()),
|
||||||
|
zap.ByteString("query", ctx.QueryArgs().QueryString()),
|
||||||
|
zap.Uint64("id", ctx.ID()))
|
||||||
|
h(ctx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) AppParams() *utils.AppParams {
|
||||||
|
return &utils.AppParams{
|
||||||
|
Logger: a.log,
|
||||||
|
Pool: a.pool,
|
||||||
|
Owner: a.owner,
|
||||||
|
Resolver: a.resolver,
|
||||||
|
}
|
||||||
|
}
|
1137
cmd/http-gw/app.go
1137
cmd/http-gw/app.go
File diff suppressed because it is too large
Load diff
|
@ -1,174 +0,0 @@
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/logs"
|
|
||||||
"git.frostfs.info/TrueCloudLab/zapjournald"
|
|
||||||
"github.com/spf13/viper"
|
|
||||||
"github.com/ssgreg/journald"
|
|
||||||
"go.uber.org/zap"
|
|
||||||
"go.uber.org/zap/zapcore"
|
|
||||||
)
|
|
||||||
|
|
||||||
func getLogLevel(v *viper.Viper) (zapcore.Level, error) {
|
|
||||||
var lvl zapcore.Level
|
|
||||||
lvlStr := v.GetString(cfgLoggerLevel)
|
|
||||||
err := lvl.UnmarshalText([]byte(lvlStr))
|
|
||||||
if err != nil {
|
|
||||||
return lvl, fmt.Errorf("incorrect logger level configuration %s (%v), "+
|
|
||||||
"value should be one of %v", lvlStr, err, [...]zapcore.Level{
|
|
||||||
zapcore.DebugLevel,
|
|
||||||
zapcore.InfoLevel,
|
|
||||||
zapcore.WarnLevel,
|
|
||||||
zapcore.ErrorLevel,
|
|
||||||
zapcore.DPanicLevel,
|
|
||||||
zapcore.PanicLevel,
|
|
||||||
zapcore.FatalLevel,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return lvl, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ zapcore.Core = (*zapCoreTagFilterWrapper)(nil)
|
|
||||||
|
|
||||||
type zapCoreTagFilterWrapper struct {
|
|
||||||
core zapcore.Core
|
|
||||||
settings TagFilterSettings
|
|
||||||
extra []zap.Field
|
|
||||||
}
|
|
||||||
|
|
||||||
type TagFilterSettings interface {
|
|
||||||
LevelEnabled(tag string, lvl zapcore.Level) bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *zapCoreTagFilterWrapper) Enabled(level zapcore.Level) bool {
|
|
||||||
return c.core.Enabled(level)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *zapCoreTagFilterWrapper) With(fields []zapcore.Field) zapcore.Core {
|
|
||||||
return &zapCoreTagFilterWrapper{
|
|
||||||
core: c.core.With(fields),
|
|
||||||
settings: c.settings,
|
|
||||||
extra: append(c.extra, fields...),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *zapCoreTagFilterWrapper) Check(entry zapcore.Entry, checked *zapcore.CheckedEntry) *zapcore.CheckedEntry {
|
|
||||||
if c.core.Enabled(entry.Level) {
|
|
||||||
return checked.AddCore(entry, c)
|
|
||||||
}
|
|
||||||
return checked
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *zapCoreTagFilterWrapper) Write(entry zapcore.Entry, fields []zapcore.Field) error {
|
|
||||||
if c.shouldSkip(entry, fields) || c.shouldSkip(entry, c.extra) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.core.Write(entry, fields)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *zapCoreTagFilterWrapper) shouldSkip(entry zapcore.Entry, fields []zap.Field) bool {
|
|
||||||
for _, field := range fields {
|
|
||||||
if field.Key == logs.TagFieldName && field.Type == zapcore.StringType {
|
|
||||||
if !c.settings.LevelEnabled(field.String, entry.Level) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *zapCoreTagFilterWrapper) Sync() error {
|
|
||||||
return c.core.Sync()
|
|
||||||
}
|
|
||||||
|
|
||||||
func applyZapCoreMiddlewares(core zapcore.Core, v *viper.Viper, loggerSettings LoggerAppSettings, tagSetting TagFilterSettings) zapcore.Core {
|
|
||||||
core = &zapCoreTagFilterWrapper{
|
|
||||||
core: core,
|
|
||||||
settings: tagSetting,
|
|
||||||
}
|
|
||||||
|
|
||||||
if v.GetBool(cfgLoggerSamplingEnabled) {
|
|
||||||
core = zapcore.NewSamplerWithOptions(core,
|
|
||||||
v.GetDuration(cfgLoggerSamplingInterval),
|
|
||||||
v.GetInt(cfgLoggerSamplingInitial),
|
|
||||||
v.GetInt(cfgLoggerSamplingThereafter),
|
|
||||||
zapcore.SamplerHook(func(_ zapcore.Entry, dec zapcore.SamplingDecision) {
|
|
||||||
if dec&zapcore.LogDropped > 0 {
|
|
||||||
loggerSettings.DroppedLogsInc()
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
return core
|
|
||||||
}
|
|
||||||
|
|
||||||
func newLogEncoder() zapcore.Encoder {
|
|
||||||
c := zap.NewProductionEncoderConfig()
|
|
||||||
c.EncodeTime = zapcore.ISO8601TimeEncoder
|
|
||||||
|
|
||||||
return zapcore.NewConsoleEncoder(c)
|
|
||||||
}
|
|
||||||
|
|
||||||
// newStdoutLogger constructs a zap.Logger instance for current application.
|
|
||||||
// Panics on failure.
|
|
||||||
//
|
|
||||||
// Logger is built from zap's production logging configuration with:
|
|
||||||
// - parameterized level (debug by default)
|
|
||||||
// - console encoding
|
|
||||||
// - ISO8601 time encoding
|
|
||||||
//
|
|
||||||
// Logger records a stack trace for all messages at or above fatal level.
|
|
||||||
//
|
|
||||||
// See also zapcore.Level, zap.NewProductionConfig, zap.AddStacktrace.
|
|
||||||
func newStdoutLogger(v *viper.Viper, lvl zap.AtomicLevel, loggerSettings LoggerAppSettings, tagSetting TagFilterSettings) *Logger {
|
|
||||||
stdout := zapcore.AddSync(os.Stderr)
|
|
||||||
|
|
||||||
consoleOutCore := zapcore.NewCore(newLogEncoder(), stdout, lvl)
|
|
||||||
consoleOutCore = applyZapCoreMiddlewares(consoleOutCore, v, loggerSettings, tagSetting)
|
|
||||||
|
|
||||||
return &Logger{
|
|
||||||
logger: zap.New(consoleOutCore, zap.AddStacktrace(zap.NewAtomicLevelAt(zap.FatalLevel))),
|
|
||||||
lvl: lvl,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func newJournaldLogger(v *viper.Viper, lvl zap.AtomicLevel, loggerSettings LoggerAppSettings, tagSetting TagFilterSettings) *Logger {
|
|
||||||
encoder := zapjournald.NewPartialEncoder(newLogEncoder(), zapjournald.SyslogFields)
|
|
||||||
|
|
||||||
core := zapjournald.NewCore(lvl, encoder, &journald.Journal{}, zapjournald.SyslogFields)
|
|
||||||
coreWithContext := core.With([]zapcore.Field{
|
|
||||||
zapjournald.SyslogFacility(zapjournald.LogDaemon),
|
|
||||||
zapjournald.SyslogIdentifier(),
|
|
||||||
zapjournald.SyslogPid(),
|
|
||||||
})
|
|
||||||
|
|
||||||
coreWithContext = applyZapCoreMiddlewares(coreWithContext, v, loggerSettings, tagSetting)
|
|
||||||
|
|
||||||
return &Logger{
|
|
||||||
logger: zap.New(coreWithContext, zap.AddStacktrace(zap.NewAtomicLevelAt(zap.FatalLevel))),
|
|
||||||
lvl: lvl,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type LoggerAppSettings interface {
|
|
||||||
DroppedLogsInc()
|
|
||||||
}
|
|
||||||
|
|
||||||
func pickLogger(v *viper.Viper, lvl zap.AtomicLevel, loggerSettings LoggerAppSettings, tagSettings TagFilterSettings) *Logger {
|
|
||||||
dest := v.GetString(cfgLoggerDestination)
|
|
||||||
|
|
||||||
switch dest {
|
|
||||||
case destinationStdout:
|
|
||||||
return newStdoutLogger(v, lvl, loggerSettings, tagSettings)
|
|
||||||
case destinationJournald:
|
|
||||||
return newJournaldLogger(v, lvl, loggerSettings, tagSettings)
|
|
||||||
default:
|
|
||||||
panic(fmt.Sprintf("wrong destination for logger: %s", dest))
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,124 +0,0 @@
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/tls"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
type (
|
|
||||||
ServerInfo struct {
|
|
||||||
Address string
|
|
||||||
TLS ServerTLSInfo
|
|
||||||
}
|
|
||||||
|
|
||||||
ServerTLSInfo struct {
|
|
||||||
Enabled bool
|
|
||||||
CertFile string
|
|
||||||
KeyFile string
|
|
||||||
}
|
|
||||||
|
|
||||||
Server interface {
|
|
||||||
Address() string
|
|
||||||
Listener() net.Listener
|
|
||||||
UpdateCert(certFile, keyFile string) error
|
|
||||||
}
|
|
||||||
|
|
||||||
server struct {
|
|
||||||
address string
|
|
||||||
listener net.Listener
|
|
||||||
tlsProvider *certProvider
|
|
||||||
}
|
|
||||||
|
|
||||||
certProvider struct {
|
|
||||||
Enabled bool
|
|
||||||
|
|
||||||
mu sync.RWMutex
|
|
||||||
certPath string
|
|
||||||
keyPath string
|
|
||||||
cert *tls.Certificate
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
func (s *server) Address() string {
|
|
||||||
return s.address
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *server) Listener() net.Listener {
|
|
||||||
return s.listener
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *server) UpdateCert(certFile, keyFile string) error {
|
|
||||||
return s.tlsProvider.UpdateCert(certFile, keyFile)
|
|
||||||
}
|
|
||||||
|
|
||||||
func newServer(ctx context.Context, serverInfo ServerInfo) (*server, error) {
|
|
||||||
var lic net.ListenConfig
|
|
||||||
ln, err := lic.Listen(ctx, "tcp", serverInfo.Address)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("could not prepare listener: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
tlsProvider := &certProvider{
|
|
||||||
Enabled: serverInfo.TLS.Enabled,
|
|
||||||
}
|
|
||||||
|
|
||||||
if serverInfo.TLS.Enabled {
|
|
||||||
if err = tlsProvider.UpdateCert(serverInfo.TLS.CertFile, serverInfo.TLS.KeyFile); err != nil {
|
|
||||||
lnErr := ln.Close()
|
|
||||||
return nil, fmt.Errorf("failed to update cert (listener close: %v): %w", lnErr, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
ln = tls.NewListener(ln, &tls.Config{
|
|
||||||
GetCertificate: tlsProvider.GetCertificate,
|
|
||||||
NextProtos: []string{"h2"}, // required to enable HTTP/2 requests in `http.Serve`
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return &server{
|
|
||||||
address: serverInfo.Address,
|
|
||||||
listener: ln,
|
|
||||||
tlsProvider: tlsProvider,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *certProvider) GetCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error) {
|
|
||||||
if !p.Enabled {
|
|
||||||
return nil, errors.New("cert provider: disabled")
|
|
||||||
}
|
|
||||||
|
|
||||||
p.mu.RLock()
|
|
||||||
defer p.mu.RUnlock()
|
|
||||||
return p.cert, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *certProvider) UpdateCert(certPath, keyPath string) error {
|
|
||||||
if !p.Enabled {
|
|
||||||
return fmt.Errorf("tls disabled")
|
|
||||||
}
|
|
||||||
|
|
||||||
cert, err := tls.LoadX509KeyPair(certPath, keyPath)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("cannot load TLS key pair from certFile '%s' and keyFile '%s': %w", certPath, keyPath, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
p.mu.Lock()
|
|
||||||
p.certPath = certPath
|
|
||||||
p.keyPath = keyPath
|
|
||||||
p.cert = &cert
|
|
||||||
p.mu.Unlock()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *certProvider) FilePaths() (string, string) {
|
|
||||||
if !p.Enabled {
|
|
||||||
return "", ""
|
|
||||||
}
|
|
||||||
|
|
||||||
p.mu.RLock()
|
|
||||||
defer p.mu.RUnlock()
|
|
||||||
return p.certPath, p.keyPath
|
|
||||||
}
|
|
|
@ -1,119 +0,0 @@
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/rand"
|
|
||||||
"crypto/rsa"
|
|
||||||
"crypto/tls"
|
|
||||||
"crypto/x509"
|
|
||||||
"crypto/x509/pkix"
|
|
||||||
"encoding/pem"
|
|
||||||
"fmt"
|
|
||||||
"math/big"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"path"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
"golang.org/x/net/http2"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
expHeaderKey = "Foo"
|
|
||||||
expHeaderValue = "Bar"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestHTTP2TLS(t *testing.T) {
|
|
||||||
ctx := context.Background()
|
|
||||||
certPath, keyPath := prepareTestCerts(t)
|
|
||||||
|
|
||||||
srv := &http.Server{
|
|
||||||
Handler: http.HandlerFunc(testHandler),
|
|
||||||
}
|
|
||||||
|
|
||||||
tlsListener, err := newServer(ctx, ServerInfo{
|
|
||||||
Address: ":0",
|
|
||||||
TLS: ServerTLSInfo{
|
|
||||||
Enabled: true,
|
|
||||||
CertFile: certPath,
|
|
||||||
KeyFile: keyPath,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
require.NoError(t, err)
|
|
||||||
port := tlsListener.Listener().Addr().(*net.TCPAddr).Port
|
|
||||||
addr := fmt.Sprintf("https://localhost:%d", port)
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
_ = srv.Serve(tlsListener.Listener())
|
|
||||||
}()
|
|
||||||
|
|
||||||
// Server is running, now send HTTP/2 request
|
|
||||||
|
|
||||||
tlsClientConfig := &tls.Config{
|
|
||||||
InsecureSkipVerify: true,
|
|
||||||
}
|
|
||||||
|
|
||||||
cliHTTP1 := http.Client{Transport: &http.Transport{TLSClientConfig: tlsClientConfig}}
|
|
||||||
cliHTTP2 := http.Client{Transport: &http2.Transport{TLSClientConfig: tlsClientConfig}}
|
|
||||||
|
|
||||||
req, err := http.NewRequest("GET", addr, nil)
|
|
||||||
require.NoError(t, err)
|
|
||||||
req.Header[expHeaderKey] = []string{expHeaderValue}
|
|
||||||
|
|
||||||
resp, err := cliHTTP1.Do(req)
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Equal(t, http.StatusOK, resp.StatusCode)
|
|
||||||
|
|
||||||
resp, err = cliHTTP2.Do(req)
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Equal(t, http.StatusOK, resp.StatusCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
func testHandler(resp http.ResponseWriter, req *http.Request) {
|
|
||||||
hdr, ok := req.Header[expHeaderKey]
|
|
||||||
if !ok || len(hdr) != 1 || hdr[0] != expHeaderValue {
|
|
||||||
resp.WriteHeader(http.StatusBadRequest)
|
|
||||||
} else {
|
|
||||||
resp.WriteHeader(http.StatusOK)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func prepareTestCerts(t *testing.T) (certPath, keyPath string) {
|
|
||||||
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
template := x509.Certificate{
|
|
||||||
SerialNumber: big.NewInt(1),
|
|
||||||
Subject: pkix.Name{CommonName: "localhost"},
|
|
||||||
NotBefore: time.Now(),
|
|
||||||
NotAfter: time.Now().Add(time.Hour * 24 * 365),
|
|
||||||
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
|
|
||||||
BasicConstraintsValid: true,
|
|
||||||
}
|
|
||||||
|
|
||||||
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
dir := t.TempDir()
|
|
||||||
certPath = path.Join(dir, "cert.pem")
|
|
||||||
keyPath = path.Join(dir, "key.pem")
|
|
||||||
|
|
||||||
certFile, err := os.Create(certPath)
|
|
||||||
require.NoError(t, err)
|
|
||||||
defer certFile.Close()
|
|
||||||
|
|
||||||
keyFile, err := os.Create(keyPath)
|
|
||||||
require.NoError(t, err)
|
|
||||||
defer keyFile.Close()
|
|
||||||
|
|
||||||
err = pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
err = pem.Encode(keyFile, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)})
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
return certPath, keyPath
|
|
||||||
}
|
|
|
@ -1,853 +0,0 @@
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/hex"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"math"
|
|
||||||
"os"
|
|
||||||
"path"
|
|
||||||
"runtime"
|
|
||||||
"sort"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/cache"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/logs"
|
|
||||||
internalnet "git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/net"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/service/frostfs"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/resolver"
|
|
||||||
grpctracing "git.frostfs.info/TrueCloudLab/frostfs-observability/tracing/grpc"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/pool"
|
|
||||||
treepool "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/pool/tree"
|
|
||||||
"github.com/spf13/pflag"
|
|
||||||
"github.com/spf13/viper"
|
|
||||||
"github.com/valyala/fasthttp"
|
|
||||||
"go.uber.org/zap"
|
|
||||||
"go.uber.org/zap/zapcore"
|
|
||||||
"google.golang.org/grpc"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
destinationStdout = "stdout"
|
|
||||||
destinationJournald = "journald"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
defaultRebalanceTimer = 60 * time.Second
|
|
||||||
defaultRequestTimeout = 15 * time.Second
|
|
||||||
defaultConnectTimeout = 10 * time.Second
|
|
||||||
defaultStreamTimeout = 10 * time.Second
|
|
||||||
|
|
||||||
defaultLoggerSamplerInterval = 1 * time.Second
|
|
||||||
|
|
||||||
defaultShutdownTimeout = 15 * time.Second
|
|
||||||
|
|
||||||
defaultPoolErrorThreshold uint32 = 100
|
|
||||||
|
|
||||||
defaultSoftMemoryLimit = math.MaxInt64
|
|
||||||
|
|
||||||
defaultBufferMaxSizeForPut = 1024 * 1024 // 1mb
|
|
||||||
|
|
||||||
defaultNamespaceHeader = "X-Frostfs-Namespace"
|
|
||||||
|
|
||||||
defaultReconnectInterval = time.Minute
|
|
||||||
|
|
||||||
defaultCORSMaxAge = 600 // seconds
|
|
||||||
|
|
||||||
defaultMultinetFallbackDelay = 300 * time.Millisecond
|
|
||||||
|
|
||||||
cfgServer = "server"
|
|
||||||
cfgTLSEnabled = "tls.enabled"
|
|
||||||
cfgTLSCertFile = "tls.cert_file"
|
|
||||||
cfgTLSKeyFile = "tls.key_file"
|
|
||||||
|
|
||||||
cfgReconnectInterval = "reconnect_interval"
|
|
||||||
|
|
||||||
cfgIndexPageEnabled = "index_page.enabled"
|
|
||||||
cfgIndexPageTemplatePath = "index_page.template_path"
|
|
||||||
|
|
||||||
cfgWorkerPoolSize = "worker_pool_size"
|
|
||||||
|
|
||||||
// Web.
|
|
||||||
cfgWebReadBufferSize = "web.read_buffer_size"
|
|
||||||
cfgWebWriteBufferSize = "web.write_buffer_size"
|
|
||||||
cfgWebReadTimeout = "web.read_timeout"
|
|
||||||
cfgWebWriteTimeout = "web.write_timeout"
|
|
||||||
cfgWebStreamRequestBody = "web.stream_request_body"
|
|
||||||
cfgWebMaxRequestBodySize = "web.max_request_body_size"
|
|
||||||
|
|
||||||
// Metrics / Profiler.
|
|
||||||
cfgPrometheusEnabled = "prometheus.enabled"
|
|
||||||
cfgPrometheusAddress = "prometheus.address"
|
|
||||||
cfgPprofEnabled = "pprof.enabled"
|
|
||||||
cfgPprofAddress = "pprof.address"
|
|
||||||
|
|
||||||
// Tracing ...
|
|
||||||
cfgTracingEnabled = "tracing.enabled"
|
|
||||||
cfgTracingExporter = "tracing.exporter"
|
|
||||||
cfgTracingEndpoint = "tracing.endpoint"
|
|
||||||
cfgTracingTrustedCa = "tracing.trusted_ca"
|
|
||||||
cfgTracingAttributes = "tracing.attributes"
|
|
||||||
|
|
||||||
// Pool config.
|
|
||||||
cfgConTimeout = "connect_timeout"
|
|
||||||
cfgStreamTimeout = "stream_timeout"
|
|
||||||
cfgReqTimeout = "request_timeout"
|
|
||||||
cfgRebalance = "rebalance_timer"
|
|
||||||
cfgPoolErrorThreshold = "pool_error_threshold"
|
|
||||||
|
|
||||||
// Logger.
|
|
||||||
cfgLoggerLevel = "logger.level"
|
|
||||||
cfgLoggerDestination = "logger.destination"
|
|
||||||
|
|
||||||
cfgLoggerSamplingEnabled = "logger.sampling.enabled"
|
|
||||||
cfgLoggerSamplingInitial = "logger.sampling.initial"
|
|
||||||
cfgLoggerSamplingThereafter = "logger.sampling.thereafter"
|
|
||||||
cfgLoggerSamplingInterval = "logger.sampling.interval"
|
|
||||||
|
|
||||||
cfgLoggerTags = "logger.tags"
|
|
||||||
cfgLoggerTagsPrefixTmpl = cfgLoggerTags + ".%d."
|
|
||||||
cfgLoggerTagsNameTmpl = cfgLoggerTagsPrefixTmpl + "name"
|
|
||||||
cfgLoggerTagsLevelTmpl = cfgLoggerTagsPrefixTmpl + "level"
|
|
||||||
|
|
||||||
// Wallet.
|
|
||||||
cfgWalletPassphrase = "wallet.passphrase"
|
|
||||||
cfgWalletPath = "wallet.path"
|
|
||||||
cfgWalletAddress = "wallet.address"
|
|
||||||
|
|
||||||
// Uploader Header.
|
|
||||||
cfgUploaderHeaderEnableDefaultTimestamp = "upload_header.use_default_timestamp"
|
|
||||||
|
|
||||||
// Peers.
|
|
||||||
cfgPeers = "peers"
|
|
||||||
|
|
||||||
// NeoGo.
|
|
||||||
cfgRPCEndpoint = "rpc_endpoint"
|
|
||||||
|
|
||||||
// Resolving.
|
|
||||||
cfgResolveOrder = "resolve_order"
|
|
||||||
|
|
||||||
// Zip compression.
|
|
||||||
//
|
|
||||||
// Deprecated: Use cfgArchiveCompression instead.
|
|
||||||
cfgZipCompression = "zip.compression"
|
|
||||||
|
|
||||||
// Archive compression.
|
|
||||||
cfgArchiveCompression = "archive.compression"
|
|
||||||
|
|
||||||
// Runtime.
|
|
||||||
cfgSoftMemoryLimit = "runtime.soft_memory_limit"
|
|
||||||
|
|
||||||
// Enabling client side object preparing for PUT operations.
|
|
||||||
cfgClientCut = "frostfs.client_cut"
|
|
||||||
// Sets max buffer size for read payload in put operations.
|
|
||||||
cfgBufferMaxSizeForPut = "frostfs.buffer_max_size_for_put"
|
|
||||||
// Configuration of parameters of requests to FrostFS.
|
|
||||||
// Sets max attempt to make successful tree request.
|
|
||||||
cfgTreePoolMaxAttempts = "frostfs.tree_pool_max_attempts"
|
|
||||||
|
|
||||||
// Caching.
|
|
||||||
cfgBucketsCacheLifetime = "cache.buckets.lifetime"
|
|
||||||
cfgBucketsCacheSize = "cache.buckets.size"
|
|
||||||
cfgNetmapCacheLifetime = "cache.netmap.lifetime"
|
|
||||||
|
|
||||||
// Bucket resolving options.
|
|
||||||
cfgResolveNamespaceHeader = "resolve_bucket.namespace_header"
|
|
||||||
cfgResolveDefaultNamespaces = "resolve_bucket.default_namespaces"
|
|
||||||
|
|
||||||
// CORS.
|
|
||||||
cfgCORSAllowOrigin = "cors.allow_origin"
|
|
||||||
cfgCORSAllowMethods = "cors.allow_methods"
|
|
||||||
cfgCORSAllowHeaders = "cors.allow_headers"
|
|
||||||
cfgCORSExposeHeaders = "cors.expose_headers"
|
|
||||||
cfgCORSAllowCredentials = "cors.allow_credentials"
|
|
||||||
cfgCORSMaxAge = "cors.max_age"
|
|
||||||
|
|
||||||
// Multinet.
|
|
||||||
cfgMultinetEnabled = "multinet.enabled"
|
|
||||||
cfgMultinetBalancer = "multinet.balancer"
|
|
||||||
cfgMultinetRestrict = "multinet.restrict"
|
|
||||||
cfgMultinetFallbackDelay = "multinet.fallback_delay"
|
|
||||||
cfgMultinetSubnets = "multinet.subnets"
|
|
||||||
|
|
||||||
// Feature.
|
|
||||||
cfgFeaturesEnableFilepathFallback = "features.enable_filepath_fallback"
|
|
||||||
cfgFeaturesTreePoolNetmapSupport = "features.tree_pool_netmap_support"
|
|
||||||
|
|
||||||
// Command line args.
|
|
||||||
cmdHelp = "help"
|
|
||||||
cmdVersion = "version"
|
|
||||||
cmdPprof = "pprof"
|
|
||||||
cmdMetrics = "metrics"
|
|
||||||
cmdWallet = "wallet"
|
|
||||||
cmdAddress = "address"
|
|
||||||
cmdConfig = "config"
|
|
||||||
cmdConfigDir = "config-dir"
|
|
||||||
cmdListenAddress = "listen_address"
|
|
||||||
)
|
|
||||||
|
|
||||||
var ignore = map[string]struct{}{
|
|
||||||
cfgPeers: {},
|
|
||||||
cmdHelp: {},
|
|
||||||
cmdVersion: {},
|
|
||||||
}
|
|
||||||
|
|
||||||
var defaultTags = []string{logs.TagApp, logs.TagDatapath, logs.TagExternalStorage, logs.TagExternalStorageTree}
|
|
||||||
|
|
||||||
type Logger struct {
|
|
||||||
logger *zap.Logger
|
|
||||||
lvl zap.AtomicLevel
|
|
||||||
}
|
|
||||||
|
|
||||||
type appCfg struct {
|
|
||||||
flags *pflag.FlagSet
|
|
||||||
|
|
||||||
mu sync.RWMutex
|
|
||||||
settings *viper.Viper
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *appCfg) reload() error {
|
|
||||||
old := a.config()
|
|
||||||
|
|
||||||
v, err := newViper(a.flags)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if old.IsSet(cmdConfig) {
|
|
||||||
v.Set(cmdConfig, old.Get(cmdConfig))
|
|
||||||
}
|
|
||||||
if old.IsSet(cmdConfigDir) {
|
|
||||||
v.Set(cmdConfigDir, old.Get(cmdConfigDir))
|
|
||||||
}
|
|
||||||
|
|
||||||
if err = readInConfig(v); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
a.setConfig(v)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *appCfg) config() *viper.Viper {
|
|
||||||
a.mu.RLock()
|
|
||||||
defer a.mu.RUnlock()
|
|
||||||
|
|
||||||
return a.settings
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *appCfg) setConfig(v *viper.Viper) {
|
|
||||||
a.mu.Lock()
|
|
||||||
a.settings = v
|
|
||||||
a.mu.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
func newViper(flags *pflag.FlagSet) (*viper.Viper, error) {
|
|
||||||
v := viper.New()
|
|
||||||
|
|
||||||
v.AutomaticEnv()
|
|
||||||
v.SetEnvPrefix(Prefix)
|
|
||||||
v.AllowEmptyEnv(true)
|
|
||||||
v.SetConfigType("yaml")
|
|
||||||
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
|
||||||
|
|
||||||
if err := bindFlags(v, flags); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
setDefaults(v, flags)
|
|
||||||
|
|
||||||
if v.IsSet(cfgServer+".0."+cfgTLSKeyFile) && v.IsSet(cfgServer+".0."+cfgTLSCertFile) {
|
|
||||||
v.Set(cfgServer+".0."+cfgTLSEnabled, true)
|
|
||||||
}
|
|
||||||
|
|
||||||
return v, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func settings() *appCfg {
|
|
||||||
// flags setup:
|
|
||||||
flags := pflag.NewFlagSet("commandline", pflag.ExitOnError)
|
|
||||||
flags.SetOutput(os.Stdout)
|
|
||||||
flags.SortFlags = false
|
|
||||||
|
|
||||||
flags.Bool(cmdPprof, false, "enable pprof")
|
|
||||||
flags.Bool(cmdMetrics, false, "enable prometheus")
|
|
||||||
|
|
||||||
help := flags.BoolP(cmdHelp, "h", false, "show help")
|
|
||||||
version := flags.BoolP(cmdVersion, "v", false, "show version")
|
|
||||||
|
|
||||||
flags.StringP(cmdWallet, "w", "", `path to the wallet`)
|
|
||||||
flags.String(cmdAddress, "", `address of wallet account`)
|
|
||||||
flags.StringArray(cmdConfig, nil, "config paths")
|
|
||||||
flags.String(cmdConfigDir, "", "config dir path")
|
|
||||||
flags.Duration(cfgConTimeout, defaultConnectTimeout, "gRPC connect timeout")
|
|
||||||
flags.Duration(cfgStreamTimeout, defaultStreamTimeout, "gRPC individual message timeout")
|
|
||||||
flags.Duration(cfgReqTimeout, defaultRequestTimeout, "gRPC request timeout")
|
|
||||||
flags.Duration(cfgRebalance, defaultRebalanceTimer, "gRPC connection rebalance timer")
|
|
||||||
|
|
||||||
flags.String(cmdListenAddress, "0.0.0.0:8080", "addresses to listen")
|
|
||||||
flags.String(cfgTLSCertFile, "", "TLS certificate path")
|
|
||||||
flags.String(cfgTLSKeyFile, "", "TLS key path")
|
|
||||||
flags.StringArrayP(cfgPeers, "p", nil, "FrostFS nodes")
|
|
||||||
|
|
||||||
flags.StringSlice(cfgResolveOrder, []string{resolver.NNSResolver, resolver.DNSResolver}, "set container name resolve order")
|
|
||||||
|
|
||||||
if err := flags.Parse(os.Args); err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
v, err := newViper(flags)
|
|
||||||
if err != nil {
|
|
||||||
panic(fmt.Errorf("bind flags: %w", err))
|
|
||||||
}
|
|
||||||
|
|
||||||
switch {
|
|
||||||
case help != nil && *help:
|
|
||||||
fmt.Printf("FrostFS HTTP Gateway %s\n", Version)
|
|
||||||
flags.PrintDefaults()
|
|
||||||
|
|
||||||
fmt.Println()
|
|
||||||
fmt.Println("Default environments:")
|
|
||||||
fmt.Println()
|
|
||||||
keys := v.AllKeys()
|
|
||||||
sort.Strings(keys)
|
|
||||||
|
|
||||||
for i := range keys {
|
|
||||||
if _, ok := ignore[keys[i]]; ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
defaultValue := v.GetString(keys[i])
|
|
||||||
if len(defaultValue) == 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
k := strings.Replace(keys[i], ".", "_", -1)
|
|
||||||
fmt.Printf("%s_%s = %s\n", Prefix, strings.ToUpper(k), defaultValue)
|
|
||||||
}
|
|
||||||
|
|
||||||
fmt.Println()
|
|
||||||
fmt.Println("Peers preset:")
|
|
||||||
fmt.Println()
|
|
||||||
|
|
||||||
fmt.Printf("%s_%s_[N]_ADDRESS = string\n", Prefix, strings.ToUpper(cfgPeers))
|
|
||||||
fmt.Printf("%s_%s_[N]_WEIGHT = float\n", Prefix, strings.ToUpper(cfgPeers))
|
|
||||||
|
|
||||||
os.Exit(0)
|
|
||||||
case version != nil && *version:
|
|
||||||
fmt.Printf("FrostFS HTTP Gateway\nVersion: %s\nGoVersion: %s\n", Version, runtime.Version())
|
|
||||||
os.Exit(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := readInConfig(v); err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &appCfg{
|
|
||||||
flags: flags,
|
|
||||||
settings: v,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func setDefaults(v *viper.Viper, flags *pflag.FlagSet) {
|
|
||||||
// set defaults:
|
|
||||||
|
|
||||||
// logger:
|
|
||||||
v.SetDefault(cfgLoggerLevel, "debug")
|
|
||||||
v.SetDefault(cfgLoggerDestination, "stdout")
|
|
||||||
v.SetDefault(cfgLoggerSamplingEnabled, false)
|
|
||||||
v.SetDefault(cfgLoggerSamplingThereafter, 100)
|
|
||||||
v.SetDefault(cfgLoggerSamplingInitial, 100)
|
|
||||||
v.SetDefault(cfgLoggerSamplingInterval, defaultLoggerSamplerInterval)
|
|
||||||
|
|
||||||
// pool:
|
|
||||||
v.SetDefault(cfgPoolErrorThreshold, defaultPoolErrorThreshold)
|
|
||||||
|
|
||||||
// frostfs:
|
|
||||||
v.SetDefault(cfgBufferMaxSizeForPut, defaultBufferMaxSizeForPut)
|
|
||||||
|
|
||||||
// web-server:
|
|
||||||
v.SetDefault(cfgWebReadBufferSize, 4096)
|
|
||||||
v.SetDefault(cfgWebWriteBufferSize, 4096)
|
|
||||||
v.SetDefault(cfgWebReadTimeout, time.Minute*10)
|
|
||||||
v.SetDefault(cfgWebWriteTimeout, time.Minute*5)
|
|
||||||
v.SetDefault(cfgWebStreamRequestBody, true)
|
|
||||||
v.SetDefault(cfgWebMaxRequestBodySize, fasthttp.DefaultMaxRequestBodySize)
|
|
||||||
|
|
||||||
v.SetDefault(cfgWorkerPoolSize, 1000)
|
|
||||||
// upload header
|
|
||||||
v.SetDefault(cfgUploaderHeaderEnableDefaultTimestamp, false)
|
|
||||||
|
|
||||||
// metrics
|
|
||||||
v.SetDefault(cfgPprofAddress, "localhost:8083")
|
|
||||||
v.SetDefault(cfgPrometheusAddress, "localhost:8084")
|
|
||||||
|
|
||||||
// resolve bucket
|
|
||||||
v.SetDefault(cfgResolveNamespaceHeader, defaultNamespaceHeader)
|
|
||||||
v.SetDefault(cfgResolveDefaultNamespaces, []string{"", "root"})
|
|
||||||
|
|
||||||
// multinet
|
|
||||||
v.SetDefault(cfgMultinetFallbackDelay, defaultMultinetFallbackDelay)
|
|
||||||
|
|
||||||
if resolveMethods, err := flags.GetStringSlice(cfgResolveOrder); err == nil {
|
|
||||||
v.SetDefault(cfgResolveOrder, resolveMethods)
|
|
||||||
}
|
|
||||||
|
|
||||||
if peers, err := flags.GetStringArray(cfgPeers); err == nil {
|
|
||||||
for i := range peers {
|
|
||||||
v.SetDefault(cfgPeers+"."+strconv.Itoa(i)+".address", peers[i])
|
|
||||||
v.SetDefault(cfgPeers+"."+strconv.Itoa(i)+".weight", 1)
|
|
||||||
v.SetDefault(cfgPeers+"."+strconv.Itoa(i)+".priority", 1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func bindFlags(v *viper.Viper, flags *pflag.FlagSet) error {
|
|
||||||
// Binding flags
|
|
||||||
if err := v.BindPFlag(cfgPprofEnabled, flags.Lookup(cmdPprof)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := v.BindPFlag(cfgPrometheusEnabled, flags.Lookup(cmdMetrics)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := v.BindPFlag(cfgWalletPath, flags.Lookup(cmdWallet)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := v.BindPFlag(cfgWalletAddress, flags.Lookup(cmdAddress)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := v.BindPFlags(flags); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := v.BindPFlag(cfgServer+".0.address", flags.Lookup(cmdListenAddress)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := v.BindPFlag(cfgServer+".0."+cfgTLSKeyFile, flags.Lookup(cfgTLSKeyFile)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := v.BindPFlag(cfgServer+".0."+cfgTLSCertFile, flags.Lookup(cfgTLSCertFile)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func readInConfig(v *viper.Viper) error {
|
|
||||||
if v.IsSet(cmdConfig) {
|
|
||||||
if err := readConfig(v); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if v.IsSet(cmdConfigDir) {
|
|
||||||
if err := readConfigDir(v); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func readConfigDir(v *viper.Viper) error {
|
|
||||||
cfgSubConfigDir := v.GetString(cmdConfigDir)
|
|
||||||
entries, err := os.ReadDir(cfgSubConfigDir)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, entry := range entries {
|
|
||||||
if entry.IsDir() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
ext := path.Ext(entry.Name())
|
|
||||||
if ext != ".yaml" && ext != ".yml" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if err = mergeConfig(v, path.Join(cfgSubConfigDir, entry.Name())); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func readConfig(v *viper.Viper) error {
|
|
||||||
for _, fileName := range v.GetStringSlice(cmdConfig) {
|
|
||||||
if err := mergeConfig(v, fileName); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func mergeConfig(v *viper.Viper, fileName string) error {
|
|
||||||
cfgFile, err := os.Open(fileName)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
defer func() {
|
|
||||||
if errClose := cfgFile.Close(); errClose != nil {
|
|
||||||
panic(errClose)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return v.MergeConfig(cfgFile)
|
|
||||||
}
|
|
||||||
|
|
||||||
func fetchLogTagsConfig(v *viper.Viper, defaultLvl zapcore.Level) (map[string]zapcore.Level, error) {
|
|
||||||
res := make(map[string]zapcore.Level)
|
|
||||||
|
|
||||||
for i := 0; ; i++ {
|
|
||||||
name := v.GetString(fmt.Sprintf(cfgLoggerTagsNameTmpl, i))
|
|
||||||
if name == "" {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
lvl := defaultLvl
|
|
||||||
level := v.GetString(fmt.Sprintf(cfgLoggerTagsLevelTmpl, i))
|
|
||||||
if level != "" {
|
|
||||||
if err := lvl.Set(level); err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to parse log tags config, unknown level: '%s'", level)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
res[name] = lvl
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(res) == 0 && !v.IsSet(cfgLoggerTags) {
|
|
||||||
for _, tag := range defaultTags {
|
|
||||||
res[tag] = defaultLvl
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return res, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func fetchReconnectInterval(cfg *viper.Viper) time.Duration {
|
|
||||||
reconnect := cfg.GetDuration(cfgReconnectInterval)
|
|
||||||
if reconnect <= 0 {
|
|
||||||
reconnect = defaultReconnectInterval
|
|
||||||
}
|
|
||||||
|
|
||||||
return reconnect
|
|
||||||
}
|
|
||||||
|
|
||||||
func fetchIndexPageTemplate(v *viper.Viper, l *zap.Logger) (string, bool) {
|
|
||||||
if !v.GetBool(cfgIndexPageEnabled) {
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
reader, err := os.Open(v.GetString(cfgIndexPageTemplatePath))
|
|
||||||
if err != nil {
|
|
||||||
l.Warn(logs.FailedToReadIndexPageTemplate, zap.Error(err), logs.TagField(logs.TagApp))
|
|
||||||
return "", true
|
|
||||||
}
|
|
||||||
|
|
||||||
tmpl, err := io.ReadAll(reader)
|
|
||||||
if err != nil {
|
|
||||||
l.Warn(logs.FailedToReadIndexPageTemplate, zap.Error(err), logs.TagField(logs.TagApp))
|
|
||||||
return "", true
|
|
||||||
}
|
|
||||||
|
|
||||||
l.Info(logs.SetCustomIndexPageTemplate, logs.TagField(logs.TagApp))
|
|
||||||
return string(tmpl), true
|
|
||||||
}
|
|
||||||
|
|
||||||
func fetchDefaultNamespaces(v *viper.Viper) []string {
|
|
||||||
namespaces := v.GetStringSlice(cfgResolveDefaultNamespaces)
|
|
||||||
|
|
||||||
for i := range namespaces { // to be set namespaces in env variable as `HTTP_GW_RESOLVE_BUCKET_DEFAULT_NAMESPACES="" "root"`
|
|
||||||
namespaces[i] = strings.Trim(namespaces[i], "\"")
|
|
||||||
}
|
|
||||||
|
|
||||||
return namespaces
|
|
||||||
}
|
|
||||||
|
|
||||||
func fetchCORSMaxAge(v *viper.Viper) int {
|
|
||||||
maxAge := v.GetInt(cfgCORSMaxAge)
|
|
||||||
if maxAge <= 0 {
|
|
||||||
maxAge = defaultCORSMaxAge
|
|
||||||
}
|
|
||||||
|
|
||||||
return maxAge
|
|
||||||
}
|
|
||||||
|
|
||||||
func fetchServers(v *viper.Viper, log *zap.Logger) []ServerInfo {
|
|
||||||
var servers []ServerInfo
|
|
||||||
seen := make(map[string]struct{})
|
|
||||||
|
|
||||||
for i := 0; ; i++ {
|
|
||||||
key := cfgServer + "." + strconv.Itoa(i) + "."
|
|
||||||
|
|
||||||
var serverInfo ServerInfo
|
|
||||||
serverInfo.Address = v.GetString(key + "address")
|
|
||||||
serverInfo.TLS.Enabled = v.GetBool(key + cfgTLSEnabled)
|
|
||||||
serverInfo.TLS.KeyFile = v.GetString(key + cfgTLSKeyFile)
|
|
||||||
serverInfo.TLS.CertFile = v.GetString(key + cfgTLSCertFile)
|
|
||||||
|
|
||||||
if serverInfo.Address == "" {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, ok := seen[serverInfo.Address]; ok {
|
|
||||||
log.Warn(logs.WarnDuplicateAddress, zap.String("address", serverInfo.Address), logs.TagField(logs.TagApp))
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
seen[serverInfo.Address] = struct{}{}
|
|
||||||
servers = append(servers, serverInfo)
|
|
||||||
}
|
|
||||||
|
|
||||||
return servers
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *app) initPools(ctx context.Context) {
|
|
||||||
key, err := getFrostFSKey(a.config(), a.log)
|
|
||||||
if err != nil {
|
|
||||||
a.log.Fatal(logs.CouldNotLoadFrostFSPrivateKey, zap.Error(err), logs.TagField(logs.TagApp))
|
|
||||||
}
|
|
||||||
|
|
||||||
var prm pool.InitParameters
|
|
||||||
var prmTree treepool.InitParameters
|
|
||||||
|
|
||||||
prm.SetKey(&key.PrivateKey)
|
|
||||||
prmTree.SetKey(key)
|
|
||||||
a.log.Info(logs.UsingCredentials, zap.String("FrostFS", hex.EncodeToString(key.PublicKey().Bytes())),
|
|
||||||
logs.TagField(logs.TagApp))
|
|
||||||
|
|
||||||
for _, peer := range fetchPeers(a.log, a.config()) {
|
|
||||||
prm.AddNode(peer)
|
|
||||||
prmTree.AddNode(peer)
|
|
||||||
}
|
|
||||||
|
|
||||||
connTimeout := a.config().GetDuration(cfgConTimeout)
|
|
||||||
if connTimeout <= 0 {
|
|
||||||
connTimeout = defaultConnectTimeout
|
|
||||||
}
|
|
||||||
prm.SetNodeDialTimeout(connTimeout)
|
|
||||||
prmTree.SetNodeDialTimeout(connTimeout)
|
|
||||||
|
|
||||||
streamTimeout := a.config().GetDuration(cfgStreamTimeout)
|
|
||||||
if streamTimeout <= 0 {
|
|
||||||
streamTimeout = defaultStreamTimeout
|
|
||||||
}
|
|
||||||
prm.SetNodeStreamTimeout(streamTimeout)
|
|
||||||
prmTree.SetNodeStreamTimeout(streamTimeout)
|
|
||||||
|
|
||||||
healthCheckTimeout := a.config().GetDuration(cfgReqTimeout)
|
|
||||||
if healthCheckTimeout <= 0 {
|
|
||||||
healthCheckTimeout = defaultRequestTimeout
|
|
||||||
}
|
|
||||||
prm.SetHealthcheckTimeout(healthCheckTimeout)
|
|
||||||
prmTree.SetHealthcheckTimeout(healthCheckTimeout)
|
|
||||||
|
|
||||||
rebalanceInterval := a.config().GetDuration(cfgRebalance)
|
|
||||||
if rebalanceInterval <= 0 {
|
|
||||||
rebalanceInterval = defaultRebalanceTimer
|
|
||||||
}
|
|
||||||
prm.SetClientRebalanceInterval(rebalanceInterval)
|
|
||||||
prmTree.SetClientRebalanceInterval(rebalanceInterval)
|
|
||||||
|
|
||||||
errorThreshold := a.config().GetUint32(cfgPoolErrorThreshold)
|
|
||||||
if errorThreshold <= 0 {
|
|
||||||
errorThreshold = defaultPoolErrorThreshold
|
|
||||||
}
|
|
||||||
prm.SetErrorThreshold(errorThreshold)
|
|
||||||
prm.SetLogger(a.log)
|
|
||||||
prmTree.SetLogger(a.log)
|
|
||||||
|
|
||||||
prmTree.SetMaxRequestAttempts(a.config().GetInt(cfgTreePoolMaxAttempts))
|
|
||||||
|
|
||||||
interceptors := []grpc.DialOption{
|
|
||||||
grpc.WithUnaryInterceptor(grpctracing.NewUnaryClientInteceptor()),
|
|
||||||
grpc.WithStreamInterceptor(grpctracing.NewStreamClientInterceptor()),
|
|
||||||
grpc.WithContextDialer(a.settings.dialerSource.GrpcContextDialer()),
|
|
||||||
}
|
|
||||||
prm.SetGRPCDialOptions(interceptors...)
|
|
||||||
prmTree.SetGRPCDialOptions(interceptors...)
|
|
||||||
|
|
||||||
p, err := pool.NewPool(prm)
|
|
||||||
if err != nil {
|
|
||||||
a.log.Fatal(logs.FailedToCreateConnectionPool, zap.Error(err), logs.TagField(logs.TagApp))
|
|
||||||
}
|
|
||||||
|
|
||||||
if err = p.Dial(ctx); err != nil {
|
|
||||||
a.log.Fatal(logs.FailedToDialConnectionPool, zap.Error(err), logs.TagField(logs.TagApp))
|
|
||||||
}
|
|
||||||
|
|
||||||
if a.config().GetBool(cfgFeaturesTreePoolNetmapSupport) {
|
|
||||||
prmTree.SetNetMapInfoSource(frostfs.NewSource(frostfs.NewFrostFS(p), cache.NewNetmapCache(getNetmapCacheOptions(a.config(), a.log)), a.bucketCache, a.log))
|
|
||||||
}
|
|
||||||
|
|
||||||
treePool, err := treepool.NewPool(prmTree)
|
|
||||||
if err != nil {
|
|
||||||
a.log.Fatal(logs.FailedToCreateTreePool, zap.Error(err), logs.TagField(logs.TagApp))
|
|
||||||
}
|
|
||||||
if err = treePool.Dial(ctx); err != nil {
|
|
||||||
a.log.Fatal(logs.FailedToDialTreePool, zap.Error(err), logs.TagField(logs.TagApp))
|
|
||||||
}
|
|
||||||
|
|
||||||
a.pool = p
|
|
||||||
a.treePool = treePool
|
|
||||||
a.key = key
|
|
||||||
}
|
|
||||||
|
|
||||||
func fetchPeers(l *zap.Logger, v *viper.Viper) []pool.NodeParam {
|
|
||||||
var nodes []pool.NodeParam
|
|
||||||
for i := 0; ; i++ {
|
|
||||||
key := cfgPeers + "." + strconv.Itoa(i) + "."
|
|
||||||
address := v.GetString(key + "address")
|
|
||||||
weight := v.GetFloat64(key + "weight")
|
|
||||||
priority := v.GetInt(key + "priority")
|
|
||||||
|
|
||||||
if address == "" {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if weight <= 0 { // unspecified or wrong
|
|
||||||
weight = 1
|
|
||||||
}
|
|
||||||
if priority <= 0 { // unspecified or wrong
|
|
||||||
priority = 1
|
|
||||||
}
|
|
||||||
|
|
||||||
nodes = append(nodes, pool.NewNodeParam(priority, address, weight))
|
|
||||||
|
|
||||||
l.Info(logs.AddedStoragePeer,
|
|
||||||
zap.Int("priority", priority),
|
|
||||||
zap.String("address", address),
|
|
||||||
zap.Float64("weight", weight),
|
|
||||||
logs.TagField(logs.TagApp))
|
|
||||||
}
|
|
||||||
|
|
||||||
return nodes
|
|
||||||
}
|
|
||||||
|
|
||||||
func fetchSoftMemoryLimit(cfg *viper.Viper) int64 {
|
|
||||||
softMemoryLimit := cfg.GetSizeInBytes(cfgSoftMemoryLimit)
|
|
||||||
if softMemoryLimit <= 0 {
|
|
||||||
softMemoryLimit = defaultSoftMemoryLimit
|
|
||||||
}
|
|
||||||
|
|
||||||
return int64(softMemoryLimit)
|
|
||||||
}
|
|
||||||
|
|
||||||
func getBucketCacheOptions(v *viper.Viper, l *zap.Logger) *cache.Config {
|
|
||||||
cacheCfg := cache.DefaultBucketConfig(l)
|
|
||||||
|
|
||||||
cacheCfg.Lifetime = fetchCacheLifetime(v, l, cfgBucketsCacheLifetime, cacheCfg.Lifetime)
|
|
||||||
cacheCfg.Size = fetchCacheSize(v, l, cfgBucketsCacheSize, cacheCfg.Size)
|
|
||||||
|
|
||||||
return cacheCfg
|
|
||||||
}
|
|
||||||
|
|
||||||
func getNetmapCacheOptions(v *viper.Viper, l *zap.Logger) *cache.NetmapCacheConfig {
|
|
||||||
cacheCfg := cache.DefaultNetmapConfig(l)
|
|
||||||
|
|
||||||
cacheCfg.Lifetime = fetchCacheLifetime(v, l, cfgNetmapCacheLifetime, cacheCfg.Lifetime)
|
|
||||||
|
|
||||||
return cacheCfg
|
|
||||||
}
|
|
||||||
|
|
||||||
func fetchCacheLifetime(v *viper.Viper, l *zap.Logger, cfgEntry string, defaultValue time.Duration) time.Duration {
|
|
||||||
if v.IsSet(cfgEntry) {
|
|
||||||
lifetime := v.GetDuration(cfgEntry)
|
|
||||||
if lifetime <= 0 {
|
|
||||||
l.Error(logs.InvalidLifetimeUsingDefaultValue,
|
|
||||||
zap.String("parameter", cfgEntry),
|
|
||||||
zap.Duration("value in config", lifetime),
|
|
||||||
zap.Duration("default", defaultValue),
|
|
||||||
logs.TagField(logs.TagApp))
|
|
||||||
} else {
|
|
||||||
return lifetime
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
func fetchCacheSize(v *viper.Viper, l *zap.Logger, cfgEntry string, defaultValue int) int {
|
|
||||||
if v.IsSet(cfgEntry) {
|
|
||||||
size := v.GetInt(cfgEntry)
|
|
||||||
if size <= 0 {
|
|
||||||
l.Error(logs.InvalidCacheSizeUsingDefaultValue,
|
|
||||||
zap.String("parameter", cfgEntry),
|
|
||||||
zap.Int("value in config", size),
|
|
||||||
zap.Int("default", defaultValue),
|
|
||||||
logs.TagField(logs.TagApp))
|
|
||||||
} else {
|
|
||||||
return size
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
func getDialerSource(logger *zap.Logger, cfg *viper.Viper) *internalnet.DialerSource {
|
|
||||||
source, err := internalnet.NewDialerSource(fetchMultinetConfig(cfg, logger))
|
|
||||||
if err != nil {
|
|
||||||
logger.Fatal(logs.FailedToLoadMultinetConfig, zap.Error(err), logs.TagField(logs.TagApp))
|
|
||||||
}
|
|
||||||
return source
|
|
||||||
}
|
|
||||||
|
|
||||||
func fetchMultinetConfig(v *viper.Viper, l *zap.Logger) (cfg internalnet.Config) {
|
|
||||||
cfg.Enabled = v.GetBool(cfgMultinetEnabled)
|
|
||||||
cfg.Balancer = v.GetString(cfgMultinetBalancer)
|
|
||||||
cfg.Restrict = v.GetBool(cfgMultinetRestrict)
|
|
||||||
cfg.FallbackDelay = v.GetDuration(cfgMultinetFallbackDelay)
|
|
||||||
cfg.Subnets = make([]internalnet.Subnet, 0, 5)
|
|
||||||
cfg.EventHandler = internalnet.NewLogEventHandler(l)
|
|
||||||
|
|
||||||
for i := 0; ; i++ {
|
|
||||||
key := cfgMultinetSubnets + "." + strconv.Itoa(i) + "."
|
|
||||||
subnet := internalnet.Subnet{}
|
|
||||||
|
|
||||||
subnet.Prefix = v.GetString(key + "mask")
|
|
||||||
if subnet.Prefix == "" {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
subnet.SourceIPs = v.GetStringSlice(key + "source_ips")
|
|
||||||
cfg.Subnets = append(cfg.Subnets, subnet)
|
|
||||||
}
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func fetchTracingAttributes(v *viper.Viper) (map[string]string, error) {
|
|
||||||
attributes := make(map[string]string)
|
|
||||||
for i := 0; ; i++ {
|
|
||||||
key := cfgTracingAttributes + "." + strconv.Itoa(i) + "."
|
|
||||||
attrKey := v.GetString(key + "key")
|
|
||||||
attrValue := v.GetString(key + "value")
|
|
||||||
if attrKey == "" {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, ok := attributes[attrKey]; ok {
|
|
||||||
return nil, fmt.Errorf("tracing attribute key %s defined more than once", attrKey)
|
|
||||||
}
|
|
||||||
|
|
||||||
if attrValue == "" {
|
|
||||||
return nil, fmt.Errorf("empty tracing attribute value for key %s", attrKey)
|
|
||||||
}
|
|
||||||
|
|
||||||
attributes[attrKey] = attrValue
|
|
||||||
}
|
|
||||||
|
|
||||||
return attributes, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func fetchArchiveCompression(v *viper.Viper) bool {
|
|
||||||
if v.IsSet(cfgZipCompression) {
|
|
||||||
return v.GetBool(cfgZipCompression)
|
|
||||||
}
|
|
||||||
return v.GetBool(cfgArchiveCompression)
|
|
||||||
}
|
|
|
@ -1,60 +0,0 @@
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/resolver"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestConfigReload(t *testing.T) {
|
|
||||||
f, err := os.CreateTemp("", "conf")
|
|
||||||
require.NoError(t, err)
|
|
||||||
defer func() {
|
|
||||||
require.NoError(t, os.Remove(f.Name()))
|
|
||||||
}()
|
|
||||||
|
|
||||||
confData := `
|
|
||||||
pprof:
|
|
||||||
enabled: true
|
|
||||||
|
|
||||||
resolve_bucket:
|
|
||||||
default_namespaces: [""]
|
|
||||||
|
|
||||||
resolve_order:
|
|
||||||
- nns
|
|
||||||
`
|
|
||||||
|
|
||||||
_, err = f.WriteString(confData)
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.NoError(t, f.Close())
|
|
||||||
|
|
||||||
cfg := settings()
|
|
||||||
|
|
||||||
require.NoError(t, cfg.flags.Parse([]string{"--config", f.Name(), "--connect_timeout", "15s"}))
|
|
||||||
require.NoError(t, cfg.reload())
|
|
||||||
|
|
||||||
require.True(t, cfg.config().GetBool(cfgPprofEnabled))
|
|
||||||
require.Equal(t, []string{""}, cfg.config().GetStringSlice(cfgResolveDefaultNamespaces))
|
|
||||||
require.Equal(t, []string{resolver.NNSResolver}, cfg.config().GetStringSlice(cfgResolveOrder))
|
|
||||||
require.Equal(t, 15*time.Second, cfg.config().GetDuration(cfgConTimeout))
|
|
||||||
|
|
||||||
require.NoError(t, os.Truncate(f.Name(), 0))
|
|
||||||
require.NoError(t, cfg.reload())
|
|
||||||
|
|
||||||
require.False(t, cfg.config().GetBool(cfgPprofEnabled))
|
|
||||||
require.Equal(t, []string{"", "root"}, cfg.config().GetStringSlice(cfgResolveDefaultNamespaces))
|
|
||||||
require.Equal(t, []string{resolver.NNSResolver, resolver.DNSResolver}, cfg.config().GetStringSlice(cfgResolveOrder))
|
|
||||||
require.Equal(t, 15*time.Second, cfg.config().GetDuration(cfgConTimeout))
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSetTLSEnabled(t *testing.T) {
|
|
||||||
cfg := settings()
|
|
||||||
|
|
||||||
require.NoError(t, cfg.flags.Parse([]string{"--" + cfgTLSCertFile, "tls.crt", "--" + cfgTLSKeyFile, "tls.key"}))
|
|
||||||
require.NoError(t, cfg.reload())
|
|
||||||
|
|
||||||
require.True(t, cfg.config().GetBool(cfgServer+".0."+cfgTLSEnabled))
|
|
||||||
}
|
|
|
@ -14,35 +14,24 @@ HTTP_GW_PPROF_ADDRESS=localhost:8083
|
||||||
HTTP_GW_PROMETHEUS_ENABLED=true
|
HTTP_GW_PROMETHEUS_ENABLED=true
|
||||||
HTTP_GW_PROMETHEUS_ADDRESS=localhost:8084
|
HTTP_GW_PROMETHEUS_ADDRESS=localhost:8084
|
||||||
|
|
||||||
# Logger.
|
# Log level.
|
||||||
HTTP_GW_LOGGER_LEVEL=debug
|
HTTP_GW_LOGGER_LEVEL=debug
|
||||||
HTTP_GW_LOGGER_SAMPLING_ENABLED=false
|
|
||||||
HTTP_GW_LOGGER_SAMPLING_INITIAL=100
|
|
||||||
HTTP_GW_LOGGER_SAMPLING_THEREAFTER=100
|
|
||||||
HTTP_GW_LOGGER_SAMPLING_INTERVAL=1s
|
|
||||||
HTTP_GW_LOGGER_TAGS_0_NAME=app
|
|
||||||
HTTP_GW_LOGGER_TAGS_1_NAME=datapath
|
|
||||||
|
|
||||||
HTTP_GW_SERVER_0_ADDRESS=0.0.0.0:443
|
# Address to bind.
|
||||||
HTTP_GW_SERVER_0_TLS_ENABLED=false
|
HTTP_GW_LISTEN_ADDRESS=0.0.0.0:443
|
||||||
HTTP_GW_SERVER_0_TLS_CERT_FILE=/path/to/tls/cert
|
# Provide cert to enable TLS.
|
||||||
HTTP_GW_SERVER_0_TLS_KEY_FILE=/path/to/tls/key
|
HTTP_GW_TLS_CERTIFICATE=/path/to/tls/cert
|
||||||
HTTP_GW_SERVER_1_ADDRESS=0.0.0.0:444
|
# Provide key to enable TLS.
|
||||||
HTTP_GW_SERVER_1_TLS_ENABLED=true
|
HTTP_GW_TLS_KEY=/path/to/tls/key
|
||||||
HTTP_GW_SERVER_1_TLS_CERT_FILE=/path/to/tls/cert
|
|
||||||
HTTP_GW_SERVER_1_TLS_KEY_FILE=/path/to/tls/key
|
|
||||||
|
|
||||||
# How often to reconnect to the servers
|
|
||||||
HTTP_GW_RECONNECT_INTERVAL: 1m
|
|
||||||
|
|
||||||
# Nodes configuration.
|
# Nodes configuration.
|
||||||
# This configuration make the gateway use the first node (grpc://s01.frostfs.devenv:8080)
|
# This configuration make the gateway use the first node (grpc://s01.neofs.devenv:8080)
|
||||||
# while it's healthy. Otherwise, the gateway use the second node (grpc://s01.frostfs.devenv:8080)
|
# while it's healthy. Otherwise, the gateway use the second node (grpc://s01.neofs.devenv:8080)
|
||||||
# for 10% of requests and the third node for 90% of requests.
|
# for 10% of requests and the third node for 90% of requests.
|
||||||
|
|
||||||
# Peer 1.
|
# Peer 1.
|
||||||
# Endpoint.
|
# Endpoint.
|
||||||
HTTP_GW_PEERS_0_ADDRESS=grpc://s01.frostfs.devenv:8080
|
HTTP_GW_PEERS_0_ADDRESS=grpc://s01.neofs.devenv:8080
|
||||||
# Until nodes with the same priority level are healthy
|
# Until nodes with the same priority level are healthy
|
||||||
# nodes with other priority are not used.
|
# nodes with other priority are not used.
|
||||||
# The lower the value, the higher the priority.
|
# The lower the value, the higher the priority.
|
||||||
|
@ -50,11 +39,11 @@ HTTP_GW_PEERS_0_PRIORITY=1
|
||||||
# Load distribution proportion for nodes with the same priority.
|
# Load distribution proportion for nodes with the same priority.
|
||||||
HTTP_GW_PEERS_0_WEIGHT=1
|
HTTP_GW_PEERS_0_WEIGHT=1
|
||||||
# Peer 2.
|
# Peer 2.
|
||||||
HTTP_GW_PEERS_1_ADDRESS=grpc://s02.frostfs.devenv:8080
|
HTTP_GW_PEERS_1_ADDRESS=grpc://s02.neofs.devenv:8080
|
||||||
HTTP_GW_PEERS_1_PRIORITY=2
|
HTTP_GW_PEERS_1_PRIORITY=2
|
||||||
HTTP_GW_PEERS_1_WEIGHT=1
|
HTTP_GW_PEERS_1_WEIGHT=1
|
||||||
# Peer 3.
|
# Peer 3.
|
||||||
HTTP_GW_PEERS_2_ADDRESS=grpc://s03.frostfs.devenv:8080
|
HTTP_GW_PEERS_2_ADDRESS=grpc://s03.neofs.devenv:8080
|
||||||
HTTP_GW_PEERS_2_PRIORITY=2
|
HTTP_GW_PEERS_2_PRIORITY=2
|
||||||
HTTP_GW_PEERS_2_WEIGHT=9
|
HTTP_GW_PEERS_2_WEIGHT=9
|
||||||
|
|
||||||
|
@ -81,7 +70,7 @@ HTTP_GW_STREAM_REQUEST_BODY=true
|
||||||
HTTP_GW_MAX_REQUEST_BODY_SIZE=4194304
|
HTTP_GW_MAX_REQUEST_BODY_SIZE=4194304
|
||||||
|
|
||||||
# RPC endpoint to be able to use nns container resolving.
|
# RPC endpoint to be able to use nns container resolving.
|
||||||
HTTP_GW_RPC_ENDPOINT=http://morph-chain.frostfs.devenv:30333
|
HTTP_GW_RPC_ENDPOINT=http://morph-chain.neofs.devenv:30333
|
||||||
# The order in which resolvers are used to find an container id by name.
|
# The order in which resolvers are used to find an container id by name.
|
||||||
HTTP_GW_RESOLVE_ORDER="nns dns"
|
HTTP_GW_RESOLVE_ORDER="nns dns"
|
||||||
|
|
||||||
|
@ -97,78 +86,7 @@ HTTP_GW_REQUEST_TIMEOUT=5s
|
||||||
# Interval to check nodes health.
|
# Interval to check nodes health.
|
||||||
HTTP_GW_REBALANCE_TIMER=30s
|
HTTP_GW_REBALANCE_TIMER=30s
|
||||||
# The number of errors on connection after which node is considered as unhealthy
|
# The number of errors on connection after which node is considered as unhealthy
|
||||||
HTTP_GW_POOL_ERROR_THRESHOLD=100
|
S3_GW_POOL_ERROR_THRESHOLD=100
|
||||||
|
|
||||||
# Enable archive compression to download files by common prefix.
|
# Enable zip compression to download files by common prefix.
|
||||||
# DEPRECATED: Use HTTP_GW_ARCHIVE_COMPRESSION instead.
|
|
||||||
HTTP_GW_ZIP_COMPRESSION=false
|
HTTP_GW_ZIP_COMPRESSION=false
|
||||||
|
|
||||||
# Enable archive compression to download files by common prefix.
|
|
||||||
HTTP_GW_ARCHIVE_COMPRESSION=false
|
|
||||||
|
|
||||||
HTTP_GW_TRACING_ENABLED=true
|
|
||||||
HTTP_GW_TRACING_ENDPOINT="localhost:4317"
|
|
||||||
HTTP_GW_TRACING_EXPORTER="otlp_grpc"
|
|
||||||
HTTP_GW_TRACING_TRUSTED_CA=""
|
|
||||||
HTTP_GW_TRACING_ATTRIBUTES_0_KEY=key0
|
|
||||||
HTTP_GW_TRACING_ATTRIBUTES_0_VALUE=value
|
|
||||||
HTTP_GW_TRACING_ATTRIBUTES_1_KEY=key1
|
|
||||||
HTTP_GW_TRACING_ATTRIBUTES_1_VALUE=value
|
|
||||||
|
|
||||||
HTTP_GW_RUNTIME_SOFT_MEMORY_LIMIT=1073741824
|
|
||||||
|
|
||||||
# Parameters of requests to FrostFS
|
|
||||||
# This flag enables client side object preparing.
|
|
||||||
HTTP_GW_FROSTFS_CLIENT_CUT=false
|
|
||||||
# Sets max buffer size for read payload in put operations.
|
|
||||||
HTTP_GW_FROSTFS_BUFFER_MAX_SIZE_FOR_PUT=1048576
|
|
||||||
|
|
||||||
# Caching
|
|
||||||
# Cache which contains mapping of bucket name to bucket info
|
|
||||||
HTTP_GW_CACHE_BUCKETS_LIFETIME=1m
|
|
||||||
HTTP_GW_CACHE_BUCKETS_SIZE=1000
|
|
||||||
# Cache which stores netmap
|
|
||||||
HTTP_GW_CACHE_NETMAP_LIFETIME=1m
|
|
||||||
|
|
||||||
# Header to determine zone to resolve bucket name
|
|
||||||
HTTP_GW_RESOLVE_BUCKET_NAMESPACE_HEADER=X-Frostfs-Namespace
|
|
||||||
# Namespaces that should be handled as default
|
|
||||||
HTTP_GW_RESOLVE_BUCKET_DEFAULT_NAMESPACES="" "root"
|
|
||||||
|
|
||||||
# Max attempt to make successful tree request.
|
|
||||||
# default value is 0 that means the number of attempts equals to number of nodes in pool.
|
|
||||||
HTTP_GW_FROSTFS_TREE_POOL_MAX_ATTEMPTS=0
|
|
||||||
|
|
||||||
HTTP_GW_CORS_ALLOW_ORIGIN="*"
|
|
||||||
HTTP_GW_CORS_ALLOW_METHODS="GET" "POST"
|
|
||||||
HTTP_GW_CORS_ALLOW_HEADERS="*"
|
|
||||||
HTTP_GW_CORS_EXPOSE_HEADERS="*"
|
|
||||||
HTTP_GW_CORS_ALLOW_CREDENTIALS=false
|
|
||||||
HTTP_GW_CORS_MAX_AGE=600
|
|
||||||
|
|
||||||
# Multinet properties
|
|
||||||
# Enable multinet support
|
|
||||||
HTTP_GW_MULTINET_ENABLED=false
|
|
||||||
# Strategy to pick source IP address
|
|
||||||
HTTP_GW_MULTINET_BALANCER=roundrobin
|
|
||||||
# Restrict requests with unknown destination subnet
|
|
||||||
HTTP_GW_MULTINET_RESTRICT=false
|
|
||||||
# Delay between ipv6 to ipv4 fallback switch
|
|
||||||
HTTP_GW_MULTINET_FALLBACK_DELAY=300ms
|
|
||||||
# List of subnets and IP addresses to use as source for those subnets
|
|
||||||
HTTP_GW_MULTINET_SUBNETS_1_MASK=1.2.3.4/24
|
|
||||||
HTTP_GW_MULTINET_SUBNETS_1_SOURCE_IPS=1.2.3.4 1.2.3.5
|
|
||||||
|
|
||||||
# Number of workers in handler's worker pool
|
|
||||||
HTTP_GW_WORKER_POOL_SIZE=1000
|
|
||||||
|
|
||||||
# Index page
|
|
||||||
# Enable index page support
|
|
||||||
HTTP_GW_INDEX_PAGE_ENABLED=false
|
|
||||||
# Index page template path
|
|
||||||
HTTP_GW_INDEX_PAGE_TEMPLATE_PATH=internal/handler/templates/index.gotmpl
|
|
||||||
|
|
||||||
# Enable using fallback path to search for a object by attribute
|
|
||||||
HTTP_GW_FEATURES_ENABLE_FILEPATH_FALLBACK=false
|
|
||||||
# Enable using new version of tree pool, which uses netmap to select nodes, for requests to tree service
|
|
||||||
HTTP_GW_FEATURES_TREE_POOL_NETMAP_SUPPORT=true
|
|
||||||
|
|
|
@ -4,56 +4,27 @@ wallet:
|
||||||
passphrase: pwd # Passphrase to decrypt wallet. If you're using a wallet without a password, place '' here.
|
passphrase: pwd # Passphrase to decrypt wallet. If you're using a wallet without a password, place '' here.
|
||||||
|
|
||||||
pprof:
|
pprof:
|
||||||
enabled: false # Enable pprof.
|
enabled: true # Enable pprof.
|
||||||
address: localhost:8083
|
address: localhost:8083
|
||||||
prometheus:
|
prometheus:
|
||||||
enabled: false # Enable metrics.
|
enabled: true # Enable metrics.
|
||||||
address: localhost:8084
|
address: localhost:8084
|
||||||
|
|
||||||
tracing:
|
|
||||||
enabled: true
|
|
||||||
exporter: "otlp_grpc"
|
|
||||||
endpoint: "localhost:4317"
|
|
||||||
trusted_ca: ""
|
|
||||||
attributes:
|
|
||||||
- key: key0
|
|
||||||
value: value
|
|
||||||
- key: key1
|
|
||||||
value: value
|
|
||||||
|
|
||||||
logger:
|
logger:
|
||||||
level: debug # Log level.
|
level: debug # Log level.
|
||||||
destination: stdout
|
|
||||||
sampling:
|
|
||||||
enabled: false
|
|
||||||
initial: 100
|
|
||||||
thereafter: 100
|
|
||||||
interval: 1s
|
|
||||||
tags:
|
|
||||||
- name: app
|
|
||||||
- name: datapath
|
|
||||||
level: debug
|
|
||||||
|
|
||||||
server:
|
listen_address: 0.0.0.0:443 # Address to bind.
|
||||||
- address: 0.0.0.0:8080
|
tls_certificate: /path/to/tls/cert # Provide cert to enable TLS.
|
||||||
tls:
|
tls_key: /path/to/tls/key # Provide key to enable TLS.
|
||||||
enabled: false
|
|
||||||
cert_file: /path/to/cert
|
|
||||||
key_file: /path/to/key
|
|
||||||
- address: 0.0.0.0:8081
|
|
||||||
tls:
|
|
||||||
enabled: false
|
|
||||||
cert_file: /path/to/cert
|
|
||||||
key_file: /path/to/key
|
|
||||||
|
|
||||||
# Nodes configuration.
|
# Nodes configuration.
|
||||||
# This configuration make the gateway use the first node (grpc://s01.frostfs.devenv:8080)
|
# This configuration make the gateway use the first node (grpc://s01.neofs.devenv:8080)
|
||||||
# while it's healthy. Otherwise, the gateway use the second node (grpc://s01.frostfs.devenv:8080)
|
# while it's healthy. Otherwise, the gateway use the second node (grpc://s01.neofs.devenv:8080)
|
||||||
# for 10% of requests and the third node for 90% of requests.
|
# for 10% of requests and the third node for 90% of requests.
|
||||||
peers:
|
peers:
|
||||||
0:
|
0:
|
||||||
# Endpoint.
|
# Endpoint.
|
||||||
address: grpc://s01.frostfs.devenv:8080
|
address: grpc://s01.neofs.devenv:8080
|
||||||
|
|
||||||
# Until nodes with the same priority level are healthy
|
# Until nodes with the same priority level are healthy
|
||||||
# nodes with other priority are not used.
|
# nodes with other priority are not used.
|
||||||
|
@ -63,15 +34,14 @@ peers:
|
||||||
# Load distribution proportion for nodes with the same priority.
|
# Load distribution proportion for nodes with the same priority.
|
||||||
weight: 1
|
weight: 1
|
||||||
1:
|
1:
|
||||||
address: grpc://s02.frostfs.devenv:8080
|
address: grpc://s02.neofs.devenv:8080
|
||||||
priority: 2
|
priority: 2
|
||||||
weight: 1
|
weight: 1
|
||||||
2:
|
2:
|
||||||
address: grpc://s03.frostfs.devenv:8080
|
address: grpc://s03.neofs.devenv:8080
|
||||||
priority: 2
|
priority: 2
|
||||||
weight: 9
|
weight: 9
|
||||||
|
|
||||||
reconnect_interval: 1m
|
|
||||||
|
|
||||||
web:
|
web:
|
||||||
# Per-connection buffer size for requests' reading.
|
# Per-connection buffer size for requests' reading.
|
||||||
|
@ -102,7 +72,7 @@ web:
|
||||||
max_request_body_size: 4194304
|
max_request_body_size: 4194304
|
||||||
|
|
||||||
# RPC endpoint to be able to use nns container resolving.
|
# RPC endpoint to be able to use nns container resolving.
|
||||||
rpc_endpoint: http://morph-chain.frostfs.devenv:30333
|
rpc_endpoint: http://morph-chain.neofs.devenv:30333
|
||||||
# The order in which resolvers are used to find an container id by name.
|
# The order in which resolvers are used to find an container id by name.
|
||||||
resolve_order:
|
resolve_order:
|
||||||
- nns
|
- nns
|
||||||
|
@ -117,77 +87,5 @@ request_timeout: 5s # Timeout to check node health during rebalance.
|
||||||
rebalance_timer: 30s # Interval to check nodes health.
|
rebalance_timer: 30s # Interval to check nodes health.
|
||||||
pool_error_threshold: 100 # The number of errors on connection after which node is considered as unhealthy.
|
pool_error_threshold: 100 # The number of errors on connection after which node is considered as unhealthy.
|
||||||
|
|
||||||
# Number of workers in handler's worker pool
|
|
||||||
worker_pool_size: 1000
|
|
||||||
|
|
||||||
# Enables index page to see objects list for specified container and prefix
|
|
||||||
index_page:
|
|
||||||
enabled: false
|
|
||||||
template_path: internal/handler/templates/index.gotmpl
|
|
||||||
|
|
||||||
# Deprecated: Use archive.compression instead
|
|
||||||
zip:
|
zip:
|
||||||
# Enables zip compression to download files by common prefix.
|
compression: false # Enable zip compression to download files by common prefix.
|
||||||
compression: false
|
|
||||||
|
|
||||||
archive:
|
|
||||||
# Enables archive compression to download files by common prefix.
|
|
||||||
compression: false
|
|
||||||
|
|
||||||
runtime:
|
|
||||||
soft_memory_limit: 1gb
|
|
||||||
|
|
||||||
# Parameters of requests to FrostFS
|
|
||||||
frostfs:
|
|
||||||
# This flag enables client side object preparing.
|
|
||||||
client_cut: false
|
|
||||||
# Sets max buffer size for read payload in put operations.
|
|
||||||
buffer_max_size_for_put: 1048576
|
|
||||||
# Max attempt to make successful tree request.
|
|
||||||
# default value is 0 that means the number of attempts equals to number of nodes in pool.
|
|
||||||
tree_pool_max_attempts: 0
|
|
||||||
|
|
||||||
# Caching
|
|
||||||
cache:
|
|
||||||
# Cache which contains mapping of bucket name to bucket info
|
|
||||||
buckets:
|
|
||||||
lifetime: 1m
|
|
||||||
size: 1000
|
|
||||||
# Cache which stores netmap
|
|
||||||
netmap:
|
|
||||||
lifetime: 1m
|
|
||||||
|
|
||||||
resolve_bucket:
|
|
||||||
namespace_header: X-Frostfs-Namespace
|
|
||||||
default_namespaces: [ "", "root" ]
|
|
||||||
|
|
||||||
cors:
|
|
||||||
allow_origin: ""
|
|
||||||
allow_methods: []
|
|
||||||
allow_headers: []
|
|
||||||
expose_headers: []
|
|
||||||
allow_credentials: false
|
|
||||||
max_age: 600
|
|
||||||
|
|
||||||
# Multinet properties
|
|
||||||
multinet:
|
|
||||||
# Enable multinet support
|
|
||||||
enabled: false
|
|
||||||
# Strategy to pick source IP address
|
|
||||||
balancer: roundrobin
|
|
||||||
# Restrict requests with unknown destination subnet
|
|
||||||
restrict: false
|
|
||||||
# Delay between ipv6 to ipv4 fallback switch
|
|
||||||
fallback_delay: 300ms
|
|
||||||
# List of subnets and IP addresses to use as source for those subnets
|
|
||||||
subnets:
|
|
||||||
- mask: 1.2.3.4/24
|
|
||||||
source_ips:
|
|
||||||
- 1.2.3.4
|
|
||||||
- 1.2.3.5
|
|
||||||
|
|
||||||
features:
|
|
||||||
# Enable using fallback path to search for a object by attribute
|
|
||||||
enable_filepath_fallback: false
|
|
||||||
# Enable using new version of tree pool, which uses netmap to select nodes, for requests to tree service
|
|
||||||
tree_pool_netmap_support: true
|
|
||||||
|
|
|
@ -1,3 +0,0 @@
|
||||||
pprof:
|
|
||||||
enabled: true
|
|
||||||
address: localhost:8083
|
|
|
@ -1,3 +0,0 @@
|
||||||
prometheus:
|
|
||||||
enabled: true
|
|
||||||
address: localhost:8084
|
|
4
debian/changelog
vendored
4
debian/changelog
vendored
|
@ -1,5 +1,5 @@
|
||||||
frostfs-http-gw (0.0.0) stable; urgency=medium
|
neofs-http-gw (0.0.0) stable; urgency=medium
|
||||||
|
|
||||||
* Please see CHANGELOG.md
|
* Please see CHANGELOG.md
|
||||||
|
|
||||||
-- TrueCloudLab <tech@frostfs.info> Wed, 24 Aug 2022 18:29:49 +0300
|
-- NeoSPCC <tech@nspcc.ru> Wed, 24 Aug 2022 18:29:49 +0300
|
||||||
|
|
17
debian/control
vendored
17
debian/control
vendored
|
@ -1,14 +1,15 @@
|
||||||
Source: frostfs-http-gw
|
Source: neofs-http-gw
|
||||||
Section: frostfs
|
Section: neofs
|
||||||
Priority: optional
|
Priority: optional
|
||||||
Maintainer: TrueCloudLab <tech@frostfs.info>
|
Maintainer: NeoSPCC <tech@nspcc.ru>
|
||||||
Build-Depends: debhelper-compat (= 13), dh-sysuser, git, devscripts
|
Build-Depends: debhelper-compat (= 13), dh-sysuser, git, devscripts
|
||||||
Standards-Version: 4.5.1
|
Standards-Version: 4.5.1
|
||||||
Homepage: https://frostfs.info/
|
Homepage: https://fs.neo.org/
|
||||||
Vcs-Git: https://git.frostfs.info/TrueCloudLab/frostfs-http-gw.git
|
Vcs-Git: https://github.com/nspcc-dev/neofs-http-gw.git
|
||||||
Vcs-Browser: https://git.frostfs.info/TrueCloudLab/frostfs-http-gw
|
Vcs-Browser: https://github.com/nspcc-dev/neofs-http-gw
|
||||||
|
|
||||||
Package: frostfs-http-gw
|
Package: neofs-http-gw
|
||||||
Architecture: any
|
Architecture: any
|
||||||
Depends: ${misc:Depends}
|
Depends: ${misc:Depends}
|
||||||
Description: FrostFS HTTP Gateway bridges FrostFS internal protocol and HTTP standard.
|
Description: NeoFS HTTP Gateway bridges NeoFS internal protocol and HTTP standard.
|
||||||
|
|
||||||
|
|
18
debian/copyright
vendored
18
debian/copyright
vendored
|
@ -1,25 +1,23 @@
|
||||||
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
|
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
|
||||||
Upstream-Name: frostfs-http-gw
|
Upstream-Name: neofs-http-gw
|
||||||
Upstream-Contact: tech@frostfs.info
|
Upstream-Contact: tech@nspcc.ru
|
||||||
Source: https://git.frostfs.info/TrueCloudLab/frostfs-http-gw
|
Source: https://github.com/nspcc-dev/neofs-http-gw
|
||||||
|
|
||||||
Files: *
|
Files: *
|
||||||
Copyright: 2018-2022 NeoSPCC (@nspcc-dev), contributors of neofs-http-gw project
|
Copyright: 2018-2022 NeoSPCC (@nspcc-dev), contributors of neofs-http-gw project
|
||||||
(https://github.com/nspcc-dev/neofs-http-gw/blob/master/CREDITS.md)
|
(https://github.com/nspcc-dev/neofs-http-gw/blob/master/CREDITS.md)
|
||||||
2022 True Cloud Lab (@TrueCloudLab), contributors of frostfs-http-gw project
|
|
||||||
(https://git.frostfs.info/TrueCloudLab/frostfs-http-gw/src/branch/master/CREDITS.md)
|
|
||||||
|
|
||||||
|
|
||||||
License: GPL-3
|
License: GPL-3
|
||||||
This program is free software: you can redistribute it and/or modify it
|
This program is free software: you can redistribute it and/or modify it
|
||||||
under the terms of the GNU General Public License as published
|
under the terms of the GNU General Public License as published
|
||||||
by the Free Software Foundation; version 3.
|
by the Free Software Foundation; version 3.
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful,
|
This program is distributed in the hope that it will be useful,
|
||||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||||
General Public License for more details.
|
General Public License for more details.
|
||||||
|
|
||||||
You should have received a copy of the GNU General Public License
|
You should have received a copy of the GNU General Public License
|
||||||
along with this program or at /usr/share/common-licenses/GPL-3.
|
along with this program or at /usr/share/common-licenses/GPL-3.
|
||||||
If not, see <http://www.gnu.org/licenses/>.
|
If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
2
debian/frostfs-http-gw.dirs
vendored
2
debian/frostfs-http-gw.dirs
vendored
|
@ -1,2 +0,0 @@
|
||||||
etc/frostfs
|
|
||||||
srv/frostfs_cache
|
|
2
debian/frostfs-http-gw.install
vendored
2
debian/frostfs-http-gw.install
vendored
|
@ -1,2 +0,0 @@
|
||||||
bin/frostfs-http-gw usr/bin
|
|
||||||
config/config.yaml etc/frostfs/http
|
|
16
debian/frostfs-http-gw.service
vendored
16
debian/frostfs-http-gw.service
vendored
|
@ -1,16 +0,0 @@
|
||||||
[Unit]
|
|
||||||
Description=FrostFS HTTP Gateway
|
|
||||||
Requires=network.target
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
Type=simple
|
|
||||||
ExecStart=/usr/bin/frostfs-http-gw --config /etc/frostfs/http/config.yaml
|
|
||||||
User=frostfs-http
|
|
||||||
Group=frostfs-http
|
|
||||||
WorkingDirectory=/srv/frostfs_cache
|
|
||||||
Restart=always
|
|
||||||
RestartSec=5
|
|
||||||
PrivateTmp=true
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
2
debian/neofs-http-gw.dirs
vendored
Normal file
2
debian/neofs-http-gw.dirs
vendored
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
etc/neofs
|
||||||
|
srv/neofs_cache
|
2
debian/neofs-http-gw.install
vendored
Normal file
2
debian/neofs-http-gw.install
vendored
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
bin/neofs-http-gw usr/bin
|
||||||
|
config/config.yaml etc/neofs/http
|
20
debian/frostfs-http-gw.postinst → debian/neofs-http-gw.postinst
vendored
Executable file → Normal file
20
debian/frostfs-http-gw.postinst → debian/neofs-http-gw.postinst
vendored
Executable file → Normal file
|
@ -1,5 +1,5 @@
|
||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# postinst script for frostfs-http-gw
|
# postinst script for neofs-http-gw
|
||||||
#
|
#
|
||||||
# see: dh_installdeb(1)
|
# see: dh_installdeb(1)
|
||||||
|
|
||||||
|
@ -21,16 +21,16 @@ set -e
|
||||||
case "$1" in
|
case "$1" in
|
||||||
configure)
|
configure)
|
||||||
USERNAME=http
|
USERNAME=http
|
||||||
id -u frostfs-$USERNAME >/dev/null 2>&1 || useradd -s /usr/sbin/nologin -d /var/lib/frostfs/$USERNAME --system -m -U -c "FrostFS HTTP gateway" frostfs-$USERNAME
|
id -u neofs-$USERNAME >/dev/null 2>&1 || useradd -s /usr/sbin/nologin -d /srv/neofs_cache --system -M -U -c "NeoFS HTTP gateway" neofs-$USERNAME
|
||||||
if ! dpkg-statoverride --list /etc/frostfs/$USERNAME >/dev/null; then
|
if ! dpkg-statoverride --list /etc/neofs/$USERNAME >/dev/null; then
|
||||||
chown -f root:frostfs-$USERNAME /etc/frostfs/$USERNAME
|
chown -f root:neofs-$USERNAME /etc/neofs/$USERNAME
|
||||||
chown -f root:frostfs-$USERNAME /etc/frostfs/$USERNAME/config.yaml || true
|
chown -f root:neofs-$USERNAME /etc/neofs/$USERNAME/config.yaml || true
|
||||||
chmod -f 0750 /etc/frostfs/$USERNAME
|
chmod -f 0750 /etc/neofs/$USERNAME
|
||||||
chmod -f 0640 /etc/frostfs/$USERNAME/config.yaml || true
|
chmod -f 0640 /etc/neofs/$USERNAME/config.yaml || true
|
||||||
fi
|
fi
|
||||||
USERDIR=$(getent passwd "frostfs-$USERNAME" | cut -d: -f6)
|
USERDIR=$(getent passwd "neofs-$USERNAME" | cut -d: -f6)
|
||||||
if ! dpkg-statoverride --list "$USERDIR" >/dev/null; then
|
if ! dpkg-statoverride --list neofs-$USERDIR >/dev/null; then
|
||||||
chown -f frostfs-$USERNAME: "$USERDIR"
|
chown -f neofs-$USERNAME: $USERDIR
|
||||||
fi
|
fi
|
||||||
;;
|
;;
|
||||||
|
|
4
debian/frostfs-http-gw.postrm → debian/neofs-http-gw.postrm
vendored
Executable file → Normal file
4
debian/frostfs-http-gw.postrm → debian/neofs-http-gw.postrm
vendored
Executable file → Normal file
|
@ -1,5 +1,5 @@
|
||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# postrm script for frostfs-http-gw
|
# postrm script for neofs-http-gw
|
||||||
#
|
#
|
||||||
# see: dh_installdeb(1)
|
# see: dh_installdeb(1)
|
||||||
|
|
||||||
|
@ -21,7 +21,7 @@ set -e
|
||||||
|
|
||||||
case "$1" in
|
case "$1" in
|
||||||
purge)
|
purge)
|
||||||
rm -rf /srv/frostfs_cache
|
rm -rf /srv/neofs_cache
|
||||||
;;
|
;;
|
||||||
|
|
||||||
remove|upgrade|failed-upgrade|abort-install|abort-upgrade|disappear)
|
remove|upgrade|failed-upgrade|abort-install|abort-upgrade|disappear)
|
2
debian/frostfs-http-gw.preinst → debian/neofs-http-gw.preinst
vendored
Executable file → Normal file
2
debian/frostfs-http-gw.preinst → debian/neofs-http-gw.preinst
vendored
Executable file → Normal file
|
@ -1,5 +1,5 @@
|
||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# preinst script for frostfs-http-gw
|
# preinst script for neofs-http-gw
|
||||||
#
|
#
|
||||||
# see: dh_installdeb(1)
|
# see: dh_installdeb(1)
|
||||||
|
|
2
debian/frostfs-http-gw.prerm → debian/neofs-http-gw.prerm
vendored
Executable file → Normal file
2
debian/frostfs-http-gw.prerm → debian/neofs-http-gw.prerm
vendored
Executable file → Normal file
|
@ -1,5 +1,5 @@
|
||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# prerm script for frostfs-http-gw
|
# prerm script for neofs-http-gw
|
||||||
#
|
#
|
||||||
# see: dh_installdeb(1)
|
# see: dh_installdeb(1)
|
||||||
|
|
16
debian/neofs-http-gw.service
vendored
Normal file
16
debian/neofs-http-gw.service
vendored
Normal file
|
@ -0,0 +1,16 @@
|
||||||
|
[Unit]
|
||||||
|
Description=NeoFS HTTP Gateway
|
||||||
|
Requires=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
ExecStart=/usr/bin/neofs-http-gw --config /etc/neofs/http/config.yaml
|
||||||
|
User=neofs-http
|
||||||
|
Group=neofs-http
|
||||||
|
WorkingDirectory=/srv/neofs_cache
|
||||||
|
Restart=always
|
||||||
|
RestartSec=5
|
||||||
|
PrivateTmp=true
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
8
debian/rules
vendored
8
debian/rules
vendored
|
@ -2,13 +2,15 @@
|
||||||
|
|
||||||
# Do not try to strip Go binaries and do not run test
|
# Do not try to strip Go binaries and do not run test
|
||||||
export DEB_BUILD_OPTIONS := nostrip nocheck
|
export DEB_BUILD_OPTIONS := nostrip nocheck
|
||||||
SERVICE = frostfs-http-gw
|
SERVICE = neofs-http-gw
|
||||||
|
|
||||||
%:
|
%:
|
||||||
dh $@
|
dh $@
|
||||||
|
|
||||||
override_dh_installsystemd:
|
override_dh_installsystemd:
|
||||||
dh_installsystemd --no-enable --no-start $(SERVICE).service
|
dh_installsystemd --no-enable --no-start $(SERVICE).service
|
||||||
|
|
||||||
override_dh_installchangelogs:
|
override_dh_installchangelogs:
|
||||||
dh_installchangelogs -k CHANGELOG.md
|
dh_installchangelogs -k CHANGELOG.md
|
||||||
|
|
||||||
|
|
||||||
|
|
319
docs/api.md
319
docs/api.md
|
@ -1,319 +0,0 @@
|
||||||
# HTTP Gateway Specification
|
|
||||||
|
|
||||||
| Route | Description |
|
|
||||||
|-------------------------------------------------|--------------------------------------------------|
|
|
||||||
| `/upload/{cid}` | [Put object](#put-object) |
|
|
||||||
| `/get/{cid}/{oid}` | [Get object](#get-object) |
|
|
||||||
| `/get_by_attribute/{cid}/{attr_key}/{attr_val}` | [Search object](#search-object) |
|
|
||||||
| `/zip/{cid}/{prefix}`, `/tar/{cid}/{prefix}` | [Download objects in archive](#download-archive) |
|
|
||||||
|
|
||||||
**Note:** `cid` parameter can be base58 encoded container ID or container name
|
|
||||||
(the name must be registered in NNS, see appropriate section in [nns.md](./nns.md)).
|
|
||||||
|
|
||||||
Route parameters can be:
|
|
||||||
|
|
||||||
* `Single` - match a single path segment (cannot contain `/` and be empty)
|
|
||||||
* `Catch-All` - match everything (such parameter usually the last one in routes)
|
|
||||||
* `Query` - regular query parameter
|
|
||||||
|
|
||||||
### Bearer token
|
|
||||||
|
|
||||||
All routes can accept [bearer token](./authentication.md) from:
|
|
||||||
|
|
||||||
* `Authorization` header with `Bearer` type and base64-encoded token in
|
|
||||||
credentials field
|
|
||||||
* `Bearer` cookie with base64-encoded token contents
|
|
||||||
|
|
||||||
Example:
|
|
||||||
|
|
||||||
Header:
|
|
||||||
|
|
||||||
```
|
|
||||||
Authorization: Bearer ChA5Gev0d8JI26tAtWyyQA3WEhsKGTVxfQ56a0uQeFmOO63mqykBS1HNpw1rxSgaBgiyEBjODyIhAyxcn89Bj5fwCfXlj5HjSYjonHSErZoXiSqeyh0ZQSb2MgQIARAB
|
|
||||||
```
|
|
||||||
|
|
||||||
Cookie:
|
|
||||||
|
|
||||||
```
|
|
||||||
cookie: Bearer=ChA5Gev0d8JI26tAtWyyQA3WEhsKGTVxfQ56a0uQeFmOO63mqykBS1HNpw1rxSgaBgiyEBjODyIhAyxcn89Bj5fwCfXlj5HjSYjonHSErZoXiSqeyh0ZQSb2MgQIARAB
|
|
||||||
```
|
|
||||||
|
|
||||||
## Put object
|
|
||||||
|
|
||||||
Route: `/upload/{cid}`
|
|
||||||
|
|
||||||
| Route parameter | Type | Description |
|
|
||||||
|-----------------|--------|---------------------------------------------------------|
|
|
||||||
| `cid` | Single | Base58 encoded container ID or container name from NNS. |
|
|
||||||
|
|
||||||
### Methods
|
|
||||||
|
|
||||||
#### POST
|
|
||||||
|
|
||||||
Upload file as object with attributes to FrostFS.
|
|
||||||
|
|
||||||
##### Request
|
|
||||||
|
|
||||||
###### Headers
|
|
||||||
|
|
||||||
| Header | Description |
|
|
||||||
|------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
||||||
| Common headers | See [bearer token](#bearer-token). |
|
|
||||||
| `X-Attribute-System-*` | Used to set system FrostFS object attributes <br/> (e.g. use "X-Attribute-System-Expiration-Epoch" to set `__SYSTEM__EXPIRATION_EPOCH` attribute). |
|
|
||||||
| `X-Attribute-*` | Used to set regular object attributes <br/> (e.g. use "X-Attribute-My-Tag" to set `My-Tag` attribute). |
|
|
||||||
| `X-Explode-Archive` | If set, gate tries to read files from uploading `tar` archive and creates an object for each file in it. Uploading `tar` could be compressed via Gzip by setting a `Content-Encoding` header. Sets a `FilePath` attribute as a relative path from archive root and a `FileName` as the last path element of the `FilePath`. |
|
|
||||||
| `Content-Encoding` | If set and value is `gzip`, gate will handle uploading file as a `Gzip` compressed `tar` file. |
|
|
||||||
| `Date` | This header is used to calculate the right `__SYSTEM__EXPIRATION` attribute for object. If the header is missing, the current server time is used. |
|
|
||||||
|
|
||||||
There are some reserved headers type of `X-Attribute-FROSTFS-*` (headers are arranged in descending order of priority):
|
|
||||||
|
|
||||||
1. `X-Attribute-System-Expiration-Epoch: 100`
|
|
||||||
2. `X-Attribute-System-Expiration-Duration: 24h30m`
|
|
||||||
3. `X-Attribute-System-Expiration-Timestamp: 1637574797`
|
|
||||||
4. `X-Attribute-System-Expiration-RFC3339: 2021-11-22T09:55:49Z`
|
|
||||||
|
|
||||||
which transforms to `X-Attribute-System-Expiration-Epoch`. So you can provide expiration any convenient way.
|
|
||||||
|
|
||||||
If you don't specify the `X-Attribute-Timestamp` header the `Timestamp` attribute can be set anyway
|
|
||||||
(see http-gw [configuration](gate-configuration.md#upload-header-section)).
|
|
||||||
|
|
||||||
The `X-Attribute-*` headers must be unique. If you provide several the same headers only one will be used.
|
|
||||||
Attribute key and value must be valid utf8 string. All attributes in sum must not be greater than 3mb.
|
|
||||||
|
|
||||||
###### Body
|
|
||||||
|
|
||||||
Body must contain multipart form with file.
|
|
||||||
The `filename` field from the multipart form will be set as `FileName` attribute of object
|
|
||||||
(can be overriden by `X-Attribute-FileName` header).
|
|
||||||
|
|
||||||
##### Response
|
|
||||||
|
|
||||||
###### Status codes
|
|
||||||
|
|
||||||
| Status | Description |
|
|
||||||
|--------|----------------------------------------------|
|
|
||||||
| 200 | Object created successfully. |
|
|
||||||
| 400 | Some error occurred during object uploading. |
|
|
||||||
|
|
||||||
## Get object
|
|
||||||
|
|
||||||
Route: `/get/{cid}/{oid}?[download=false]`
|
|
||||||
|
|
||||||
| Route parameter | Type | Description |
|
|
||||||
|-----------------|--------|------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
||||||
| `cid` | Single | Base58 encoded `container ID` or `container name` from NNS or `bucket name`. |
|
|
||||||
| `oid` | Single | Base58 encoded `object ID`. Also could be `S3 object name` if `cid` is specified as bucket name. |
|
|
||||||
| `download` | Query | Set the `Content-Disposition` header as `attachment` in response.<br/> This make the browser to download object as file instead of showing it on the page. |
|
|
||||||
|
|
||||||
### Methods
|
|
||||||
|
|
||||||
#### GET
|
|
||||||
|
|
||||||
Get an object (payload and attributes) by an address.
|
|
||||||
|
|
||||||
##### Request
|
|
||||||
|
|
||||||
###### Headers
|
|
||||||
|
|
||||||
| Header | Description |
|
|
||||||
|----------------|------------------------------------|
|
|
||||||
| Common headers | See [bearer token](#bearer-token). |
|
|
||||||
|
|
||||||
##### Response
|
|
||||||
|
|
||||||
###### Headers
|
|
||||||
|
|
||||||
| Header | Description |
|
|
||||||
|------------------------|----------------------------------------------------------------------------------------------------------------------------------------------|
|
|
||||||
| `X-Attribute-System-*` | System FrostFS object attributes <br/> (e.g. `__SYSTEM__EXPIRATION_EPOCH` set "X-Attribute-System-Expiration-Epoch" header). |
|
|
||||||
| `X-Attribute-*` | Regular object attributes <br/> (e.g. `My-Tag` set "X-Attribute-My-Tag" header). |
|
|
||||||
| `Content-Disposition` | Indicate how to browsers should treat file. <br/> Set `filename` as base part of `FileName` object attribute (if it's set, empty otherwise). |
|
|
||||||
| `Content-Type` | Indicate content type of object. Set from `Content-Type` attribute or detected using payload. |
|
|
||||||
| `Content-Length` | Size of object payload. |
|
|
||||||
| `Last-Modified` | Contains the `Timestamp` attribute (if exists) formatted as HTTP time (RFC7231,RFC1123). |
|
|
||||||
| `X-Owner-Id` | Base58 encoded owner ID. |
|
|
||||||
| `X-Container-Id` | Base58 encoded container ID. |
|
|
||||||
| `X-Object-Id` | Base58 encoded object ID. |
|
|
||||||
|
|
||||||
###### Status codes
|
|
||||||
|
|
||||||
| Status | Description |
|
|
||||||
|--------|------------------------------------------------|
|
|
||||||
| 200 | Object got successfully. |
|
|
||||||
| 400 | Some error occurred during object downloading. |
|
|
||||||
| 404 | Container or object not found. |
|
|
||||||
|
|
||||||
###### Body
|
|
||||||
|
|
||||||
Returns object data. If request performed from browser, either displays raw data or downloads it as
|
|
||||||
attachment if `download` query parameter is set to `true`.
|
|
||||||
If `index_page.enabled` is set to `true`, returns HTML with index-page if no object with specified
|
|
||||||
S3-name was found.
|
|
||||||
|
|
||||||
#### HEAD
|
|
||||||
|
|
||||||
Get an object attributes by an address.
|
|
||||||
|
|
||||||
##### Request
|
|
||||||
|
|
||||||
###### Headers
|
|
||||||
|
|
||||||
| Header | Description |
|
|
||||||
|----------------|------------------------------------|
|
|
||||||
| Common headers | See [bearer token](#bearer-token). |
|
|
||||||
|
|
||||||
##### Response
|
|
||||||
|
|
||||||
###### Headers
|
|
||||||
|
|
||||||
| Header | Description |
|
|
||||||
|------------------------|------------------------------------------------------------------------------------------------------------------------------|
|
|
||||||
| `X-Attribute-System-*` | System FrostFS object attributes <br/> (e.g. `__SYSTEM__EXPIRATION_EPOCH` set "X-Attribute-System-Expiration-Epoch" header). |
|
|
||||||
| `X-Attribute-*` | Regular object attributes <br/> (e.g. `My-Tag` set "X-Attribute-My-Tag" header). |
|
|
||||||
| `Content-Type` | Indicate content type of object. Set from `Content-Type` attribute or detected using payload. |
|
|
||||||
| `Content-Length` | Size of object payload. |
|
|
||||||
| `Last-Modified` | Contains the `Timestamp` attribute (if exists) formatted as HTTP time (RFC7231,RFC1123). |
|
|
||||||
| `X-Owner-Id` | Base58 encoded owner ID. |
|
|
||||||
| `X-Container-Id` | Base58 encoded container ID. |
|
|
||||||
| `X-Object-Id` | Base58 encoded object ID. |
|
|
||||||
|
|
||||||
###### Status codes
|
|
||||||
|
|
||||||
| Status | Description |
|
|
||||||
|--------|---------------------------------------------------|
|
|
||||||
| 200 | Object head successfully. |
|
|
||||||
| 400 | Some error occurred during object HEAD operation. |
|
|
||||||
| 404 | Container or object not found. |
|
|
||||||
|
|
||||||
## Search object
|
|
||||||
|
|
||||||
Route: `/get_by_attribute/{cid}/{attr_key}/{attr_val}?[download=true]`
|
|
||||||
|
|
||||||
| Route parameter | Type | Description |
|
|
||||||
|-----------------|-----------|-------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
||||||
| `cid` | Single | Base58 encoded container ID or container name from NNS. |
|
|
||||||
| `attr_key` | Single | Object attribute key to search. |
|
|
||||||
| `attr_val` | Catch-All | Object attribute value to match. |
|
|
||||||
| `download` | Query | Set the `Content-Disposition` header as `attachment` in response. This make the browser to download object as file instead of showing it on the page. |
|
|
||||||
|
|
||||||
### Methods
|
|
||||||
|
|
||||||
#### GET
|
|
||||||
|
|
||||||
Find and get an object (payload and attributes) by a specific attribute.
|
|
||||||
If more than one object is found, an arbitrary one will be returned.
|
|
||||||
|
|
||||||
##### Request
|
|
||||||
|
|
||||||
###### Headers
|
|
||||||
|
|
||||||
| Header | Description |
|
|
||||||
|----------------|------------------------------------|
|
|
||||||
| Common headers | See [bearer token](#bearer-token). |
|
|
||||||
|
|
||||||
##### Response
|
|
||||||
|
|
||||||
###### Headers
|
|
||||||
|
|
||||||
| Header | Description |
|
|
||||||
|------------------------|----------------------------------------------------------------------------------------------------------------------------------------------|
|
|
||||||
| `X-Attribute-System-*` | System FrostFS object attributes <br/> (e.g. `__SYSTEM__EXPIRATION_EPOCH` set "X-Attribute-System-Expiration-Epoch" header). |
|
|
||||||
| `X-Attribute-*` | Regular object attributes <br/> (e.g. `My-Tag` set "X-Attribute-My-Tag" header). |
|
|
||||||
| `Content-Disposition` | Indicate how to browsers should treat file. <br/> Set `filename` as base part of `FileName` object attribute (if it's set, empty otherwise). |
|
|
||||||
| `Content-Type` | Indicate content type of object. Set from `Content-Type` attribute or detected using payload. |
|
|
||||||
| `Content-Length` | Size of object payload. |
|
|
||||||
| `Last-Modified` | Contains the `Timestamp` attribute (if exists) formatted as HTTP time (RFC7231,RFC1123). |
|
|
||||||
| `X-Owner-Id` | Base58 encoded owner ID. |
|
|
||||||
| `X-Container-Id` | Base58 encoded container ID. |
|
|
||||||
| `X-Object-Id` | Base58 encoded object ID. |
|
|
||||||
|
|
||||||
###### Status codes
|
|
||||||
|
|
||||||
| Status | Description |
|
|
||||||
|--------|------------------------------------------------|
|
|
||||||
| 200 | Object got successfully. |
|
|
||||||
| 400 | Some error occurred during object downloading. |
|
|
||||||
| 404 | Container or object not found. |
|
|
||||||
|
|
||||||
#### HEAD
|
|
||||||
|
|
||||||
Get object attributes by a specific attribute.
|
|
||||||
If more than one object is found, an arbitrary one will be used to get attributes.
|
|
||||||
|
|
||||||
##### Request
|
|
||||||
|
|
||||||
###### Headers
|
|
||||||
|
|
||||||
| Header | Description |
|
|
||||||
|----------------|------------------------------------|
|
|
||||||
| Common headers | See [bearer token](#bearer-token). |
|
|
||||||
|
|
||||||
##### Response
|
|
||||||
|
|
||||||
###### Headers
|
|
||||||
|
|
||||||
| Header | Description |
|
|
||||||
|------------------------|------------------------------------------------------------------------------------------------------------------------------|
|
|
||||||
| `X-Attribute-System-*` | System FrostFS object attributes <br/> (e.g. `__SYSTEM__EXPIRATION_EPOCH` set "X-Attribute-System-Expiration-Epoch" header). |
|
|
||||||
| `X-Attribute-*` | Regular object attributes <br/> (e.g. `My-Tag` set "X-Attribute-My-Tag" header). |
|
|
||||||
| `Content-Type` | Indicate content type of object. Set from `Content-Type` attribute or detected using payload. |
|
|
||||||
| `Content-Length` | Size of object payload. |
|
|
||||||
| `Last-Modified` | Contains the `Timestamp` attribute (if exists) formatted as HTTP time (RFC7231,RFC1123). |
|
|
||||||
| `X-Owner-Id` | Base58 encoded owner ID. |
|
|
||||||
| `X-Container-Id` | Base58 encoded container ID. |
|
|
||||||
| `X-Object-Id` | Base58 encoded object ID. |
|
|
||||||
|
|
||||||
###### Status codes
|
|
||||||
|
|
||||||
| Status | Description |
|
|
||||||
|--------|---------------------------------------|
|
|
||||||
| 200 | Object head successfully. |
|
|
||||||
| 400 | Some error occurred during operation. |
|
|
||||||
| 404 | Container or object not found. |
|
|
||||||
|
|
||||||
## Download archive
|
|
||||||
|
|
||||||
Route: `/zip/{cid}/{prefix}`, `/tar/{cid}/{prefix}`
|
|
||||||
|
|
||||||
| Route parameter | Type | Description |
|
|
||||||
|-----------------|-----------|---------------------------------------------------------|
|
|
||||||
| `cid` | Single | Base58 encoded container ID or container name from NNS. |
|
|
||||||
| `prefix` | Catch-All | Prefix for object attribute `FilePath` to match. |
|
|
||||||
|
|
||||||
### Methods
|
|
||||||
|
|
||||||
#### GET
|
|
||||||
|
|
||||||
Find objects by prefix for `FilePath` attributes. Return found objects in zip or tar archive.
|
|
||||||
Name of files in archive sets to `FilePath` attribute of objects.
|
|
||||||
Time of files sets to time when object has started downloading.
|
|
||||||
You can download all files in container that have `FilePath` attribute by `/zip/{cid}/` or
|
|
||||||
`/tar/{cid}/` route.
|
|
||||||
|
|
||||||
Archive can be compressed (see http-gw [configuration](gate-configuration.md#archive-section)).
|
|
||||||
|
|
||||||
##### Request
|
|
||||||
|
|
||||||
###### Headers
|
|
||||||
|
|
||||||
| Header | Description |
|
|
||||||
|----------------|------------------------------------|
|
|
||||||
| Common headers | See [bearer token](#bearer-token). |
|
|
||||||
|
|
||||||
##### Response
|
|
||||||
|
|
||||||
###### Headers
|
|
||||||
|
|
||||||
| Header | Description |
|
|
||||||
|-----------------------|-------------------------------------------------------------------------------------------------------------------|
|
|
||||||
| `Content-Disposition` | Indicate how to browsers should treat file (`attachment`). Set `filename` as `archive.zip`. |
|
|
||||||
| `Content-Type` | Indicate content type of object. Set to `application/zip` |
|
|
||||||
|
|
||||||
###### Status codes
|
|
||||||
|
|
||||||
| Status | Description |
|
|
||||||
|--------|-----------------------------------------------------|
|
|
||||||
| 200 | Object got successfully. |
|
|
||||||
| 400 | Some error occurred during object downloading. |
|
|
||||||
| 404 | Container or objects not found. |
|
|
||||||
| 500 | Some inner error (e.g. error on streaming objects). |
|
|
|
@ -1,108 +0,0 @@
|
||||||
# Request authentication
|
|
||||||
|
|
||||||
HTTP Gateway does not authorize requests. Gateway converts HTTP request to a
|
|
||||||
FrostFS request and signs it with its own private key.
|
|
||||||
|
|
||||||
You can always upload files to public containers (open for anyone to put
|
|
||||||
objects into), but for restricted containers you need to explicitly allow PUT
|
|
||||||
operations for a request signed with your HTTP Gateway keys.
|
|
||||||
|
|
||||||
If you don't want to manage gateway's secret keys and adjust policies when
|
|
||||||
gateway configuration changes (new gate, key rotation, etc) or you plan to use
|
|
||||||
public services, there is an option to let your application backend (or you) to
|
|
||||||
issue Bearer Tokens and pass them from the client via gate down to FrostFS level
|
|
||||||
to grant access.
|
|
||||||
|
|
||||||
FrostFS Bearer Token basically is a container owner-signed policy (refer to FrostFS
|
|
||||||
documentation for more details). There are two options to pass them to gateway:
|
|
||||||
* "Authorization" header with "Bearer" type and base64-encoded token in
|
|
||||||
credentials field
|
|
||||||
* "Bearer" cookie with base64-encoded token contents
|
|
||||||
|
|
||||||
For example, you have a mobile application frontend with a backend part storing
|
|
||||||
data in FrostFS. When a user authorizes in the mobile app, the backend issues a FrostFS
|
|
||||||
Bearer token and provides it to the frontend. Then, the mobile app may generate
|
|
||||||
some data and upload it via any available FrostFS HTTP Gateway by adding
|
|
||||||
the corresponding header to the upload request. Accessing policy protected data
|
|
||||||
works the same way.
|
|
||||||
|
|
||||||
##### Example
|
|
||||||
In order to generate a bearer token, you need to have wallet (which will be used to sign the token)
|
|
||||||
|
|
||||||
1. Suppose you have a container with private policy for wallet key
|
|
||||||
|
|
||||||
```
|
|
||||||
$ frostfs-cli container create -r <endpoint> --wallet <wallet> -policy <policy> --basic-acl 0 --await
|
|
||||||
CID: 9dfzyvq82JnFqp5svxcREf2iy6XNuifYcJPusEDnGK9Z
|
|
||||||
|
|
||||||
$ frostfs-cli ape-manager add -r <endpoint> --wallet <wallet> \
|
|
||||||
--target-type container --target-name 9dfzyvq82JnFqp5svxcREf2iy6XNuifYcJPusEDnGK9Z \
|
|
||||||
--rule "allow Object.* RequestCondition:"\$Actor:publicKey"=03b09baabff3f6107c7e9acb8721a6fc5618d45b50247a314d82e548702cce8cd5 *" \
|
|
||||||
--chain-id <chainID>
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
2. Form a Bearer token (10000 is lifetime expiration in epoch) to impersonate
|
|
||||||
HTTP Gateway request as wallet signed request and save it to **bearer.json**:
|
|
||||||
```
|
|
||||||
{
|
|
||||||
"body": {
|
|
||||||
"allowImpersonate": true,
|
|
||||||
"lifetime": {
|
|
||||||
"exp": "10000",
|
|
||||||
"nbf": "0",
|
|
||||||
"iat": "0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"signature": null
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
3. Sign it with the wallet:
|
|
||||||
```
|
|
||||||
$ frostfs-cli util sign bearer-token --from bearer.json --to signed.json -w <wallet>
|
|
||||||
```
|
|
||||||
|
|
||||||
4. Encode to base64 to use in header:
|
|
||||||
```
|
|
||||||
$ base64 -w 0 signed.json
|
|
||||||
# output: Ck4KKgoECAIQBhIiCiCZGdlbN7DPGPMg9rsWqV+p2XdMzUqknRiexewSFp8kmBIbChk17MUri6OJ0X5ftsHzy7NERDNFB4C92PcaGgMIkE4SZgohAxpsb7vfAso1F0X6hrm6WpRS14WsT3/Ct1SMoqRsT89KEkEEGxKi8GjKSf52YqhppgaOTQHbUsL3jn7SHLqS3ndAQ7NtAATnmRHleZw2V2xRRSRBQdjDC05KK83LhdSax72Fsw==
|
|
||||||
```
|
|
||||||
|
|
||||||
After that, the Bearer token can be used:
|
|
||||||
|
|
||||||
```
|
|
||||||
$ curl -F 'file=@cat.jpeg;filename=cat.jpeg' -H "Authorization: Bearer Ck4KKgoECAIQBhIiCiCZGdlbN7DPGPMg9rsWqV+p2XdMzUqknRiexewSFp8kmBIbChk17MUri6OJ0X5ftsHzy7NERDNFB4C92PcaGgMIkE4SZgohAxpsb7vfAso1F0X6hrm6WpRS14WsT3/Ct1SMoqRsT89KEkEEGxKi8GjKSf52YqhppgaOTQHbUsL3jn7SHLqS3ndAQ7NtAATnmRHleZw2V2xRRSRBQdjDC05KK83LhdSax72Fsw==" \
|
|
||||||
http://localhost:8082/upload/BJeErH9MWmf52VsR1mLWKkgF3pRm3FkubYxM7TZkBP4K
|
|
||||||
# output:
|
|
||||||
# {
|
|
||||||
# "object_id": "DhfES9nVrFksxGDD2jQLunGADfrXExxNwqXbDafyBn9X",
|
|
||||||
# "container_id": "BJeErH9MWmf52VsR1mLWKkgF3pRm3FkubYxM7TZkBP4K"
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
##### Note: Bearer Token owner
|
|
||||||
|
|
||||||
You can specify exact key who can use Bearer Token (gateway wallet address).
|
|
||||||
To do this, encode wallet address in base64 format
|
|
||||||
|
|
||||||
```
|
|
||||||
$ echo 'NhVtreTTCoqsMQV5Wp55fqnriiUCpEaKm3' | base58 --decode | base64
|
|
||||||
# output: NezFK4ujidF+X7bB88uzREQzRQeAvdj3Gg==
|
|
||||||
```
|
|
||||||
|
|
||||||
Then specify this value in Bearer Token Json
|
|
||||||
```
|
|
||||||
{
|
|
||||||
"body": {
|
|
||||||
"ownerID": {
|
|
||||||
"value": "NezFK4ujidF+X7bB88uzREQzRQeAvdj3Gg=="
|
|
||||||
},
|
|
||||||
...
|
|
||||||
```
|
|
||||||
|
|
||||||
##### Note: Policy override
|
|
||||||
|
|
||||||
Instead of impersonation, you can define the set of policies that will be applied
|
|
||||||
to the request sender. This allows to restrict access to specific operation and
|
|
||||||
specific objects without giving full impersonation control to the token user.
|
|
|
@ -1,6 +1,6 @@
|
||||||
# FrostFS HTTP Gateway configuration file
|
# NeoFS HTTP Gateway configuration file
|
||||||
|
|
||||||
This section contains detailed FrostFS HTTP Gateway configuration file description
|
This section contains detailed NeoFS HTTP Gateway configuration file description
|
||||||
including default config values and some tips to set up configurable values.
|
including default config values and some tips to set up configurable values.
|
||||||
|
|
||||||
There are some custom types used for brevity:
|
There are some custom types used for brevity:
|
||||||
|
@ -23,80 +23,74 @@ $ kill -s SIGHUP <app_pid>
|
||||||
Example:
|
Example:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
$ ./bin/frostfs-http-gw --config config.yaml &> http.log &
|
$ ./bin/neofs-http-gw --config config.yaml &> http.log &
|
||||||
[1] 998346
|
[1] 998346
|
||||||
|
|
||||||
$ cat http.log
|
$ cat http.log
|
||||||
# ...
|
# ...
|
||||||
2022-10-03T09:37:25.826+0300 info frostfs-http-gw/app.go:332 starting application {"app_name": "frostfs-http-gw", "version": "v0.24.0"}
|
2022-10-03T09:37:25.826+0300 info neofs-http-gw/app.go:332 starting application {"app_name": "neofs-http-gw", "version": "v0.24.0"}
|
||||||
# ...
|
# ...
|
||||||
|
|
||||||
$ kill -s SIGHUP 998346
|
$ kill -s SIGHUP 998346
|
||||||
|
|
||||||
$ cat http.log
|
$ cat http.log
|
||||||
# ...
|
# ...
|
||||||
2022-10-03T09:38:16.205+0300 info frostfs-http-gw/app.go:470 SIGHUP config reload completed
|
2022-10-03T09:38:16.205+0300 info neofs-http-gw/app.go:470 SIGHUP config reload completed
|
||||||
```
|
```
|
||||||
|
|
||||||
# Structure
|
# Structure
|
||||||
|
|
||||||
| Section | Description |
|
| Section | Description |
|
||||||
|------------------|----------------------------------------------------------------|
|
|-----------------|-------------------------------------------------------|
|
||||||
| no section | [General parameters](#general-section) |
|
| no section | [General parameters](#general-section) |
|
||||||
| `wallet` | [Wallet configuration](#wallet-section) |
|
| `wallet` | [Wallet configuration](#wallet-section) |
|
||||||
| `peers` | [Nodes configuration](#peers-section) |
|
| `peers` | [Nodes configuration](#peers-section) |
|
||||||
| `logger` | [Logger configuration](#logger-section) |
|
| `logger` | [Logger configuration](#logger-section) |
|
||||||
| `web` | [Web configuration](#web-section) |
|
| `web` | [Web configuration](#web-section) |
|
||||||
| `server` | [Server configuration](#server-section) |
|
| `upload-header` | [Upload header configuration](#upload-header-section) |
|
||||||
| `upload-header` | [Upload header configuration](#upload-header-section) |
|
| `zip` | [ZIP configuration](#zip-section) |
|
||||||
| `zip` | [ZIP configuration](#zip-section) |
|
| `pprof` | [Pprof configuration](#pprof-section) |
|
||||||
| `pprof` | [Pprof configuration](#pprof-section) |
|
| `prometheus` | [Prometheus configuration](#prometheus-section) |
|
||||||
| `prometheus` | [Prometheus configuration](#prometheus-section) |
|
|
||||||
| `tracing` | [Tracing configuration](#tracing-section) |
|
|
||||||
| `runtime` | [Runtime configuration](#runtime-section) |
|
|
||||||
| `frostfs` | [Frostfs configuration](#frostfs-section) |
|
|
||||||
| `cache` | [Cache configuration](#cache-section) |
|
|
||||||
| `resolve_bucket` | [Bucket name resolving configuration](#resolve_bucket-section) |
|
|
||||||
| `index_page` | [Index page configuration](#index_page-section) |
|
|
||||||
| `multinet` | [Multinet configuration](#multinet-section) |
|
|
||||||
| `features` | [Features configuration](#features-section) |
|
|
||||||
|
|
||||||
# General section
|
# General section
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
rpc_endpoint: http://morph-chain.frostfs.devenv:30333
|
listen_address: 0.0.0.0:8082
|
||||||
|
tls_certificate: /path/to/tls/cert
|
||||||
|
tls_key: /path/to/tls/key
|
||||||
|
|
||||||
|
rpc_endpoint: http://morph-chain.neofs.devenv:30333
|
||||||
resolve_order:
|
resolve_order:
|
||||||
- nns
|
- nns
|
||||||
- dns
|
- dns
|
||||||
|
|
||||||
connect_timeout: 5s
|
connect_timeout: 5s
|
||||||
stream_timeout: 10s
|
stream_timeout: 10s
|
||||||
request_timeout: 5s
|
request_timeout: 5s
|
||||||
rebalance_timer: 30s
|
rebalance_timer: 30s
|
||||||
pool_error_threshold: 100
|
pool_error_threshold: 100
|
||||||
reconnect_interval: 1m
|
|
||||||
worker_pool_size: 1000
|
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
| Parameter | Type | SIGHUP reload | Default value | Description |
|
| Parameter | Type | SIGHUP reload | Default value | Description |
|
||||||
|------------------------|------------|---------------|---------------|------------------------------------------------------------------------------------|
|
|------------------------|------------|---------------|----------------|------------------------------------------------------------------------------------|
|
||||||
| `rpc_endpoint` | `string` | yes | | The address of the RPC host to which the gateway connects to resolve bucket names. |
|
| `listen_address` | `string` | | `0.0.0.0:8082` | The address that the gateway is listening on. |
|
||||||
| `resolve_order` | `[]string` | yes | `[nns, dns]` | Order of bucket name resolvers to use. |
|
| `tls_certificate` | `string` | yes | | Path to the TLS certificate. |
|
||||||
| `connect_timeout` | `duration` | | `10s` | Timeout to connect to a node. |
|
| `tls_key` | `string` | yes | | Path to the TLS key. |
|
||||||
| `stream_timeout` | `duration` | | `10s` | Timeout for individual operations in streaming RPC. |
|
| `rpc_endpoint` | `string` | yes | | The address of the RPC host to which the gateway connects to resolve bucket names. |
|
||||||
| `request_timeout` | `duration` | | `15s` | Timeout to check node health during rebalance. |
|
| `resolve_order` | `[]string` | yes | `[nns, dns]` | Order of bucket name resolvers to use. |
|
||||||
| `rebalance_timer` | `duration` | | `60s` | Interval to check node health. |
|
| `connect_timeout` | `duration` | | `10s` | Timeout to connect to a node. |
|
||||||
| `pool_error_threshold` | `uint32` | | `100` | The number of errors on connection after which node is considered as unhealthy. |
|
| `stream_timeout` | `duration` | | `10s` | Timeout for individual operations in streaming RPC. |
|
||||||
| `reconnect_interval` | `duration` | no | `1m` | Listeners reconnection interval. |
|
| `request_timeout` | `duration` | | `15s` | Timeout to check node health during rebalance. |
|
||||||
| `worker_pool_size` | `int` | no | `1000` | Maximum worker count in handler's worker pool. |
|
| `rebalance_timer` | `duration` | | `60s` | Interval to check node health. |
|
||||||
|
| `pool_error_threshold` | `uint32` | | `100` | The number of errors on connection after which node is considered as unhealthy. |
|
||||||
|
|
||||||
# `wallet` section
|
# `wallet` section
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
wallet:
|
wallet:
|
||||||
path: /path/to/wallet.json
|
path: /path/to/wallet.json
|
||||||
address: NfgHwwTi3wHAS8aFAN243C5vGbkYDpqLHP
|
address: NfgHwwTi3wHAS8aFAN243C5vGbkYDpqLHP
|
||||||
passphrase: pwd
|
passphrase: pwd
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -110,23 +104,23 @@ wallet:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
# Nodes configuration
|
# Nodes configuration
|
||||||
# This configuration makes the gateway use the first node (node1.frostfs:8080)
|
# This configuration makes the gateway use the first node (node1.neofs:8080)
|
||||||
# while it's healthy. Otherwise, gateway uses the second node (node2.frostfs:8080)
|
# while it's healthy. Otherwise, gateway uses the second node (node2.neofs:8080)
|
||||||
# for 10% of requests and the third node (node3.frostfs:8080) for 90% of requests.
|
# for 10% of requests and the third node (node3.neofs:8080) for 90% of requests.
|
||||||
# Until nodes with the same priority level are healthy
|
# Until nodes with the same priority level are healthy
|
||||||
# nodes with other priority are not used.
|
# nodes with other priority are not used.
|
||||||
# The lower the value, the higher the priority.
|
# The lower the value, the higher the priority.
|
||||||
peers:
|
peers:
|
||||||
0:
|
0:
|
||||||
address: node1.frostfs:8080
|
address: node1.neofs:8080
|
||||||
priority: 1
|
priority: 1
|
||||||
weight: 1
|
weight: 1
|
||||||
1:
|
1:
|
||||||
address: node2.frostfs:8080
|
address: node2.neofs:8080
|
||||||
priority: 2
|
priority: 2
|
||||||
weight: 0.1
|
weight: 0.1
|
||||||
2:
|
2:
|
||||||
address: node3.frostfs:8080
|
address: node3.neofs:8080
|
||||||
priority: 2
|
priority: 2
|
||||||
weight: 0.9
|
weight: 0.9
|
||||||
```
|
```
|
||||||
|
@ -137,82 +131,17 @@ peers:
|
||||||
| `priority` | `int` | `1` | It allows to group nodes and don't switch group until all nodes with the same priority will be unhealthy. The lower the value, the higher the priority. |
|
| `priority` | `int` | `1` | It allows to group nodes and don't switch group until all nodes with the same priority will be unhealthy. The lower the value, the higher the priority. |
|
||||||
| `weight` | `float` | `1` | Weight of node in the group with the same priority. Distribute requests to nodes proportionally to these values. |
|
| `weight` | `float` | `1` | Weight of node in the group with the same priority. Distribute requests to nodes proportionally to these values. |
|
||||||
|
|
||||||
# `server` section
|
|
||||||
|
|
||||||
You can specify several listeners for server. For example, for `http` and `https`.
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
server:
|
|
||||||
- address: 0.0.0.0:8080
|
|
||||||
tls:
|
|
||||||
enabled: false
|
|
||||||
cert_file: /path/to/cert
|
|
||||||
key_file: /path/to/key
|
|
||||||
- address: 0.0.0.0:8081
|
|
||||||
tls:
|
|
||||||
enabled: true
|
|
||||||
cert_file: /path/to/another/cert
|
|
||||||
key_file: /path/to/another/key
|
|
||||||
```
|
|
||||||
|
|
||||||
| Parameter | Type | SIGHUP reload | Default value | Description |
|
|
||||||
|-----------------|----------|---------------|----------------|-----------------------------------------------|
|
|
||||||
| `address` | `string` | | `0.0.0.0:8080` | The address that the gateway is listening on. |
|
|
||||||
| `tls.enabled` | `bool` | | false | Enable TLS or not. |
|
|
||||||
| `tls.cert_file` | `string` | yes | | Path to the TLS certificate. |
|
|
||||||
| `tls.key_file` | `string` | yes | | Path to the key. |
|
|
||||||
|
|
||||||
|
|
||||||
# `logger` section
|
# `logger` section
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
logger:
|
logger:
|
||||||
level: debug
|
level: debug
|
||||||
destination: stdout
|
|
||||||
sampling:
|
|
||||||
enabled: false
|
|
||||||
initial: 100
|
|
||||||
thereafter: 100
|
|
||||||
interval: 1s
|
|
||||||
tags:
|
|
||||||
- name: "app"
|
|
||||||
level: info
|
|
||||||
- name: "datapath"
|
|
||||||
- name: "external_storage_tree"
|
|
||||||
```
|
```
|
||||||
|
|
||||||
| Parameter | Type | SIGHUP reload | Default value | Description |
|
| Parameter | Type | SIGHUP reload | Default value | Description |
|
||||||
|-----------------------|------------|---------------|---------------|----------------------------------------------------------------------------------------------------|
|
|-----------|----------|---------------|---------------|----------------------------------------------------------------------------------------------------|
|
||||||
| `level` | `string` | yes | `debug` | Logging level.<br/>Possible values: `debug`, `info`, `warn`, `error`, `dpanic`, `panic`, `fatal`. |
|
| `level` | `string` | yes | `debug` | Logging level.<br/>Possible values: `debug`, `info`, `warn`, `error`, `dpanic`, `panic`, `fatal`. |
|
||||||
| `destination` | `string` | no | `stdout` | Destination for logger: `stdout` or `journald` |
|
|
||||||
| `sampling.enabled` | `bool` | no | false | Sampling enabling flag. |
|
|
||||||
| `sampling.initial` | `int` | no | '100' | Sampling count of first log entries. |
|
|
||||||
| `sampling.thereafter` | `int` | no | '100' | Sampling count of entries after an `interval`. |
|
|
||||||
| `sampling.interval` | `duration` | no | '1s' | Sampling interval of messaging similar entries. |
|
|
||||||
| `sampling.tags` | `[]Tag` | yes | | Tagged log entries that should be additionally logged (available tags see in the next section). |
|
|
||||||
|
|
||||||
## Tags
|
|
||||||
|
|
||||||
There are additional log entries that can hurt performance and can be additionally logged by using `logger.tags`
|
|
||||||
parameter. Available tags:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
tags:
|
|
||||||
- name: "app"
|
|
||||||
level: info
|
|
||||||
```
|
|
||||||
|
|
||||||
| Parameter | Type | SIGHUP reload | Default value | Description |
|
|
||||||
|-----------------------|------------|---------------|---------------------------|-------------------------------------------------------------------------------------------------------|
|
|
||||||
| `name` | `string` | yes | | Tag name. Possible values see below in `Tag values` section. |
|
|
||||||
| `level` | `string` | yes | Value from `logger.level` | Logging level for specific tag. Possible values: `debug`, `info`, `warn`, `dpanic`, `panic`, `fatal`. |
|
|
||||||
|
|
||||||
### Tag values
|
|
||||||
|
|
||||||
* `app` - common application logs (enabled by default).
|
|
||||||
* `datapath` - main logic of application (enabled by default).
|
|
||||||
* `external_storage` - external interaction with storage node (enabled by default).
|
|
||||||
* `external_storage_tree` - external interaction with tree service in storage node (enabled by default).
|
|
||||||
|
|
||||||
# `web` section
|
# `web` section
|
||||||
|
|
||||||
|
@ -247,30 +176,18 @@ upload_header:
|
||||||
|-------------------------|--------|---------------|---------------|-------------------------------------------------------------|
|
|-------------------------|--------|---------------|---------------|-------------------------------------------------------------|
|
||||||
| `use_default_timestamp` | `bool` | yes | `false` | Create timestamp for object if it isn't provided by header. |
|
| `use_default_timestamp` | `bool` | yes | `false` | Create timestamp for object if it isn't provided by header. |
|
||||||
|
|
||||||
# `zip` section
|
|
||||||
|
|
||||||
> **_DEPRECATED:_** Use archive section instead
|
# `zip` section
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
zip:
|
zip:
|
||||||
compression: false
|
compression: false
|
||||||
```
|
```
|
||||||
|
|
||||||
| Parameter | Type | SIGHUP reload | Default value | Description |
|
| Parameter | Type | SIGHUP reload | Default value | Description |
|
||||||
|---------------|--------|---------------|---------------|--------------------------------------------------------------|
|
|---------------|--------|---------------|---------------|--------------------------------------------------------------|
|
||||||
| `compression` | `bool` | yes | `false` | Enable zip compression when download files by common prefix. |
|
| `compression` | `bool` | yes | `false` | Enable zip compression when download files by common prefix. |
|
||||||
|
|
||||||
# `archive` section
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
archive:
|
|
||||||
compression: false
|
|
||||||
```
|
|
||||||
|
|
||||||
| Parameter | Type | SIGHUP reload | Default value | Description |
|
|
||||||
|---------------|--------|---------------|---------------|------------------------------------------------------------------|
|
|
||||||
| `compression` | `bool` | yes | `false` | Enable archive compression when download files by common prefix. |
|
|
||||||
|
|
||||||
|
|
||||||
# `pprof` section
|
# `pprof` section
|
||||||
|
|
||||||
|
@ -301,217 +218,3 @@ prometheus:
|
||||||
|-----------|----------|---------------|------------------|-----------------------------------------|
|
|-----------|----------|---------------|------------------|-----------------------------------------|
|
||||||
| `enabled` | `bool` | yes | `false` | Flag to enable the service. |
|
| `enabled` | `bool` | yes | `false` | Flag to enable the service. |
|
||||||
| `address` | `string` | yes | `localhost:8084` | Address that service listener binds to. |
|
| `address` | `string` | yes | `localhost:8084` | Address that service listener binds to. |
|
||||||
|
|
||||||
# `tracing` section
|
|
||||||
|
|
||||||
Contains configuration for the `tracing` service.
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
tracing:
|
|
||||||
enabled: true
|
|
||||||
exporter: "otlp_grpc"
|
|
||||||
endpoint: "localhost:4317"
|
|
||||||
trusted_ca: "/etc/ssl/telemetry-trusted-ca.pem"
|
|
||||||
attributes:
|
|
||||||
- key: key0
|
|
||||||
value: value
|
|
||||||
- key: key1
|
|
||||||
value: value
|
|
||||||
```
|
|
||||||
|
|
||||||
| Parameter | Type | SIGHUP reload | Default value | Description |
|
|
||||||
| ------------ | -------------------------------------- | ------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------- |
|
|
||||||
| `enabled` | `bool` | yes | `false` | Flag to enable the tracing. |
|
|
||||||
| `exporter` | `string` | yes | | Trace collector type (`stdout` or `otlp_grpc` are supported). |
|
|
||||||
| `endpoint` | `string` | yes | | Address of collector endpoint for OTLP exporters. |
|
|
||||||
| `trusted_ca` | `string` | yes | | Path to certificate of a certification authority in pem format, that issued the TLS certificate of the telemetry remote server. |
|
|
||||||
| `attributes` | [[]Attributes](#attributes-subsection) | yes | | An array of configurable attributes in key-value format. |
|
|
||||||
|
|
||||||
|
|
||||||
#### `attributes` subsection
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
attributes:
|
|
||||||
- key: key0
|
|
||||||
value: value
|
|
||||||
- key: key1
|
|
||||||
value: value
|
|
||||||
```
|
|
||||||
|
|
||||||
| Parameter | Type | SIGHUP reload | Default value | Description |
|
|
||||||
|-----------------------|----------|---------------|---------------|----------------------------------------------------------|
|
|
||||||
| `key` | `string` | yes | | Attribute key. |
|
|
||||||
| `value` | `string` | yes | | Attribute value. |
|
|
||||||
|
|
||||||
# `runtime` section
|
|
||||||
Contains runtime parameters.
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
runtime:
|
|
||||||
soft_memory_limit: 1gb
|
|
||||||
```
|
|
||||||
|
|
||||||
| Parameter | Type | SIGHUP reload | Default value | Description |
|
|
||||||
|---------------------|--------|---------------|---------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
||||||
| `soft_memory_limit` | `size` | yes | maxint64 | Soft memory limit for the runtime. Zero or no value stands for no limit. If `GOMEMLIMIT` environment variable is set, the value from the configuration file will be ignored. |
|
|
||||||
|
|
||||||
# `frostfs` section
|
|
||||||
|
|
||||||
Contains parameters of requests to FrostFS.
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
frostfs:
|
|
||||||
client_cut: false
|
|
||||||
buffer_max_size_for_put: 1048576 # 1mb
|
|
||||||
tree_pool_max_attempts: 0
|
|
||||||
```
|
|
||||||
|
|
||||||
| Parameter | Type | SIGHUP reload | Default value | Description |
|
|
||||||
|---------------------------|----------|---------------|---------------|---------------------------------------------------------------------------------------------------------------------------|
|
|
||||||
| `client_cut` | `bool` | yes | `false` | This flag enables client side object preparing. |
|
|
||||||
| `buffer_max_size_for_put` | `uint64` | yes | `1048576` | Sets max buffer size for read payload in put operations. |
|
|
||||||
| `tree_pool_max_attempts` | `uint32` | no | `0` | Sets max attempt to make successful tree request. Value 0 means the number of attempts equals to number of nodes in pool. |
|
|
||||||
|
|
||||||
|
|
||||||
### `cache` section
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
cache:
|
|
||||||
buckets:
|
|
||||||
lifetime: 1m
|
|
||||||
size: 1000
|
|
||||||
netmap:
|
|
||||||
lifetime: 1m
|
|
||||||
```
|
|
||||||
|
|
||||||
| Parameter | Type | Default value | Description |
|
|
||||||
|-----------|-----------------------------------|---------------------------------|---------------------------------------------------------------------------|
|
|
||||||
| `buckets` | [Cache config](#cache-subsection) | `lifetime: 60s`<br>`size: 1000` | Cache which contains mapping of bucket name to bucket info. |
|
|
||||||
| `netmap` | [Cache config](#cache-subsection) | `lifetime: 1m` | Cache which stores netmap. `netmap.size` isn't applicable for this cache. |
|
|
||||||
|
|
||||||
|
|
||||||
#### `cache` subsection
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
lifetime: 1m
|
|
||||||
size: 1000
|
|
||||||
```
|
|
||||||
|
|
||||||
| Parameter | Type | Default value | Description |
|
|
||||||
|------------|------------|------------------|-------------------------------|
|
|
||||||
| `lifetime` | `duration` | depends on cache | Lifetime of entries in cache. |
|
|
||||||
| `size` | `int` | depends on cache | LRU cache size. |
|
|
||||||
|
|
||||||
|
|
||||||
# `resolve_bucket` section
|
|
||||||
|
|
||||||
Bucket name resolving parameters from and to container ID.
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
resolve_bucket:
|
|
||||||
namespace_header: X-Frostfs-Namespace
|
|
||||||
default_namespaces: [ "", "root" ]
|
|
||||||
```
|
|
||||||
|
|
||||||
| Parameter | Type | SIGHUP reload | Default value | Description |
|
|
||||||
|----------------------|------------|---------------|-----------------------|--------------------------------------------------------------------------------------------------------------------------|
|
|
||||||
| `namespace_header` | `string` | yes | `X-Frostfs-Namespace` | Header to determine zone to resolve bucket name. |
|
|
||||||
| `default_namespaces` | `[]string` | yes | ["","root"] | Namespaces that should be handled as default. |
|
|
||||||
|
|
||||||
# `index_page` section
|
|
||||||
|
|
||||||
Parameters for index HTML-page output. Activates if `GetObject` request returns `not found`. Two
|
|
||||||
index page modes available:
|
|
||||||
|
|
||||||
* `s3` mode uses tree service for listing objects,
|
|
||||||
* `native` sends requests to nodes via native protocol.
|
|
||||||
If request pass S3-bucket name instead of CID, `s3` mode will be used, otherwise `native`.
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
index_page:
|
|
||||||
enabled: false
|
|
||||||
template_path: ""
|
|
||||||
```
|
|
||||||
|
|
||||||
| Parameter | Type | SIGHUP reload | Default value | Description |
|
|
||||||
|-----------------|----------|---------------|---------------|---------------------------------------------------------------------------------|
|
|
||||||
| `enabled` | `bool` | yes | `false` | Flag to enable index_page return if no object with specified S3-name was found. |
|
|
||||||
| `template_path` | `string` | yes | `""` | Path to .gotmpl file with html template for index_page. |
|
|
||||||
|
|
||||||
# `cors` section
|
|
||||||
|
|
||||||
Parameters for CORS (used in OPTIONS requests and responses in all handlers).
|
|
||||||
If values are not set, headers will not be included to response.
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
cors:
|
|
||||||
allow_origin: "*"
|
|
||||||
allow_methods: ["GET", "HEAD"]
|
|
||||||
allow_headers: ["Authorization"]
|
|
||||||
expose_headers: ["*"]
|
|
||||||
allow_credentials: false
|
|
||||||
max_age: 600
|
|
||||||
```
|
|
||||||
|
|
||||||
| Parameter | Type | SIGHUP reload | Default value | Description |
|
|
||||||
|---------------------|------------|---------------|---------------|--------------------------------------------------------|
|
|
||||||
| `allow_origin` | `string` | yes | | Values for `Access-Control-Allow-Origin` headers. |
|
|
||||||
| `allow_methods` | `[]string` | yes | | Values for `Access-Control-Allow-Methods` headers. |
|
|
||||||
| `allow_headers` | `[]string` | yes | | Values for `Access-Control-Allow-Headers` headers. |
|
|
||||||
| `expose_headers` | `[]string` | yes | | Values for `Access-Control-Expose-Headers` headers. |
|
|
||||||
| `allow_credentials` | `bool` | yes | `false` | Values for `Access-Control-Allow-Credentials` headers. |
|
|
||||||
| `max_age` | `int` | yes | `600` | Values for `Access-Control-Max-Age ` headers. |
|
|
||||||
|
|
||||||
# `multinet` section
|
|
||||||
|
|
||||||
Configuration of multinet support.
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
multinet:
|
|
||||||
enabled: false
|
|
||||||
balancer: roundrobin
|
|
||||||
restrict: false
|
|
||||||
fallback_delay: 300ms
|
|
||||||
subnets:
|
|
||||||
- mask: 1.2.3.4/24
|
|
||||||
source_ips:
|
|
||||||
- 1.2.3.4
|
|
||||||
- 1.2.3.5
|
|
||||||
```
|
|
||||||
|
|
||||||
| Parameter | Type | SIGHUP reload | Default value | Description |
|
|
||||||
|------------------|--------------------------------|---------------|---------------|--------------------------------------------------------------------------------------------|
|
|
||||||
| `enabled` | `bool` | yes | `false` | Enables multinet setting to manage source ip of outcoming requests. |
|
|
||||||
| `balancer` | `string` | yes | `""` | Strategy to pick source IP. By default picks first address. Supports `roundrobin` setting. |
|
|
||||||
| `restrict` | `bool` | yes | `false` | Restricts requests to an undefined subnets. |
|
|
||||||
| `fallback_delay` | `duration` | yes | `300ms` | Delay between IPv6 and IPv4 fallback stack switch. |
|
|
||||||
| `subnets` | [[]Subnet](#subnet-subsection) | yes | | Set of subnets to apply multinet dial settings. |
|
|
||||||
|
|
||||||
#### `subnet` subsection
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
- mask: 1.2.3.4/24
|
|
||||||
source_ips:
|
|
||||||
- 1.2.3.4
|
|
||||||
- 1.2.3.5
|
|
||||||
```
|
|
||||||
|
|
||||||
| Parameter | Type | SIGHUP reload | Default value | Description |
|
|
||||||
|--------------|------------|---------------|---------------|----------------------------------------------------------------------|
|
|
||||||
| `mask` | `string` | yes | | Destination subnet. |
|
|
||||||
| `source_ips` | `[]string` | yes | | Array of source IP addresses to use when dialing destination subnet. |
|
|
||||||
|
|
||||||
# `features` section
|
|
||||||
|
|
||||||
Contains parameters for enabling features.
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
features:
|
|
||||||
enable_filepath_fallback: true
|
|
||||||
tree_pool_netmap_support: true
|
|
||||||
```
|
|
||||||
|
|
||||||
| Parameter | Type | SIGHUP reload | Default value | Description |
|
|
||||||
|-------------------------------------|--------|---------------|---------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
||||||
| `features.enable_filepath_fallback` | `bool` | yes | `false` | Enable using fallback path to search for a object by attribute. If the value of the `FilePath` attribute in the request contains no `/` symbols or single leading `/` symbol and the object was not found, then an attempt is made to search for the object by the attribute `FileName`. |
|
|
||||||
| `features.tree_pool_netmap_support` | `bool` | no | `false` | Enable using new version of tree pool, which uses netmap to select nodes, for requests to tree service. |
|
|
||||||
|
|
36
docs/nns.md
36
docs/nns.md
|
@ -1,36 +0,0 @@
|
||||||
# Nicename Resolving with NNS
|
|
||||||
|
|
||||||
Steps to start using name resolving:
|
|
||||||
|
|
||||||
1. Enable NNS resolving in config (`rpc_endpoint` must be a valid neo rpc node, see [configs](./config) for other examples):
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
rpc_endpoint: http://morph-chain.frostfs.devenv:30333
|
|
||||||
resolve_order:
|
|
||||||
- nns
|
|
||||||
```
|
|
||||||
|
|
||||||
2. Make sure your container is registered in NNS contract. If you use [frostfs-dev-env](https://git.frostfs.info/TrueCloudLab/frostfs-dev-env)
|
|
||||||
you can check if your container (e.g. with `container-name` name) is registered in NNS:
|
|
||||||
|
|
||||||
```shell
|
|
||||||
$ curl -s --data '{"id":1,"jsonrpc":"2.0","method":"getcontractstate","params":[1]}' \
|
|
||||||
http://morph-chain.frostfs.devenv:30333 | jq -r '.result.hash'
|
|
||||||
|
|
||||||
0x8e6c3cd4b976b28e84a3788f6ea9e2676c15d667
|
|
||||||
|
|
||||||
$ docker exec -it morph_chain neo-go \
|
|
||||||
contract testinvokefunction \
|
|
||||||
-r http://morph-chain.frostfs.devenv:30333 0x8e6c3cd4b976b28e84a3788f6ea9e2676c15d667 \
|
|
||||||
resolve string:container-name.container int:16 \
|
|
||||||
| jq -r '.stack[0].value | if type=="array" then .[0].value else . end' \
|
|
||||||
| base64 -d && echo
|
|
||||||
|
|
||||||
7f3vvkw4iTiS5ZZbu5BQXEmJtETWbi3uUjLNaSs29xrL
|
|
||||||
```
|
|
||||||
|
|
||||||
3. Use container name instead of its `$CID`. For example:
|
|
||||||
|
|
||||||
```shell
|
|
||||||
$ curl http://localhost:8082/get_by_attribute/container-name/FileName/object-name
|
|
||||||
```
|
|
534
downloader/download.go
Normal file
534
downloader/download.go
Normal file
|
@ -0,0 +1,534 @@
|
||||||
|
package downloader
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"bufio"
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"path"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/nspcc-dev/neofs-http-gw/resolver"
|
||||||
|
"github.com/nspcc-dev/neofs-http-gw/response"
|
||||||
|
"github.com/nspcc-dev/neofs-http-gw/tokens"
|
||||||
|
"github.com/nspcc-dev/neofs-http-gw/utils"
|
||||||
|
"github.com/nspcc-dev/neofs-sdk-go/bearer"
|
||||||
|
"github.com/nspcc-dev/neofs-sdk-go/client"
|
||||||
|
"github.com/nspcc-dev/neofs-sdk-go/container"
|
||||||
|
cid "github.com/nspcc-dev/neofs-sdk-go/container/id"
|
||||||
|
"github.com/nspcc-dev/neofs-sdk-go/object"
|
||||||
|
oid "github.com/nspcc-dev/neofs-sdk-go/object/id"
|
||||||
|
"github.com/nspcc-dev/neofs-sdk-go/pool"
|
||||||
|
"github.com/valyala/fasthttp"
|
||||||
|
"go.uber.org/atomic"
|
||||||
|
"go.uber.org/zap"
|
||||||
|
)
|
||||||
|
|
||||||
|
type request struct {
|
||||||
|
*fasthttp.RequestCtx
|
||||||
|
appCtx context.Context
|
||||||
|
log *zap.Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
func isValidToken(s string) bool {
|
||||||
|
for _, c := range s {
|
||||||
|
if c <= ' ' || c > 127 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if strings.ContainsRune("()<>@,;:\\\"/[]?={}", c) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func isValidValue(s string) bool {
|
||||||
|
for _, c := range s {
|
||||||
|
// HTTP specification allows for more technically, but we don't want to escape things.
|
||||||
|
if c < ' ' || c > 127 || c == '"' {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
type readCloser struct {
|
||||||
|
io.Reader
|
||||||
|
io.Closer
|
||||||
|
}
|
||||||
|
|
||||||
|
// initializes io.Reader with the limited size and detects Content-Type from it.
|
||||||
|
// Returns r's error directly. Also returns the processed data.
|
||||||
|
func readContentType(maxSize uint64, rInit func(uint64) (io.Reader, error)) (string, []byte, error) {
|
||||||
|
if maxSize > sizeToDetectType {
|
||||||
|
maxSize = sizeToDetectType
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := make([]byte, maxSize) // maybe sync-pool the slice?
|
||||||
|
|
||||||
|
r, err := rInit(maxSize)
|
||||||
|
if err != nil {
|
||||||
|
return "", nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err := r.Read(buf)
|
||||||
|
if err != nil && err != io.EOF {
|
||||||
|
return "", nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
buf = buf[:n]
|
||||||
|
|
||||||
|
return http.DetectContentType(buf), buf, err // to not lose io.EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r request) receiveFile(clnt *pool.Pool, objectAddress oid.Address) {
|
||||||
|
var (
|
||||||
|
err error
|
||||||
|
dis = "inline"
|
||||||
|
start = time.Now()
|
||||||
|
filename string
|
||||||
|
)
|
||||||
|
if err = tokens.StoreBearerToken(r.RequestCtx); err != nil {
|
||||||
|
r.log.Error("could not fetch and store bearer token", zap.Error(err))
|
||||||
|
response.Error(r.RequestCtx, "could not fetch and store bearer token: "+err.Error(), fasthttp.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var prm pool.PrmObjectGet
|
||||||
|
prm.SetAddress(objectAddress)
|
||||||
|
if btoken := bearerToken(r.RequestCtx); btoken != nil {
|
||||||
|
prm.UseBearer(*btoken)
|
||||||
|
}
|
||||||
|
|
||||||
|
rObj, err := clnt.GetObject(r.appCtx, prm)
|
||||||
|
if err != nil {
|
||||||
|
r.handleNeoFSErr(err, start)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// we can't close reader in this function, so how to do it?
|
||||||
|
|
||||||
|
if r.Request.URI().QueryArgs().GetBool("download") {
|
||||||
|
dis = "attachment"
|
||||||
|
}
|
||||||
|
|
||||||
|
payloadSize := rObj.Header.PayloadSize()
|
||||||
|
|
||||||
|
r.Response.Header.Set(fasthttp.HeaderContentLength, strconv.FormatUint(payloadSize, 10))
|
||||||
|
var contentType string
|
||||||
|
for _, attr := range rObj.Header.Attributes() {
|
||||||
|
key := attr.Key()
|
||||||
|
val := attr.Value()
|
||||||
|
if !isValidToken(key) || !isValidValue(val) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(key, utils.SystemAttributePrefix) {
|
||||||
|
key = systemBackwardTranslator(key)
|
||||||
|
}
|
||||||
|
r.Response.Header.Set(utils.UserAttributeHeaderPrefix+key, val)
|
||||||
|
switch key {
|
||||||
|
case object.AttributeFileName:
|
||||||
|
filename = val
|
||||||
|
case object.AttributeTimestamp:
|
||||||
|
value, err := strconv.ParseInt(val, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
r.log.Info("couldn't parse creation date",
|
||||||
|
zap.String("key", key),
|
||||||
|
zap.String("val", val),
|
||||||
|
zap.Error(err))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
r.Response.Header.Set(fasthttp.HeaderLastModified,
|
||||||
|
time.Unix(value, 0).UTC().Format(http.TimeFormat))
|
||||||
|
case object.AttributeContentType:
|
||||||
|
contentType = val
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
idsToResponse(&r.Response, &rObj.Header)
|
||||||
|
|
||||||
|
if len(contentType) == 0 {
|
||||||
|
// determine the Content-Type from the payload head
|
||||||
|
var payloadHead []byte
|
||||||
|
|
||||||
|
contentType, payloadHead, err = readContentType(payloadSize, func(uint64) (io.Reader, error) {
|
||||||
|
return rObj.Payload, nil
|
||||||
|
})
|
||||||
|
if err != nil && err != io.EOF {
|
||||||
|
r.log.Error("could not detect Content-Type from payload", zap.Error(err))
|
||||||
|
response.Error(r.RequestCtx, "could not detect Content-Type from payload: "+err.Error(), fasthttp.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// reset payload reader since a part of the data has been read
|
||||||
|
var headReader io.Reader = bytes.NewReader(payloadHead)
|
||||||
|
|
||||||
|
if err != io.EOF { // otherwise, we've already read full payload
|
||||||
|
headReader = io.MultiReader(headReader, rObj.Payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
// note: we could do with io.Reader, but SetBodyStream below closes body stream
|
||||||
|
// if it implements io.Closer and that's useful for us.
|
||||||
|
rObj.Payload = readCloser{headReader, rObj.Payload}
|
||||||
|
}
|
||||||
|
r.SetContentType(contentType)
|
||||||
|
|
||||||
|
r.Response.Header.Set(fasthttp.HeaderContentDisposition, dis+"; filename="+path.Base(filename))
|
||||||
|
|
||||||
|
r.Response.SetBodyStream(rObj.Payload, int(payloadSize))
|
||||||
|
}
|
||||||
|
|
||||||
|
// systemBackwardTranslator is used to convert headers looking like '__NEOFS__ATTR_NAME' to 'Neofs-Attr-Name'.
|
||||||
|
func systemBackwardTranslator(key string) string {
|
||||||
|
// trim specified prefix '__NEOFS__'
|
||||||
|
key = strings.TrimPrefix(key, utils.SystemAttributePrefix)
|
||||||
|
|
||||||
|
var res strings.Builder
|
||||||
|
res.WriteString("Neofs-")
|
||||||
|
|
||||||
|
strs := strings.Split(key, "_")
|
||||||
|
for i, s := range strs {
|
||||||
|
s = title(strings.ToLower(s))
|
||||||
|
res.WriteString(s)
|
||||||
|
if i != len(strs)-1 {
|
||||||
|
res.WriteString("-")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func title(str string) string {
|
||||||
|
if str == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
r, size := utf8.DecodeRuneInString(str)
|
||||||
|
r0 := unicode.ToTitle(r)
|
||||||
|
return string(r0) + str[size:]
|
||||||
|
}
|
||||||
|
|
||||||
|
func bearerToken(ctx context.Context) *bearer.Token {
|
||||||
|
if tkn, err := tokens.LoadBearerToken(ctx); err == nil {
|
||||||
|
return tkn
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *request) handleNeoFSErr(err error, start time.Time) {
|
||||||
|
r.log.Error(
|
||||||
|
"could not receive object",
|
||||||
|
zap.Stringer("elapsed", time.Since(start)),
|
||||||
|
zap.Error(err),
|
||||||
|
)
|
||||||
|
|
||||||
|
if client.IsErrObjectNotFound(err) || client.IsErrContainerNotFound(err) {
|
||||||
|
response.Error(r.RequestCtx, "Not Found", fasthttp.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
msg := fmt.Sprintf("could not receive object: %v", err)
|
||||||
|
response.Error(r.RequestCtx, msg, fasthttp.StatusBadRequest)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Downloader is a download request handler.
|
||||||
|
type Downloader struct {
|
||||||
|
appCtx context.Context
|
||||||
|
log *zap.Logger
|
||||||
|
pool *pool.Pool
|
||||||
|
containerResolver *resolver.ContainerResolver
|
||||||
|
settings *Settings
|
||||||
|
}
|
||||||
|
|
||||||
|
// Settings stores reloading parameters, so it has to provide atomic getters and setters.
|
||||||
|
type Settings struct {
|
||||||
|
zipCompression atomic.Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Settings) ZipCompression() bool {
|
||||||
|
return s.zipCompression.Load()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Settings) SetZipCompression(val bool) {
|
||||||
|
s.zipCompression.Store(val)
|
||||||
|
}
|
||||||
|
|
||||||
|
// New creates an instance of Downloader using specified options.
|
||||||
|
func New(ctx context.Context, params *utils.AppParams, settings *Settings) *Downloader {
|
||||||
|
return &Downloader{
|
||||||
|
appCtx: ctx,
|
||||||
|
log: params.Logger,
|
||||||
|
pool: params.Pool,
|
||||||
|
settings: settings,
|
||||||
|
containerResolver: params.Resolver,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Downloader) newRequest(ctx *fasthttp.RequestCtx, log *zap.Logger) *request {
|
||||||
|
return &request{
|
||||||
|
RequestCtx: ctx,
|
||||||
|
appCtx: d.appCtx,
|
||||||
|
log: log,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// DownloadByAddress handles download requests using simple cid/oid format.
|
||||||
|
func (d *Downloader) DownloadByAddress(c *fasthttp.RequestCtx) {
|
||||||
|
d.byAddress(c, request.receiveFile)
|
||||||
|
}
|
||||||
|
|
||||||
|
// byAddress is a wrapper for function (e.g. request.headObject, request.receiveFile) that
|
||||||
|
// prepares request and object address to it.
|
||||||
|
func (d *Downloader) byAddress(c *fasthttp.RequestCtx, f func(request, *pool.Pool, oid.Address)) {
|
||||||
|
var (
|
||||||
|
idCnr, _ = c.UserValue("cid").(string)
|
||||||
|
idObj, _ = c.UserValue("oid").(string)
|
||||||
|
log = d.log.With(zap.String("cid", idCnr), zap.String("oid", idObj))
|
||||||
|
)
|
||||||
|
|
||||||
|
cnrID, err := utils.GetContainerID(d.appCtx, idCnr, d.containerResolver)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("wrong container id", zap.Error(err))
|
||||||
|
response.Error(c, "wrong container id", fasthttp.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
objID := new(oid.ID)
|
||||||
|
if err = objID.DecodeString(idObj); err != nil {
|
||||||
|
log.Error("wrong object id", zap.Error(err))
|
||||||
|
response.Error(c, "wrong object id", fasthttp.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var addr oid.Address
|
||||||
|
addr.SetContainer(*cnrID)
|
||||||
|
addr.SetObject(*objID)
|
||||||
|
|
||||||
|
f(*d.newRequest(c, log), d.pool, addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DownloadByAttribute handles attribute-based download requests.
|
||||||
|
func (d *Downloader) DownloadByAttribute(c *fasthttp.RequestCtx) {
|
||||||
|
d.byAttribute(c, request.receiveFile)
|
||||||
|
}
|
||||||
|
|
||||||
|
// byAttribute is a wrapper similar to byAddress.
|
||||||
|
func (d *Downloader) byAttribute(c *fasthttp.RequestCtx, f func(request, *pool.Pool, oid.Address)) {
|
||||||
|
var (
|
||||||
|
scid, _ = c.UserValue("cid").(string)
|
||||||
|
key, _ = url.QueryUnescape(c.UserValue("attr_key").(string))
|
||||||
|
val, _ = url.QueryUnescape(c.UserValue("attr_val").(string))
|
||||||
|
log = d.log.With(zap.String("cid", scid), zap.String("attr_key", key), zap.String("attr_val", val))
|
||||||
|
)
|
||||||
|
|
||||||
|
containerID, err := utils.GetContainerID(d.appCtx, scid, d.containerResolver)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("wrong container id", zap.Error(err))
|
||||||
|
response.Error(c, "wrong container id", fasthttp.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
res, err := d.search(c, containerID, key, val, object.MatchStringEqual)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("could not search for objects", zap.Error(err))
|
||||||
|
response.Error(c, "could not search for objects: "+err.Error(), fasthttp.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
defer res.Close()
|
||||||
|
|
||||||
|
buf := make([]oid.ID, 1)
|
||||||
|
|
||||||
|
n, err := res.Read(buf)
|
||||||
|
if n == 0 {
|
||||||
|
if errors.Is(err, io.EOF) {
|
||||||
|
log.Error("object not found", zap.Error(err))
|
||||||
|
response.Error(c, "object not found", fasthttp.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Error("read object list failed", zap.Error(err))
|
||||||
|
response.Error(c, "read object list failed: "+err.Error(), fasthttp.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var addrObj oid.Address
|
||||||
|
addrObj.SetContainer(*containerID)
|
||||||
|
addrObj.SetObject(buf[0])
|
||||||
|
|
||||||
|
f(*d.newRequest(c, log), d.pool, addrObj)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Downloader) search(c *fasthttp.RequestCtx, cid *cid.ID, key, val string, op object.SearchMatchType) (pool.ResObjectSearch, error) {
|
||||||
|
filters := object.NewSearchFilters()
|
||||||
|
filters.AddRootFilter()
|
||||||
|
filters.AddFilter(key, val, op)
|
||||||
|
|
||||||
|
var prm pool.PrmObjectSearch
|
||||||
|
prm.SetContainerID(*cid)
|
||||||
|
prm.SetFilters(filters)
|
||||||
|
if btoken := bearerToken(c); btoken != nil {
|
||||||
|
prm.UseBearer(*btoken)
|
||||||
|
}
|
||||||
|
|
||||||
|
return d.pool.SearchObjects(d.appCtx, prm)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Downloader) getContainer(cnrID cid.ID) (container.Container, error) {
|
||||||
|
var prm pool.PrmContainerGet
|
||||||
|
prm.SetContainerID(cnrID)
|
||||||
|
|
||||||
|
return d.pool.GetContainer(d.appCtx, prm)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Downloader) addObjectToZip(zw *zip.Writer, obj *object.Object) (io.Writer, error) {
|
||||||
|
method := zip.Store
|
||||||
|
if d.settings.ZipCompression() {
|
||||||
|
method = zip.Deflate
|
||||||
|
}
|
||||||
|
|
||||||
|
filePath := getZipFilePath(obj)
|
||||||
|
if len(filePath) == 0 || filePath[len(filePath)-1] == '/' {
|
||||||
|
return nil, fmt.Errorf("invalid filepath '%s'", filePath)
|
||||||
|
}
|
||||||
|
|
||||||
|
return zw.CreateHeader(&zip.FileHeader{
|
||||||
|
Name: filePath,
|
||||||
|
Method: method,
|
||||||
|
Modified: time.Now(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// DownloadZipped handles zip by prefix requests.
|
||||||
|
func (d *Downloader) DownloadZipped(c *fasthttp.RequestCtx) {
|
||||||
|
scid, _ := c.UserValue("cid").(string)
|
||||||
|
prefix, _ := url.QueryUnescape(c.UserValue("prefix").(string))
|
||||||
|
log := d.log.With(zap.String("cid", scid), zap.String("prefix", prefix))
|
||||||
|
|
||||||
|
containerID, err := utils.GetContainerID(d.appCtx, scid, d.containerResolver)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("wrong container id", zap.Error(err))
|
||||||
|
response.Error(c, "wrong container id", fasthttp.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = tokens.StoreBearerToken(c); err != nil {
|
||||||
|
log.Error("could not fetch and store bearer token", zap.Error(err))
|
||||||
|
response.Error(c, "could not fetch and store bearer token: "+err.Error(), fasthttp.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// check if container exists here to be able to return 404 error,
|
||||||
|
// otherwise we get this error only in object iteration step
|
||||||
|
// and client get 200 OK.
|
||||||
|
if _, err = d.getContainer(*containerID); err != nil {
|
||||||
|
log.Error("could not check container existence", zap.Error(err))
|
||||||
|
if client.IsErrContainerNotFound(err) {
|
||||||
|
response.Error(c, "Not Found", fasthttp.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
response.Error(c, "could not check container existence: "+err.Error(), fasthttp.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
resSearch, err := d.search(c, containerID, object.AttributeFilePath, prefix, object.MatchCommonPrefix)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("could not search for objects", zap.Error(err))
|
||||||
|
response.Error(c, "could not search for objects: "+err.Error(), fasthttp.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Response.Header.Set(fasthttp.HeaderContentType, "application/zip")
|
||||||
|
c.Response.Header.Set(fasthttp.HeaderContentDisposition, "attachment; filename=\"archive.zip\"")
|
||||||
|
c.Response.SetStatusCode(http.StatusOK)
|
||||||
|
|
||||||
|
c.SetBodyStreamWriter(func(w *bufio.Writer) {
|
||||||
|
defer resSearch.Close()
|
||||||
|
|
||||||
|
zipWriter := zip.NewWriter(w)
|
||||||
|
|
||||||
|
var bufZip []byte
|
||||||
|
var addr oid.Address
|
||||||
|
|
||||||
|
empty := true
|
||||||
|
called := false
|
||||||
|
btoken := bearerToken(c)
|
||||||
|
addr.SetContainer(*containerID)
|
||||||
|
|
||||||
|
errIter := resSearch.Iterate(func(id oid.ID) bool {
|
||||||
|
called = true
|
||||||
|
|
||||||
|
if empty {
|
||||||
|
bufZip = make([]byte, 3<<20) // the same as for upload
|
||||||
|
}
|
||||||
|
empty = false
|
||||||
|
|
||||||
|
addr.SetObject(id)
|
||||||
|
if err = d.zipObject(zipWriter, addr, btoken, bufZip); err != nil {
|
||||||
|
log.Error("failed to add object to archive", zap.String("oid", id.EncodeToString()), zap.Error(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
})
|
||||||
|
if errIter != nil {
|
||||||
|
log.Error("iterating over selected objects failed", zap.Error(errIter))
|
||||||
|
} else if !called {
|
||||||
|
log.Error("objects not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = zipWriter.Close(); err != nil {
|
||||||
|
log.Error("close zip writer", zap.Error(err))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Downloader) zipObject(zipWriter *zip.Writer, addr oid.Address, btoken *bearer.Token, bufZip []byte) error {
|
||||||
|
var prm pool.PrmObjectGet
|
||||||
|
prm.SetAddress(addr)
|
||||||
|
if btoken != nil {
|
||||||
|
prm.UseBearer(*btoken)
|
||||||
|
}
|
||||||
|
|
||||||
|
resGet, err := d.pool.GetObject(d.appCtx, prm)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("get NeoFS object: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
objWriter, err := d.addObjectToZip(zipWriter, &resGet.Header)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("zip create header: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err = io.CopyBuffer(objWriter, resGet.Payload, bufZip); err != nil {
|
||||||
|
return fmt.Errorf("copy object payload to zip file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = resGet.Payload.Close(); err != nil {
|
||||||
|
return fmt.Errorf("object body close error: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = zipWriter.Flush(); err != nil {
|
||||||
|
return fmt.Errorf("flush zip writer: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getZipFilePath(obj *object.Object) string {
|
||||||
|
for _, attr := range obj.Attributes() {
|
||||||
|
if attr.Key() == object.AttributeFilePath {
|
||||||
|
return attr.Value()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ""
|
||||||
|
}
|
23
downloader/download_test.go
Normal file
23
downloader/download_test.go
Normal file
|
@ -0,0 +1,23 @@
|
||||||
|
package downloader
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSystemBackwardTranslator(t *testing.T) {
|
||||||
|
input := []string{
|
||||||
|
"__NEOFS__EXPIRATION_EPOCH",
|
||||||
|
"__NEOFS__RANDOM_ATTR",
|
||||||
|
}
|
||||||
|
expected := []string{
|
||||||
|
"Neofs-Expiration-Epoch",
|
||||||
|
"Neofs-Random-Attr",
|
||||||
|
}
|
||||||
|
|
||||||
|
for i, str := range input {
|
||||||
|
res := systemBackwardTranslator(str)
|
||||||
|
require.Equal(t, expected[i], res)
|
||||||
|
}
|
||||||
|
}
|
120
downloader/head.go
Normal file
120
downloader/head.go
Normal file
|
@ -0,0 +1,120 @@
|
||||||
|
package downloader
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/nspcc-dev/neofs-http-gw/response"
|
||||||
|
"github.com/nspcc-dev/neofs-http-gw/tokens"
|
||||||
|
"github.com/nspcc-dev/neofs-http-gw/utils"
|
||||||
|
"github.com/nspcc-dev/neofs-sdk-go/object"
|
||||||
|
oid "github.com/nspcc-dev/neofs-sdk-go/object/id"
|
||||||
|
"github.com/nspcc-dev/neofs-sdk-go/pool"
|
||||||
|
"github.com/valyala/fasthttp"
|
||||||
|
"go.uber.org/zap"
|
||||||
|
)
|
||||||
|
|
||||||
|
// max bytes needed to detect content type according to http.DetectContentType docs.
|
||||||
|
const sizeToDetectType = 512
|
||||||
|
|
||||||
|
const (
|
||||||
|
hdrObjectID = "X-Object-Id"
|
||||||
|
hdrOwnerID = "X-Owner-Id"
|
||||||
|
hdrContainerID = "X-Container-Id"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (r request) headObject(clnt *pool.Pool, objectAddress oid.Address) {
|
||||||
|
var start = time.Now()
|
||||||
|
if err := tokens.StoreBearerToken(r.RequestCtx); err != nil {
|
||||||
|
r.log.Error("could not fetch and store bearer token", zap.Error(err))
|
||||||
|
response.Error(r.RequestCtx, "could not fetch and store bearer token", fasthttp.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
btoken := bearerToken(r.RequestCtx)
|
||||||
|
|
||||||
|
var prm pool.PrmObjectHead
|
||||||
|
prm.SetAddress(objectAddress)
|
||||||
|
if btoken != nil {
|
||||||
|
prm.UseBearer(*btoken)
|
||||||
|
}
|
||||||
|
|
||||||
|
obj, err := clnt.HeadObject(r.appCtx, prm)
|
||||||
|
if err != nil {
|
||||||
|
r.handleNeoFSErr(err, start)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
r.Response.Header.Set(fasthttp.HeaderContentLength, strconv.FormatUint(obj.PayloadSize(), 10))
|
||||||
|
var contentType string
|
||||||
|
for _, attr := range obj.Attributes() {
|
||||||
|
key := attr.Key()
|
||||||
|
val := attr.Value()
|
||||||
|
if !isValidToken(key) || !isValidValue(val) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(key, utils.SystemAttributePrefix) {
|
||||||
|
key = systemBackwardTranslator(key)
|
||||||
|
}
|
||||||
|
r.Response.Header.Set(utils.UserAttributeHeaderPrefix+key, val)
|
||||||
|
switch key {
|
||||||
|
case object.AttributeTimestamp:
|
||||||
|
value, err := strconv.ParseInt(val, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
r.log.Info("couldn't parse creation date",
|
||||||
|
zap.String("key", key),
|
||||||
|
zap.String("val", val),
|
||||||
|
zap.Error(err))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
r.Response.Header.Set(fasthttp.HeaderLastModified, time.Unix(value, 0).UTC().Format(http.TimeFormat))
|
||||||
|
case object.AttributeContentType:
|
||||||
|
contentType = val
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
idsToResponse(&r.Response, &obj)
|
||||||
|
|
||||||
|
if len(contentType) == 0 {
|
||||||
|
contentType, _, err = readContentType(obj.PayloadSize(), func(sz uint64) (io.Reader, error) {
|
||||||
|
var prmRange pool.PrmObjectRange
|
||||||
|
prmRange.SetAddress(objectAddress)
|
||||||
|
prmRange.SetLength(sz)
|
||||||
|
if btoken != nil {
|
||||||
|
prmRange.UseBearer(*btoken)
|
||||||
|
}
|
||||||
|
|
||||||
|
resObj, err := clnt.ObjectRange(r.appCtx, prmRange)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &resObj, nil
|
||||||
|
})
|
||||||
|
if err != nil && err != io.EOF {
|
||||||
|
r.handleNeoFSErr(err, start)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
r.SetContentType(contentType)
|
||||||
|
}
|
||||||
|
|
||||||
|
func idsToResponse(resp *fasthttp.Response, obj *object.Object) {
|
||||||
|
objID, _ := obj.ID()
|
||||||
|
cnrID, _ := obj.ContainerID()
|
||||||
|
resp.Header.Set(hdrObjectID, objID.String())
|
||||||
|
resp.Header.Set(hdrOwnerID, obj.OwnerID().String())
|
||||||
|
resp.Header.Set(hdrContainerID, cnrID.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// HeadByAddress handles head requests using simple cid/oid format.
|
||||||
|
func (d *Downloader) HeadByAddress(c *fasthttp.RequestCtx) {
|
||||||
|
d.byAddress(c, request.headObject)
|
||||||
|
}
|
||||||
|
|
||||||
|
// HeadByAttribute handles attribute-based head requests.
|
||||||
|
func (d *Downloader) HeadByAttribute(c *fasthttp.RequestCtx) {
|
||||||
|
d.byAttribute(c, request.headObject)
|
||||||
|
}
|
46
downloader/reader_test.go
Normal file
46
downloader/reader_test.go
Normal file
|
@ -0,0 +1,46 @@
|
||||||
|
package downloader
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDetector(t *testing.T) {
|
||||||
|
txtContentType := "text/plain; charset=utf-8"
|
||||||
|
sb := strings.Builder{}
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
sb.WriteString("Some txt content. Content-Type must be detected properly by detector.")
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range []struct {
|
||||||
|
Name string
|
||||||
|
ContentType string
|
||||||
|
Expected string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "less than 512b",
|
||||||
|
ContentType: txtContentType,
|
||||||
|
Expected: sb.String()[:256],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "more than 512b",
|
||||||
|
ContentType: txtContentType,
|
||||||
|
Expected: sb.String(),
|
||||||
|
},
|
||||||
|
} {
|
||||||
|
t.Run(tc.Name, func(t *testing.T) {
|
||||||
|
contentType, data, err := readContentType(uint64(len(tc.Expected)),
|
||||||
|
func(sz uint64) (io.Reader, error) {
|
||||||
|
return strings.NewReader(tc.Expected), nil
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, tc.ContentType, contentType)
|
||||||
|
require.True(t, strings.HasPrefix(tc.Expected, string(data)))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
181
go.mod
181
go.mod
|
@ -1,138 +1,99 @@
|
||||||
module git.frostfs.info/TrueCloudLab/frostfs-http-gw
|
module github.com/nspcc-dev/neofs-http-gw
|
||||||
|
|
||||||
go 1.22
|
go 1.17
|
||||||
|
|
||||||
require (
|
require (
|
||||||
git.frostfs.info/TrueCloudLab/frostfs-observability v0.0.0-20241125133852-37bd75821121
|
|
||||||
git.frostfs.info/TrueCloudLab/frostfs-sdk-go v0.0.0-20250130095343-593dd77d841a
|
|
||||||
git.frostfs.info/TrueCloudLab/multinet v0.0.0-20241015075604-6cb0d80e0972
|
|
||||||
git.frostfs.info/TrueCloudLab/zapjournald v0.0.0-20240124114243-cb2e66427d02
|
|
||||||
github.com/bluele/gcache v0.0.2
|
|
||||||
github.com/docker/docker v27.1.1+incompatible
|
|
||||||
github.com/docker/go-units v0.5.0
|
|
||||||
github.com/fasthttp/router v1.4.1
|
github.com/fasthttp/router v1.4.1
|
||||||
github.com/nspcc-dev/neo-go v0.106.2
|
github.com/nspcc-dev/neo-go v0.99.4
|
||||||
github.com/panjf2000/ants/v2 v2.5.0
|
github.com/nspcc-dev/neofs-api-go/v2 v2.14.0
|
||||||
github.com/prometheus/client_golang v1.19.0
|
github.com/nspcc-dev/neofs-sdk-go v1.0.0-rc.7.0.20221115140820-b4b07a3c4e11
|
||||||
github.com/prometheus/client_model v0.5.0
|
github.com/prometheus/client_golang v1.13.0
|
||||||
github.com/spf13/pflag v1.0.5
|
github.com/spf13/pflag v1.0.5
|
||||||
github.com/spf13/viper v1.15.0
|
github.com/spf13/viper v1.8.1
|
||||||
github.com/ssgreg/journald v1.0.0
|
github.com/stretchr/testify v1.8.0
|
||||||
github.com/stretchr/testify v1.9.0
|
github.com/testcontainers/testcontainers-go v0.13.0
|
||||||
github.com/testcontainers/testcontainers-go v0.35.0
|
|
||||||
github.com/trailofbits/go-fuzz-utils v0.0.0-20230413173806-58c38daa3cb4
|
|
||||||
github.com/valyala/fasthttp v1.34.0
|
github.com/valyala/fasthttp v1.34.0
|
||||||
go.opentelemetry.io/otel v1.31.0
|
go.uber.org/atomic v1.10.0
|
||||||
go.opentelemetry.io/otel/trace v1.31.0
|
go.uber.org/zap v1.23.0
|
||||||
go.uber.org/zap v1.27.0
|
|
||||||
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842
|
|
||||||
golang.org/x/net v0.30.0
|
|
||||||
golang.org/x/sys v0.28.0
|
|
||||||
google.golang.org/grpc v1.69.2
|
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
dario.cat/mergo v1.0.0 // indirect
|
|
||||||
git.frostfs.info/TrueCloudLab/frostfs-contract v0.19.3-0.20240621131249-49e5270f673e // indirect
|
|
||||||
git.frostfs.info/TrueCloudLab/frostfs-crypto v0.6.0 // indirect
|
|
||||||
git.frostfs.info/TrueCloudLab/hrw v1.2.1 // indirect
|
|
||||||
git.frostfs.info/TrueCloudLab/rfc6979 v0.4.0 // indirect
|
|
||||||
git.frostfs.info/TrueCloudLab/tzhash v1.8.0 // indirect
|
|
||||||
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect
|
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect
|
||||||
github.com/Microsoft/go-winio v0.6.2 // indirect
|
github.com/Microsoft/go-winio v0.5.2 // indirect
|
||||||
github.com/VictoriaMetrics/easyproto v0.1.4 // indirect
|
github.com/Microsoft/hcsshim v0.9.2 // indirect
|
||||||
github.com/andybalholm/brotli v1.0.4 // indirect
|
github.com/andybalholm/brotli v1.0.4 // indirect
|
||||||
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
|
github.com/antlr/antlr4/runtime/Go/antlr v1.4.10 // indirect
|
||||||
github.com/beorn7/perks v1.0.1 // indirect
|
github.com/beorn7/perks v1.0.1 // indirect
|
||||||
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
|
github.com/btcsuite/btcd v0.22.0-beta // indirect
|
||||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
github.com/cenkalti/backoff/v4 v4.1.3 // indirect
|
||||||
github.com/containerd/containerd v1.7.18 // indirect
|
github.com/cespare/xxhash/v2 v2.1.2 // indirect
|
||||||
github.com/containerd/log v0.1.0 // indirect
|
github.com/containerd/cgroups v1.0.3 // indirect
|
||||||
github.com/containerd/platforms v0.2.1 // indirect
|
github.com/containerd/containerd v1.6.2 // indirect
|
||||||
github.com/cpuguy83/dockercfg v0.3.2 // indirect
|
github.com/coreos/go-semver v0.3.0 // indirect
|
||||||
github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect
|
github.com/cpuguy83/go-md2man/v2 v2.0.1 // indirect
|
||||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect
|
github.com/docker/distribution v2.8.1+incompatible // indirect
|
||||||
github.com/distribution/reference v0.6.0 // indirect
|
github.com/docker/docker v20.10.14+incompatible // indirect
|
||||||
github.com/docker/go-connections v0.5.0 // indirect
|
github.com/docker/go-connections v0.4.0 // indirect
|
||||||
github.com/felixge/httpsnoop v1.0.4 // indirect
|
github.com/docker/go-units v0.4.0 // indirect
|
||||||
github.com/fsnotify/fsnotify v1.6.0 // indirect
|
github.com/fsnotify/fsnotify v1.4.9 // indirect
|
||||||
github.com/go-logr/logr v1.4.2 // indirect
|
|
||||||
github.com/go-logr/stdr v1.2.2 // indirect
|
|
||||||
github.com/go-ole/go-ole v1.2.6 // indirect
|
|
||||||
github.com/gogo/protobuf v1.3.2 // indirect
|
github.com/gogo/protobuf v1.3.2 // indirect
|
||||||
github.com/golang/snappy v0.0.4 // indirect
|
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
github.com/golang/protobuf v1.5.2 // indirect
|
||||||
github.com/gorilla/websocket v1.5.1 // indirect
|
github.com/google/uuid v1.3.0 // indirect
|
||||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0 // indirect
|
github.com/gorilla/mux v1.8.0 // indirect
|
||||||
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
github.com/gorilla/websocket v1.4.2 // indirect
|
||||||
|
github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d // indirect
|
||||||
github.com/hashicorp/hcl v1.0.0 // indirect
|
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||||
github.com/ipfs/go-cid v0.0.7 // indirect
|
github.com/klauspost/compress v1.15.0 // indirect
|
||||||
github.com/klauspost/compress v1.17.4 // indirect
|
github.com/magiconair/properties v1.8.6 // indirect
|
||||||
github.com/klauspost/cpuid/v2 v2.2.6 // indirect
|
github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect
|
||||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
|
github.com/mitchellh/mapstructure v1.4.1 // indirect
|
||||||
github.com/magiconair/properties v1.8.7 // indirect
|
github.com/moby/sys/mount v0.3.2 // indirect
|
||||||
github.com/minio/sha256-simd v1.0.1 // indirect
|
github.com/moby/sys/mountinfo v0.6.1 // indirect
|
||||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect
|
||||||
github.com/moby/docker-image-spec v1.3.1 // indirect
|
|
||||||
github.com/moby/patternmatcher v0.6.0 // indirect
|
|
||||||
github.com/moby/sys/sequential v0.5.0 // indirect
|
|
||||||
github.com/moby/sys/user v0.1.0 // indirect
|
|
||||||
github.com/moby/term v0.5.0 // indirect
|
|
||||||
github.com/morikuni/aec v1.0.0 // indirect
|
github.com/morikuni/aec v1.0.0 // indirect
|
||||||
github.com/mr-tron/base58 v1.2.0 // indirect
|
github.com/mr-tron/base58 v1.2.0 // indirect
|
||||||
github.com/multiformats/go-base32 v0.1.0 // indirect
|
github.com/nspcc-dev/go-ordered-json v0.0.0-20220111165707-25110be27d22 // indirect
|
||||||
github.com/multiformats/go-base36 v0.2.0 // indirect
|
github.com/nspcc-dev/hrw v1.0.9 // indirect
|
||||||
github.com/multiformats/go-multiaddr v0.14.0 // indirect
|
github.com/nspcc-dev/neo-go/pkg/interop v0.0.0-20220927123257-24c107e3a262 // indirect
|
||||||
github.com/multiformats/go-multibase v0.2.0 // indirect
|
github.com/nspcc-dev/neofs-contract v0.16.0 // indirect
|
||||||
github.com/multiformats/go-multihash v0.2.3 // indirect
|
github.com/nspcc-dev/neofs-crypto v0.4.0 // indirect
|
||||||
github.com/multiformats/go-varint v0.0.7 // indirect
|
github.com/nspcc-dev/rfc6979 v0.2.0 // indirect
|
||||||
github.com/nspcc-dev/go-ordered-json v0.0.0-20240301084351-0246b013f8b2 // indirect
|
github.com/nspcc-dev/tzhash v1.6.1 // indirect
|
||||||
github.com/nspcc-dev/neo-go/pkg/interop v0.0.0-20240521091047-78685785716d // indirect
|
|
||||||
github.com/nspcc-dev/rfc6979 v0.2.1 // indirect
|
|
||||||
github.com/opencontainers/go-digest v1.0.0 // indirect
|
github.com/opencontainers/go-digest v1.0.0 // indirect
|
||||||
github.com/opencontainers/image-spec v1.1.0 // indirect
|
github.com/opencontainers/image-spec v1.0.2 // indirect
|
||||||
github.com/pelletier/go-toml/v2 v2.0.6 // indirect
|
github.com/opencontainers/runc v1.1.1 // indirect
|
||||||
|
github.com/pelletier/go-toml v1.9.3 // indirect
|
||||||
github.com/pkg/errors v0.9.1 // indirect
|
github.com/pkg/errors v0.9.1 // indirect
|
||||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
|
github.com/prometheus/client_model v0.2.0 // indirect
|
||||||
github.com/prometheus/common v0.48.0 // indirect
|
github.com/prometheus/common v0.37.0 // indirect
|
||||||
github.com/prometheus/procfs v0.12.0 // indirect
|
github.com/prometheus/procfs v0.8.0 // indirect
|
||||||
github.com/russross/blackfriday/v2 v2.1.0 // indirect
|
github.com/russross/blackfriday/v2 v2.1.0 // indirect
|
||||||
github.com/savsgio/gotils v0.0.0-20210617111740-97865ed5a873 // indirect
|
github.com/savsgio/gotils v0.0.0-20210617111740-97865ed5a873 // indirect
|
||||||
github.com/shirou/gopsutil/v3 v3.23.12 // indirect
|
github.com/sirupsen/logrus v1.8.1 // indirect
|
||||||
github.com/shoenig/go-m1cpu v0.1.6 // indirect
|
|
||||||
github.com/sirupsen/logrus v1.9.3 // indirect
|
|
||||||
github.com/spaolacci/murmur3 v1.1.0 // indirect
|
github.com/spaolacci/murmur3 v1.1.0 // indirect
|
||||||
github.com/spf13/afero v1.9.3 // indirect
|
github.com/spf13/afero v1.6.0 // indirect
|
||||||
github.com/spf13/cast v1.5.0 // indirect
|
github.com/spf13/cast v1.3.1 // indirect
|
||||||
github.com/spf13/jwalterweatherman v1.1.0 // indirect
|
github.com/spf13/jwalterweatherman v1.1.0 // indirect
|
||||||
github.com/subosito/gotenv v1.4.2 // indirect
|
github.com/subosito/gotenv v1.2.0 // indirect
|
||||||
github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 // indirect
|
github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 // indirect
|
||||||
github.com/tklauser/go-sysconf v0.3.12 // indirect
|
github.com/urfave/cli v1.22.5 // indirect
|
||||||
github.com/tklauser/numcpus v0.6.1 // indirect
|
|
||||||
github.com/twmb/murmur3 v1.1.8 // indirect
|
|
||||||
github.com/urfave/cli v1.22.12 // indirect
|
|
||||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||||
github.com/yusufpapurcu/wmi v1.2.3 // indirect
|
go.opencensus.io v0.23.0 // indirect
|
||||||
go.etcd.io/bbolt v1.3.9 // indirect
|
go.uber.org/multierr v1.8.0 // indirect
|
||||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 // indirect
|
golang.org/x/crypto v0.0.0-20220214200702-86341886e292 // indirect
|
||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.28.0 // indirect
|
golang.org/x/net v0.0.0-20220412020605-290c469a71a5 // indirect
|
||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.28.0 // indirect
|
golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f // indirect
|
||||||
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.28.0 // indirect
|
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a // indirect
|
||||||
go.opentelemetry.io/otel/metric v1.31.0 // indirect
|
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 // indirect
|
||||||
go.opentelemetry.io/otel/sdk v1.31.0 // indirect
|
golang.org/x/text v0.3.7 // indirect
|
||||||
go.opentelemetry.io/proto/otlp v1.3.1 // indirect
|
google.golang.org/genproto v0.0.0-20220414192740-2d67ff6cf2b4 // indirect
|
||||||
go.uber.org/multierr v1.11.0 // indirect
|
google.golang.org/grpc v1.48.0 // indirect
|
||||||
golang.org/x/crypto v0.31.0 // indirect
|
google.golang.org/protobuf v1.28.1 // indirect
|
||||||
golang.org/x/sync v0.10.0 // indirect
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
|
||||||
golang.org/x/term v0.27.0 // indirect
|
gopkg.in/ini.v1 v1.62.0 // indirect
|
||||||
golang.org/x/text v0.21.0 // indirect
|
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||||
golang.org/x/time v0.3.0 // indirect
|
|
||||||
google.golang.org/genproto/googleapis/api v0.0.0-20241015192408-796eee8c2d53 // indirect
|
|
||||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20241015192408-796eee8c2d53 // indirect
|
|
||||||
google.golang.org/protobuf v1.36.1 // indirect
|
|
||||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
lukechampine.com/blake3 v1.2.1 // indirect
|
|
||||||
)
|
)
|
||||||
|
|
|
@ -1,37 +1,28 @@
|
||||||
//go:build integration
|
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"archive/zip"
|
"archive/zip"
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/base64"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"mime/multipart"
|
"mime/multipart"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
containerv2 "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/api/container"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/bearer"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/acl"
|
|
||||||
cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/eacl"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/netmap"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object"
|
|
||||||
oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/pool"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/user"
|
|
||||||
docker "github.com/docker/docker/api/types/container"
|
|
||||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||||
"github.com/nspcc-dev/neo-go/pkg/wallet"
|
"github.com/nspcc-dev/neofs-sdk-go/container"
|
||||||
|
"github.com/nspcc-dev/neofs-sdk-go/container/acl"
|
||||||
|
cid "github.com/nspcc-dev/neofs-sdk-go/container/id"
|
||||||
|
"github.com/nspcc-dev/neofs-sdk-go/netmap"
|
||||||
|
"github.com/nspcc-dev/neofs-sdk-go/object"
|
||||||
|
oid "github.com/nspcc-dev/neofs-sdk-go/object/id"
|
||||||
|
"github.com/nspcc-dev/neofs-sdk-go/pool"
|
||||||
|
"github.com/nspcc-dev/neofs-sdk-go/user"
|
||||||
|
"github.com/spf13/viper"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
"github.com/testcontainers/testcontainers-go"
|
"github.com/testcontainers/testcontainers-go"
|
||||||
"github.com/testcontainers/testcontainers-go/wait"
|
"github.com/testcontainers/testcontainers-go/wait"
|
||||||
|
@ -43,28 +34,26 @@ type putResponse struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
testContainerName = "friendly"
|
testContainerName = "friendly"
|
||||||
testListenAddress = "localhost:8082"
|
versionWithNativeNames = "0.27.5"
|
||||||
testHost = "http://" + testListenAddress
|
testListenAddress = "localhost:8082"
|
||||||
|
testHost = "http://" + testListenAddress
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestIntegration(t *testing.T) {
|
func TestIntegration(t *testing.T) {
|
||||||
rootCtx := context.Background()
|
rootCtx := context.Background()
|
||||||
aioImage := "git.frostfs.info/truecloudlab/frostfs-aio:"
|
aioImage := "nspccdev/neofs-aio-testcontainer:"
|
||||||
versions := []string{
|
versions := []string{
|
||||||
"1.2.7",
|
"0.27.5",
|
||||||
"1.3.0",
|
"0.28.1",
|
||||||
"1.5.0",
|
"0.29.0",
|
||||||
"1.6.5",
|
"0.30.0",
|
||||||
|
"0.32.0",
|
||||||
|
"latest",
|
||||||
}
|
}
|
||||||
key, err := keys.NewPrivateKeyFromHex("1dd37fba80fec4e6a6f13fd708d8dcb3b29def768017052f6c930fa1c5d90bbb")
|
key, err := keys.NewPrivateKeyFromHex("1dd37fba80fec4e6a6f13fd708d8dcb3b29def768017052f6c930fa1c5d90bbb")
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
file, err := os.CreateTemp("", "wallet")
|
|
||||||
require.NoError(t, err)
|
|
||||||
defer os.Remove(file.Name())
|
|
||||||
makeTempWallet(t, key, file.Name())
|
|
||||||
|
|
||||||
var ownerID user.ID
|
var ownerID user.ID
|
||||||
user.IDFromKey(&ownerID, key.PrivateKey.PublicKey)
|
user.IDFromKey(&ownerID, key.PrivateKey.PublicKey)
|
||||||
|
|
||||||
|
@ -72,28 +61,15 @@ func TestIntegration(t *testing.T) {
|
||||||
ctx, cancel2 := context.WithCancel(rootCtx)
|
ctx, cancel2 := context.WithCancel(rootCtx)
|
||||||
|
|
||||||
aioContainer := createDockerContainer(ctx, t, aioImage+version)
|
aioContainer := createDockerContainer(ctx, t, aioImage+version)
|
||||||
if strings.HasPrefix(version, "1.6") {
|
server, cancel := runServer()
|
||||||
registerUser(t, ctx, aioContainer, file.Name())
|
|
||||||
}
|
|
||||||
|
|
||||||
// See the logs from the command execution.
|
|
||||||
server, cancel := runServer(file.Name())
|
|
||||||
clientPool := getPool(ctx, t, key)
|
clientPool := getPool(ctx, t, key)
|
||||||
CID, err := createContainer(ctx, t, clientPool, ownerID)
|
CID, err := createContainer(ctx, t, clientPool, ownerID, version)
|
||||||
require.NoError(t, err, version)
|
require.NoError(t, err, version)
|
||||||
|
|
||||||
jsonToken, binaryToken := makeBearerTokens(t, key, ownerID, version)
|
t.Run("simple put "+version, func(t *testing.T) { simplePut(ctx, t, clientPool, CID, version) })
|
||||||
|
t.Run("simple get "+version, func(t *testing.T) { simpleGet(ctx, t, clientPool, ownerID, CID, version) })
|
||||||
t.Run("simple put "+version, func(t *testing.T) { simplePut(ctx, t, clientPool, CID) })
|
t.Run("get by attribute "+version, func(t *testing.T) { getByAttr(ctx, t, clientPool, ownerID, CID, version) })
|
||||||
t.Run("put with json bearer token in header"+version, func(t *testing.T) { putWithBearerTokenInHeader(ctx, t, clientPool, CID, jsonToken) })
|
t.Run("get zip "+version, func(t *testing.T) { getZip(ctx, t, clientPool, ownerID, CID, version) })
|
||||||
t.Run("put with json bearer token in cookie"+version, func(t *testing.T) { putWithBearerTokenInCookie(ctx, t, clientPool, CID, jsonToken) })
|
|
||||||
t.Run("put with binary bearer token in header"+version, func(t *testing.T) { putWithBearerTokenInHeader(ctx, t, clientPool, CID, binaryToken) })
|
|
||||||
t.Run("put with binary bearer token in cookie"+version, func(t *testing.T) { putWithBearerTokenInCookie(ctx, t, clientPool, CID, binaryToken) })
|
|
||||||
t.Run("put with duplicate keys "+version, func(t *testing.T) { putWithDuplicateKeys(t, CID) })
|
|
||||||
t.Run("simple get "+version, func(t *testing.T) { simpleGet(ctx, t, clientPool, ownerID, CID) })
|
|
||||||
t.Run("get by attribute "+version, func(t *testing.T) { getByAttr(ctx, t, clientPool, ownerID, CID) })
|
|
||||||
t.Run("get zip "+version, func(t *testing.T) { getZip(ctx, t, clientPool, ownerID, CID) })
|
|
||||||
t.Run("test namespaces "+version, func(t *testing.T) { checkNamespaces(ctx, t, clientPool, ownerID, CID) })
|
|
||||||
|
|
||||||
cancel()
|
cancel()
|
||||||
server.Wait()
|
server.Wait()
|
||||||
|
@ -103,59 +79,28 @@ func TestIntegration(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func runServer(pathToWallet string) (App, context.CancelFunc) {
|
func runServer() (App, context.CancelFunc) {
|
||||||
cancelCtx, cancel := context.WithCancel(context.Background())
|
cancelCtx, cancel := context.WithCancel(context.Background())
|
||||||
|
|
||||||
v := getDefaultConfig()
|
v := getDefaultConfig()
|
||||||
v.config().Set(cfgWalletPath, pathToWallet)
|
l, lvl := newLogger(v)
|
||||||
v.config().Set(cfgWalletPassphrase, "")
|
application := newApp(cancelCtx, WithConfig(v), WithLogger(l, lvl))
|
||||||
|
go application.Serve(cancelCtx)
|
||||||
application := newApp(cancelCtx, v)
|
|
||||||
go application.Serve()
|
|
||||||
|
|
||||||
return application, cancel
|
return application, cancel
|
||||||
}
|
}
|
||||||
|
|
||||||
func simplePut(ctx context.Context, t *testing.T, p *pool.Pool, CID cid.ID) {
|
func simplePut(ctx context.Context, t *testing.T, p *pool.Pool, CID cid.ID, version string) {
|
||||||
url := testHost + "/upload/" + CID.String()
|
url := testHost + "/upload/" + CID.String()
|
||||||
makePutRequestAndCheck(ctx, t, p, CID, url)
|
makePutRequestAndCheck(ctx, t, p, CID, url)
|
||||||
|
|
||||||
url = testHost + "/upload/" + testContainerName
|
if version >= versionWithNativeNames {
|
||||||
makePutRequestAndCheck(ctx, t, p, CID, url)
|
url = testHost + "/upload/" + testContainerName
|
||||||
}
|
makePutRequestAndCheck(ctx, t, p, CID, url)
|
||||||
|
}
|
||||||
func putWithBearerTokenInHeader(ctx context.Context, t *testing.T, p *pool.Pool, CID cid.ID, token string) {
|
|
||||||
url := testHost + "/upload/" + CID.String()
|
|
||||||
|
|
||||||
request, content, attributes := makePutRequest(t, url)
|
|
||||||
request.Header.Set("Authorization", "Bearer "+token)
|
|
||||||
resp, err := http.DefaultClient.Do(request)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
checkPutResponse(ctx, t, p, CID, resp, content, attributes)
|
|
||||||
}
|
|
||||||
|
|
||||||
func putWithBearerTokenInCookie(ctx context.Context, t *testing.T, p *pool.Pool, CID cid.ID, token string) {
|
|
||||||
url := testHost + "/upload/" + CID.String()
|
|
||||||
|
|
||||||
request, content, attributes := makePutRequest(t, url)
|
|
||||||
request.AddCookie(&http.Cookie{Name: "Bearer", Value: token})
|
|
||||||
resp, err := http.DefaultClient.Do(request)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
checkPutResponse(ctx, t, p, CID, resp, content, attributes)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func makePutRequestAndCheck(ctx context.Context, t *testing.T, p *pool.Pool, cnrID cid.ID, url string) {
|
func makePutRequestAndCheck(ctx context.Context, t *testing.T, p *pool.Pool, cnrID cid.ID, url string) {
|
||||||
request, content, attributes := makePutRequest(t, url)
|
|
||||||
|
|
||||||
resp, err := http.DefaultClient.Do(request)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
checkPutResponse(ctx, t, p, cnrID, resp, content, attributes)
|
|
||||||
}
|
|
||||||
|
|
||||||
func makePutRequest(t *testing.T, url string) (*http.Request, string, map[string]string) {
|
|
||||||
content := "content of file"
|
content := "content of file"
|
||||||
keyAttr, valAttr := "User-Attribute", "user value"
|
keyAttr, valAttr := "User-Attribute", "user value"
|
||||||
attributes := map[string]string{
|
attributes := map[string]string{
|
||||||
|
@ -177,10 +122,9 @@ func makePutRequest(t *testing.T, url string) (*http.Request, string, map[string
|
||||||
request.Header.Set("Content-Type", w.FormDataContentType())
|
request.Header.Set("Content-Type", w.FormDataContentType())
|
||||||
request.Header.Set("X-Attribute-"+keyAttr, valAttr)
|
request.Header.Set("X-Attribute-"+keyAttr, valAttr)
|
||||||
|
|
||||||
return request, content, attributes
|
resp, err := http.DefaultClient.Do(request)
|
||||||
}
|
require.NoError(t, err)
|
||||||
|
|
||||||
func checkPutResponse(ctx context.Context, t *testing.T, p *pool.Pool, cnrID cid.ID, resp *http.Response, content string, attributes map[string]string) {
|
|
||||||
defer func() {
|
defer func() {
|
||||||
err := resp.Body.Close()
|
err := resp.Body.Close()
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
@ -227,44 +171,7 @@ func checkPutResponse(ctx context.Context, t *testing.T, p *pool.Pool, cnrID cid
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func putWithDuplicateKeys(t *testing.T, CID cid.ID) {
|
func simpleGet(ctx context.Context, t *testing.T, clientPool *pool.Pool, ownerID user.ID, CID cid.ID, version string) {
|
||||||
url := testHost + "/upload/" + CID.String()
|
|
||||||
|
|
||||||
attr := "X-Attribute-User-Attribute"
|
|
||||||
content := "content of file"
|
|
||||||
valOne, valTwo := "first_value", "second_value"
|
|
||||||
fileName := "newFile.txt"
|
|
||||||
|
|
||||||
var buff bytes.Buffer
|
|
||||||
w := multipart.NewWriter(&buff)
|
|
||||||
fw, err := w.CreateFormFile("file", fileName)
|
|
||||||
require.NoError(t, err)
|
|
||||||
_, err = io.Copy(fw, bytes.NewBufferString(content))
|
|
||||||
require.NoError(t, err)
|
|
||||||
err = w.Close()
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
request, err := http.NewRequest(http.MethodPost, url, &buff)
|
|
||||||
require.NoError(t, err)
|
|
||||||
request.Header.Set("Content-Type", w.FormDataContentType())
|
|
||||||
request.Header.Add(attr, valOne)
|
|
||||||
request.Header.Add(attr, valTwo)
|
|
||||||
|
|
||||||
resp, err := http.DefaultClient.Do(request)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
defer func() {
|
|
||||||
err := resp.Body.Close()
|
|
||||||
require.NoError(t, err)
|
|
||||||
}()
|
|
||||||
|
|
||||||
body, err := io.ReadAll(resp.Body)
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Equal(t, "key duplication error: "+attr+"\n", string(body))
|
|
||||||
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
func simpleGet(ctx context.Context, t *testing.T, clientPool *pool.Pool, ownerID user.ID, CID cid.ID) {
|
|
||||||
content := "content of file"
|
content := "content of file"
|
||||||
attributes := map[string]string{
|
attributes := map[string]string{
|
||||||
"some-attr": "some-get-value",
|
"some-attr": "some-get-value",
|
||||||
|
@ -276,9 +183,11 @@ func simpleGet(ctx context.Context, t *testing.T, clientPool *pool.Pool, ownerID
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
checkGetResponse(t, resp, content, attributes)
|
checkGetResponse(t, resp, content, attributes)
|
||||||
|
|
||||||
resp, err = http.Get(testHost + "/get/" + testContainerName + "/" + id.String())
|
if version >= versionWithNativeNames {
|
||||||
require.NoError(t, err)
|
resp, err = http.Get(testHost + "/get/" + testContainerName + "/" + id.String())
|
||||||
checkGetResponse(t, resp, content, attributes)
|
require.NoError(t, err)
|
||||||
|
checkGetResponse(t, resp, content, attributes)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func checkGetResponse(t *testing.T, resp *http.Response, content string, attributes map[string]string) {
|
func checkGetResponse(t *testing.T, resp *http.Response, content string, attributes map[string]string) {
|
||||||
|
@ -311,7 +220,7 @@ func checkGetByAttrResponse(t *testing.T, resp *http.Response, content string, a
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getByAttr(ctx context.Context, t *testing.T, clientPool *pool.Pool, ownerID user.ID, CID cid.ID) {
|
func getByAttr(ctx context.Context, t *testing.T, clientPool *pool.Pool, ownerID user.ID, CID cid.ID, version string) {
|
||||||
keyAttr, valAttr := "some-attr", "some-get-by-attr-value"
|
keyAttr, valAttr := "some-attr", "some-get-by-attr-value"
|
||||||
content := "content of file"
|
content := "content of file"
|
||||||
attributes := map[string]string{keyAttr: valAttr}
|
attributes := map[string]string{keyAttr: valAttr}
|
||||||
|
@ -328,12 +237,14 @@ func getByAttr(ctx context.Context, t *testing.T, clientPool *pool.Pool, ownerID
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
checkGetByAttrResponse(t, resp, content, expectedAttr)
|
checkGetByAttrResponse(t, resp, content, expectedAttr)
|
||||||
|
|
||||||
resp, err = http.Get(testHost + "/get_by_attribute/" + testContainerName + "/" + keyAttr + "/" + valAttr)
|
if version >= versionWithNativeNames {
|
||||||
require.NoError(t, err)
|
resp, err = http.Get(testHost + "/get_by_attribute/" + testContainerName + "/" + keyAttr + "/" + valAttr)
|
||||||
checkGetByAttrResponse(t, resp, content, expectedAttr)
|
require.NoError(t, err)
|
||||||
|
checkGetByAttrResponse(t, resp, content, expectedAttr)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getZip(ctx context.Context, t *testing.T, clientPool *pool.Pool, ownerID user.ID, CID cid.ID) {
|
func getZip(ctx context.Context, t *testing.T, clientPool *pool.Pool, ownerID user.ID, CID cid.ID, version string) {
|
||||||
names := []string{"zipfolder/dir/name1.txt", "zipfolder/name2.txt"}
|
names := []string{"zipfolder/dir/name1.txt", "zipfolder/name2.txt"}
|
||||||
contents := []string{"content of file1", "content of file2"}
|
contents := []string{"content of file1", "content of file2"}
|
||||||
attributes1 := map[string]string{object.AttributeFilePath: names[0]}
|
attributes1 := map[string]string{object.AttributeFilePath: names[0]}
|
||||||
|
@ -345,8 +256,10 @@ func getZip(ctx context.Context, t *testing.T, clientPool *pool.Pool, ownerID us
|
||||||
baseURL := testHost + "/zip/" + CID.String()
|
baseURL := testHost + "/zip/" + CID.String()
|
||||||
makeZipTest(t, baseURL, names, contents)
|
makeZipTest(t, baseURL, names, contents)
|
||||||
|
|
||||||
baseURL = testHost + "/zip/" + testContainerName
|
if version >= versionWithNativeNames {
|
||||||
makeZipTest(t, baseURL, names, contents)
|
baseURL = testHost + "/zip/" + testContainerName
|
||||||
|
makeZipTest(t, baseURL, names, contents)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func makeZipTest(t *testing.T, baseURL string, names, contents []string) {
|
func makeZipTest(t *testing.T, baseURL string, names, contents []string) {
|
||||||
|
@ -398,49 +311,13 @@ func checkZip(t *testing.T, data []byte, length int64, names, contents []string)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func checkNamespaces(ctx context.Context, t *testing.T, clientPool *pool.Pool, ownerID user.ID, CID cid.ID) {
|
|
||||||
content := "content of file"
|
|
||||||
attributes := map[string]string{
|
|
||||||
"some-attr": "some-get-value",
|
|
||||||
}
|
|
||||||
|
|
||||||
id := putObject(ctx, t, clientPool, ownerID, CID, content, attributes)
|
|
||||||
|
|
||||||
req, err := http.NewRequest(http.MethodGet, testHost+"/get/"+testContainerName+"/"+id.String(), nil)
|
|
||||||
require.NoError(t, err)
|
|
||||||
req.Header.Set(defaultNamespaceHeader, "")
|
|
||||||
|
|
||||||
resp, err := http.DefaultClient.Do(req)
|
|
||||||
require.NoError(t, err)
|
|
||||||
checkGetResponse(t, resp, content, attributes)
|
|
||||||
|
|
||||||
req, err = http.NewRequest(http.MethodGet, testHost+"/get/"+testContainerName+"/"+id.String(), nil)
|
|
||||||
require.NoError(t, err)
|
|
||||||
req.Header.Set(defaultNamespaceHeader, "root")
|
|
||||||
|
|
||||||
resp, err = http.DefaultClient.Do(req)
|
|
||||||
require.NoError(t, err)
|
|
||||||
checkGetResponse(t, resp, content, attributes)
|
|
||||||
|
|
||||||
req, err = http.NewRequest(http.MethodGet, testHost+"/get/"+testContainerName+"/"+id.String(), nil)
|
|
||||||
require.NoError(t, err)
|
|
||||||
req.Header.Set(defaultNamespaceHeader, "root2")
|
|
||||||
|
|
||||||
resp, err = http.DefaultClient.Do(req)
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Equal(t, http.StatusNotFound, resp.StatusCode)
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func createDockerContainer(ctx context.Context, t *testing.T, image string) testcontainers.Container {
|
func createDockerContainer(ctx context.Context, t *testing.T, image string) testcontainers.Container {
|
||||||
req := testcontainers.ContainerRequest{
|
req := testcontainers.ContainerRequest{
|
||||||
Image: image,
|
Image: image,
|
||||||
WaitingFor: wait.NewLogStrategy("aio container started").WithStartupTimeout(2 * time.Minute),
|
WaitingFor: wait.NewLogStrategy("aio container started").WithStartupTimeout(30 * time.Second),
|
||||||
Name: "aio",
|
Name: "aio",
|
||||||
Hostname: "aio",
|
Hostname: "aio",
|
||||||
HostConfigModifier: func(hc *docker.HostConfig) {
|
NetworkMode: "host",
|
||||||
hc.NetworkMode = "host"
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
aioC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
|
aioC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
|
||||||
ContainerRequest: req,
|
ContainerRequest: req,
|
||||||
|
@ -451,14 +328,14 @@ func createDockerContainer(ctx context.Context, t *testing.T, image string) test
|
||||||
return aioC
|
return aioC
|
||||||
}
|
}
|
||||||
|
|
||||||
func getDefaultConfig() *appCfg {
|
func getDefaultConfig() *viper.Viper {
|
||||||
v := settings()
|
v := settings()
|
||||||
v.config().SetDefault(cfgPeers+".0.address", "localhost:8080")
|
v.SetDefault(cfgPeers+".0.address", "localhost:8080")
|
||||||
v.config().SetDefault(cfgPeers+".0.weight", 1)
|
v.SetDefault(cfgPeers+".0.weight", 1)
|
||||||
v.config().SetDefault(cfgPeers+".0.priority", 1)
|
v.SetDefault(cfgPeers+".0.priority", 1)
|
||||||
|
|
||||||
v.config().SetDefault(cfgRPCEndpoint, "http://localhost:30333")
|
v.SetDefault(cfgRPCEndpoint, "http://localhost:30333")
|
||||||
v.config().SetDefault("server.0.address", testListenAddress)
|
v.SetDefault(cfgListenAddress, testListenAddress)
|
||||||
|
|
||||||
return v
|
return v
|
||||||
}
|
}
|
||||||
|
@ -477,7 +354,7 @@ func getPool(ctx context.Context, t *testing.T, key *keys.PrivateKey) *pool.Pool
|
||||||
return clientPool
|
return clientPool
|
||||||
}
|
}
|
||||||
|
|
||||||
func createContainer(ctx context.Context, t *testing.T, clientPool *pool.Pool, ownerID user.ID) (cid.ID, error) {
|
func createContainer(ctx context.Context, t *testing.T, clientPool *pool.Pool, ownerID user.ID, version string) (cid.ID, error) {
|
||||||
var policy netmap.PlacementPolicy
|
var policy netmap.PlacementPolicy
|
||||||
err := policy.DecodeString("REP 1")
|
err := policy.DecodeString("REP 1")
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
@ -490,11 +367,11 @@ func createContainer(ctx context.Context, t *testing.T, clientPool *pool.Pool, o
|
||||||
|
|
||||||
container.SetCreationTime(&cnr, time.Now())
|
container.SetCreationTime(&cnr, time.Now())
|
||||||
|
|
||||||
var domain container.Domain
|
if version >= versionWithNativeNames {
|
||||||
domain.SetName(testContainerName)
|
var domain container.Domain
|
||||||
|
domain.SetName(testContainerName)
|
||||||
cnr.SetAttribute(containerv2.SysAttributeName, domain.Name())
|
container.WriteDomain(&cnr, domain)
|
||||||
cnr.SetAttribute(containerv2.SysAttributeZone, domain.Zone())
|
}
|
||||||
|
|
||||||
var waitPrm pool.WaitParams
|
var waitPrm pool.WaitParams
|
||||||
waitPrm.SetTimeout(15 * time.Second)
|
waitPrm.SetTimeout(15 * time.Second)
|
||||||
|
@ -516,7 +393,7 @@ func createContainer(ctx context.Context, t *testing.T, clientPool *pool.Pool, o
|
||||||
func putObject(ctx context.Context, t *testing.T, clientPool *pool.Pool, ownerID user.ID, CID cid.ID, content string, attributes map[string]string) oid.ID {
|
func putObject(ctx context.Context, t *testing.T, clientPool *pool.Pool, ownerID user.ID, CID cid.ID, content string, attributes map[string]string) oid.ID {
|
||||||
obj := object.New()
|
obj := object.New()
|
||||||
obj.SetContainerID(CID)
|
obj.SetContainerID(CID)
|
||||||
obj.SetOwnerID(ownerID)
|
obj.SetOwnerID(&ownerID)
|
||||||
|
|
||||||
var attrs []object.Attribute
|
var attrs []object.Attribute
|
||||||
for key, val := range attributes {
|
for key, val := range attributes {
|
||||||
|
@ -534,57 +411,5 @@ func putObject(ctx context.Context, t *testing.T, clientPool *pool.Pool, ownerID
|
||||||
id, err := clientPool.PutObject(ctx, prm)
|
id, err := clientPool.PutObject(ctx, prm)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
return id.ObjectID
|
return id
|
||||||
}
|
|
||||||
|
|
||||||
func registerUser(t *testing.T, ctx context.Context, aioContainer testcontainers.Container, pathToWallet string) {
|
|
||||||
err := aioContainer.CopyFileToContainer(ctx, pathToWallet, "/usr/wallet.json", 644)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
_, _, err = aioContainer.Exec(ctx, []string{
|
|
||||||
"/usr/bin/frostfs-s3-authmate", "register-user",
|
|
||||||
"--wallet", "/usr/wallet.json",
|
|
||||||
"--rpc-endpoint", "http://localhost:30333",
|
|
||||||
"--contract-wallet", "/config/s3-gw-wallet.json"})
|
|
||||||
require.NoError(t, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func makeBearerTokens(t *testing.T, key *keys.PrivateKey, ownerID user.ID, version string) (jsonTokenBase64, binaryTokenBase64 string) {
|
|
||||||
tkn := new(bearer.Token)
|
|
||||||
tkn.ForUser(ownerID)
|
|
||||||
tkn.SetExp(10000)
|
|
||||||
|
|
||||||
if version == "1.2.7" {
|
|
||||||
tkn.SetEACLTable(*eacl.NewTable())
|
|
||||||
} else {
|
|
||||||
tkn.SetImpersonate(true)
|
|
||||||
}
|
|
||||||
|
|
||||||
err := tkn.Sign(key.PrivateKey)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
jsonToken, err := tkn.MarshalJSON()
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
jsonTokenBase64 = base64.StdEncoding.EncodeToString(jsonToken)
|
|
||||||
binaryTokenBase64 = base64.StdEncoding.EncodeToString(tkn.Marshal())
|
|
||||||
|
|
||||||
require.NotEmpty(t, jsonTokenBase64)
|
|
||||||
require.NotEmpty(t, binaryTokenBase64)
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func makeTempWallet(t *testing.T, key *keys.PrivateKey, path string) {
|
|
||||||
w, err := wallet.NewWallet(path)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
acc := wallet.NewAccountFromPrivateKey(key)
|
|
||||||
err = acc.Encrypt("", w.Scrypt)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
w.AddAccount(acc)
|
|
||||||
|
|
||||||
err = w.Save()
|
|
||||||
require.NoError(t, err)
|
|
||||||
}
|
}
|
111
internal/cache/buckets.go
vendored
111
internal/cache/buckets.go
vendored
|
@ -1,111 +0,0 @@
|
||||||
package cache
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/data"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/logs"
|
|
||||||
cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id"
|
|
||||||
"github.com/bluele/gcache"
|
|
||||||
"go.uber.org/zap"
|
|
||||||
)
|
|
||||||
|
|
||||||
// BucketCache contains cache with objects and the lifetime of cache entries.
|
|
||||||
type BucketCache struct {
|
|
||||||
cache gcache.Cache
|
|
||||||
cidCache gcache.Cache
|
|
||||||
logger *zap.Logger
|
|
||||||
}
|
|
||||||
|
|
||||||
// Config stores expiration params for cache.
|
|
||||||
type Config struct {
|
|
||||||
Size int
|
|
||||||
Lifetime time.Duration
|
|
||||||
Logger *zap.Logger
|
|
||||||
}
|
|
||||||
|
|
||||||
const (
|
|
||||||
// DefaultBucketCacheSize is a default maximum number of entries in cache.
|
|
||||||
DefaultBucketCacheSize = 1e3
|
|
||||||
// DefaultBucketCacheLifetime is a default lifetime of entries in cache.
|
|
||||||
DefaultBucketCacheLifetime = time.Minute
|
|
||||||
)
|
|
||||||
|
|
||||||
// DefaultBucketConfig returns new default cache expiration values.
|
|
||||||
func DefaultBucketConfig(logger *zap.Logger) *Config {
|
|
||||||
return &Config{
|
|
||||||
Size: DefaultBucketCacheSize,
|
|
||||||
Lifetime: DefaultBucketCacheLifetime,
|
|
||||||
Logger: logger,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewBucketCache creates an object of BucketCache.
|
|
||||||
func NewBucketCache(config *Config, cidCache bool) *BucketCache {
|
|
||||||
cache := &BucketCache{
|
|
||||||
cache: gcache.New(config.Size).LRU().Expiration(config.Lifetime).Build(),
|
|
||||||
logger: config.Logger,
|
|
||||||
}
|
|
||||||
|
|
||||||
if cidCache {
|
|
||||||
cache.cidCache = gcache.New(config.Size).LRU().Expiration(config.Lifetime).Build()
|
|
||||||
}
|
|
||||||
return cache
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get returns a cached object.
|
|
||||||
func (o *BucketCache) Get(ns, bktName string) *data.BucketInfo {
|
|
||||||
return o.get(formKey(ns, bktName))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o *BucketCache) GetByCID(cnrID cid.ID) *data.BucketInfo {
|
|
||||||
if o.cidCache == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
entry, err := o.cidCache.Get(cnrID)
|
|
||||||
if err != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
key, ok := entry.(string)
|
|
||||||
if !ok {
|
|
||||||
o.logger.Warn(logs.InvalidCacheEntryType, zap.String("actual", fmt.Sprintf("%T", entry)),
|
|
||||||
zap.String("expected", fmt.Sprintf("%T", key)), logs.TagField(logs.TagDatapath))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return o.get(key)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o *BucketCache) get(key string) *data.BucketInfo {
|
|
||||||
entry, err := o.cache.Get(key)
|
|
||||||
if err != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
result, ok := entry.(*data.BucketInfo)
|
|
||||||
if !ok {
|
|
||||||
o.logger.Warn(logs.InvalidCacheEntryType, zap.String("actual", fmt.Sprintf("%T", entry)),
|
|
||||||
zap.String("expected", fmt.Sprintf("%T", result)), logs.TagField(logs.TagDatapath))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
// Put puts an object to cache.
|
|
||||||
func (o *BucketCache) Put(bkt *data.BucketInfo) error {
|
|
||||||
if o.cidCache != nil {
|
|
||||||
if err := o.cidCache.Set(bkt.CID, formKey(bkt.Zone, bkt.Name)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return o.cache.Set(formKey(bkt.Zone, bkt.Name), bkt)
|
|
||||||
}
|
|
||||||
|
|
||||||
func formKey(ns, name string) string {
|
|
||||||
return name + "." + ns
|
|
||||||
}
|
|
65
internal/cache/netmap.go
vendored
65
internal/cache/netmap.go
vendored
|
@ -1,65 +0,0 @@
|
||||||
package cache
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/logs"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/netmap"
|
|
||||||
"github.com/bluele/gcache"
|
|
||||||
"go.uber.org/zap"
|
|
||||||
)
|
|
||||||
|
|
||||||
type (
|
|
||||||
// NetmapCache provides cache for netmap.
|
|
||||||
NetmapCache struct {
|
|
||||||
cache gcache.Cache
|
|
||||||
logger *zap.Logger
|
|
||||||
}
|
|
||||||
|
|
||||||
// NetmapCacheConfig stores expiration params for cache.
|
|
||||||
NetmapCacheConfig struct {
|
|
||||||
Lifetime time.Duration
|
|
||||||
Logger *zap.Logger
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
DefaultNetmapCacheLifetime = time.Minute
|
|
||||||
netmapCacheSize = 1
|
|
||||||
netmapKey = "netmap"
|
|
||||||
)
|
|
||||||
|
|
||||||
// DefaultNetmapConfig returns new default cache expiration values.
|
|
||||||
func DefaultNetmapConfig(logger *zap.Logger) *NetmapCacheConfig {
|
|
||||||
return &NetmapCacheConfig{
|
|
||||||
Lifetime: DefaultNetmapCacheLifetime,
|
|
||||||
Logger: logger,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewNetmapCache creates an object of NetmapCache.
|
|
||||||
func NewNetmapCache(config *NetmapCacheConfig) *NetmapCache {
|
|
||||||
gc := gcache.New(netmapCacheSize).LRU().Expiration(config.Lifetime).Build()
|
|
||||||
return &NetmapCache{cache: gc, logger: config.Logger}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *NetmapCache) Get() *netmap.NetMap {
|
|
||||||
entry, err := c.cache.Get(netmapKey)
|
|
||||||
if err != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
result, ok := entry.(netmap.NetMap)
|
|
||||||
if !ok {
|
|
||||||
c.logger.Warn(logs.InvalidCacheEntryType, zap.String("actual", fmt.Sprintf("%T", entry)),
|
|
||||||
zap.String("expected", fmt.Sprintf("%T", result)), logs.TagField(logs.TagDatapath))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return &result
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *NetmapCache) Put(nm netmap.NetMap) error {
|
|
||||||
return c.cache.Set(netmapKey, nm)
|
|
||||||
}
|
|
|
@ -1,14 +0,0 @@
|
||||||
package data
|
|
||||||
|
|
||||||
import (
|
|
||||||
cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/netmap"
|
|
||||||
)
|
|
||||||
|
|
||||||
type BucketInfo struct {
|
|
||||||
Name string // container name from system attribute
|
|
||||||
Zone string // container zone from system attribute
|
|
||||||
CID cid.ID
|
|
||||||
HomomorphicHashDisabled bool
|
|
||||||
PlacementPolicy netmap.PlacementPolicy
|
|
||||||
}
|
|
|
@ -1,27 +0,0 @@
|
||||||
package data
|
|
||||||
|
|
||||||
import (
|
|
||||||
oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
|
|
||||||
)
|
|
||||||
|
|
||||||
// NodeVersion represent node from tree service.
|
|
||||||
type NodeVersion struct {
|
|
||||||
BaseNodeVersion
|
|
||||||
}
|
|
||||||
|
|
||||||
// BaseNodeVersion is minimal node info from tree service.
|
|
||||||
// Basically used for "system" object.
|
|
||||||
type BaseNodeVersion struct {
|
|
||||||
ID uint64
|
|
||||||
OID oid.ID
|
|
||||||
IsDeleteMarker bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type NodeInfo struct {
|
|
||||||
Meta []NodeMeta
|
|
||||||
}
|
|
||||||
|
|
||||||
type NodeMeta interface {
|
|
||||||
GetKey() string
|
|
||||||
GetValue() []byte
|
|
||||||
}
|
|
|
@ -1,382 +0,0 @@
|
||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"html/template"
|
|
||||||
"net/url"
|
|
||||||
"sort"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/data"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/logs"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/utils"
|
|
||||||
cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object"
|
|
||||||
oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
|
|
||||||
"github.com/docker/go-units"
|
|
||||||
"github.com/valyala/fasthttp"
|
|
||||||
"go.uber.org/zap"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
dateFormat = "02-01-2006 15:04"
|
|
||||||
attrOID = "OID"
|
|
||||||
attrCreated = "Created"
|
|
||||||
attrFileName = "FileName"
|
|
||||||
attrFilePath = "FilePath"
|
|
||||||
attrSize = "Size"
|
|
||||||
attrDeleteMarker = "IsDeleteMarker"
|
|
||||||
)
|
|
||||||
|
|
||||||
type (
|
|
||||||
BrowsePageData struct {
|
|
||||||
HasErrors bool
|
|
||||||
Container string
|
|
||||||
Prefix string
|
|
||||||
Protocol string
|
|
||||||
Objects []ResponseObject
|
|
||||||
}
|
|
||||||
ResponseObject struct {
|
|
||||||
OID string
|
|
||||||
Created string
|
|
||||||
FileName string
|
|
||||||
FilePath string
|
|
||||||
Size string
|
|
||||||
IsDir bool
|
|
||||||
GetURL string
|
|
||||||
IsDeleteMarker bool
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
func newListObjectsResponseS3(attrs map[string]string) ResponseObject {
|
|
||||||
return ResponseObject{
|
|
||||||
Created: formatTimestamp(attrs[attrCreated]),
|
|
||||||
OID: attrs[attrOID],
|
|
||||||
FileName: attrs[attrFileName],
|
|
||||||
Size: attrs[attrSize],
|
|
||||||
IsDir: attrs[attrOID] == "",
|
|
||||||
IsDeleteMarker: attrs[attrDeleteMarker] == "true",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func newListObjectsResponseNative(attrs map[string]string) ResponseObject {
|
|
||||||
filename := lastPathElement(attrs[object.AttributeFilePath])
|
|
||||||
if filename == "" {
|
|
||||||
filename = attrs[attrFileName]
|
|
||||||
}
|
|
||||||
return ResponseObject{
|
|
||||||
OID: attrs[attrOID],
|
|
||||||
Created: formatTimestamp(attrs[object.AttributeTimestamp] + "000"),
|
|
||||||
FileName: filename,
|
|
||||||
FilePath: attrs[object.AttributeFilePath],
|
|
||||||
Size: attrs[attrSize],
|
|
||||||
IsDir: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func getNextDir(filepath, prefix string) string {
|
|
||||||
restPath := strings.Replace(filepath, prefix, "", 1)
|
|
||||||
index := strings.Index(restPath, "/")
|
|
||||||
if index == -1 {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return restPath[:index]
|
|
||||||
}
|
|
||||||
|
|
||||||
func lastPathElement(path string) string {
|
|
||||||
if path == "" {
|
|
||||||
return path
|
|
||||||
}
|
|
||||||
index := strings.LastIndex(path, "/")
|
|
||||||
if index == len(path)-1 {
|
|
||||||
index = strings.LastIndex(path[:index], "/")
|
|
||||||
}
|
|
||||||
return path[index+1:]
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseTimestamp(tstamp string) (time.Time, error) {
|
|
||||||
millis, err := strconv.ParseInt(tstamp, 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
return time.Time{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return time.UnixMilli(millis), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func formatTimestamp(strdate string) string {
|
|
||||||
date, err := parseTimestamp(strdate)
|
|
||||||
if err != nil || date.IsZero() {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
return date.Format(dateFormat)
|
|
||||||
}
|
|
||||||
|
|
||||||
func formatSize(strsize string) string {
|
|
||||||
size, err := strconv.ParseFloat(strsize, 64)
|
|
||||||
if err != nil {
|
|
||||||
return "0B"
|
|
||||||
}
|
|
||||||
return units.HumanSize(size)
|
|
||||||
}
|
|
||||||
|
|
||||||
func parentDir(prefix string) string {
|
|
||||||
index := strings.LastIndex(prefix, "/")
|
|
||||||
if index == -1 {
|
|
||||||
return prefix
|
|
||||||
}
|
|
||||||
return prefix[index:]
|
|
||||||
}
|
|
||||||
|
|
||||||
func trimPrefix(encPrefix string) string {
|
|
||||||
prefix, err := url.PathUnescape(encPrefix)
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
slashIndex := strings.LastIndex(prefix, "/")
|
|
||||||
if slashIndex == -1 {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return prefix[:slashIndex]
|
|
||||||
}
|
|
||||||
|
|
||||||
func urlencode(path string) string {
|
|
||||||
var res strings.Builder
|
|
||||||
|
|
||||||
prefixParts := strings.Split(path, "/")
|
|
||||||
for _, prefixPart := range prefixParts {
|
|
||||||
prefixPart = "/" + url.PathEscape(prefixPart)
|
|
||||||
if prefixPart == "/." || prefixPart == "/.." {
|
|
||||||
prefixPart = url.PathEscape(prefixPart)
|
|
||||||
}
|
|
||||||
res.WriteString(prefixPart)
|
|
||||||
}
|
|
||||||
|
|
||||||
return res.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetObjectsResponse struct {
|
|
||||||
objects []ResponseObject
|
|
||||||
hasErrors bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) getDirObjectsS3(ctx context.Context, bucketInfo *data.BucketInfo, prefix string) (*GetObjectsResponse, error) {
|
|
||||||
nodes, _, err := h.tree.GetSubTreeByPrefix(ctx, bucketInfo, prefix, true)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
result := &GetObjectsResponse{
|
|
||||||
objects: make([]ResponseObject, 0, len(nodes)),
|
|
||||||
}
|
|
||||||
for _, node := range nodes {
|
|
||||||
meta := node.Meta
|
|
||||||
if meta == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
var attrs = make(map[string]string, len(meta))
|
|
||||||
for _, m := range meta {
|
|
||||||
attrs[m.GetKey()] = string(m.GetValue())
|
|
||||||
}
|
|
||||||
obj := newListObjectsResponseS3(attrs)
|
|
||||||
if obj.IsDeleteMarker {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
obj.FilePath = prefix + obj.FileName
|
|
||||||
obj.GetURL = "/get/" + bucketInfo.Name + urlencode(obj.FilePath)
|
|
||||||
result.objects = append(result.objects, obj)
|
|
||||||
}
|
|
||||||
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) getDirObjectsNative(ctx context.Context, bucketInfo *data.BucketInfo, prefix string) (*GetObjectsResponse, error) {
|
|
||||||
var basePath string
|
|
||||||
if ind := strings.LastIndex(prefix, "/"); ind != -1 {
|
|
||||||
basePath = prefix[:ind+1]
|
|
||||||
}
|
|
||||||
|
|
||||||
filters := object.NewSearchFilters()
|
|
||||||
filters.AddRootFilter()
|
|
||||||
if prefix != "" {
|
|
||||||
filters.AddFilter(object.AttributeFilePath, prefix, object.MatchCommonPrefix)
|
|
||||||
}
|
|
||||||
|
|
||||||
prm := PrmObjectSearch{
|
|
||||||
PrmAuth: PrmAuth{
|
|
||||||
BearerToken: bearerToken(ctx),
|
|
||||||
},
|
|
||||||
Container: bucketInfo.CID,
|
|
||||||
Filters: filters,
|
|
||||||
}
|
|
||||||
objectIDs, err := h.frostfs.SearchObjects(ctx, prm)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer objectIDs.Close()
|
|
||||||
|
|
||||||
resp, err := h.headDirObjects(ctx, bucketInfo.CID, objectIDs, basePath)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
log := utils.GetReqLogOrDefault(ctx, h.log)
|
|
||||||
dirs := make(map[string]struct{})
|
|
||||||
result := &GetObjectsResponse{
|
|
||||||
objects: make([]ResponseObject, 0, 100),
|
|
||||||
}
|
|
||||||
for objExt := range resp {
|
|
||||||
if objExt.Error != nil {
|
|
||||||
log.Error(logs.FailedToHeadObject, zap.Error(objExt.Error), logs.TagField(logs.TagExternalStorage))
|
|
||||||
result.hasErrors = true
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if objExt.Object.IsDir {
|
|
||||||
if _, ok := dirs[objExt.Object.FileName]; ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
objExt.Object.GetURL = "/get/" + bucketInfo.CID.EncodeToString() + urlencode(objExt.Object.FilePath)
|
|
||||||
dirs[objExt.Object.FileName] = struct{}{}
|
|
||||||
} else {
|
|
||||||
objExt.Object.GetURL = "/get/" + bucketInfo.CID.EncodeToString() + "/" + objExt.Object.OID
|
|
||||||
}
|
|
||||||
result.objects = append(result.objects, objExt.Object)
|
|
||||||
}
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type ResponseObjectExtended struct {
|
|
||||||
Object ResponseObject
|
|
||||||
Error error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) headDirObjects(ctx context.Context, cnrID cid.ID, objectIDs ResObjectSearch, basePath string) (<-chan ResponseObjectExtended, error) {
|
|
||||||
res := make(chan ResponseObjectExtended)
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
defer close(res)
|
|
||||||
log := utils.GetReqLogOrDefault(ctx, h.log).With(
|
|
||||||
zap.String("cid", cnrID.EncodeToString()),
|
|
||||||
zap.String("path", basePath),
|
|
||||||
)
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
err := objectIDs.Iterate(func(id oid.ID) bool {
|
|
||||||
wg.Add(1)
|
|
||||||
err := h.workerPool.Submit(func() {
|
|
||||||
defer wg.Done()
|
|
||||||
var obj ResponseObjectExtended
|
|
||||||
obj.Object, obj.Error = h.headDirObject(ctx, cnrID, id, basePath)
|
|
||||||
res <- obj
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
wg.Done()
|
|
||||||
log.Warn(logs.FailedToSumbitTaskToPool, zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
}
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return true
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
log.Error(logs.FailedToIterateOverResponse, zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
}
|
|
||||||
wg.Wait()
|
|
||||||
}()
|
|
||||||
|
|
||||||
return res, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) headDirObject(ctx context.Context, cnrID cid.ID, objID oid.ID, basePath string) (ResponseObject, error) {
|
|
||||||
addr := newAddress(cnrID, objID)
|
|
||||||
obj, err := h.frostfs.HeadObject(ctx, PrmObjectHead{
|
|
||||||
PrmAuth: PrmAuth{BearerToken: bearerToken(ctx)},
|
|
||||||
Address: addr,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return ResponseObject{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
attrs := loadAttributes(obj.Attributes())
|
|
||||||
attrs[attrOID] = objID.EncodeToString()
|
|
||||||
if multipartSize, ok := attrs[attributeMultipartObjectSize]; ok {
|
|
||||||
attrs[attrSize] = multipartSize
|
|
||||||
} else {
|
|
||||||
attrs[attrSize] = strconv.FormatUint(obj.PayloadSize(), 10)
|
|
||||||
}
|
|
||||||
|
|
||||||
dirname := getNextDir(attrs[object.AttributeFilePath], basePath)
|
|
||||||
if dirname == "" {
|
|
||||||
return newListObjectsResponseNative(attrs), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return ResponseObject{
|
|
||||||
FileName: dirname,
|
|
||||||
FilePath: basePath + dirname,
|
|
||||||
IsDir: true,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type browseParams struct {
|
|
||||||
bucketInfo *data.BucketInfo
|
|
||||||
prefix string
|
|
||||||
isNative bool
|
|
||||||
listObjects func(ctx context.Context, bucketName *data.BucketInfo, prefix string) (*GetObjectsResponse, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) browseObjects(c *fasthttp.RequestCtx, p browseParams) {
|
|
||||||
const S3Protocol = "s3"
|
|
||||||
const FrostfsProtocol = "frostfs"
|
|
||||||
|
|
||||||
ctx := utils.GetContextFromRequest(c)
|
|
||||||
reqLog := utils.GetReqLogOrDefault(ctx, h.log)
|
|
||||||
log := reqLog.With(
|
|
||||||
zap.String("bucket", p.bucketInfo.Name),
|
|
||||||
zap.String("container", p.bucketInfo.CID.EncodeToString()),
|
|
||||||
zap.String("prefix", p.prefix),
|
|
||||||
)
|
|
||||||
resp, err := p.listObjects(ctx, p.bucketInfo, p.prefix)
|
|
||||||
if err != nil {
|
|
||||||
logAndSendBucketError(c, log, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
objects := resp.objects
|
|
||||||
sort.Slice(objects, func(i, j int) bool {
|
|
||||||
if objects[i].IsDir == objects[j].IsDir {
|
|
||||||
return objects[i].FileName < objects[j].FileName
|
|
||||||
}
|
|
||||||
return objects[i].IsDir
|
|
||||||
})
|
|
||||||
|
|
||||||
tmpl, err := template.New("index").Funcs(template.FuncMap{
|
|
||||||
"formatSize": formatSize,
|
|
||||||
"trimPrefix": trimPrefix,
|
|
||||||
"urlencode": urlencode,
|
|
||||||
"parentDir": parentDir,
|
|
||||||
}).Parse(h.config.IndexPageTemplate())
|
|
||||||
if err != nil {
|
|
||||||
logAndSendBucketError(c, log, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
bucketName := p.bucketInfo.Name
|
|
||||||
protocol := S3Protocol
|
|
||||||
if p.isNative {
|
|
||||||
bucketName = p.bucketInfo.CID.EncodeToString()
|
|
||||||
protocol = FrostfsProtocol
|
|
||||||
}
|
|
||||||
if err = tmpl.Execute(c, &BrowsePageData{
|
|
||||||
Container: bucketName,
|
|
||||||
Prefix: p.prefix,
|
|
||||||
Objects: objects,
|
|
||||||
Protocol: protocol,
|
|
||||||
HasErrors: resp.hasErrors,
|
|
||||||
}); err != nil {
|
|
||||||
logAndSendBucketError(c, log, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,321 +0,0 @@
|
||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"archive/tar"
|
|
||||||
"archive/zip"
|
|
||||||
"bufio"
|
|
||||||
"compress/gzip"
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net/url"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/data"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/layer"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/logs"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/utils"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-observability/tracing"
|
|
||||||
cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object"
|
|
||||||
oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
|
|
||||||
"github.com/valyala/fasthttp"
|
|
||||||
"go.uber.org/zap"
|
|
||||||
)
|
|
||||||
|
|
||||||
// DownloadByAddressOrBucketName handles download requests using simple cid/oid or bucketname/key format.
|
|
||||||
func (h *Handler) DownloadByAddressOrBucketName(c *fasthttp.RequestCtx) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(utils.GetContextFromRequest(c), "handler.DownloadByAddressOrBucketName")
|
|
||||||
defer span.End()
|
|
||||||
utils.SetContextToRequest(ctx, c)
|
|
||||||
|
|
||||||
cidParam := c.UserValue("cid").(string)
|
|
||||||
oidParam := c.UserValue("oid").(string)
|
|
||||||
downloadParam := c.QueryArgs().GetBool("download")
|
|
||||||
|
|
||||||
log := utils.GetReqLogOrDefault(ctx, h.log).With(
|
|
||||||
zap.String("cid", cidParam),
|
|
||||||
zap.String("oid", oidParam),
|
|
||||||
)
|
|
||||||
|
|
||||||
bktInfo, err := h.getBucketInfo(ctx, cidParam, log)
|
|
||||||
if err != nil {
|
|
||||||
logAndSendBucketError(c, log, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
checkS3Err := h.tree.CheckSettingsNodeExists(ctx, bktInfo)
|
|
||||||
if checkS3Err != nil && !errors.Is(checkS3Err, layer.ErrNodeNotFound) {
|
|
||||||
log.Error(logs.FailedToCheckIfSettingsNodeExist, zap.String("cid", bktInfo.CID.String()),
|
|
||||||
zap.Error(checkS3Err), logs.TagField(logs.TagExternalStorageTree))
|
|
||||||
logAndSendBucketError(c, log, checkS3Err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
req := newRequest(c, log)
|
|
||||||
|
|
||||||
var objID oid.ID
|
|
||||||
if checkS3Err == nil && shouldDownload(oidParam, downloadParam) {
|
|
||||||
h.byS3Path(ctx, req, bktInfo.CID, oidParam, h.receiveFile)
|
|
||||||
} else if err = objID.DecodeString(oidParam); err == nil {
|
|
||||||
h.byNativeAddress(ctx, req, bktInfo.CID, objID, h.receiveFile)
|
|
||||||
} else {
|
|
||||||
h.browseIndex(c, checkS3Err != nil)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func shouldDownload(oidParam string, downloadParam bool) bool {
|
|
||||||
return !isDir(oidParam) || downloadParam
|
|
||||||
}
|
|
||||||
|
|
||||||
// DownloadByAttribute handles attribute-based download requests.
|
|
||||||
func (h *Handler) DownloadByAttribute(c *fasthttp.RequestCtx) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(utils.GetContextFromRequest(c), "handler.DownloadByAttribute")
|
|
||||||
defer span.End()
|
|
||||||
utils.SetContextToRequest(ctx, c)
|
|
||||||
|
|
||||||
h.byAttribute(c, h.receiveFile)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) search(ctx context.Context, cnrID cid.ID, key, val string, op object.SearchMatchType) (ResObjectSearch, error) {
|
|
||||||
filters := object.NewSearchFilters()
|
|
||||||
filters.AddRootFilter()
|
|
||||||
filters.AddFilter(key, val, op)
|
|
||||||
|
|
||||||
prm := PrmObjectSearch{
|
|
||||||
PrmAuth: PrmAuth{
|
|
||||||
BearerToken: bearerToken(ctx),
|
|
||||||
},
|
|
||||||
Container: cnrID,
|
|
||||||
Filters: filters,
|
|
||||||
}
|
|
||||||
|
|
||||||
return h.frostfs.SearchObjects(ctx, prm)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DownloadZip handles zip by prefix requests.
|
|
||||||
func (h *Handler) DownloadZip(c *fasthttp.RequestCtx) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(utils.GetContextFromRequest(c), "handler.DownloadZip")
|
|
||||||
defer span.End()
|
|
||||||
utils.SetContextToRequest(ctx, c)
|
|
||||||
|
|
||||||
scid, _ := c.UserValue("cid").(string)
|
|
||||||
|
|
||||||
log := utils.GetReqLogOrDefault(ctx, h.log)
|
|
||||||
bktInfo, err := h.getBucketInfo(ctx, scid, log)
|
|
||||||
if err != nil {
|
|
||||||
logAndSendBucketError(c, log, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
resSearch, err := h.searchObjectsByPrefix(c, log, bktInfo.CID)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.Response.Header.Set(fasthttp.HeaderContentType, "application/zip")
|
|
||||||
c.Response.Header.Set(fasthttp.HeaderContentDisposition, "attachment; filename=\"archive.zip\"")
|
|
||||||
|
|
||||||
c.SetBodyStreamWriter(h.getZipResponseWriter(ctx, log, resSearch, bktInfo))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) getZipResponseWriter(ctx context.Context, log *zap.Logger, resSearch ResObjectSearch, bktInfo *data.BucketInfo) func(w *bufio.Writer) {
|
|
||||||
return func(w *bufio.Writer) {
|
|
||||||
defer resSearch.Close()
|
|
||||||
|
|
||||||
buf := make([]byte, 3<<20)
|
|
||||||
zipWriter := zip.NewWriter(w)
|
|
||||||
var objectsWritten int
|
|
||||||
|
|
||||||
errIter := resSearch.Iterate(h.putObjectToArchive(ctx, log, bktInfo.CID, buf,
|
|
||||||
func(obj *object.Object) (io.Writer, error) {
|
|
||||||
objectsWritten++
|
|
||||||
return h.createZipFile(zipWriter, obj)
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
if errIter != nil {
|
|
||||||
log.Error(logs.IteratingOverSelectedObjectsFailed, zap.Error(errIter), logs.TagField(logs.TagDatapath))
|
|
||||||
return
|
|
||||||
} else if objectsWritten == 0 {
|
|
||||||
log.Warn(logs.ObjectsNotFound, logs.TagField(logs.TagDatapath))
|
|
||||||
}
|
|
||||||
if err := zipWriter.Close(); err != nil {
|
|
||||||
log.Error(logs.CloseZipWriter, zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) createZipFile(zw *zip.Writer, obj *object.Object) (io.Writer, error) {
|
|
||||||
method := zip.Store
|
|
||||||
if h.config.ArchiveCompression() {
|
|
||||||
method = zip.Deflate
|
|
||||||
}
|
|
||||||
|
|
||||||
filePath := getFilePath(obj)
|
|
||||||
if len(filePath) == 0 || filePath[len(filePath)-1] == '/' {
|
|
||||||
return nil, fmt.Errorf("invalid filepath '%s'", filePath)
|
|
||||||
}
|
|
||||||
|
|
||||||
return zw.CreateHeader(&zip.FileHeader{
|
|
||||||
Name: filePath,
|
|
||||||
Method: method,
|
|
||||||
Modified: time.Now(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// DownloadTar forms tar.gz from objects by prefix.
|
|
||||||
func (h *Handler) DownloadTar(c *fasthttp.RequestCtx) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(utils.GetContextFromRequest(c), "handler.DownloadTar")
|
|
||||||
defer span.End()
|
|
||||||
utils.SetContextToRequest(ctx, c)
|
|
||||||
|
|
||||||
scid, _ := c.UserValue("cid").(string)
|
|
||||||
|
|
||||||
log := utils.GetReqLogOrDefault(ctx, h.log)
|
|
||||||
bktInfo, err := h.getBucketInfo(ctx, scid, log)
|
|
||||||
if err != nil {
|
|
||||||
logAndSendBucketError(c, log, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
resSearch, err := h.searchObjectsByPrefix(c, log, bktInfo.CID)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.Response.Header.Set(fasthttp.HeaderContentType, "application/gzip")
|
|
||||||
c.Response.Header.Set(fasthttp.HeaderContentDisposition, "attachment; filename=\"archive.tar.gz\"")
|
|
||||||
|
|
||||||
c.SetBodyStreamWriter(h.getTarResponseWriter(ctx, log, resSearch, bktInfo))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) getTarResponseWriter(ctx context.Context, log *zap.Logger, resSearch ResObjectSearch, bktInfo *data.BucketInfo) func(w *bufio.Writer) {
|
|
||||||
return func(w *bufio.Writer) {
|
|
||||||
defer resSearch.Close()
|
|
||||||
|
|
||||||
compressionLevel := gzip.NoCompression
|
|
||||||
if h.config.ArchiveCompression() {
|
|
||||||
compressionLevel = gzip.DefaultCompression
|
|
||||||
}
|
|
||||||
|
|
||||||
// ignore error because it's not nil only if compressionLevel argument is invalid
|
|
||||||
gzipWriter, _ := gzip.NewWriterLevel(w, compressionLevel)
|
|
||||||
tarWriter := tar.NewWriter(gzipWriter)
|
|
||||||
|
|
||||||
defer func() {
|
|
||||||
if err := tarWriter.Close(); err != nil {
|
|
||||||
log.Error(logs.CloseTarWriter, zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
}
|
|
||||||
if err := gzipWriter.Close(); err != nil {
|
|
||||||
log.Error(logs.CloseGzipWriter, zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
var objectsWritten int
|
|
||||||
buf := make([]byte, 3<<20) // the same as for upload
|
|
||||||
|
|
||||||
errIter := resSearch.Iterate(h.putObjectToArchive(ctx, log, bktInfo.CID, buf,
|
|
||||||
func(obj *object.Object) (io.Writer, error) {
|
|
||||||
objectsWritten++
|
|
||||||
return h.createTarFile(tarWriter, obj)
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
if errIter != nil {
|
|
||||||
log.Error(logs.IteratingOverSelectedObjectsFailed, zap.Error(errIter), logs.TagField(logs.TagDatapath))
|
|
||||||
} else if objectsWritten == 0 {
|
|
||||||
log.Warn(logs.ObjectsNotFound, logs.TagField(logs.TagDatapath))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) createTarFile(tw *tar.Writer, obj *object.Object) (io.Writer, error) {
|
|
||||||
filePath := getFilePath(obj)
|
|
||||||
if len(filePath) == 0 || filePath[len(filePath)-1] == '/' {
|
|
||||||
return nil, fmt.Errorf("invalid filepath '%s'", filePath)
|
|
||||||
}
|
|
||||||
|
|
||||||
return tw, tw.WriteHeader(&tar.Header{
|
|
||||||
Name: filePath,
|
|
||||||
Mode: 0655,
|
|
||||||
Size: int64(obj.PayloadSize()),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) putObjectToArchive(ctx context.Context, log *zap.Logger, cnrID cid.ID, buf []byte, createArchiveHeader func(obj *object.Object) (io.Writer, error)) func(id oid.ID) bool {
|
|
||||||
return func(id oid.ID) bool {
|
|
||||||
log = log.With(zap.String("oid", id.EncodeToString()))
|
|
||||||
|
|
||||||
prm := PrmObjectGet{
|
|
||||||
PrmAuth: PrmAuth{
|
|
||||||
BearerToken: bearerToken(ctx),
|
|
||||||
},
|
|
||||||
Address: newAddress(cnrID, id),
|
|
||||||
}
|
|
||||||
|
|
||||||
resGet, err := h.frostfs.GetObject(ctx, prm)
|
|
||||||
if err != nil {
|
|
||||||
log.Error(logs.FailedToGetObject, zap.Error(err), logs.TagField(logs.TagExternalStorage))
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
fileWriter, err := createArchiveHeader(&resGet.Header)
|
|
||||||
if err != nil {
|
|
||||||
log.Error(logs.FailedToAddObjectToArchive, zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if err = writeToArchive(resGet, fileWriter, buf); err != nil {
|
|
||||||
log.Error(logs.FailedToAddObjectToArchive, zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) searchObjectsByPrefix(c *fasthttp.RequestCtx, log *zap.Logger, cnrID cid.ID) (ResObjectSearch, error) {
|
|
||||||
scid, _ := c.UserValue("cid").(string)
|
|
||||||
prefix, _ := c.UserValue("prefix").(string)
|
|
||||||
|
|
||||||
ctx := utils.GetContextFromRequest(c)
|
|
||||||
|
|
||||||
prefix, err := url.QueryUnescape(prefix)
|
|
||||||
if err != nil {
|
|
||||||
log.Error(logs.FailedToUnescapeQuery, zap.String("cid", scid), zap.String("prefix", prefix),
|
|
||||||
zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
ResponseError(c, "could not unescape prefix: "+err.Error(), fasthttp.StatusBadRequest)
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
log = log.With(zap.String("cid", scid), zap.String("prefix", prefix))
|
|
||||||
|
|
||||||
resSearch, err := h.search(ctx, cnrID, object.AttributeFilePath, prefix, object.MatchCommonPrefix)
|
|
||||||
if err != nil {
|
|
||||||
log.Error(logs.CouldNotSearchForObjects, zap.Error(err), logs.TagField(logs.TagExternalStorage))
|
|
||||||
ResponseError(c, "could not search for objects: "+err.Error(), fasthttp.StatusBadRequest)
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return resSearch, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeToArchive(resGet *Object, objWriter io.Writer, buf []byte) error {
|
|
||||||
var err error
|
|
||||||
if _, err = io.CopyBuffer(objWriter, resGet.Payload, buf); err != nil {
|
|
||||||
return fmt.Errorf("copy object payload to zip file: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err = resGet.Payload.Close(); err != nil {
|
|
||||||
return fmt.Errorf("object body close error: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func getFilePath(obj *object.Object) string {
|
|
||||||
for _, attr := range obj.Attributes() {
|
|
||||||
if attr.Key() == object.AttributeFilePath {
|
|
||||||
return attr.Value()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return ""
|
|
||||||
}
|
|
|
@ -1,58 +0,0 @@
|
||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/logs"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/utils"
|
|
||||||
"github.com/valyala/fasthttp"
|
|
||||||
"go.uber.org/zap"
|
|
||||||
)
|
|
||||||
|
|
||||||
func filterHeaders(l *zap.Logger, header *fasthttp.RequestHeader) (map[string]string, error) {
|
|
||||||
var err error
|
|
||||||
result := make(map[string]string)
|
|
||||||
prefix := []byte(utils.UserAttributeHeaderPrefix)
|
|
||||||
|
|
||||||
header.VisitAll(func(key, val []byte) {
|
|
||||||
// checks that the key and the val not empty
|
|
||||||
if len(key) == 0 || len(val) == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// checks that the key has attribute prefix
|
|
||||||
if !bytes.HasPrefix(key, prefix) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// removing attribute prefix
|
|
||||||
clearKey := bytes.TrimPrefix(key, prefix)
|
|
||||||
|
|
||||||
clearKey = utils.TransformIfSystem(clearKey)
|
|
||||||
|
|
||||||
// checks that the attribute key is not empty
|
|
||||||
if len(clearKey) == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// check if key gets duplicated
|
|
||||||
// return error containing full key name (with prefix)
|
|
||||||
if _, ok := result[string(clearKey)]; ok {
|
|
||||||
err = fmt.Errorf("key duplication error: %s", string(key))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// make string representation of key / val
|
|
||||||
k, v := string(clearKey), string(val)
|
|
||||||
|
|
||||||
result[k] = v
|
|
||||||
|
|
||||||
l.Debug(logs.AddAttributeToResultObject,
|
|
||||||
zap.String("key", k),
|
|
||||||
zap.String("val", v),
|
|
||||||
logs.TagField(logs.TagDatapath))
|
|
||||||
})
|
|
||||||
|
|
||||||
return result, err
|
|
||||||
}
|
|
|
@ -1,53 +0,0 @@
|
||||||
//go:build !integration
|
|
||||||
|
|
||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
"github.com/valyala/fasthttp"
|
|
||||||
"go.uber.org/zap"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestFilter(t *testing.T) {
|
|
||||||
log := zap.NewNop()
|
|
||||||
|
|
||||||
t.Run("duplicate keys error", func(t *testing.T) {
|
|
||||||
req := &fasthttp.RequestHeader{}
|
|
||||||
req.DisableNormalizing()
|
|
||||||
req.Add("X-Attribute-DupKey", "first-value")
|
|
||||||
req.Add("X-Attribute-DupKey", "second-value")
|
|
||||||
_, err := filterHeaders(log, req)
|
|
||||||
require.Error(t, err)
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("duplicate system keys error", func(t *testing.T) {
|
|
||||||
req := &fasthttp.RequestHeader{}
|
|
||||||
req.DisableNormalizing()
|
|
||||||
req.Add("X-Attribute-System-DupKey", "first-value")
|
|
||||||
req.Add("X-Attribute-System-DupKey", "second-value")
|
|
||||||
_, err := filterHeaders(log, req)
|
|
||||||
require.Error(t, err)
|
|
||||||
})
|
|
||||||
|
|
||||||
req := &fasthttp.RequestHeader{}
|
|
||||||
req.DisableNormalizing()
|
|
||||||
|
|
||||||
req.Set("X-Attribute-System-Expiration-Epoch1", "101")
|
|
||||||
req.Set("X-Attribute-SYSTEM-Expiration-Epoch2", "102")
|
|
||||||
req.Set("X-Attribute-system-Expiration-Epoch3", "103")
|
|
||||||
req.Set("X-Attribute-MyAttribute", "value")
|
|
||||||
|
|
||||||
expected := map[string]string{
|
|
||||||
"__SYSTEM__EXPIRATION_EPOCH1": "101",
|
|
||||||
"MyAttribute": "value",
|
|
||||||
"__SYSTEM__EXPIRATION_EPOCH3": "103",
|
|
||||||
"__SYSTEM__EXPIRATION_EPOCH2": "102",
|
|
||||||
}
|
|
||||||
|
|
||||||
result, err := filterHeaders(log, req)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
require.Equal(t, expected, result)
|
|
||||||
}
|
|
|
@ -1,275 +0,0 @@
|
||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"crypto/rand"
|
|
||||||
"crypto/sha256"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/utils"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/bearer"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/checksum"
|
|
||||||
apistatus "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/client/status"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/acl"
|
|
||||||
cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object"
|
|
||||||
oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/user"
|
|
||||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
|
||||||
)
|
|
||||||
|
|
||||||
type TestFrostFS struct {
|
|
||||||
objects map[string]*object.Object
|
|
||||||
containers map[string]*container.Container
|
|
||||||
accessList map[string]bool
|
|
||||||
key *keys.PrivateKey
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewTestFrostFS(key *keys.PrivateKey) *TestFrostFS {
|
|
||||||
return &TestFrostFS{
|
|
||||||
objects: make(map[string]*object.Object),
|
|
||||||
containers: make(map[string]*container.Container),
|
|
||||||
accessList: make(map[string]bool),
|
|
||||||
key: key,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TestFrostFS) ContainerID(name string) (*cid.ID, error) {
|
|
||||||
for id, cnr := range t.containers {
|
|
||||||
if container.Name(*cnr) == name {
|
|
||||||
var cnrID cid.ID
|
|
||||||
return &cnrID, cnrID.DecodeString(id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil, fmt.Errorf("not found")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TestFrostFS) SetContainer(cnrID cid.ID, cnr *container.Container) {
|
|
||||||
t.containers[cnrID.EncodeToString()] = cnr
|
|
||||||
}
|
|
||||||
|
|
||||||
// AllowUserOperation grants access to object operations.
|
|
||||||
// Empty userID and objID means any user and object respectively.
|
|
||||||
func (t *TestFrostFS) AllowUserOperation(cnrID cid.ID, userID user.ID, op acl.Op, objID oid.ID) {
|
|
||||||
t.accessList[fmt.Sprintf("%s/%s/%s/%s", cnrID, userID, op, objID)] = true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TestFrostFS) Container(_ context.Context, prm PrmContainer) (*container.Container, error) {
|
|
||||||
for k, v := range t.containers {
|
|
||||||
if k == prm.ContainerID.EncodeToString() {
|
|
||||||
return v, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, fmt.Errorf("container not found %s", prm.ContainerID)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TestFrostFS) requestOwner(btoken *bearer.Token) user.ID {
|
|
||||||
if btoken != nil {
|
|
||||||
return bearer.ResolveIssuer(*btoken)
|
|
||||||
}
|
|
||||||
|
|
||||||
var owner user.ID
|
|
||||||
user.IDFromKey(&owner, t.key.PrivateKey.PublicKey)
|
|
||||||
return owner
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TestFrostFS) retrieveObject(addr oid.Address, btoken *bearer.Token) (*object.Object, error) {
|
|
||||||
sAddr := addr.EncodeToString()
|
|
||||||
|
|
||||||
if obj, ok := t.objects[sAddr]; ok {
|
|
||||||
owner := t.requestOwner(btoken)
|
|
||||||
|
|
||||||
if !t.isAllowed(addr.Container(), owner, acl.OpObjectGet, addr.Object()) {
|
|
||||||
return nil, ErrAccessDenied
|
|
||||||
}
|
|
||||||
|
|
||||||
return obj, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, fmt.Errorf("%w: %s", &apistatus.ObjectNotFound{}, addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TestFrostFS) HeadObject(_ context.Context, prm PrmObjectHead) (*object.Object, error) {
|
|
||||||
return t.retrieveObject(prm.Address, prm.BearerToken)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TestFrostFS) GetObject(_ context.Context, prm PrmObjectGet) (*Object, error) {
|
|
||||||
obj, err := t.retrieveObject(prm.Address, prm.BearerToken)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return &Object{
|
|
||||||
Header: *obj,
|
|
||||||
Payload: io.NopCloser(bytes.NewReader(obj.Payload())),
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TestFrostFS) RangeObject(_ context.Context, prm PrmObjectRange) (io.ReadCloser, error) {
|
|
||||||
obj, err := t.retrieveObject(prm.Address, prm.BearerToken)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
off := prm.PayloadRange[0]
|
|
||||||
payload := obj.Payload()[off : off+prm.PayloadRange[1]]
|
|
||||||
return io.NopCloser(bytes.NewReader(payload)), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TestFrostFS) CreateObject(_ context.Context, prm PrmObjectCreate) (oid.ID, error) {
|
|
||||||
b := make([]byte, 32)
|
|
||||||
if _, err := io.ReadFull(rand.Reader, b); err != nil {
|
|
||||||
return oid.ID{}, err
|
|
||||||
}
|
|
||||||
var id oid.ID
|
|
||||||
id.SetSHA256(sha256.Sum256(b))
|
|
||||||
prm.Object.SetID(id)
|
|
||||||
|
|
||||||
attrs := prm.Object.Attributes()
|
|
||||||
if prm.ClientCut {
|
|
||||||
a := object.NewAttribute()
|
|
||||||
a.SetKey("s3-client-cut")
|
|
||||||
a.SetValue("true")
|
|
||||||
attrs = append(attrs, *a)
|
|
||||||
}
|
|
||||||
|
|
||||||
prm.Object.SetAttributes(attrs...)
|
|
||||||
|
|
||||||
if prm.Payload != nil {
|
|
||||||
all, err := io.ReadAll(prm.Payload)
|
|
||||||
if err != nil {
|
|
||||||
return oid.ID{}, err
|
|
||||||
}
|
|
||||||
prm.Object.SetPayload(all)
|
|
||||||
prm.Object.SetPayloadSize(uint64(len(all)))
|
|
||||||
var hash checksum.Checksum
|
|
||||||
checksum.Calculate(&hash, checksum.SHA256, all)
|
|
||||||
prm.Object.SetPayloadChecksum(hash)
|
|
||||||
}
|
|
||||||
|
|
||||||
cnrID, _ := prm.Object.ContainerID()
|
|
||||||
objID, _ := prm.Object.ID()
|
|
||||||
|
|
||||||
owner := t.requestOwner(prm.BearerToken)
|
|
||||||
|
|
||||||
if !t.isAllowed(cnrID, owner, acl.OpObjectPut, objID) {
|
|
||||||
return oid.ID{}, ErrAccessDenied
|
|
||||||
}
|
|
||||||
|
|
||||||
addr := newAddress(cnrID, objID)
|
|
||||||
t.objects[addr.EncodeToString()] = prm.Object
|
|
||||||
return objID, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type resObjectSearchMock struct {
|
|
||||||
res []oid.ID
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *resObjectSearchMock) Read(buf []oid.ID) (int, error) {
|
|
||||||
for i := range buf {
|
|
||||||
if i > len(r.res)-1 {
|
|
||||||
return len(r.res), io.EOF
|
|
||||||
}
|
|
||||||
buf[i] = r.res[i]
|
|
||||||
}
|
|
||||||
|
|
||||||
r.res = r.res[len(buf):]
|
|
||||||
|
|
||||||
return len(buf), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *resObjectSearchMock) Iterate(f func(oid.ID) bool) error {
|
|
||||||
for _, id := range r.res {
|
|
||||||
if f(id) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *resObjectSearchMock) Close() {}
|
|
||||||
|
|
||||||
func (t *TestFrostFS) SearchObjects(_ context.Context, prm PrmObjectSearch) (ResObjectSearch, error) {
|
|
||||||
if !t.isAllowed(prm.Container, t.requestOwner(prm.BearerToken), acl.OpObjectSearch, oid.ID{}) {
|
|
||||||
return nil, ErrAccessDenied
|
|
||||||
}
|
|
||||||
|
|
||||||
cidStr := prm.Container.EncodeToString()
|
|
||||||
var res []oid.ID
|
|
||||||
|
|
||||||
if len(prm.Filters) == 1 { // match root filter
|
|
||||||
for k, v := range t.objects {
|
|
||||||
if strings.Contains(k, cidStr) {
|
|
||||||
id, _ := v.ID()
|
|
||||||
res = append(res, id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return &resObjectSearchMock{res: res}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
filter := prm.Filters[1]
|
|
||||||
if len(prm.Filters) != 2 ||
|
|
||||||
filter.Operation() != object.MatchCommonPrefix && filter.Operation() != object.MatchStringEqual {
|
|
||||||
return nil, fmt.Errorf("usupported filters")
|
|
||||||
}
|
|
||||||
|
|
||||||
for k, v := range t.objects {
|
|
||||||
if strings.Contains(k, cidStr) && isMatched(v.Attributes(), filter) {
|
|
||||||
id, _ := v.ID()
|
|
||||||
res = append(res, id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &resObjectSearchMock{res: res}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TestFrostFS) InitMultiObjectReader(context.Context, PrmInitMultiObjectReader) (io.Reader, error) {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func isMatched(attributes []object.Attribute, filter object.SearchFilter) bool {
|
|
||||||
for _, attr := range attributes {
|
|
||||||
if attr.Key() == filter.Header() {
|
|
||||||
switch filter.Operation() {
|
|
||||||
case object.MatchStringEqual:
|
|
||||||
return attr.Value() == filter.Value()
|
|
||||||
case object.MatchCommonPrefix:
|
|
||||||
return strings.HasPrefix(attr.Value(), filter.Value())
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TestFrostFS) GetEpochDurations(context.Context) (*utils.EpochDurations, error) {
|
|
||||||
return &utils.EpochDurations{
|
|
||||||
CurrentEpoch: 10,
|
|
||||||
MsPerBlock: 1000,
|
|
||||||
BlockPerEpoch: 100,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TestFrostFS) isAllowed(cnrID cid.ID, userID user.ID, op acl.Op, objID oid.ID) bool {
|
|
||||||
keysToCheck := []string{
|
|
||||||
fmt.Sprintf("%s/%s/%s/%s", cnrID, userID, op, objID),
|
|
||||||
fmt.Sprintf("%s/%s/%s/%s", cnrID, userID, op, oid.ID{}),
|
|
||||||
fmt.Sprintf("%s/%s/%s/%s", cnrID, user.ID{}, op, objID),
|
|
||||||
fmt.Sprintf("%s/%s/%s/%s", cnrID, user.ID{}, op, oid.ID{}),
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, key := range keysToCheck {
|
|
||||||
if t.accessList[key] {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
|
@ -1,443 +0,0 @@
|
||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net/url"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/cache"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/data"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/handler/middleware"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/layer"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/logs"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/utils"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-observability/tracing"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/bearer"
|
|
||||||
apistatus "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/client/status"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container"
|
|
||||||
cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object"
|
|
||||||
oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/user"
|
|
||||||
"github.com/panjf2000/ants/v2"
|
|
||||||
"github.com/valyala/fasthttp"
|
|
||||||
"go.uber.org/zap"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Config interface {
|
|
||||||
DefaultTimestamp() bool
|
|
||||||
ArchiveCompression() bool
|
|
||||||
ClientCut() bool
|
|
||||||
IndexPageEnabled() bool
|
|
||||||
IndexPageTemplate() string
|
|
||||||
BufferMaxSizeForPut() uint64
|
|
||||||
NamespaceHeader() string
|
|
||||||
EnableFilepathFallback() bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// PrmContainer groups parameters of FrostFS.Container operation.
|
|
||||||
type PrmContainer struct {
|
|
||||||
// Container identifier.
|
|
||||||
ContainerID cid.ID
|
|
||||||
}
|
|
||||||
|
|
||||||
// PrmAuth groups authentication parameters for the FrostFS operation.
|
|
||||||
type PrmAuth struct {
|
|
||||||
// Bearer token to be used for the operation. Overlaps PrivateKey. Optional.
|
|
||||||
BearerToken *bearer.Token
|
|
||||||
}
|
|
||||||
|
|
||||||
// PrmObjectHead groups parameters of FrostFS.HeadObject operation.
|
|
||||||
type PrmObjectHead struct {
|
|
||||||
// Authentication parameters.
|
|
||||||
PrmAuth
|
|
||||||
|
|
||||||
// Address to read the object header from.
|
|
||||||
Address oid.Address
|
|
||||||
}
|
|
||||||
|
|
||||||
// PrmObjectGet groups parameters of FrostFS.GetObject operation.
|
|
||||||
type PrmObjectGet struct {
|
|
||||||
// Authentication parameters.
|
|
||||||
PrmAuth
|
|
||||||
|
|
||||||
// Address to read the object header from.
|
|
||||||
Address oid.Address
|
|
||||||
}
|
|
||||||
|
|
||||||
// PrmObjectRange groups parameters of FrostFS.RangeObject operation.
|
|
||||||
type PrmObjectRange struct {
|
|
||||||
// Authentication parameters.
|
|
||||||
PrmAuth
|
|
||||||
|
|
||||||
// Address to read the object header from.
|
|
||||||
Address oid.Address
|
|
||||||
|
|
||||||
// Offset-length range of the object payload to be read.
|
|
||||||
PayloadRange [2]uint64
|
|
||||||
}
|
|
||||||
|
|
||||||
// Object represents FrostFS object.
|
|
||||||
type Object struct {
|
|
||||||
// Object header (doesn't contain payload).
|
|
||||||
Header object.Object
|
|
||||||
|
|
||||||
// Object payload part encapsulated in io.Reader primitive.
|
|
||||||
// Returns ErrAccessDenied on read access violation.
|
|
||||||
Payload io.ReadCloser
|
|
||||||
}
|
|
||||||
|
|
||||||
// PrmObjectCreate groups parameters of FrostFS.CreateObject operation.
|
|
||||||
type PrmObjectCreate struct {
|
|
||||||
// Authentication parameters.
|
|
||||||
PrmAuth
|
|
||||||
|
|
||||||
Object *object.Object
|
|
||||||
|
|
||||||
// Object payload encapsulated in io.Reader primitive.
|
|
||||||
Payload io.Reader
|
|
||||||
|
|
||||||
// Enables client side object preparing.
|
|
||||||
ClientCut bool
|
|
||||||
|
|
||||||
// Disables using Tillich-Zémor hash for payload.
|
|
||||||
WithoutHomomorphicHash bool
|
|
||||||
|
|
||||||
// Sets max buffer size to read payload.
|
|
||||||
BufferMaxSize uint64
|
|
||||||
}
|
|
||||||
|
|
||||||
// PrmObjectSearch groups parameters of FrostFS.sear SearchObjects operation.
|
|
||||||
type PrmObjectSearch struct {
|
|
||||||
// Authentication parameters.
|
|
||||||
PrmAuth
|
|
||||||
|
|
||||||
// Container to select the objects from.
|
|
||||||
Container cid.ID
|
|
||||||
|
|
||||||
Filters object.SearchFilters
|
|
||||||
}
|
|
||||||
|
|
||||||
type PrmInitMultiObjectReader struct {
|
|
||||||
// payload range
|
|
||||||
Off, Ln uint64
|
|
||||||
|
|
||||||
Addr oid.Address
|
|
||||||
Bearer *bearer.Token
|
|
||||||
}
|
|
||||||
|
|
||||||
type ResObjectSearch interface {
|
|
||||||
Read(buf []oid.ID) (int, error)
|
|
||||||
Iterate(f func(oid.ID) bool) error
|
|
||||||
Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
// ErrAccessDenied is returned from FrostFS in case of access violation.
|
|
||||||
ErrAccessDenied = errors.New("access denied")
|
|
||||||
// ErrGatewayTimeout is returned from FrostFS in case of timeout, deadline exceeded etc.
|
|
||||||
ErrGatewayTimeout = errors.New("gateway timeout")
|
|
||||||
// ErrQuotaLimitReached is returned from FrostFS in case of quota exceeded.
|
|
||||||
ErrQuotaLimitReached = errors.New("quota limit reached")
|
|
||||||
)
|
|
||||||
|
|
||||||
// FrostFS represents virtual connection to FrostFS network.
|
|
||||||
type FrostFS interface {
|
|
||||||
Container(context.Context, PrmContainer) (*container.Container, error)
|
|
||||||
HeadObject(context.Context, PrmObjectHead) (*object.Object, error)
|
|
||||||
GetObject(context.Context, PrmObjectGet) (*Object, error)
|
|
||||||
RangeObject(context.Context, PrmObjectRange) (io.ReadCloser, error)
|
|
||||||
CreateObject(context.Context, PrmObjectCreate) (oid.ID, error)
|
|
||||||
SearchObjects(context.Context, PrmObjectSearch) (ResObjectSearch, error)
|
|
||||||
InitMultiObjectReader(ctx context.Context, p PrmInitMultiObjectReader) (io.Reader, error)
|
|
||||||
|
|
||||||
utils.EpochInfoFetcher
|
|
||||||
}
|
|
||||||
|
|
||||||
type ContainerResolver interface {
|
|
||||||
Resolve(ctx context.Context, name string) (*cid.ID, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type Handler struct {
|
|
||||||
log *zap.Logger
|
|
||||||
frostfs FrostFS
|
|
||||||
ownerID *user.ID
|
|
||||||
config Config
|
|
||||||
containerResolver ContainerResolver
|
|
||||||
tree layer.TreeService
|
|
||||||
cache *cache.BucketCache
|
|
||||||
workerPool *ants.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
type AppParams struct {
|
|
||||||
Logger *zap.Logger
|
|
||||||
FrostFS FrostFS
|
|
||||||
Owner *user.ID
|
|
||||||
Resolver ContainerResolver
|
|
||||||
Cache *cache.BucketCache
|
|
||||||
}
|
|
||||||
|
|
||||||
func New(params *AppParams, config Config, tree layer.TreeService, workerPool *ants.Pool) *Handler {
|
|
||||||
return &Handler{
|
|
||||||
log: params.Logger,
|
|
||||||
frostfs: params.FrostFS,
|
|
||||||
ownerID: params.Owner,
|
|
||||||
config: config,
|
|
||||||
containerResolver: params.Resolver,
|
|
||||||
tree: tree,
|
|
||||||
cache: params.Cache,
|
|
||||||
workerPool: workerPool,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// byNativeAddress is a wrapper for function (e.g. request.headObject, request.receiveFile) that
|
|
||||||
// prepares request and object address to it.
|
|
||||||
func (h *Handler) byNativeAddress(ctx context.Context, req request, cnrID cid.ID, objID oid.ID, handler func(context.Context, request, oid.Address)) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(ctx, "handler.byNativeAddress")
|
|
||||||
defer span.End()
|
|
||||||
|
|
||||||
addr := newAddress(cnrID, objID)
|
|
||||||
handler(ctx, req, addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
// byS3Path is a wrapper for function (e.g. request.headObject, request.receiveFile) that
|
|
||||||
// resolves object address from S3-like path <bucket name>/<object key>.
|
|
||||||
func (h *Handler) byS3Path(ctx context.Context, req request, cnrID cid.ID, path string, handler func(context.Context, request, oid.Address)) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(ctx, "handler.byS3Path")
|
|
||||||
defer span.End()
|
|
||||||
|
|
||||||
c, log := req.RequestCtx, req.log
|
|
||||||
|
|
||||||
foundOID, err := h.tree.GetLatestVersion(ctx, &cnrID, path)
|
|
||||||
if err != nil {
|
|
||||||
log.Error(logs.FailedToGetLatestVersionOfObject, zap.Error(err), zap.String("cid", cnrID.String()),
|
|
||||||
zap.String("path", path), logs.TagField(logs.TagExternalStorageTree))
|
|
||||||
logAndSendBucketError(c, log, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if foundOID.IsDeleteMarker {
|
|
||||||
log.Error(logs.ObjectWasDeleted, logs.TagField(logs.TagExternalStorageTree))
|
|
||||||
ResponseError(c, "object deleted", fasthttp.StatusNotFound)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
addr := newAddress(cnrID, foundOID.OID)
|
|
||||||
handler(ctx, newRequest(c, log), addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
// byAttribute is a wrapper similar to byNativeAddress.
|
|
||||||
func (h *Handler) byAttribute(c *fasthttp.RequestCtx, handler func(context.Context, request, oid.Address)) {
|
|
||||||
cidParam, _ := c.UserValue("cid").(string)
|
|
||||||
key, _ := c.UserValue("attr_key").(string)
|
|
||||||
val, _ := c.UserValue("attr_val").(string)
|
|
||||||
|
|
||||||
ctx := utils.GetContextFromRequest(c)
|
|
||||||
log := utils.GetReqLogOrDefault(ctx, h.log)
|
|
||||||
|
|
||||||
key, err := url.QueryUnescape(key)
|
|
||||||
if err != nil {
|
|
||||||
log.Error(logs.FailedToUnescapeQuery, zap.String("cid", cidParam), zap.String("attr_key", key),
|
|
||||||
zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
ResponseError(c, "could not unescape attr_key: "+err.Error(), fasthttp.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
val, err = url.QueryUnescape(val)
|
|
||||||
if err != nil {
|
|
||||||
log.Error(logs.FailedToUnescapeQuery, zap.String("cid", cidParam), zap.String("attr_val", val),
|
|
||||||
zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
ResponseError(c, "could not unescape attr_val: "+err.Error(), fasthttp.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if key == attrFileName {
|
|
||||||
val = prepareFileName(val)
|
|
||||||
}
|
|
||||||
|
|
||||||
log = log.With(zap.String("cid", cidParam), zap.String("attr_key", key), zap.String("attr_val", val))
|
|
||||||
|
|
||||||
bktInfo, err := h.getBucketInfo(ctx, cidParam, log)
|
|
||||||
if err != nil {
|
|
||||||
logAndSendBucketError(c, log, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
objID, err := h.findObjectByAttribute(ctx, log, bktInfo.CID, key, val)
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, io.EOF) {
|
|
||||||
ResponseError(c, err.Error(), fasthttp.StatusNotFound)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
ResponseError(c, err.Error(), fasthttp.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var addr oid.Address
|
|
||||||
addr.SetContainer(bktInfo.CID)
|
|
||||||
addr.SetObject(objID)
|
|
||||||
|
|
||||||
handler(ctx, newRequest(c, log), addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) findObjectByAttribute(ctx context.Context, log *zap.Logger, cnrID cid.ID, attrKey, attrVal string) (oid.ID, error) {
|
|
||||||
res, err := h.search(ctx, cnrID, attrKey, attrVal, object.MatchStringEqual)
|
|
||||||
if err != nil {
|
|
||||||
log.Error(logs.CouldNotSearchForObjects, zap.Error(err), logs.TagField(logs.TagExternalStorage))
|
|
||||||
return oid.ID{}, fmt.Errorf("could not search for objects: %w", err)
|
|
||||||
}
|
|
||||||
defer res.Close()
|
|
||||||
|
|
||||||
buf := make([]oid.ID, 1)
|
|
||||||
|
|
||||||
n, err := res.Read(buf)
|
|
||||||
if n == 0 {
|
|
||||||
switch {
|
|
||||||
case errors.Is(err, io.EOF) && h.needSearchByFileName(attrKey, attrVal):
|
|
||||||
log.Debug(logs.ObjectNotFoundByFilePathTrySearchByFileName, logs.TagField(logs.TagExternalStorage))
|
|
||||||
return h.findObjectByAttribute(ctx, log, cnrID, attrFileName, prepareFileName(attrVal))
|
|
||||||
case errors.Is(err, io.EOF):
|
|
||||||
log.Error(logs.ObjectNotFound, zap.Error(err), logs.TagField(logs.TagExternalStorage))
|
|
||||||
return oid.ID{}, fmt.Errorf("object not found: %w", err)
|
|
||||||
default:
|
|
||||||
log.Error(logs.ReadObjectListFailed, zap.Error(err), logs.TagField(logs.TagExternalStorage))
|
|
||||||
return oid.ID{}, fmt.Errorf("read object list failed: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return buf[0], nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) needSearchByFileName(key, val string) bool {
|
|
||||||
if key != attrFilePath || !h.config.EnableFilepathFallback() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
return strings.HasPrefix(val, "/") && strings.Count(val, "/") == 1 || !strings.Contains(val, "/")
|
|
||||||
}
|
|
||||||
|
|
||||||
func prepareFileName(fileName string) string {
|
|
||||||
if strings.HasPrefix(fileName, "/") {
|
|
||||||
return fileName[1:]
|
|
||||||
}
|
|
||||||
|
|
||||||
return fileName
|
|
||||||
}
|
|
||||||
|
|
||||||
// resolveContainer decode container id, if it's not a valid container id
|
|
||||||
// then trey to resolve name using provided resolver.
|
|
||||||
func (h *Handler) resolveContainer(ctx context.Context, containerID string) (*cid.ID, error) {
|
|
||||||
cnrID := new(cid.ID)
|
|
||||||
err := cnrID.DecodeString(containerID)
|
|
||||||
if err != nil {
|
|
||||||
cnrID, err = h.containerResolver.Resolve(ctx, containerID)
|
|
||||||
if err != nil && strings.Contains(err.Error(), "not found") {
|
|
||||||
err = fmt.Errorf("%w: %s", new(apistatus.ContainerNotFound), err.Error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return cnrID, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) getBucketInfo(ctx context.Context, containerName string, log *zap.Logger) (*data.BucketInfo, error) {
|
|
||||||
ns, err := middleware.GetNamespace(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if bktInfo := h.cache.Get(ns, containerName); bktInfo != nil {
|
|
||||||
return bktInfo, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
cnrID, err := h.resolveContainer(ctx, containerName)
|
|
||||||
if err != nil {
|
|
||||||
log.Error(logs.CouldNotResolveContainerID, zap.Error(err), zap.String("cnrName", containerName),
|
|
||||||
logs.TagField(logs.TagDatapath))
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
bktInfo, err := h.readContainer(ctx, *cnrID)
|
|
||||||
if err != nil {
|
|
||||||
log.Error(logs.CouldNotGetContainerInfo, zap.Error(err), zap.String("cnrName", containerName),
|
|
||||||
zap.String("cnrName", cnrID.String()),
|
|
||||||
logs.TagField(logs.TagExternalStorage))
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err = h.cache.Put(bktInfo); err != nil {
|
|
||||||
log.Warn(logs.CouldntPutBucketIntoCache,
|
|
||||||
zap.String("bucket name", bktInfo.Name),
|
|
||||||
zap.Stringer("bucket cid", bktInfo.CID),
|
|
||||||
zap.Error(err),
|
|
||||||
logs.TagField(logs.TagDatapath))
|
|
||||||
}
|
|
||||||
|
|
||||||
return bktInfo, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) readContainer(ctx context.Context, cnrID cid.ID) (*data.BucketInfo, error) {
|
|
||||||
prm := PrmContainer{ContainerID: cnrID}
|
|
||||||
res, err := h.frostfs.Container(ctx, prm)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("get frostfs container '%s': %w", cnrID.String(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
bktInfo := &data.BucketInfo{
|
|
||||||
CID: cnrID,
|
|
||||||
Name: cnrID.EncodeToString(),
|
|
||||||
}
|
|
||||||
|
|
||||||
if domain := container.ReadDomain(*res); domain.Name() != "" {
|
|
||||||
bktInfo.Name = domain.Name()
|
|
||||||
bktInfo.Zone = domain.Zone()
|
|
||||||
}
|
|
||||||
|
|
||||||
bktInfo.HomomorphicHashDisabled = container.IsHomomorphicHashingDisabled(*res)
|
|
||||||
bktInfo.PlacementPolicy = res.PlacementPolicy()
|
|
||||||
|
|
||||||
return bktInfo, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) browseIndex(c *fasthttp.RequestCtx, isNativeList bool) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(utils.GetContextFromRequest(c), "handler.browseIndex")
|
|
||||||
defer span.End()
|
|
||||||
utils.SetContextToRequest(ctx, c)
|
|
||||||
|
|
||||||
if !h.config.IndexPageEnabled() {
|
|
||||||
c.SetStatusCode(fasthttp.StatusNotFound)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
cidURLParam := c.UserValue("cid").(string)
|
|
||||||
oidURLParam := c.UserValue("oid").(string)
|
|
||||||
|
|
||||||
reqLog := utils.GetReqLogOrDefault(ctx, h.log)
|
|
||||||
log := reqLog.With(zap.String("cid", cidURLParam), zap.String("oid", oidURLParam))
|
|
||||||
|
|
||||||
unescapedKey, err := url.QueryUnescape(oidURLParam)
|
|
||||||
if err != nil {
|
|
||||||
logAndSendBucketError(c, log, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
bktInfo, err := h.getBucketInfo(ctx, cidURLParam, log)
|
|
||||||
if err != nil {
|
|
||||||
logAndSendBucketError(c, log, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
listFunc := h.getDirObjectsS3
|
|
||||||
if isNativeList {
|
|
||||||
// tree probe failed, trying to use native
|
|
||||||
listFunc = h.getDirObjectsNative
|
|
||||||
}
|
|
||||||
|
|
||||||
h.browseObjects(c, browseParams{
|
|
||||||
bucketInfo: bktInfo,
|
|
||||||
prefix: unescapedKey,
|
|
||||||
listObjects: listFunc,
|
|
||||||
isNative: isNativeList,
|
|
||||||
})
|
|
||||||
}
|
|
|
@ -1,580 +0,0 @@
|
||||||
//go:build gofuzz
|
|
||||||
// +build gofuzz
|
|
||||||
|
|
||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"io"
|
|
||||||
"mime/multipart"
|
|
||||||
"net/http"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/handler/middleware"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/tokens"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/utils"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/acl"
|
|
||||||
cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object"
|
|
||||||
go_fuzz_utils "github.com/trailofbits/go-fuzz-utils"
|
|
||||||
"github.com/valyala/fasthttp"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
fuzzSuccessExitCode = 0
|
|
||||||
fuzzFailExitCode = -1
|
|
||||||
)
|
|
||||||
|
|
||||||
func prepareStrings(tp *go_fuzz_utils.TypeProvider, count int) ([]string, error) {
|
|
||||||
array := make([]string, count)
|
|
||||||
var err error
|
|
||||||
|
|
||||||
for i := 0; i < count; i++ {
|
|
||||||
err = tp.Reset()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
array[i], err = tp.GetString()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return array, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func prepareBools(tp *go_fuzz_utils.TypeProvider, count int) ([]bool, error) {
|
|
||||||
array := make([]bool, count)
|
|
||||||
var err error
|
|
||||||
|
|
||||||
for i := 0; i < count; i++ {
|
|
||||||
err = tp.Reset()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
array[i], err = tp.GetBool()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return array, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func getRandomDeterministicPositiveIntInRange(tp *go_fuzz_utils.TypeProvider, max int) (int, error) {
|
|
||||||
count, err := tp.GetInt()
|
|
||||||
if err != nil {
|
|
||||||
return -1, err
|
|
||||||
}
|
|
||||||
count = count % max
|
|
||||||
if count < 0 {
|
|
||||||
count += max
|
|
||||||
}
|
|
||||||
return count, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func generateHeaders(tp *go_fuzz_utils.TypeProvider, r *fasthttp.Request, params []string) error {
|
|
||||||
count, err := tp.GetInt()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
count = count % len(params)
|
|
||||||
if count < 0 {
|
|
||||||
count += len(params)
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < count; i++ {
|
|
||||||
position, err := tp.GetInt()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
position = position % len(params)
|
|
||||||
if position < 0 {
|
|
||||||
position += len(params)
|
|
||||||
}
|
|
||||||
|
|
||||||
v, err := tp.GetString()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
r.Header.Set(params[position], v)
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func maybeFillRandom(tp *go_fuzz_utils.TypeProvider, initValue string) (string, error) {
|
|
||||||
rnd, err := tp.GetBool()
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
if rnd == true {
|
|
||||||
initValue, err = tp.GetString()
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return initValue, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func upload(tp *go_fuzz_utils.TypeProvider) (context.Context, *handlerContext, cid.ID, *fasthttp.RequestCtx, string, string, string, error) {
|
|
||||||
hc, err := prepareHandlerContext()
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, cid.ID{}, nil, "", "", "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
aclList := []acl.Basic{
|
|
||||||
acl.Private,
|
|
||||||
acl.PrivateExtended,
|
|
||||||
acl.PublicRO,
|
|
||||||
acl.PublicROExtended,
|
|
||||||
acl.PublicRW,
|
|
||||||
acl.PublicRWExtended,
|
|
||||||
acl.PublicAppend,
|
|
||||||
acl.PublicAppendExtended,
|
|
||||||
}
|
|
||||||
|
|
||||||
pos, err := getRandomDeterministicPositiveIntInRange(tp, len(aclList))
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, cid.ID{}, nil, "", "", "", err
|
|
||||||
}
|
|
||||||
acl := aclList[pos]
|
|
||||||
|
|
||||||
strings, err := prepareStrings(tp, 6)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, cid.ID{}, nil, "", "", "", err
|
|
||||||
}
|
|
||||||
bktName := strings[0]
|
|
||||||
objFileName := strings[1]
|
|
||||||
valAttr := strings[2]
|
|
||||||
keyAttr := strings[3]
|
|
||||||
|
|
||||||
if len(bktName) == 0 {
|
|
||||||
return nil, nil, cid.ID{}, nil, "", "", "", errors.New("not enought buckets")
|
|
||||||
}
|
|
||||||
|
|
||||||
cnrID, cnr, err := hc.prepareContainer(bktName, acl)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, cid.ID{}, nil, "", "", "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
hc.frostfs.SetContainer(cnrID, cnr)
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
ctx = middleware.SetNamespace(ctx, "")
|
|
||||||
|
|
||||||
r := new(fasthttp.RequestCtx)
|
|
||||||
utils.SetContextToRequest(ctx, r)
|
|
||||||
r.SetUserValue("cid", cnrID.EncodeToString())
|
|
||||||
|
|
||||||
attributes := map[string]string{
|
|
||||||
object.AttributeFileName: objFileName,
|
|
||||||
keyAttr: valAttr,
|
|
||||||
}
|
|
||||||
|
|
||||||
var buff bytes.Buffer
|
|
||||||
w := multipart.NewWriter(&buff)
|
|
||||||
fw, err := w.CreateFormFile("file", attributes[object.AttributeFileName])
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, cid.ID{}, nil, "", "", "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
content, err := tp.GetBytes()
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, cid.ID{}, nil, "", "", "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err = io.Copy(fw, bytes.NewReader(content)); err != nil {
|
|
||||||
return nil, nil, cid.ID{}, nil, "", "", "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err = w.Close(); err != nil {
|
|
||||||
return nil, nil, cid.ID{}, nil, "", "", "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
r.Request.SetBodyStream(&buff, buff.Len())
|
|
||||||
r.Request.Header.Set("Content-Type", w.FormDataContentType())
|
|
||||||
r.Request.Header.Set("X-Attribute-"+keyAttr, valAttr)
|
|
||||||
|
|
||||||
err = generateHeaders(tp, &r.Request, []string{"X-Attribute-", "X-Attribute-DupKey", "X-Attribute-MyAttribute", "X-Attribute-System-DupKey", "X-Attribute-System-Expiration-Epoch1", "X-Attribute-SYSTEM-Expiration-Epoch2", "X-Attribute-system-Expiration-Epoch3", "X-Attribute-User-Attribute", "X-Attribute-", "X-Attribute-FileName", "X-Attribute-FROSTFS", "X-Attribute-neofs", "X-Attribute-SYSTEM", "X-Attribute-System-Expiration-Duration", "X-Attribute-System-Expiration-Epoch", "X-Attribute-System-Expiration-RFC3339", "X-Attribute-System-Expiration-Timestamp", "X-Attribute-Timestamp", "X-Attribute-" + strings[4], "X-Attribute-System-" + strings[5]})
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, cid.ID{}, nil, "", "", "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
hc.Handler().Upload(r)
|
|
||||||
|
|
||||||
if r.Response.StatusCode() != http.StatusOK {
|
|
||||||
return nil, nil, cid.ID{}, nil, "", "", "", errors.New("error on upload")
|
|
||||||
}
|
|
||||||
|
|
||||||
return ctx, hc, cnrID, r, objFileName, keyAttr, valAttr, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func InitFuzzUpload() {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func DoFuzzUpload(input []byte) int {
|
|
||||||
// FUZZER INIT
|
|
||||||
if len(input) < 100 {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
tp, err := go_fuzz_utils.NewTypeProvider(input)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
_, _, _, _, _, _, _, err = upload(tp)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
return fuzzSuccessExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
func FuzzUpload(f *testing.F) {
|
|
||||||
f.Fuzz(func(t *testing.T, data []byte) {
|
|
||||||
DoFuzzUpload(data)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func downloadOrHead(tp *go_fuzz_utils.TypeProvider, ctx context.Context, hc *handlerContext, cnrID cid.ID, resp *fasthttp.RequestCtx, filename string) (*fasthttp.RequestCtx, error) {
|
|
||||||
|
|
||||||
var putRes putResponse
|
|
||||||
|
|
||||||
defer func() {
|
|
||||||
if r := recover(); r != nil {
|
|
||||||
panic(resp)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
data := resp.Response.Body()
|
|
||||||
err := json.Unmarshal(data, &putRes)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
obj := hc.frostfs.objects[putRes.ContainerID+"/"+putRes.ObjectID]
|
|
||||||
attr := object.NewAttribute()
|
|
||||||
attr.SetKey(object.AttributeFilePath)
|
|
||||||
|
|
||||||
filename, err = maybeFillRandom(tp, filename)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
attr.SetValue(filename)
|
|
||||||
obj.SetAttributes(append(obj.Attributes(), *attr)...)
|
|
||||||
|
|
||||||
r := new(fasthttp.RequestCtx)
|
|
||||||
utils.SetContextToRequest(ctx, r)
|
|
||||||
|
|
||||||
cid := cnrID.EncodeToString()
|
|
||||||
cid, err = maybeFillRandom(tp, cid)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
oid := putRes.ObjectID
|
|
||||||
oid, err = maybeFillRandom(tp, oid)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
r.SetUserValue("cid", cid)
|
|
||||||
r.SetUserValue("oid", oid)
|
|
||||||
|
|
||||||
rnd, err := tp.GetBool()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if rnd == true {
|
|
||||||
r.SetUserValue("download", "true")
|
|
||||||
}
|
|
||||||
|
|
||||||
return r, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func InitFuzzGet() {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func DoFuzzGet(input []byte) int {
|
|
||||||
// FUZZER INIT
|
|
||||||
if len(input) < 100 {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
tp, err := go_fuzz_utils.NewTypeProvider(input)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, hc, cnrID, resp, filename, _, _, err := upload(tp)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
r, err := downloadOrHead(tp, ctx, hc, cnrID, resp, filename)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
hc.Handler().DownloadByAddressOrBucketName(r)
|
|
||||||
|
|
||||||
return fuzzSuccessExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
func FuzzGet(f *testing.F) {
|
|
||||||
f.Fuzz(func(t *testing.T, data []byte) {
|
|
||||||
DoFuzzUpload(data)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func InitFuzzHead() {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func DoFuzzHead(input []byte) int {
|
|
||||||
// FUZZER INIT
|
|
||||||
if len(input) < 100 {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
tp, err := go_fuzz_utils.NewTypeProvider(input)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, hc, cnrID, resp, filename, _, _, err := upload(tp)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
r, err := downloadOrHead(tp, ctx, hc, cnrID, resp, filename)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
hc.Handler().HeadByAddressOrBucketName(r)
|
|
||||||
|
|
||||||
return fuzzSuccessExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
func FuzzHead(f *testing.F) {
|
|
||||||
f.Fuzz(func(t *testing.T, data []byte) {
|
|
||||||
DoFuzzHead(data)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func InitFuzzDownloadByAttribute() {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func DoFuzzDownloadByAttribute(input []byte) int {
|
|
||||||
// FUZZER INIT
|
|
||||||
if len(input) < 100 {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
tp, err := go_fuzz_utils.NewTypeProvider(input)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, hc, cnrID, _, _, attrKey, attrVal, err := upload(tp)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
cid := cnrID.EncodeToString()
|
|
||||||
cid, err = maybeFillRandom(tp, cid)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
attrKey, err = maybeFillRandom(tp, attrKey)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
attrVal, err = maybeFillRandom(tp, attrVal)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
r := new(fasthttp.RequestCtx)
|
|
||||||
utils.SetContextToRequest(ctx, r)
|
|
||||||
r.SetUserValue("cid", cid)
|
|
||||||
r.SetUserValue("attr_key", attrKey)
|
|
||||||
r.SetUserValue("attr_val", attrVal)
|
|
||||||
|
|
||||||
hc.Handler().DownloadByAttribute(r)
|
|
||||||
|
|
||||||
return fuzzSuccessExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
func FuzzDownloadByAttribute(f *testing.F) {
|
|
||||||
f.Fuzz(func(t *testing.T, data []byte) {
|
|
||||||
DoFuzzDownloadByAttribute(data)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func InitFuzzHeadByAttribute() {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func DoFuzzHeadByAttribute(input []byte) int {
|
|
||||||
// FUZZER INIT
|
|
||||||
if len(input) < 100 {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
tp, err := go_fuzz_utils.NewTypeProvider(input)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, hc, cnrID, _, _, attrKey, attrVal, err := upload(tp)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
cid := cnrID.EncodeToString()
|
|
||||||
cid, err = maybeFillRandom(tp, cid)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
attrKey, err = maybeFillRandom(tp, attrKey)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
attrVal, err = maybeFillRandom(tp, attrVal)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
r := new(fasthttp.RequestCtx)
|
|
||||||
utils.SetContextToRequest(ctx, r)
|
|
||||||
r.SetUserValue("cid", cid)
|
|
||||||
r.SetUserValue("attr_key", attrKey)
|
|
||||||
r.SetUserValue("attr_val", attrVal)
|
|
||||||
|
|
||||||
hc.Handler().HeadByAttribute(r)
|
|
||||||
|
|
||||||
return fuzzSuccessExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
func FuzzHeadByAttribute(f *testing.F) {
|
|
||||||
f.Fuzz(func(t *testing.T, data []byte) {
|
|
||||||
DoFuzzHeadByAttribute(data)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func InitFuzzDownloadZipped() {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func DoFuzzDownloadZipped(input []byte) int {
|
|
||||||
// FUZZER INIT
|
|
||||||
if len(input) < 100 {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
tp, err := go_fuzz_utils.NewTypeProvider(input)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, hc, cnrID, _, _, _, _, err := upload(tp)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
cid := cnrID.EncodeToString()
|
|
||||||
cid, err = maybeFillRandom(tp, cid)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
prefix := ""
|
|
||||||
prefix, err = maybeFillRandom(tp, prefix)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
r := new(fasthttp.RequestCtx)
|
|
||||||
utils.SetContextToRequest(ctx, r)
|
|
||||||
r.SetUserValue("cid", cid)
|
|
||||||
r.SetUserValue("prefix", prefix)
|
|
||||||
|
|
||||||
hc.Handler().DownloadZip(r)
|
|
||||||
|
|
||||||
return fuzzSuccessExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
func FuzzDownloadZipped(f *testing.F) {
|
|
||||||
f.Fuzz(func(t *testing.T, data []byte) {
|
|
||||||
DoFuzzDownloadZipped(data)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func InitFuzzStoreBearerTokenAppCtx() {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func DoFuzzStoreBearerTokenAppCtx(input []byte) int {
|
|
||||||
// FUZZER INIT
|
|
||||||
if len(input) < 100 {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
tp, err := go_fuzz_utils.NewTypeProvider(input)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
prefix := ""
|
|
||||||
prefix, err = maybeFillRandom(tp, prefix)
|
|
||||||
if err != nil {
|
|
||||||
return fuzzFailExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
ctx = middleware.SetNamespace(ctx, "")
|
|
||||||
|
|
||||||
r := new(fasthttp.RequestCtx)
|
|
||||||
utils.SetContextToRequest(ctx, r)
|
|
||||||
|
|
||||||
strings, err := prepareStrings(tp, 3)
|
|
||||||
|
|
||||||
rand, err := prepareBools(tp, 2)
|
|
||||||
|
|
||||||
if rand[0] == true {
|
|
||||||
r.Request.Header.Set(fasthttp.HeaderAuthorization, "Bearer"+strings[0])
|
|
||||||
} else if rand[1] == true {
|
|
||||||
r.Request.Header.SetCookie(fasthttp.HeaderAuthorization, "Bearer"+strings[1])
|
|
||||||
} else {
|
|
||||||
r.Request.Header.Set(fasthttp.HeaderAuthorization, "Bearer"+strings[0])
|
|
||||||
r.Request.Header.SetCookie(fasthttp.HeaderAuthorization, "Bearer"+strings[1])
|
|
||||||
}
|
|
||||||
|
|
||||||
tokens.StoreBearerTokenAppCtx(ctx, r)
|
|
||||||
|
|
||||||
return fuzzSuccessExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
func FuzzStoreBearerTokenAppCtx(f *testing.F) {
|
|
||||||
f.Fuzz(func(t *testing.T, data []byte) {
|
|
||||||
DoFuzzStoreBearerTokenAppCtx(data)
|
|
||||||
})
|
|
||||||
}
|
|
|
@ -1,524 +0,0 @@
|
||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"archive/zip"
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"io"
|
|
||||||
"mime/multipart"
|
|
||||||
"net/http"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/cache"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/data"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/handler/middleware"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/layer"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/resolver"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/utils"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/acl"
|
|
||||||
cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id"
|
|
||||||
cidtest "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id/test"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/netmap"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object"
|
|
||||||
oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/user"
|
|
||||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
|
||||||
"github.com/panjf2000/ants/v2"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
"github.com/valyala/fasthttp"
|
|
||||||
"go.uber.org/zap"
|
|
||||||
)
|
|
||||||
|
|
||||||
type treeServiceMock struct {
|
|
||||||
system map[string]map[string]*data.BaseNodeVersion
|
|
||||||
}
|
|
||||||
|
|
||||||
func newTreeService() *treeServiceMock {
|
|
||||||
return &treeServiceMock{
|
|
||||||
system: make(map[string]map[string]*data.BaseNodeVersion),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *treeServiceMock) CheckSettingsNodeExists(context.Context, *data.BucketInfo) error {
|
|
||||||
_, ok := t.system["bucket-settings"]
|
|
||||||
if !ok {
|
|
||||||
return layer.ErrNodeNotFound
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *treeServiceMock) GetSubTreeByPrefix(context.Context, *data.BucketInfo, string, bool) ([]data.NodeInfo, string, error) {
|
|
||||||
return nil, "", nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *treeServiceMock) GetLatestVersion(context.Context, *cid.ID, string) (*data.NodeVersion, error) {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type configMock struct {
|
|
||||||
additionalSearch bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *configMock) DefaultTimestamp() bool {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *configMock) ArchiveCompression() bool {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *configMock) IndexPageEnabled() bool {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *configMock) IndexPageTemplate() string {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *configMock) IndexPageNativeTemplate() string {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *configMock) ClientCut() bool {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *configMock) BufferMaxSizeForPut() uint64 {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *configMock) NamespaceHeader() string {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *configMock) EnableFilepathFallback() bool {
|
|
||||||
return c.additionalSearch
|
|
||||||
}
|
|
||||||
|
|
||||||
type handlerContext struct {
|
|
||||||
key *keys.PrivateKey
|
|
||||||
owner user.ID
|
|
||||||
|
|
||||||
h *Handler
|
|
||||||
frostfs *TestFrostFS
|
|
||||||
tree *treeServiceMock
|
|
||||||
cfg *configMock
|
|
||||||
}
|
|
||||||
|
|
||||||
func (hc *handlerContext) Handler() *Handler {
|
|
||||||
return hc.h
|
|
||||||
}
|
|
||||||
|
|
||||||
func prepareHandlerContext() (*handlerContext, error) {
|
|
||||||
logger, err := zap.NewDevelopment()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
key, err := keys.NewPrivateKey()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var owner user.ID
|
|
||||||
user.IDFromKey(&owner, key.PrivateKey.PublicKey)
|
|
||||||
|
|
||||||
testFrostFS := NewTestFrostFS(key)
|
|
||||||
|
|
||||||
testResolver := &resolver.Resolver{Name: "test_resolver"}
|
|
||||||
testResolver.SetResolveFunc(func(_ context.Context, name string) (*cid.ID, error) {
|
|
||||||
return testFrostFS.ContainerID(name)
|
|
||||||
})
|
|
||||||
|
|
||||||
params := &AppParams{
|
|
||||||
Logger: logger,
|
|
||||||
FrostFS: testFrostFS,
|
|
||||||
Owner: &owner,
|
|
||||||
Resolver: testResolver,
|
|
||||||
Cache: cache.NewBucketCache(&cache.Config{
|
|
||||||
Size: 1,
|
|
||||||
Lifetime: 1,
|
|
||||||
Logger: logger,
|
|
||||||
}, false),
|
|
||||||
}
|
|
||||||
|
|
||||||
treeMock := newTreeService()
|
|
||||||
cfgMock := &configMock{}
|
|
||||||
|
|
||||||
workerPool, err := ants.NewPool(1)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
handler := New(params, cfgMock, treeMock, workerPool)
|
|
||||||
|
|
||||||
return &handlerContext{
|
|
||||||
key: key,
|
|
||||||
owner: owner,
|
|
||||||
h: handler,
|
|
||||||
frostfs: testFrostFS,
|
|
||||||
tree: treeMock,
|
|
||||||
cfg: cfgMock,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (hc *handlerContext) prepareContainer(name string, basicACL acl.Basic) (cid.ID, *container.Container, error) {
|
|
||||||
var pp netmap.PlacementPolicy
|
|
||||||
err := pp.DecodeString("REP 1")
|
|
||||||
if err != nil {
|
|
||||||
return cid.ID{}, nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var cnr container.Container
|
|
||||||
cnr.Init()
|
|
||||||
cnr.SetOwner(hc.owner)
|
|
||||||
cnr.SetPlacementPolicy(pp)
|
|
||||||
cnr.SetBasicACL(basicACL)
|
|
||||||
|
|
||||||
var domain container.Domain
|
|
||||||
domain.SetName(name)
|
|
||||||
container.WriteDomain(&cnr, domain)
|
|
||||||
container.SetName(&cnr, name)
|
|
||||||
container.SetCreationTime(&cnr, time.Now())
|
|
||||||
|
|
||||||
cnrID := cidtest.ID()
|
|
||||||
|
|
||||||
for op := acl.OpObjectGet; op < acl.OpObjectHash; op++ {
|
|
||||||
hc.frostfs.AllowUserOperation(cnrID, hc.owner, op, oid.ID{})
|
|
||||||
if basicACL.IsOpAllowed(op, acl.RoleOthers) {
|
|
||||||
hc.frostfs.AllowUserOperation(cnrID, user.ID{}, op, oid.ID{})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return cnrID, &cnr, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestBasic(t *testing.T) {
|
|
||||||
hc, err := prepareHandlerContext()
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
bktName := "bucket"
|
|
||||||
cnrID, cnr, err := hc.prepareContainer(bktName, acl.PublicRWExtended)
|
|
||||||
require.NoError(t, err)
|
|
||||||
hc.frostfs.SetContainer(cnrID, cnr)
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
ctx = middleware.SetNamespace(ctx, "")
|
|
||||||
|
|
||||||
content := "hello"
|
|
||||||
r, err := prepareUploadRequest(ctx, cnrID.EncodeToString(), content)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
hc.Handler().Upload(r)
|
|
||||||
require.Equal(t, r.Response.StatusCode(), http.StatusOK)
|
|
||||||
|
|
||||||
var putRes putResponse
|
|
||||||
err = json.Unmarshal(r.Response.Body(), &putRes)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
obj := hc.frostfs.objects[putRes.ContainerID+"/"+putRes.ObjectID]
|
|
||||||
attr := prepareObjectAttributes(object.AttributeFilePath, objFileName)
|
|
||||||
obj.SetAttributes(append(obj.Attributes(), attr)...)
|
|
||||||
|
|
||||||
t.Run("get", func(t *testing.T) {
|
|
||||||
r = prepareGetRequest(ctx, cnrID.EncodeToString(), putRes.ObjectID)
|
|
||||||
hc.Handler().DownloadByAddressOrBucketName(r)
|
|
||||||
require.Equal(t, content, string(r.Response.Body()))
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("head", func(t *testing.T) {
|
|
||||||
r = prepareGetRequest(ctx, cnrID.EncodeToString(), putRes.ObjectID)
|
|
||||||
hc.Handler().HeadByAddressOrBucketName(r)
|
|
||||||
require.Equal(t, putRes.ObjectID, string(r.Response.Header.Peek(hdrObjectID)))
|
|
||||||
require.Equal(t, putRes.ContainerID, string(r.Response.Header.Peek(hdrContainerID)))
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("get by attribute", func(t *testing.T) {
|
|
||||||
r = prepareGetByAttributeRequest(ctx, bktName, keyAttr, valAttr)
|
|
||||||
hc.Handler().DownloadByAttribute(r)
|
|
||||||
require.Equal(t, content, string(r.Response.Body()))
|
|
||||||
|
|
||||||
r = prepareGetByAttributeRequest(ctx, bktName, attrFileName, "/"+objFileName)
|
|
||||||
hc.Handler().DownloadByAttribute(r)
|
|
||||||
require.Equal(t, content, string(r.Response.Body()))
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("head by attribute", func(t *testing.T) {
|
|
||||||
r = prepareGetByAttributeRequest(ctx, bktName, keyAttr, valAttr)
|
|
||||||
hc.Handler().HeadByAttribute(r)
|
|
||||||
require.Equal(t, putRes.ObjectID, string(r.Response.Header.Peek(hdrObjectID)))
|
|
||||||
require.Equal(t, putRes.ContainerID, string(r.Response.Header.Peek(hdrContainerID)))
|
|
||||||
|
|
||||||
r = prepareGetByAttributeRequest(ctx, bktName, attrFileName, "/"+objFileName)
|
|
||||||
hc.Handler().HeadByAttribute(r)
|
|
||||||
require.Equal(t, putRes.ObjectID, string(r.Response.Header.Peek(hdrObjectID)))
|
|
||||||
require.Equal(t, putRes.ContainerID, string(r.Response.Header.Peek(hdrContainerID)))
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("zip", func(t *testing.T) {
|
|
||||||
r = prepareGetZipped(ctx, bktName, "")
|
|
||||||
hc.Handler().DownloadZip(r)
|
|
||||||
|
|
||||||
readerAt := bytes.NewReader(r.Response.Body())
|
|
||||||
zipReader, err := zip.NewReader(readerAt, int64(len(r.Response.Body())))
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Len(t, zipReader.File, 1)
|
|
||||||
require.Equal(t, objFileName, zipReader.File[0].Name)
|
|
||||||
f, err := zipReader.File[0].Open()
|
|
||||||
require.NoError(t, err)
|
|
||||||
defer func() {
|
|
||||||
inErr := f.Close()
|
|
||||||
require.NoError(t, inErr)
|
|
||||||
}()
|
|
||||||
data, err := io.ReadAll(f)
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Equal(t, content, string(data))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFindObjectByAttribute(t *testing.T) {
|
|
||||||
hc, err := prepareHandlerContext()
|
|
||||||
require.NoError(t, err)
|
|
||||||
hc.cfg.additionalSearch = true
|
|
||||||
|
|
||||||
bktName := "bucket"
|
|
||||||
cnrID, cnr, err := hc.prepareContainer(bktName, acl.PublicRWExtended)
|
|
||||||
require.NoError(t, err)
|
|
||||||
hc.frostfs.SetContainer(cnrID, cnr)
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
ctx = middleware.SetNamespace(ctx, "")
|
|
||||||
|
|
||||||
content := "hello"
|
|
||||||
r, err := prepareUploadRequest(ctx, cnrID.EncodeToString(), content)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
hc.Handler().Upload(r)
|
|
||||||
require.Equal(t, r.Response.StatusCode(), http.StatusOK)
|
|
||||||
|
|
||||||
var putRes putResponse
|
|
||||||
err = json.Unmarshal(r.Response.Body(), &putRes)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
testAttrVal1 := "/folder/cat.jpg"
|
|
||||||
testAttrVal2 := "cat.jpg"
|
|
||||||
testAttrVal3 := "test-attr-val3"
|
|
||||||
|
|
||||||
for _, tc := range []struct {
|
|
||||||
name string
|
|
||||||
firstAttr object.Attribute
|
|
||||||
secondAttr object.Attribute
|
|
||||||
reqAttrKey string
|
|
||||||
reqAttrValue string
|
|
||||||
err string
|
|
||||||
additionalSearch bool
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "success search by FileName",
|
|
||||||
firstAttr: prepareObjectAttributes(attrFilePath, testAttrVal1),
|
|
||||||
secondAttr: prepareObjectAttributes(attrFileName, testAttrVal2),
|
|
||||||
reqAttrKey: attrFileName,
|
|
||||||
reqAttrValue: testAttrVal2,
|
|
||||||
additionalSearch: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "failed search by FileName",
|
|
||||||
firstAttr: prepareObjectAttributes(attrFilePath, testAttrVal1),
|
|
||||||
secondAttr: prepareObjectAttributes(attrFileName, testAttrVal2),
|
|
||||||
reqAttrKey: attrFileName,
|
|
||||||
reqAttrValue: testAttrVal3,
|
|
||||||
err: "not found",
|
|
||||||
additionalSearch: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "success search by FilePath (with additional search)",
|
|
||||||
firstAttr: prepareObjectAttributes(attrFilePath, testAttrVal1),
|
|
||||||
secondAttr: prepareObjectAttributes(attrFileName, testAttrVal2),
|
|
||||||
reqAttrKey: attrFilePath,
|
|
||||||
reqAttrValue: testAttrVal2,
|
|
||||||
additionalSearch: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "failed by FilePath (with additional search)",
|
|
||||||
firstAttr: prepareObjectAttributes(attrFilePath, testAttrVal1),
|
|
||||||
secondAttr: prepareObjectAttributes(attrFileName, testAttrVal2),
|
|
||||||
reqAttrKey: attrFilePath,
|
|
||||||
reqAttrValue: testAttrVal3,
|
|
||||||
err: "not found",
|
|
||||||
additionalSearch: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "success search by FilePath with leading slash (with additional search)",
|
|
||||||
firstAttr: prepareObjectAttributes(attrFilePath, testAttrVal1),
|
|
||||||
secondAttr: prepareObjectAttributes(attrFileName, testAttrVal2),
|
|
||||||
reqAttrKey: attrFilePath,
|
|
||||||
reqAttrValue: "/cat.jpg",
|
|
||||||
additionalSearch: true,
|
|
||||||
},
|
|
||||||
} {
|
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
|
||||||
obj := hc.frostfs.objects[putRes.ContainerID+"/"+putRes.ObjectID]
|
|
||||||
obj.SetAttributes(tc.firstAttr, tc.secondAttr)
|
|
||||||
hc.cfg.additionalSearch = tc.additionalSearch
|
|
||||||
|
|
||||||
objID, err := hc.Handler().findObjectByAttribute(ctx, hc.Handler().log, cnrID, tc.reqAttrKey, tc.reqAttrValue)
|
|
||||||
if tc.err != "" {
|
|
||||||
require.Error(t, err)
|
|
||||||
require.Contains(t, err.Error(), tc.err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Equal(t, putRes.ObjectID, objID.EncodeToString())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestNeedSearchByFileName(t *testing.T) {
|
|
||||||
hc, err := prepareHandlerContext()
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
for _, tc := range []struct {
|
|
||||||
name string
|
|
||||||
attrKey string
|
|
||||||
attrVal string
|
|
||||||
additionalSearch bool
|
|
||||||
expected bool
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "need search - not contains slash",
|
|
||||||
attrKey: attrFilePath,
|
|
||||||
attrVal: "cat.png",
|
|
||||||
additionalSearch: true,
|
|
||||||
expected: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "need search - single lead slash",
|
|
||||||
attrKey: attrFilePath,
|
|
||||||
attrVal: "/cat.png",
|
|
||||||
additionalSearch: true,
|
|
||||||
expected: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "don't need search - single slash but not lead",
|
|
||||||
attrKey: attrFilePath,
|
|
||||||
attrVal: "cats/cat.png",
|
|
||||||
additionalSearch: true,
|
|
||||||
expected: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "don't need search - more one slash",
|
|
||||||
attrKey: attrFilePath,
|
|
||||||
attrVal: "/cats/cat.png",
|
|
||||||
additionalSearch: true,
|
|
||||||
expected: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "don't need search - incorrect attribute key",
|
|
||||||
attrKey: attrFileName,
|
|
||||||
attrVal: "cat.png",
|
|
||||||
additionalSearch: true,
|
|
||||||
expected: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "don't need search - additional search disabled",
|
|
||||||
attrKey: attrFilePath,
|
|
||||||
attrVal: "cat.png",
|
|
||||||
additionalSearch: false,
|
|
||||||
expected: false,
|
|
||||||
},
|
|
||||||
} {
|
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
|
||||||
hc.cfg.additionalSearch = tc.additionalSearch
|
|
||||||
|
|
||||||
res := hc.h.needSearchByFileName(tc.attrKey, tc.attrVal)
|
|
||||||
require.Equal(t, tc.expected, res)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPrepareFileName(t *testing.T) {
|
|
||||||
fileName := "/cat.jpg"
|
|
||||||
expected := "cat.jpg"
|
|
||||||
actual := prepareFileName(fileName)
|
|
||||||
require.Equal(t, expected, actual)
|
|
||||||
|
|
||||||
fileName = "cat.jpg"
|
|
||||||
actual = prepareFileName(fileName)
|
|
||||||
require.Equal(t, expected, actual)
|
|
||||||
}
|
|
||||||
|
|
||||||
func prepareUploadRequest(ctx context.Context, bucket, content string) (*fasthttp.RequestCtx, error) {
|
|
||||||
r := new(fasthttp.RequestCtx)
|
|
||||||
utils.SetContextToRequest(ctx, r)
|
|
||||||
r.SetUserValue("cid", bucket)
|
|
||||||
return r, fillMultipartBody(r, content)
|
|
||||||
}
|
|
||||||
|
|
||||||
func prepareGetRequest(ctx context.Context, bucket, objID string) *fasthttp.RequestCtx {
|
|
||||||
r := new(fasthttp.RequestCtx)
|
|
||||||
utils.SetContextToRequest(ctx, r)
|
|
||||||
r.SetUserValue("cid", bucket)
|
|
||||||
r.SetUserValue("oid", objID)
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
|
|
||||||
func prepareGetByAttributeRequest(ctx context.Context, bucket, attrKey, attrVal string) *fasthttp.RequestCtx {
|
|
||||||
r := new(fasthttp.RequestCtx)
|
|
||||||
utils.SetContextToRequest(ctx, r)
|
|
||||||
r.SetUserValue("cid", bucket)
|
|
||||||
r.SetUserValue("attr_key", attrKey)
|
|
||||||
r.SetUserValue("attr_val", attrVal)
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
|
|
||||||
func prepareGetZipped(ctx context.Context, bucket, prefix string) *fasthttp.RequestCtx {
|
|
||||||
r := new(fasthttp.RequestCtx)
|
|
||||||
utils.SetContextToRequest(ctx, r)
|
|
||||||
r.SetUserValue("cid", bucket)
|
|
||||||
r.SetUserValue("prefix", prefix)
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
|
|
||||||
func prepareObjectAttributes(attrKey, attrValue string) object.Attribute {
|
|
||||||
attr := object.NewAttribute()
|
|
||||||
attr.SetKey(attrKey)
|
|
||||||
attr.SetValue(attrValue)
|
|
||||||
return *attr
|
|
||||||
}
|
|
||||||
|
|
||||||
const (
|
|
||||||
keyAttr = "User-Attribute"
|
|
||||||
valAttr = "user value"
|
|
||||||
objFileName = "newFile.txt"
|
|
||||||
)
|
|
||||||
|
|
||||||
func fillMultipartBody(r *fasthttp.RequestCtx, content string) error {
|
|
||||||
attributes := map[string]string{
|
|
||||||
object.AttributeFileName: objFileName,
|
|
||||||
keyAttr: valAttr,
|
|
||||||
}
|
|
||||||
|
|
||||||
var buff bytes.Buffer
|
|
||||||
w := multipart.NewWriter(&buff)
|
|
||||||
fw, err := w.CreateFormFile("file", attributes[object.AttributeFileName])
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err = io.Copy(fw, bytes.NewBufferString(content)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err = w.Close(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
r.Request.SetBodyStream(&buff, buff.Len())
|
|
||||||
r.Request.Header.Set("Content-Type", w.FormDataContentType())
|
|
||||||
r.Request.Header.Set("X-Attribute-"+keyAttr, valAttr)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
|
@ -1,163 +0,0 @@
|
||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/layer"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/logs"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/utils"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-observability/tracing"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object"
|
|
||||||
oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
|
|
||||||
"github.com/valyala/fasthttp"
|
|
||||||
"go.uber.org/zap"
|
|
||||||
)
|
|
||||||
|
|
||||||
// max bytes needed to detect content type according to http.DetectContentType docs.
|
|
||||||
const sizeToDetectType = 512
|
|
||||||
|
|
||||||
const (
|
|
||||||
hdrObjectID = "X-Object-Id"
|
|
||||||
hdrOwnerID = "X-Owner-Id"
|
|
||||||
hdrContainerID = "X-Container-Id"
|
|
||||||
)
|
|
||||||
|
|
||||||
func (h *Handler) headObject(ctx context.Context, req request, objectAddress oid.Address) {
|
|
||||||
var start = time.Now()
|
|
||||||
|
|
||||||
btoken := bearerToken(ctx)
|
|
||||||
|
|
||||||
prm := PrmObjectHead{
|
|
||||||
PrmAuth: PrmAuth{
|
|
||||||
BearerToken: btoken,
|
|
||||||
},
|
|
||||||
Address: objectAddress,
|
|
||||||
}
|
|
||||||
|
|
||||||
obj, err := h.frostfs.HeadObject(ctx, prm)
|
|
||||||
if err != nil {
|
|
||||||
req.handleFrostFSErr(err, start)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
req.Response.Header.Set(fasthttp.HeaderContentLength, strconv.FormatUint(obj.PayloadSize(), 10))
|
|
||||||
var (
|
|
||||||
contentType string
|
|
||||||
filename string
|
|
||||||
filepath string
|
|
||||||
)
|
|
||||||
for _, attr := range obj.Attributes() {
|
|
||||||
key := attr.Key()
|
|
||||||
val := attr.Value()
|
|
||||||
if !isValidToken(key) || !isValidValue(val) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
key = utils.BackwardTransformIfSystem(key)
|
|
||||||
|
|
||||||
req.Response.Header.Set(utils.UserAttributeHeaderPrefix+key, val)
|
|
||||||
switch key {
|
|
||||||
case object.AttributeTimestamp:
|
|
||||||
value, err := strconv.ParseInt(val, 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
req.log.Info(logs.CouldntParseCreationDate,
|
|
||||||
zap.String("key", key),
|
|
||||||
zap.String("val", val),
|
|
||||||
zap.Error(err),
|
|
||||||
logs.TagField(logs.TagDatapath))
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
req.Response.Header.Set(fasthttp.HeaderLastModified, time.Unix(value, 0).UTC().Format(http.TimeFormat))
|
|
||||||
case object.AttributeContentType:
|
|
||||||
contentType = val
|
|
||||||
case object.AttributeFilePath:
|
|
||||||
filepath = val
|
|
||||||
case object.AttributeFileName:
|
|
||||||
filename = val
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if filename == "" {
|
|
||||||
filename = filepath
|
|
||||||
}
|
|
||||||
|
|
||||||
idsToResponse(&req.Response, obj)
|
|
||||||
|
|
||||||
if len(contentType) == 0 {
|
|
||||||
contentType, _, err = readContentType(obj.PayloadSize(), func(sz uint64) (io.Reader, error) {
|
|
||||||
prmRange := PrmObjectRange{
|
|
||||||
PrmAuth: PrmAuth{
|
|
||||||
BearerToken: btoken,
|
|
||||||
},
|
|
||||||
Address: objectAddress,
|
|
||||||
PayloadRange: [2]uint64{0, sz},
|
|
||||||
}
|
|
||||||
|
|
||||||
return h.frostfs.RangeObject(ctx, prmRange)
|
|
||||||
}, filename)
|
|
||||||
if err != nil && err != io.EOF {
|
|
||||||
req.handleFrostFSErr(err, start)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
req.SetContentType(contentType)
|
|
||||||
}
|
|
||||||
|
|
||||||
func idsToResponse(resp *fasthttp.Response, obj *object.Object) {
|
|
||||||
objID, _ := obj.ID()
|
|
||||||
cnrID, _ := obj.ContainerID()
|
|
||||||
resp.Header.Set(hdrObjectID, objID.String())
|
|
||||||
resp.Header.Set(hdrOwnerID, obj.OwnerID().String())
|
|
||||||
resp.Header.Set(hdrContainerID, cnrID.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
// HeadByAddressOrBucketName handles head requests using simple cid/oid or bucketname/key format.
|
|
||||||
func (h *Handler) HeadByAddressOrBucketName(c *fasthttp.RequestCtx) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(utils.GetContextFromRequest(c), "handler.HeadByAddressOrBucketName")
|
|
||||||
defer span.End()
|
|
||||||
|
|
||||||
cidParam, _ := c.UserValue("cid").(string)
|
|
||||||
oidParam, _ := c.UserValue("oid").(string)
|
|
||||||
|
|
||||||
log := utils.GetReqLogOrDefault(ctx, h.log).With(
|
|
||||||
zap.String("cid", cidParam),
|
|
||||||
zap.String("oid", oidParam),
|
|
||||||
)
|
|
||||||
|
|
||||||
bktInfo, err := h.getBucketInfo(ctx, cidParam, log)
|
|
||||||
if err != nil {
|
|
||||||
logAndSendBucketError(c, log, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
checkS3Err := h.tree.CheckSettingsNodeExists(ctx, bktInfo)
|
|
||||||
if checkS3Err != nil && !errors.Is(checkS3Err, layer.ErrNodeNotFound) {
|
|
||||||
log.Error(logs.FailedToCheckIfSettingsNodeExist, zap.String("cid", bktInfo.CID.String()),
|
|
||||||
zap.Error(checkS3Err), logs.TagField(logs.TagExternalStorageTree))
|
|
||||||
logAndSendBucketError(c, log, checkS3Err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
req := newRequest(c, log)
|
|
||||||
|
|
||||||
var objID oid.ID
|
|
||||||
if checkS3Err == nil {
|
|
||||||
h.byS3Path(ctx, req, bktInfo.CID, oidParam, h.headObject)
|
|
||||||
} else if err = objID.DecodeString(oidParam); err == nil {
|
|
||||||
h.byNativeAddress(ctx, req, bktInfo.CID, objID, h.headObject)
|
|
||||||
} else {
|
|
||||||
logAndSendBucketError(c, log, checkS3Err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// HeadByAttribute handles attribute-based head requests.
|
|
||||||
func (h *Handler) HeadByAttribute(c *fasthttp.RequestCtx) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(utils.GetContextFromRequest(c), "handler.HeadByAttribute")
|
|
||||||
defer span.End()
|
|
||||||
utils.SetContextToRequest(ctx, c)
|
|
||||||
|
|
||||||
h.byAttribute(c, h.headObject)
|
|
||||||
}
|
|
|
@ -1,26 +0,0 @@
|
||||||
package middleware
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
)
|
|
||||||
|
|
||||||
// keyWrapper is wrapper for context keys.
|
|
||||||
type keyWrapper string
|
|
||||||
|
|
||||||
const nsKey = keyWrapper("namespace")
|
|
||||||
|
|
||||||
// GetNamespace extract namespace from context.
|
|
||||||
func GetNamespace(ctx context.Context) (string, error) {
|
|
||||||
ns, ok := ctx.Value(nsKey).(string)
|
|
||||||
if !ok {
|
|
||||||
return "", fmt.Errorf("couldn't get namespace from context")
|
|
||||||
}
|
|
||||||
|
|
||||||
return ns, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetNamespace sets namespace in the context.
|
|
||||||
func SetNamespace(ctx context.Context, ns string) context.Context {
|
|
||||||
return context.WithValue(ctx, nsKey, ns)
|
|
||||||
}
|
|
|
@ -1,80 +0,0 @@
|
||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"io"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/handler/multipart"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/logs"
|
|
||||||
"go.uber.org/zap"
|
|
||||||
)
|
|
||||||
|
|
||||||
const attributeMultipartObjectSize = "S3-Multipart-Object-Size"
|
|
||||||
|
|
||||||
// MultipartFile provides standard ReadCloser interface and also allows one to
|
|
||||||
// get file name, it's used for multipart uploads.
|
|
||||||
type MultipartFile interface {
|
|
||||||
io.ReadCloser
|
|
||||||
FileName() string
|
|
||||||
}
|
|
||||||
|
|
||||||
func fetchMultipartFile(l *zap.Logger, r io.Reader, boundary string) (MultipartFile, error) {
|
|
||||||
// To have a custom buffer (3mb) the custom multipart reader is used.
|
|
||||||
// Default reader uses 4KiB chunks, which slow down upload speed up to 400%
|
|
||||||
// https://github.com/golang/go/blob/91b9915d3f6f8cd2e9e9fda63f67772803adfa03/src/mime/multipart/multipart.go#L32
|
|
||||||
reader := multipart.NewReader(r, boundary)
|
|
||||||
|
|
||||||
for {
|
|
||||||
part, err := reader.NextPart()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
name := part.FormName()
|
|
||||||
if name == "" {
|
|
||||||
l.Debug(logs.IgnorePartEmptyFormName, logs.TagField(logs.TagDatapath))
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
filename := part.FileName()
|
|
||||||
|
|
||||||
// ignore multipart/form-data values
|
|
||||||
if filename == "" {
|
|
||||||
l.Debug(logs.IgnorePartEmptyFilename, zap.String("form", name), logs.TagField(logs.TagDatapath))
|
|
||||||
if err = part.Close(); err != nil {
|
|
||||||
l.Warn(logs.FailedToCloseReader, zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
return part, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// getPayload returns initial payload if object is not multipart else composes new reader with parts data.
|
|
||||||
func (h *Handler) getPayload(p getMultiobjectBodyParams) (io.ReadCloser, uint64, error) {
|
|
||||||
cid, ok := p.obj.Header.ContainerID()
|
|
||||||
if !ok {
|
|
||||||
return nil, 0, errors.New("no container id set")
|
|
||||||
}
|
|
||||||
oid, ok := p.obj.Header.ID()
|
|
||||||
if !ok {
|
|
||||||
return nil, 0, errors.New("no object id set")
|
|
||||||
}
|
|
||||||
size, err := strconv.ParseUint(p.strSize, 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
return nil, 0, err
|
|
||||||
}
|
|
||||||
ctx := p.req.RequestCtx
|
|
||||||
params := PrmInitMultiObjectReader{
|
|
||||||
Addr: newAddress(cid, oid),
|
|
||||||
Bearer: bearerToken(ctx),
|
|
||||||
}
|
|
||||||
payload, err := h.frostfs.InitMultiObjectReader(ctx, params)
|
|
||||||
if err != nil {
|
|
||||||
return nil, 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return io.NopCloser(payload), size, nil
|
|
||||||
}
|
|
|
@ -1,199 +0,0 @@
|
||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"io"
|
|
||||||
"mime"
|
|
||||||
"net/http"
|
|
||||||
"path"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/logs"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/utils"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object"
|
|
||||||
oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
|
|
||||||
"github.com/valyala/fasthttp"
|
|
||||||
"go.uber.org/zap"
|
|
||||||
)
|
|
||||||
|
|
||||||
type readCloser struct {
|
|
||||||
io.Reader
|
|
||||||
io.Closer
|
|
||||||
}
|
|
||||||
|
|
||||||
// initializes io.Reader with the limited size and detects Content-Type from it.
|
|
||||||
// Returns r's error directly. Also returns the processed data.
|
|
||||||
func readContentType(maxSize uint64, rInit func(uint64) (io.Reader, error), filename string) (string, []byte, error) {
|
|
||||||
if maxSize > sizeToDetectType {
|
|
||||||
maxSize = sizeToDetectType
|
|
||||||
}
|
|
||||||
|
|
||||||
buf := make([]byte, maxSize) // maybe sync-pool the slice?
|
|
||||||
|
|
||||||
r, err := rInit(maxSize)
|
|
||||||
if err != nil {
|
|
||||||
return "", nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
n, err := r.Read(buf)
|
|
||||||
if err != nil && err != io.EOF {
|
|
||||||
return "", nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
buf = buf[:n]
|
|
||||||
|
|
||||||
contentType := http.DetectContentType(buf)
|
|
||||||
|
|
||||||
// Since the detector detects the "text/plain" content type for various types of text files,
|
|
||||||
// including CSS, JavaScript, and CSV files,
|
|
||||||
// we'll determine the final content type based on the file's extension.
|
|
||||||
if strings.HasPrefix(contentType, "text/plain") {
|
|
||||||
ext := path.Ext(filename)
|
|
||||||
// If the file doesn't have a file extension, we'll keep the content type as is.
|
|
||||||
if len(ext) > 0 {
|
|
||||||
contentType = mime.TypeByExtension(ext)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return contentType, buf, err // to not lose io.EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
type getMultiobjectBodyParams struct {
|
|
||||||
obj *Object
|
|
||||||
req request
|
|
||||||
strSize string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) receiveFile(ctx context.Context, req request, objAddress oid.Address) {
|
|
||||||
var (
|
|
||||||
shouldDownload = req.QueryArgs().GetBool("download")
|
|
||||||
start = time.Now()
|
|
||||||
filename string
|
|
||||||
filepath string
|
|
||||||
contentType string
|
|
||||||
)
|
|
||||||
|
|
||||||
prm := PrmObjectGet{
|
|
||||||
PrmAuth: PrmAuth{
|
|
||||||
BearerToken: bearerToken(ctx),
|
|
||||||
},
|
|
||||||
Address: objAddress,
|
|
||||||
}
|
|
||||||
|
|
||||||
rObj, err := h.frostfs.GetObject(ctx, prm)
|
|
||||||
if err != nil {
|
|
||||||
req.handleFrostFSErr(err, start)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// we can't close reader in this function, so how to do it?
|
|
||||||
req.setIDs(rObj.Header)
|
|
||||||
payload := rObj.Payload
|
|
||||||
payloadSize := rObj.Header.PayloadSize()
|
|
||||||
for _, attr := range rObj.Header.Attributes() {
|
|
||||||
key := attr.Key()
|
|
||||||
val := attr.Value()
|
|
||||||
if !isValidToken(key) || !isValidValue(val) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
key = utils.BackwardTransformIfSystem(key)
|
|
||||||
|
|
||||||
req.Response.Header.Set(utils.UserAttributeHeaderPrefix+key, val)
|
|
||||||
switch key {
|
|
||||||
case object.AttributeFileName:
|
|
||||||
filename = val
|
|
||||||
case object.AttributeTimestamp:
|
|
||||||
if err = req.setTimestamp(val); err != nil {
|
|
||||||
req.log.Error(logs.CouldntParseCreationDate,
|
|
||||||
zap.String("val", val),
|
|
||||||
zap.Error(err),
|
|
||||||
logs.TagField(logs.TagDatapath))
|
|
||||||
}
|
|
||||||
case object.AttributeContentType:
|
|
||||||
contentType = val
|
|
||||||
case object.AttributeFilePath:
|
|
||||||
filepath = val
|
|
||||||
case attributeMultipartObjectSize:
|
|
||||||
payload, payloadSize, err = h.getPayload(getMultiobjectBodyParams{
|
|
||||||
obj: rObj,
|
|
||||||
req: req,
|
|
||||||
strSize: val,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
req.handleFrostFSErr(err, start)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if filename == "" {
|
|
||||||
filename = filepath
|
|
||||||
}
|
|
||||||
|
|
||||||
req.setDisposition(shouldDownload, filename)
|
|
||||||
|
|
||||||
req.Response.Header.Set(fasthttp.HeaderContentLength, strconv.FormatUint(payloadSize, 10))
|
|
||||||
|
|
||||||
if len(contentType) == 0 {
|
|
||||||
// determine the Content-Type from the payload head
|
|
||||||
var payloadHead []byte
|
|
||||||
|
|
||||||
contentType, payloadHead, err = readContentType(payloadSize, func(uint64) (io.Reader, error) {
|
|
||||||
return payload, nil
|
|
||||||
}, filename)
|
|
||||||
if err != nil && err != io.EOF {
|
|
||||||
req.log.Error(logs.CouldNotDetectContentTypeFromPayload, zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
ResponseError(req.RequestCtx, "could not detect Content-Type from payload: "+err.Error(), fasthttp.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// reset payload reader since a part of the data has been read
|
|
||||||
var headReader io.Reader = bytes.NewReader(payloadHead)
|
|
||||||
|
|
||||||
if err != io.EOF { // otherwise, we've already read full payload
|
|
||||||
headReader = io.MultiReader(headReader, payload)
|
|
||||||
}
|
|
||||||
|
|
||||||
// note: we could do with io.Reader, but SetBodyStream below closes body stream
|
|
||||||
// if it implements io.Closer and that's useful for us.
|
|
||||||
payload = readCloser{headReader, payload}
|
|
||||||
}
|
|
||||||
req.SetContentType(contentType)
|
|
||||||
req.Response.SetBodyStream(payload, int(payloadSize))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *request) setIDs(obj object.Object) {
|
|
||||||
objID, _ := obj.ID()
|
|
||||||
cnrID, _ := obj.ContainerID()
|
|
||||||
r.Response.Header.Set(hdrObjectID, objID.String())
|
|
||||||
r.Response.Header.Set(hdrOwnerID, obj.OwnerID().String())
|
|
||||||
r.Response.Header.Set(hdrContainerID, cnrID.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *request) setDisposition(shouldDownload bool, filename string) {
|
|
||||||
const (
|
|
||||||
inlineDisposition = "inline"
|
|
||||||
attachmentDisposition = "attachment"
|
|
||||||
)
|
|
||||||
|
|
||||||
dis := inlineDisposition
|
|
||||||
if shouldDownload {
|
|
||||||
dis = attachmentDisposition
|
|
||||||
}
|
|
||||||
|
|
||||||
r.Response.Header.Set(fasthttp.HeaderContentDisposition, dis+"; filename="+path.Base(filename))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *request) setTimestamp(timestamp string) error {
|
|
||||||
value, err := strconv.ParseInt(timestamp, 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
r.Response.Header.Set(fasthttp.HeaderLastModified,
|
|
||||||
time.Unix(value, 0).UTC().Format(http.TimeFormat))
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
|
@ -1,89 +0,0 @@
|
||||||
//go:build !integration
|
|
||||||
|
|
||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
txtContentType = "text/plain; charset=utf-8"
|
|
||||||
cssContentType = "text/css; charset=utf-8"
|
|
||||||
htmlContentType = "text/html; charset=utf-8"
|
|
||||||
javascriptContentType = "text/javascript; charset=utf-8"
|
|
||||||
|
|
||||||
htmlBody = "<!DOCTYPE html><html ><head><meta charset=\"utf-8\"><title>Test Html</title>"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestDetector(t *testing.T) {
|
|
||||||
sb := strings.Builder{}
|
|
||||||
for i := 0; i < 10; i++ {
|
|
||||||
sb.WriteString("Some txt content. Content-Type must be detected properly by detector.")
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tc := range []struct {
|
|
||||||
Name string
|
|
||||||
ExpectedContentType string
|
|
||||||
Content string
|
|
||||||
FileName string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
Name: "less than 512b",
|
|
||||||
ExpectedContentType: txtContentType,
|
|
||||||
Content: sb.String()[:256],
|
|
||||||
FileName: "test.txt",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "more than 512b",
|
|
||||||
ExpectedContentType: txtContentType,
|
|
||||||
Content: sb.String(),
|
|
||||||
FileName: "test.txt",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "css content type",
|
|
||||||
ExpectedContentType: cssContentType,
|
|
||||||
Content: sb.String(),
|
|
||||||
FileName: "test.css",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "javascript content type",
|
|
||||||
ExpectedContentType: javascriptContentType,
|
|
||||||
Content: sb.String(),
|
|
||||||
FileName: "test.js",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "html content type by file content",
|
|
||||||
ExpectedContentType: htmlContentType,
|
|
||||||
Content: htmlBody,
|
|
||||||
FileName: "test.detect-by-content",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "html content type by file extension",
|
|
||||||
ExpectedContentType: htmlContentType,
|
|
||||||
Content: sb.String(),
|
|
||||||
FileName: "test.html",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "empty file extension",
|
|
||||||
ExpectedContentType: txtContentType,
|
|
||||||
Content: sb.String(),
|
|
||||||
FileName: "test",
|
|
||||||
},
|
|
||||||
} {
|
|
||||||
t.Run(tc.Name, func(t *testing.T) {
|
|
||||||
contentType, data, err := readContentType(uint64(len(tc.Content)),
|
|
||||||
func(uint64) (io.Reader, error) {
|
|
||||||
return strings.NewReader(tc.Content), nil
|
|
||||||
}, tc.FileName,
|
|
||||||
)
|
|
||||||
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Equal(t, tc.ExpectedContentType, contentType)
|
|
||||||
require.True(t, strings.HasPrefix(tc.Content, string(data)))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,295 +0,0 @@
|
||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"archive/tar"
|
|
||||||
"bytes"
|
|
||||||
"compress/gzip"
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"path/filepath"
|
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/data"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/logs"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/tokens"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/utils"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-observability/tracing"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/bearer"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object"
|
|
||||||
oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
|
|
||||||
"github.com/valyala/fasthttp"
|
|
||||||
"go.uber.org/zap"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
jsonHeader = "application/json; charset=UTF-8"
|
|
||||||
drainBufSize = 4096
|
|
||||||
explodeArchiveHeader = "X-Explode-Archive"
|
|
||||||
)
|
|
||||||
|
|
||||||
type putResponse struct {
|
|
||||||
ObjectID string `json:"object_id"`
|
|
||||||
ContainerID string `json:"container_id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func newPutResponse(addr oid.Address) *putResponse {
|
|
||||||
return &putResponse{
|
|
||||||
ObjectID: addr.Object().EncodeToString(),
|
|
||||||
ContainerID: addr.Container().EncodeToString(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pr *putResponse) encode(w io.Writer) error {
|
|
||||||
enc := json.NewEncoder(w)
|
|
||||||
enc.SetIndent("", "\t")
|
|
||||||
return enc.Encode(pr)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Upload handles multipart upload request.
|
|
||||||
func (h *Handler) Upload(c *fasthttp.RequestCtx) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(utils.GetContextFromRequest(c), "handler.Upload")
|
|
||||||
defer span.End()
|
|
||||||
utils.SetContextToRequest(ctx, c)
|
|
||||||
|
|
||||||
var file MultipartFile
|
|
||||||
|
|
||||||
scid, _ := c.UserValue("cid").(string)
|
|
||||||
bodyStream := c.RequestBodyStream()
|
|
||||||
drainBuf := make([]byte, drainBufSize)
|
|
||||||
|
|
||||||
reqLog := utils.GetReqLogOrDefault(ctx, h.log)
|
|
||||||
log := reqLog.With(zap.String("cid", scid))
|
|
||||||
|
|
||||||
bktInfo, err := h.getBucketInfo(ctx, scid, log)
|
|
||||||
if err != nil {
|
|
||||||
logAndSendBucketError(c, log, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
boundary := string(c.Request.Header.MultipartFormBoundary())
|
|
||||||
if file, err = fetchMultipartFile(log, bodyStream, boundary); err != nil {
|
|
||||||
log.Error(logs.CouldNotReceiveMultipartForm, zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
ResponseError(c, "could not receive multipart/form: "+err.Error(), fasthttp.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
filtered, err := filterHeaders(log, &c.Request.Header)
|
|
||||||
if err != nil {
|
|
||||||
log.Error(logs.FailedToFilterHeaders, zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
ResponseError(c, err.Error(), fasthttp.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if c.Request.Header.Peek(explodeArchiveHeader) != nil {
|
|
||||||
h.explodeArchive(request{c, log}, bktInfo, file, filtered)
|
|
||||||
} else {
|
|
||||||
h.uploadSingleObject(request{c, log}, bktInfo, file, filtered)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Multipart is multipart and thus can contain more than one part which
|
|
||||||
// we ignore at the moment. Also, when dealing with chunked encoding
|
|
||||||
// the last zero-length chunk might be left unread (because multipart
|
|
||||||
// reader only cares about its boundary and doesn't look further) and
|
|
||||||
// it will be (erroneously) interpreted as the start of the next
|
|
||||||
// pipelined header. Thus, we need to drain the body buffer.
|
|
||||||
for {
|
|
||||||
_, err = bodyStream.Read(drainBuf)
|
|
||||||
if err == io.EOF || errors.Is(err, io.ErrUnexpectedEOF) {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) uploadSingleObject(req request, bkt *data.BucketInfo, file MultipartFile, filtered map[string]string) {
|
|
||||||
c, log := req.RequestCtx, req.log
|
|
||||||
|
|
||||||
ctx, span := tracing.StartSpanFromContext(utils.GetContextFromRequest(c), "handler.uploadSingleObject")
|
|
||||||
defer span.End()
|
|
||||||
utils.SetContextToRequest(ctx, c)
|
|
||||||
|
|
||||||
setIfNotExist(filtered, object.AttributeFileName, file.FileName())
|
|
||||||
|
|
||||||
attributes, err := h.extractAttributes(c, log, filtered)
|
|
||||||
if err != nil {
|
|
||||||
log.Error(logs.FailedToGetAttributes, zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
ResponseError(c, "could not extract attributes: "+err.Error(), fasthttp.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
idObj, err := h.uploadObject(c, bkt, attributes, file)
|
|
||||||
if err != nil {
|
|
||||||
h.handlePutFrostFSErr(c, err, log)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
log.Debug(logs.ObjectUploaded,
|
|
||||||
zap.String("oid", idObj.EncodeToString()),
|
|
||||||
zap.String("FileName", file.FileName()),
|
|
||||||
logs.TagField(logs.TagExternalStorage),
|
|
||||||
)
|
|
||||||
|
|
||||||
addr := newAddress(bkt.CID, idObj)
|
|
||||||
c.Response.Header.SetContentType(jsonHeader)
|
|
||||||
// Try to return the response, otherwise, if something went wrong, throw an error.
|
|
||||||
if err = newPutResponse(addr).encode(c); err != nil {
|
|
||||||
log.Error(logs.CouldNotEncodeResponse, zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
ResponseError(c, "could not encode response", fasthttp.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) uploadObject(c *fasthttp.RequestCtx, bkt *data.BucketInfo, attrs []object.Attribute, file io.Reader) (oid.ID, error) {
|
|
||||||
ctx := utils.GetContextFromRequest(c)
|
|
||||||
|
|
||||||
obj := object.New()
|
|
||||||
obj.SetContainerID(bkt.CID)
|
|
||||||
obj.SetOwnerID(*h.ownerID)
|
|
||||||
obj.SetAttributes(attrs...)
|
|
||||||
|
|
||||||
prm := PrmObjectCreate{
|
|
||||||
PrmAuth: PrmAuth{
|
|
||||||
BearerToken: h.fetchBearerToken(ctx),
|
|
||||||
},
|
|
||||||
Object: obj,
|
|
||||||
Payload: file,
|
|
||||||
ClientCut: h.config.ClientCut(),
|
|
||||||
WithoutHomomorphicHash: bkt.HomomorphicHashDisabled,
|
|
||||||
BufferMaxSize: h.config.BufferMaxSizeForPut(),
|
|
||||||
}
|
|
||||||
|
|
||||||
idObj, err := h.frostfs.CreateObject(ctx, prm)
|
|
||||||
if err != nil {
|
|
||||||
return oid.ID{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return idObj, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) extractAttributes(c *fasthttp.RequestCtx, log *zap.Logger, filtered map[string]string) ([]object.Attribute, error) {
|
|
||||||
ctx := utils.GetContextFromRequest(c)
|
|
||||||
now := time.Now()
|
|
||||||
if rawHeader := c.Request.Header.Peek(fasthttp.HeaderDate); rawHeader != nil {
|
|
||||||
if parsed, err := time.Parse(http.TimeFormat, string(rawHeader)); err != nil {
|
|
||||||
log.Warn(logs.CouldNotParseClientTime, zap.String("Date header", string(rawHeader)), zap.Error(err),
|
|
||||||
logs.TagField(logs.TagDatapath))
|
|
||||||
} else {
|
|
||||||
now = parsed
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := utils.PrepareExpirationHeader(ctx, h.frostfs, filtered, now); err != nil {
|
|
||||||
log.Error(logs.CouldNotPrepareExpirationHeader, zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
attributes := make([]object.Attribute, 0, len(filtered))
|
|
||||||
// prepares attributes from filtered headers
|
|
||||||
for key, val := range filtered {
|
|
||||||
attribute := newAttribute(key, val)
|
|
||||||
attributes = append(attributes, attribute)
|
|
||||||
}
|
|
||||||
// sets Timestamp attribute if it wasn't set from header and enabled by settings
|
|
||||||
if _, ok := filtered[object.AttributeTimestamp]; !ok && h.config.DefaultTimestamp() {
|
|
||||||
timestamp := newAttribute(object.AttributeTimestamp, strconv.FormatInt(time.Now().Unix(), 10))
|
|
||||||
attributes = append(attributes, timestamp)
|
|
||||||
}
|
|
||||||
|
|
||||||
return attributes, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func newAttribute(key string, val string) object.Attribute {
|
|
||||||
attr := object.NewAttribute()
|
|
||||||
attr.SetKey(key)
|
|
||||||
attr.SetValue(val)
|
|
||||||
return *attr
|
|
||||||
}
|
|
||||||
|
|
||||||
// explodeArchive read files from archive and creates objects for each of them.
|
|
||||||
// Sets FilePath attribute with name from tar.Header.
|
|
||||||
func (h *Handler) explodeArchive(req request, bkt *data.BucketInfo, file io.ReadCloser, filtered map[string]string) {
|
|
||||||
c, log := req.RequestCtx, req.log
|
|
||||||
|
|
||||||
ctx, span := tracing.StartSpanFromContext(utils.GetContextFromRequest(c), "handler.explodeArchive")
|
|
||||||
defer span.End()
|
|
||||||
utils.SetContextToRequest(ctx, c)
|
|
||||||
|
|
||||||
// remove user attributes which vary for each file in archive
|
|
||||||
// to guarantee that they won't appear twice
|
|
||||||
delete(filtered, object.AttributeFileName)
|
|
||||||
delete(filtered, object.AttributeFilePath)
|
|
||||||
|
|
||||||
commonAttributes, err := h.extractAttributes(c, log, filtered)
|
|
||||||
if err != nil {
|
|
||||||
log.Error(logs.FailedToGetAttributes, zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
ResponseError(c, "could not extract attributes: "+err.Error(), fasthttp.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
attributes := commonAttributes
|
|
||||||
|
|
||||||
reader := file
|
|
||||||
if bytes.EqualFold(c.Request.Header.Peek(fasthttp.HeaderContentEncoding), []byte("gzip")) {
|
|
||||||
log.Debug(logs.GzipReaderSelected, logs.TagField(logs.TagDatapath))
|
|
||||||
gzipReader, err := gzip.NewReader(file)
|
|
||||||
if err != nil {
|
|
||||||
log.Error(logs.FailedToCreateGzipReader, zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
ResponseError(c, "could read gzip file: "+err.Error(), fasthttp.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer func() {
|
|
||||||
if err := gzipReader.Close(); err != nil {
|
|
||||||
log.Warn(logs.FailedToCloseReader, zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
reader = gzipReader
|
|
||||||
}
|
|
||||||
|
|
||||||
tarReader := tar.NewReader(reader)
|
|
||||||
for {
|
|
||||||
obj, err := tarReader.Next()
|
|
||||||
if errors.Is(err, io.EOF) {
|
|
||||||
break
|
|
||||||
} else if err != nil {
|
|
||||||
log.Error(logs.FailedToReadFileFromTar, zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
ResponseError(c, "could not get next entry: "+err.Error(), fasthttp.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if isDir(obj.Name) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// set varying attributes
|
|
||||||
attributes = attributes[:len(commonAttributes)]
|
|
||||||
fileName := filepath.Base(obj.Name)
|
|
||||||
attributes = append(attributes, newAttribute(object.AttributeFilePath, obj.Name))
|
|
||||||
attributes = append(attributes, newAttribute(object.AttributeFileName, fileName))
|
|
||||||
|
|
||||||
idObj, err := h.uploadObject(c, bkt, attributes, tarReader)
|
|
||||||
if err != nil {
|
|
||||||
h.handlePutFrostFSErr(c, err, log)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Debug(logs.ObjectUploaded,
|
|
||||||
zap.String("oid", idObj.EncodeToString()),
|
|
||||||
zap.String("FileName", fileName),
|
|
||||||
logs.TagField(logs.TagExternalStorage),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) handlePutFrostFSErr(r *fasthttp.RequestCtx, err error, log *zap.Logger) {
|
|
||||||
statusCode, msg, additionalFields := formErrorResponse("could not store file in frostfs", err)
|
|
||||||
logFields := append([]zap.Field{zap.Error(err)}, additionalFields...)
|
|
||||||
|
|
||||||
log.Error(logs.CouldNotStoreFileInFrostfs, append(logFields, logs.TagField(logs.TagExternalStorage))...)
|
|
||||||
ResponseError(r, msg, statusCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) fetchBearerToken(ctx context.Context) *bearer.Token {
|
|
||||||
if tkn, err := tokens.LoadBearerToken(ctx); err == nil && tkn != nil {
|
|
||||||
return tkn
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
|
@ -1,142 +0,0 @@
|
||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/logs"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/tokens"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/bearer"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/client"
|
|
||||||
sdkstatus "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/client/status"
|
|
||||||
cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object"
|
|
||||||
oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
|
|
||||||
"github.com/valyala/fasthttp"
|
|
||||||
"go.uber.org/zap"
|
|
||||||
)
|
|
||||||
|
|
||||||
type request struct {
|
|
||||||
*fasthttp.RequestCtx
|
|
||||||
log *zap.Logger
|
|
||||||
}
|
|
||||||
|
|
||||||
func newRequest(ctx *fasthttp.RequestCtx, log *zap.Logger) request {
|
|
||||||
return request{
|
|
||||||
RequestCtx: ctx,
|
|
||||||
log: log,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *request) handleFrostFSErr(err error, start time.Time) {
|
|
||||||
logFields := []zap.Field{
|
|
||||||
zap.Stringer("elapsed", time.Since(start)),
|
|
||||||
zap.Error(err),
|
|
||||||
}
|
|
||||||
statusCode, msg, additionalFields := formErrorResponse("could not receive object", err)
|
|
||||||
logFields = append(logFields, additionalFields...)
|
|
||||||
|
|
||||||
r.log.Error(logs.CouldNotReceiveObject, append(logFields, logs.TagField(logs.TagExternalStorage))...)
|
|
||||||
ResponseError(r.RequestCtx, msg, statusCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
func bearerToken(ctx context.Context) *bearer.Token {
|
|
||||||
if tkn, err := tokens.LoadBearerToken(ctx); err == nil {
|
|
||||||
return tkn
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func isDir(name string) bool {
|
|
||||||
return name == "" || strings.HasSuffix(name, "/")
|
|
||||||
}
|
|
||||||
|
|
||||||
func loadAttributes(attrs []object.Attribute) map[string]string {
|
|
||||||
result := make(map[string]string)
|
|
||||||
for _, attr := range attrs {
|
|
||||||
result[attr.Key()] = attr.Value()
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
func isValidToken(s string) bool {
|
|
||||||
for _, c := range s {
|
|
||||||
if c <= ' ' || c > 127 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if strings.ContainsRune("()<>@,;:\\\"/[]?={}", c) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func isValidValue(s string) bool {
|
|
||||||
for _, c := range s {
|
|
||||||
// HTTP specification allows for more technically, but we don't want to escape things.
|
|
||||||
if c < ' ' || c > 127 || c == '"' {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func logAndSendBucketError(c *fasthttp.RequestCtx, log *zap.Logger, err error) {
|
|
||||||
log.Error(logs.CouldNotGetBucket, zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
|
|
||||||
if client.IsErrContainerNotFound(err) {
|
|
||||||
ResponseError(c, "Not Found", fasthttp.StatusNotFound)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ResponseError(c, "could not get bucket: "+err.Error(), fasthttp.StatusBadRequest)
|
|
||||||
}
|
|
||||||
|
|
||||||
func newAddress(cnr cid.ID, obj oid.ID) oid.Address {
|
|
||||||
var addr oid.Address
|
|
||||||
addr.SetContainer(cnr)
|
|
||||||
addr.SetObject(obj)
|
|
||||||
return addr
|
|
||||||
}
|
|
||||||
|
|
||||||
// setIfNotExist sets key value to map if key is not present yet.
|
|
||||||
func setIfNotExist(m map[string]string, key, value string) {
|
|
||||||
if _, ok := m[key]; !ok {
|
|
||||||
m[key] = value
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func ResponseError(r *fasthttp.RequestCtx, msg string, code int) {
|
|
||||||
r.Error(msg+"\n", code)
|
|
||||||
}
|
|
||||||
|
|
||||||
func formErrorResponse(message string, err error) (int, string, []zap.Field) {
|
|
||||||
var (
|
|
||||||
msg string
|
|
||||||
statusCode int
|
|
||||||
logFields []zap.Field
|
|
||||||
)
|
|
||||||
|
|
||||||
st := new(sdkstatus.ObjectAccessDenied)
|
|
||||||
|
|
||||||
switch {
|
|
||||||
case errors.As(err, &st):
|
|
||||||
statusCode = fasthttp.StatusForbidden
|
|
||||||
reason := st.Reason()
|
|
||||||
msg = fmt.Sprintf("%s: %v: %s", message, err, reason)
|
|
||||||
logFields = append(logFields, zap.String("error_detail", reason))
|
|
||||||
case errors.Is(err, ErrQuotaLimitReached):
|
|
||||||
statusCode = fasthttp.StatusConflict
|
|
||||||
msg = fmt.Sprintf("%s: %v", message, err)
|
|
||||||
case client.IsErrObjectNotFound(err) || client.IsErrContainerNotFound(err):
|
|
||||||
statusCode = fasthttp.StatusNotFound
|
|
||||||
msg = "Not Found"
|
|
||||||
default:
|
|
||||||
statusCode = fasthttp.StatusBadRequest
|
|
||||||
msg = fmt.Sprintf("%s: %v", message, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return statusCode, msg, logFields
|
|
||||||
}
|
|
|
@ -1,24 +0,0 @@
|
||||||
package layer
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/data"
|
|
||||||
cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TreeService provide interface to interact with tree service using s3 data models.
|
|
||||||
type TreeService interface {
|
|
||||||
GetLatestVersion(ctx context.Context, cnrID *cid.ID, objectName string) (*data.NodeVersion, error)
|
|
||||||
GetSubTreeByPrefix(ctx context.Context, bktInfo *data.BucketInfo, prefix string, latestOnly bool) ([]data.NodeInfo, string, error)
|
|
||||||
CheckSettingsNodeExists(ctx context.Context, bktInfo *data.BucketInfo) error
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
// ErrNodeNotFound is returned from Tree service in case of not found error.
|
|
||||||
ErrNodeNotFound = errors.New("not found")
|
|
||||||
|
|
||||||
// ErrNodeAccessDenied is returned from Tree service in case of access denied error.
|
|
||||||
ErrNodeAccessDenied = errors.New("access denied")
|
|
||||||
)
|
|
|
@ -1,131 +0,0 @@
|
||||||
package logs
|
|
||||||
|
|
||||||
import "go.uber.org/zap"
|
|
||||||
|
|
||||||
const (
|
|
||||||
TagFieldName = "tag"
|
|
||||||
|
|
||||||
TagApp = "app"
|
|
||||||
TagDatapath = "datapath"
|
|
||||||
TagExternalStorage = "external_storage"
|
|
||||||
TagExternalStorageTree = "external_storage_tree"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TagField(tag string) zap.Field {
|
|
||||||
return zap.String(TagFieldName, tag)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Log messages with the "app" tag.
|
|
||||||
const (
|
|
||||||
ServiceIsRunning = "service is running"
|
|
||||||
ServiceCouldntStartOnConfiguredPort = "service couldn't start on configured port"
|
|
||||||
ServiceHasntStartedSinceItsDisabled = "service hasn't started since it's disabled"
|
|
||||||
ShuttingDownService = "shutting down service"
|
|
||||||
CantShutDownService = "can't shut down service"
|
|
||||||
CantGracefullyShutDownService = "can't gracefully shut down service, force stop"
|
|
||||||
FailedToCreateResolver = "failed to create resolver"
|
|
||||||
FailedToCreateWorkerPool = "failed to create worker pool"
|
|
||||||
StartingApplication = "starting application"
|
|
||||||
StartingServer = "starting server"
|
|
||||||
ListenAndServe = "listen and serve"
|
|
||||||
ShuttingDownWebServer = "shutting down web server"
|
|
||||||
FailedToShutdownTracing = "failed to shutdown tracing"
|
|
||||||
AddedPathUploadCid = "added path /upload/{cid}"
|
|
||||||
AddedPathGetCidOid = "added path /get/{cid}/{oid}"
|
|
||||||
AddedPathGetByAttributeCidAttrKeyAttrVal = "added path /get_by_attribute/{cid}/{attr_key}/{attr_val:*}"
|
|
||||||
AddedPathZipCidPrefix = "added path /zip/{cid}/{prefix}"
|
|
||||||
FailedToAddServer = "failed to add server"
|
|
||||||
AddServer = "add server"
|
|
||||||
NoHealthyServers = "no healthy servers"
|
|
||||||
FailedToInitializeTracing = "failed to initialize tracing"
|
|
||||||
RuntimeSoftMemoryDefinedWithGOMEMLIMIT = "soft runtime memory defined with GOMEMLIMIT environment variable, config value skipped"
|
|
||||||
RuntimeSoftMemoryLimitUpdated = "soft runtime memory limit value updated"
|
|
||||||
CouldNotLoadFrostFSPrivateKey = "could not load FrostFS private key"
|
|
||||||
UsingCredentials = "using credentials"
|
|
||||||
FailedToCreateConnectionPool = "failed to create connection pool"
|
|
||||||
FailedToDialConnectionPool = "failed to dial connection pool"
|
|
||||||
FailedToCreateTreePool = "failed to create tree pool"
|
|
||||||
FailedToDialTreePool = "failed to dial tree pool"
|
|
||||||
ServerReconnecting = "reconnecting server..."
|
|
||||||
ServerReconnectedSuccessfully = "server reconnected successfully"
|
|
||||||
ServerReconnectFailed = "failed to reconnect server"
|
|
||||||
MultinetDialSuccess = "multinet dial successful"
|
|
||||||
MultinetDialFail = "multinet dial failed"
|
|
||||||
ContainerResolverWillBeDisabledBecauseOfResolversResolverOrderIsEmpty = "container resolver will be disabled because of resolvers 'resolver_order' is empty"
|
|
||||||
MetricsAreDisabled = "metrics are disabled"
|
|
||||||
NoWalletPathSpecifiedCreatingEphemeralKeyAutomaticallyForThisRun = "no wallet path specified, creating ephemeral key automatically for this run"
|
|
||||||
SIGHUPConfigReloadStarted = "SIGHUP config reload started"
|
|
||||||
FailedToReloadConfigBecauseItsMissed = "failed to reload config because it's missed"
|
|
||||||
FailedToReloadConfig = "failed to reload config"
|
|
||||||
FailedToUpdateResolvers = "failed to update resolvers"
|
|
||||||
FailedToReloadServerParameters = "failed to reload server parameters"
|
|
||||||
SIGHUPConfigReloadCompleted = "SIGHUP config reload completed"
|
|
||||||
TracingConfigUpdated = "tracing config updated"
|
|
||||||
ResolverNNSWontBeUsedSinceRPCEndpointIsntProvided = "resolver nns won't be used since rpc_endpoint isn't provided"
|
|
||||||
AddedStoragePeer = "added storage peer"
|
|
||||||
InvalidLifetimeUsingDefaultValue = "invalid lifetime, using default value (in seconds)"
|
|
||||||
InvalidCacheSizeUsingDefaultValue = "invalid cache size, using default value"
|
|
||||||
WarnDuplicateAddress = "duplicate address"
|
|
||||||
FailedToLoadMultinetConfig = "failed to load multinet config"
|
|
||||||
MultinetConfigWontBeUpdated = "multinet config won't be updated"
|
|
||||||
LogLevelWontBeUpdated = "log level won't be updated"
|
|
||||||
TagsLogConfigWontBeUpdated = "tags log config won't be updated"
|
|
||||||
FailedToReadIndexPageTemplate = "failed to read index page template"
|
|
||||||
SetCustomIndexPageTemplate = "set custom index page template"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Log messages with the "datapath" tag.
|
|
||||||
const (
|
|
||||||
CouldntParseCreationDate = "couldn't parse creation date"
|
|
||||||
CouldNotDetectContentTypeFromPayload = "could not detect Content-Type from payload"
|
|
||||||
FailedToAddObjectToArchive = "failed to add object to archive"
|
|
||||||
CloseZipWriter = "close zip writer"
|
|
||||||
IgnorePartEmptyFormName = "ignore part, empty form name"
|
|
||||||
IgnorePartEmptyFilename = "ignore part, empty filename"
|
|
||||||
CouldNotParseClientTime = "could not parse client time"
|
|
||||||
CouldNotPrepareExpirationHeader = "could not prepare expiration header"
|
|
||||||
CouldNotEncodeResponse = "could not encode response"
|
|
||||||
AddAttributeToResultObject = "add attribute to result object"
|
|
||||||
Request = "request"
|
|
||||||
CouldNotFetchAndStoreBearerToken = "could not fetch and store bearer token"
|
|
||||||
CouldntPutBucketIntoCache = "couldn't put bucket info into cache"
|
|
||||||
FailedToIterateOverResponse = "failed to iterate over search response"
|
|
||||||
InvalidCacheEntryType = "invalid cache entry type"
|
|
||||||
FailedToUnescapeQuery = "failed to unescape query"
|
|
||||||
CouldntCacheNetmap = "couldn't cache netmap"
|
|
||||||
FailedToCloseReader = "failed to close reader"
|
|
||||||
FailedToFilterHeaders = "failed to filter headers"
|
|
||||||
FailedToReadFileFromTar = "failed to read file from tar"
|
|
||||||
FailedToGetAttributes = "failed to get attributes"
|
|
||||||
CloseGzipWriter = "close gzip writer"
|
|
||||||
CloseTarWriter = "close tar writer"
|
|
||||||
FailedToCreateGzipReader = "failed to create gzip reader"
|
|
||||||
GzipReaderSelected = "gzip reader selected"
|
|
||||||
CouldNotReceiveMultipartForm = "could not receive multipart/form"
|
|
||||||
ObjectsNotFound = "objects not found"
|
|
||||||
IteratingOverSelectedObjectsFailed = "iterating over selected objects failed"
|
|
||||||
CouldNotGetBucket = "could not get bucket"
|
|
||||||
CouldNotResolveContainerID = "could not resolve container id"
|
|
||||||
FailedToSumbitTaskToPool = "failed to submit task to pool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Log messages with the "external_storage" tag.
|
|
||||||
const (
|
|
||||||
CouldNotReceiveObject = "could not receive object"
|
|
||||||
CouldNotSearchForObjects = "could not search for objects"
|
|
||||||
ObjectNotFound = "object not found"
|
|
||||||
ReadObjectListFailed = "read object list failed"
|
|
||||||
CouldNotStoreFileInFrostfs = "could not store file in frostfs"
|
|
||||||
FailedToHeadObject = "failed to head object"
|
|
||||||
ObjectNotFoundByFilePathTrySearchByFileName = "object not found by filePath attribute, try search by fileName"
|
|
||||||
FailedToGetObject = "failed to get object"
|
|
||||||
ObjectUploaded = "object uploaded"
|
|
||||||
CouldNotGetContainerInfo = "could not get container info"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Log messages with the "external_storage_tree" tag.
|
|
||||||
const (
|
|
||||||
ObjectWasDeleted = "object was deleted"
|
|
||||||
FailedToGetLatestVersionOfObject = "failed to get latest version of object"
|
|
||||||
FailedToCheckIfSettingsNodeExist = "Failed to check if settings node exists"
|
|
||||||
)
|
|
|
@ -1,68 +0,0 @@
|
||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"net/netip"
|
|
||||||
"slices"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/multinet"
|
|
||||||
)
|
|
||||||
|
|
||||||
var errEmptySourceIPList = errors.New("empty source IP list")
|
|
||||||
|
|
||||||
type Subnet struct {
|
|
||||||
Prefix string
|
|
||||||
SourceIPs []string
|
|
||||||
}
|
|
||||||
|
|
||||||
type Config struct {
|
|
||||||
Enabled bool
|
|
||||||
Subnets []Subnet
|
|
||||||
Balancer string
|
|
||||||
Restrict bool
|
|
||||||
FallbackDelay time.Duration
|
|
||||||
EventHandler multinet.EventHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c Config) toMultinetConfig() (multinet.Config, error) {
|
|
||||||
var subnets []multinet.Subnet
|
|
||||||
for _, s := range c.Subnets {
|
|
||||||
var ms multinet.Subnet
|
|
||||||
p, err := netip.ParsePrefix(s.Prefix)
|
|
||||||
if err != nil {
|
|
||||||
return multinet.Config{}, fmt.Errorf("parse IP prefix '%s': %w", s.Prefix, err)
|
|
||||||
}
|
|
||||||
ms.Prefix = p
|
|
||||||
for _, ip := range s.SourceIPs {
|
|
||||||
addr, err := netip.ParseAddr(ip)
|
|
||||||
if err != nil {
|
|
||||||
return multinet.Config{}, fmt.Errorf("parse IP address '%s': %w", ip, err)
|
|
||||||
}
|
|
||||||
ms.SourceIPs = append(ms.SourceIPs, addr)
|
|
||||||
}
|
|
||||||
if len(ms.SourceIPs) == 0 {
|
|
||||||
return multinet.Config{}, errEmptySourceIPList
|
|
||||||
}
|
|
||||||
subnets = append(subnets, ms)
|
|
||||||
}
|
|
||||||
return multinet.Config{
|
|
||||||
Subnets: subnets,
|
|
||||||
Balancer: multinet.BalancerType(c.Balancer),
|
|
||||||
Restrict: c.Restrict,
|
|
||||||
FallbackDelay: c.FallbackDelay,
|
|
||||||
Dialer: newDefaultDialer(),
|
|
||||||
EventHandler: c.EventHandler,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c Config) equals(other Config) bool {
|
|
||||||
return c.Enabled == other.Enabled &&
|
|
||||||
slices.EqualFunc(c.Subnets, other.Subnets, func(lhs, rhs Subnet) bool {
|
|
||||||
return lhs.Prefix == rhs.Prefix && slices.Equal(lhs.SourceIPs, rhs.SourceIPs)
|
|
||||||
}) &&
|
|
||||||
c.Balancer == other.Balancer &&
|
|
||||||
c.Restrict == other.Restrict &&
|
|
||||||
c.FallbackDelay == other.FallbackDelay
|
|
||||||
}
|
|
|
@ -1,54 +0,0 @@
|
||||||
// NOTE: code is taken from https://github.com/grpc/grpc-go/blob/v1.68.x/internal/transport/http_util.go
|
|
||||||
|
|
||||||
/*
|
|
||||||
*
|
|
||||||
* Copyright 2014 gRPC authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
|
|
||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/url"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// parseDialTarget returns the network and address to pass to dialer.
|
|
||||||
func parseDialTarget(target string) (string, string) {
|
|
||||||
net := "tcp"
|
|
||||||
m1 := strings.Index(target, ":")
|
|
||||||
m2 := strings.Index(target, ":/")
|
|
||||||
// handle unix:addr which will fail with url.Parse
|
|
||||||
if m1 >= 0 && m2 < 0 {
|
|
||||||
if n := target[0:m1]; n == "unix" {
|
|
||||||
return n, target[m1+1:]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if m2 >= 0 {
|
|
||||||
t, err := url.Parse(target)
|
|
||||||
if err != nil {
|
|
||||||
return net, target
|
|
||||||
}
|
|
||||||
scheme := t.Scheme
|
|
||||||
addr := t.Path
|
|
||||||
if scheme == "unix" {
|
|
||||||
if addr == "" {
|
|
||||||
addr = t.Host
|
|
||||||
}
|
|
||||||
return scheme, addr
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return net, target
|
|
||||||
}
|
|
|
@ -1,36 +0,0 @@
|
||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"syscall"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"golang.org/x/sys/unix"
|
|
||||||
)
|
|
||||||
|
|
||||||
func newDefaultDialer() net.Dialer {
|
|
||||||
// From `grpc.WithContextDialer` comment:
|
|
||||||
//
|
|
||||||
// Note: All supported releases of Go (as of December 2023) override the OS
|
|
||||||
// defaults for TCP keepalive time and interval to 15s. To enable TCP keepalive
|
|
||||||
// with OS defaults for keepalive time and interval, use a net.Dialer that sets
|
|
||||||
// the KeepAlive field to a negative value, and sets the SO_KEEPALIVE socket
|
|
||||||
// option to true from the Control field. For a concrete example of how to do
|
|
||||||
// this, see internal.NetDialerWithTCPKeepalive().
|
|
||||||
//
|
|
||||||
// https://github.com/grpc/grpc-go/blob/830135e6c5a351abf75f0c9cfdf978e5df8daeba/dialoptions.go#L432
|
|
||||||
//
|
|
||||||
// From `internal.NetDialerWithTCPKeepalive` comment:
|
|
||||||
//
|
|
||||||
// TODO: Once https://github.com/golang/go/issues/62254 lands, and the
|
|
||||||
// appropriate Go version becomes less than our least supported Go version, we
|
|
||||||
// should look into using the new API to make things more straightforward.
|
|
||||||
return net.Dialer{
|
|
||||||
KeepAlive: time.Duration(-1),
|
|
||||||
Control: func(_, _ string, c syscall.RawConn) error {
|
|
||||||
return c.Control(func(fd uintptr) {
|
|
||||||
_ = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_KEEPALIVE, 1)
|
|
||||||
})
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,69 +0,0 @@
|
||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/multinet"
|
|
||||||
)
|
|
||||||
|
|
||||||
type DialerSource struct {
|
|
||||||
guard sync.RWMutex
|
|
||||||
|
|
||||||
c Config
|
|
||||||
|
|
||||||
md multinet.Dialer
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDialerSource(c Config) (*DialerSource, error) {
|
|
||||||
result := &DialerSource{}
|
|
||||||
if err := result.build(c); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *DialerSource) build(c Config) error {
|
|
||||||
if c.Enabled {
|
|
||||||
mc, err := c.toMultinetConfig()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
md, err := multinet.NewDialer(mc)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
s.md = md
|
|
||||||
s.c = c
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
s.md = nil
|
|
||||||
s.c = c
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GrpcContextDialer returns grpc.WithContextDialer func.
|
|
||||||
// Returns nil if multinet disabled.
|
|
||||||
func (s *DialerSource) GrpcContextDialer() func(context.Context, string) (net.Conn, error) {
|
|
||||||
s.guard.RLock()
|
|
||||||
defer s.guard.RUnlock()
|
|
||||||
|
|
||||||
if s.c.Enabled {
|
|
||||||
return func(ctx context.Context, address string) (net.Conn, error) {
|
|
||||||
network, address := parseDialTarget(address)
|
|
||||||
return s.md.DialContext(ctx, network, address)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *DialerSource) Update(c Config) error {
|
|
||||||
s.guard.Lock()
|
|
||||||
defer s.guard.Unlock()
|
|
||||||
|
|
||||||
if s.c.equals(c) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return s.build(c)
|
|
||||||
}
|
|
|
@ -1,30 +0,0 @@
|
||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/logs"
|
|
||||||
"go.uber.org/zap"
|
|
||||||
)
|
|
||||||
|
|
||||||
type LogEventHandler struct {
|
|
||||||
logger *zap.Logger
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l LogEventHandler) DialPerformed(sourceIP net.Addr, _, address string, err error) {
|
|
||||||
sourceIPString := "undefined"
|
|
||||||
if sourceIP != nil {
|
|
||||||
sourceIPString = sourceIP.Network() + "://" + sourceIP.String()
|
|
||||||
}
|
|
||||||
if err == nil {
|
|
||||||
l.logger.Debug(logs.MultinetDialSuccess, zap.String("source", sourceIPString),
|
|
||||||
zap.String("destination", address), logs.TagField(logs.TagApp))
|
|
||||||
} else {
|
|
||||||
l.logger.Debug(logs.MultinetDialFail, zap.String("source", sourceIPString),
|
|
||||||
zap.String("destination", address), logs.TagField(logs.TagApp))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewLogEventHandler(logger *zap.Logger) LogEventHandler {
|
|
||||||
return LogEventHandler{logger: logger}
|
|
||||||
}
|
|
|
@ -1,287 +0,0 @@
|
||||||
package frostfs
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/handler"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/utils"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-observability/tracing"
|
|
||||||
apistatus "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/client/status"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/netmap"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object"
|
|
||||||
oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/pool"
|
|
||||||
"google.golang.org/grpc/codes"
|
|
||||||
"google.golang.org/grpc/status"
|
|
||||||
)
|
|
||||||
|
|
||||||
// FrostFS represents virtual connection to the FrostFS network.
|
|
||||||
// It is used to provide an interface to dependent packages
|
|
||||||
// which work with FrostFS.
|
|
||||||
type FrostFS struct {
|
|
||||||
pool *pool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewFrostFS creates new FrostFS using provided pool.Pool.
|
|
||||||
func NewFrostFS(p *pool.Pool) *FrostFS {
|
|
||||||
return &FrostFS{
|
|
||||||
pool: p,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Container implements frostfs.FrostFS interface method.
|
|
||||||
func (x *FrostFS) Container(ctx context.Context, containerPrm handler.PrmContainer) (*container.Container, error) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(ctx, "frostfs.Container")
|
|
||||||
defer span.End()
|
|
||||||
|
|
||||||
prm := pool.PrmContainerGet{
|
|
||||||
ContainerID: containerPrm.ContainerID,
|
|
||||||
}
|
|
||||||
|
|
||||||
res, err := x.pool.GetContainer(ctx, prm)
|
|
||||||
if err != nil {
|
|
||||||
return nil, handleObjectError("read container via connection pool", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &res, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateObject implements frostfs.FrostFS interface method.
|
|
||||||
func (x *FrostFS) CreateObject(ctx context.Context, prm handler.PrmObjectCreate) (oid.ID, error) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(ctx, "frostfs.CreateObject")
|
|
||||||
defer span.End()
|
|
||||||
|
|
||||||
var prmPut pool.PrmObjectPut
|
|
||||||
prmPut.SetHeader(*prm.Object)
|
|
||||||
prmPut.SetPayload(prm.Payload)
|
|
||||||
prmPut.SetClientCut(prm.ClientCut)
|
|
||||||
prmPut.WithoutHomomorphicHash(prm.WithoutHomomorphicHash)
|
|
||||||
prmPut.SetBufferMaxSize(prm.BufferMaxSize)
|
|
||||||
|
|
||||||
if prm.BearerToken != nil {
|
|
||||||
prmPut.UseBearer(*prm.BearerToken)
|
|
||||||
}
|
|
||||||
|
|
||||||
idObj, err := x.pool.PutObject(ctx, prmPut)
|
|
||||||
if err != nil {
|
|
||||||
return oid.ID{}, handleObjectError("save object via connection pool", err)
|
|
||||||
}
|
|
||||||
return idObj.ObjectID, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// wraps io.ReadCloser and transforms Read errors related to access violation
|
|
||||||
// to frostfs.ErrAccessDenied.
|
|
||||||
type payloadReader struct {
|
|
||||||
io.ReadCloser
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x payloadReader) Read(p []byte) (int, error) {
|
|
||||||
n, err := x.ReadCloser.Read(p)
|
|
||||||
if err != nil && errors.Is(err, io.EOF) {
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
return n, handleObjectError("read payload", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// HeadObject implements frostfs.FrostFS interface method.
|
|
||||||
func (x *FrostFS) HeadObject(ctx context.Context, prm handler.PrmObjectHead) (*object.Object, error) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(ctx, "frostfs.HeadObject")
|
|
||||||
defer span.End()
|
|
||||||
|
|
||||||
var prmHead pool.PrmObjectHead
|
|
||||||
prmHead.SetAddress(prm.Address)
|
|
||||||
|
|
||||||
if prm.BearerToken != nil {
|
|
||||||
prmHead.UseBearer(*prm.BearerToken)
|
|
||||||
}
|
|
||||||
|
|
||||||
res, err := x.pool.HeadObject(ctx, prmHead)
|
|
||||||
if err != nil {
|
|
||||||
return nil, handleObjectError("read object header via connection pool", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &res, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetObject implements frostfs.FrostFS interface method.
|
|
||||||
func (x *FrostFS) GetObject(ctx context.Context, prm handler.PrmObjectGet) (*handler.Object, error) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(ctx, "frostfs.GetObject")
|
|
||||||
defer span.End()
|
|
||||||
|
|
||||||
var prmGet pool.PrmObjectGet
|
|
||||||
prmGet.SetAddress(prm.Address)
|
|
||||||
|
|
||||||
if prm.BearerToken != nil {
|
|
||||||
prmGet.UseBearer(*prm.BearerToken)
|
|
||||||
}
|
|
||||||
|
|
||||||
res, err := x.pool.GetObject(ctx, prmGet)
|
|
||||||
if err != nil {
|
|
||||||
return nil, handleObjectError("init full object reading via connection pool", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &handler.Object{
|
|
||||||
Header: res.Header,
|
|
||||||
Payload: res.Payload,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// RangeObject implements frostfs.FrostFS interface method.
|
|
||||||
func (x *FrostFS) RangeObject(ctx context.Context, prm handler.PrmObjectRange) (io.ReadCloser, error) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(ctx, "frostfs.RangeObject")
|
|
||||||
defer span.End()
|
|
||||||
|
|
||||||
var prmRange pool.PrmObjectRange
|
|
||||||
prmRange.SetAddress(prm.Address)
|
|
||||||
prmRange.SetOffset(prm.PayloadRange[0])
|
|
||||||
prmRange.SetLength(prm.PayloadRange[1])
|
|
||||||
|
|
||||||
if prm.BearerToken != nil {
|
|
||||||
prmRange.UseBearer(*prm.BearerToken)
|
|
||||||
}
|
|
||||||
|
|
||||||
res, err := x.pool.ObjectRange(ctx, prmRange)
|
|
||||||
if err != nil {
|
|
||||||
return nil, handleObjectError("init payload range reading via connection pool", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return payloadReader{&res}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SearchObjects implements frostfs.FrostFS interface method.
|
|
||||||
func (x *FrostFS) SearchObjects(ctx context.Context, prm handler.PrmObjectSearch) (handler.ResObjectSearch, error) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(ctx, "frostfs.SearchObjects")
|
|
||||||
defer span.End()
|
|
||||||
|
|
||||||
var prmSearch pool.PrmObjectSearch
|
|
||||||
prmSearch.SetContainerID(prm.Container)
|
|
||||||
prmSearch.SetFilters(prm.Filters)
|
|
||||||
|
|
||||||
if prm.BearerToken != nil {
|
|
||||||
prmSearch.UseBearer(*prm.BearerToken)
|
|
||||||
}
|
|
||||||
|
|
||||||
res, err := x.pool.SearchObjects(ctx, prmSearch)
|
|
||||||
if err != nil {
|
|
||||||
return nil, handleObjectError("init object search via connection pool", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &res, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetEpochDurations implements frostfs.FrostFS interface method.
|
|
||||||
func (x *FrostFS) GetEpochDurations(ctx context.Context) (*utils.EpochDurations, error) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(ctx, "frostfs.GetEpochDurations")
|
|
||||||
defer span.End()
|
|
||||||
|
|
||||||
networkInfo, err := x.pool.NetworkInfo(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
res := &utils.EpochDurations{
|
|
||||||
CurrentEpoch: networkInfo.CurrentEpoch(),
|
|
||||||
MsPerBlock: networkInfo.MsPerBlock(),
|
|
||||||
BlockPerEpoch: networkInfo.EpochDuration(),
|
|
||||||
}
|
|
||||||
|
|
||||||
if res.BlockPerEpoch == 0 {
|
|
||||||
return nil, fmt.Errorf("EpochDuration is empty")
|
|
||||||
}
|
|
||||||
return res, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *FrostFS) NetmapSnapshot(ctx context.Context) (netmap.NetMap, error) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(ctx, "frostfs.NetmapSnapshot")
|
|
||||||
defer span.End()
|
|
||||||
|
|
||||||
netmapSnapshot, err := x.pool.NetMapSnapshot(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return netmapSnapshot, handleObjectError("get netmap via connection pool", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return netmapSnapshot, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ResolverFrostFS represents virtual connection to the FrostFS network.
|
|
||||||
// It implements resolver.FrostFS.
|
|
||||||
type ResolverFrostFS struct {
|
|
||||||
pool *pool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewResolverFrostFS creates new ResolverFrostFS using provided pool.Pool.
|
|
||||||
func NewResolverFrostFS(p *pool.Pool) *ResolverFrostFS {
|
|
||||||
return &ResolverFrostFS{pool: p}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SystemDNS implements resolver.FrostFS interface method.
|
|
||||||
func (x *ResolverFrostFS) SystemDNS(ctx context.Context) (string, error) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(ctx, "frostfs.SystemDNS")
|
|
||||||
defer span.End()
|
|
||||||
|
|
||||||
networkInfo, err := x.pool.NetworkInfo(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return "", handleObjectError("read network info via client", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
domain := networkInfo.RawNetworkParameter("SystemDNS")
|
|
||||||
if domain == nil {
|
|
||||||
return "", errors.New("system DNS parameter not found or empty")
|
|
||||||
}
|
|
||||||
|
|
||||||
return string(domain), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func handleObjectError(msg string, err error) error {
|
|
||||||
if err == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if reason, ok := IsErrObjectAccessDenied(err); ok {
|
|
||||||
if strings.Contains(reason, "limit reached") {
|
|
||||||
return fmt.Errorf("%s: %w: %s", msg, handler.ErrQuotaLimitReached, reason)
|
|
||||||
}
|
|
||||||
|
|
||||||
return fmt.Errorf("%s: %w: %s", msg, handler.ErrAccessDenied, reason)
|
|
||||||
}
|
|
||||||
|
|
||||||
if IsTimeoutError(err) {
|
|
||||||
return fmt.Errorf("%s: %w: %s", msg, handler.ErrGatewayTimeout, err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
return fmt.Errorf("%s: %w", msg, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func UnwrapErr(err error) error {
|
|
||||||
unwrappedErr := errors.Unwrap(err)
|
|
||||||
for unwrappedErr != nil {
|
|
||||||
err = unwrappedErr
|
|
||||||
unwrappedErr = errors.Unwrap(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func IsErrObjectAccessDenied(err error) (string, bool) {
|
|
||||||
err = UnwrapErr(err)
|
|
||||||
switch err := err.(type) {
|
|
||||||
default:
|
|
||||||
return "", false
|
|
||||||
case *apistatus.ObjectAccessDenied:
|
|
||||||
return err.Reason(), true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func IsTimeoutError(err error) bool {
|
|
||||||
if strings.Contains(err.Error(), "timeout") ||
|
|
||||||
errors.Is(err, context.DeadlineExceeded) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
return status.Code(UnwrapErr(err)) == codes.DeadlineExceeded
|
|
||||||
}
|
|
|
@ -1,83 +0,0 @@
|
||||||
package frostfs
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/handler"
|
|
||||||
apistatus "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/client/status"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
"google.golang.org/grpc/codes"
|
|
||||||
"google.golang.org/grpc/status"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestHandleObjectError(t *testing.T) {
|
|
||||||
msg := "some msg"
|
|
||||||
|
|
||||||
t.Run("nil error", func(t *testing.T) {
|
|
||||||
err := handleObjectError(msg, nil)
|
|
||||||
require.Nil(t, err)
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("simple access denied", func(t *testing.T) {
|
|
||||||
reason := "some reason"
|
|
||||||
inputErr := new(apistatus.ObjectAccessDenied)
|
|
||||||
inputErr.WriteReason(reason)
|
|
||||||
|
|
||||||
err := handleObjectError(msg, inputErr)
|
|
||||||
require.ErrorIs(t, err, handler.ErrAccessDenied)
|
|
||||||
require.Contains(t, err.Error(), reason)
|
|
||||||
require.Contains(t, err.Error(), msg)
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("access denied - quota reached", func(t *testing.T) {
|
|
||||||
reason := "Quota limit reached"
|
|
||||||
inputErr := new(apistatus.ObjectAccessDenied)
|
|
||||||
inputErr.WriteReason(reason)
|
|
||||||
|
|
||||||
err := handleObjectError(msg, inputErr)
|
|
||||||
require.ErrorIs(t, err, handler.ErrQuotaLimitReached)
|
|
||||||
require.Contains(t, err.Error(), reason)
|
|
||||||
require.Contains(t, err.Error(), msg)
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("simple timeout", func(t *testing.T) {
|
|
||||||
inputErr := errors.New("timeout")
|
|
||||||
|
|
||||||
err := handleObjectError(msg, inputErr)
|
|
||||||
require.ErrorIs(t, err, handler.ErrGatewayTimeout)
|
|
||||||
require.Contains(t, err.Error(), inputErr.Error())
|
|
||||||
require.Contains(t, err.Error(), msg)
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("deadline exceeded", func(t *testing.T) {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
|
|
||||||
defer cancel()
|
|
||||||
<-ctx.Done()
|
|
||||||
|
|
||||||
err := handleObjectError(msg, ctx.Err())
|
|
||||||
require.ErrorIs(t, err, handler.ErrGatewayTimeout)
|
|
||||||
require.Contains(t, err.Error(), ctx.Err().Error())
|
|
||||||
require.Contains(t, err.Error(), msg)
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("grpc deadline exceeded", func(t *testing.T) {
|
|
||||||
inputErr := fmt.Errorf("wrap grpc error: %w", status.Error(codes.DeadlineExceeded, "error"))
|
|
||||||
|
|
||||||
err := handleObjectError(msg, inputErr)
|
|
||||||
require.ErrorIs(t, err, handler.ErrGatewayTimeout)
|
|
||||||
require.Contains(t, err.Error(), inputErr.Error())
|
|
||||||
require.Contains(t, err.Error(), msg)
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("unknown error", func(t *testing.T) {
|
|
||||||
inputErr := errors.New("unknown error")
|
|
||||||
|
|
||||||
err := handleObjectError(msg, inputErr)
|
|
||||||
require.ErrorIs(t, err, inputErr)
|
|
||||||
require.Contains(t, err.Error(), msg)
|
|
||||||
})
|
|
||||||
}
|
|
|
@ -1,248 +0,0 @@
|
||||||
package frostfs
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/handler"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-observability/tracing"
|
|
||||||
oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
|
|
||||||
)
|
|
||||||
|
|
||||||
// PartInfo is upload information about part.
|
|
||||||
type PartInfo struct {
|
|
||||||
Key string `json:"key"`
|
|
||||||
UploadID string `json:"uploadId"`
|
|
||||||
Number int `json:"number"`
|
|
||||||
OID oid.ID `json:"oid"`
|
|
||||||
Size uint64 `json:"size"`
|
|
||||||
ETag string `json:"etag"`
|
|
||||||
MD5 string `json:"md5"`
|
|
||||||
Created time.Time `json:"created"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetFrostFSParams struct {
|
|
||||||
// payload range
|
|
||||||
Off, Ln uint64
|
|
||||||
Addr oid.Address
|
|
||||||
}
|
|
||||||
|
|
||||||
type PartObj struct {
|
|
||||||
OID oid.ID
|
|
||||||
Size uint64
|
|
||||||
}
|
|
||||||
|
|
||||||
type readerInitiator interface {
|
|
||||||
InitFrostFSObjectPayloadReader(ctx context.Context, p GetFrostFSParams) (io.ReadCloser, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
// MultiObjectReader implements io.Reader of payloads of the object list stored in the FrostFS network.
|
|
||||||
type MultiObjectReader struct {
|
|
||||||
ctx context.Context
|
|
||||||
|
|
||||||
layer readerInitiator
|
|
||||||
|
|
||||||
startPartOffset uint64
|
|
||||||
endPartLength uint64
|
|
||||||
|
|
||||||
prm GetFrostFSParams
|
|
||||||
|
|
||||||
curIndex int
|
|
||||||
curReader io.ReadCloser
|
|
||||||
|
|
||||||
parts []PartObj
|
|
||||||
}
|
|
||||||
|
|
||||||
type MultiObjectReaderConfig struct {
|
|
||||||
Initiator readerInitiator
|
|
||||||
|
|
||||||
// the offset of complete object and total size to read
|
|
||||||
Off, Ln uint64
|
|
||||||
|
|
||||||
Addr oid.Address
|
|
||||||
Parts []PartObj
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
errOffsetIsOutOfRange = errors.New("offset is out of payload range")
|
|
||||||
errLengthIsOutOfRange = errors.New("length is out of payload range")
|
|
||||||
errEmptyPartsList = errors.New("empty parts list")
|
|
||||||
errorZeroRangeLength = errors.New("zero range length")
|
|
||||||
)
|
|
||||||
|
|
||||||
func (x *FrostFS) InitMultiObjectReader(ctx context.Context, p handler.PrmInitMultiObjectReader) (io.Reader, error) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(ctx, "frostfs.InitMultiObjectReader")
|
|
||||||
defer span.End()
|
|
||||||
|
|
||||||
combinedObj, err := x.GetObject(ctx, handler.PrmObjectGet{
|
|
||||||
PrmAuth: handler.PrmAuth{BearerToken: p.Bearer},
|
|
||||||
Address: p.Addr,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("get combined object '%s': %w", p.Addr.Object().EncodeToString(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var parts []*PartInfo
|
|
||||||
if err = json.NewDecoder(combinedObj.Payload).Decode(&parts); err != nil {
|
|
||||||
return nil, fmt.Errorf("unmarshal combined object parts: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
objParts := make([]PartObj, len(parts))
|
|
||||||
for i, part := range parts {
|
|
||||||
objParts[i] = PartObj{
|
|
||||||
OID: part.OID,
|
|
||||||
Size: part.Size,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return NewMultiObjectReader(ctx, MultiObjectReaderConfig{
|
|
||||||
Initiator: x,
|
|
||||||
Off: p.Off,
|
|
||||||
Ln: p.Ln,
|
|
||||||
Parts: objParts,
|
|
||||||
Addr: p.Addr,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewMultiObjectReader(ctx context.Context, cfg MultiObjectReaderConfig) (*MultiObjectReader, error) {
|
|
||||||
if len(cfg.Parts) == 0 {
|
|
||||||
return nil, errEmptyPartsList
|
|
||||||
}
|
|
||||||
|
|
||||||
r := &MultiObjectReader{
|
|
||||||
ctx: ctx,
|
|
||||||
layer: cfg.Initiator,
|
|
||||||
prm: GetFrostFSParams{
|
|
||||||
Addr: cfg.Addr,
|
|
||||||
},
|
|
||||||
parts: cfg.Parts,
|
|
||||||
}
|
|
||||||
|
|
||||||
if cfg.Off+cfg.Ln == 0 {
|
|
||||||
return r, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if cfg.Off > 0 && cfg.Ln == 0 {
|
|
||||||
return nil, errorZeroRangeLength
|
|
||||||
}
|
|
||||||
|
|
||||||
startPartIndex, startPartOffset := findStartPart(cfg)
|
|
||||||
if startPartIndex == -1 {
|
|
||||||
return nil, errOffsetIsOutOfRange
|
|
||||||
}
|
|
||||||
r.startPartOffset = startPartOffset
|
|
||||||
|
|
||||||
endPartIndex, endPartLength := findEndPart(cfg)
|
|
||||||
if endPartIndex == -1 {
|
|
||||||
return nil, errLengthIsOutOfRange
|
|
||||||
}
|
|
||||||
r.endPartLength = endPartLength
|
|
||||||
|
|
||||||
r.parts = cfg.Parts[startPartIndex : endPartIndex+1]
|
|
||||||
|
|
||||||
return r, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func findStartPart(cfg MultiObjectReaderConfig) (index int, offset uint64) {
|
|
||||||
position := cfg.Off
|
|
||||||
for i, part := range cfg.Parts {
|
|
||||||
// Strict inequality when searching for start position to avoid reading zero length part.
|
|
||||||
if position < part.Size {
|
|
||||||
return i, position
|
|
||||||
}
|
|
||||||
position -= part.Size
|
|
||||||
}
|
|
||||||
|
|
||||||
return -1, 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func findEndPart(cfg MultiObjectReaderConfig) (index int, length uint64) {
|
|
||||||
position := cfg.Off + cfg.Ln
|
|
||||||
for i, part := range cfg.Parts {
|
|
||||||
// Non-strict inequality when searching for end position to avoid out of payload range error.
|
|
||||||
if position <= part.Size {
|
|
||||||
return i, position
|
|
||||||
}
|
|
||||||
position -= part.Size
|
|
||||||
}
|
|
||||||
|
|
||||||
return -1, 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *MultiObjectReader) Read(p []byte) (n int, err error) {
|
|
||||||
if x.curReader != nil {
|
|
||||||
n, err = x.curReader.Read(p)
|
|
||||||
if err != nil {
|
|
||||||
if closeErr := x.curReader.Close(); closeErr != nil {
|
|
||||||
return n, fmt.Errorf("%w (close err: %v)", err, closeErr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !errors.Is(err, io.EOF) {
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
x.curIndex++
|
|
||||||
}
|
|
||||||
|
|
||||||
if x.curIndex == len(x.parts) {
|
|
||||||
return n, io.EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
x.prm.Addr.SetObject(x.parts[x.curIndex].OID)
|
|
||||||
|
|
||||||
if x.curIndex == 0 {
|
|
||||||
x.prm.Off = x.startPartOffset
|
|
||||||
x.prm.Ln = x.parts[x.curIndex].Size - x.startPartOffset
|
|
||||||
}
|
|
||||||
|
|
||||||
if x.curIndex == len(x.parts)-1 {
|
|
||||||
x.prm.Ln = x.endPartLength - x.prm.Off
|
|
||||||
}
|
|
||||||
|
|
||||||
x.curReader, err = x.layer.InitFrostFSObjectPayloadReader(x.ctx, x.prm)
|
|
||||||
if err != nil {
|
|
||||||
return n, fmt.Errorf("init payload reader for the next part: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
x.prm.Off = 0
|
|
||||||
x.prm.Ln = 0
|
|
||||||
|
|
||||||
next, err := x.Read(p[n:])
|
|
||||||
|
|
||||||
return n + next, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// InitFrostFSObjectPayloadReader initializes payload reader of the FrostFS object.
|
|
||||||
// Zero range corresponds to full payload (panics if only offset is set).
|
|
||||||
func (x *FrostFS) InitFrostFSObjectPayloadReader(ctx context.Context, p GetFrostFSParams) (io.ReadCloser, error) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(ctx, "frostfs.InitFrostFSObjectPayloadReader")
|
|
||||||
defer span.End()
|
|
||||||
|
|
||||||
var prmAuth handler.PrmAuth
|
|
||||||
|
|
||||||
if p.Off+p.Ln != 0 {
|
|
||||||
prm := handler.PrmObjectRange{
|
|
||||||
PrmAuth: prmAuth,
|
|
||||||
PayloadRange: [2]uint64{p.Off, p.Ln},
|
|
||||||
Address: p.Addr,
|
|
||||||
}
|
|
||||||
|
|
||||||
return x.RangeObject(ctx, prm)
|
|
||||||
}
|
|
||||||
|
|
||||||
prm := handler.PrmObjectGet{
|
|
||||||
PrmAuth: prmAuth,
|
|
||||||
Address: p.Addr,
|
|
||||||
}
|
|
||||||
|
|
||||||
res, err := x.GetObject(ctx, prm)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return res.Payload, nil
|
|
||||||
}
|
|
|
@ -1,137 +0,0 @@
|
||||||
package frostfs
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
|
|
||||||
oidtest "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id/test"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
type readerInitiatorMock struct {
|
|
||||||
parts map[oid.ID][]byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *readerInitiatorMock) InitFrostFSObjectPayloadReader(_ context.Context, p GetFrostFSParams) (io.ReadCloser, error) {
|
|
||||||
partPayload, ok := r.parts[p.Addr.Object()]
|
|
||||||
if !ok {
|
|
||||||
return nil, errors.New("part not found")
|
|
||||||
}
|
|
||||||
|
|
||||||
if p.Off+p.Ln == 0 {
|
|
||||||
return io.NopCloser(bytes.NewReader(partPayload)), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if p.Off > uint64(len(partPayload)-1) {
|
|
||||||
return nil, fmt.Errorf("invalid offset: %d/%d", p.Off, len(partPayload))
|
|
||||||
}
|
|
||||||
|
|
||||||
if p.Off+p.Ln > uint64(len(partPayload)) {
|
|
||||||
return nil, fmt.Errorf("invalid range: %d-%d/%d", p.Off, p.Off+p.Ln, len(partPayload))
|
|
||||||
}
|
|
||||||
|
|
||||||
return io.NopCloser(bytes.NewReader(partPayload[p.Off : p.Off+p.Ln])), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func prepareDataReader() ([]byte, []PartObj, *readerInitiatorMock) {
|
|
||||||
mockInitReader := &readerInitiatorMock{
|
|
||||||
parts: map[oid.ID][]byte{
|
|
||||||
oidtest.ID(): []byte("first part 1"),
|
|
||||||
oidtest.ID(): []byte("second part 2"),
|
|
||||||
oidtest.ID(): []byte("third part 3"),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
var fullPayload []byte
|
|
||||||
parts := make([]PartObj, 0, len(mockInitReader.parts))
|
|
||||||
for id, payload := range mockInitReader.parts {
|
|
||||||
parts = append(parts, PartObj{OID: id, Size: uint64(len(payload))})
|
|
||||||
fullPayload = append(fullPayload, payload...)
|
|
||||||
}
|
|
||||||
|
|
||||||
return fullPayload, parts, mockInitReader
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMultiReader(t *testing.T) {
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
fullPayload, parts, mockInitReader := prepareDataReader()
|
|
||||||
|
|
||||||
for _, tc := range []struct {
|
|
||||||
name string
|
|
||||||
off uint64
|
|
||||||
ln uint64
|
|
||||||
err error
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "simple read all",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "simple read with length",
|
|
||||||
ln: uint64(len(fullPayload)),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "middle of parts",
|
|
||||||
off: parts[0].Size + 2,
|
|
||||||
ln: 4,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "first and second",
|
|
||||||
off: parts[0].Size - 4,
|
|
||||||
ln: 8,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "first and third",
|
|
||||||
off: parts[0].Size - 4,
|
|
||||||
ln: parts[1].Size + 8,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "second part",
|
|
||||||
off: parts[0].Size,
|
|
||||||
ln: parts[1].Size,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "second and third",
|
|
||||||
off: parts[0].Size,
|
|
||||||
ln: parts[1].Size + parts[2].Size,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "offset out of range",
|
|
||||||
off: uint64(len(fullPayload) + 1),
|
|
||||||
ln: 1,
|
|
||||||
err: errOffsetIsOutOfRange,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "zero length",
|
|
||||||
off: parts[1].Size + 1,
|
|
||||||
ln: 0,
|
|
||||||
err: errorZeroRangeLength,
|
|
||||||
},
|
|
||||||
} {
|
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
|
||||||
multiReader, err := NewMultiObjectReader(ctx, MultiObjectReaderConfig{
|
|
||||||
Initiator: mockInitReader,
|
|
||||||
Parts: parts,
|
|
||||||
Off: tc.off,
|
|
||||||
Ln: tc.ln,
|
|
||||||
})
|
|
||||||
require.ErrorIs(t, err, tc.err)
|
|
||||||
|
|
||||||
if tc.err == nil {
|
|
||||||
off := tc.off
|
|
||||||
ln := tc.ln
|
|
||||||
if off+ln == 0 {
|
|
||||||
ln = uint64(len(fullPayload))
|
|
||||||
}
|
|
||||||
data, err := io.ReadAll(multiReader)
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Equal(t, fullPayload[off:off+ln], data)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,69 +0,0 @@
|
||||||
package frostfs
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/cache"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/handler"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/logs"
|
|
||||||
cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/netmap"
|
|
||||||
"go.uber.org/zap"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Source struct {
|
|
||||||
frostFS *FrostFS
|
|
||||||
netmapCache *cache.NetmapCache
|
|
||||||
bucketCache *cache.BucketCache
|
|
||||||
log *zap.Logger
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSource(frostFS *FrostFS, netmapCache *cache.NetmapCache, bucketCache *cache.BucketCache, log *zap.Logger) *Source {
|
|
||||||
return &Source{
|
|
||||||
frostFS: frostFS,
|
|
||||||
netmapCache: netmapCache,
|
|
||||||
bucketCache: bucketCache,
|
|
||||||
log: log,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Source) NetMapSnapshot(ctx context.Context) (netmap.NetMap, error) {
|
|
||||||
cachedNetmap := s.netmapCache.Get()
|
|
||||||
if cachedNetmap != nil {
|
|
||||||
return *cachedNetmap, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
netmapSnapshot, err := s.frostFS.NetmapSnapshot(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return netmap.NetMap{}, fmt.Errorf("get netmap: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err = s.netmapCache.Put(netmapSnapshot); err != nil {
|
|
||||||
s.log.Warn(logs.CouldntCacheNetmap, zap.Error(err), logs.TagField(logs.TagDatapath))
|
|
||||||
}
|
|
||||||
|
|
||||||
return netmapSnapshot, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Source) PlacementPolicy(ctx context.Context, cnrID cid.ID) (netmap.PlacementPolicy, error) {
|
|
||||||
info := s.bucketCache.GetByCID(cnrID)
|
|
||||||
if info != nil {
|
|
||||||
return info.PlacementPolicy, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
prm := handler.PrmContainer{
|
|
||||||
ContainerID: cnrID,
|
|
||||||
}
|
|
||||||
res, err := s.frostFS.Container(ctx, prm)
|
|
||||||
if err != nil {
|
|
||||||
return netmap.PlacementPolicy{}, fmt.Errorf("get container: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// We don't put container back to the cache to keep cache
|
|
||||||
// coherent to the requests made by users. FrostFS Source
|
|
||||||
// is being used by SDK Tree Pool and it should not fill cache
|
|
||||||
// with possibly irrelevant container values.
|
|
||||||
|
|
||||||
return res.PlacementPolicy(), nil
|
|
||||||
}
|
|
|
@ -1,170 +0,0 @@
|
||||||
package frostfs
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/data"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/tokens"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/tree"
|
|
||||||
"git.frostfs.info/TrueCloudLab/frostfs-observability/tracing"
|
|
||||||
apitree "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/api/tree"
|
|
||||||
treepool "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/pool/tree"
|
|
||||||
)
|
|
||||||
|
|
||||||
type GetNodeByPathResponseInfoWrapper struct {
|
|
||||||
response *apitree.GetNodeByPathResponseInfo
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n GetNodeByPathResponseInfoWrapper) GetNodeID() []uint64 {
|
|
||||||
return []uint64{n.response.GetNodeID()}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n GetNodeByPathResponseInfoWrapper) GetParentID() []uint64 {
|
|
||||||
return []uint64{n.response.GetParentID()}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n GetNodeByPathResponseInfoWrapper) GetTimestamp() []uint64 {
|
|
||||||
return []uint64{n.response.GetTimestamp()}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n GetNodeByPathResponseInfoWrapper) GetMeta() []tree.Meta {
|
|
||||||
res := make([]tree.Meta, len(n.response.GetMeta()))
|
|
||||||
for i, value := range n.response.GetMeta() {
|
|
||||||
res[i] = value
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
type PoolWrapper struct {
|
|
||||||
p *treepool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewPoolWrapper(p *treepool.Pool) *PoolWrapper {
|
|
||||||
return &PoolWrapper{p: p}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *PoolWrapper) GetNodes(ctx context.Context, prm *tree.GetNodesParams) ([]tree.NodeResponse, error) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(ctx, "frostfs.GetNodes")
|
|
||||||
defer span.End()
|
|
||||||
|
|
||||||
poolPrm := treepool.GetNodesParams{
|
|
||||||
CID: prm.CnrID,
|
|
||||||
TreeID: prm.TreeID,
|
|
||||||
Path: prm.Path,
|
|
||||||
Meta: prm.Meta,
|
|
||||||
PathAttribute: tree.FileNameKey,
|
|
||||||
LatestOnly: prm.LatestOnly,
|
|
||||||
AllAttrs: prm.AllAttrs,
|
|
||||||
BearerToken: getBearer(ctx),
|
|
||||||
}
|
|
||||||
|
|
||||||
nodes, err := w.p.GetNodes(ctx, poolPrm)
|
|
||||||
if err != nil {
|
|
||||||
return nil, handleError(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
res := make([]tree.NodeResponse, len(nodes))
|
|
||||||
for i, info := range nodes {
|
|
||||||
res[i] = GetNodeByPathResponseInfoWrapper{info}
|
|
||||||
}
|
|
||||||
|
|
||||||
return res, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func getBearer(ctx context.Context) []byte {
|
|
||||||
token, err := tokens.LoadBearerToken(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return token.Marshal()
|
|
||||||
}
|
|
||||||
|
|
||||||
func handleError(err error) error {
|
|
||||||
if err == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if errors.Is(err, treepool.ErrNodeNotFound) {
|
|
||||||
return fmt.Errorf("%w: %s", tree.ErrNodeNotFound, err.Error())
|
|
||||||
}
|
|
||||||
if errors.Is(err, treepool.ErrNodeAccessDenied) {
|
|
||||||
return fmt.Errorf("%w: %s", tree.ErrNodeAccessDenied, err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *PoolWrapper) GetSubTree(ctx context.Context, bktInfo *data.BucketInfo, treeID string, rootID []uint64, depth uint32, sort bool) ([]tree.NodeResponse, error) {
|
|
||||||
ctx, span := tracing.StartSpanFromContext(ctx, "frostfs.GetSubTree")
|
|
||||||
defer span.End()
|
|
||||||
|
|
||||||
order := treepool.NoneOrder
|
|
||||||
if sort {
|
|
||||||
order = treepool.AscendingOrder
|
|
||||||
}
|
|
||||||
poolPrm := treepool.GetSubTreeParams{
|
|
||||||
CID: bktInfo.CID,
|
|
||||||
TreeID: treeID,
|
|
||||||
RootID: rootID,
|
|
||||||
Depth: depth,
|
|
||||||
BearerToken: getBearer(ctx),
|
|
||||||
Order: order,
|
|
||||||
}
|
|
||||||
if len(rootID) == 1 && rootID[0] == 0 {
|
|
||||||
// storage node interprets 'nil' value as []uint64{0}
|
|
||||||
// gate wants to send 'nil' value instead of []uint64{0}, because
|
|
||||||
// it provides compatibility with previous tree service api where
|
|
||||||
// single uint64(0) value is dropped from signature
|
|
||||||
poolPrm.RootID = nil
|
|
||||||
}
|
|
||||||
|
|
||||||
subTreeReader, err := w.p.GetSubTree(ctx, poolPrm)
|
|
||||||
if err != nil {
|
|
||||||
return nil, handleError(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var subtree []tree.NodeResponse
|
|
||||||
|
|
||||||
node, err := subTreeReader.Next()
|
|
||||||
for err == nil {
|
|
||||||
subtree = append(subtree, GetSubTreeResponseBodyWrapper{node})
|
|
||||||
node, err = subTreeReader.Next()
|
|
||||||
}
|
|
||||||
if err != io.EOF {
|
|
||||||
return nil, handleError(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return subtree, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetSubTreeResponseBodyWrapper struct {
|
|
||||||
response *apitree.GetSubTreeResponseBody
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n GetSubTreeResponseBodyWrapper) GetNodeID() []uint64 {
|
|
||||||
return n.response.GetNodeID()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n GetSubTreeResponseBodyWrapper) GetParentID() []uint64 {
|
|
||||||
resp := n.response.GetParentID()
|
|
||||||
if resp == nil {
|
|
||||||
// storage sends nil that should be interpreted as []uint64{0}
|
|
||||||
// due to protobuf compatibility, see 'GetSubTree' function
|
|
||||||
return []uint64{0}
|
|
||||||
}
|
|
||||||
return resp
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n GetSubTreeResponseBodyWrapper) GetTimestamp() []uint64 {
|
|
||||||
return n.response.GetTimestamp()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n GetSubTreeResponseBodyWrapper) GetMeta() []tree.Meta {
|
|
||||||
res := make([]tree.Meta, len(n.response.GetMeta()))
|
|
||||||
for i, value := range n.response.GetMeta() {
|
|
||||||
res[i] = value
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
}
|
|
|
@ -1,112 +0,0 @@
|
||||||
{{$container := .Container}}
|
|
||||||
{{ $prefix := trimPrefix .Prefix }}
|
|
||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8"/>
|
|
||||||
<title>Index of {{.Protocol}}://{{$container}}
|
|
||||||
/{{if $prefix}}/{{$prefix}}/{{end}}</title>
|
|
||||||
<style>
|
|
||||||
.alert {
|
|
||||||
width: 80%;
|
|
||||||
box-sizing: border-box;
|
|
||||||
padding: 20px;
|
|
||||||
background-color: #f44336;
|
|
||||||
color: white;
|
|
||||||
margin-bottom: 15px;
|
|
||||||
}
|
|
||||||
table {
|
|
||||||
width: 80%;
|
|
||||||
border-collapse: collapse;
|
|
||||||
}
|
|
||||||
body {
|
|
||||||
background: #f2f2f2;
|
|
||||||
}
|
|
||||||
table, th, td {
|
|
||||||
border: 0 solid transparent;
|
|
||||||
}
|
|
||||||
th, td {
|
|
||||||
padding: 10px;
|
|
||||||
text-align: left;
|
|
||||||
}
|
|
||||||
th {
|
|
||||||
background-color: #c3bcbc;
|
|
||||||
}
|
|
||||||
|
|
||||||
h1 {
|
|
||||||
font-size: 1.5em;
|
|
||||||
}
|
|
||||||
tr:nth-child(even) {background-color: #ebe7e7;}
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<h1>Index of {{.Protocol}}://{{$container}}/{{if $prefix}}{{$prefix}}/{{end}}</h1>
|
|
||||||
{{ if .HasErrors }}
|
|
||||||
<div class="alert">
|
|
||||||
Errors occurred while processing the request. Perhaps some objects are missing
|
|
||||||
</div>
|
|
||||||
{{ end }}
|
|
||||||
<table>
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>Filename</th>
|
|
||||||
<th>OID</th>
|
|
||||||
<th>Size</th>
|
|
||||||
<th>Created</th>
|
|
||||||
<th>Download</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{{ $trimmedPrefix := trimPrefix $prefix }}
|
|
||||||
{{if $trimmedPrefix }}
|
|
||||||
<tr>
|
|
||||||
<td>
|
|
||||||
⮐<a href="/get/{{$container}}{{ urlencode $trimmedPrefix }}/">..</a>
|
|
||||||
</td>
|
|
||||||
<td></td>
|
|
||||||
<td></td>
|
|
||||||
<td></td>
|
|
||||||
<td></td>
|
|
||||||
</tr>
|
|
||||||
{{else}}
|
|
||||||
<tr>
|
|
||||||
<td>
|
|
||||||
⮐<a href="/get/{{$container}}/">..</a>
|
|
||||||
</td>
|
|
||||||
<td></td>
|
|
||||||
<td></td>
|
|
||||||
<td></td>
|
|
||||||
<td></td>
|
|
||||||
</tr>
|
|
||||||
{{end}}
|
|
||||||
{{range .Objects}}
|
|
||||||
<tr>
|
|
||||||
<td>
|
|
||||||
{{if .IsDir}}
|
|
||||||
🗀
|
|
||||||
<a href="{{.GetURL}}/">
|
|
||||||
{{.FileName}}/
|
|
||||||
</a>
|
|
||||||
{{else}}
|
|
||||||
🗎
|
|
||||||
<a href="{{ .GetURL }}">
|
|
||||||
{{.FileName}}
|
|
||||||
</a>
|
|
||||||
{{end}}
|
|
||||||
</td>
|
|
||||||
<td>{{.OID}}</td>
|
|
||||||
<td>{{if not .IsDir}}{{ formatSize .Size }}{{end}}</td>
|
|
||||||
<td>{{ .Created }}</td>
|
|
||||||
<td>
|
|
||||||
{{ if .OID }}
|
|
||||||
<a href="{{ .GetURL }}?download=true">
|
|
||||||
Link
|
|
||||||
</a>
|
|
||||||
{{ end }}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
{{end}}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue