Scheduled Backup

Auflistung von gewünschten Features, Ausschreibung zur Umsetzung
mivola
Beiträge: 34
Registriert: Fr Nov 27, 2020 9:41 am

Re: Scheduled Backup

Beitrag von mivola »

Danke an alle Mitwirkenden. Habe das Backup innerhalb von 5min auf meiner Synology eingerichtet!!

Evtl könnte man den Link zur aktuellen Version etwas prominenter (in einem der ersten Beiträge?) anbringen? Falls nicht, dann ist er zumindest jetzt hier: https://github.com/snaptec/openWB/wiki/ ... nology-nas :-)

Und ein kleiner "Schönheitsfehler" bei der Beschreibung von
"OUTPUTDIR=/volume1/backup/Smarthome/openWB_Wallbox": "Wichtig ist letzte / am Ende!" => sollte dann in dem Beispiel zumindest das letzte "/" am Ende vorhanden sein?

Danke und VG
Micha
yankee
Beiträge: 481
Registriert: Sa Mai 16, 2020 11:34 am

Re: Scheduled Backup

Beitrag von yankee »

mivola hat geschrieben: Mo Jan 10, 2022 12:59 pm Und ein kleiner "Schönheitsfehler" bei der Beschreibung von
"OUTPUTDIR=/volume1/backup/Smarthome/openWB_Wallbox": "Wichtig ist letzte / am Ende!" => sollte dann in dem Beispiel zumindest das letzte "/" am Ende vorhanden sein?
Nicht der einzige. Eigentlich soll da kein Schrägstrich hinter. Und Pfade gehen auch mit Leerzeichen und Escapes sind auch nicht nötig, wenn man Anführungszeichen verwendet. Alles gefixt.
fussi24
Beiträge: 125
Registriert: Mi Mai 13, 2020 6:36 pm

Re: Scheduled Backup

Beitrag von fussi24 »

Das Powershell Script funktioniert auch sehr gut. Der Task wird angelegt und das Backup wird erfolgreich durchgeführt.

Vielen Dank dafür.
Osoliman
Beiträge: 1
Registriert: Mi Apr 07, 2021 7:17 pm

Re: Scheduled Backup

Beitrag von Osoliman »

Hallo zusammen,
super Lösung! Auch bei mir auf Synology in 10 Minuten umgesetzt und getestet.
Vielen Dank an alle!
philipp123
Beiträge: 1032
Registriert: Mi Jul 21, 2021 3:00 pm

Re: Scheduled Backup

Beitrag von philipp123 »

Mir ist gerade meine SD-Karte abgeraucht. Backup hatte ich ja dank diesem Skript. Danke dafür!

Ein Thema ist mir dabei aufgefallen. Ich habe das Problem bemerkt, dass bei mir die Tagesgraphen nicht mehr 24h gingen. Erst im Nachgang ist mir aufgefallen, dass seit 2 Tagen bei mir die Backups kleiner statt größer wurden. Und hier jetzt meine Idee. Wäre es möglich, auf der Synology zusätzlich zum Backup auch abzufragen, ob das Backup größer als das vom Vortag ist. Wenn kleiner schicke eine Alarmmeldung? Dann könnte man schneller auf eine abrauchende SD-Karte reagieren.
LP1: openWB series2 custom mit Phasenumschaltung
LP2: go-e V2
Kostal Plenticore Plus
e-up BJ 2021, SOC mit OVMS
EQB 250 BJ 2023, SOC mit Mercedes ME über Home Assistant
EVU mit Tasmato-Lesekopf auf SmartMeter
9 x Smarthome mit Shellys
derNeueDet
Beiträge: 4197
Registriert: Mi Nov 11, 2020 7:16 pm

Re: Scheduled Backup

Beitrag von derNeueDet »

Hmm, das kann daneben gehen, da die Logfiles ja immer wieder mal gekürzt werden. Es kann also vorkommen, dass eine Sicherung vom Vortag kleiner ist als eine aktuelle Sicherung.

Bei mir z.B. in den letzten Tagen zwei Mal vorgekommen. am 21. und am 28.

Code: Alles auswählen

