Бэкапалка таблиц mysql 8 через брокер сообщений nats

Overview

nats-mysql-tables-backup

Бэкап таблиц mysql 8 через брокер сообщений nats (проверено и работает в ubuntu 20.04, при наличии python 3.8)

ПРИМЕРЫ: Ниже приводятся примеры, которые приводятся на примере использования набора утилит nats-examples (https://github.com/nats-io/go-nats-examples/releases/download/0.0.50/go-nats-examples-v0.0.50-linux-amd64.zip)


Получение списка ранее созданных файлов архивов резервных копий:

    ./nats-req backup.listbackups "listfiles"

Результат выполнения:

    Published [backup.listbackups] : 'listfiles'
    Received  [_INBOX.NCUWVOrx7SHW05sSy4xVWo.K60eWp7p] : '{"0": "somebackup.7z"}'

В случае невозможности получения списка:

    ./nats-req backup.listbackups "listfiles"

Результат выполнения:

    Published [backup.listbackups] : 'listfiles'
    Received  [_INBOX.Boy8V1VInXgyEl1dkjmpcy.Jisakt3I] : '{}'

^ пустой список


Создание бэкапа:

Создать архив с резервными копиями таблиц можно двумя способами:

  1. При запросе необходимо передать параметр headers={json}, где формат json объекта должен представлять из себя {'tables':'table1,table2...'}.В json объекте передаются имена таблиц, которые необходимо поместить в архив резервной копии. Соответствующий запрос на языке python выглядеть будет так:
nc.request("backup.makebackup", 'makebackup'.encode(), headers={'tables':'table1,table2,table3'})

Формирование подобного запроса на других языках необходимо уточнять.

  1. Список файлов можно передать в сообщении через знак =. К примеру запрос, выполняемый через nats-req:
./nats-req backup.makebackup "makebackup=table1,table2,table3"

Результат выполнения:

Published [backup.makebackup] : 'makebackup=table1,table2,table3'
Received  [_INBOX.GFb3Zj69O4ieT3CTo6NIrs.Nzz5ApkM] : '{"status": "ok", "futurefilename": "/opt/backups/2021-11-28_17-59-19-backup.7z"}'

В случае достижения успешного результата в ответе будет получен json в виде {"status": "ok", "futurefilename": "/opt/backups/2021-11-28_17-59-19-backup.7z"}, где status - ok (процесс был запущен; futurefilename - /opt/backups/2021-11-28_17-59-19-backup.7z (обещаемое имя файла после успешного завершения процесса резервного копирования)).

В случае краха процесса будет возвращён json в виде {'status':'bad','futurefilename':''}, где status - bad (ой всё плохо); futurefilename - '' (пустая строка с обещанным файлом). Процесс создания архива производится в отдельном потоке, дабы быстрее отдать статус запрашиваемому, не удерживая соединения (дабы не отвалилось по таймауту).


Получение содержимого архива резервной копии:

Получить можно двумя способами:

  1. Разместить имя запрашиваемого архива в заголовке headers в теле запроса. Пример на языке python ниже, для остальных языков необходимо уточнение:
nc.request("backup.archive", 'archive'.encode(), headers={'archivename':'2021-11-28_20-30-39-backup.7z'})
  1. Разместить имя архива в теле сообщения через знак =. Пример с клиентом nats-req:
./nats-req backup.archive "archivename=wrong.7z"

В случае успешного получения информации будет возвращён список файлов, содержащихся в архиве. Пример:

./nats-req backup.archive "archivename=2021-11-28_20-30-39-backup.7z"
Published [backup.archive] : 'archivename=2021-11-28_20-30-39-backup.7z'
Received  [_INBOX.RJtuKZcqC65JAEWy8gMV6A.RQ5cYzMA] : '{"2021-11-28_20-30-39-backup.7z": "table1.sql,table2.sql,table3.sql"}'

В случае если архив невозможно прочитать (его не существует, он повреждён или он не является 7z архивом) будет возвращено:

./nats-req backup.archive "archivename=2021-11-28_20-30-39-backupf.7z"
Published [backup.archive] : 'archivename=2021-11-28_20-30-39-backupf.7z'
Received  [_INBOX.CnPNfscvrTQjoMlakfzVJe.15UZxvuk] : '{"2021-11-28_20-30-39-backupf.7z": "bad"}'

Восстановление таблиц в БД из резервных копий

Восстановить таблицы возможно двумя способами:

  1. Разместить имя запрашиваемого архива и перечень таблиц, необходимых для восстановления в заголовке headers. Пример на языке python, для остальных языков необходимо уточнять:
nc.request("backup.restore", 'archive'.encode(), headers={'archivename':'2021-11-28_23-49-44-backup.7z','tables':'table1.sql,table2.sql,table3.sql'})
  1. Разместить имя архива и имена таблиц в теле сообщения. В качестве разделителя между именем файла и перечнем таблиц служит - ; , а для указания имени архива и имён таблиц - = . Пример с клиентом nats-req:
./nats-req backup.restore "archive=2021-11-28_23-49-44-backup.7z;tables=table1.sql,table2.sql,table3.sql"

Восстановление производится в отдельном потоке, т.к. процесс может занять приличное время, поэтому ответ производится как можно раньше. В случае успешного запуска процесса восстановления будет получено (пример):

">
Received  [_INBOX.tNRLxow09f16DSeyRXYf6A.tNRLxow09f16DSeyRXYfAG]: '{"status": "ok"}'

   

   
./nats-req backup.restore "archive=2021-11-28_23-49-44-backup.7z;tables=table1.sql,table2.sql,table3.sql"
Published [backup.restore] : 'archive=2021-11-28_23-49-44-backup.7z;tables=table1.sql,table2.sql,table3.sql'
Received  [_INBOX.Y3K4HT267jQS6xDsI26F3z.6oVGfVpL] : '{"status": "ok"}'

В случае невозможности восстановления в выводе будет фигурировать {'status':'bad'}. Пример:

./nats-req backup.restore "archive=2021-11-28_23-49-44-backup.7z;tables=table1.sql,table2.sql,table3.sqld"
Published [backup.restore] : 'archive=2021-11-28_23-49-44-backup.7z;tables=table1.sql,table2.sql,table3.sqld'
Received  [_INBOX.DzRdPAG7u1Ew3ueQ8M6b0C.lOgyRqBl] : '{"status": "bad"}'

При использовании, в коде где будет использоваться данное решение лучше прописать исключение, что может быть получено что то неожиданное в плане вывода.

Owner
Constantine
Constantine
This repository contains completed Python projects

My Python projects This repository contains completed Python projects: 1) Build projects Guide for building projects into executable files 2) Calculat

