Compare commits

..
Author SHA1 Message Date
txix 3c0c32ec72 2026-02-10 17:42:12: merge [main:f97795bd90603310b924d685666ce64c68644e4a];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-02-10 17:42:12 +03:00
txix bd3a52e7f3 2026-02-09 12:15:13: merge [main:f7931b1d8350cf640562be540836310ee6da010b];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-02-09 12:15:13 +03:00
txix bb02ef25ab 2026-02-06 11:20:37: merge [main:245cf8852da4396ef3b198c2af5f7e483379e391]; 2026-02-06 11:20:37 +03:00
txix bd633d1599 2026-02-05 17:50:20: merge [main:7b09eb3a07fc352b4ebee3cd1f0a9631f4ccb38d]; 2026-02-05 17:50:20 +03:00
txix 7ee7b6749f 2025-12-01 16:45:09: merge [main:8101f9a8c84d0c8c7bd462ac374f4db79dbc5d21];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-12-01 16:45:09 +03:00
txix 065c96042d 2025-10-09 15:30:52: merge [main:efed09bb923fb843bd0ebfcc65fd558a5a91727b];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-10-09 15:30:52 +03:00
txix 964ead61f7 2025-09-17 18:00:36: merge [main:5a3d4fffeaf49ec2831d3f9b1dea027c1e1784e1];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-09-17 18:00:36 +03:00
txix c36b4cdc1c 2025-08-21 16:39:38: merge [main:7a585711f6c2abcee6bbfb53dbf4c38fbbb68103]; 2025-08-21 16:39:38 +03:00
txix 261dfbd3cd 2025-07-08 11:38:08: merge [main:846129b1afe26f21c7e182be578112bb0c3f76ce];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-07-08 11:38:08 +03:00
txix f32c1bef30 2025-06-10 09:17:26: merge [main:78eeee0bc665dc8fd1e8b99c5ce47dc227342a7f];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-06-10 09:17:26 +03:00
txix 5e248d85fe 2025-06-06 17:09:42: merge [main:eb7997476085e283af784adf7ada881a3d37e535];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-06-06 17:09:42 +03:00
txix 7ec4962301 2025-06-06 16:56:57: merge [main:350d22ae7512add0069a2d5ac30546bd8b32d979]; 2025-06-06 16:56:57 +03:00
txix 6b7ddafa32 2025-05-27 14:44:20: merge [main:3e7f2358764cd22b6766b4ea57d14a429cfb06ab]; 2025-05-27 14:44:20 +03:00
txix 7ba1f0a5e8 2025-04-18 12:20:59: merge [main:aefc14ece9229d4d8e88c117a09f85d1a6775b46]; 2025-04-18 12:20:59 +03:00
txix 18205b2e66 2025-04-17 18:01:00: merge [main:0e6b5dec5225670f20a213993b54e1c0fcd44c63]; 2025-04-17 18:01:00 +03:00
txix 22baffabfb 2025-03-24 15:30:34: merge [main:7a1d8822489f02be3b825bb1224de48bab9c1657]; 2025-03-24 15:30:34 +03:00
txix 4a95b4b578 2024-12-27 16:47:46: merge [main:69567c48694f02359eecd8e696669f7c3de0b398]; 2024-12-27 16:47:46 +03:00
txix 0fbe723485 2024-12-12 13:56:05: merge [main:5fbfe1b039c8b70814b6262508bfeda3a8069dd2]; 2024-12-12 13:56:05 +03:00
txix e81f8c64cf 2024-11-27 12:16:06: merge [master:8f9dc2048fde1f9cb1c40e716e65dd91b77256b8]; 2024-11-27 12:16:06 +03:00
txix 802ce18a5e 2024-11-26 19:14:10: merge [master:16d2701e265c75b03df0b81a0cefc06bc9563e7a]; 2024-11-26 19:14:10 +03:00
txix 77244d4997 2024-11-20 14:39:28: merge [master:83355f8bbc6bf330c8f3d946415d732d2590d17d]; 2024-11-20 14:39:28 +03:00
txix 12b71a1777 2024-11-15 13:12:14: merge [master:93f2a5ed50211ee88fbdb241f4dbaa4af50d1d38]; 2024-11-15 13:12:14 +03:00
txix 1badb6b931 2024-04-24 17:59:21: merge [master:5e72ec386437c66661a2a98b1a232a3ad49af893]; 2024-04-24 17:59:21 +03:00
txix 14221f778c 2024-03-25 17:42:24: merge [master:e2419e2c4bf843e66dc679b387cbb6900599ee22]; 2024-03-25 17:42:24 +03:00
txix a5ca7b230a 2024-03-25 17:06:20: merge [master:72afc94782d802dbef7d4b1b092b6b1d02301edf]; 2024-03-25 17:06:20 +03:00
txix 3427a92d08 2024-03-25 16:52:24: merge [master:02070b1db1d2009dc917980dfc5e731e9508b8d0]; 2024-03-25 16:52:24 +03:00
txix ef7c017e4c 2024-03-25 16:23:54: merge [master:2fc6c7ba91a773e1055473094b8e3d7192bf4df4]; 2024-03-25 16:23:54 +03:00
163 changed files with 10086 additions and 6988 deletions

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
name: Create and publish a Docker image
on:
push:
tags:
- 'v*'
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
APP_NAME: ${{ github.event.repository.name }}
jobs:
build-and-push-image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
attestations: write
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Get version from tag
id: version_reader
run: |
VERSION=${GITHUB_REF_NAME#v}
echo "version=$VERSION" >> $GITHUB_OUTPUT
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
driver: docker-container
- name: Log in to the Container registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push Docker image
id: push
uses: docker/build-push-action@v6
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version_reader.outputs.version }}
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
labels: |
org.opencontainers.image.title=${{ env.IMAGE_NAME }}
org.opencontainers.image.version=${{ steps.version_reader.outputs.version }}
build-args: |
app_name=${{ env.APP_NAME }}
version=${{ steps.version_reader.outputs.version }}
- name: Generate artifact attestation
uses: actions/attest-build-provenance@v2
with:
subject-name: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME}}
subject-digest: ${{ steps.push.outputs.digest }}
push-to-registry: true
+6 -2
View File
@@ -9,8 +9,8 @@
.idea/**/tasks.xml
.idea/dictionaries
*.iml
config_service
config-service
convert_service
convert-service
# Sensitive or high-churn files:
.idea/**/dataSources/
@@ -69,3 +69,7 @@ fabric.properties
/node_modules/
/vendor/
package.json
yarn.lock
conf/config_dev.yml
+3 -3
View File
@@ -1,8 +1,8 @@
docker-build:
image: docker:latest
image: docker:20.10.16
stage: build
services:
- docker:dind
- docker:20.10.16-dind
before_script:
- docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
- export VERSION=`cat .version `
@@ -12,7 +12,7 @@ docker-build:
script:
- set
- mkdir -p migrations
- docker build -f "$CI_DOCKER_FILE" --force-rm --build-arg="version=$VERSION" --build-arg="app_name=$CI_PROJECT_NAME" --pull -t "$CI_REGISTRY/$CI_PROJECT_NAME:$VERSION" .
- docker build -f Dockerfile.dit --force-rm --build-arg="version=$VERSION" --build-arg="app_name=$CI_PROJECT_NAME" --pull -t "$CI_REGISTRY/$CI_PROJECT_NAME:$VERSION" .
- |
docker tag "$CI_REGISTRY/$CI_PROJECT_NAME:$VERSION" "$CI_REGISTRY/$CI_PROJECT_NAME:latest"
docker push "$CI_REGISTRY/$CI_PROJECT_NAME:$VERSION"
+70
View File
@@ -0,0 +1,70 @@
version: "2"
run:
allow-parallel-runners: true
linters:
default: all
disable:
- contextcheck # не имеет смысла
- depguard # не всегда имеет смысл
- dupword # не имеет смысла
- exhaustruct # не имеет смысла
- godot # не актуально для swagger
- godox # не позволяет оставлять todo
- gomoddirectives
- musttag # у нас собственное правило: не используем теги, если работаем с пакетом isp-kit/json и с внутренними структурами(между нашими сервисами), при этом теги обязательный для всех внешних для нас структур
- nlreturn # не всегда имеет смысл
- nolintlint # Goland все равно форматирует с отступом
- perfsprint # мнимая производительность в угоду читаемости
- tagalign # не всегда имеет смысл
- varnamelen # очень индивидуально (db)
- wsl # расставление пробелов очень индивидуально
- wsl_v5
settings:
cyclop:
max-complexity: 15 # по умолчанию 10 мало
funlen:
lines: 80
lll:
line-length: 150
revive:
rules:
- name: var-naming # отключаем Id -> ID
disabled: true
staticcheck:
checks: # отключаем Id -> ID
- -ST1000
- -ST1016
- -ST1020
- -ST1021
- -ST1022
testifylint:
disable:
- compares
- equal-values
exclusions:
generated: lax
presets:
- comments
- common-false-positives
- legacy
- std-error-handling
rules:
- linters:
- wrapcheck
path: controller # достаточное кол-во контекста на уровне контроллеров
- linters:
- wrapcheck
path: transaction # транзакции прозрачны
paths:
- third_party$
- builtin$
- examples$
formatters:
enable:
- gofmt
exclusions:
generated: lax
paths:
- third_party$
- builtin$
- examples$
+1 -1
View File
@@ -1 +1 @@
2.4.9
3.8.1
-84
View File
@@ -1,84 +0,0 @@
* исправлен метод /config/get_config_by_id
### v2.4.9
* обновлены зависимости (исправляет panic при запуске)
### v2.4.8
* do not check for instance_uuid anymore
### v2.4.7
* updated dependencies
### v2.4.6
* increase default version config count to 15
* fix leader address race on leader disconnect (it was possible that after the change of the leader, one of the nodes will not be declared available, although this is not so)
* enable metric server
* add integration test for multiple config updates
* fix service hanging on shutdown
* improve raft logging
* fix deadlock in cluster client
* add timeouts to all websocket emits to prevent connections leakage
### v2.4.5
* updated isp-lib
### v2.4.4
* fix marshaling body of `ERROR_CONNECTION` event
### v2.4.3
* updated isp-lib
* updated isp-event-lib
### v2.4.2
* add db pass part
### v2.4.1
* updated method `/config/get_configs_by_module_id`
### v2.4.0
* add method `/config/get_config_by_id`
* add method `/config/get_configs_by_module_id`
* updated docs
### v2.3.1
* fix old configs order
* add `createdAt` field to config version
### v2.3.0
* add method `/module/broadcast_event` to broadcast arbitrary event to modules
* add module dependencies to response `/module/get_modules_info`
* add option to create a new config version instead update it
* fix broadcasting config on activating and upserting configs
* add saving old configs
* add method `/config/delete_version`
* add method `/config/get_all_version`
* update libs
### v2.2.1
* update deps
* fix bug in json schema marshaling/unmarshaling
### v2.2.0
* migrate to go modules
* add linter, refactor
### v2.1.3
* improved logging
### v2.1.2
* leader ws client ConnectionReadLimit is now configured by WS.WsConnectionReadLimitKB config param and defaults to 4 MB
### v2.1.1
* update to new endpoint descriptor struct with extra fields introduced in isp-lib v2.1.0
### v2.1.0
* fix panic type casting in snapshot
* create empty default config now
* add method `/module/get_by_name` to fetch module object by name
### v2.0.3
* fix data race when applyCommandOnLeader in websocket handler
* update dependencies
### v2.0.2
* fix raft server address announcing (serverId == serverAddress == cluster.outerAddress)
### v2.0.1
* fix nil pointer dereference in repositories
* increase default websocket ConnectionReadLimit to 4 MB, add to configuration
### v2.0.0
* full rewrite to support cluster mode
* change websocket protocol from socketio to etp
### v1.1.0
* update libs
* default config handling
+42
View File
@@ -0,0 +1,42 @@
FROM golang:1.25-alpine as builder
WORKDIR /build
ARG version
ENV version_env=$version
ARG app_name
ENV app_name_env=$app_name
COPY . .
RUN apk update && apk upgrade && apk add --no-cache gcc musl-dev
RUN go build -ldflags="-X 'main.version=$version_env'" -o /main .
WORKDIR cmd/migrate
RUN CGO_ENABLED=1 go build -o /migrate .
FROM alpine:3.22
RUN apk add --no-cache tzdata
RUN cp /usr/share/zoneinfo/Europe/Moscow /etc/localtime
RUN echo "Europe/Moscow" > /etc/timezone
COPY --from=builder migrate /migrate/migrate
COPY cmd/migrate/config.yml /migrate/config.yml
RUN chmod 666 /migrate/config.yml
ARG UID=10001
RUN adduser \
--disabled-password \
--gecos "" \
--home "/nonexistent" \
--shell "/sbin/nologin" \
--no-create-home \
--uid "${UID}" \
appuser
USER appuser
WORKDIR /app
ARG app_name
ENV app_name_env=$app_name
COPY --from=builder main /app/$app_name_env
COPY /conf/config.yml /app/config.yml
COPY /conf/default_remote_config.json* /app/default_remote_config.json
COPY /migrations /app/migrations
ENTRYPOINT /app/$app_name_env
+12 -1
View File
@@ -1,5 +1,5 @@
FROM dockerhub.mos.ru/mosos/arbat:15.5 as builder
RUN zypper --no-gpg-checks update -y && zypper --no-gpg-checks install -y go1.23 git
RUN zypper --no-gpg-checks update -y && zypper --no-gpg-checks install -y go1.25 git
WORKDIR /build
ARG version
ENV version_env=$version
@@ -8,12 +8,18 @@ ENV app_name_env=$app_name
COPY . .
ENV GOPROXY=https://repo-mirror.mos.ru/repository/go-public
RUN go build -ldflags="-X 'main.version=$version_env'" -o /main .
WORKDIR cmd/migrate
RUN CGO_ENABLED=1 go build -o /migrate .
FROM dockerhub.mos.ru/mosos/arbat:15.5
RUN cp /usr/share/zoneinfo/Europe/Moscow /etc/localtime
RUN echo "Europe/Moscow" > /etc/timezone
COPY --from=builder migrate /migrate/migrate
COPY cmd/migrate/config.yml /migrate/config.yml
RUN chmod 666 /migrate/config.yml
ARG UID=10001
RUN useradd \
--home "/nonexistent" \
@@ -34,6 +40,11 @@ WORKDIR /app
ARG app_name
ENV app_name_env=$app_name
COPY --from=builder main /app/$app_name_env
COPY /conf/config.yml /app/config.yml
COPY /conf/default_remote_config.json* /app/default_remote_config.json
COPY /migrations /app/migrations
ENTRYPOINT /app/$app_name_env
COPY /conf/config.yml /app/config.yml
COPY /conf/default_remote_config.json* /app/default_remote_config.json
COPY /migrations /app/migrations
-674
View File
@@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+2 -1
View File
@@ -1 +1,2 @@
test
# isp-config-service
+214
View File
@@ -0,0 +1,214 @@
package assembly
import (
"context"
"net/http"
"net/http/httputil"
"net/url"
"time"
"isp-config-service/conf"
"isp-config-service/service/module/backend"
"isp-config-service/service/variable"
httpEndpoint "github.com/txix-open/isp-kit/http/endpoint"
"github.com/txix-open/isp-kit/http/endpoint/httplog"
"isp-config-service/controller"
"isp-config-service/controller/api"
"isp-config-service/repository"
"isp-config-service/routes"
apisvs "isp-config-service/service/api"
"isp-config-service/service/event"
"isp-config-service/service/metrics"
"isp-config-service/service/module"
"isp-config-service/service/rqlite/db"
"isp-config-service/service/subscription"
"github.com/txix-open/etp/v4"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/grpc/endpoint"
"github.com/txix-open/isp-kit/log"
"github.com/txix-open/isp-kit/worker"
)
const (
wsReadLimit = 4 * 1024 * 1024
handleEventsInterval = 500 * time.Millisecond
cleanEventInterval = 60 * time.Second
cleanPhantomBackendsInterval = 5 * time.Minute
eventTtl = 60 * time.Second
)
type LocalConfig struct {
Local conf.Local
RqliteAddress string
}
type Locator struct {
db db.DB
cfg LocalConfig
leaderChecker LeaderChecker
logger log.Logger
}
type LeaderChecker interface {
IsLeader() bool
}
type OwnBackendsCleaner interface {
DeleteOwnBackends(ctx context.Context)
}
func NewLocator(
db db.DB,
leaderChecker LeaderChecker,
cfg LocalConfig,
logger log.Logger,
) Locator {
return Locator{
db: db,
leaderChecker: leaderChecker,
cfg: cfg,
logger: logger,
}
}
type Config struct {
GrpcMux *grpc.Mux
HttpMux http.Handler
MetricsAdHandler http.Handler
EtpSrv *etp.Server
HandleEventWorker *worker.Worker
CleanEventWorker *worker.Worker
CleanPhantomBackendWorker *worker.Worker
CleanBackupsWorker *worker.Worker
OwnBackendsCleaner OwnBackendsCleaner
}
//nolint:funlen
func (l Locator) Config() *Config {
moduleRepo := repository.NewModule(l.db)
backendRepo := repository.NewBackend(l.db)
eventRepo := repository.NewEvent(l.db)
configRepo := repository.NewConfig(l.db)
configSchemaRepo := repository.NewConfigSchema(l.db)
configHistoryRepo := repository.NewConfigHistory(l.db)
variableRepo := repository.NewVariable(l.db)
variableService := variable.NewService(variableRepo, configRepo, eventRepo)
variableController := api.NewVariable(variableService)
etpSrv := etp.NewServer(
etp.WithServerReadLimit(wsReadLimit),
etp.WithServerAcceptOptions(&etp.AcceptOptions{
InsecureSkipVerify: true,
}),
)
emitter := module.NewEmitter(l.logger)
subscriptionService := subscription.NewService(
moduleRepo,
backendRepo,
configRepo,
etpSrv.Rooms(),
emitter,
variableService,
l.logger,
)
backendService := backend.NewBackend(
backendRepo,
eventRepo,
l.cfg.Local.Rqlite.NodeId,
etpSrv.Rooms(),
l.logger,
)
cleanPhantomBackendJob := backend.NewCleaner(backendService, l.logger)
cleanPhantomBackendWorker := worker.New(cleanPhantomBackendJob, worker.WithInterval(cleanPhantomBackendsInterval))
moduleService := module.NewService(
moduleRepo,
backendService,
configRepo,
configSchemaRepo,
subscriptionService,
emitter,
variableService,
l.logger,
)
moduleController := controller.NewModule(moduleService, l.logger)
configHistoryApiService := apisvs.NewConfigHistory(configRepo, moduleRepo, configHistoryRepo,
l.cfg.Local.KeepConfigVersions, l.logger)
configHistoryController := api.NewConfigHistory(configHistoryApiService)
moduleApiService := apisvs.NewModule(moduleRepo, backendRepo, configSchemaRepo)
moduleApiController := api.NewModule(moduleApiService)
configApiService := apisvs.NewConfig(
configRepo,
moduleRepo,
configSchemaRepo,
eventRepo,
configHistoryApiService,
variableService,
l.logger,
)
configApiController := api.NewConfig(configApiService)
configSchemaApiService := apisvs.NewConfigSchema(configSchemaRepo, moduleRepo)
configSchemaController := api.NewConfigSchema(configSchemaApiService)
controllers := routes.Controllers{
Module: moduleController,
ModuleApi: moduleApiController,
ConfigApi: configApiController,
ConfigHistoryApi: configHistoryController,
ConfigSchemaApi: configSchemaController,
VariableApi: variableController,
}
mapper := endpoint.DefaultWrapper(l.logger)
grpcMux := routes.GrpcHandler(mapper, controllers)
routes.BindEtp(etpSrv, controllers, l.logger)
rqliteUrl, err := url.Parse(l.cfg.RqliteAddress)
if err != nil {
panic(err)
}
rqliteProxy := httputil.NewSingleHostReverseProxy(rqliteUrl)
rqliteBackupUrl, err := url.Parse(l.cfg.RqliteAddress + "/db/backup")
if err != nil {
panic(err)
}
rqliteBackupProxy := httputil.NewSingleHostReverseProxy(rqliteBackupUrl)
httpMux := routes.HttpHandler(etpSrv, l.cfg.Local, rqliteProxy, rqliteBackupProxy)
eventHandler := event.NewHandler(subscriptionService, l.logger)
handleEventJob := event.NewWorker(eventRepo, eventHandler, l.logger)
handleEventWorker := worker.New(handleEventJob, worker.WithInterval(handleEventsInterval))
cleanerJob := event.NewCleaner(eventRepo, l.leaderChecker, eventTtl, l.logger)
cleanEventWorker := worker.New(cleanerJob, worker.WithInterval(cleanEventInterval))
cleanBackupsJob := event.NewBackupCleaner(l.leaderChecker, l.cfg.Local.Backup, l.logger)
cleanBackupsWorker := worker.New(cleanBackupsJob, worker.WithInterval(l.cfg.Local.Backup.ClearInterval))
metricsSvc := metrics.New(backendRepo)
metricsController := controller.NewMetrics(metricsSvc)
httpWrapper := httpEndpoint.DefaultWrapper(l.logger, httplog.Log(l.logger, false))
return &Config{
GrpcMux: grpcMux,
EtpSrv: etpSrv,
HttpMux: httpMux,
MetricsAdHandler: httpWrapper.Endpoint(metricsController.Autodiscovery),
HandleEventWorker: handleEventWorker,
CleanEventWorker: cleanEventWorker,
CleanPhantomBackendWorker: cleanPhantomBackendWorker,
CleanBackupsWorker: cleanBackupsWorker,
OwnBackendsCleaner: backendService,
}
}
+45
View File
@@ -0,0 +1,45 @@
### v3.8.1
* исправлена миграция для `config-history`
### v3.8.0
* Добавлен новый endpoint `config/schema/update_by_module_name` для обновления схемы модуля по его названию
## v3.7.0
* добавлены rqlite-автобэкапы и прокси-эндпоинт `/backup` для создания резервных копий
* изменен таймаут ожидания лидера с 30 до 180 секунд
* исправлены потенциальные race conditions
* добавлен параметр периодической оптимизации sqlite `AutoOptimizeInterval: 23h`
* обновлены зависимости
## v3.6.0
* добавлен новый эндпоинт `config/config/purge_versions` для удаления старых версий всех конфигураций модуля, за исключением n последних
* обновлены зависимости
## v3.5.0
* обновлены зависимости
## v3.4.1
* исправлена проблема при которой не отвязывалась единственная переменная от конфигурации
* исправлена проблема при которой версия конфига сохраняется с некорректным временем (бралось текущее время, а не время обновления конфига)
* обновлены зависимости
## v3.4.0
* добавлено поле `metrics_autodiscovery` в таблицу `isp_config_service__backend`
* реализован внутренний метод `/internal/metrics/autodiscovery`, формирующий конфигурацию для `HTTP-based service discovery` механизма `Prometheus`
* обновлены зависимости
## v3.3.1
* добавлен скрипт для сборки и публикации образа в `GitHub Contaier Registry`
* обновлены зависимости
## v3.3.0
* обновлены зависимости
* добавлен новый эндпоинт `config/config/update_config_name` для изменения названия конфигурации без повышения версии и рассылки события
* теперь эндпоинт `config/config/get_all_version` первым элементом возвращает актуальную версию конфигурации
* добавлен новый эндпоинт `/config/config/sync` для синхронизации актуальной конфигурации пришедшего модуля
* добавлена оптимизация в `config/config/create_update_config`: если в запросе `data` и `name` не отличаются от текущей версии конфигурации, то событие логируется на уровне `info` без обновления конфигурации; возвращается текущая версия конфигурации
## v3.2.0
* добавлена поддержка переменных в конфигурациях
## v3.1.2
* возвращена поддержка rqlite.DiscoMode `dns` и `dns-srv`
* добавлена поддержка работы в `kubernetes` c autodiscovery
## v3.1.1
* инструмент миграции перенесен внутрь контейнера
## v3.1.0
* добавлено возможность анонсировать несколько бекендов с одинаковыми адресами
* реализован механизм поиска и очистки фантомных бекендов (те который отключились, но остались висеть в таблице маршрутизации)
* добавлена очистка таблицы маршрутизации в момент отключения самого модуля
## v3.0.2
* Новая реализация модуля на базе rqlite
-209
View File
@@ -1,209 +0,0 @@
package cluster
import (
"errors"
"fmt"
"sync"
"time"
"github.com/integration-system/isp-lib/v2/atomic"
"github.com/integration-system/isp-lib/v2/structure"
"github.com/integration-system/isp-lib/v2/utils"
log "github.com/integration-system/isp-log"
jsoniter "github.com/json-iterator/go"
"isp-config-service/codes"
"isp-config-service/entity"
"isp-config-service/raft"
"isp-config-service/store/state"
)
var (
ErrNoLeader = errors.New("no leader in cluster")
ErrLeaderClientNotInitialized = errors.New("leader client not initialized")
ErrNotLeader = errors.New("node is not a leader")
json = jsoniter.ConfigFastest
)
const (
leaderConnectionTimeout = 3 * time.Second
defaultApplyTimeout = 3 * time.Second
)
type Client struct {
r *raft.Raft
leaderMu sync.RWMutex
isLeader *atomic.AtomicBool
leaderState leaderState
leaderClient *SocketLeaderClient
declaration structure.BackendDeclaration
onClientDisconnect func(string)
}
func (client *Client) Shutdown() error {
client.leaderMu.Lock()
defer client.leaderMu.Unlock()
if client.leaderClient != nil {
client.leaderClient.Close()
client.leaderClient = nil
}
return client.r.GracefulShutdown()
}
func (client *Client) IsLeader() bool {
return client.isLeader.Get()
}
func (client *Client) SyncApply(command []byte) (*ApplyLogResponse, error) {
client.leaderMu.RLock()
defer client.leaderMu.RUnlock()
if !client.leaderState.leaderElected {
return nil, ErrNoLeader
}
if client.leaderState.isLeader {
apply, err := client.r.SyncApply(command)
if err != nil {
return nil, fmt.Errorf("apply to raft as a leader: %v", err)
}
logResponse := apply.(ApplyLogResponse)
return &logResponse, nil
}
if client.leaderClient == nil {
return nil, ErrLeaderClientNotInitialized
}
response, err := client.leaderClient.Ack(command, defaultApplyTimeout)
if err != nil {
return nil, fmt.Errorf("send to leader to apply: %v", err)
}
var logResponse ApplyLogResponse
err = json.Unmarshal(response, &logResponse)
if err != nil {
return nil, err
}
return &logResponse, nil
}
func (client *Client) SyncApplyOnLeader(command []byte) (*ApplyLogResponse, error) {
client.leaderMu.RLock()
defer client.leaderMu.RUnlock()
if !client.leaderState.isLeader {
return nil, ErrNotLeader
}
apply, err := client.r.SyncApply(command)
if err != nil {
return nil, fmt.Errorf("apply to raft as a leader: %v", err)
}
logResponse := apply.(ApplyLogResponse)
return &logResponse, nil
}
func (client *Client) listenLeader() {
for n := range client.r.LeaderCh() {
client.leaderMu.Lock()
log.WithMetadata(map[string]interface{}{
"leader_elected": n.LeaderElected,
"current_leader": n.CurrentLeaderAddress,
"is_leader": n.IsLeader,
}).Info(codes.LeaderStateChanged, "leader state changed")
if client.leaderClient != nil {
client.leaderClient.Close()
client.leaderClient = nil
}
if n.LeaderElected && !n.IsLeader {
leaderAddr := n.CurrentLeaderAddress
leaderClient := NewSocketLeaderClient(leaderAddr, func() {
client.onClientDisconnect(leaderAddr)
})
if err := leaderClient.Dial(leaderConnectionTimeout); err != nil {
log.Fatalf(codes.LeaderClientConnectionError, "could not connect to leader: %v", err)
}
client.leaderClient = leaderClient
log.Info(codes.SendDeclarationToLeader, "sending declaration to leader through websocket")
go client.declareMyselfToLeader(leaderClient)
} else if n.LeaderElected && n.IsLeader {
go client.declareMyselfToCluster()
}
client.leaderState = leaderState{
leaderElected: n.LeaderElected,
isLeader: n.IsLeader,
leaderAddr: n.CurrentLeaderAddress,
}
client.isLeader.Set(n.IsLeader)
client.leaderMu.Unlock()
}
}
func (client *Client) declareMyselfToLeader(leaderClient *SocketLeaderClient) {
response, err := leaderClient.SendDeclaration(client.declaration, defaultApplyTimeout)
if err != nil {
log.Warnf(codes.SendDeclarationToLeader, "send declaration to leader. err: %v", err)
} else if response != utils.WsOkResponse {
log.Warnf(codes.SendDeclarationToLeader, "send declaration to leader. error response: '%s'", response)
} else {
log.Info(codes.SendDeclarationToLeader, "successfully sent my declaration to leader")
}
}
// used when a leader need to declare himself to a cluster
func (client *Client) declareMyselfToCluster() {
now := state.GenerateDate()
module := entity.Module{
Id: state.GenerateId(),
Name: client.declaration.ModuleName,
CreatedAt: now,
LastConnectedAt: now,
}
command := PrepareModuleConnectedCommand(module)
syncApplyCommand(client, command)
declarationCommand := PrepareUpdateBackendDeclarationCommand(client.declaration)
syncApplyCommand(client, declarationCommand)
}
type leaderState struct {
leaderElected bool
isLeader bool
leaderAddr string
}
func NewRaftClusterClient(r *raft.Raft, declaration structure.BackendDeclaration, onLeaderDisconnect func(string)) *Client {
client := &Client{
r: r,
declaration: declaration,
leaderState: leaderState{},
onClientDisconnect: onLeaderDisconnect,
isLeader: atomic.NewAtomicBool(false),
}
go client.listenLeader()
return client
}
func syncApplyCommand(clusterClient *Client, command []byte) {
applyLogResponse, err := clusterClient.SyncApply(command)
if err != nil {
commandName := ParseCommand(command).String()
log.WithMetadata(map[string]interface{}{
"command": string(command),
"commandName": commandName,
}).Warnf(codes.SyncApplyError, "announce myself. apply command: %v", err)
}
if applyLogResponse != nil && applyLogResponse.ApplyError != "" {
commandName := ParseCommand(command).String()
log.WithMetadata(map[string]interface{}{
"result": string(applyLogResponse.Result),
"applyError": applyLogResponse.ApplyError,
"commandName": commandName,
}).Warnf(codes.SyncApplyError, "announce myself. apply command")
}
}
-113
View File
@@ -1,113 +0,0 @@
package cluster
import (
"bytes"
"encoding/binary"
"time"
"github.com/integration-system/isp-lib/v2/structure"
log "github.com/integration-system/isp-log"
"isp-config-service/codes"
"isp-config-service/entity"
)
const (
ApplyCommandEvent = "CONFIG_CLUSTER:APPLY_COMMAND"
CommandSizeBytes = 8
GETParam = "cluster"
)
type Command uint64
// needed: go get golang.org/x/tools/cmd/stringer
//go:generate stringer -type=Command -output const_string.go
const (
_ Command = iota
UpdateBackendDeclarationCommand
DeleteBackendDeclarationCommand
UpdateConfigSchemaCommand
ModuleConnectedCommand
ModuleDisconnectedCommand
DeleteModulesCommand
DeleteVersionConfigCommand
ActivateConfigCommand
DeleteConfigsCommand
UpsertConfigCommand
DeleteCommonConfigsCommand
UpsertCommonConfigCommand
BroadcastEventCommand
)
func ParseCommand(data []byte) Command {
return Command(binary.BigEndian.Uint64(data[:CommandSizeBytes]))
}
func PrepareUpdateBackendDeclarationCommand(backend structure.BackendDeclaration) []byte {
return prepareCommand(UpdateBackendDeclarationCommand, backend)
}
func PrepareDeleteBackendDeclarationCommand(backend structure.BackendDeclaration) []byte {
return prepareCommand(DeleteBackendDeclarationCommand, backend)
}
func PrepareModuleConnectedCommand(module entity.Module) []byte {
return prepareCommand(ModuleConnectedCommand, module)
}
func PrepareModuleDisconnectedCommand(module entity.Module) []byte {
return prepareCommand(ModuleDisconnectedCommand, module)
}
func PrepareDeleteModulesCommand(ids []string) []byte {
return prepareCommand(DeleteModulesCommand, DeleteModules{Ids: ids})
}
func PrepareActivateConfigCommand(configID string, date time.Time) []byte {
return prepareCommand(ActivateConfigCommand, ActivateConfig{ConfigId: configID, Date: date})
}
func PrepareDeleteConfigsCommand(ids []string) []byte {
return prepareCommand(DeleteConfigsCommand, DeleteModules{Ids: ids})
}
func PrepareUpsertConfigCommand(config UpsertConfig) []byte {
return prepareCommand(UpsertConfigCommand, config)
}
func PrepareUpdateConfigSchemaCommand(schema entity.ConfigSchema) []byte {
return prepareCommand(UpdateConfigSchemaCommand, schema)
}
func PrepareDeleteCommonConfigsCommand(id string) []byte {
return prepareCommand(DeleteCommonConfigsCommand, DeleteCommonConfig{Id: id})
}
func PrepareUpsertCommonConfigCommand(config UpsertCommonConfig) []byte {
return prepareCommand(UpsertCommonConfigCommand, config)
}
func PrepareBroadcastEventCommand(event BroadcastEvent) []byte {
return prepareCommand(BroadcastEventCommand, event)
}
func PrepareDeleteConfigVersionCommand(id string) []byte {
return prepareCommand(DeleteVersionConfigCommand, Identity{Id: id})
}
func prepareCommand(command Command, payload interface{}) []byte {
cmd := make([]byte, 8)
binary.BigEndian.PutUint64(cmd, uint64(command))
buf := bytes.NewBuffer(cmd)
err := json.NewEncoder(buf).Encode(payload)
if err != nil {
log.Fatalf(codes.PrepareLogCommandError, "prepare log command: %v", err)
}
return buf.Bytes()
}
-36
View File
@@ -1,36 +0,0 @@
// Code generated by "stringer -type=Command -output const_string.go"; DO NOT EDIT.
package cluster
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[UpdateBackendDeclarationCommand-1]
_ = x[DeleteBackendDeclarationCommand-2]
_ = x[UpdateConfigSchemaCommand-3]
_ = x[ModuleConnectedCommand-4]
_ = x[ModuleDisconnectedCommand-5]
_ = x[DeleteModulesCommand-6]
_ = x[DeleteVersionConfigCommand-7]
_ = x[ActivateConfigCommand-8]
_ = x[DeleteConfigsCommand-9]
_ = x[UpsertConfigCommand-10]
_ = x[DeleteCommonConfigsCommand-11]
_ = x[UpsertCommonConfigCommand-12]
_ = x[BroadcastEventCommand-13]
}
const _Command_name = "UpdateBackendDeclarationCommandDeleteBackendDeclarationCommandUpdateConfigSchemaCommandModuleConnectedCommandModuleDisconnectedCommandDeleteModulesCommandDeleteVersionConfigCommandActivateConfigCommandDeleteConfigsCommandUpsertConfigCommandDeleteCommonConfigsCommandUpsertCommonConfigCommandBroadcastEventCommand"
var _Command_index = [...]uint16{0, 31, 62, 87, 109, 134, 154, 180, 201, 221, 240, 266, 291, 312}
func (i Command) String() string {
i -= 1
if i >= Command(len(_Command_index)-1) {
return "Command(" + strconv.FormatInt(int64(i+1), 10) + ")"
}
return _Command_name[_Command_index[i]:_Command_index[i+1]]
}
-79
View File
@@ -1,79 +0,0 @@
package cluster
import (
json2 "encoding/json"
"fmt"
"time"
"google.golang.org/grpc/codes"
"isp-config-service/entity"
)
type ApplyLogResponse struct {
ApplyError string
Result json2.RawMessage
}
func (a ApplyLogResponse) Error() string {
return a.ApplyError
}
type DeleteModules struct {
Ids []string
}
type ActivateConfig struct {
ConfigId string
Date time.Time
}
type UpsertConfig struct {
Config entity.Config
VersionId string
VersionCreateAt time.Time
Create bool
Unsafe bool
}
type DeleteConfigs struct {
Ids []string
}
type DeleteCommonConfig struct {
Id string
}
type Identity struct {
Id string
}
type UpsertCommonConfig struct {
Config entity.CommonConfig
Create bool
}
type BroadcastEvent struct {
Event string
ModuleNames []string
PerformUntil time.Time // stateless events, must be broadcast until this in UTC
Payload json2.RawMessage
}
type ResponseWithError struct {
Response interface{}
Error string
ErrorCode codes.Code
}
func NewResponseErrorf(code codes.Code, format string, args ...interface{}) ResponseWithError {
return ResponseWithError{
Error: fmt.Sprintf(format, args...),
ErrorCode: code,
}
}
func NewResponse(value interface{}) ResponseWithError {
return ResponseWithError{
Response: value,
}
}
-119
View File
@@ -1,119 +0,0 @@
package cluster
import (
"context"
"fmt"
"net"
"net/http"
"net/url"
"time"
"github.com/cenkalti/backoff/v4"
etp "github.com/integration-system/isp-etp-go/v2/client"
"github.com/integration-system/isp-lib/v2/config"
"github.com/integration-system/isp-lib/v2/structure"
"github.com/integration-system/isp-lib/v2/utils"
log "github.com/integration-system/isp-log"
"isp-config-service/codes"
"isp-config-service/conf"
)
var (
// Set from config in main
WsConnectionReadLimit int64
)
type SocketLeaderClient struct {
client etp.Client
url string
globalCtx context.Context
cancel context.CancelFunc
}
func (c *SocketLeaderClient) Ack(data []byte, timeout time.Duration) ([]byte, error) {
ctx, cancel := context.WithTimeout(c.globalCtx, timeout)
defer cancel()
response, err := c.client.EmitWithAck(ctx, ApplyCommandEvent, data)
return response, err
}
func (c *SocketLeaderClient) SendDeclaration(backend structure.BackendDeclaration, timeout time.Duration) (string, error) {
data, err := json.Marshal(backend)
if err != nil {
return "", err
}
ctx, cancel := context.WithTimeout(c.globalCtx, timeout)
defer cancel()
response, err := c.client.EmitWithAck(ctx, utils.ModuleReady, data)
return string(response), err
}
func (c *SocketLeaderClient) Dial(timeout time.Duration) error {
backOff := backoff.NewExponentialBackOff()
backOff.MaxElapsedTime = timeout
bf := backoff.WithContext(backOff, c.globalCtx)
dial := func() error {
return c.client.Dial(c.globalCtx, c.url)
}
return backoff.Retry(dial, bf)
}
func (c *SocketLeaderClient) Close() {
c.cancel()
err := c.client.Close()
if err != nil {
log.Warnf(codes.LeaderClientConnectionError, "leader client %s close err: %v", c.url, err)
}
log.Debugf(0, "close previous leader ws connection %s", c.url)
}
func NewSocketLeaderClient(address string, leaderDisconnectionCallback func()) *SocketLeaderClient {
etpConfig := etp.Config{
HttpClient: &http.Client{},
ConnectionReadLimit: WsConnectionReadLimit,
WorkersNum: 1,
WorkersBufferMultiplier: 1,
}
client := etp.NewClient(etpConfig)
leaderClient := &SocketLeaderClient{
client: client,
url: getURL(address),
}
ctx, cancel := context.WithCancel(context.Background())
leaderClient.globalCtx = ctx
leaderClient.cancel = cancel
leaderClient.client.OnDisconnect(func(err error) {
log.WithMetadata(map[string]interface{}{
"leaderAddr": address,
"error": err,
}).Warn(codes.LeaderClientDisconnected, "disconnected ws from leader")
leaderDisconnectionCallback()
})
leaderClient.client.OnError(func(err error) {
log.WithMetadata(map[string]interface{}{
"leaderAddr": address,
"error": err,
}).Warn(codes.LeaderClientDisconnected, "leader client on error")
})
leaderClient.client.OnConnect(func() {
log.WithMetadata(map[string]interface{}{
"leaderAddr": address,
}).Info(codes.LeaderClientConnected, "connected to new leader")
})
return leaderClient
}
func getURL(address string) string {
addr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
panic(err) // must never occurred
}
cfg := config.Get().(*conf.Configuration)
params := url.Values{}
params.Add(GETParam, "true")
params.Add(utils.ModuleNameGetParamKey, cfg.ModuleName)
return fmt.Sprintf("ws://%s:%d/isp-etp/?%s", addr.IP.String(), addr.Port, params.Encode())
}
+12
View File
@@ -0,0 +1,12 @@
db:
host: 127.0.0.1
port: 5432
database: test
username: test
password: test
schema: config_service
newConfigService:
address: http://127.0.0.1:9001/
username: default
password: test
+43
View File
@@ -0,0 +1,43 @@
package main
import (
"time"
"github.com/txix-open/isp-kit/json"
)
type Module struct {
Id string
Name string
LastConnectedAt *time.Time
LastDisconnectedAt *time.Time
CreatedAt time.Time
}
type Config struct {
Id string
ModuleId string
Name string
Version int
Active bool
Data json.RawMessage
CreatedAt time.Time
UpdatedAt time.Time
}
type ConfigHistory struct {
Id string
ConfigId string
ConfigVersion int
Data json.RawMessage
CreatedAt time.Time
}
type ConfigSchema struct {
Id string
ModuleId string
Version string
Schema json.RawMessage
CreatedAt time.Time
UpdatedAt time.Time
}
+77
View File
@@ -0,0 +1,77 @@
module isp-config-service/migrate
go 1.25.0
replace isp-config-service => ../..
require (
github.com/jmoiron/sqlx v1.4.0
github.com/mattn/go-sqlite3 v1.14.32
github.com/pkg/errors v0.9.1
github.com/pressly/goose/v3 v3.26.0
github.com/txix-open/isp-kit v1.63.3
isp-config-service v0.0.0-00010101000000-000000000000
)
require (
github.com/Masterminds/squirrel v1.5.4 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/coder/websocket v1.8.14 // indirect
github.com/gabriel-vasile/mimetype v1.4.11 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect
github.com/iancoleman/strcase v0.3.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.7.6 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mfridman/interpolate v0.0.2 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/prometheus/client_golang v1.23.2 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.67.3 // indirect
github.com/prometheus/procfs v0.19.2 // indirect
github.com/sethvargo/go-retry v0.3.0 // indirect
github.com/tidwall/gjson v1.18.0 // indirect
github.com/tidwall/match v1.2.0 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/txix-open/bellows v1.2.0 // indirect
github.com/txix-open/etp/v4 v4.0.1 // indirect
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.63.0 // indirect
go.opentelemetry.io/otel v1.38.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0 // indirect
go.opentelemetry.io/otel/metric v1.38.0 // indirect
go.opentelemetry.io/otel/sdk v1.38.0 // indirect
go.opentelemetry.io/otel/trace v1.38.0 // indirect
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.1 // indirect
go.yaml.in/yaml/v2 v2.4.3 // indirect
golang.org/x/crypto v0.45.0 // indirect
golang.org/x/net v0.47.0 // indirect
golang.org/x/sync v0.18.0 // indirect
golang.org/x/sys v0.38.0 // indirect
golang.org/x/text v0.31.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20251111163417-95abcf5c77ba // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20251124214823-79d6a2a48846 // indirect
google.golang.org/grpc v1.77.0 // indirect
google.golang.org/protobuf v1.36.10 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+221
View File
@@ -0,0 +1,221 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM=
github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10=
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g=
github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/gabriel-vasile/mimetype v1.4.11 h1:AQvxbp830wPhHTqc1u7nzoLT+ZFxGY7emj5DR5DYFik=
github.com/gabriel-vasile/mimetype v1.4.11/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/getsentry/sentry-go v0.38.0 h1:S8Xui7gLeAvXINVLMOaX94HnsDf1GexnfXGSNC4+KQs=
github.com/getsentry/sentry-go v0.38.0/go.mod h1:eRXCoh3uvmjQLY6qu63BjUZnaBu5L5WhMV1RwYO8W5s=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-resty/resty/v2 v2.16.5 h1:hBKqmWrr7uRc3euHVqmh1HTHcKn99Smr7o5spptdhTM=
github.com/go-resty/resty/v2 v2.16.5/go.mod h1:hkJtXbA2iKHzJheXYvQ8snQES5ZLGKMwQ07xAwp/fiA=
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=
github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 h1:NmZ1PKzSTQbuGHw9DGPFomqkkLWMC+vZCkfs+FHv1Vg=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3/go.mod h1:zQrxl1YP88HQlA6i9c63DSVPFklWpGX4OWAc9bFuaH4=
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.7.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk=
github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw=
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o=
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk=
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/mattn/go-sqlite3 v1.14.32 h1:JD12Ag3oLy1zQA+BNn74xRgaBbdhbNIDYvQUEuuErjs=
github.com/mattn/go-sqlite3 v1.14.32/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pressly/goose/v3 v3.26.0 h1:KJakav68jdH0WDvoAcj8+n61WqOIaPGgH0bJWS6jpmM=
github.com/pressly/goose/v3 v3.26.0/go.mod h1:4hC1KrritdCxtuFsqgs1R4AU5bWtTAf+cnWvfhf2DNY=
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.67.3 h1:shd26MlnwTw5jksTDhC7rTQIteBxy+ZZDr3t7F2xN2Q=
github.com/prometheus/common v0.67.3/go.mod h1:gP0fq6YjjNCLssJCQp0yk4M8W6ikLURwkdd/YKtTbyI=
github.com/prometheus/procfs v0.19.2 h1:zUMhqEW66Ex7OXIiDkll3tl9a1ZdilUOd/F6ZXw4Vws=
github.com/prometheus/procfs v0.19.2/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrah2SE=
github.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLyYaFyAZraas=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/match v1.2.0 h1:0pt8FlkOwjN2fPt4bIl4BoNxb98gGHN2ObFEDkrfZnM=
github.com/tidwall/match v1.2.0/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/txix-open/bellows v1.2.0 h1:CXv8nQaZtB/micraeRilYyj/gtfv+bqBgP5aPYQgjeY=
github.com/txix-open/bellows v1.2.0/go.mod h1:qbKCy+RTgD30Qpw1fyb3y3jp5Y9mGhLLxgae1l0W92o=
github.com/txix-open/etp/v4 v4.0.1 h1:5VSYgGsvnMz0tvUHsjVWFETI0qWBTCF1O3ARCHaCIgA=
github.com/txix-open/etp/v4 v4.0.1/go.mod h1:FIu7TUDdwcgmtmF6tFTV1bGA2fRY/iVaPQdsGzvqYc8=
github.com/txix-open/isp-kit v1.63.3 h1:UJLgR4z8sYXUX6r1sl6Ww1aijPx6b7ieMeB+elZoViM=
github.com/txix-open/isp-kit v1.63.3/go.mod h1:rwqKqB3PyZxaoep6iH1PKL89LS9nzRklA6+S4II72M4=
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0=
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb/go.mod h1:0biAFE0bgbcKeBBAwgEDhbZz6uT1vuSETCrFQlv2RiA=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.63.0 h1:2pn7OzMewmYRiNtv1doZnLo3gONcnMHlFnmOR8Vgt+8=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.63.0/go.mod h1:rjbQTDEPQymPE0YnRQp9/NuPwwtL0sesz/fnqRW/v84=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg=
go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8=
go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 h1:GqRJVj7UmLjCVyVJ3ZFLdPRmhDUp2zFmQe3RHIOsw24=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0/go.mod h1:ri3aaHSmCTVYu2AWv44YMauwAQc0aqI9gHKIcSbI1pU=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0 h1:aTL7F04bJHUlztTsNGJ2l+6he8c+y/b//eR0jjjemT4=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0/go.mod h1:kldtb7jDTeol0l3ewcmd8SDvx3EmIE7lyvqbasU3QC4=
go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA=
go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI=
go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E=
go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg=
go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM=
go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA=
go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE=
go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs=
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o=
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
google.golang.org/genproto/googleapis/api v0.0.0-20251111163417-95abcf5c77ba h1:B14OtaXuMaCQsl2deSvNkyPKIzq3BjfxQp8d00QyWx4=
google.golang.org/genproto/googleapis/api v0.0.0-20251111163417-95abcf5c77ba/go.mod h1:G5IanEx8/PgI9w6CFcYQf7jMtHQhZruvfM1i3qOqk5U=
google.golang.org/genproto/googleapis/rpc v0.0.0-20251124214823-79d6a2a48846 h1:Wgl1rcDNThT+Zn47YyCXOXyX/COgMTIdhJ717F0l4xk=
google.golang.org/genproto/googleapis/rpc v0.0.0-20251124214823-79d6a2a48846/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk=
google.golang.org/grpc v1.77.0 h1:wVVY6/8cGA6vvffn+wWK5ToddbgdU3d8MNENr4evgXM=
google.golang.org/grpc v1.77.0/go.mod h1:z0BY1iVj0q8E1uSQCjL9cppRj+gnZjzDnzV0dHhrNig=
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/libc v1.66.3 h1:cfCbjTUcdsKyyZZfEUKfoHcP3S0Wkvz3jgSzByEWVCQ=
modernc.org/libc v1.66.3/go.mod h1:XD9zO8kt59cANKvHPXpx7yS2ELPheAey0vjIuZOhOU8=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.38.2 h1:Aclu7+tgjgcQVShZqim41Bbw9Cho0y/7WzYptXqkEek=
modernc.org/sqlite v1.38.2/go.mod h1:cPTJYSlgg3Sfg046yBShXENNtPrWrDX8bsbAQBzgQ5E=
+204
View File
@@ -0,0 +1,204 @@
package main
import (
"context"
"database/sql"
"fmt"
"os"
"time"
"github.com/pressly/goose/v3"
"github.com/txix-open/isp-kit/config"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/http/httpclix"
"github.com/txix-open/isp-kit/log"
"github.com/txix-open/isp-kit/validator"
"isp-config-service/service/rqlite/goose_store"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/app"
"github.com/txix-open/isp-kit/db"
"isp-config-service/entity"
"isp-config-service/entity/xtypes"
"isp-config-service/migrate/migration"
"isp-config-service/migrations"
"isp-config-service/repository"
)
type Cfg struct {
Db dbx.Config
NewConfigService struct {
Address string
Username string
Password string
}
}
type dbClient struct {
*db.Client
}
func (d dbClient) ExecTransaction(ctx context.Context, requests [][]any) ([]sql.Result, error) {
panic("implement me")
}
func main() {
app, err := app.New(app.WithConfigOptions(
config.WithValidator(validator.Default),
config.WithExtraSource(config.NewYamlConfig("config.yml")),
))
if err != nil {
panic(err)
}
logger := app.Logger()
logger.SetLevel(log.DebugLevel)
ctx := app.Context()
cfg := Cfg{}
err = app.Config().Read(&cfg)
if err != nil {
panic(errors.WithMessage(err, "read config"))
}
pgDb, err := dbx.Open(ctx, cfg.Db, dbx.WithQueryTracer(dbx.NewLogTracer(logger)))
if err != nil {
panic(err)
}
defer pgDb.Close()
fileName := fmt.Sprintf("db_%d.sqlite", time.Now().Unix())
dbClient := dbClient{&db.Client{}}
dbClient.DB, err = sqlx.Open("sqlite3", fileName)
dbClient.DB.MapperFunc(db.ToSnakeCase)
if err != nil {
panic(errors.WithMessage(err, "err opening db"))
}
defer dbClient.Close()
migrationStore := goose_store.NewStore(dbClient.DB.DB)
mr := migration.NewRunner("", migrations.Migrations, logger)
err = mr.Run(ctx, dbClient.DB.DB, goose.WithStore(migrationStore))
if err != nil {
panic(errors.WithMessage(err, "err connecting to db"))
}
moduleRepo := repository.NewModule(dbClient)
configRepo := repository.NewConfig(dbClient)
configSchemaRepo := repository.NewConfigSchema(dbClient)
configHistoryRepo := repository.NewConfigHistory(dbClient)
logger.Info(ctx, "start modules migration")
modules := make([]Module, 0)
err = pgDb.Select(ctx, &modules, "select * from modules")
if err != nil {
panic(errors.WithMessage(err, "err selecting modules"))
}
for _, module := range modules {
result := entity.Module{
Id: module.Id,
Name: module.Name,
CreatedAt: xtypes.Time(module.CreatedAt),
}
_, _ = moduleRepo.Upsert(ctx, result)
}
logger.Info(ctx, "modules migrated")
logger.Info(ctx, "start configs migration")
configs := make([]Config, 0)
err = pgDb.Select(ctx, &configs, "select id, module_id, version, active, created_at, updated_at, data, name from configs")
if err != nil {
panic(errors.WithMessage(err, "err selecting configs"))
}
for _, config := range configs {
result := entity.Config{
Id: config.Id,
Name: config.Name,
ModuleId: config.ModuleId,
Data: config.Data,
Version: config.Version,
Active: xtypes.Bool(config.Active),
AdminId: 0,
CreatedAt: xtypes.Time(config.CreatedAt),
UpdatedAt: xtypes.Time(config.UpdatedAt),
}
err := configRepo.Insert(ctx, result)
if err != nil {
panic(errors.WithMessagef(err, "err inserting config: %s", config.Id))
}
}
logger.Info(ctx, "configs migrated")
logger.Info(ctx, "start config schemas migration")
schemas := make([]ConfigSchema, 0)
err = pgDb.Select(ctx, &schemas, "select * from config_schemas")
if err != nil {
panic(errors.WithMessage(err, "err selecting schemas"))
}
for _, schema := range schemas {
result := entity.ConfigSchema{
Id: schema.Id,
ModuleId: schema.ModuleId,
Data: schema.Schema,
ModuleVersion: schema.Version,
CreatedAt: xtypes.Time(schema.CreatedAt),
UpdatedAt: xtypes.Time(schema.UpdatedAt),
}
err := configSchemaRepo.Upsert(ctx, result)
if err != nil {
panic(errors.WithMessagef(err, "err upserting config_schema: %s", schema.Id))
}
}
logger.Info(ctx, "config schemas migrated")
logger.Info(ctx, "start config history migration")
configHistories := make([]ConfigHistory, 0)
err = pgDb.Select(ctx, &configHistories, "select * from version_config")
if err != nil {
panic(errors.WithMessage(err, "err selecting configs"))
}
for _, history := range configHistories {
result := entity.ConfigHistory{
Id: history.Id,
ConfigId: history.ConfigId,
Data: history.Data,
Version: history.ConfigVersion,
AdminId: 0,
CreatedAt: xtypes.Time(history.CreatedAt),
}
err := configHistoryRepo.InsertV2(ctx, result)
if err != nil {
panic(errors.WithMessagef(err, "err inserting config_history: %s", history.Id))
}
}
logger.Info(ctx, "config history migrated")
logger.Info(ctx, "close sqlite db")
_ = dbClient.Close()
logger.Info(ctx, "loading db to isp-config-service")
sqliteFile, err := os.ReadFile(fileName)
if err != nil {
panic(errors.WithMessage(err, "err opening sqlite file"))
}
cli := httpcli.New(httpcli.WithMiddlewares(httpclix.Log(logger)))
cli.GlobalRequestConfig().BaseUrl = cfg.NewConfigService.Address
cli.GlobalRequestConfig().BasicAuth = &httpcli.BasicAuth{
Username: cfg.NewConfigService.Username,
Password: cfg.NewConfigService.Password,
}
ctx = httpclix.LogConfigToContext(ctx, false, true)
err = cli.Post("/db/load").
Header("Content-Type", "application/octet-stream").
RequestBody(sqliteFile).
StatusCodeToError().
Timeout(120 * time.Second).
DoWithoutResponse(ctx)
if err != nil {
panic(errors.WithMessage(err, "load sqlite file"))
}
logger.Info(ctx, "done!")
}
+86
View File
@@ -0,0 +1,86 @@
package migration
import (
"context"
"database/sql"
"fmt"
"io/fs"
"path/filepath"
"strings"
"time"
"github.com/pkg/errors"
"github.com/pressly/goose/v3"
"github.com/txix-open/isp-kit/log"
)
const (
DialectPostgreSQL = goose.DialectPostgres
DialectSqlite3 = goose.DialectSQLite3
DialectClickhouse = goose.DialectClickHouse
)
type Runner struct {
dialect goose.Dialect
fs fs.FS
logger log.Logger
}
func NewRunner(
dialect goose.Dialect,
fs fs.FS,
logger log.Logger,
) Runner {
return Runner{
dialect: dialect,
fs: fs,
logger: logger,
}
}
func (r Runner) Run(ctx context.Context, db *sql.DB, gooseOpts ...goose.ProviderOption) error {
ctx = log.ToContext(ctx, log.String("worker", "goose_db_migration"))
provider, err := goose.NewProvider(r.dialect, db, r.fs, gooseOpts...)
if err != nil {
return errors.WithMessage(err, "get goose provider")
}
dbVersion, err := provider.GetDBVersion(ctx)
if err != nil {
return errors.WithMessage(err, "get db version")
}
r.logger.Info(ctx, fmt.Sprintf("current db version: %d", dbVersion))
migrations, err := provider.Status(ctx)
if err != nil {
return errors.WithMessage(err, "get status migrations")
}
r.logger.Info(ctx, "print migration list")
if len(migrations) == 0 {
r.logger.Info(ctx, "no migrations")
}
for _, migration := range migrations {
appliedAt := "Pending"
if !migration.AppliedAt.IsZero() {
appliedAt = migration.AppliedAt.Format(time.RFC3339)
}
msg := fmt.Sprintf(
"migration: %s %s %s",
filepath.Base(migration.Source.Path),
strings.ToUpper(string(migration.State)),
appliedAt,
)
r.logger.Info(ctx, msg)
}
result, err := provider.Up(ctx)
if err != nil {
return errors.WithMessage(err, "apply pending migrations")
}
for _, migrationResult := range result {
r.logger.Info(ctx, fmt.Sprintf("applied migration: %s", migrationResult.String()))
}
return nil
}
-42
View File
@@ -1,42 +0,0 @@
package codes
const (
// Common
StartHttpServerError = 1001
ShutdownHttpServerError = 1002
ShutdownHttpServerInfo = 1003
WebsocketError = 1004
WebsocketEmitError = 1005
DatabaseOperationError = 1006
// Raft
InitRaftError = 1007
RestoreFromRepositoryError = 1008
RaftLoggerCode = 1009
BootstrapClusterError = 1010
RaftShutdownError = 1011
RaftShutdownInfo = 1012
// Raft Log
ApplyLogCommandError = 1013
PrepareLogCommandError = 1014
SyncApplyError = 1015
// Raft Cluster
SendDeclarationToLeader = 1016
LeaderClientConnectionError = 1017
LeaderClientDisconnected = 1018
LeaderClientConnected = 1023
LeaderStateChanged = 1024
LeaderManualDeleteLeader = 1025
// Services
DiscoveryServiceSendModulesError = 1019
RoutesServiceSendRoutesError = 1020
ConfigServiceBroadcastConfigError = 1021
// Mux
InitMuxError = 1022
)
+45 -35
View File
@@ -1,41 +1,51 @@
database:
address: "127.0.0.1"
schema: "config_service"
database: "test"
port: "5432"
username: "test"
password: "password"
createSchema: true
moduleName: "config"
configServiceAddress:
ip: localhost
port: 9001
grpcOuterAddress:
ip: ""
ip: isp-config-service
port: 9002
grpcInnerAddress:
ip: 0.0.0.0
port: 9002
moduleName: isp-config-service
ws:
rest:
port: "9001"
ip: "0.0.0.0"
grpc:
port: "9002"
ip: "0.0.0.0"
infraServerPort: 9006
metrics:
gc: true
memory: true
address:
addressConfiguration:
ip: "0.0.0.0"
port: "9551"
path: "/metrics"
logLevel: debug
cluster:
dataDir: ./data
inMemory: true
outerAddress: 127.0.0.1:9001
connectTimeoutSeconds: 5
bootstrapCluster: true
peers:
- 127.0.0.1:9001
maintenanceMode: false
versionConfigCount: 15
keepConfigVersions: 64
credentials:
- username: default
password: 38kPk0upqI5j
perms: ["all"]
- username: monitor
password: monitor
perms: ["ready"]
internalClientCredential: default
rqlite:
DataPath: "data"
NodeID: 1
BootstrapExpect: 1
RaftAddr: "127.0.0.1:9008"
JoinAddrs: "127.0.0.1:9008"
FKConstraints: true
AutoVacInterval: 12h
AutoOptimizeInterval: 23h
JoinAs: default
backup:
Enable: true
Amount: 5
Interval: "24h"
ClearInterval: "168h"
Sub:
Dir: "/app/data/backups/rqlite"
Name: "backup.sqlite.gz"
metricsAutodiscovery:
enable: true
-7
View File
@@ -1,7 +0,0 @@
moduleName: config
registry:
host: nexus.msp.mobi
images:
module: nexus.msp.mobi/msp2/dev/isp-config-service:latest
-31
View File
@@ -1,31 +0,0 @@
//nolint:lll
package conf
import (
"github.com/integration-system/isp-lib/v2/structure"
)
type Configuration struct {
Database structure.DBConfiguration `valid:"required~Required" schema:"База данных,настройка параметров подключения к базе данных"`
GrpcOuterAddress structure.AddressConfiguration `valid:"required~Required" json:"grpcOuterAddress"`
ModuleName string `valid:"required~Required"`
WS WebService `valid:"required~Required" schema:"Конфигурация веб сервиса"`
Metrics structure.MetricConfiguration
Cluster ClusterConfiguration `valid:"required~Required"`
VersionConfigCount int `schema:"Количество сохраняемых старых версий конфигурации"`
}
type ClusterConfiguration struct {
InMemory bool `schema:"Хранить логи и снэпшоты только в памяти"`
BootstrapCluster bool `schema:"Поднимать кластер и объявлять лидером"`
DataDir string `valid:"required~Required" schema:"Пусть до директории для логов и снэпшотов рафта"`
Peers []string `valid:"required~Required" schema:"Адреса всех нод в кластере,формат address:port"`
OuterAddress string `valid:"required~Required" schema:"Внешний адрес ноды"`
ConnectTimeoutSeconds int `valid:"required~Required" schema:"Таймаут подключения"`
}
type WebService struct {
Rest structure.AddressConfiguration `valid:"required~Required"`
Grpc structure.AddressConfiguration `valid:"required~Required"`
WsConnectionReadLimitKB int64 `schema:"Максимальное количество килобайт на чтение по вебсокету,при превышении соединение закрывается с ошибкой"`
}
File renamed without changes.
+22
View File
@@ -0,0 +1,22 @@
package conf
import (
"isp-config-service/service/rqlite"
"github.com/rqlite/rqlite/v9/auth"
"github.com/txix-open/isp-kit/bootstrap"
)
type Local struct {
ConfigServiceAddress bootstrap.ConfigServiceAddr
MaintenanceMode bool
Credentials []auth.Credential
KeepConfigVersions int `validate:"required"`
InternalClientCredential string `validate:"required"`
Rqlite Rqlite
Backup rqlite.Backup
}
type Rqlite struct {
NodeId string `validate:"required"`
}
+4
View File
@@ -0,0 +1,4 @@
package conf
type Remote struct {
}
+292
View File
@@ -0,0 +1,292 @@
//nolint:lll
package api
import (
"context"
"strconv"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/grpc/apierrors"
"google.golang.org/grpc/metadata"
"isp-config-service/domain"
"isp-config-service/entity"
)
type ConfigService interface {
GetActiveConfigByModuleName(ctx context.Context, moduleName string) (*domain.Config, error)
GetConfigsByModuleId(ctx context.Context, moduleId string) ([]domain.Config, error)
CreateUpdateConfig(ctx context.Context, adminId int, req domain.CreateUpdateConfigRequest) (*domain.CreateUpdateConfigResponse, error)
GetConfigById(ctx context.Context, configId string) (*domain.Config, error)
MarkConfigAsActive(ctx context.Context, configId string) error
DeleteConfig(ctx context.Context, id string) error
UpdateConfigName(ctx context.Context, req domain.UpdateConfigNameRequest) error
SyncConfig(ctx context.Context, moduleName string) error
}
type Config struct {
service ConfigService
}
func NewConfig(service ConfigService) Config {
return Config{
service: service,
}
}
// GetActiveConfigByModuleName
// @Summary Метод получения объекта конфигурации по названию модуля
// @Description Возвращает активную конфиграцию по названию модуля
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.GetByModuleNameRequest true "название модуля"
// @Success 200 {object} domain.Config
// @Failure 400 {object} apierrors.Error "`errorCode: 2001` - модуль не найден<br/>`errorCode: 2002` - конфиг не найден"
// @Failure 500 {object} apierrors.Error
// @Router /config/get_active_config_by_module_name [POST]
func (c Config) GetActiveConfigByModuleName(ctx context.Context, req domain.GetByModuleNameRequest) (*domain.Config, error) {
config, err := c.service.GetActiveConfigByModuleName(ctx, req.ModuleName)
switch {
case errors.Is(err, entity.ErrModuleNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeModuleNotFound,
"module not found",
err,
)
case errors.Is(err, entity.ErrConfigNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeConfigNotFound,
"active config not found",
err,
)
case err != nil:
return nil, apierrors.NewInternalServiceError(err)
default:
return config, nil
}
}
// GetConfigsByModuleId
// @Summary Метод получения списка конфигураций по ID модуля
// @Description Возвращает список конфиграции по ID модуля
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.GetByModuleIdRequest true "ID модуля"
// @Success 200 {array} domain.Config
// @Failure 400 {object} apierrors.Error "если идентификатор не указан"
// @Failure 500 {object} apierrors.Error
// @Router /config/get_configs_by_module_id [POST]
func (c Config) GetConfigsByModuleId(ctx context.Context, req domain.GetByModuleIdRequest) ([]domain.Config, error) {
configs, err := c.service.GetConfigsByModuleId(ctx, req.ModuleId)
switch {
case err != nil:
return nil, apierrors.NewInternalServiceError(err)
default:
return configs, nil
}
}
// CreateUpdateConfig
// @Summary Метод обновления конфигурации
// @Description Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу
// @Description В случае обновления рассылает всем подключенным модулям актуальную конфигурацию
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.CreateUpdateConfigRequest true "объект для сохранения"
// @Success 200 {object} domain.CreateUpdateConfigResponse
// @Failure 400 {object} apierrors.Error "`errorCode: 2003` - конфиг не соотвествует текущей схеме<br/>`errorCode: 2002` - указанного id не сущесвует<br/>`errorCode: 2004` - кто-то уже обновил конфигурацию<br/>`errorCode: 2005` - схема конфигурации не найдена<br/>"
// @Failure 500 {object} apierrors.Error
// @Router /config/create_update_config [POST]
func (c Config) CreateUpdateConfig(
ctx context.Context,
authData grpc.AuthData,
req domain.CreateUpdateConfigRequest,
) (*domain.CreateUpdateConfigResponse, error) {
adminIdValue, _ := grpc.StringFromMd("x-admin-id", metadata.MD(authData))
var adminId int
if adminIdValue != "" {
adminId, _ = strconv.Atoi(adminIdValue)
}
resp, err := c.service.CreateUpdateConfig(ctx, adminId, req)
var validationError domain.ConfigValidationError
switch {
case errors.As(err, &validationError):
details := map[string]any{}
for key, value := range validationError.Details {
details[key] = value
}
return nil, apierrors.NewBusinessError(
domain.ErrorCodeInvalidConfig,
"invalid config",
err,
).WithDetails(details)
case errors.Is(err, entity.ErrConfigNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeConfigNotFound,
"config not found",
err,
)
case errors.Is(err, entity.ErrConfigConflictUpdate):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeConfigVersionConflict,
"someone has updated the config",
err,
)
case errors.Is(err, entity.ErrSchemaNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeSchemaNotFound,
"config schema not found",
err,
)
case err != nil:
return nil, apierrors.NewInternalServiceError(err)
default:
return resp, nil
}
}
// GetConfigById
// @Summary Метод получение конфигурации по id
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.IdRequest true "id конфигурации"
// @Success 200 {object} domain.Config
// @Failure 400 {object} apierrors.Error "`errorCode: 2002` - конфиг не найден<br/>"
// @Failure 500 {object} apierrors.Error
// @Router /config/get_config_by_id [POST]
func (c Config) GetConfigById(ctx context.Context, req domain.IdRequest) (*domain.Config, error) {
config, err := c.service.GetConfigById(ctx, req.Id)
switch {
case errors.Is(err, entity.ErrConfigNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeConfigNotFound,
"config not found",
err,
)
case err != nil:
return nil, apierrors.NewInternalServiceError(err)
default:
return config, nil
}
}
// MarkConfigAsActive
// @Summary Метод активации конфигурации для модуля
// @Description Активирует указанную конфигурацию и деактивирует остальные, возвращает активированную конфигурацию
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.IdRequest true "id конфигурации для изменения"
// @Success 200
// @Failure 400 {object} apierrors.Error "`errorCode: 2002` - конфиг не найден<br/>"
// @Failure 500 {object} apierrors.Error
// @Router /config/mark_config_as_active [POST]
func (c Config) MarkConfigAsActive(ctx context.Context, identity domain.IdRequest) error {
err := c.service.MarkConfigAsActive(ctx, identity.Id)
switch {
case errors.Is(err, entity.ErrConfigNotFound):
return apierrors.NewBusinessError(
domain.ErrorCodeConfigNotFound,
"config not found",
err,
)
case err != nil:
return apierrors.NewInternalServiceError(err)
default:
return nil
}
}
// DeleteConfigs
// @Summary Метод удаления объектов конфигурации по идентификаторам
// @Description Возвращает количество удаленных модулей
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body []string true "массив идентификаторов конфигураций"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} apierrors.Error "если не указан массив идентификаторов"
// @Failure 500 {object} apierrors.Error
// @Router /config/delete_config [POST]
func (c Config) DeleteConfigs(ctx context.Context, identities []string) (*domain.DeleteResponse, error) {
configId, err := getSingleId(identities)
if err != nil {
return nil, err
}
err = c.service.DeleteConfig(ctx, configId)
switch {
case errors.Is(err, entity.ErrConfigNotFoundOrActive):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeConfigNotFound,
"config not found or is active",
err,
)
case err != nil:
return nil, apierrors.NewInternalServiceError(err)
default:
return &domain.DeleteResponse{
Deleted: 1,
}, nil
}
}
// UpdateConfigName
// @Summary Метод переименования объекта конфигурации
// @Description Изменеяет название конфигурации без повышения версии и без рассылки события
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.UpdateConfigNameRequest true "id конфигурации и новое название"
// @Success 200
// @Failure 400 {object} apierrors.Error "`errorCode: 2002` - конфиг не найден<br/>"
// @Failure 500 {object} apierrors.Error
// @Router /config/update_config_name [POST]
func (c Config) UpdateConfigName(ctx context.Context, req domain.UpdateConfigNameRequest) error {
err := c.service.UpdateConfigName(ctx, req)
switch {
case errors.Is(err, entity.ErrConfigNotFound):
return apierrors.NewBusinessError(
domain.ErrorCodeConfigNotFound,
"config not found",
err,
)
case err != nil:
return apierrors.NewInternalServiceError(err)
default:
return nil
}
}
// SyncConfig
// @Summary Метод синхронизации актуальной конфигурации пришедешего модуля
// @Description Метод синхронизации актуальной конфигурации пришедешего модуля
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.SyncConfigRequest true "название модуля"
// @Success 200 {object} domain.Config
// @Failure 400 {object} apierrors.Error "`errorCode: 2001` - модуль не найден<br/>`errorCode: 2002` - конфиг не найден"
// @Failure 500 {object} apierrors.Error
// @Router /config/sync_config [POST]
func (c Config) SyncConfig(ctx context.Context, req domain.SyncConfigRequest) error {
err := c.service.SyncConfig(ctx, req.ModuleName)
switch {
case errors.Is(err, entity.ErrModuleNotFound):
return apierrors.NewBusinessError(
domain.ErrorCodeModuleNotFound,
"module not found",
err,
)
case err != nil:
return apierrors.NewInternalServiceError(err)
default:
return nil
}
}
+102
View File
@@ -0,0 +1,102 @@
package api
import (
"context"
"isp-config-service/domain"
"isp-config-service/entity"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
)
type ConfigHistoryService interface {
GetAllVersions(ctx context.Context, configId string) ([]domain.ConfigVersion, error)
Delete(ctx context.Context, id string) error
Purge(ctx context.Context, moduleName string, keepVersions int) (map[string]int, error)
}
type ConfigHistory struct {
service ConfigHistoryService
}
func NewConfigHistory(service ConfigHistoryService) ConfigHistory {
return ConfigHistory{
service: service,
}
}
// GetAllVersion
// @Summary Метод получение старых версий конфигурации
// @Description Возвращает предыдущие версии конфигураций
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.IdRequest true "id конфигурации"
// @Success 200 {array} domain.ConfigVersion
// @Failure 400 {object} apierrors.Error "если не указан массив идентификаторов"
// @Failure 500 {object} apierrors.Error
// @Router /config/get_all_version [POST]
func (c ConfigHistory) GetAllVersion(ctx context.Context, req domain.IdRequest) ([]domain.ConfigVersion, error) {
versions, err := c.service.GetAllVersions(ctx, req.Id)
switch {
case errors.Is(err, entity.ErrConfigNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeConfigNotFound,
"config not found",
err,
)
case err != nil:
return nil, apierrors.NewInternalServiceError(err)
default:
return versions, nil
}
}
// DeleteConfigVersion
// @Summary Метод удаления версии конфигурации
// @Description Возвращает количество удаленных версий
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.IdRequest true "id версии конфигурации"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} apierrors.Error "не указан массив идентификаторов"
// @Failure 500 {object} apierrors.Error
// @Router /config/delete_version [POST]
func (c ConfigHistory) DeleteConfigVersion(ctx context.Context, req domain.IdRequest) (*domain.DeleteResponse, error) {
err := c.service.Delete(ctx, req.Id)
if err != nil {
return nil, apierrors.NewInternalServiceError(err)
}
return &domain.DeleteResponse{
Deleted: 1,
}, nil
}
// PurgeConfigVersions
// @Summary Метод удаления старых версий всех конфигураций модуля, оставляет keepVersions последних версий каждой конфигурации
// @Description Возвращает количество удаленных версий каждой конфигурации
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.PurgeConfigVersionsRequest true "Название модуля, количество оставленных версий конфигурации"
// @Success 200 {object} map[string]int
// @Failure 400 {object} apierrors.Error "`errorCode: 2001` - модуль не найден"
// @Failure 500 {object} apierrors.Error
// @Router /config/purge_versions [POST]
func (c ConfigHistory) PurgeConfigVersions(ctx context.Context, req domain.PurgeConfigVersionsRequest) (map[string]int, error) {
result, err := c.service.Purge(ctx, req.ModuleName, req.KeepVersions)
switch {
case errors.Is(err, entity.ErrModuleNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeModuleNotFound,
"module not found",
err,
)
case err != nil:
return nil, apierrors.NewInternalServiceError(err)
default:
return result, nil
}
}
+80
View File
@@ -0,0 +1,80 @@
package api
import (
"context"
"isp-config-service/domain"
"isp-config-service/entity"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
)
type ConfigSchemaService interface {
SchemaByModuleId(ctx context.Context, moduleId string) (*domain.ConfigSchema, error)
UpdateSchemaByModuleName(ctx context.Context, request domain.UpdateSchemaRequest) error
}
type ConfigSchema struct {
service ConfigSchemaService
}
func NewConfigSchema(service ConfigSchemaService) ConfigSchema {
return ConfigSchema{
service: service,
}
}
// SchemaByModuleId
// @Summary Метод получения схемы конфигурации модуля
// @Description Возвращает текущую json схему конфигурации модуля
// @Tags Схема
// @Accept json
// @Produce json
// @Param body body domain.GetByModuleIdRequest true "идентификатор модуля"
// @Success 200 {object} domain.ConfigSchema
// @Failure 400 {object} apierrors.Error "`errorCode: 2005` - схема для модуля не найдена"
// @Failure 500 {object} apierrors.Error
// @Router /schema/get_by_module_id [POST]
func (c ConfigSchema) SchemaByModuleId(ctx context.Context, request domain.GetByModuleIdRequest) (*domain.ConfigSchema, error) {
schema, err := c.service.SchemaByModuleId(ctx, request.ModuleId)
switch {
case errors.Is(err, entity.ErrSchemaNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeSchemaNotFound,
"config schema not found",
err,
)
case err != nil:
return nil, apierrors.NewInternalServiceError(err)
default:
return schema, nil
}
}
// UpdateSchemaByModuleName
// @Summary Метод обновления схемы конфигурации модуля
// @Description Меняет схему конфигурации модуля на переданную
// @Tags Схема
// @Accept json
// @Produce json
// @Param body body domain.UpdateSchemaRequest true "название модуля и схема конфига"
// @Success 200 {object} any
// @Failure 400 {object} apierrors.Error "`errorCode: 2001` - модуль не найден"
// @Failure 500 {object} apierrors.Error
// @Router /schema/update_by_module_name [POST]
func (c ConfigSchema) UpdateSchemaByModuleName(ctx context.Context, request domain.UpdateSchemaRequest) error {
err := c.service.UpdateSchemaByModuleName(ctx, request)
switch {
case errors.Is(err, entity.ErrModuleNotFound):
return apierrors.NewBusinessError(
domain.ErrorCodeModuleNotFound,
"module not found",
err,
)
case err != nil:
return apierrors.NewInternalServiceError(err)
default:
return nil
}
}
+93
View File
@@ -0,0 +1,93 @@
package api
import (
"context"
"github.com/txix-open/isp-kit/grpc/apierrors"
"isp-config-service/domain"
)
type ModuleService interface {
Status(ctx context.Context) ([]domain.ModuleInfo, error)
Delete(ctx context.Context, id string) error
Connections(ctx context.Context) ([]domain.Connection, error)
}
type Module struct {
service ModuleService
}
func NewModule(service ModuleService) Module {
return Module{
service: service,
}
}
// Status
// @Summary Метод полчения полной информации о состоянии модулей
// @Description Возвращает полное состояние всех модулей в кластере (схема конфигурации, подключенные экземпляры)
// @Tags Модули
// @Accept json
// @Produce json
// @Success 200 {array} domain.ModuleInfo
// @Failure 500 {object} apierrors.Error
// @Router /module/get_modules_info [POST]
func (c Module) Status(ctx context.Context) ([]domain.ModuleInfo, error) {
modulesInfo, err := c.service.Status(ctx)
if err != nil {
return nil, apierrors.NewInternalServiceError(err)
}
return modulesInfo, nil
}
// DeleteModule
// @Summary Метод удаления объектов модулей по идентификаторам
// @Description Возвращает количество удаленных модулей
// @Tags Модули
// @Accept json
// @Produce json
// @Param body body []string true "массив идентификаторов модулей"
// @Success 200 {object} domain.DeleteResponse
// @Failure 500 {object} apierrors.Error
// @Router /module/delete_module [POST]
func (c Module) DeleteModule(ctx context.Context, identities []string) (*domain.DeleteResponse, error) {
id, err := getSingleId(identities)
if err != nil {
return nil, err
}
err = c.service.Delete(ctx, id)
if err != nil {
return nil, apierrors.NewInternalServiceError(err)
}
return &domain.DeleteResponse{
Deleted: len(identities),
}, nil
}
// Connections
// @Summary Метод получения маршрутов
// @Description Возвращает все доступные роуты
// @Tags Модули
// @Accept json
// @Produce json
// @Success 200 {array} domain.Connection
// @Failure 500 {object} apierrors.Error
// @Router /routing/get_routes [POST]
func (c Module) Connections(ctx context.Context) ([]domain.Connection, error) {
connections, err := c.service.Connections(ctx)
if err != nil {
return nil, apierrors.NewInternalServiceError(err)
}
return connections, nil
}
func getSingleId(identities []string) (string, error) {
if len(identities) == 0 {
return "", apierrors.NewBusinessError(domain.ErrorCodeBadRequest, "at least one id is required", nil)
}
if len(identities) > 1 {
return "", apierrors.NewBusinessError(domain.ErrorCodeBadRequest, "accept only single identity", nil)
}
return identities[0], nil
}
+151
View File
@@ -0,0 +1,151 @@
//nolint:lll
package api
import (
"context"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
_ "github.com/txix-open/isp-kit/grpc/apierrors"
"isp-config-service/domain"
"isp-config-service/entity"
)
type Service interface {
All(ctx context.Context) ([]domain.Variable, error)
GetByName(ctx context.Context, name string) (*domain.Variable, error)
Create(ctx context.Context, req domain.CreateVariableRequest) error
Update(ctx context.Context, req domain.UpdateVariableRequest) error
Upsert(ctx context.Context, req []domain.UpsertVariableRequest) error
Delete(ctx context.Context, name string) error
}
type Variable struct {
service Service
}
func NewVariable(service Service) Variable {
return Variable{
service: service,
}
}
// All
// @Summary Метод получения списка всех переменных
// @Tags Переменные
// @Accept json
// @Produce json
// @Success 200 {array} domain.Variable
// @Failure 500 {object} apierrors.Error
// @Router /variable/all [POST]
func (c Variable) All(ctx context.Context) ([]domain.Variable, error) {
return c.service.All(ctx)
}
// GetByName
// @Summary Метод получения переменной по точному совпадению имени
// @Tags Переменные
// @Accept json
// @Produce json
// @Param body body domain.VariableByNameRequest true "тело запроса"
// @Success 200 {object} domain.Variable
// @Failure 400 {object} apierrors.Error "`errorCode: 2006` - переменная по имени не найдена<br/>"
// @Failure 500 {object} apierrors.Error
// @Router /variable/get_by_name [POST]
func (c Variable) GetByName(ctx context.Context, req domain.VariableByNameRequest) (*domain.Variable, error) {
v, err := c.service.GetByName(ctx, req.Name)
switch {
case errors.Is(err, entity.ErrVariableNotFound):
return nil, apierrors.NewBusinessError(domain.ErrorCodeVariableNotFound, "variable by name not found", err)
case err != nil:
return nil, apierrors.NewInternalServiceError(err)
}
return v, nil
}
// Create
// @Summary Метод создания новой переменной
// @Description Создает новую переменную с указанным наименованием и значением
// @Tags Переменные
// @Accept json
// @Produce json
// @Param body body domain.CreateVariableRequest true "тело запроса"
// @Success 200
// @Failure 400 {object} apierrors.Error "`errorCode: 2007` - переменная с таким именем уже существует<br/>"
// @Failure 500 {object} apierrors.Error
// @Router /variable/create [POST]
func (c Variable) Create(ctx context.Context, req domain.CreateVariableRequest) error {
err := c.service.Create(ctx, req)
switch {
case errors.Is(err, entity.ErrVariableAlreadyExists):
return apierrors.NewBusinessError(domain.ErrorCodeVariableAlreadyExists, "variable with the same name already exists", err)
case err != nil:
return apierrors.NewInternalServiceError(err)
}
return nil
}
// Update
// @Summary Метод обновления переменной
// @Description Выполняет обновление переменной по ее названию
// @Tags Переменные
// @Accept json
// @Produce json
// @Param body body domain.UpdateVariableRequest true "тело запроса"
// @Success 200
// @Failure 400 {object} apierrors.Error "`errorCode: 2006` - переменная по имени не найдена<br/>"
// @Failure 500 {object} apierrors.Error
// @Router /variable/update [POST]
func (c Variable) Update(ctx context.Context, req domain.UpdateVariableRequest) error {
err := c.service.Update(ctx, req)
switch {
case errors.Is(err, entity.ErrVariableNotFound):
return apierrors.NewBusinessError(domain.ErrorCodeVariableNotFound, "variable by name not found", err)
case err != nil:
return apierrors.NewInternalServiceError(err)
}
return nil
}
// Upsert
// @Summary Метод добавления/обновления переменных
// @Description Выполняет безусловное добавление/обновление указанных в теле запроса переменных
// @Description Операция выполняется не в транзакции
// @Tags Переменные
// @Accept json
// @Produce json
// @Param body body []domain.UpsertVariableRequest true "тело запроса"
// @Success 200
// @Failure 500 {object} apierrors.Error
// @Router /variable/upsert [POST]
func (c Variable) Upsert(ctx context.Context, req []domain.UpsertVariableRequest) error {
err := c.service.Upsert(ctx, req)
if err != nil {
return apierrors.NewInternalServiceError(err)
}
return nil
}
// Delete
// @Summary Метод удаления переменной
// @Description Переменная связанная с конфигурациями, не может быть удалена
// @Tags Переменные
// @Accept json
// @Produce json
// @Param body body domain.VariableByNameRequest true "тело запроса"
// @Success 200
// @Failure 400 {object} apierrors.Error "`errorCode: 2006` - переменная по имени не найдена<br/>`errorCode: 2008` - переменная используется в конфигурациях<br/>"
// @Failure 500 {object} apierrors.Error
// @Router /variable/delete [POST]
func (c Variable) Delete(ctx context.Context, req domain.VariableByNameRequest) error {
err := c.service.Delete(ctx, req.Name)
switch {
case errors.Is(err, entity.ErrVariableNotFound):
return apierrors.NewBusinessError(domain.ErrorCodeVariableNotFound, "variable by name not found", err)
case errors.Is(err, entity.ErrVariableUsedInConfigs):
return apierrors.NewBusinessError(domain.ErrorCodeVariableUsedInConfigs, "variable used in configs", err)
case err != nil:
return apierrors.NewInternalServiceError(err)
}
return nil
}
-123
View File
@@ -1,123 +0,0 @@
package controller
import (
"isp-config-service/cluster"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/service"
"isp-config-service/store"
"isp-config-service/store/state"
)
var CommonConfig *commonConfig
type commonConfig struct {
rstore *store.Store
}
// @Summary Метод получения объектов конфигурации по идентификаторам
// @Description Возвращает массив конфигураций по запрошенным идентификаторам (все, если массив пустой)
// @Tags Общие конфигурации
// @Accept json
// @Produce json
// @Success 200 {array} entity.CommonConfig
// @Router /common_config/get_configs [POST]
func (c *commonConfig) GetConfigs(identities []string) []entity.CommonConfig {
var response []entity.CommonConfig
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
if len(identities) > 0 {
response = state.CommonConfigs().GetByIds(identities)
} else {
response = state.CommonConfigs().GetAll()
}
})
return response
}
// @Summary Метод обновления общей конфигурации
// @Description Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу
// @Description В случае обновления рассылает всем подключенным модулям актуальную конфигурацию
// @Tags Общие конфигурации
// @Accept json
// @Produce json
// @Param body body entity.CommonConfig true "объект для сохранения"
// @Success 200 {object} entity.CommonConfig
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
// @Failure 500 {object} structure.GrpcError
// @Router /common_config/create_update_config [POST]
func (c *commonConfig) CreateUpdateConfig(config entity.CommonConfig) (*entity.CommonConfig, error) {
var response entity.CommonConfig
now := state.GenerateDate()
config.CreatedAt = now
config.UpdatedAt = now
upsertConfig := cluster.UpsertCommonConfig{
Config: config,
}
if config.Id == "" {
upsertConfig.Config.Id = state.GenerateId()
upsertConfig.Create = true
}
command := cluster.PrepareUpsertCommonConfigCommand(upsertConfig)
err := PerformSyncApplyWithError(command, &response)
if err != nil {
return nil, err
}
return &response, nil
}
// @Summary Метод удаления объектов общей конфигурации по идентификаторам
// @Description Возвращает флаг удаления и набор связей с модулями и конфигурациями, в случае наличия связей deleted всегда false
// @Tags Общие конфигурации
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id общей конфигурации"
// @Success 200 {object} domain.DeleteCommonConfigResponse
// @Failure 500 {object} structure.GrpcError
// @Router /common_config/delete_config [POST]
func (c *commonConfig) DeleteConfigs(req domain.ConfigIdRequest) (*domain.DeleteCommonConfigResponse, error) {
var response domain.DeleteCommonConfigResponse
command := cluster.PrepareDeleteCommonConfigsCommand(req.Id)
err := PerformSyncApplyWithError(command, &response)
if err != nil {
return nil, err
}
return &response, nil
}
// @Summary Метод компиляции итоговой конфигурации для модулей
// @Description Возвращает скомпилированный объект конфигурации
// @Tags Общие конфигурации
// @Accept json
// @Produce json
// @Param body body domain.CompileConfigsRequest true "перечисление идентификаторов общей конфигурации и исхдных конфиг"
// @Success 200 {object} domain.CompiledConfigResponse
// @Router /common_config/compile [POST]
func (c *commonConfig) CompileConfigs(req domain.CompileConfigsRequest) domain.CompiledConfigResponse {
var result map[string]interface{}
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
result = service.ConfigService.CompileConfig(req.Data, state, req.CommonConfigsIdList...)
})
return result
}
// @Summary Метод получения связей общей конфигурациями с конфигурацией модулей
// @Description Возвращает ассоциативный массив, ключами которого являются название модулей, а значения - название конфигурации модуля
// @Tags Общие конфигурации
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id общей конфигурации"
// @Success 200 {object} domain.CommonConfigLinks
// @Router /common_config/get_links [POST]
func (c *commonConfig) GetLinks(req domain.ConfigIdRequest) domain.CommonConfigLinks {
var result domain.CommonConfigLinks
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
result = service.CommonConfig.GetCommonConfigLinks(req.Id, state)
})
return result
}
func NewCommonConfig(rstore *store.Store) *commonConfig {
return &commonConfig{
rstore: rstore,
}
}
-236
View File
@@ -1,236 +0,0 @@
package controller
import (
"time"
"github.com/integration-system/isp-lib/v2/utils"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-config-service/cluster"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/service"
"isp-config-service/store"
"isp-config-service/store/state"
)
var Config *config
type config struct {
rstore *store.Store
}
// @Summary Метод получения объекта конфигурации по названию модуля
// @Description Возвращает активную конфиграцию по названию модуля
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.GetByModuleNameRequest true "название модуля"
// @Success 200 {object} entity.Config
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
// @Failure 500 {object} structure.GrpcError
// @Router /config/get_active_config_by_module_name [POST]
func (c *config) GetActiveConfigByModuleName(request domain.GetByModuleNameRequest) (*entity.Config, error) {
var (
module *entity.Module
config *entity.Config
)
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
module = state.Modules().GetByName(request.ModuleName)
if module != nil {
config = state.Configs().GetActiveByModuleId(module.Id)
}
})
if module == nil {
return nil, status.Errorf(codes.NotFound, "module with name '%s' not found", request.ModuleName)
}
if config == nil {
return nil, status.Errorf(codes.NotFound, "active config for module '%s' not found", request.ModuleName)
}
return config, nil
}
// @Summary Метод получения списка конфигураций по ID модуля
// @Description Возвращает список конфиграции по ID модуля
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.GetByModuleIdRequest true "ID модуля"
// @Success 200 {array} domain.ConfigModuleInfo
// @Failure 400 {object} structure.GrpcError "если идентификатор не указан"
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
// @Failure 500 {object} structure.GrpcError
// @Router /config/get_configs_by_module_id [POST]
func (c *config) GetConfigsByModuleId(request domain.GetByModuleIdRequest) ([]domain.ConfigModuleInfo, error) {
var config []entity.Config
var configInfo []domain.ConfigModuleInfo
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
config = state.Configs().GetByModuleIds([]string{request.ModuleId})
if len(config) == 0 {
return
}
for _, value := range config {
configInfo = append(configInfo, domain.ConfigModuleInfo{
Config: value,
Valid: service.ModuleRegistry.ValidateConfig(value, state),
})
}
})
if len(configInfo) == 0 {
return nil, status.Errorf(codes.NotFound, "configs for module '%s' not found", request.ModuleId)
}
return configInfo, nil
}
// @Summary Метод обновления конфигурации
// @Description Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу
// @Description В случае обновления рассылает всем подключенным модулям актуальную конфигурацию
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.CreateUpdateConfigRequest true "объект для сохранения"
// @Success 200 {object} domain.ConfigModuleInfo
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
// @Failure 500 {object} structure.GrpcError
// @Router /config/create_update_config [POST]
func (c *config) CreateUpdateConfig(config domain.CreateUpdateConfigRequest) (*domain.ConfigModuleInfo, error) {
var response domain.CreateUpdateConfigResponse
now := state.GenerateDate()
config.CreatedAt = now
config.UpdatedAt = now
upsertConfig := cluster.UpsertConfig{
Config: config.Config,
Unsafe: config.Unsafe,
VersionId: state.GenerateId(),
VersionCreateAt: time.Now(),
}
if config.Id == "" {
upsertConfig.Config.Id = state.GenerateId()
upsertConfig.Create = true
}
command := cluster.PrepareUpsertConfigCommand(upsertConfig)
err := PerformSyncApplyWithError(command, &response)
if err != nil {
return nil, err
} else if response.ErrorDetails != nil {
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument, utils.ValidationError, response.ErrorDetails)
}
return response.Config, nil
}
// @Summary Метод активации конфигурации для модуля
// @Description Активирует указанную конфигурацию и деактивирует остальные, возвращает активированную конфигурацию
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id конфигурации для изменения"
// @Success 200 {object} entity.Config "активированная конфигурация"
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
// @Failure 500 {object} structure.GrpcError
// @Router /config/mark_config_as_active [POST]
func (c *config) MarkConfigAsActive(identity domain.ConfigIdRequest) (*entity.Config, error) {
var response entity.Config
command := cluster.PrepareActivateConfigCommand(identity.Id, state.GenerateDate())
err := PerformSyncApplyWithError(command, &response)
if err != nil {
return nil, err
}
return &response, nil
}
// @Summary Метод удаления объектов конфигурации по идентификаторам
// @Description Возвращает количество удаленных модулей
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body []string true "массив идентификаторов конфигураций"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} structure.GrpcError "если не указан массив идентификаторов"
// @Failure 500 {object} structure.GrpcError
// @Router /config/delete_config [POST]
func (c *config) DeleteConfigs(identities []string) (*domain.DeleteResponse, error) {
if len(identities) == 0 {
validationErrors := map[string]string{
"ids": "Required",
}
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument, utils.ValidationError, validationErrors)
}
var response domain.DeleteResponse
command := cluster.PrepareDeleteConfigsCommand(identities)
err := PerformSyncApply(command, &response)
if err != nil {
return nil, err
}
return &response, nil
}
// @Summary Метод удаления версии конфигурации
// @Description Возвращает количество удаленных версий
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id версии конфигурации"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} structure.GrpcError "если не указан массив идентификаторов"
// @Failure 500 {object} structure.GrpcError
// @Router /config/delete_version [POST]
func (c *config) DeleteConfigVersion(req domain.ConfigIdRequest) (*domain.DeleteResponse, error) {
var response domain.DeleteResponse
command := cluster.PrepareDeleteConfigVersionCommand(req.Id)
err := PerformSyncApplyWithError(command, &response)
if err != nil {
return nil, err
}
return &response, nil
}
// @Summary Метод получение старых версий конфигурации
// @Description Возвращает предыдущие версии конфигураций
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id конфигурации"
// @Success 200 {array} entity.VersionConfig
// @Failure 400 {object} structure.GrpcError "если не указан массив идентификаторов"
// @Failure 500 {object} structure.GrpcError
// @Router /config/get_all_version [POST]
func (c *config) GetAllVersion(req domain.ConfigIdRequest) ([]entity.VersionConfig, error) {
var response []entity.VersionConfig
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
response = state.VersionConfig().GetByConfigId(req.Id)
})
return response, nil
}
// @Summary Метод получение актуальной конфигурации конфигурации
// @Description Возвращает актуальную версию конфигурации без дополнительного содержимого (ConfigData)
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id конфигурации"
// @Success 200 {object} entity.Config
// @Failure 400 {object} structure.GrpcError "если не указан идентификатор конфигурации"
// @Failure 500 {object} structure.GrpcError
// @Router /config/get_config_by_id [POST]
func (c *config) GetConfigById(req domain.ConfigIdRequest) (entity.Config, error) {
var response []entity.Config
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
response = state.Configs().GetByIds([]string{req.Id})
})
if len(response) > 0 {
return response[0], nil
}
return entity.Config{}, status.Errorf(codes.NotFound, "config with id '%s' not found", req.Id)
}
func NewConfig(rstore *store.Store) *config {
return &config{
rstore: rstore,
}
}
-72
View File
@@ -1,72 +0,0 @@
package controller
import (
"github.com/integration-system/isp-lib/v2/utils"
log "github.com/integration-system/isp-log"
jsoniter "github.com/json-iterator/go"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-config-service/cluster"
codes2 "isp-config-service/codes"
"isp-config-service/holder"
)
var json = jsoniter.ConfigFastest
func unknownError() error {
return status.Error(codes.Unknown, utils.ServiceError)
}
func PerformSyncApply(command []byte, responsePtr interface{}) error {
applyLogResponse, err := holder.ClusterClient.SyncApply(command)
if err != nil {
cmd := cluster.ParseCommand(command)
log.Warnf(codes2.SyncApplyError, "apply %s: %v", cmd, err)
return unknownError()
}
if applyLogResponse != nil && applyLogResponse.ApplyError != "" {
commandName := cluster.ParseCommand(command).String()
log.WithMetadata(map[string]interface{}{
"result": string(applyLogResponse.Result),
"applyError": applyLogResponse.ApplyError,
"commandName": commandName,
}).Warnf(codes2.SyncApplyError, "apply command")
return unknownError()
}
if responsePtr != nil {
err = json.Unmarshal(applyLogResponse.Result, responsePtr)
if err != nil {
return unknownError()
}
}
return nil
}
func PerformSyncApplyWithError(command []byte, responsePtr interface{}) error {
applyLogResponse, err := holder.ClusterClient.SyncApply(command)
if err != nil {
cmd := cluster.ParseCommand(command)
log.Warnf(codes2.SyncApplyError, "apply %s: %v", cmd, err)
return unknownError()
}
if applyLogResponse != nil && applyLogResponse.ApplyError != "" {
commandName := cluster.ParseCommand(command).String()
log.WithMetadata(map[string]interface{}{
"result": string(applyLogResponse.Result),
"applyError": applyLogResponse.ApplyError,
"commandName": commandName,
}).Warnf(codes2.SyncApplyError, "apply command")
return unknownError()
}
clusterResp := cluster.ResponseWithError{
Response: responsePtr,
}
err = json.Unmarshal(applyLogResponse.Result, &clusterResp)
if err != nil {
return unknownError()
}
if clusterResp.Error != "" {
return status.Error(clusterResp.ErrorCode, clusterResp.Error)
}
return nil
}
+37
View File
@@ -0,0 +1,37 @@
package controller
import (
"context"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/http/apierrors"
"isp-config-service/domain"
)
type metricsService interface {
Autodiscovery(ctx context.Context) (domain.AutodiscoveryResponse, error)
}
type Metrics struct {
svc metricsService
}
func NewMetrics(svc metricsService) Metrics {
return Metrics{svc: svc}
}
// Autodiscovery
// @Summary Метод получения конфигурации для HTTP-based service discovery механизма Prometheus
// @Tags Метрики
// @Accept json
// @Produce json
// @Success 200 {object} domain.AutodiscoveryResponse
// @Failure 500 {object} apierrors.Error
// @Router /internal/metrics/autodiscovery [POST]
func (c Metrics) Autodiscovery(ctx context.Context) (domain.AutodiscoveryResponse, error) {
resp, err := c.svc.Autodiscovery(ctx)
if err != nil {
return nil, apierrors.NewInternalServiceError(errors.WithMessage(err, "autodiscovery"))
}
return resp, nil
}
+121 -95
View File
@@ -1,117 +1,143 @@
package controller
import (
"google.golang.org/grpc/status"
"isp-config-service/cluster"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/service"
"isp-config-service/store"
"isp-config-service/store/state"
"time"
"context"
"github.com/integration-system/isp-lib/v2/utils"
"google.golang.org/grpc/codes"
"github.com/pkg/errors"
"github.com/txix-open/etp/v4"
"github.com/txix-open/etp/v4/msg"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/json"
"github.com/txix-open/isp-kit/log"
"isp-config-service/helpers"
)
const (
defaultEventLifetime = 5 * time.Second
var (
ok = []byte("ok") //nolint:gochecknoglobals
)
var Module *module
type module struct {
rstore *store.Store
type ModuleService interface {
OnConnect(ctx context.Context, conn *etp.Conn, moduleName string) error
OnDisconnect(ctx context.Context, conn *etp.Conn, moduleName string, isNormalClose bool, err error) error
OnError(ctx context.Context, conn *etp.Conn, err error)
OnModuleReady(
ctx context.Context,
conn *etp.Conn,
backend cluster.BackendDeclaration,
) error
OnModuleRequirements(
ctx context.Context,
conn *etp.Conn,
requirements cluster.ModuleRequirements,
) error
OnModuleConfigSchema(
ctx context.Context,
conn *etp.Conn,
data cluster.ConfigData,
) error
}
// @Summary Метод получения полной информации о состоянии модуля
// @Description Возвращает полное состояние всех модулей в кластере (конфигурация, схема конфигурации, подключенные экземпляры)
// @Tags Модули
// @Accept json
// @Produce json
// @Success 200 {array} domain.ModuleInfo
// @Failure 500 {object} structure.GrpcError
// @Router /module/get_modules_info [POST]
func (c *module) GetModulesAggregatedInfo() ([]domain.ModuleInfo, error) {
var response []domain.ModuleInfo
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
response = service.ModuleRegistry.GetAggregatedModuleInfo(state)
})
return response, nil
type Module struct {
service ModuleService
logger log.Logger
}
// @Summary Метод удаления объектов модулей по идентификаторам
// @Description Возвращает количество удаленных модулей
// @Tags Модули
// @Accept json
// @Produce json
// @Param body body []string true "массив идентификаторов модулей"
// @Success 200 {object} domain.DeleteResponse
// @Failure 500 {object} structure.GrpcError
// @Router /module/delete_module [POST]
func (*module) DeleteModules(identities []string) (*domain.DeleteResponse, error) {
if len(identities) == 0 {
validationErrors := map[string]string{
"ids": "Required",
}
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument, utils.ValidationError, validationErrors)
func NewModule(service ModuleService, logger log.Logger) Module {
return Module{
service: service,
logger: logger,
}
}
var deleteResponse domain.DeleteResponse
command := cluster.PrepareDeleteModulesCommand(identities)
err := PerformSyncApply(command, &deleteResponse)
func (m Module) OnConnect(conn *etp.Conn) {
ctx := conn.HttpRequest().Context()
err := conn.HttpRequest().ParseForm()
if err != nil {
return nil, err
m.handleError(ctx, errors.WithMessage(err, "parse form"))
_ = conn.Close()
return
}
return &deleteResponse, err
}
// @Summary Метод получения модуля по имени
// @Tags Модули
// @Accept json
// @Produce json
// @Param body body domain.GetByModuleNameRequest true "название модуля"
// @Success 200 {object} entity.Module
// @Failure 500 {object} structure.GrpcError
// @Failure 404 {object} structure.GrpcError "модуль с указанным названием не найден"
// @Router /module/get_by_name [POST]
func (c *module) GetModuleByName(req domain.GetByModuleNameRequest) (*entity.Module, error) {
var module *entity.Module
c.rstore.VisitReadonlyState(func(readonlyState state.ReadonlyState) {
module = readonlyState.Modules().GetByName(req.ModuleName)
})
if module == nil {
return nil, status.Errorf(codes.NotFound, "module with name '%s' not found", req.ModuleName)
moduleName := helpers.ModuleName(conn)
if moduleName == "" {
m.handleError(ctx, errors.New("module_name is required query param"))
_ = conn.Close()
return
}
return module, nil
}
// @Summary Метод отправки события всем подключенным модулям
// @Tags Модули
// @Accept json
// @Produce json
// @Param body body domain.BroadcastEventRequest true "событие"
// @Success 200 "OK"
// @Failure 500 {object} structure.GrpcError
// @Router /module/broadcast_event [POST]
func (c *module) BroadcastEvent(req domain.BroadcastEventRequest) error {
cmd := cluster.BroadcastEvent{
Event: req.Event,
ModuleNames: req.ModuleNames,
Payload: req.Payload,
PerformUntil: time.Now().UTC().Add(defaultEventLifetime),
}
command := cluster.PrepareBroadcastEventCommand(cmd)
err := PerformSyncApply(command, nil)
err = m.service.OnConnect(ctx, conn, moduleName)
if err != nil {
return err
}
return nil
}
func NewModule(rstore *store.Store) *module {
return &module{
rstore: rstore,
m.handleError(ctx, errors.WithMessage(err, "handle onConnect"))
}
}
func (m Module) OnDisconnect(conn *etp.Conn, err error) {
ctx := conn.HttpRequest().Context()
handleDisconnectErr := m.service.OnDisconnect(
ctx,
conn,
helpers.ModuleName(conn),
etp.IsNormalClose(err),
err,
)
if handleDisconnectErr != nil {
m.handleError(ctx, errors.WithMessage(handleDisconnectErr, "handle onDisconnect"))
}
}
func (m Module) OnError(conn *etp.Conn, err error) {
m.service.OnError(conn.HttpRequest().Context(), conn, err)
}
func (m Module) OnModuleReady(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
backend := cluster.BackendDeclaration{}
err := json.Unmarshal(event.Data, &backend)
if err != nil {
return m.handleError(ctx, errors.WithMessage(err, "unmarshal event data"))
}
err = m.service.OnModuleReady(ctx, conn, backend)
if err != nil {
return m.handleError(ctx, errors.WithMessage(err, "handle onModuleReady"))
}
return ok
}
func (m Module) OnModuleRequirements(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
requirements := cluster.ModuleRequirements{}
err := json.Unmarshal(event.Data, &requirements)
if err != nil {
return m.handleError(ctx, errors.WithMessage(err, "unmarshal event data"))
}
err = m.service.OnModuleRequirements(ctx, conn, requirements)
if err != nil {
return m.handleError(ctx, errors.WithMessage(err, "handle onModuleRequirements"))
}
return ok
}
func (m Module) OnModuleConfigSchema(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
configData := cluster.ConfigData{}
err := json.Unmarshal(event.Data, &configData)
if err != nil {
return m.handleError(ctx, errors.WithMessage(err, "unmarshal event data"))
}
err = m.service.OnModuleConfigSchema(ctx, conn, configData)
if err != nil {
return m.handleError(ctx, errors.WithMessage(err, "handle onModuleConfigSchema"))
}
return ok
}
func (m Module) handleError(
ctx context.Context,
err error,
) []byte {
m.logger.Error(ctx, err)
return []byte(err.Error())
}
-36
View File
@@ -1,36 +0,0 @@
package controller
import (
"github.com/integration-system/isp-lib/v2/structure"
"isp-config-service/store"
"isp-config-service/store/state"
)
var (
Routes *routes
)
type routes struct {
rstore *store.Store
}
// @Summary Метод получения маршрутов
// @Description Возвращает все доступные модули
// @Tags Роуты
// @Accept json
// @Produce json
// @Success 200 {array} structure.BackendDeclaration
// @Router /routing/get_routes [POST]
func (c *routes) GetRoutes() ([]structure.BackendDeclaration, error) {
var response structure.RoutingConfig
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
response = state.Mesh().GetRoutes()
})
return response, nil
}
func NewRoutes(rstore *store.Store) *routes {
return &routes{
rstore: rstore,
}
}
-43
View File
@@ -1,43 +0,0 @@
package controller
import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/store"
"isp-config-service/store/state"
)
var Schema *schema
type schema struct {
rstore *store.Store
}
// @Summary Метод получения схемы конфигурации модуля
// @Description Возвращает текущую json схему конфигурации модуля
// @Tags Схема
// @Accept json
// @Produce json
// @Param body body domain.GetByModuleIdRequest true "идентификатор модуля"
// @Success 200 {object} entity.ConfigSchema
// @Failure 404 {object} structure.GrpcError "если схема для модуля не найдена"
// @Failure 500 {object} structure.GrpcError
// @Router /schema/get_by_module_id [POST]
func (c *schema) GetByModuleId(request domain.GetByModuleIdRequest) (*entity.ConfigSchema, error) {
var result []entity.ConfigSchema
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
result = state.Schemas().GetByModuleIds([]string{request.ModuleId})
})
if len(result) == 0 {
return nil, status.Errorf(codes.NotFound, "schema with moduleId %s not found", request.ModuleId)
}
return &result[0], nil
}
func NewSchema(rstore *store.Store) *schema {
return &schema{
rstore: rstore,
}
}
+40
View File
@@ -0,0 +1,40 @@
services:
isp-config-service-1:
image: "isp-config-service:latest"
container_name: "isp-config-service-1"
hostname: "isp-config-service-1"
restart: unless-stopped
environment:
grpcOuterAddress.ip: isp-config-service-1
rqlite.NodeID: 1
rqlite.BootstrapExpect: 3
rqlite.RaftAddr: "isp-config-service-1:4002"
rqlite.JoinAddrs: "isp-config-service-1:4002,isp-config-service-2:4002,isp-config-service-3:4002"
volumes:
- "./isp-config-service-1/data:/app/data"
isp-config-service-2:
image: "isp-config-service:latest"
container_name: "isp-config-service-2"
hostname: "isp-config-service-2"
restart: unless-stopped
environment:
grpcOuterAddress.ip: isp-config-service-2
rqlite.NodeID: 2
rqlite.BootstrapExpect: 3
rqlite.RaftAddr: "isp-config-service-2:4002"
rqlite.JoinAddrs: "isp-config-service-1:4002,isp-config-service-2:4002,isp-config-service-3:4002"
volumes:
- "./isp-config-service-2/data:/app/data"
isp-config-service-3:
image: "isp-config-service:latest"
container_name: "isp-config-service-3"
hostname: "isp-config-service-3"
restart: unless-stopped
environment:
grpcOuterAddress.ip: isp-config-service-3
rqlite.NodeID: 3
rqlite.BootstrapExpect: 3
rqlite.RaftAddr: "isp-config-service-3:4002"
rqlite.JoinAddrs: "isp-config-service-1:4002,isp-config-service-2:4002,isp-config-service-3:4002"
volumes:
- "./isp-config-service-3/data:/app/data"
+30
View File
@@ -0,0 +1,30 @@
apiVersion: v1
kind: Service
metadata:
name: isp-config-service-internal
spec:
clusterIP: None
publishNotReadyAddresses: True
selector:
app: isp-config-service
ports:
- protocol: TCP
port: 4001
targetPort: 4001
---
apiVersion: v1
kind: Service
metadata:
name: isp-config-service
spec:
selector:
app: isp-config-service
ports:
- protocol: TCP
name: ws
port: 9001
targetPort: 9001
- protocol: TCP
name: grpc
port: 9002
targetPort: 9002
+87
View File
@@ -0,0 +1,87 @@
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: isp-config-service
spec:
selector:
matchLabels:
app: isp-config-service # has to match .spec.template.metadata.labels
serviceName: isp-config-service-internal
replicas: 3
podManagementPolicy: "Parallel"
template:
metadata:
labels:
app: isp-config-service # has to match .spec.selector.matchLabels
spec:
terminationGracePeriodSeconds: 10
imagePullSecrets:
- name: regcred
containers:
- name: isp-config-service
image: isp-config-service:latest
imagePullPolicy: Always
env:
- name: rqlite.NodeID
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: rqlite.BootstrapExpect
value: "3"
- name: rqlite.HttpAddr
value: "0.0.0.0:4001"
- name: rqlite.HttpAdv
value: "$HOSTNAME:4001"
- name: rqlite.RaftAddr
value: "0.0.0.0:4002"
- name: rqlite.RaftAdv
value: "$HOSTNAME:4002"
- name: rqlite.JoinAddrs
value: ""
- name: rqlite.DiscoMode
value: "dns"
- name: rqlite.DiscoConfig
value: "{\"name\":\"isp-config-service-internal\"}"
- name: rqlite.JoinInterval
value: "1s"
- name: rqlite.JoinAttempts
value: "120"
- name: rqlite.RaftClusterRemoveOnShutdown
value: "true"
ports:
- containerPort: 4001
name: rqlite
readinessProbe:
httpGet:
scheme: HTTP
path: /readyz
port: rqlite
httpHeaders:
- name: Authorization
value: Basic bW9uaXRvcjptb25pdG9y
periodSeconds: 5
timeoutSeconds: 2
initialDelaySeconds: 2
livenessProbe:
httpGet:
scheme: HTTP
path: /readyz?noleader
port: rqlite
httpHeaders:
- name: Authorization
value: Basic bW9uaXRvcjptb25pdG9y
initialDelaySeconds: 5
timeoutSeconds: 2
failureThreshold: 3
volumeMounts:
- name: isp-config-service-data
mountPath: /app/data
volumeClaimTemplates:
- metadata:
name: isp-config-service-data
spec:
accessModes: [ "ReadWriteOnce" ]
storageClassName: "local-path"
resources:
requests:
storage: 1Gi
+616 -730
View File
File diff suppressed because it is too large. Load diff
+36
View File
@@ -0,0 +1,36 @@
package domain
import (
"fmt"
"strings"
)
const (
ErrorCodeBadRequest = 400
ErrorCodeModuleNotFound = 2001
ErrorCodeConfigNotFound = 2002
ErrorCodeInvalidConfig = 2003
ErrorCodeConfigVersionConflict = 2004
ErrorCodeSchemaNotFound = 2005
ErrorCodeVariableNotFound = 2006
ErrorCodeVariableAlreadyExists = 2007
ErrorCodeVariableUsedInConfigs = 2008
)
type ConfigValidationError struct {
Details map[string]string
}
func NewConfigValidationError(details map[string]string) ConfigValidationError {
return ConfigValidationError{
Details: details,
}
}
func (e ConfigValidationError) Error() string {
descriptions := make([]string, 0, len(e.Details))
for field, err := range e.Details {
descriptions = append(descriptions, fmt.Sprintf("%s -> %s", field, err))
}
return strings.Join(descriptions, "; ")
}
+33 -16
View File
@@ -1,35 +1,52 @@
package domain
import (
json2 "encoding/json"
"isp-config-service/entity"
"github.com/txix-open/isp-kit/json"
)
type ConfigIdRequest struct {
Id string `json:"id" valid:"required~Required"`
type IdRequest struct {
Id string `validate:"required"`
}
type CompileConfigsRequest struct {
Data map[string]interface{}
CommonConfigsIdList []string
type PurgeConfigVersionsRequest struct {
ModuleName string `validate:"required"`
KeepVersions int `validate:"required"`
}
type GetByModuleIdRequest struct {
ModuleId string `valid:"required~Required"`
ModuleId string `validate:"required"`
}
type GetByModuleNameRequest struct {
ModuleName string `valid:"required~Required"`
ModuleName string `validate:"required"`
}
type BroadcastEventRequest struct {
ModuleNames []string `valid:"required~Required"`
Event string `valid:"required~Required"`
Payload json2.RawMessage
type UpdateSchemaRequest struct {
ModuleName string `validate:"required"`
Schema json.RawMessage `validate:"required" swaggertype:"object"`
}
type CreateUpdateConfigRequest struct {
entity.Config
Unsafe bool
Id string
Name string `validate:"required"`
ModuleId string `validate:"required"`
Version int
Data json.RawMessage `swaggertype:"object"`
Unsafe bool
}
type UpdateConfigNameRequest struct {
Id string `validate:"required"`
NewConfigName string `validate:"required"`
}
type SyncConfigRequest struct {
ModuleName string `validate:"required"`
}
type PrometheusTargets struct {
Targets []string
Labels map[string]string
}
type AutodiscoveryResponse []PrometheusTargets
+46 -28
View File
@@ -3,57 +3,75 @@ package domain
import (
"time"
"github.com/integration-system/isp-lib/v2/config/schema"
"github.com/integration-system/isp-lib/v2/structure"
"isp-config-service/entity"
"github.com/txix-open/isp-kit/json"
)
type DeleteResponse struct {
Deleted int
}
type CreateUpdateConfigResponse struct {
Config
IsChanged bool
}
type ModuleInfo struct {
Id string
Name string
Active bool
CreatedAt time.Time
LastConnectedAt time.Time
LastDisconnectedAt time.Time
Configs []ConfigModuleInfo
ConfigSchema *schema.Schema
LastConnectedAt *time.Time
LastDisconnectedAt *time.Time
ConfigSchema json.RawMessage `swaggertype:"object"`
Status []Connection
RequiredModules []ModuleDependency
CreatedAt time.Time
}
type Connection struct {
Id string
ModuleName string
LibVersion string
Version string
Address structure.AddressConfiguration
Endpoints []structure.EndpointDescriptor
Address Address
Endpoints []EndpointDescriptor
EstablishedAt time.Time
}
type ModuleDependency struct {
Id string
Name string
Required bool
type Address struct {
Ip string
Port string
}
type CommonConfigLinks map[string][]string
type CompiledConfigResponse map[string]interface{}
type DeleteCommonConfigResponse struct {
Deleted bool
Links CommonConfigLinks
type EndpointDescriptor struct {
Path string
Inner bool
}
type CreateUpdateConfigResponse struct {
ErrorDetails map[string]string
Config *ConfigModuleInfo
type Config struct {
Id string
Name string
ModuleId string
Valid bool
Data json.RawMessage `swaggertype:"object"`
Version int
Active bool
CreatedAt time.Time
UpdatedAt time.Time
}
type ConfigModuleInfo struct {
entity.Config
Valid bool
type ConfigVersion struct {
Id string
ConfigId string
ConfigVersion int
Data json.RawMessage `swaggertype:"object"`
CreatedAt time.Time
}
type ConfigSchema struct {
Id string
Version string
ModuleId string
Schema json.RawMessage `swaggertype:"object"`
CreatedAt time.Time
UpdatedAt time.Time
}
+52
View File
@@ -0,0 +1,52 @@
package domain
import (
"time"
"isp-config-service/entity"
)
type Variable struct {
Name string
Description string
Type string
Value string
CreatedAt time.Time
UpdatedAt time.Time
ContainsInConfigs []LinkedConfig
}
type LinkedConfig struct {
Id string
ModuleId string
Name string
}
type CreateVariableRequest struct {
Name string `validate:"required"`
Description string
Type string `validate:"required,oneof=SECRET TEXT"`
Value string `validate:"required"`
}
type UpdateVariableRequest struct {
Name string `validate:"required"`
Description string
Value string `validate:"required"`
}
type UpsertVariableRequest struct {
Name string `validate:"required"`
Description string
Type string `validate:"required,oneof=SECRET TEXT"`
Value string `validate:"required"`
}
type VariableByNameRequest struct {
Name string `validate:"required"`
}
type VariableExtractionResult struct {
VariableLinks []entity.ConfigHasVariable
AbsentVariables []string
}
+26
View File
@@ -0,0 +1,26 @@
package entity
import (
"github.com/txix-open/isp-kit/cluster"
"isp-config-service/entity/xtypes"
)
// nolint: tagliatelle
type Backend struct {
WsConnectionId string `json:"ws_connection_id"`
ModuleId string `json:"module_id"`
Address string `json:"address"`
Version string `json:"version"`
LibVersion string `json:"lib_version"`
ModuleName string `json:"module_name"`
ConfigServiceNodeId string `json:"config_service_node_id"`
Endpoints xtypes.Json[[]cluster.EndpointDescriptor] `json:"endpoints"`
RequiredModules xtypes.Json[[]cluster.ModuleDependency] `json:"required_modules"`
CreatedAt xtypes.Time `json:"created_at"`
MetricsAutodiscovery *xtypes.Json[cluster.MetricsAutodiscovery] `json:"metrics_autodiscovery"`
}
// nolint: tagliatelle
type MetricsAdWrapper struct {
MetricsAutodiscovery xtypes.Json[cluster.MetricsAutodiscovery] `json:"metrics_autodiscovery"`
}
+32 -34
View File
@@ -1,46 +1,44 @@
// nolint: tagliatelle
package entity
import (
"time"
"github.com/integration-system/isp-lib/v2/config/schema"
"isp-config-service/entity/xtypes"
)
type ConfigData map[string]interface{}
type Config struct {
//nolint
tableName string `pg:"?db_schema.configs" json:"-"`
Id string `json:"id"`
Name string `json:"name" valid:"required~Required"`
CommonConfigs []string `json:"commonConfigs" pg:",array"`
Description string `json:"description"`
ModuleId string `json:"moduleId" valid:"required~Required"`
Version int32 `json:"version" pg:",null"`
Active bool `json:"active" pg:",null"`
CreatedAt time.Time `json:"createdAt" pg:",null"`
UpdatedAt time.Time `json:"updatedAt" pg:",null"`
Data ConfigData `json:"data,omitempty" pg:",notnull"`
Id string `json:"id"`
Name string `json:"name"`
ModuleId string `json:"module_id"`
Data []byte `json:"data"`
Version int `json:"version"`
Active xtypes.Bool `json:"active"`
AdminId int `json:"admin_id"`
CreatedAt xtypes.Time `json:"created_at"`
UpdatedAt xtypes.Time `json:"updated_at"`
}
type CommonConfig struct {
//nolint
tableName string `pg:"?db_schema.common_configs" json:"-"`
Id string `json:"id"`
Name string `json:"name" valid:"required~Required"`
Description string `json:"description"`
CreatedAt time.Time `json:"createdAt" pg:",null"`
UpdatedAt time.Time `json:"updatedAt" pg:",null"`
Data ConfigData `json:"data" pg:",notnull"`
type ConfigMetaWithVariable struct {
Id string `json:"id"`
Name string `json:"name"`
ModuleId string `json:"module_id"`
VariableName string `json:"variable_name"`
Active xtypes.Bool `json:"active"`
}
type ConfigHistory struct {
Id string `json:"id"`
ConfigId string `json:"config_id"`
Data []byte `json:"data"`
Version int `json:"version"`
AdminId int `json:"admin_id"`
CreatedAt xtypes.Time `json:"created_at"`
}
type ConfigSchema struct {
//nolint
tableName string `pg:"?db_schema.config_schemas" json:"-"`
Id string `json:"id"`
Version string
ModuleId string
Schema schema.Schema
CreatedAt time.Time
UpdatedAt time.Time
Id string `json:"id"`
ModuleId string `json:"module_id"`
Data []byte `json:"data"`
ModuleVersion string `json:"module_version"`
CreatedAt xtypes.Time `json:"created_at"`
UpdatedAt xtypes.Time `json:"updated_at"`
}
+16
View File
@@ -0,0 +1,16 @@
package entity
import (
"github.com/pkg/errors"
)
var (
ErrConfigNotFound = errors.New("no active config")
ErrModuleNotFound = errors.New("module not found")
ErrSchemaNotFound = errors.New("config schema not found")
ErrConfigNotFoundOrActive = errors.New("config not found or markers as active")
ErrConfigConflictUpdate = errors.New("config conflict update")
ErrVariableNotFound = errors.New("variable not found")
ErrVariableAlreadyExists = errors.New("variable already exists")
ErrVariableUsedInConfigs = errors.New("variable used in configs")
)
+52
View File
@@ -0,0 +1,52 @@
package entity
import (
"fmt"
"isp-config-service/entity/xtypes"
)
type Event struct {
Id int `json:"id"`
Payload xtypes.Json[EventPayload] `json:"payload"`
}
func NewEvent(payload EventPayload) Event {
return Event{
Payload: xtypes.Json[EventPayload]{
Value: payload,
},
}
}
func (e Event) Key() string {
switch {
case e.Payload.Value.ConfigUpdated != nil:
return fmt.Sprintf("config_updated_%s", e.Payload.Value.ConfigUpdated.ModuleId)
case e.Payload.Value.ModuleReady != nil:
return fmt.Sprintf("module_lifecycle_%s", e.Payload.Value.ModuleReady.ModuleId)
case e.Payload.Value.ModuleDisconnected != nil:
return fmt.Sprintf("module_lifecycle_%s", e.Payload.Value.ModuleDisconnected.ModuleId)
default:
return ""
}
}
// nolint:tagliatelle
type EventPayload struct {
ConfigUpdated *PayloadConfigUpdated `json:",omitempty"`
ModuleReady *PayloadModuleReady `json:",omitempty"`
ModuleDisconnected *PayloadModuleDisconnected `json:",omitempty"`
}
type PayloadConfigUpdated struct {
ModuleId string
}
type PayloadModuleReady struct {
ModuleId string
}
type PayloadModuleDisconnected struct {
ModuleId string
}
+9 -8
View File
@@ -1,13 +1,14 @@
package entity
import "time"
import (
"isp-config-service/entity/xtypes"
)
// nolint:tagliatelle
type Module struct {
//nolint
tableName string `pg:"?db_schema.modules" json:"-"`
Id string `json:"id"`
Name string `json:"name" valid:"required~Required"`
CreatedAt time.Time `json:"createdAt" pg:",null"`
LastConnectedAt time.Time `json:"lastConnectedAt"`
LastDisconnectedAt time.Time `json:"lastDisconnectedAt"`
Id string `json:"id"`
Name string `json:"name"`
LastConnectedAt *xtypes.Time `json:"last_connected_at"`
LastDisconnectedAt *xtypes.Time `json:"last_disconnected_at"`
CreatedAt xtypes.Time `json:"created_at"`
}
+20
View File
@@ -0,0 +1,20 @@
// nolint:tagliatelle
package entity
import (
"isp-config-service/entity/xtypes"
)
type Variable struct {
Name string `json:"name"`
Description string `json:"description"`
Type string `json:"type"`
Value string `json:"value"`
CreatedAt xtypes.Time `json:"created_at"`
UpdatedAt xtypes.Time `json:"updated_at"`
}
type ConfigHasVariable struct {
ConfigId string `json:"config_id"`
VariableName string `json:"variable_name"`
}
-15
View File
@@ -1,15 +0,0 @@
package entity
import (
"time"
)
type VersionConfig struct {
//nolint
tableName string `pg:"?db_schema.version_config" json:"-"`
Id string
ConfigId string
ConfigVersion int32
Data ConfigData `json:"data,omitempty" pg:",notnull"`
CreatedAt time.Time
}
+23
View File
@@ -0,0 +1,23 @@
package xtypes
type Bool bool
func (l Bool) MarshalJSON() ([]byte, error) {
return l.MarshalText()
}
func (l *Bool) UnmarshalJSON(data []byte) error {
return l.UnmarshalText(data)
}
func (l Bool) MarshalText() ([]byte, error) {
if l {
return []byte("1"), nil
}
return []byte("0"), nil
}
func (l *Bool) UnmarshalText(data []byte) error {
*l = string(data) == "1"
return nil
}
+44
View File
@@ -0,0 +1,44 @@
package xtypes
import (
"strconv"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/json"
)
type Json[T any] struct {
Value T
}
func (l Json[T]) MarshalJSON() ([]byte, error) {
data, err := l.MarshalText()
if err != nil {
return nil, err
}
return []byte(strconv.Quote(string(data))), nil
}
func (l *Json[T]) UnmarshalJSON(data []byte) error {
s, err := strconv.Unquote(string(data))
if err != nil {
return errors.WithMessage(err, "unquote text")
}
return l.UnmarshalText([]byte(s))
}
func (l Json[T]) MarshalText() ([]byte, error) {
data, err := json.Marshal(l.Value)
if err != nil {
return nil, errors.WithMessage(err, "marshal json")
}
return data, nil
}
func (l *Json[T]) UnmarshalText(data []byte) error {
err := json.Unmarshal(data, &l.Value)
if err != nil {
return errors.WithMessage(err, "unmarshal json")
}
return nil
}
+36
View File
@@ -0,0 +1,36 @@
package xtypes
import (
"strconv"
"time"
"github.com/pkg/errors"
)
type Time time.Time
func (l Time) MarshalJSON() ([]byte, error) {
return l.MarshalText()
}
func (l *Time) UnmarshalJSON(data []byte) error {
return l.UnmarshalText(data)
}
func (l Time) MarshalText() ([]byte, error) {
t := time.Time(l)
value := strconv.Itoa(int(t.Unix()))
return []byte(value), nil
}
func (l *Time) UnmarshalText(data []byte) error {
if string(data) == "null" {
return nil
}
value, err := strconv.Atoi(string(data))
if err != nil {
return errors.WithMessagef(err, "parse int: %s", string(data))
}
*l = Time(time.Unix(int64(value), 0))
return nil
}
+112 -88
View File
@@ -1,102 +1,126 @@
module isp-config-service
go 1.19
go 1.25.0
require (
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d
github.com/cenkalti/backoff/v4 v4.2.0
github.com/go-pg/pg/v9 v9.2.1
github.com/hashicorp/raft v1.3.11
github.com/hashicorp/raft-boltdb/v2 v2.2.2
github.com/integration-system/bellows v1.0.1
github.com/integration-system/isp-etp-go/v2 v2.1.3
github.com/integration-system/isp-lib/v2 v2.11.0
github.com/integration-system/isp-log v1.2.0
github.com/integration-system/net-mux v1.0.1
github.com/json-iterator/go v1.1.12
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826
github.com/pkg/errors v0.9.1
github.com/satori/go.uuid v1.2.0
github.com/xeipuuv/gojsonschema v1.2.0
google.golang.org/grpc v1.51.0
replace (
github.com/armon/go-metrics => github.com/hashicorp/go-metrics v0.5.1
github.com/mattn/go-sqlite3 => github.com/rqlite/go-sqlite3 v1.42.0
golang.org/x/text => golang.org/x/text v0.3.8
)
require (
github.com/KyleBanks/depth v1.2.1 // indirect
github.com/andybalholm/brotli v1.0.4 // indirect
github.com/armon/go-metrics v0.4.1 // indirect
github.com/boltdb/bolt v1.3.1 // indirect
github.com/buaazp/fasthttprouter v0.1.1 // indirect
github.com/codemodus/kace v0.5.1 // indirect
github.com/fatih/color v1.13.0 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/go-openapi/jsonpointer v0.19.5 // indirect
github.com/go-openapi/jsonreference v0.20.0 // indirect
github.com/go-openapi/spec v0.20.7 // indirect
github.com/go-openapi/swag v0.22.3 // indirect
github.com/go-pg/zerochecker v0.2.0 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/gorilla/websocket v1.4.2 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-hclog v1.3.1 // indirect
github.com/Masterminds/squirrel v1.5.4
github.com/google/uuid v1.6.0
github.com/pkg/errors v0.9.1
github.com/pressly/goose/v3 v3.26.0
github.com/prometheus/client_golang v1.23.2
github.com/rqlite/gorqlite v0.0.0-20250609141355-ac86a4a1c9a8
github.com/rqlite/rqlite-disco-clients v0.0.0-20250205044118-8ada2b350099
github.com/rqlite/rqlite/v9 v9.3.2
github.com/stretchr/testify v1.11.1
github.com/tidwall/gjson v1.18.0
github.com/txix-open/etp/v4 v4.0.1
github.com/txix-open/go-cmp v0.0.0-20240401171944-16b203530f60
github.com/txix-open/isp-kit v1.63.3
github.com/xeipuuv/gojsonschema v1.2.0
golang.org/x/sync v0.18.0
google.golang.org/grpc v1.77.0
)
require (
github.com/armon/go-metrics v0.5.4 // indirect
github.com/aws/aws-sdk-go-v2 v1.40.0 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.3 // indirect
github.com/aws/aws-sdk-go-v2/config v1.32.0 // indirect
github.com/aws/aws-sdk-go-v2/credentials v1.19.0 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.14 // indirect
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.20.9 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.14 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.14 // indirect
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.14 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.3 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.5 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.14 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.14 // indirect
github.com/aws/aws-sdk-go-v2/service/s3 v1.91.1 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.0.1 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.30.4 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.8 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.41.1 // indirect
github.com/aws/smithy-go v1.23.2 // indirect
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/buger/jsonparser v1.1.1 // indirect
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/coder/websocket v1.8.14 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/fatih/color v1.18.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.11 // indirect
github.com/getsentry/sentry-go v0.38.0 // indirect
github.com/go-faker/faker/v4 v4.7.0 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect
github.com/hashicorp/go-hclog v1.6.3 // indirect
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
github.com/hashicorp/go-msgpack v0.5.5 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/go-uuid v1.0.1 // indirect
github.com/hashicorp/golang-lru v0.5.4 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/integration-system/go-cmp v0.0.0-20190131081942-ac5582987a2f // indirect
github.com/integration-system/jsonschema v1.0.1 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/klauspost/compress v1.15.12 // indirect
github.com/lib/pq v1.10.7 // indirect
github.com/magiconair/properties v1.8.6 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.16 // indirect
github.com/hashicorp/go-metrics v0.5.4 // indirect
github.com/hashicorp/go-msgpack v1.1.5 // indirect
github.com/hashicorp/go-msgpack/v2 v2.1.5 // indirect
github.com/hashicorp/go-uuid v1.0.3 // indirect
github.com/hashicorp/golang-lru v1.0.2 // indirect
github.com/hashicorp/raft v1.7.3 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mailru/easyjson v0.9.1 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-sqlite3 v1.14.32 // indirect
github.com/mfridman/interpolate v0.0.2 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/onsi/ginkgo v1.15.0 // indirect
github.com/onsi/gomega v1.10.5 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.0.6 // indirect
github.com/pressly/goose v2.7.0+incompatible // indirect
github.com/profefe/profefe v0.0.0-20210412073930-18342f204d75 // indirect
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect
github.com/segmentio/asm v1.2.0 // indirect
github.com/segmentio/encoding v0.3.6 // indirect
github.com/sirupsen/logrus v1.9.0 // indirect
github.com/spf13/afero v1.9.3 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.14.0 // indirect
github.com/subosito/gotenv v1.4.1 // indirect
github.com/swaggo/files v0.0.0-20220728132757-551d4a08d97a // indirect
github.com/swaggo/http-swagger v1.3.3 // indirect
github.com/swaggo/swag v1.8.8 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.43.0 // indirect
github.com/vmihailenco/bufpool v0.1.11 // indirect
github.com/vmihailenco/msgpack/v4 v4.3.12 // indirect
github.com/vmihailenco/tagparser v0.1.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.67.3 // indirect
github.com/prometheus/procfs v0.19.2 // indirect
github.com/rqlite/raft-boltdb/v2 v2.0.0-20230523104317-c08e70f4de48 // indirect
github.com/rqlite/sql v0.0.0-20251114131613-ef07423e7137 // indirect
github.com/sethvargo/go-retry v0.3.0 // indirect
github.com/tidwall/match v1.2.0 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/txix-open/bellows v1.2.0 // indirect
github.com/txix-open/jsonschema v1.3.0 // indirect
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb // indirect
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
go.etcd.io/bbolt v1.3.6 // indirect
golang.org/x/crypto v0.3.0 // indirect
golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 // indirect
golang.org/x/net v0.2.0 // indirect
golang.org/x/sys v0.2.0 // indirect
golang.org/x/text v0.4.0 // indirect
golang.org/x/tools v0.3.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto v0.0.0-20221118155620-16455021b5e6 // indirect
google.golang.org/protobuf v1.28.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
go.etcd.io/bbolt v1.4.3 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.63.0 // indirect
go.opentelemetry.io/otel v1.38.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0 // indirect
go.opentelemetry.io/otel/metric v1.38.0 // indirect
go.opentelemetry.io/otel/sdk v1.38.0 // indirect
go.opentelemetry.io/otel/trace v1.38.0 // indirect
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.1 // indirect
go.yaml.in/yaml/v2 v2.4.3 // indirect
golang.org/x/crypto v0.45.0 // indirect
golang.org/x/net v0.47.0 // indirect
golang.org/x/sys v0.38.0 // indirect
golang.org/x/text v0.31.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20251111163417-95abcf5c77ba // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20251124214823-79d6a2a48846 // indirect
google.golang.org/protobuf v1.36.10 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
mellium.im/sasl v0.3.0 // indirect
nhooyr.io/websocket v1.8.7 // indirect
)
+296 -703
View File
File diff suppressed because it is too large. Load diff
-68
View File
@@ -1,68 +0,0 @@
//nolint:lll
package helper
import (
"github.com/integration-system/isp-lib/v2/structure"
"isp-config-service/controller"
"isp-config-service/domain"
"isp-config-service/entity"
)
type Handlers struct {
// ===== MODULE =====
DeleteModules func(identities []string) (*domain.DeleteResponse, error) `method:"delete_module" group:"module" inner:"true"`
GetModulesInfo func() ([]domain.ModuleInfo, error) `method:"get_modules_info" group:"module" inner:"true"`
GetModuleByName func(req domain.GetByModuleNameRequest) (*entity.Module, error) `method:"get_by_name" group:"module" inner:"true"`
BroadcastEvent func(req domain.BroadcastEventRequest) error `method:"broadcast_event" group:"module" inner:"true"`
// ===== CONFIG =====
GetActiveConfigByModuleName func(request domain.GetByModuleNameRequest) (*entity.Config, error) `method:"get_active_config_by_module_name" group:"config" inner:"true"`
GetConfigsByModuleId func(request domain.GetByModuleIdRequest) ([]domain.ConfigModuleInfo, error) `method:"get_configs_by_module_id" group:"config" inner:"true"`
CreateUpdateConfig func(config domain.CreateUpdateConfigRequest) (*domain.ConfigModuleInfo, error) `method:"create_update_config" group:"config" inner:"true"`
MarkConfigAsActive func(identity domain.ConfigIdRequest) (*entity.Config, error) `method:"mark_config_as_active" group:"config" inner:"true"`
DeleteConfig func(identities []string) (*domain.DeleteResponse, error) `method:"delete_config" group:"config" inner:"true"`
DeleteVersion func(identity domain.ConfigIdRequest) (*domain.DeleteResponse, error) `method:"delete_version" group:"config" inner:"true"`
GetAllVersion func(identity domain.ConfigIdRequest) ([]entity.VersionConfig, error) `method:"get_all_version" group:"config" inner:"true"`
GetConfigByID func(identity domain.ConfigIdRequest) (entity.Config, error) `method:"get_config_by_id" group:"config" inner:"true"`
// ===== COMMON CONFIG =====
GetCommonConfigs func(identities []string) []entity.CommonConfig `method:"get_configs" group:"common_config" inner:"true"`
CreateUpdateCommonConfig func(config entity.CommonConfig) (*entity.CommonConfig, error) `method:"create_update_config" group:"common_config" inner:"true"`
DeleteCommonConfig func(req domain.ConfigIdRequest) (*domain.DeleteCommonConfigResponse, error) `method:"delete_config" group:"common_config" inner:"true"`
CompileConfigs func(req domain.CompileConfigsRequest) domain.CompiledConfigResponse `method:"compile" group:"common_config" inner:"true"`
GetLinks func(req domain.ConfigIdRequest) domain.CommonConfigLinks `method:"get_links" group:"common_config" inner:"true"`
// ===== ROUTING =====
GetRoutes func() ([]structure.BackendDeclaration, error) `method:"get_routes" group:"routing" inner:"true"`
// ===== SCHEMA =====
GetSchemaByModuleId func(domain.GetByModuleIdRequest) (*entity.ConfigSchema, error) `method:"get_by_module_id" group:"schema" inner:"true"`
}
func GetHandlers() *Handlers {
return &Handlers{
DeleteModules: controller.Module.DeleteModules,
GetModulesInfo: controller.Module.GetModulesAggregatedInfo,
GetModuleByName: controller.Module.GetModuleByName,
BroadcastEvent: controller.Module.BroadcastEvent,
GetActiveConfigByModuleName: controller.Config.GetActiveConfigByModuleName,
GetConfigsByModuleId: controller.Config.GetConfigsByModuleId,
CreateUpdateConfig: controller.Config.CreateUpdateConfig,
MarkConfigAsActive: controller.Config.MarkConfigAsActive,
DeleteConfig: controller.Config.DeleteConfigs,
DeleteVersion: controller.Config.DeleteConfigVersion,
GetAllVersion: controller.Config.GetAllVersion,
GetConfigByID: controller.Config.GetConfigById,
GetCommonConfigs: controller.CommonConfig.GetConfigs,
CreateUpdateCommonConfig: controller.CommonConfig.CreateUpdateConfig,
DeleteCommonConfig: controller.CommonConfig.DeleteConfigs,
CompileConfigs: controller.CommonConfig.CompileConfigs,
GetLinks: controller.CommonConfig.GetLinks,
GetRoutes: controller.Routes.GetRoutes,
GetSchemaByModuleId: controller.Schema.GetByModuleId,
}
}
+33
View File
@@ -0,0 +1,33 @@
package helpers
import (
"net"
"github.com/pkg/errors"
"github.com/txix-open/etp/v4"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/log"
"isp-config-service/entity"
)
func ModuleName(conn *etp.Conn) string {
return conn.HttpRequest().Form.Get("module_name")
}
func SplitAddress(backend entity.Backend) (cluster.AddressConfiguration, error) {
host, port, err := net.SplitHostPort(backend.Address)
if err != nil {
return cluster.AddressConfiguration{}, errors.WithMessagef(err, "split backend %s address: %s", backend.ModuleId, backend.Address)
}
return cluster.AddressConfiguration{
IP: host,
Port: port,
}, nil
}
func LogFields(conn *etp.Conn) []log.Field {
return []log.Field{
log.String("moduleName", ModuleName(conn)),
log.String("connId", conn.Id()),
}
}
-14
View File
@@ -1,14 +0,0 @@
package holder
import (
"net/http"
etp "github.com/integration-system/isp-etp-go/v2"
"isp-config-service/cluster"
)
var (
ClusterClient *cluster.Client
EtpServer etp.Server
HTTPServer *http.Server
)
+23 -236
View File
@@ -1,262 +1,49 @@
package main
import (
"context"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/integration-system/isp-etp-go/v2"
"github.com/integration-system/isp-lib/v2/backend"
"github.com/integration-system/isp-lib/v2/bootstrap"
"github.com/integration-system/isp-lib/v2/config"
"github.com/integration-system/isp-lib/v2/metric"
"github.com/integration-system/isp-lib/v2/structure"
"github.com/integration-system/isp-lib/v2/utils"
log "github.com/integration-system/isp-log"
mux "github.com/integration-system/net-mux"
"isp-config-service/cluster"
"isp-config-service/codes"
"isp-config-service/conf"
"isp-config-service/controller"
"isp-config-service/helper"
"isp-config-service/holder"
"isp-config-service/model"
"isp-config-service/raft"
"isp-config-service/service"
"isp-config-service/store"
"isp-config-service/store/state"
"isp-config-service/subs"
)
"isp-config-service/routes"
"isp-config-service/service/startup"
const (
moduleName = "config"
defaultWsConnectionReadLimit int64 = 4 << 20 // 4 MB
"github.com/txix-open/isp-kit/bootstrap"
"github.com/txix-open/isp-kit/shutdown"
)
var (
version = "0.1.0"
muxer mux.Mux
version = "1.0.0"
)
func init() {
config.InitConfig(&conf.Configuration{})
if utils.LOG_LEVEL != "" {
_ = log.SetLevel(utils.LOG_LEVEL)
}
}
// @title ISP configuration service
// @version 2.4.1
// @description Сервис управления конфигурацией модулей ISP кластера
// @title isp-config-service
// @version 3.0.0
// @description Модуль управления конфигурациями
// @license.name GNU GPL v3.0
// @host localhost:9003
// @host localhost:9000
// @BasePath /api/config
//go:generate swag init --parseDependency
//go:generate rm -f docs/swagger.json
//go:generate rm -f docs/swagger.json docs/docs.go
func main() {
cfg := config.Get().(*conf.Configuration)
handlers := helper.GetHandlers()
endpoints := backend.GetEndpoints(cfg.ModuleName, handlers)
address := cfg.GrpcOuterAddress
if address.IP == "" {
ip, err := getOutboundIP()
if err != nil {
panic(err)
}
address.IP = ip
}
declaration := structure.BackendDeclaration{
ModuleName: cfg.ModuleName,
Version: version,
LibVersion: bootstrap.LibraryVersion,
Endpoints: endpoints,
Address: address,
}
boot := bootstrap.New(version, conf.Remote{}, routes.EndpointDescriptors())
app := boot.App
logger := app.Logger()
connectionReadLimit := defaultWsConnectionReadLimit
if cfg.WS.WsConnectionReadLimitKB > 0 {
//nolint:gomnd
connectionReadLimit = cfg.WS.WsConnectionReadLimitKB << 10
}
cluster.WsConnectionReadLimit = connectionReadLimit
cfg.Database.Password = fmt.Sprintf("%s%s", cfg.Database.Password, os.Getenv("DB_PASSPART"))
model.DbClient.ReceiveConfiguration(cfg.Database)
httpListener, raftListener, err := initMultiplexer(cfg.WS.Rest)
startup, err := startup.New(boot)
if err != nil {
log.Fatalf(codes.InitMuxError, "init mux: %v", err)
boot.Fatal(err)
}
app.AddRunners(startup)
app.AddClosers(startup.Closers()...)
_, raftStore := initRaft(raftListener, cfg.Cluster, declaration)
initWebsocket(connectionReadLimit, httpListener, raftStore)
initGrpc(cfg.WS.Grpc, raftStore)
metric.InitProfiling(cfg.ModuleName)
metric.InitCollectors(cfg.Metrics, structure.MetricConfiguration{})
metric.InitHttpServer(cfg.Metrics)
gracefulShutdown()
}
func initMultiplexer(addressConfiguration structure.AddressConfiguration) (net.Listener, net.Listener, error) {
outerAddr, err := net.ResolveTCPAddr("tcp4", addressConfiguration.GetAddress())
if err != nil {
return nil, nil, fmt.Errorf("resolve outer address: %v", err)
}
tcpListener, err := net.ListenTCP("tcp4", outerAddr)
if err != nil {
return nil, nil, fmt.Errorf("create tcp transport: %v", err)
}
muxer = mux.New(tcpListener)
httpListener := muxer.Match(mux.HTTP1())
raftListener := muxer.Match(mux.Any())
go func() {
if err := muxer.Serve(); err != nil {
log.Fatalf(codes.InitMuxError, "serve mux: %v", err)
}
}()
return httpListener, raftListener, nil
}
func initWebsocket(connectionReadLimit int64, listener net.Listener, raftStore *store.Store) {
etpConfig := etp.ServerConfig{
InsecureSkipVerify: true,
ConnectionReadLimit: connectionReadLimit,
}
etpServer := etp.NewServer(context.Background(), etpConfig)
subs.NewSocketEventHandler(etpServer, raftStore).SubscribeAll()
mux := http.NewServeMux()
mux.HandleFunc("/isp-etp/", etpServer.ServeHttp)
httpServer := &http.Server{Handler: mux}
go func() {
if err := httpServer.Serve(listener); err != nil && err != http.ErrServerClosed {
log.Fatalf(codes.StartHttpServerError, "http server closed: %v", err)
}
}()
holder.EtpServer = etpServer
holder.HTTPServer = httpServer
}
func initRaft(listener net.Listener, clusterCfg conf.ClusterConfiguration,
declaration structure.BackendDeclaration) (*cluster.Client, *store.Store) {
raftState, err := store.NewStateFromRepository()
if err != nil {
log.Fatal(codes.RestoreFromRepositoryError, err)
return nil, nil
}
raftStore := store.NewStateStore(raftState)
r, err := raft.NewRaft(listener, clusterCfg, raftStore)
if err != nil {
log.Fatalf(codes.InitRaftError, "unable to create raft server. %v", err)
return nil, nil
}
clusterClient := cluster.NewRaftClusterClient(r, declaration, func(address string) {
go raftStore.VisitState(func(s state.WritableState) {
cfg := config.Get().(*conf.Configuration)
addr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
panic(err) // must never occurred
}
port := cfg.GrpcOuterAddress.Port
addressConfiguration := structure.AddressConfiguration{Port: port, IP: addr.IP.String()}
back := structure.BackendDeclaration{ModuleName: cfg.ModuleName, Address: addressConfiguration}
log.WithMetadata(map[string]interface{}{"declaration": back}).
Infof(codes.LeaderManualDeleteLeader, "manually delete disconnected leader's declaration")
service.ClusterMesh.HandleDeleteBackendDeclarationCommand(back, s)
})
shutdown.On(func() {
logger.Info(app.Context(), "starting shutdown")
app.Shutdown()
logger.Info(app.Context(), "shutdown completed")
})
holder.ClusterClient = clusterClient
if clusterCfg.BootstrapCluster {
err = r.BootstrapCluster() // err can be ignored
if err != nil {
log.Errorf(codes.BootstrapClusterError, "bootstrap cluster. %v", err)
}
}
return clusterClient, raftStore
}
func initGrpc(bindAddress structure.AddressConfiguration, raftStore *store.Store) {
controller.Routes = controller.NewRoutes(raftStore)
controller.Schema = controller.NewSchema(raftStore)
controller.Module = controller.NewModule(raftStore)
controller.Config = controller.NewConfig(raftStore)
controller.CommonConfig = controller.NewCommonConfig(raftStore)
defaultService := backend.GetDefaultService(moduleName, helper.GetHandlers())
backend.StartBackendGrpcServer(bindAddress, defaultService)
}
func gracefulShutdown() {
const (
gracefulTimeout = 10 * time.Second
terminateTimeout = 11 * time.Second
)
signalsCh := make(chan os.Signal, 1)
signal.Notify(signalsCh, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
sig := <-signalsCh
log.Infof(0, "received signal '%s'", sig)
finishedCh := make(chan struct{})
go func() {
select {
case <-time.After(terminateTimeout):
log.Fatal(0, "exit timeout reached: terminating")
case <-finishedCh:
// ok
case sig := <-signalsCh:
log.Fatalf(0, "received duplicate exit signal '%s': terminating", sig)
}
}()
ctx, cancel := context.WithTimeout(context.Background(), gracefulTimeout)
defer cancel()
onShutdown(ctx)
finishedCh <- struct{}{}
log.Info(0, "application exited normally")
}
func onShutdown(ctx context.Context) {
backend.StopGrpcServer()
if err := holder.HTTPServer.Shutdown(ctx); err != nil {
log.Warnf(codes.ShutdownHttpServerError, "http server shutdown err: %v", err)
} else {
log.Info(codes.ShutdownHttpServerInfo, "http server shutdown success")
}
holder.EtpServer.Close()
if err := holder.ClusterClient.Shutdown(); err != nil {
log.Warnf(codes.RaftShutdownError, "raft shutdown err: %v", err)
} else {
log.Info(codes.RaftShutdownInfo, "raft shutdown success")
}
if err := model.DbClient.Close(); err != nil {
log.Warnf(0, "database shutdown err: %v", err)
}
_ = muxer.Close()
}
func getOutboundIP() (string, error) {
conn, err := net.Dial("udp", "9.9.9.9:80")
err = app.Run()
if err != nil {
return "", err
boot.Fatal(err)
}
defer conn.Close()
return conn.LocalAddr().(*net.UDPAddr).IP.To4().String(), nil
}
+33
View File
@@ -0,0 +1,33 @@
package middlewares
import (
"context"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/metrics"
"isp-config-service/middlewares/sql_metrics"
)
func SqlOperationMiddleware() httpcli.Middleware {
//nolint:promlinter
sqlQueryDuration := metrics.GetOrRegister(metrics.DefaultRegistry, prometheus.NewSummaryVec(prometheus.SummaryOpts{
Subsystem: "sql",
Name: "query_duration_ms",
Help: "The latencies of sql query",
Objectives: metrics.DefaultObjectives,
}, []string{"operation"}))
return func(next httpcli.RoundTripper) httpcli.RoundTripper {
return httpcli.RoundTripperFunc(func(ctx context.Context, request *httpcli.Request) (*httpcli.Response, error) {
label := sql_metrics.OperationLabelFromContext(ctx)
now := time.Now()
resp, err := next.RoundTrip(ctx, request)
if label != "" {
duration := time.Since(now)
sqlQueryDuration.WithLabelValues(label).Observe(metrics.Milliseconds(duration))
}
return resp, err //nolint:wrapcheck
})
}
}
+20
View File
@@ -0,0 +1,20 @@
package sql_metrics
import (
"context"
)
type tracerContextKey int
const (
labelContextKey = tracerContextKey(2)
)
func OperationLabelToContext(ctx context.Context, label string) context.Context {
return context.WithValue(ctx, labelContextKey, label)
}
func OperationLabelFromContext(ctx context.Context) string {
value, _ := ctx.Value(labelContextKey).(string)
return value
}
+34
View File
@@ -0,0 +1,34 @@
package middlewares
import (
"context"
"github.com/txix-open/etp/v4"
"github.com/txix-open/etp/v4/msg"
"github.com/txix-open/isp-kit/log"
"isp-config-service/helpers"
)
type EtpMiddleware func(next etp.Handler) etp.Handler
func EtpLogger(logger log.Logger) EtpMiddleware {
return func(next etp.Handler) etp.Handler {
return etp.HandlerFunc(func(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
fields := append(
helpers.LogFields(conn),
log.String("event", event.Name),
)
logger.Debug(ctx, "event received", fields...)
return next.Handle(ctx, conn, event)
})
}
}
//nolint:ireturn
func EtpChain(root etp.Handler, middlewares ...EtpMiddleware) etp.Handler {
for i := len(middlewares) - 1; i >= 0; i-- {
root = middlewares[i](root)
}
return root
}
@@ -1,5 +0,0 @@
-- +goose Up
CREATE schema if NOT EXISTS "config_service";
-- +goose Down
DROP schema if EXISTS config_service CASCADE;
@@ -1,47 +0,0 @@
-- +goose Up
CREATE TABLE instances (
id serial4 NOT NULL PRIMARY KEY,
uuid UUID NOT NULL,
"name" varchar(255) NOT NULL,
created_at timestamp DEFAULT (now() at time zone 'utc') NOT NULL
);
-- +goose StatementBegin
CREATE OR REPLACE FUNCTION update_created_modified_column_date()
RETURNS TRIGGER AS
$body$
BEGIN
IF TG_OP = 'UPDATE' THEN
NEW.created_at = OLD.created_at;
NEW.updated_at = (now() at time zone 'utc');
ELSIF TG_OP = 'INSERT' THEN
NEW.updated_at = (now() at time zone 'utc');
END IF;
RETURN NEW;
END;
$body$ LANGUAGE plpgsql;
-- +goose StatementEnd
-- +goose StatementBegin
CREATE OR REPLACE FUNCTION update_created_column_date()
RETURNS TRIGGER AS
$body$
BEGIN
IF TG_OP = 'UPDATE' THEN
NEW.created_at = OLD.created_at;
ELSIF TG_OP = 'INSERT' THEN
NEW.created_at = (now() at time zone 'utc');
END IF;
RETURN NEW;
END;
$body$ LANGUAGE plpgsql;
-- +goose StatementEnd
CREATE TRIGGER update_customer_modtime BEFORE INSERT OR UPDATE ON instances
FOR EACH ROW EXECUTE PROCEDURE update_created_column_date();
ALTER TABLE instances ADD CONSTRAINT "UQ_instances_uuid" UNIQUE ("uuid");
-- +goose Down
DROP TABLE instances;
@@ -1,24 +0,0 @@
-- +goose Up
CREATE TABLE modules (
id serial4 NOT NULL PRIMARY KEY,
instance_id int4 NOT NULL,
"name" varchar(255) NOT NULL,
"active" bool DEFAULT true,
created_at timestamp DEFAULT (now() at time zone 'utc') NOT NULL,
last_connected_at timestamp,
last_disconnected_at timestamp
);
ALTER TABLE modules
ADD CONSTRAINT "FK_modules_instanceId_instances_id"
FOREIGN KEY ("instance_id") REFERENCES instances ("id")
ON DELETE CASCADE ON UPDATE CASCADE;
CREATE INDEX IX_modules_instanceId ON modules USING hash (instance_id);
CREATE TRIGGER update_customer_modtime BEFORE INSERT OR UPDATE ON modules
FOR EACH ROW EXECUTE PROCEDURE update_created_column_date();
ALTER TABLE modules ADD CONSTRAINT "UQ_modules_instanceId_name" UNIQUE ("instance_id", "name");
-- +goose Down
DROP TABLE modules;
@@ -1,70 +0,0 @@
-- +goose Up
CREATE TABLE configs (
id serial8 NOT NULL PRIMARY KEY,
module_id int4 NOT NULL,
"version" int4 NOT NULL,
"active" bool DEFAULT false,
created_at timestamp DEFAULT (now() at time zone 'utc') NOT NULL,
updated_at timestamp DEFAULT (now() at time zone 'utc') NOT NULL,
"data" jsonb NOT NULL DEFAULT '{}'
);
ALTER TABLE configs
ADD CONSTRAINT "FK_configs_moduleId_modules_id"
FOREIGN KEY ("module_id") REFERENCES modules ("id")
ON DELETE CASCADE ON UPDATE CASCADE;
CREATE INDEX IX_configs_moduleId ON configs USING hash (module_id);
-- +goose StatementBegin
CREATE OR REPLACE FUNCTION deactivate_config()
RETURNS TRIGGER AS
$body$
DECLARE
last_version integer;
BEGIN
NEW.updated_at = (now() at time zone 'utc');
IF TG_OP = 'INSERT'
THEN
EXECUTE format('
SELECT version
FROM %I.configs
WHERE module_id = ' || NEW.module_id || '
ORDER BY created_at DESC
LIMIT 1;
', TG_TABLE_SCHEMA) INTO last_version;
IF last_version IS NOT NULL
THEN
NEW.version = last_version + 1;
ELSE
NEW.version = 1;
END IF;
ELSE
NEW.version = OLD.version;
NEW.created_at = OLD.created_at;
END IF;
IF NEW.active = TRUE
THEN
EXECUTE format('
UPDATE %I.configs
SET active = FALSE,
updated_at = (now() at time zone ''utc'')
WHERE active = TRUE AND ' || NEW.id || ' != id AND module_id = ' || NEW.module_id || ';
', TG_TABLE_SCHEMA);
END IF;
RETURN NEW;
END;
$body$ LANGUAGE plpgsql;
-- +goose StatementEnd
CREATE TRIGGER "deactivate_config"
BEFORE INSERT OR UPDATE ON configs
FOR EACH ROW EXECUTE PROCEDURE deactivate_config();
CREATE TRIGGER update_config_create_time BEFORE INSERT OR UPDATE ON configs
FOR EACH ROW EXECUTE PROCEDURE update_created_column_date();
-- +goose Down
DROP TABLE configs;
DROP FUNCTION deactivate_config;
@@ -1,9 +0,0 @@
-- +goose Up
ALTER TABLE configs
ADD COLUMN name VARCHAR(255) NOT NULL DEFAULT 'unnamed',
ADD COLUMN description TEXT;
-- +goose Down
ALTER TABLE configs
DROP COLUMN name,
DROP COLUMN description;
@@ -1,23 +0,0 @@
-- +goose Up
CREATE TABLE config_schemas (
id SERIAL4 PRIMARY KEY,
module_id INTEGER NOT NULL,
version VARCHAR(255) NOT NULL,
schema JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMP NOT NULL DEFAULT (now() at time zone 'utc'),
updated_at TIMESTAMP NOT NULL DEFAULT (now() at time zone 'utc'),
CONSTRAINT FK_module_id__module_id FOREIGN KEY (module_id)
REFERENCES modules (id) ON UPDATE CASCADE ON DELETE CASCADE
);
CREATE TRIGGER update_schema_create_time
BEFORE INSERT OR UPDATE
ON config_schemas
FOR EACH ROW EXECUTE PROCEDURE update_created_modified_column_date();
CREATE INDEX IX_schemes_moduleId
ON config_schemas
USING hash (module_id);
-- +goose Down
DROP TABLE config_schemas;
-46
View File
@@ -1,46 +0,0 @@
-- +goose Up
DROP TABLE instances CASCADE;
DROP TRIGGER update_config_create_time ON configs;
DROP TRIGGER deactivate_config on configs;
DROP TRIGGER update_schema_create_time ON config_schemas;
DROP TRIGGER update_customer_modtime ON modules;
ALTER TABLE configs
DROP CONSTRAINT "FK_configs_moduleId_modules_id";
ALTER TABLE config_schemas
DROP CONSTRAINT "fk_module_id__module_id";
ALTER TABLE configs
ALTER COLUMN id TYPE varchar(255),
ALTER COLUMN module_id TYPE varchar(255),
ADD COLUMN common_configs varchar(255)[] NOT NULL DEFAULT '{}';
ALTER TABLE config_schemas
ALTER COLUMN module_id TYPE varchar(255),
ALTER COLUMN id TYPE varchar(255);
ALTER TABLE modules
ALTER COLUMN id TYPE varchar(255),
DROP COLUMN active,
DROP COLUMN instance_id;
CREATE TABLE common_configs
(
id VARCHAR(255) NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL DEFAULT 'unnamed',
description TEXT,
created_at timestamp NOT NULL DEFAULT (now() at time zone 'utc'),
updated_at timestamp NOT NULL DEFAULT (now() at time zone 'utc'),
data jsonb NOT NULL DEFAULT '{}'
);
-- +goose Down
DROP TABLE common_configs;
@@ -1,13 +0,0 @@
-- +goose Up
CREATE TABLE version_config
(
id VARCHAR(255) NOT NULL PRIMARY KEY,
config_id VARCHAR(255) NOT NULL,
config_version INT4 NOT NULL,
data JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMP NOT NULL DEFAULT (now() at time zone 'utc')
);
-- +goose Down
DROP TABLE version_config;
@@ -1,7 +0,0 @@
-- +goose Up
ALTER TABLE version_config
ADD COLUMN IF NOT EXISTS created_at TIMESTAMP NOT NULL DEFAULT (now() at time zone 'utc');
-- +goose Down
+81
View File
@@ -0,0 +1,81 @@
-- +goose Up
-- +goose NO TRANSACTION
create table isp_config_service__module
(
id text not null primary key,
name text not null unique,
last_connected_at integer,
last_disconnected_at integer,
created_at integer not null default (unixepoch())
);
create table isp_config_service__config
(
id text not null primary key,
name text not null,
module_id text not null,
data blob not null,
version int not null default 1,
active int not null default 0,
admin_id int not null default 0,
created_at integer not null default (unixepoch()),
updated_at integer not null default (unixepoch()),
foreign key (module_id) references isp_config_service__module (id) on delete cascade on update cascade
);
create index IX_isp_config_service__config__module_id on isp_config_service__config (module_id);
create table isp_config_service__config_history
(
id text not null primary key,
config_id text not null,
data blob not null,
version int not null default 1,
admin_id int not null default 0,
created_at integer not null default (unixepoch()),
foreign key (config_id) references isp_config_service__config (id) on delete cascade on update cascade
);
create index IX_isp_config_service__config_history__config_id on isp_config_service__config_history (config_id);
create table isp_config_service__config_schema
(
id text not null primary key,
module_id text not null unique,
data blob not null,
module_version text not null default 1,
created_at integer not null default (unixepoch()),
updated_at integer not null default (unixepoch()),
foreign key (module_id) references isp_config_service__module (id) on delete cascade on update cascade
);
create table isp_config_service__backend
(
module_id text not null,
address text not null,
version text not null,
lib_version text not null,
module_name text not null,
endpoints blob not null,
required_modules blob not null,
created_at integer not null default (unixepoch()),
updated_at integer not null default (unixepoch()),
primary key (module_id, address),
foreign key (module_id) references isp_config_service__module (id) on delete cascade on update cascade
);
create table isp_config_service__event
(
id integer,
payload blob not null,
created_at integer not null default (unixepoch()),
primary key (id)
);
-- +goose Down
drop table isp_config_service__module;
drop table isp_config_service__config;
drop table isp_config_service__config_history;
drop table isp_config_service__config_schema;
drop table isp_config_service__backend;
drop table isp_config_service__event;
@@ -0,0 +1,17 @@
-- +goose Up
-- +goose NO TRANSACTION
CREATE TABLE isp_config_service__event_autoincrement (
id integer primary key autoincrement,
payload blob not null,
created_at integer not null default (unixepoch())
);
INSERT INTO
isp_config_service__event_autoincrement (id, payload, created_at)
SELECT id, payload, created_at
FROM isp_config_service__event;
DROP TABLE isp_config_service__event;
ALTER TABLE isp_config_service__event_autoincrement RENAME TO isp_config_service__event;
-- +goose Down
@@ -0,0 +1,24 @@
-- +goose Up
-- +goose NO TRANSACTION
drop table isp_config_service__backend;
create table isp_config_service__backend
(
ws_connection_id text not null,
module_id text not null,
address text not null,
version text not null,
lib_version text not null,
module_name text not null,
config_service_node_id text not null,
endpoints blob not null,
required_modules blob not null,
created_at integer not null default (unixepoch()),
primary key (ws_connection_id),
foreign key (module_id) references isp_config_service__module (id) on delete cascade on update cascade
);
create index IX_isp_config_service__backend__module_id on isp_config_service__backend (module_id);
create index IX_isp_config_service__backend__node_id on isp_config_service__backend(config_service_node_id);
-- +goose Down
@@ -0,0 +1,26 @@
-- +goose Up
-- +goose NO TRANSACTION
create table isp_config_service__variable
(
name text primary key,
description text not null,
type text not null,
value text not null,
created_at integer not null default (unixepoch()),
updated_at integer not null default (unixepoch())
);
create table isp_config_service__config_has_variable
(
config_id text not null,
variable_name text not null,
primary key (config_id, variable_name),
foreign key (config_id) references isp_config_service__config (id) on delete cascade on update cascade,
foreign key (variable_name) references isp_config_service__variable (name)
);
create index IX_isp_config_service__config_has_variable__variable_name on isp_config_service__config_has_variable (variable_name);
-- +goose Down
drop table isp_config_service__config_has_variable;
drop table isp_config_service__variable;
@@ -0,0 +1,6 @@
-- +goose Up
-- +goose NO TRANSACTION
alter table isp_config_service__backend add column metrics_autodiscovery blob;
-- +goose Down
alter table isp_config_service__backend drop column metrics_autodiscovery;
+10
View File
@@ -0,0 +1,10 @@
package migrations
import (
"embed"
)
var (
//go:embed *
Migrations embed.FS
)
-23
View File
@@ -1,23 +0,0 @@
package model
import (
"github.com/integration-system/isp-lib/v2/database"
log "github.com/integration-system/isp-log"
"github.com/integration-system/isp-log/stdcodes"
)
var (
DbClient = database.NewRxDbClient(
database.WithSchemaEnsuring(),
database.WithSchemaAutoInjecting(),
database.WithMigrationsEnsuring(),
database.WithInitializingErrorHandler(func(err *database.ErrorEvent) {
log.Fatal(stdcodes.InitializingDbError, err.Error())
}),
)
ConfigRep ConfigRepository = &configRepPg{rxClient: DbClient}
CommonConfigRep CommonConfigRepository = &commonConfigRepPg{rxClient: DbClient}
SchemaRep SchemaRepository = &schemaRepPg{rxClient: DbClient}
ModuleRep ModulesRepository = &modulesRepPg{rxClient: DbClient}
VersionStoreRep VersionConfigRepository = &versionConfigRepPg{rxClient: DbClient}
)
-55
View File
@@ -1,55 +0,0 @@
//nolint: dupl
package model
import (
"github.com/go-pg/pg/v9"
"github.com/integration-system/isp-lib/v2/database"
"isp-config-service/entity"
)
type CommonConfigRepository interface {
Snapshot() ([]entity.CommonConfig, error)
Upsert(config entity.CommonConfig) (*entity.CommonConfig, error)
Delete(identities []string) (int, error)
}
type commonConfigRepPg struct {
rxClient *database.RxDbClient
}
func (r *commonConfigRepPg) Snapshot() ([]entity.CommonConfig, error) {
configs := make([]entity.CommonConfig, 0)
err := r.rxClient.Visit(func(db *pg.DB) error {
return db.Model(&configs).Select()
})
return configs, err
}
func (r *commonConfigRepPg) Upsert(config entity.CommonConfig) (*entity.CommonConfig, error) {
err := r.rxClient.Visit(func(db *pg.DB) error {
_, err := db.Model(&config).
OnConflict("(id) DO UPDATE").
Returning("*").
Insert()
return err
})
if err != nil {
return nil, err
}
return &config, err
}
func (r *commonConfigRepPg) Delete(identities []string) (int, error) {
var err error
var res pg.Result
err = r.rxClient.Visit(func(db *pg.DB) error {
res, err = db.Model(&entity.CommonConfig{}).
Where("id IN (?)", pg.In(identities)).
Delete()
return err
})
if err != nil {
return 0, err
}
return res.RowsAffected(), err
}
-55
View File
@@ -1,55 +0,0 @@
//nolint:dupl
package model
import (
"github.com/go-pg/pg/v9"
"github.com/integration-system/isp-lib/v2/database"
"isp-config-service/entity"
)
type ConfigRepository interface {
Snapshot() ([]entity.Config, error)
Upsert(config entity.Config) (*entity.Config, error)
Delete(identities []string) (int, error)
}
type configRepPg struct {
rxClient *database.RxDbClient
}
func (r *configRepPg) Snapshot() ([]entity.Config, error) {
configs := make([]entity.Config, 0)
err := r.rxClient.Visit(func(db *pg.DB) error {
return db.Model(&configs).Select()
})
return configs, err
}
func (r *configRepPg) Upsert(config entity.Config) (*entity.Config, error) {
err := r.rxClient.Visit(func(db *pg.DB) error {
_, err := db.Model(&config).
OnConflict("(id) DO UPDATE").
Returning("*").
Insert()
return err
})
if err != nil {
return nil, err
}
return &config, err
}
func (r *configRepPg) Delete(identities []string) (int, error) {
var err error
var res pg.Result
err = r.rxClient.Visit(func(db *pg.DB) error {
res, err = db.Model(&entity.Config{}).
Where("id IN (?)", pg.In(identities)).
Delete()
return err
})
if err != nil {
return 0, err
}
return res.RowsAffected(), err
}
-54
View File
@@ -1,54 +0,0 @@
//nolint:dupl
package model
import (
"github.com/go-pg/pg/v9"
"github.com/integration-system/isp-lib/v2/database"
"isp-config-service/entity"
)
type ModulesRepository interface {
Snapshot() ([]entity.Module, error)
Upsert(module entity.Module) (*entity.Module, error)
Delete(identities []string) (int, error)
}
type modulesRepPg struct {
rxClient *database.RxDbClient
}
func (r *modulesRepPg) Snapshot() ([]entity.Module, error) {
modules := make([]entity.Module, 0)
err := r.rxClient.Visit(func(db *pg.DB) error {
return db.Model(&modules).Select()
})
return modules, err
}
func (r *modulesRepPg) Upsert(module entity.Module) (*entity.Module, error) {
err := r.rxClient.Visit(func(db *pg.DB) error {
_, err := db.Model(&module).
OnConflict("(id) DO UPDATE").
Returning("*").
Insert()
return err
})
if err != nil {
return nil, err
}
return &module, err
}
func (r *modulesRepPg) Delete(identities []string) (int, error) {
var err error
var res pg.Result
err = r.rxClient.Visit(func(db *pg.DB) error {
res, err = db.Model(&entity.Module{}).
Where("id IN (?)", pg.In(identities)).Delete()
return err
})
if err != nil {
return 0, err
}
return res.RowsAffected(), err
}
-54
View File
@@ -1,54 +0,0 @@
//nolint:dupl
package model
import (
"github.com/go-pg/pg/v9"
"github.com/integration-system/isp-lib/v2/database"
"isp-config-service/entity"
)
type SchemaRepository interface {
Snapshot() ([]entity.ConfigSchema, error)
Upsert(schema entity.ConfigSchema) (*entity.ConfigSchema, error)
Delete(identities []string) (int, error)
}
type schemaRepPg struct {
rxClient *database.RxDbClient
}
func (r *schemaRepPg) Snapshot() ([]entity.ConfigSchema, error) {
schemas := make([]entity.ConfigSchema, 0)
err := r.rxClient.Visit(func(db *pg.DB) error {
return db.Model(&schemas).Select()
})
return schemas, err
}
func (r *schemaRepPg) Upsert(schema entity.ConfigSchema) (*entity.ConfigSchema, error) {
err := r.rxClient.Visit(func(db *pg.DB) error {
_, err := db.Model(&schema).
OnConflict("(id) DO UPDATE").
Returning("*").
Insert()
return err
})
if err != nil {
return nil, err
}
return &schema, err
}
func (r *schemaRepPg) Delete(identities []string) (int, error) {
var err error
var res pg.Result
err = r.rxClient.Visit(func(db *pg.DB) error {
res, err = db.Model(&entity.ConfigSchema{}).
Where("id IN (?)", pg.In(identities)).Delete()
return err
})
if err != nil {
return 0, err
}
return res.RowsAffected(), err
}
-53
View File
@@ -1,53 +0,0 @@
package model
import (
"github.com/go-pg/pg/v9"
"github.com/integration-system/isp-lib/v2/database"
"isp-config-service/entity"
)
type VersionConfigRepository interface {
Snapshot() ([]entity.VersionConfig, error)
Upsert(model entity.VersionConfig) (*entity.VersionConfig, error)
Delete(identities string) (int, error)
}
type versionConfigRepPg struct {
rxClient *database.RxDbClient
}
func (r *versionConfigRepPg) Snapshot() ([]entity.VersionConfig, error) {
modules := make([]entity.VersionConfig, 0)
err := r.rxClient.Visit(func(db *pg.DB) error {
return db.Model(&modules).Select()
})
return modules, err
}
func (r *versionConfigRepPg) Upsert(module entity.VersionConfig) (*entity.VersionConfig, error) {
err := r.rxClient.Visit(func(db *pg.DB) error {
_, err := db.Model(&module).
OnConflict("(id) DO UPDATE").
Returning("*").
Insert()
return err
})
if err != nil {
return nil, err
}
return &module, err
}
func (r *versionConfigRepPg) Delete(id string) (int, error) {
var err error
var res pg.Result
err = r.rxClient.Visit(func(db *pg.DB) error {
res, err = db.Model(&entity.VersionConfig{}).
Where("id = ?", id).Delete()
return err
})
if err != nil {
return 0, err
}
return res.RowsAffected(), err
}
-175
View File
@@ -1,175 +0,0 @@
package raft
import (
"net"
"os"
"path/filepath"
"time"
"github.com/hashicorp/raft"
"github.com/hashicorp/raft-boltdb/v2"
"github.com/integration-system/isp-log/adapter"
"github.com/pkg/errors"
"isp-config-service/codes"
"isp-config-service/conf"
)
const (
defaultSyncTimeout = 3 * time.Second
leaderNotificationChBuffer = 10
dbFile = "raft_db"
)
type ChangeLeaderNotification struct {
CurrentLeaderAddress string
IsLeader bool
LeaderElected bool
}
type Raft struct {
r *raft.Raft
cfg conf.ClusterConfiguration
leaderObs *raft.Observer
leaderObsCh chan raft.Observation
changeLeaderCh chan ChangeLeaderNotification
closer chan struct{}
}
func (r *Raft) BootstrapCluster() error {
peers := makeConfiguration(r.cfg.Peers)
if f := r.r.BootstrapCluster(peers); f.Error() != nil {
return errors.WithMessage(f.Error(), "bootstrap cluster")
}
return nil
}
func (r *Raft) SyncApply(command []byte) (interface{}, error) {
f := r.r.Apply(command, defaultSyncTimeout)
if err := f.Error(); err != nil {
return nil, err
}
return f.Response(), nil
}
func (r *Raft) LeaderCh() <-chan ChangeLeaderNotification {
return r.changeLeaderCh
}
func (r *Raft) GracefulShutdown() error {
r.r.DeregisterObserver(r.leaderObs)
close(r.closer)
close(r.leaderObsCh)
return r.r.Shutdown().Error()
}
func (r *Raft) listenLeader() {
defer close(r.changeLeaderCh)
for {
select {
case _, ok := <-r.leaderObsCh:
if !ok {
return
}
currentLeader := r.r.Leader()
select {
case r.changeLeaderCh <- ChangeLeaderNotification{
IsLeader: r.r.State() == raft.Leader,
CurrentLeaderAddress: string(currentLeader),
LeaderElected: currentLeader != "",
}:
case <-r.closer:
return
default:
continue
}
case <-r.closer:
return
}
}
}
func NewRaft(tcpListener net.Listener, configuration conf.ClusterConfiguration, state raft.FSM) (*Raft, error) {
logStore, store, snapshotStore, err := makeStores(configuration)
if err != nil {
return nil, err
}
netLogger := adapter.NewHcLogger("RAFT-NET", codes.RaftLoggerCode)
streamLayer := &StreamLayer{Listener: tcpListener}
timeout := time.Duration(configuration.ConnectTimeoutSeconds) * time.Second
config := &raft.NetworkTransportConfig{
Stream: streamLayer,
MaxPool: len(configuration.Peers),
Timeout: timeout,
Logger: netLogger,
ServerAddressProvider: transparentAddressProvider{},
}
trans := raft.NewNetworkTransportWithConfig(config)
cfg := raft.DefaultConfig()
cfg.Logger = adapter.NewHcLogger("RAFT", codes.RaftLoggerCode)
cfg.NoSnapshotRestoreOnStart = true
cfg.LocalID = raft.ServerID(configuration.OuterAddress)
r, err := raft.NewRaft(cfg, state, logStore, store, snapshotStore, trans)
if err != nil {
return nil, errors.WithMessage(err, "create raft")
}
leaderObs, leaderObsCh := makeLeaderObserver()
r.RegisterObserver(leaderObs)
raft := &Raft{
r: r,
cfg: configuration,
leaderObs: leaderObs,
leaderObsCh: leaderObsCh,
changeLeaderCh: make(chan ChangeLeaderNotification, leaderNotificationChBuffer),
closer: make(chan struct{}),
}
go raft.listenLeader()
return raft, nil
}
func makeLeaderObserver() (*raft.Observer, chan raft.Observation) {
ch := make(chan raft.Observation)
obs := raft.NewObserver(ch, false, func(o *raft.Observation) bool {
_, ok := o.Data.(raft.LeaderObservation)
return ok
})
return obs, ch
}
func makeConfiguration(peers []string) raft.Configuration {
servers := make([]raft.Server, len(peers))
for i, peer := range peers {
servers[i] = raft.Server{
ID: raft.ServerID(peer),
Address: raft.ServerAddress(peer),
}
}
return raft.Configuration{
Servers: servers,
}
}
func makeStores(configuration conf.ClusterConfiguration) (raft.LogStore, raft.StableStore, raft.SnapshotStore, error) {
if configuration.InMemory {
dbStore := raft.NewInmemStore()
snapStore := raft.NewInmemSnapshotStore()
return dbStore, dbStore, snapStore, nil
} else {
dbStore, err := raftboltdb.NewBoltStore(filepath.Join(configuration.DataDir, dbFile))
if err != nil {
return nil, nil, nil, errors.WithMessage(err, "create db")
}
snapStore, err := raft.NewFileSnapshotStore(configuration.DataDir, 1, os.Stdout)
if err != nil {
return nil, nil, nil, errors.WithMessage(err, "create snapshot store")
}
return dbStore, dbStore, snapStore, nil
}
}
-22
View File
@@ -1,22 +0,0 @@
package raft
import (
"github.com/hashicorp/raft"
"net"
"time"
)
type StreamLayer struct {
net.Listener
}
func (r *StreamLayer) Dial(address raft.ServerAddress, timeout time.Duration) (net.Conn, error) {
return net.DialTimeout("tcp", string(address), timeout)
}
type transparentAddressProvider struct {
}
func (t transparentAddressProvider) ServerAddr(id raft.ServerID) (raft.ServerAddress, error) {
return raft.ServerAddress(id), nil
}
+163
View File
@@ -0,0 +1,163 @@
package repository
import (
"context"
"fmt"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"isp-config-service/entity"
"isp-config-service/middlewares/sql_metrics"
"isp-config-service/service/rqlite/db"
)
type Backend struct {
db db.DB
}
func NewBackend(db db.DB) Backend {
return Backend{
db: db,
}
}
func (r Backend) Insert(ctx context.Context, backend entity.Backend) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.Insert")
query, args, err := squirrel.Insert(Table("backend")).
Columns("ws_connection_id", "module_id", "address",
"version", "lib_version", "module_name", "config_service_node_id",
"endpoints", "required_modules", "metrics_autodiscovery").
Values(backend.WsConnectionId, backend.ModuleId, backend.Address,
backend.Version, backend.LibVersion, backend.ModuleName, backend.ConfigServiceNodeId,
backend.Endpoints, backend.RequiredModules, backend.MetricsAutodiscovery,
).
ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
_, err = r.db.Exec(ctx, query, args...)
if err != nil {
return errors.WithMessagef(err, "exec: %s", query)
}
return nil
}
func (r Backend) DeleteByWsConnectionIds(ctx context.Context, wsConnectionIds []string) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.DeleteByWsConnectionIds")
query, args, err := squirrel.Delete(Table("backend")).
Where(squirrel.Eq{
"ws_connection_id": wsConnectionIds,
}).ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
_, err = r.db.Exec(ctx, query, args...)
if err != nil {
return errors.WithMessagef(err, "exec: %s", query)
}
return nil
}
func (r Backend) DeleteByConfigServiceNodeId(ctx context.Context, configServiceNodeId string) (int, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.DeleteByConfigServiceNodeId")
query, args, err := squirrel.Delete(Table("backend")).
Where(squirrel.Eq{
"config_service_node_id": configServiceNodeId,
}).ToSql()
if err != nil {
return 0, errors.WithMessage(err, "build query")
}
result, err := r.db.Exec(ctx, query, args...)
if err != nil {
return 0, errors.WithMessagef(err, "exec: %s", query)
}
deleted, err := result.RowsAffected()
if err != nil {
return 0, errors.WithMessage(err, "rows affected")
}
return int(deleted), nil
}
func (r Backend) GetByConfigServiceNodeId(ctx context.Context, configServiceNodeId string) ([]entity.Backend, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.GetByConfigServiceNodeId")
query, args, err := squirrel.Select("*").
From(Table("backend")).
Where(squirrel.Eq{
"config_service_node_id": configServiceNodeId,
}).OrderBy("created_at desc").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.Backend, 0)
err = r.db.Select(ctx, &result, query, args...)
if err != nil {
return nil, errors.WithMessagef(err, "select: %s", query)
}
return result, nil
}
func (r Backend) All(ctx context.Context) ([]entity.Backend, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.All")
result := make([]entity.Backend, 0)
query := fmt.Sprintf("SELECT * FROM %s order by created_at desc", Table("backend"))
err := r.db.Select(ctx, &result, query)
if err != nil {
return nil, errors.WithMessagef(err, "select: %s", query)
}
return result, nil
}
func (r Backend) GetByModuleId(ctx context.Context, moduleId string) ([]entity.Backend, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.GetByModuleId")
query, args, err := squirrel.Select("*").
From(Table("backend")).
Where(squirrel.Eq{
"module_id": moduleId,
}).OrderBy("created_at desc").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.Backend, 0)
err = r.db.Select(ctx, &result, query, args...)
if err != nil {
return nil, errors.WithMessagef(err, "select: %s", query)
}
return result, nil
}
func (r Backend) AllMetricsAutodiscovery(ctx context.Context) ([]entity.MetricsAdWrapper, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.AllMetricsAutodiscovery")
result := make([]entity.MetricsAdWrapper, 0)
query := fmt.Sprintf(`
SELECT metrics_autodiscovery FROM %s
WHERE metrics_autodiscovery IS NOT NULL
ORDER BY module_name, created_at DESC`,
Table("backend"),
)
err := r.db.Select(ctx, &result, query)
if err != nil {
return nil, errors.WithMessagef(err, "select %s", query)
}
return result, nil
}
+227
View File
@@ -0,0 +1,227 @@
package repository
import (
"context"
"fmt"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/entity/xtypes"
"isp-config-service/middlewares/sql_metrics"
"isp-config-service/service/rqlite/db"
)
type Config struct {
db db.DB
}
func NewConfig(db db.DB) Config {
return Config{
db: db,
}
}
func (r Config) Insert(ctx context.Context, cfg entity.Config) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Config.Insert")
query, args, err := squirrel.Insert(Table("config")).
Columns("id", "name", "module_id", "data", "version", "active", "admin_id").
Values(cfg.Id, cfg.Name, cfg.ModuleId, cfg.Data, cfg.Version, cfg.Active, cfg.AdminId).
Suffix("on conflict (id) do nothing").
ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
_, err = r.db.Exec(ctx, query, args...)
if err != nil {
return errors.WithMessagef(err, "exec: %s", query)
}
return nil
}
func (r Config) GetActive(ctx context.Context, moduleId string) (*entity.Config, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Config.GetActive")
query, args, err := squirrel.Select("*").
From(Table("config")).
Where(squirrel.Eq{
"module_id": moduleId,
"active": xtypes.Bool(true),
}).OrderBy("version DESC").
Limit(1).
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
return selectRow[entity.Config](ctx, r.db, query, args...)
}
func (r Config) GetByModuleId(ctx context.Context, moduleId string) ([]entity.Config, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Config.GetByModuleId")
query, args, err := squirrel.Select("*").
From(Table("config")).
Where(squirrel.Eq{
"module_id": moduleId,
}).OrderBy("created_at desc").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.Config, 0)
err = r.db.Select(ctx, &result, query, args...)
if err != nil {
return nil, errors.WithMessagef(err, "select: %s", query)
}
return result, nil
}
func (r Config) GetById(ctx context.Context, id string) (*entity.Config, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Config.GetById")
query, args, err := squirrel.Select("*").
From(Table("config")).
Where(squirrel.Eq{
"id": id,
}).ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
return selectRow[entity.Config](ctx, r.db, query, args...)
}
func (r Config) DeleteNonActiveById(ctx context.Context, id string) (bool, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Config.DeleteNonActiveById")
query, args, err := squirrel.Delete(Table("config")).
Where(squirrel.Eq{
"id": id,
"active": xtypes.Bool(false),
}).ToSql()
if err != nil {
return false, errors.WithMessage(err, "build query")
}
result, err := r.db.Exec(ctx, query, args...)
if err != nil {
return false, errors.WithMessagef(err, "exec: %s", query)
}
affected, err := result.RowsAffected()
if err != nil {
return false, errors.WithMessage(err, "get rows affected")
}
return affected > 0, nil
}
func (r Config) UpdateByVersion(ctx context.Context, cfg entity.Config) (bool, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Config.UpdateByVersion")
query, args, err := squirrel.Update(Table("config")).
SetMap(map[string]any{
"name": cfg.Name,
"data": cfg.Data,
"version": squirrel.Expr("version + 1"),
"updated_at": squirrel.Expr("unixepoch()"),
"admin_id": cfg.AdminId,
}).Where(squirrel.Eq{
"id": cfg.Id,
"version": cfg.Version,
}).ToSql()
if err != nil {
return false, errors.WithMessage(err, "build query")
}
result, err := r.db.Exec(ctx, query, args...)
if err != nil {
return false, errors.WithMessagef(err, "exec: %s", query)
}
affected, err := result.RowsAffected()
if err != nil {
return false, errors.WithMessage(err, "get rows affected")
}
return affected > 0, nil
}
func (r Config) SetActive(ctx context.Context, configId string, active xtypes.Bool) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Config.SetActive")
query, args, err := squirrel.Update(Table("config")).
Set("active", active).
Set("updated_at", squirrel.Expr("unixepoch()")).
Where(squirrel.Eq{
"id": configId,
}).ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
_, err = r.db.Exec(ctx, query, args...)
if err != nil {
return errors.WithMessagef(err, "exec: %s", query)
}
return nil
}
func (r Config) GetMetaByVariables(ctx context.Context, variables []string) (map[string][]entity.ConfigMetaWithVariable, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Config.GetMetaByVariables")
query, args, err := squirrel.Select("c.id", "c.name", "c.module_id", "c.active", "l.variable_name").
From(Table("config c")).
Join(fmt.Sprintf("%s l on c.id = l.config_id", Table("config_has_variable"))).
Where(squirrel.Eq{
"l.variable_name": variables,
}).ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
list := make([]entity.ConfigMetaWithVariable, 0)
err = r.db.Select(ctx, &list, query, args...)
if err != nil {
return nil, errors.WithMessagef(err, "select: %s", query)
}
result := make(map[string][]entity.ConfigMetaWithVariable)
for _, variable := range list {
result[variable.VariableName] = append(result[variable.VariableName], variable)
}
return result, nil
}
func (r Config) UpdateConfigName(ctx context.Context, req domain.UpdateConfigNameRequest) (bool, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Config.UpdateConfigName")
query, args, err := squirrel.Update(Table("config")).
Set("name", req.NewConfigName).
Where(squirrel.Eq{
"id": req.Id,
}).
ToSql()
if err != nil {
return false, errors.WithMessage(err, "build query")
}
result, err := r.db.Exec(ctx, query, args...)
if err != nil {
return false, errors.WithMessagef(err, "exec: %s", query)
}
affected, err := result.RowsAffected()
if err != nil {
return false, errors.WithMessage(err, "get rows affected")
}
return affected > 0, nil
}
+102
View File
@@ -0,0 +1,102 @@
package repository
import (
"context"
"fmt"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"isp-config-service/entity"
"isp-config-service/middlewares/sql_metrics"
"isp-config-service/service/rqlite/db"
)
type ConfigHistory struct {
db db.DB
}
func NewConfigHistory(db db.DB) ConfigHistory {
return ConfigHistory{
db: db,
}
}
func (r ConfigHistory) GetByConfigId(ctx context.Context, configId string) ([]entity.ConfigHistory, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "ConfigHistory.GetByConfigId")
query := fmt.Sprintf(`select * from %s where config_id = ? order by version desc`, Table("config_history"))
result := make([]entity.ConfigHistory, 0)
err := r.db.Select(ctx, &result, query, configId)
if err != nil {
return nil, errors.WithMessagef(err, "select: %s", query)
}
return result, nil
}
func (r ConfigHistory) Delete(ctx context.Context, id string) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "ConfigHistory.Delete")
query := fmt.Sprintf(`delete from %s where id = ?`, Table("config_history"))
_, err := r.db.Exec(ctx, query, id)
if err != nil {
return errors.WithMessagef(err, "exec: %s", query)
}
return nil
}
func (r ConfigHistory) InsertV2(ctx context.Context, history entity.ConfigHistory) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "ConfigHistory.InsertV2")
query, args, err := squirrel.Insert(Table("config_history")).
Columns("id", "config_id", "data", "version", "admin_id").
Values(history.Id, history.ConfigId, history.Data, history.Version, history.AdminId).
ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
_, err = r.db.Exec(ctx, query, args...)
if err != nil {
return errors.WithMessagef(err, "exec: %s", query)
}
return nil
}
func (r ConfigHistory) Insert(ctx context.Context, history entity.ConfigHistory) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "ConfigHistory.Insert")
query, args, err := squirrel.Insert(Table("config_history")).
Columns("id", "config_id", "data", "version", "admin_id", "created_at").
Values(history.Id, history.ConfigId, history.Data, history.Version, history.AdminId, history.CreatedAt).
ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
_, err = r.db.Exec(ctx, query, args...)
if err != nil {
return errors.WithMessagef(err, "exec: %s", query)
}
return nil
}
func (r ConfigHistory) DeleteOld(ctx context.Context, configId string, keepVersions int) (int, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "ConfigHistory.DeleteOld")
query := fmt.Sprintf(`delete from %s where config_id = ? and id not in (
select id from %s where config_id = ? order by version desc limit ?
)`, Table("config_history"), Table("config_history"))
result, err := r.db.Exec(ctx, query, configId, configId, keepVersions)
if err != nil {
return 0, errors.WithMessagef(err, "exec: %s", query)
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return 0, errors.WithMessage(err, "get rows affected")
}
return int(rowsAffected), nil
}
+101
View File
@@ -0,0 +1,101 @@
package repository
import (
"context"
"database/sql"
"fmt"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"isp-config-service/entity"
"isp-config-service/middlewares/sql_metrics"
"isp-config-service/service/rqlite/db"
)
type ConfigSchema struct {
db db.DB
}
func NewConfigSchema(db db.DB) ConfigSchema {
return ConfigSchema{
db: db,
}
}
func (r ConfigSchema) Upsert(ctx context.Context, schema entity.ConfigSchema) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "ConfigSchema.Upsert")
query, args, err := squirrel.Insert(Table("config_schema")).
Columns("id", "module_id", "data", "module_version").
Values(schema.Id, schema.ModuleId, schema.Data, schema.ModuleVersion).
Suffix(`on conflict (module_id) do update
set data = excluded.data, module_version = excluded.module_version, updated_at = unixepoch()`).
ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
_, err = r.db.Exec(ctx, query, args...)
if err != nil {
return errors.WithMessagef(err, "exec: %s", query)
}
return nil
}
func (r ConfigSchema) All(ctx context.Context) ([]entity.ConfigSchema, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "ConfigSchema.All")
result := make([]entity.ConfigSchema, 0)
query := fmt.Sprintf("select * from %s order by created_at", Table("config_schema"))
err := r.db.Select(ctx, &result, query)
if err != nil {
return nil, errors.WithMessagef(err, "select: %s", query)
}
return result, nil
}
func (r ConfigSchema) GetByModuleId(ctx context.Context, moduleId string) (*entity.ConfigSchema, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "ConfigSchema.GetByModuleId")
query, args, err := squirrel.Select("*").
From(Table("config_schema")).
Where(squirrel.Eq{"module_id": moduleId}).
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
return selectRow[entity.ConfigSchema](ctx, r.db, query, args...)
}
func (r ConfigSchema) UpdateByModuleId(ctx context.Context, moduleId string, data []byte) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "ConfigSchema.UpdateByModuleId")
query, args, err := squirrel.Update(Table("config_schema")).
Set("data", data).
Set("updated_at", squirrel.Expr("unixepoch()")).
Where(squirrel.Eq{"module_id": moduleId}).
ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
_, err = r.db.Exec(ctx, query, args...)
if err != nil {
return errors.WithMessagef(err, "exec: %s", query)
}
return nil
}
//nolint:nilnil
func selectRow[T any](ctx context.Context, db db.DB, query string, args ...interface{}) (*T, error) {
var result T
err := db.SelectRow(ctx, &result, query, args...)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, errors.WithMessagef(err, "select row: %s", query)
}
return &result, nil
}
+62
View File
@@ -0,0 +1,62 @@
package repository
import (
"context"
"fmt"
"github.com/pkg/errors"
"isp-config-service/entity"
"isp-config-service/entity/xtypes"
"isp-config-service/middlewares/sql_metrics"
"isp-config-service/service/rqlite/db"
)
type Event struct {
db db.DB
}
func NewEvent(db db.DB) Event {
return Event{
db: db,
}
}
func (r Event) Insert(ctx context.Context, event entity.Event) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Event.Insert")
query := fmt.Sprintf("insert into %s (payload) values (?)", Table("event"))
_, err := r.db.Exec(ctx, query, event.Payload)
if err != nil {
return errors.WithMessagef(err, "exec: %s", query)
}
return nil
}
func (r Event) Get(ctx context.Context, lastEventId int, limit int) ([]entity.Event, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Event.Get")
query := fmt.Sprintf("select * from %s where id > ? order by id limit ?", Table("event"))
result := make([]entity.Event, 0)
err := r.db.Select(ctx, &result, query, lastEventId, limit)
if err != nil {
return nil, errors.WithMessagef(err, "select: %s", query)
}
return result, nil
}
func (r Event) DeleteByCreatedAt(ctx context.Context, before xtypes.Time) (int, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Event.DeleteByCreatedAt")
query := fmt.Sprintf("delete from %s where created_at < ?", Table("event"))
result, err := r.db.Exec(ctx, query, before)
if err != nil {
return 0, errors.WithMessagef(err, "exec: %s", query)
}
affected, err := result.RowsAffected()
if err != nil {
return 0, errors.WithMessage(err, "get affected rows")
}
return int(affected), nil
}
+126
View File
@@ -0,0 +1,126 @@
package repository
import (
"context"
"fmt"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"isp-config-service/entity"
"isp-config-service/middlewares/sql_metrics"
"isp-config-service/service/rqlite/db"
)
type Module struct {
db db.DB
}
func NewModule(db db.DB) Module {
return Module{
db: db,
}
}
func (r Module) Upsert(ctx context.Context, module entity.Module) (string, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Module.Upsert")
query, args, err := squirrel.Insert(Table("module")).
Columns("id", "name", "last_connected_at").
Values(module.Id, module.Name, squirrel.Expr("unixepoch()")).
Suffix(`on conflict (name) do update set last_connected_at = unixepoch() returning id`).
ToSql()
if err != nil {
return "", errors.WithMessage(err, "build query")
}
result := make(map[string]string)
err = r.db.SelectRow(ctx, &result, query, args...)
if err != nil {
return "", errors.WithMessagef(err, "select: %s", query)
}
return result["id"], nil
}
func (r Module) SetDisconnectedAtNow(
ctx context.Context,
moduleId string,
) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Module.SetDisconnectedAtNow")
query, args, err := squirrel.Update(Table("module")).
Set("last_disconnected_at", squirrel.Expr("unixepoch()")).
Where(squirrel.Eq{"id": moduleId}).
ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
_, err = r.db.Exec(ctx, query, args...)
if err != nil {
return errors.WithMessagef(err, "exec: %s", query)
}
return nil
}
func (r Module) GetByNames(ctx context.Context, names []string) ([]entity.Module, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Module.GetByNames")
query, args, err := squirrel.Select("*").
From(Table("module")).
Where(squirrel.Eq{
"name": names,
}).OrderBy("created_at desc").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.Module, 0)
err = r.db.Select(ctx, &result, query, args...)
if err != nil {
return nil, errors.WithMessagef(err, "select: %s", query)
}
return result, nil
}
func (r Module) GetById(ctx context.Context, id string) (*entity.Module, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Module.GetById")
query := fmt.Sprintf("select * from %s where id = ?", Table("module"))
return selectRow[entity.Module](ctx, r.db, query, id)
}
func (r Module) All(ctx context.Context) ([]entity.Module, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Module.All")
result := make([]entity.Module, 0)
query := fmt.Sprintf("select * from %s order by name", Table("module"))
err := r.db.Select(ctx, &result, query)
if err != nil {
return nil, errors.WithMessagef(err, "select: %s", query)
}
return result, nil
}
func (r Module) Delete(ctx context.Context, id string) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Module.Delete")
query, args, err := squirrel.Delete(Table("module")).
Where(squirrel.Eq{"id": id}).
ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
_, err = r.db.Exec(ctx, query, args...)
if err != nil {
return errors.WithMessagef(err, "exec: %s", query)
}
return nil
}
func Table(table string) string {
return fmt.Sprintf("isp_config_service__%s", table)
}
+190
View File
@@ -0,0 +1,190 @@
package repository
import (
"context"
"database/sql"
"fmt"
"strings"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"isp-config-service/entity"
"isp-config-service/middlewares/sql_metrics"
"isp-config-service/service/rqlite/db"
)
type Variable struct {
db db.DB
}
func NewVariable(db db.DB) Variable {
return Variable{
db: db,
}
}
func (r Variable) All(ctx context.Context) ([]entity.Variable, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Variable.All")
result := make([]entity.Variable, 0)
query := fmt.Sprintf("SELECT * FROM %s order by created_at desc", Table("variable"))
err := r.db.Select(ctx, &result, query)
if err != nil {
return nil, errors.WithMessagef(err, "select: %s", query)
}
return result, nil
}
func (r Variable) GetByName(ctx context.Context, name string) (*entity.Variable, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Variable.GetByName")
query, args, err := squirrel.Select("*").
From(Table("variable")).
Where(squirrel.Eq{"name": name}).
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := entity.Variable{}
err = r.db.SelectRow(ctx, &result, query, args...)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil //nolint:nilnil
}
if err != nil {
return nil, errors.WithMessagef(err, "select: %s", query)
}
return &result, nil
}
func (r Variable) Insert(ctx context.Context, variable entity.Variable) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Variable.Insert")
query, args, err := squirrel.Insert(Table("variable")).
Columns("name", "description", "type", "value").
Values(variable.Name, variable.Description, variable.Type, variable.Value).
ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
_, err = r.db.Exec(ctx, query, args...)
if err != nil {
if strings.Contains(err.Error(), "UNIQUE constraint failed") {
return entity.ErrVariableAlreadyExists
}
return errors.WithMessagef(err, "exec: %s", query)
}
return nil
}
func (r Variable) Update(ctx context.Context, variable entity.Variable) (bool, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Variable.Update")
query, args, err := squirrel.Update(Table("variable")).
SetMap(map[string]any{
"description": variable.Description,
"value": variable.Value,
"updated_at": squirrel.Expr("unixepoch()"),
}).Where(squirrel.Eq{
"name": variable.Name,
}).ToSql()
if err != nil {
return false, errors.WithMessage(err, "build query")
}
result, err := r.db.Exec(ctx, query, args...)
if err != nil {
return false, errors.WithMessagef(err, "exec: %s", query)
}
affected, err := result.RowsAffected()
if err != nil {
return false, errors.WithMessage(err, "get rows affected")
}
return affected > 0, nil
}
func (r Variable) Upsert(ctx context.Context, variables []entity.Variable) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Variable.Upsert")
requests := make([][]any, 0, len(variables))
for _, variable := range variables {
query, args, err := squirrel.Insert(Table("variable")).
Columns("name", "description", "type", "value").
Values(variable.Name, variable.Description, variable.Type, variable.Value).
Suffix(`on conflict (name) do update
set description = excluded.description,
type = excluded.type,
value = excluded.value,
updated_at = unixepoch()`,
).ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
requests = append(requests, db.Request(query, args...))
}
_, err := r.db.ExecTransaction(ctx, requests)
if err != nil {
return errors.WithMessagef(err, "exec transaction: %v", requests)
}
return nil
}
func (r Variable) UpsertLinks(ctx context.Context, configId string, links []entity.ConfigHasVariable) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Variable.UpsertLinks")
deleteQuery, args, err := squirrel.Delete(Table("config_has_variable")).Where(squirrel.Eq{
"config_id": configId,
}).ToSql()
if err != nil {
return errors.WithMessage(err, "build delete query")
}
requests := [][]any{
db.Request(deleteQuery, args...),
}
for _, variable := range links {
query, args, err := squirrel.Insert(Table("config_has_variable")).
Columns("config_id", "variable_name").
Values(variable.ConfigId, variable.VariableName).
ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
requests = append(requests, db.Request(query, args...))
}
_, err = r.db.ExecTransaction(ctx, requests)
if err != nil {
return errors.WithMessagef(err, "exec transaction: %v", requests)
}
return nil
}
func (r Variable) Delete(ctx context.Context, name string) (bool, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Variable.Delete")
query, args, err := squirrel.Delete(Table("variable")).
Where(squirrel.Eq{
"name": name,
}).ToSql()
if err != nil {
return false, errors.WithMessage(err, "build query")
}
result, err := r.db.Exec(ctx, query, args...)
if err != nil {
return false, errors.WithMessagef(err, "exec: %s", query)
}
affected, err := result.RowsAffected()
if err != nil {
return false, errors.WithMessage(err, "get rows affected")
}
return affected > 0, nil
}
+168
View File
@@ -0,0 +1,168 @@
package routes
import (
"net/http"
"isp-config-service/conf"
"github.com/txix-open/etp/v4"
"isp-config-service/controller"
"isp-config-service/controller/api"
mws "isp-config-service/middlewares"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/grpc/endpoint"
"github.com/txix-open/isp-kit/log"
)
type Controllers struct {
Module controller.Module
ModuleApi api.Module
ConfigApi api.Config
ConfigHistoryApi api.ConfigHistory
ConfigSchemaApi api.ConfigSchema
VariableApi api.Variable
}
func EndpointDescriptors() []cluster.EndpointDescriptor {
return endpointDescriptors(Controllers{})
}
func GrpcHandler(wrapper endpoint.Wrapper, c Controllers) *grpc.Mux {
muxer := grpc.NewMux()
for _, descriptor := range endpointDescriptors(c) {
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
}
return muxer
}
func BindEtp(etpSrv *etp.Server, c Controllers, logger log.Logger) {
middlewares := []mws.EtpMiddleware{
mws.EtpLogger(logger),
}
etpSrv.OnConnect(c.Module.OnConnect)
etpSrv.OnDisconnect(c.Module.OnDisconnect)
etpSrv.OnError(c.Module.OnError)
onConfigSchema := mws.EtpChain(etp.HandlerFunc(c.Module.OnModuleConfigSchema), middlewares...)
etpSrv.On(cluster.ModuleSendConfigSchema, onConfigSchema)
onRequirements := mws.EtpChain(etp.HandlerFunc(c.Module.OnModuleRequirements), middlewares...)
etpSrv.On(cluster.ModuleSendRequirements, onRequirements)
onModuleReady := mws.EtpChain(etp.HandlerFunc(c.Module.OnModuleReady), middlewares...)
etpSrv.On(cluster.ModuleReady, onModuleReady)
}
func HttpHandler(etpSrv *etp.Server, conf conf.Local, rqliteProxy, rqliteBackupProxy http.Handler) http.Handler {
httpMux := http.NewServeMux()
if conf.MaintenanceMode {
httpMux.Handle("/", rqliteProxy)
} else {
httpMux.Handle("/isp-etp/", etpSrv)
httpMux.Handle("/backup", rqliteBackupProxy)
}
return httpMux
}
// nolint:funlen
func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
// modules
{
Path: "config/module/get_modules_info",
Inner: true,
Handler: c.ModuleApi.Status,
}, {
Path: "config/module/delete_module",
Inner: true,
Handler: c.ModuleApi.DeleteModule,
}, {
Path: "config/routing/get_routes",
Inner: true,
Handler: c.ModuleApi.Connections,
},
// configs
{
Path: "config/config/get_active_config_by_module_name",
Inner: true,
Handler: c.ConfigApi.GetActiveConfigByModuleName,
}, {
Path: "config/config/get_configs_by_module_id",
Inner: true,
Handler: c.ConfigApi.GetConfigsByModuleId,
}, {
Path: "config/config/create_update_config",
Inner: true,
Handler: c.ConfigApi.CreateUpdateConfig,
}, {
Path: "config/config/get_config_by_id",
Inner: true,
Handler: c.ConfigApi.GetConfigById,
}, {
Path: "config/config/mark_config_as_active",
Inner: true,
Handler: c.ConfigApi.MarkConfigAsActive,
}, {
Path: "config/config/update_config_name",
Inner: true,
Handler: c.ConfigApi.UpdateConfigName,
}, {
Path: "config/config/delete_config",
Inner: true,
Handler: c.ConfigApi.DeleteConfigs,
}, {
Path: "config/config/sync",
Inner: true,
Handler: c.ConfigApi.SyncConfig,
}, {
Path: "config/config/get_all_version",
Inner: true,
Handler: c.ConfigHistoryApi.GetAllVersion,
}, {
Path: "config/config/delete_version",
Inner: true,
Handler: c.ConfigHistoryApi.DeleteConfigVersion,
}, {
Path: "config/config/purge_versions",
Inner: true,
Handler: c.ConfigHistoryApi.PurgeConfigVersions,
}, {
Path: "config/schema/get_by_module_id",
Inner: true,
Handler: c.ConfigSchemaApi.SchemaByModuleId,
}, {
Path: "config/schema/update_by_module_name",
Inner: true,
Handler: c.ConfigSchemaApi.UpdateSchemaByModuleName,
},
// variables
{
Path: "config/variable/all",
Inner: true,
Handler: c.VariableApi.All,
}, {
Path: "config/variable/get_by_name",
Inner: true,
Handler: c.VariableApi.GetByName,
}, {
Path: "config/variable/create",
Inner: true,
Handler: c.VariableApi.Create,
}, {
Path: "config/variable/update",
Inner: true,
Handler: c.VariableApi.Update,
}, {
Path: "config/variable/upsert",
Inner: true,
Handler: c.VariableApi.Upsert,
}, {
Path: "config/variable/delete",
Inner: true,
Handler: c.VariableApi.Delete,
},
}
}
Loaded 100 of 163 files, more files were not shown because too many files have changed in this diff. Show more