pi@raspi4:~/backup/openWB $ ls -ltr
insgesamt 173196
-rw-r--r-- 1 pi pi 17708470 Jan 20 00:05 openWB_backup_2022-01-20_00-05-00.tar.gz
-rw-r--r-- 1 pi pi [b]17707533[/b] Jan 21 00:05 openWB_backup_2022-01-21_00-05-00.tar.gz
-rw-r--r-- 1 pi pi 17717260 Jan 22 00:05 openWB_backup_2022-01-22_00-05-01.tar.gz
-rw-r--r-- 1 pi pi 17723409 Jan 23 00:05 openWB_backup_2022-01-23_00-05-01.tar.gz
-rw-r--r-- 1 pi pi 17732061 Jan 24 00:05 openWB_backup_2022-01-24_00-05-00.tar.gz
-rw-r--r-- 1 pi pi 17742830 Jan 25 00:05 openWB_backup_2022-01-25_00-05-00.tar.gz
-rw-r--r-- 1 pi pi 17755365 Jan 26 00:05 openWB_backup_2022-01-26_00-05-00.tar.gz
-rw-r--r-- 1 pi pi 17758853 Jan 27 00:05 openWB_backup_2022-01-27_00-05-01.tar.gz
-rw-r--r-- 1 pi pi [b]17738136[/b] Jan 28 00:05 openWB_backup_2022-01-28_00-05-01.tar.gz
-rw-r--r-- 1 pi pi 17745166 Jan 29 00:05 openWB_backup_2022-01-29_00-05-02.tar.gz
pi@raspi4:~/backup/openWB $
VG
Det
10kWp PV mit SMA Tripower 10000TL-10 (PE11 mit SDM72V2); 2,4kWp mit Solis 2.5 G6 (EE11 mit SDM120). OpenWB Standard+. EVU EM540 an einem Raspi mit Venus OS. BEV Mercedes EQA 250 (07/2023)
philipp123
Beiträge: 1032
Registriert: Mi Jul 21, 2021 3:00 pm

Re: Scheduled Backup

Beitrag von philipp123 »

Hm, das ist natürlich ein Punkt. Kann das auch 2 Tage in Folge regulär passieren?
LP1: openWB series2 custom mit Phasenumschaltung
LP2: go-e V2
Kostal Plenticore Plus
e-up BJ 2021, SOC mit OVMS
EQB 250 BJ 2023, SOC mit Mercedes ME über Home Assistant
EVU mit Tasmato-Lesekopf auf SmartMeter
9 x Smarthome mit Shellys
derNeueDet
Beiträge: 4197
Registriert: Mi Nov 11, 2020 7:16 pm

Re: Scheduled Backup

Beitrag von derNeueDet »

Naja, zumindest ist der 29. immer noch kleiner als der 27.

Sinnvoller wäre es vermutlich, das syslog entsprechend zu monitoren nach spezifischen Meldungen, die die SD Karte betreffen.

Aber in der Richtung gibt es noch nichts in der openWB.


VG
Det
10kWp PV mit SMA Tripower 10000TL-10 (PE11 mit SDM72V2); 2,4kWp mit Solis 2.5 G6 (EE11 mit SDM120). OpenWB Standard+. EVU EM540 an einem Raspi mit Venus OS. BEV Mercedes EQA 250 (07/2023)
philipp123
Beiträge: 1032
Registriert: Mi Jul 21, 2021 3:00 pm

Re: Scheduled Backup

Beitrag von philipp123 »

Ich meinte mit 2 Tage in Folge 29. < 28. und 28. < 27. Ist bei dir ja nicht so. War zumindest bei mir so, so dass die Prüfung das erkannt hätte.

Hätte ich es noch länger nicht bemerkt, wäre es bitter geworden. Die letzten beiden Backups waren schon Schrott. Ich werde auf jeden Fall bei mir das Script so einstellen, dass ich einmal die Woche ein Backup auch länger liegen lasse und nicht nur die letzten 10 Tage.

Hab mal gesucht, ob es generell was gibt, SD-Karten zu überwachen, aber irgendwie nix auf die Schnelle gefunden.
LP1: openWB series2 custom mit Phasenumschaltung
LP2: go-e V2
Kostal Plenticore Plus
e-up BJ 2021, SOC mit OVMS
EQB 250 BJ 2023, SOC mit Mercedes ME über Home Assistant
EVU mit Tasmato-Lesekopf auf SmartMeter
9 x Smarthome mit Shellys
burningbecks
Beiträge: 29
Registriert: Mo Nov 09, 2020 5:41 pm
Kontaktdaten:

Re: Scheduled Backup

Beitrag von burningbecks »

Frage zum Windows PowerShell Script von mrinas:
Hat das schonmal irgendjemand mit Username und Passwort zum Laufen gebracht? :?:
mrinas hat geschrieben: So Mai 30, 2021 1:49 pm
burningbecks hat geschrieben: So Mai 30, 2021 1:44 pm
mrinas hat geschrieben: Fr Jan 08, 2021 4:23 pm So, das hier klappt nun und verwendet den Link welchen die openWB beim Aufruf der backup.php liefert.