Igor Yunusov 8 Nov 04, 2021
Python 101 Forever

🚀 Python 101 Forever 🚀 Official Python 101 Forever GitHub repository. START HERE - CHECK README SUBSCRIBE FOR UPDATES HERE Sponsors Contac

Hack Bulgaria 58 Nov 30, 2022
Integration of Hotwire's Turbo library with Flask.

turbo-flask Integration of Hotwire's Turbo library with Flask, to allow you to create applications that look and feel like single-page apps without us

Miguel Grinberg 240 Jan 06, 2023
OCR-ID-Card VietNamese (new id-card)

OCR-ID-Card VietNamese (new id-card) run project: download 2 file weights and pu

12 Jun 15, 2022
Explores the python bytecode, provides some tools to access it for fun and profit.

Pyasmtools - looking at the python bytecode for fun and profit. The pyasmtools library is made up of two parts A python bytecode disassembler . See Py

Michael Moser 299 Jan 04, 2023
This is an example manipulation package of for a robot manipulator based on Drake with ROS2.

This is an example manipulation package of for a robot manipulator based on Drake with ROS2.

Sotaro Katayama 1 Oct 21, 2021
This repo holds custom callback plugin, so your Ansible could write everything in the PostgreSQL database.

English What is it? This is callback plugin that dumps most of the Ansible internal state to the external PostgreSQL database. What is this for? If yo

Sergey Pechenko 19 Oct 21, 2022
My Solutions to 120 commonly asked data science interview questions.

Data_Science_Interview_Questions Introduction 👋 Here are the answers to 120 Data Science Interview Questions The above answer some is modified based

Milaan Parmar / Милан пармар / _米兰 帕尔马 181 Dec 31, 2022
GNU/Linux'u yeni kurulumu bitirmiş olarak açtığınızda sizi karşılayacak bir uygulama.

Hoş Geldiniz GNU/Linux'u yeni kurulumu bitirmiş olarak açtığınızda sizi karşılayacak bir uygulama.

Alperen İsa 96 Oct 30, 2022
This app is to use algorithms to find the root of the equation

In this repository, I made an amazing app with tkinter python language and other libraries the idea of this app is to use algorithms to find the root of the equation I used three methods from numeric

Mohammad Al Jadallah 3 Sep 16, 2022
Its a simple and fun to use application. You can make your own quizes and send the lik of the quiz to your friends.

Quiz Application Its a simple and fun to use application. You can make your own quizes and send the lik of the quiz to your friends. When they would a

Atharva Parkhe 1 Feb 23, 2022
Manjaro CN Repository

Manjaro CN Repository Automatically built packages based on archlinuxcn/repo and manjarocn/docker. Install Add manjarocn to /etc/pacman.conf: Please m

Manjaro CN 28 Jun 26, 2022
this is a basic python project that I made using python

this is a basic python project that I made using python. This project is only for practice because my python skills are still newbie.

Elvira Firmansyah 2 Dec 14, 2022
A python package for batch import of resume attachments to be parsed in HrFlow.

HrFlow Importer Description A python package for batch import of resume attachments to be parsed in HrFlow. hrflow-importer is an open-source project

HrFlow.ai (ex: Riminder.net) 3 Nov 15, 2022
The Doodle Master seeks to turn your UI mockups into real code.

Doodle Master The Doodle Master seeks to turn your UI mockups into real code. Currently this repository just serves to demonstrate a Proof Of Concept

Karanbir Chahal 2.4k Dec 09, 2022
List Less Than Ten with python

List Less Than Ten with python

PyLaboratory 0 Feb 07, 2022
A Python version of Canvacord

A copy of canvacord made in python! Installation Run any of these commands in terminal: Mac / Linux pip install canvacord Windows python -m pip insta

10 Mar 28, 2022
Developed a website to analyze and generate report of students based on the curriculum that represents student’s academic performance.

Developed a website to analyze and generate report of students based on the curriculum that represents student’s academic performance. We have developed the system such that, it will automatically pa

VIJETA CHAVHAN 3 Nov 08, 2022
Python Create Your Own Tool Series

Python Create Your Own Tool Series Hey there! This is an additional Github repository that contains the final product files for each video in my Youtu

Joe Helle 21 Dec 02, 2022
Python decorator for `TODO`s

Python decorator for `TODO`s. Don't let your TODOs rot in your python projects anymore !

Klemen Sever 74 Sep 13, 2022