diff --git a/README.md b/README.md index d9c1fc7..737f3d8 100644 --- a/README.md +++ b/README.md @@ -14,10 +14,12 @@ # velero-notifications -This is a simple Kubernetes controller written in Crystal that sends Email/Slack/webhook notifications when backups are performed by [Velero](https://velero.io/) in a [Kubernetes](https://kubernetes.io/) cluster. +This is a simple Kubernetes controller written in Crystal that sends Email/Slack/Discord/webhook notifications when backups are performed by [Velero](https://velero.io/) in a [Kubernetes](https://kubernetes.io/) cluster. ![Screenshot](slack.png?raw=true "Screenshot") +![Screenshot](discord.png?raw=true "Screenshot") + If you like this or any of my other projects and would like to help with their development, consider [becoming a sponsor](https://github.com/sponsors/vitobotta). ## Installation @@ -35,6 +37,12 @@ helm upgrade --install \ --set slack.webhook=https://... \ --set slack.channel=velero \ --set slack.username=Velero \ + --set discord.enabled=true \ + --set discord.failures_only=false \ + --set discord.webhook=https://... \ + --set discord.mentions.enabled=false \ + --set discord.mentions.failures_only=true \ + --set discord.mentions.role_id="1234567890" \ --set email.enabled=true \ --set email.failures_only=true \ --set email.smtp.host=... \ diff --git a/bin/build b/bin/build index 3f8ee4b..f17d5bf 100755 --- a/bin/build +++ b/bin/build @@ -1,9 +1,9 @@ #!/bin/bash -docker run --rm -it --platform=linux/amd64 -v $(pwd):/workspace -w /workspace crystallang/crystal:latest-alpine crystal build src/velero-notifications.cr --static +docker run --rm -it --platform=linux/amd64 -v $(pwd):/workspace -w /workspace crystallang/crystal:latest-alpine /bin/sh -c "shards install && crystal run ./lib/k8s/bin/gen_crd.cr -- ./crds.yaml ./src/crds && crystal build src/velero-notifications.cr --static" -IMAGE="vitobotta/velero-backup-notification" +IMAGE="woutthenines/velero-backup-notification" VERSION="$(git describe --tags --abbrev=0)" docker build --platform=linux -t ${IMAGE}:${VERSION} . diff --git a/crds.yaml b/crds.yaml index 07496b5..c697675 100644 --- a/crds.yaml +++ b/crds.yaml @@ -1,20 +1,11 @@ +--- apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - controller-gen.kubebuilder.io/version: v0.7.0 - kubectl.kubernetes.io/last-applied-configuration: | - {"apiVersion":"apiextensions.k8s.io/v1","kind":"CustomResourceDefinition","metadata":{"annotations":{"controller-gen.kubebuilder.io/version":"v0.7.0"},"creationTimestamp":null,"labels":{"component":"velero"},"name":"backups.velero.io"},"spec":{"group":"velero.io","names":{"kind":"Backup","listKind":"BackupList","plural":"backups","singular":"backup"},"scope":"Namespaced","versions":[{"name":"v1","schema":{"openAPIV3Schema":{"description":"Backup is a Velero resource that represents the capture of Kubernetes cluster state at a point in time (API objects and associated volume state).","properties":{"apiVersion":{"description":"APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources","type":"string"},"kind":{"description":"Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds","type":"string"},"metadata":{"type":"object"},"spec":{"description":"BackupSpec defines the specification for a Velero backup.","properties":{"csiSnapshotTimeout":{"description":"CSISnapshotTimeout specifies the time used to wait for CSI VolumeSnapshot status turns to ReadyToUse during creation, before returning error as timeout. The default value is 10 minute.","type":"string"},"defaultVolumesToFsBackup":{"description":"DefaultVolumesToFsBackup specifies whether pod volume file system backup should be used for all volumes by default.","nullable":true,"type":"boolean"},"defaultVolumesToRestic":{"description":"DefaultVolumesToRestic specifies whether restic should be used to take a backup of all pod volumes by default. \n Deprecated: this field is no longer used and will be removed entirely in future. Use DefaultVolumesToFsBackup instead.","nullable":true,"type":"boolean"},"excludedClusterScopedResources":{"description":"ExcludedClusterScopedResources is a slice of cluster-scoped resource type names to exclude from the backup. If set to \"*\", all cluster-scoped resource types are excluded. The default value is empty.","items":{"type":"string"},"nullable":true,"type":"array"},"excludedNamespaceScopedResources":{"description":"ExcludedNamespaceScopedResources is a slice of namespace-scoped resource type names to exclude from the backup. If set to \"*\", all namespace-scoped resource types are excluded. The default value is empty.","items":{"type":"string"},"nullable":true,"type":"array"},"excludedNamespaces":{"description":"ExcludedNamespaces contains a list of namespaces that are not included in the backup.","items":{"type":"string"},"nullable":true,"type":"array"},"excludedResources":{"description":"ExcludedResources is a slice of resource names that are not included in the backup.","items":{"type":"string"},"nullable":true,"type":"array"},"hooks":{"description":"Hooks represent custom behaviors that should be executed at different phases of the backup.","properties":{"resources":{"description":"Resources are hooks that should be executed when backing up individual instances of a resource.","items":{"description":"BackupResourceHookSpec defines one or more BackupResourceHooks that should be executed based on the rules defined for namespaces, resources, and label selector.","properties":{"excludedNamespaces":{"description":"ExcludedNamespaces specifies the namespaces to which this hook spec does not apply.","items":{"type":"string"},"nullable":true,"type":"array"},"excludedResources":{"description":"ExcludedResources specifies the resources to which this hook spec does not apply.","items":{"type":"string"},"nullable":true,"type":"array"},"includedNamespaces":{"description":"IncludedNamespaces specifies the namespaces to which this hook spec applies. If empty, it applies to all namespaces.","items":{"type":"string"},"nullable":true,"type":"array"},"includedResources":{"description":"IncludedResources specifies the resources to which this hook spec applies. If empty, it applies to all resources.","items":{"type":"string"},"nullable":true,"type":"array"},"labelSelector":{"description":"LabelSelector, if specified, filters the resources to which this hook spec applies.","nullable":true,"properties":{"matchExpressions":{"description":"matchExpressions is a list of label selector requirements. The requirements are ANDed.","items":{"description":"A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values.","properties":{"key":{"description":"key is the label key that the selector applies to.","type":"string"},"operator":{"description":"operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist.","type":"string"},"values":{"description":"values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.","items":{"type":"string"},"type":"array"}},"required":["key","operator"],"type":"object"},"type":"array"},"matchLabels":{"additionalProperties":{"type":"string"},"description":"matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.","type":"object"}},"type":"object"},"name":{"description":"Name is the name of this hook.","type":"string"},"post":{"description":"PostHooks is a list of BackupResourceHooks to execute after storing the item in the backup. These are executed after all \"additional items\" from item actions are processed.","items":{"description":"BackupResourceHook defines a hook for a resource.","properties":{"exec":{"description":"Exec defines an exec hook.","properties":{"command":{"description":"Command is the command and arguments to execute.","items":{"type":"string"},"minItems":1,"type":"array"},"container":{"description":"Container is the container in the pod where the command should be executed. If not specified, the pod's first container is used.","type":"string"},"onError":{"description":"OnError specifies how Velero should behave if it encounters an error executing this hook.","enum":["Continue","Fail"],"type":"string"},"timeout":{"description":"Timeout defines the maximum amount of time Velero should wait for the hook to complete before considering the execution a failure.","type":"string"}},"required":["command"],"type":"object"}},"required":["exec"],"type":"object"},"type":"array"},"pre":{"description":"PreHooks is a list of BackupResourceHooks to execute prior to storing the item in the backup. These are executed before any \"additional items\" from item actions are processed.","items":{"description":"BackupResourceHook defines a hook for a resource.","properties":{"exec":{"description":"Exec defines an exec hook.","properties":{"command":{"description":"Command is the command and arguments to execute.","items":{"type":"string"},"minItems":1,"type":"array"},"container":{"description":"Container is the container in the pod where the command should be executed. If not specified, the pod's first container is used.","type":"string"},"onError":{"description":"OnError specifies how Velero should behave if it encounters an error executing this hook.","enum":["Continue","Fail"],"type":"string"},"timeout":{"description":"Timeout defines the maximum amount of time Velero should wait for the hook to complete before considering the execution a failure.","type":"string"}},"required":["command"],"type":"object"}},"required":["exec"],"type":"object"},"type":"array"}},"required":["name"],"type":"object"},"nullable":true,"type":"array"}},"type":"object"},"includeClusterResources":{"description":"IncludeClusterResources specifies whether cluster-scoped resources should be included for consideration in the backup.","nullable":true,"type":"boolean"},"includedClusterScopedResources":{"description":"IncludedClusterScopedResources is a slice of cluster-scoped resource type names to include in the backup. If set to \"*\", all cluster-scoped resource types are included. The default value is empty, which means only related cluster-scoped resources are included.","items":{"type":"string"},"nullable":true,"type":"array"},"includedNamespaceScopedResources":{"description":"IncludedNamespaceScopedResources is a slice of namespace-scoped resource type names to include in the backup. The default value is \"*\".","items":{"type":"string"},"nullable":true,"type":"array"},"includedNamespaces":{"description":"IncludedNamespaces is a slice of namespace names to include objects from. If empty, all namespaces are included.","items":{"type":"string"},"nullable":true,"type":"array"},"includedResources":{"description":"IncludedResources is a slice of resource names to include in the backup. If empty, all resources are included.","items":{"type":"string"},"nullable":true,"type":"array"},"itemOperationTimeout":{"description":"ItemOperationTimeout specifies the time used to wait for asynchronous BackupItemAction operations The default value is 1 hour.","type":"string"},"labelSelector":{"description":"LabelSelector is a metav1.LabelSelector to filter with when adding individual objects to the backup. If empty or nil, all objects are included. Optional.","nullable":true,"properties":{"matchExpressions":{"description":"matchExpressions is a list of label selector requirements. The requirements are ANDed.","items":{"description":"A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values.","properties":{"key":{"description":"key is the label key that the selector applies to.","type":"string"},"operator":{"description":"operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist.","type":"string"},"values":{"description":"values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.","items":{"type":"string"},"type":"array"}},"required":["key","operator"],"type":"object"},"type":"array"},"matchLabels":{"additionalProperties":{"type":"string"},"description":"matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.","type":"object"}},"type":"object"},"metadata":{"properties":{"labels":{"additionalProperties":{"type":"string"},"type":"object"}},"type":"object"},"orLabelSelectors":{"description":"OrLabelSelectors is list of metav1.LabelSelector to filter with when adding individual objects to the backup. If multiple provided they will be joined by the OR operator. LabelSelector as well as OrLabelSelectors cannot co-exist in backup request, only one of them can be used.","items":{"description":"A label selector is a label query over a set of resources. The result of matchLabels and matchExpressions are ANDed. An empty label selector matches all objects. A null label selector matches no objects.","properties":{"matchExpressions":{"description":"matchExpressions is a list of label selector requirements. The requirements are ANDed.","items":{"description":"A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values.","properties":{"key":{"description":"key is the label key that the selector applies to.","type":"string"},"operator":{"description":"operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist.","type":"string"},"values":{"description":"values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.","items":{"type":"string"},"type":"array"}},"required":["key","operator"],"type":"object"},"type":"array"},"matchLabels":{"additionalProperties":{"type":"string"},"description":"matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.","type":"object"}},"type":"object"},"nullable":true,"type":"array"},"orderedResources":{"additionalProperties":{"type":"string"},"description":"OrderedResources specifies the backup order of resources of specific Kind. The map key is the resource name and value is a list of object names separated by commas. Each resource name has format \"namespace/objectname\". For cluster resources, simply use \"objectname\".","nullable":true,"type":"object"},"resourcePolicy":{"description":"ResourcePolicy specifies the referenced resource policies that backup should follow","properties":{"apiGroup":{"description":"APIGroup is the group for the resource being referenced. If APIGroup is not specified, the specified Kind must be in the core API group. For any other third-party types, APIGroup is required.","type":"string"},"kind":{"description":"Kind is the type of resource being referenced","type":"string"},"name":{"description":"Name is the name of resource being referenced","type":"string"}},"required":["kind","name"],"type":"object"},"snapshotVolumes":{"description":"SnapshotVolumes specifies whether to take snapshots of any PV's referenced in the set of objects included in the Backup.","nullable":true,"type":"boolean"},"storageLocation":{"description":"StorageLocation is a string containing the name of a BackupStorageLocation where the backup should be stored.","type":"string"},"ttl":{"description":"TTL is a time.Duration-parseable string describing how long the Backup should be retained for.","type":"string"},"volumeSnapshotLocations":{"description":"VolumeSnapshotLocations is a list containing names of VolumeSnapshotLocations associated with this backup.","items":{"type":"string"},"type":"array"}},"type":"object"},"status":{"description":"BackupStatus captures the current status of a Velero backup.","properties":{"backupItemOperationsAttempted":{"description":"BackupItemOperationsAttempted is the total number of attempted async BackupItemAction operations for this backup.","type":"integer"},"backupItemOperationsCompleted":{"description":"BackupItemOperationsCompleted is the total number of successfully completed async BackupItemAction operations for this backup.","type":"integer"},"backupItemOperationsFailed":{"description":"BackupItemOperationsFailed is the total number of async BackupItemAction operations for this backup which ended with an error.","type":"integer"},"completionTimestamp":{"description":"CompletionTimestamp records the time a backup was completed. Completion time is recorded even on failed backups. Completion time is recorded before uploading the backup object. The server's time is used for CompletionTimestamps","format":"date-time","nullable":true,"type":"string"},"csiVolumeSnapshotsAttempted":{"description":"CSIVolumeSnapshotsAttempted is the total number of attempted CSI VolumeSnapshots for this backup.","type":"integer"},"csiVolumeSnapshotsCompleted":{"description":"CSIVolumeSnapshotsCompleted is the total number of successfully completed CSI VolumeSnapshots for this backup.","type":"integer"},"errors":{"description":"Errors is a count of all error messages that were generated during execution of the backup. The actual errors are in the backup's log file in object storage.","type":"integer"},"expiration":{"description":"Expiration is when this Backup is eligible for garbage-collection.","format":"date-time","nullable":true,"type":"string"},"failureReason":{"description":"FailureReason is an error that caused the entire backup to fail.","type":"string"},"formatVersion":{"description":"FormatVersion is the backup format version, including major, minor, and patch version.","type":"string"},"phase":{"description":"Phase is the current state of the Backup.","enum":["New","FailedValidation","InProgress","WaitingForPluginOperations","WaitingForPluginOperationsPartiallyFailed","Finalizing","FinalizingPartiallyFailed","Completed","PartiallyFailed","Failed","Deleting"],"type":"string"},"progress":{"description":"Progress contains information about the backup's execution progress. Note that this information is best-effort only -- if Velero fails to update it during a backup for any reason, it may be inaccurate/stale.","nullable":true,"properties":{"itemsBackedUp":{"description":"ItemsBackedUp is the number of items that have actually been written to the backup tarball so far.","type":"integer"},"totalItems":{"description":"TotalItems is the total number of items to be backed up. This number may change throughout the execution of the backup due to plugins that return additional related items to back up, the velero.io/exclude-from-backup label, and various other filters that happen as items are processed.","type":"integer"}},"type":"object"},"startTimestamp":{"description":"StartTimestamp records the time a backup was started. Separate from CreationTimestamp, since that value changes on restores. The server's time is used for StartTimestamps","format":"date-time","nullable":true,"type":"string"},"validationErrors":{"description":"ValidationErrors is a slice of all validation errors (if applicable).","items":{"type":"string"},"nullable":true,"type":"array"},"version":{"description":"Version is the backup format major version. Deprecated: Please see FormatVersion","type":"integer"},"volumeSnapshotsAttempted":{"description":"VolumeSnapshotsAttempted is the total number of attempted volume snapshots for this backup.","type":"integer"},"volumeSnapshotsCompleted":{"description":"VolumeSnapshotsCompleted is the total number of successfully completed volume snapshots for this backup.","type":"integer"},"warnings":{"description":"Warnings is a count of all warning messages that were generated during execution of the backup. The actual warnings are in the backup's log file in object storage.","type":"integer"}},"type":"object"}},"type":"object"}},"served":true,"storage":true}]}} - creationTimestamp: "2023-04-16T10:51:33Z" - generation: 2 - labels: - component: velero + controller-gen.kubebuilder.io/version: v0.12.0 name: backups.velero.io - resourceVersion: "6920040" - uid: b489ac82-cf5b-487f-b471-8b8e985d61b7 spec: - conversion: - strategy: None group: velero.io names: kind: Backup @@ -49,6 +40,11 @@ spec: CSI VolumeSnapshot status turns to ReadyToUse during creation, before returning error as timeout. The default value is 10 minute. type: string + datamover: + description: DataMover specifies the data mover to be used by the + backup. If DataMover is "" or "velero", the built-in data mover + will be used. + type: string defaultVolumesToFsBackup: description: DefaultVolumesToFsBackup specifies whether pod volume file system backup should be used for all volumes by default. @@ -182,6 +178,7 @@ spec: contains only "value". The requirements are ANDed. type: object type: object + x-kubernetes-map-type: atomic name: description: Name is the name of this hook. type: string @@ -367,6 +364,7 @@ spec: are ANDed. type: object type: object + x-kubernetes-map-type: atomic metadata: properties: labels: @@ -427,6 +425,7 @@ spec: are ANDed. type: object type: object + x-kubernetes-map-type: atomic nullable: true type: array orderedResources: @@ -459,6 +458,12 @@ spec: - kind - name type: object + x-kubernetes-map-type: atomic + snapshotMoveData: + description: SnapshotMoveData specifies whether snapshot data should + be moved + nullable: true + type: boolean snapshotVolumes: description: SnapshotVolumes specifies whether to take snapshots of any PV's referenced in the set of objects included in the Backup. @@ -472,6 +477,15 @@ spec: description: TTL is a time.Duration-parseable string describing how long the Backup should be retained for. type: string + uploaderConfig: + description: UploaderConfig specifies the configuration for the uploader. + nullable: true + properties: + parallelFilesUpload: + description: ParallelFilesUpload is the number of files parallel + uploads to perform when using the uploader. + type: integer + type: object volumeSnapshotLocations: description: VolumeSnapshotLocations is a list containing names of VolumeSnapshotLocations associated with this backup. @@ -530,6 +544,22 @@ spec: description: FormatVersion is the backup format version, including major, minor, and patch version. type: string + hookStatus: + description: HookStatus contains information about the status of the + hooks. + nullable: true + properties: + hooksAttempted: + description: HooksAttempted is the total number of attempted hooks + Specifically, HooksAttempted represents the number of hooks + that failed to execute and the number of hooks that executed + successfully. + type: integer + hooksFailed: + description: HooksFailed is the total number of hooks which ended + with an error + type: integer + type: object phase: description: Phase is the current state of the Backup. enum: @@ -597,23 +627,4 @@ spec: type: object type: object served: true - storage: true -status: - acceptedNames: - kind: Backup - listKind: BackupList - plural: backups - singular: backup - conditions: - - lastTransitionTime: "2023-04-16T10:51:33Z" - message: no conflicts found - reason: NoConflicts - status: "True" - type: NamesAccepted - - lastTransitionTime: "2023-04-16T10:51:33Z" - message: the initial names have been accepted - reason: InitialNamesAccepted - status: "True" - type: Established - storedVersions: - - v1 + storage: true \ No newline at end of file diff --git a/discord.png b/discord.png new file mode 100644 index 0000000..5f3594d Binary files /dev/null and b/discord.png differ diff --git a/helm/Chart.yaml b/helm/Chart.yaml index c4aa573..5b67cdb 100644 --- a/helm/Chart.yaml +++ b/helm/Chart.yaml @@ -1,5 +1,5 @@ apiVersion: v1 -appVersion: "1.0" +appVersion: "v1.0.3" description: A Helm chart to send email/Slack notifications for Velero backups/restores name: velero-backup-notification -version: 0.1.0 +version: 1.0.3 diff --git a/helm/templates/deployment.yaml b/helm/templates/deployment.yaml index 5406618..acc801a 100644 --- a/helm/templates/deployment.yaml +++ b/helm/templates/deployment.yaml @@ -52,6 +52,21 @@ spec: secretKeyRef: key: slack_channel name: velero-backup-notification-secrets + - name: ENABLE_DISCORD_NOTIFICATIONS + value: {{ .Values.discord.enabled | quote }} + - name: DISCORD_FAILURES_ONLY + value: {{ .Values.discord.failures_only | quote }} + - name: DISCORD_WEBHOOK + valueFrom: + secretKeyRef: + key: discord_webhook + name: velero-backup-notification-secrets + - name: ENABLE_DISCORD_MENTIONS + value: {{ .Values.discord.mentions.enabled | quote }} + - name: DISCORD_MENTIONS_FAILURES_ONLY + value: {{ .Values.discord.mentions.failures_only | quote }} + - name: DISCORD_MENTIONS_ROLE_ID + value: {{ .Values.discord.mentions.role_id | quote }} - name: ENABLE_EMAIL_NOTIFICATIONS value: {{ .Values.email.enabled | quote }} - name: EMAIL_FAILURES_ONLY diff --git a/helm/templates/secret.yaml b/helm/templates/secret.yaml index de99291..65e0355 100644 --- a/helm/templates/secret.yaml +++ b/helm/templates/secret.yaml @@ -6,6 +6,7 @@ type: Opaque stringData: slack_webhook: {{ .Values.slack.webhook | quote }} slack_channel: {{ .Values.slack.channel | quote }} + discord_webhook: {{ .Values.discord.webhook | quote }} email_smtp_host: {{ .Values.email.smtp.host | quote }} email_smtp_port: {{ .Values.email.smtp.port | quote }} email_smtp_username: {{ .Values.email.smtp.username | quote }} diff --git a/helm/values.yaml b/helm/values.yaml index bd3f7d1..d11f164 100644 --- a/helm/values.yaml +++ b/helm/values.yaml @@ -1,6 +1,6 @@ image: - repository: vitobotta/velero-backup-notification - tag: v1.0.0 + repository: woutthenines/velero-backup-notification + tag: v1.0.3 slack: enabled: false @@ -9,6 +9,15 @@ slack: channel: "stuff" username: Velero +discord: + enabled: false + failures_only: true + webhook: "https://...." + mentions: + enabled: false + failures_only: true + role_id: "1234567890" + email: enabled: false failures_only: true diff --git a/shard.lock b/shard.lock index 72b7873..2eac0ff 100644 --- a/shard.lock +++ b/shard.lock @@ -2,7 +2,7 @@ version: 2.0 shards: db: git: https://github.com/crystal-lang/crystal-db.git - version: 0.11.0 + version: 0.12.0 email: git: https://github.com/arcage/crystal-email.git @@ -14,11 +14,11 @@ shards: k8s: git: https://github.com/spoved/k8s.cr.git - version: 0.1.11 + version: 0.1.12 kube-client: git: https://github.com/spoved/kube-client.cr.git - version: 0.4.6+git.commit.8778313a458f239376c7f05896a79fd8414e4139 + version: 0.4.8 retriable: git: https://github.com/sija/retriable.cr.git diff --git a/shard.yml b/shard.yml index bc3c329..cf21c93 100644 --- a/shard.yml +++ b/shard.yml @@ -1,5 +1,5 @@ name: velero-notifications -version: 0.1.0 +version: 1.0.3 authors: - Vito Botta @@ -15,7 +15,7 @@ license: MIT dependencies: kube-client: github: spoved/kube-client.cr - branch: kalinon/issue12 + version: 0.4.8 retriable: git: https://github.com/sija/retriable.cr.git version: 0.2.4 diff --git a/src/controller.cr b/src/controller.cr index 851fbd6..aa9749f 100644 --- a/src/controller.cr +++ b/src/controller.cr @@ -1,5 +1,5 @@ require "log" -require "kube-client/v1.26" +require "kube-client/v1.28" require "retriable" require "./crds/velero/v1/backup_spec" require "./crds/velero/v1/backup_status" diff --git a/src/crds/velero/v1/backup_spec.cr b/src/crds/velero/v1/backup_spec.cr index fddf720..98f8f75 100644 --- a/src/crds/velero/v1/backup_spec.cr +++ b/src/crds/velero/v1/backup_spec.cr @@ -8,6 +8,7 @@ require "json" properties: [ {name: "csi_snapshot_timeout", kind: String, key: "csiSnapshotTimeout", nilable: true, read_only: false, description: "CSISnapshotTimeout specifies the time used to wait for CSI VolumeSnapshot status turns to ReadyToUse during creation, before returning error as timeout. The default value is 10 minute."}, + {name: "datamover", kind: String, key: "datamover", nilable: true, read_only: false, description: "DataMover specifies the data mover to be used by the backup. If DataMover is \"\" or \"velero\", the built-in data mover will be used."}, {name: "default_volumes_to_fs_backup", kind: ::Bool, key: "defaultVolumesToFsBackup", nilable: true, read_only: false, description: "DefaultVolumesToFsBackup specifies whether pod volume file system backup should be used for all volumes by default."}, {name: "default_volumes_to_restic", kind: ::Bool, key: "defaultVolumesToRestic", nilable: true, read_only: false, description: "DefaultVolumesToRestic specifies whether restic should be used to take a backup of all pod volumes by default. \n Deprecated: this field is no longer used and will be removed entirely in future. Use DefaultVolumesToFsBackup instead."}, {name: "excluded_cluster_scoped_resources", kind: ::Array(String), key: "excludedClusterScopedResources", nilable: true, read_only: false, description: "ExcludedClusterScopedResources is a slice of cluster-scoped resource type names to exclude from the backup. If set to \"*\", all cluster-scoped resource types are excluded. The default value is empty."}, @@ -26,9 +27,11 @@ require "json" {name: "or_label_selectors", kind: Union(::Array(::Hash(String, ::Array(::Hash(String, String | ::Array(String))) | ::Hash(String, String)))), key: "orLabelSelectors", nilable: true, read_only: false, description: "OrLabelSelectors is list of metav1.LabelSelector to filter with when adding individual objects to the backup. If multiple provided they will be joined by the OR operator. LabelSelector as well as OrLabelSelectors cannot co-exist in backup request, only one of them can be used."}, {name: "ordered_resources", kind: ::Hash(String, String), key: "orderedResources", nilable: true, read_only: false, description: "OrderedResources specifies the backup order of resources of specific Kind. The map key is the resource name and value is a list of object names separated by commas. Each resource name has format [\"namespace/objectname\". For cluster resources, simply use \"objectname\".](\"namespace/objectname\". For cluster resources, simply use \"objectname\".)"}, {name: "resource_policy", kind: ::Hash(String, String), key: "resourcePolicy", nilable: true, read_only: false, description: "ResourcePolicy specifies the referenced resource policies that backup should follow"}, + {name: "snapshot_move_data", kind: ::Bool, key: "snapshotMoveData", nilable: true, read_only: false, description: "SnapshotMoveData specifies whether snapshot data should be moved"}, {name: "snapshot_volumes", kind: ::Bool, key: "snapshotVolumes", nilable: true, read_only: false, description: "SnapshotVolumes specifies whether to take snapshots of any PV's referenced in the set of objects included in the Backup."}, {name: "storage_location", kind: String, key: "storageLocation", nilable: true, read_only: false, description: "StorageLocation is a string containing the name of a BackupStorageLocation where the backup should be stored."}, {name: "ttl", kind: String, key: "ttl", nilable: true, read_only: false, description: "TTL is a time.Duration-parseable string describing how long the Backup should be retained for."}, + {name: "uploader_config", kind: ::Hash(String, Int32), key: "uploaderConfig", nilable: true, read_only: false, description: "UploaderConfig specifies the configuration for the uploader."}, {name: "volume_snapshot_locations", kind: ::Array(String), key: "volumeSnapshotLocations", nilable: true, read_only: false, description: "VolumeSnapshotLocations is a list containing names of VolumeSnapshotLocations associated with this backup."}, ] diff --git a/src/crds/velero/v1/backup_status.cr b/src/crds/velero/v1/backup_status.cr index 3d31846..379aa8b 100644 --- a/src/crds/velero/v1/backup_status.cr +++ b/src/crds/velero/v1/backup_status.cr @@ -17,6 +17,7 @@ require "json" {name: "expiration", kind: String, key: "expiration", nilable: true, read_only: false, description: "Expiration is when this Backup is eligible for garbage-collection."}, {name: "failure_reason", kind: String, key: "failureReason", nilable: true, read_only: false, description: "FailureReason is an error that caused the entire backup to fail."}, {name: "format_version", kind: String, key: "formatVersion", nilable: true, read_only: false, description: "FormatVersion is the backup format version, including major, minor, and patch version."}, + {name: "hook_status", kind: ::Hash(String, Int32), key: "hookStatus", nilable: true, read_only: false, description: "HookStatus contains information about the status of the hooks."}, {name: "phase", kind: String, key: "phase", nilable: true, read_only: false, description: "Phase is the current state of the Backup."}, {name: "progress", kind: ::Hash(String, Int32), key: "progress", nilable: true, read_only: false, description: "Progress contains information about the backup's execution progress. Note that this information is best-effort only -- if Velero fails to update it during a backup for any reason, it may be [inaccurate/stale.](inaccurate/stale.)"}, {name: "start_timestamp", kind: String, key: "startTimestamp", nilable: true, read_only: false, description: "StartTimestamp records the time a backup was started. Separate from CreationTimestamp, since that value changes on restores. The server's time is used for StartTimestamps"}, diff --git a/src/event.cr b/src/event.cr index cc98604..c25ea94 100644 --- a/src/event.cr +++ b/src/event.cr @@ -4,6 +4,10 @@ require "email" class Event SLACK_WEBHOOK = ENV.fetch("SLACK_WEBHOOK", "") + DISCORD_WEBHOOK = ENV.fetch("DISCORD_WEBHOOK", "") + ENABLE_DISCORD_MENTIONS = ENV.fetch("ENABLE_DISCORD_MENTIONS", "false").downcase + DISCORD_MENTIONS_FAILURES_ONLY = ENV.fetch("DISCORD_MENTIONS_FAILURES_ONLY", "false").downcase + DISCORD_MENTIONS_ROLE_ID = ENV.fetch("DISCORD_MENTIONS_ROLE_ID", "") EMAIL_SMTP_HOST = ENV.fetch("EMAIL_SMTP_HOST", "") EMAIL_SMTP_PORT = ENV.fetch("EMAIL_SMTP_PORT", "") EMAIL_SMTP_USERNAME = ENV.fetch("EMAIL_SMTP_USERNAME", "") @@ -25,6 +29,7 @@ class Event Log.info { notification_subject } send_slack_notification if send_slack_notification? + send_discord_notification if send_discord_notification? send_email_notification if send_email_notification? send_webhook_notification if send_webhook_notification? end @@ -83,6 +88,48 @@ class Event ) end + def send_discord_notification? + send_notification?(:discord) + end + + # Add a method to send notifications to Discord + def send_discord_notification + if DISCORD_WEBHOOK.blank? + Log.info { "Ensure the DISCORD_WEBHOOK environment variable is set" } + raise Exception.new("Discord configuration missing") + end + + if ENABLE_DISCORD_MENTIONS == "true" + if DISCORD_MENTIONS_ROLE_ID.blank? + Log.info { "Ensure the DISCORD_MENTIONS_ROLE_ID environment variable is set" } + raise Exception.new("Discord mentions configuration missing") + end + + failures_only = DISCORD_MENTIONS_FAILURES_ONLY == "true" + succeeded = phase == "Completed" + + notification_mention = !failures_only || (failures_only && !succeeded) ? "<@&#{DISCORD_MENTIONS_ROLE_ID}>" : nil + end + + color = phase == "Completed" ? 0x36a64f : 0xa30202 + payload = { + "content" => notification_mention.nil? ? "" : notification_mention, + "embeds" => [ + { + "title" => notification_subject, + "description" => notification_body, + "color" => color + } + ] + }.to_json + + HTTP::Client.post( + DISCORD_WEBHOOK, + headers: HTTP::Headers{"Content-type" => "application/json"}, + body: payload + ) + end + private def email_client : EMail::Client @email_client ||= begin if EMAIL_SMTP_HOST.blank? || EMAIL_SMTP_PORT.blank? || EMAIL_SMTP_USERNAME.blank? || EMAIL_SMTP_PASSWORD.blank? || EMAIL_FROM_ADDRESS.blank? || EMAIL_TO_ADDRESS.blank? @@ -138,4 +185,3 @@ class Event HTTP::Client.get(WEBHOOK_URL) end end - diff --git a/src/velero-notifications.cr b/src/velero-notifications.cr index 6c43a05..fd018b0 100644 --- a/src/velero-notifications.cr +++ b/src/velero-notifications.cr @@ -1,7 +1,7 @@ require "./controller" module Velero::Notifications - VERSION = "1.0.0" + VERSION = "1.0.3" end