Skip to content

Commit 3f40f50

Browse files
author
anton.voskresensky
committed
add action params
1 parent 2a55a97 commit 3f40f50

File tree

11 files changed

+350
-75
lines changed

11 files changed

+350
-75
lines changed

Dockerfile

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,12 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
3232
mtr-tiny \
3333
&& rm -rf /var/lib/apt/lists/*
3434

35-
COPY --from=builder /app/osctl /usr/local/bin/osctl
35+
RUN mkdir -p /app/osctl
3636

37-
RUN chmod +x /usr/local/bin/osctl
37+
COPY --from=builder /app/osctl /app/osctl
3838

39-
CMD ["/usr/local/bin/osctl"]
39+
RUN chmod +x /app/osctl
40+
41+
ENV PATH="/app:${PATH}"
42+
43+
CMD ["/app/osctl"]

ENVIRONMENT_VARIABLES_AND_FLAGS.md

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
| Флаг | Переменная окружения | Описание | Значение по умолчанию |
1919
|------|---------------------|----------|--------------|
20+
| `--action` | `OSCTL_ACTION` | Автоматически выполнить команду (snapshot, retention, dereplicator, etc.) | (пусто) |
2021
| `--config` | `OSCTL_CONFIG` | Путь к файлу конфигурации | `config.yaml` |
2122
| `--os-url` | `OPENSEARCH_URL` | URL OpenSearch | `https://opendistro:9200` |
2223
| `--os-recoverer-url` | `OPENSEARCH_RECOVERER_URL` | URL OpenSearch Recoverer | `https://opendistro-recoverer:9200` |
@@ -35,6 +36,42 @@
3536
| `--dry-run` | `DRY_RUN` | Показать что будет сделано без выполнения | `false` |
3637
| `--snap-repo` | `SNAPSHOT_REPOSITORY` | Название репо для снапшотов | (пусто) |
3738

39+
## Параметр action
40+
41+
Параметр `action` позволяет автоматически выполнить нужную команду без указания её в командной строке. Сделано для деплойментов и кронджоб в Kubernetes.
42+
43+
### Доступные значения action:
44+
- `snapshot` - Создание снапшотов индексов
45+
- `snapshot-manual` - Ручное создание снапшотов
46+
- `snapshotdelete` - Удаление старых снапшотов
47+
- `snapshotchecker` - Проверка отсутствующих снапшотов
48+
- `indicesdelete` - Удаление старых индексов
49+
- `retention` - Управление дисковым пространством
50+
- `dereplicator` - Уменьшение реплик для старых индексов
51+
- `coldstorage` - Перемещение индексов в холодное хранилище
52+
- `extracteddelete` - Удаление извлеченных индексов
53+
- `danglingchecker` - Проверка висячих индексов
54+
55+
### Примеры использования:
56+
57+
**В config.yaml:**
58+
```yaml
59+
action: "snapshot"
60+
opensearch_url: "https://opendistro:9200"
61+
# остальные настройки...
62+
```
63+
64+
**Через переменную окружения:**
65+
```bash
66+
export OSCTL_ACTION=retention
67+
osctl
68+
```
69+
70+
**Через флаг:**
71+
```bash
72+
osctl --action=snapshot
73+
```
74+
3875
## Флаги команд
3976

4077
### `coldstorage`
@@ -102,6 +139,3 @@
102139
| `--snapshot-manual-value` | `SNAPSHOT_VALUE` | Значение паттерна | (пусто) |
103140
| `--snapshot-manual-name` | `SNAPSHOT_NAME` | Имя снапшота (обязательно для regex) | (пусто) |
104141
| `--snapshot-manual-system` | `SNAPSHOT_SYSTEM` | Флаг системного индекса (получает индексы с точкой, независимо от даты) | `false` |
105-
| `--snapshot-manual-days-count` | `SNAPSHOT_DAYS_COUNT` | Какое количество дней держать индекс | `7` |
106-
| `--snapshot-manual-count-s3` | `SNAPSHOT_COUNT_S3` | Какое количество дней хранить снапшот в S3 | `14` |
107-

README.md

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,33 @@
11
# osctl - Инструмент управления жизненным циклом индексов и снапшотов OpenSearch
22

3-
По-умолчанию предполагается использование `config.yaml` в котором описаны параметры запуска, а также указание конкретной команды, которая будет выполнять действие. Для некоторых действий также требуется файлик osctlindicesconfig.yaml ( пример в config-example) с описанием паттернов индексов и числом дней хранения.
3+
По-умолчанию предполагается использование `config.yaml` в котором описаны параметры запуска. Для автоматического выполнения команд можно использовать параметр `action`.
44

5-
```bash
6-
osctl snapshot
5+
Все, что указано в конфгиах можно переопределять через флаги, а также большинство команд поддерживают `--dry-run`.
76

8-
osctl snapshot-manual --snapshot-manual-kind=prefix --snapshot-manual-value=prod --snapshot-manual-days-count=14
7+
## Быстрый старт
98

10-
osctl retention --retention-threshold=75 --snap-repo=s3-backup
11-
osctl dereplicator --dereplicator-days-count=7 --dereplicator-use-snapshot
9+
### Использование с параметром action (рекомендуется)
10+
```bash
11+
# Создать config.yaml с нужной командой
12+
cat > config.yaml << EOF
13+
action: "snapshot"
14+
opensearch_url: "https://your-opensearch:9200"
15+
cert_file: "/path/to/cert.pem"
16+
key_file: "/path/to/key.pem"
17+
ca_file: "/path/to/ca.pem"
18+
EOF
19+
20+
# Запустить osctl - команда выполнится автоматически
21+
osctl
22+
```
1223

13-
osctl extracteddelete --days=7
14-
osctl coldstorage --hot-count=7 --cold-attribute=cold
24+
### Вариант использования через команды и флаги
25+
```bash
26+
osctl snapshot --config=config.yaml --osctl-indices-config=osctlindicesconfig.yaml
27+
osctl snapshotdelete --dry-run
1528
```
1629

17-
## Команды
30+
## Доступные команды (action)
1831

1932
| Команда | Назначение |
2033
|---------|------------|
@@ -37,7 +50,7 @@ osctl coldstorage --hot-count=7 --cold-attribute=cold
3750

3851
### Конфигурация индексов (`osctlindicesconfig.yaml`)
3952

40-
Пример в `osctlindicesconfig.yaml`
53+
Пример в `config-example/osctlindicesconfig.yaml`
4154

4255
## Приоритет конфигурации
4356

commands/root.go

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"osctl/pkg/config"
66

77
"github.com/spf13/cobra"
8+
"github.com/spf13/pflag"
89
)
910

1011
var rootCmd = &cobra.Command{
@@ -26,6 +27,37 @@ Available Commands:
2627
datasource Create Kibana data sources
2728
coldstorage Migrate indices to cold storage nodes
2829
extracteddelete Delete extracted indices that are no longer needed`,
30+
RunE: func(cmd *cobra.Command, args []string) error {
31+
32+
actionFlag, _ := cmd.Flags().GetString("action")
33+
if actionFlag != "" {
34+
if err := config.ValidateAction(actionFlag); err != nil {
35+
fmt.Printf("Error: %v\n", err)
36+
return err
37+
}
38+
39+
if err := config.LoadConfig(cmd, "root"); err != nil {
40+
fmt.Printf("Error: Could not load config: %v\n", err)
41+
return err
42+
}
43+
return executeActionCommand(actionFlag, args)
44+
}
45+
46+
if err := config.LoadConfig(cmd, "root"); err != nil {
47+
fmt.Printf("Error: Could not load config: %v\n", err)
48+
return err
49+
}
50+
cfg := config.GetConfig()
51+
if cfg.Action != "" {
52+
if err := config.ValidateAction(cfg.Action); err != nil {
53+
fmt.Printf("Error: %v\n", err)
54+
return err
55+
}
56+
return executeActionCommand(cfg.Action, args)
57+
}
58+
59+
return cmd.Help()
60+
},
2961
}
3062

3163
func Execute() error {
@@ -46,7 +78,53 @@ func Execute() error {
4678
return rootCmd.Execute()
4779
}
4880

81+
func executeActionCommand(action string, args []string) error {
82+
83+
var targetCmd *cobra.Command
84+
85+
switch action {
86+
case "snapshot":
87+
targetCmd = snapshotCmd
88+
case "snapshot-manual":
89+
targetCmd = snapshotManualCmd
90+
case "snapshotdelete":
91+
targetCmd = snapshotDeleteCmd
92+
case "snapshotchecker":
93+
targetCmd = snapshotCheckerCmd
94+
case "indicesdelete":
95+
targetCmd = indicesDeleteCmd
96+
case "retention":
97+
targetCmd = retentionCmd
98+
case "dereplicator":
99+
targetCmd = dereplicatorCmd
100+
case "coldstorage":
101+
targetCmd = coldStorageCmd
102+
case "extracteddelete":
103+
targetCmd = extractedDeleteCmd
104+
case "danglingchecker":
105+
targetCmd = danglingCheckerCmd
106+
default:
107+
return fmt.Errorf("unknown action: %s", action)
108+
}
109+
110+
targetCmd.SetArgs(args)
111+
112+
newCmd := &cobra.Command{
113+
Use: targetCmd.Use,
114+
Short: targetCmd.Short,
115+
Long: targetCmd.Long,
116+
RunE: targetCmd.RunE,
117+
}
118+
119+
targetCmd.Flags().VisitAll(func(flag *pflag.Flag) {
120+
newCmd.Flags().AddFlag(flag)
121+
})
122+
123+
return newCmd.Execute()
124+
}
125+
49126
func init() {
127+
addFlags(rootCmd)
50128
rootCmd.AddCommand(snapshotCmd)
51129
rootCmd.AddCommand(snapshotManualCmd)
52130
rootCmd.AddCommand(snapshotDeleteCmd)
@@ -63,6 +141,7 @@ func init() {
63141
}
64142

65143
func addFlags(cmd *cobra.Command) {
144+
cmd.PersistentFlags().String("action", "", "Action to execute (snapshot, retention, dereplicator, etc.)")
66145
cmd.PersistentFlags().String("config", "", "Path to configuration file")
67146
cmd.PersistentFlags().String("os-url", "", "OpenSearch URL")
68147
cmd.PersistentFlags().String("cert-file", "", "Certificate file path")

commands/snapshotmanual.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,6 @@ func runSnapshotManual(cmd *cobra.Command, args []string) error {
3333
value := cfg.SnapshotManualValue
3434
name := cfg.SnapshotManualName
3535
system, _ := strconv.ParseBool(cfg.SnapshotManualSystem)
36-
daysCount, _ := strconv.Atoi(cfg.SnapshotManualDaysCount)
37-
snapshotCountS3, _ := strconv.Atoi(cfg.SnapshotManualCountS3)
3836

3937
if value == "" {
4038
return fmt.Errorf("value is required")
@@ -44,7 +42,7 @@ func runSnapshotManual(cmd *cobra.Command, args []string) error {
4442
return fmt.Errorf("name is required for regex patterns")
4543
}
4644

47-
logger.Info(fmt.Sprintf("Starting manual snapshot creation kind=%s value=%s name=%s system=%t daysCount=%d snapshotCountS3=%d", kind, value, name, system, daysCount, snapshotCountS3))
45+
logger.Info(fmt.Sprintf("Starting manual snapshot creation kind=%s value=%s name=%s system=%t daysCount=%d snapshotCountS3=%d", kind, value, name, system))
4846

4947
client, err := opensearch.NewClient(cfg.OpenSearchURL, cfg.CertFile, cfg.KeyFile, cfg.CAFile, cfg.GetTimeout(), cfg.GetRetryAttempts())
5048
if err != nil {
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
apiVersion: apps/v1
2+
kind: Deployment
3+
metadata:
4+
name: osctl-snapshot
5+
namespace: infra-elklogs
6+
spec:
7+
replicas: 1
8+
selector:
9+
matchLabels:
10+
app: osctl-snapshot
11+
template:
12+
metadata:
13+
labels:
14+
app: osctl-snapshot
15+
spec:
16+
containers:
17+
- name: osctl-snapshot
18+
image: ghcr.io/flant/osctl:latest
19+
volumeMounts:
20+
- mountPath: /app/config.yaml
21+
name: config
22+
subPath: config.yaml
23+
- mountPath: /app/osctlindicesconfig.yaml
24+
name: config
25+
subPath: osctlindicesconfig.yaml
26+
- mountPath: /etc/ssl/certs/elk-crt.pem
27+
name: certs
28+
readOnly: true
29+
subPath: elk-crt.pem
30+
- mountPath: /etc/ssl/certs/elk-key.pem
31+
name: certs
32+
readOnly: true
33+
subPath: elk-key.pem
34+
- mountPath: /etc/ssl/certs/elk-root-ca.pem
35+
name: certs
36+
readOnly: true
37+
subPath: elk-root-ca.pem
38+
volumes:
39+
- name: config
40+
configMap:
41+
name: osctl-config
42+
- name: certs
43+
secret:
44+
secretName: opendistro-tls-data

config-example/helm-configmap.yaml

Lines changed: 0 additions & 29 deletions
This file was deleted.

0 commit comments

Comments
 (0)