Ich starte das über die Aufgabenplanung auf meinem PC einmal monatlich. Im Reiter Bedingungen noch den Haken bei 'Beenden, wenn Computer in Akkubetrieb wechselt' entfernen und dafür in 'Einstellungen' den Haken bei 'Aufgabe so schnell wie möglich nach einem verpassten Start ausführen' setzen - dann wird das auch durchgeführt wenn zum Zeitpunkt des geplanten Backups der Rechner gerade nicht läuft.

Ausgeführt wird "powershell.exe" mit diesen Parametern: "-ExecutionPolicy Bypass C:\Users\martrin\OneDrive\openWB\Get-OpenWBBackup.ps1" Wobei der Pfad & Name zum Script natürlich noch auf die eigene Umgebung angepasst werden muss.

Code: Alles auswählen

# Environmental parameters
$OpenWBIP = '192.168.178.51'
$LocalBackupFolder = "$Env:UserProfile" + '\Documents\'

# Generate backup file name, change optional
$LocalBackupFileName = ("OpenWB-backup-" + (get-date -format u) + ".tar.gz").Replace(":","-")
$LocalBackupPath = $LocalBackupFolder + $LocalBackupFileName

# Path definitions, no need to change them unless openWB changes location of those files
$OpenWBBackupPath = '/openWB/web/tools/backup.php'
$URIToCall = "http://" + $OpenWBIP + $OpenWBBackupPath

$Result = Invoke-WebRequest -uri $URIToCall #create backup

if ($Result.StatusCode -eq '200') # New backup created?
{
    try 
    {
        #$OpenWBBackupDownloadPath = '/openWB/web/backup/backup.tar.gz' # We could also use $Result.Links.href to dynamically fetch location if we wanted to. Does require extra handling if more than one link is provided
        if ($Result.Links.Count -gt 1)
        {
            throw "More than one link found in response, cannot proceed."
        }
        $OpenWBBackupDownloadPath = $Result.Links.href
        $BackupURI = "http://" + $OpenWBIP + $OpenWBBackupDownloadPath
        Invoke-WebRequest -Uri $BackupURI -OutFile $LocalBackupPath # Downlaod backup and store locally
        Write-Host "Created backup at $LocalBackupPath" # we're done here
    }  
    catch 
    {
        Write-Host "Backup created but couldn't be downloaded." 
    }
}
else 
{
    Write-Host 'Unexpected return code when asking for backup:' ($Result.StatusCode) ($Result.StatusDescription)   
}
Perfekt - danke, mrinas! :)
da fällt mir ein, ich hatte ja noch eine neuere Version des Scripts erstellt. Diese Variante erstellt auch den geplanten Task und hatte noch ein paar andere Anpassungen. Muss das mal per PR einstellen, derweil hier schonmal meine aktuelle Version.


Einfach im Pfad der Wahl als Get-OpenWBBackup.ps1 abspeichern und abrufen. Ohne weitere Parameter wird nach der IP der openWB gefragt und ein geplanter Task erstellt. get-help get-openwbbackup liefert weitere Details was das Script noch so machen kann.

Code: Alles auswählen

  
<#
  .SYNOPSIS
  Creates ad-hoc and scheduled backup of openWB wallbox.
  .DESCRIPTION
    This script will create a backup of the openWB wallbox and store the backup in a folder while keeping older versions. The script can also register a scheduled task to automate the backup creation. 
    Starting the script without any parameters will 1) ask for the IP of the openWB, 2) check if a scheduled task already exists. A new task will be registered if needed and an immediate backup will be created. Script will not perform any action if backup job already exists. 
    Start script with -RunOnce parameter to perform an immediate backup without creating the scheduled task.
  .PARAMETER LocalBackupFolder
  Specifies local path to store backups. Defaults to script location
  .PARAMETER OpenWBIP
  IP of openWB, required parameter.
  .PARAMETER VerboseLogFileName
  Logfile for Verbose output, defaults to VerboseOutput.Log if not specified
  .PARAMETER AppendToLogfile
  Appends to existing verbose log file, defaults to override.
  .PARAMETER RunOnce
  Execute backup directly, skip creation of scheduled task.
    .EXAMPLE
  PS> .\Get-OpenWBBackup.ps1
  Checks for scheduled task, creates one if it doesn't exist already. openWB backup will be executed every 4 weeks, Monday at 09:00 local time. Reruns if time is missed. After creating the task an immediate backup is created. 
  Skips all actions if a scheduled task already exists.
  .EXAMPLE
  PS> .\Get-OpenWBBackup.ps1 -OpenWBIP 192.168.178.200 -RunOnce
  Performs an immediate backup of OpenWB 192.168.178.200 and skips creation of scheduled task.
  
  .NOTES
  MIT License
  Copyright (c) 2021 Martin Rinas
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
#>
[CmdletBinding()] #few examples how a script accepts input parameters
param
(
    [Parameter(Mandatory=$false)]
    [ValidateScript({Test-Path $_ })]
    [string]$LocalBackupFolder,
    [Parameter(Mandatory=$true,HelpMessage="Please enter IP of openWB")]
    [string]$OpenWBIP,
    [Parameter(Mandatory=$false)]
    [string] $VerboseLogFileName = 'VerboseOutput.Log',
    [switch]$AppendToLogfile,
    [switch]$RunOnce
)



#region function definition
function Write-VerboseLog{
    <#
        .SYNOPSIS
        Writes messages to Verbose output and Verbose log file
        .DESCRIPTION
        This fuction will direct verbose output to the console if the -Verbose 
        paramerter is specified.  It will also write output to the Verboselog.
        .EXAMPLE
        Write-VerboseLog -Message 'This is a single verbose message'
        .EXAMPLE
        # Write-VerboseLog -Message ('This is a more complex version where we want to include the value of a variable: {0}' -f ($MyVariable | Out-String) )
    #>
    param(
      [String]$Message  
    )
  
    $VerboseMessage = ('{0} Line:{1} {2}' -f (Get-Date), $MyInvocation.ScriptLineNumber, $Message)
    Write-Verbose -Message $VerboseMessage
    Add-Content -Path $VerboseLogFileName -Value $VerboseMessage
  }
function Register-OpenWBBackupTask
{
    param
    (
        [Parameter(Mandatory=$true,HelpMessage='Full path to the backup script')]
        [ValidateScript({Test-Path $_ })]
        [String]$ScriptPath,
        [Parameter(Mandatory=$true,HelpMessage='Name of backuptask')]
        [string]$TaskName,
        [Parameter(Mandatory=$true,HelpMessage='IP of OpenWB')]
        [string]$IPAddr

    )
    try 
    {
        $null = Get-ScheduledTask -TaskName $TaskName -ErrorAction stop
        Write-VerboseLog -Message ('Scheduled Task: {0} does already exist. Please delete first if you want to re-create' -f ($TaskName | Out-String) )
        Write-Error "Task $TaskName already exists. Will not re-create, please delete manually in Task Scheduler if you want to re-create. Exiting."
        break
    }
    catch 
    {
        # Scheduled Task does not exist. Creating.
        Write-VerboseLog -Message ('Scheduled task: {0} does not exist, creating.'-f ($TaskName | Out-String) )
        $WorkingDir = Split-Path $ScriptPath -Parent
        Write-VerboseLog -Message ('Setting Working directory to: {0}' -f($WorkingDir | out-string))
        $Action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-ExecutionPolicy Bypass -File  `"$ScriptPath`" -RunOnce -openWBIP $IPAddr" -WorkingDirectory $WorkingDir
        $Trigger = New-ScheduledTaskTrigger -Weekly -WeeksInterval 4 -At '09:00' -DaysOfWeek Monday
        $Principal = New-ScheduledTaskPrincipal -LogonType Interactive -Id Author -UserId $env:USERNAME -RunLevel Limited -ProcessTokenSidType Default
        $Settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Hours 1) -StartWhenAvailable -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries
        $ScheduledTask = New-ScheduledTask -Action $Action -Principal $Principal -Settings $Settings -Trigger $Trigger -Description 'OpenWB BackupJob'
        Register-ScheduledTask $TaskName -InputObject $ScheduledTask -ErrorAction Stop
    }

}

#endregion

#region variable definition
if ([string]::IsNullOrEmpty($LocalBackupFolder))
{
    $LocalBackupFolder = (Split-path $MyInvocation.MyCommand.Path -parent)
    Write-VerboseLog -Message ('LocalBackupFolder was empty, set to {0}' -f ($LocalBackupFolder))
}

if([string]::IsNullOrEmpty($ScriptLocation))
{
    $ScriptLocation = (Split-path $MyInvocation.MyCommand.Path -parent)
    Write-VerboseLog -Message ('ScriptLocation was empty, set to {0}' -f ($ScriptLocation))
}

$LocalBackupFileName = ("OpenWB-backup-" + (get-date -format u) + ".tar.gz").Replace(":","-")
$LocalBackupPath = $LocalBackupFolder + '\' + $LocalBackupFileName
$OpenWBBackupPath = '/openWB/web/settings/backup.php'
$URIToCall = "http://" + $OpenWBIP + $OpenWBBackupPath
$BackupTaskName = 'openWB Backup'
$ScriptName = $MyInvocation.MyCommand

#endregion

#region main script
if (!$AppendToLogfile)
{
    $null = New-Item -Path $VerboseLogFileName -ItemType File -Force
    Write-VerboseLog -Message 'Script started'
    Write-VerboseLog -Message ('Parameters: {0}' -f ($MyInvocation | Out-String) )
}
else 
{
    Write-VerboseLog -Message 'Script started, appending to existing log'
}

if ($RunOnce)
{
    Write-VerboseLog 'Skip scheduled task and executy directly'
}
else
{
    # check for and create scheduled task
    Write-VerboseLog -message ('Checking for existence of scheduled task: {0} and creating if needed. ' -f ($BackupTaskName) )
    
    try 
    {
        $null = Get-ScheduledTask -TaskName $BackupTaskName -ErrorAction stop
        Write-VerboseLog -Message ('Scheduled Task: {0} does already exist. ' -f ($BackupTaskName) )
        $BackupTaskExists = $True
    }
    catch 
    {
        Write-VerboseLog -Message ('Scheduled Task: {0} does not exist. ' -f ($BackupTaskName) )
        $BackupTaskExists = $False
    }

    if ($BackupTaskExists)
    {
        Write-VerboseLog -Message ('nothing to do.' -f ($BackupTaskName) )
        Write-Host "Backupjob $BackupTaskName already exists, nothing to do. Exiting..."
        exit
    }
    else
    {
        Write-VerboseLog -Message ('BackupTask: {0} does not already exist, creating.' -f ($BackupTaskName) )    
        Write-Host "Creating scheduled backup task for openWB"
        $FullScriptPath = $ScriptLocation + '\' + $ScriptName
        Write-VerboseLog -Message ('Full script location: {0}' -f ($FullScriptPath| Out-String))
        Register-OpenWBBackupTask -TaskName $BackupTaskName -ScriptPath $FullScriptPath -IPAddr $OpenWBIP
        Write-Host "Creating one backup immediately."
    }
}

Write-VerboseLog -Message ('Using this as backup path to store file: {0}' -f ($LocalBackupPath | Out-String) )

Write-Host "Starting backup of openWB"
Write-VerboseLog -Message ('Triggering openWB backup creation by calling: {0}' -f ($URIToCall | Out-String) )
$Result = Invoke-WebRequest -uri $URIToCall -UseBasicParsing  #create backup

if ($Result.StatusCode -eq '200') # New backup created?
{
    try 
    {
        #$OpenWBBackupDownloadPath = '/openWB/web/backup/backup.tar.gz' # We could also use $Result.Links.href to dynamically fetch location if we wanted to. Does require extra handling if more than one link is provided
        if ($Result.Links.Count -gt 1)
        {
            Write-VerboseLog -Message ('More than one link found in response: {0}' -f ($result.links | Out-String) )
            throw "More than one link found in response, cannot proceed."
        }
        $OpenWBBackupDownloadPath = $Result.Links.href
        $BackupURI = "http://" + $OpenWBIP + $OpenWBBackupDownloadPath
        Write-VerboseLog -Message ( 'Backup generated, downloading from: {0} to : {1}' -f ($BackupURI | Out-String), ($LocalBackupPath | Out-String) )
        Invoke-WebRequest -Uri $BackupURI -OutFile $LocalBackupPath # Downlaod backup and store locally
        Write-Host "Created backup at $LocalBackupPath" # we're done here
        Write-VerboseLog -Message 'Download completed.'
    }  
    catch 
    {
        Write-VerboseLog 'Backup created bout could not be downloaded'
        Write-Host "Backup created but couldn't be downloaded." 
    }
}
else 
{
    Write-VerboseLog -Message ( 'Unexpected return code when asking for backup: {0} {1}' -f ($result.StatusCode | Out-String), ($Result.StatusDescription | Out-String ) )
    Write-Host 'Unexpected return code when asking for backup:' ($Result.StatusCode) ($Result.StatusDescription)   
}
#endregion
BMW i3s, go-eCharger Gemini (22kW FIX).
openWB Standalone + EVU Kit v2 MID als Lastmanager.
Antworten