repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Resources/views/settings/web-forms/preview.blade.php
packages/Webkul/WebForm/src/Resources/views/settings/web-forms/preview.blade.php
<x-web_form::layouts> <x-slot:title> {{ strip_tags($webForm->title) }} </x-slot> <!-- Web Form --> <v-web-form> <div class="flex h-[100vh] items-center justify-center"> <div class="flex flex-col items-center gap-5"> <x-web_form::spinner /> </div> </div> </v-web-form> @pushOnce('scripts') <script type="text/template" id="v-web-form-template" > <div class="flex h-[100vh] items-center justify-center" style="background-color: {{ $webForm->background_color }}" > <div class="flex flex-col items-center gap-5"> <!-- Logo --> <img class="w-max" src="{{ vite()->asset('images/logo.svg') }}" alt="{{ config('app.name') }}" /> <h1 class="text-2xl font-bold" style="color: {{ $webForm->form_title_color }} !important;" > {{ $webForm->title }} </h1> <p class="mt-2 text-base text-gray-600">{{ $webForm->description }}</p> <div class="box-shadow flex min-w-[300px] flex-col rounded-lg border border-gray-200 bg-white p-4 dark:bg-gray-900" style="background-color: {{ $webForm->form_background_color }}" > {!! view_render_event('web_forms.web_forms.form_controls.before', ['webForm' => $webForm]) !!} <!-- Webform Form --> <x-web_form::form v-slot="{ meta, values, errors, handleSubmit }" as="div" ref="modalForm" > <form @submit="handleSubmit($event, create)" ref="webForm" > @include('web_form::settings.web-forms.controls') <div class="flex justify-center"> <x-web_form::button class="primary-button" :title="$webForm->submit_button_label" ::loading="isStoring" ::disabled="isStoring" style="background-color: {{ $webForm->form_submit_button_color }} !important" /> </div> </form> </x-web_form::form> {!! view_render_event('web_forms.web_forms.form_controls.after', ['webForm' => $webForm]) !!} </div> </div> </div> </script> <script type="module"> app.component('v-web-form', { template: '#v-web-form-template', data() { return { isStoring: false, }; }, methods: { create(params, { resetForm, setErrors }) { this.isStoring = true; const formData = new FormData(this.$refs.webForm); let inputNames = Array.from(formData.keys()); inputNames = inputNames.reduce((acc, name) => { const dotName = name.replace(/\[([^\]]+)\]/g, '.$1'); acc[dotName] = name; return acc; }, {}); this.$axios .post('{{ route('admin.settings.web_forms.form_store', $webForm->id) }}', formData, { headers: { 'Content-Type': 'multipart/form-data', }, }) .then(response => { resetForm(); this.$refs.webForm.reset(); this.$emitter.emit('add-flash', { type: 'success', message: response.data.message }); }) .catch(error => { if (error.response.data.redirect) { window.location.href = error.response.data.redirect; return; } if (! error.response.data.errors) { this.$emitter.emit('add-flash', { type: 'error', message: error.response.data.message }); return; } const laravelErrors = error.response.data.errors || {}; const mappedErrors = {}; for ( const [dotKey, messages] of Object.entries(laravelErrors) ) { const inputName = inputNames[dotKey]; if ( inputName && messages.length ) { mappedErrors[inputName] = messages[0]; } } setErrors(mappedErrors); }) .finally(() => { this.isStoring = false; }); } } }); </script> @endPushOnce </x-web_form::layouts>
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Resources/views/settings/web-forms/embed.blade.php
packages/Webkul/WebForm/src/Resources/views/settings/web-forms/embed.blade.php
(function() { document.write(`{!! view('web_form::settings.web-forms.preview', compact('webForm'))->render() !!}`.replaceAll('$', '\$')); })();
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Resources/views/settings/web-forms/controls.blade.php
packages/Webkul/WebForm/src/Resources/views/settings/web-forms/controls.blade.php
@foreach ($webForm->attributes as $attribute) @php $parentAttribute = $attribute->attribute; $fieldName = $parentAttribute->entity_type . '[' . $parentAttribute->code . ']'; $validations = $attribute->is_required ? 'required' : ''; @endphp <x-web_form::form.control-group> <x-web_form::form.control-group.label :for="$fieldName" class="{{ $validations }}" style="color: {{ $webForm->attribute_label_color }} !important;" > {{ $attribute->name ?? $parentAttribute->name }} </x-web_form::form.control-group.label> @switch($parentAttribute->type) @case('text') <x-web_form::form.control-group.control type="text" :name="$fieldName" :id="$fieldName" :rules="$validations" :label="$attribute->name ?? $parentAttribute->name" :placeholder="$attribute->placeholder" /> <x-web_form::form.control-group.error :control-name="$fieldName" /> @break @case('price') <x-web_form::form.control-group.control type="text" :name="$fieldName" :id="$fieldName" :rules="$validations.'|numeric'" :label="$attribute->name ?? $parentAttribute->name" :placeholder="$attribute->placeholder" /> <x-web_form::form.control-group.error :control-name="$fieldName" /> @break @case('email') <x-web_form::form.control-group.control type="email" name="{{ $fieldName }}[0][value]" id="{{ $fieldName }}[0][value]" rules="{{ $validations }}|email" :label="$attribute->name ?? $parentAttribute->name" :placeholder="$attribute->placeholder" /> <x-web_form::form.control-group.control type="hidden" name="{{ $fieldName }}[0][label]" id="{{ $fieldName }}[0][label]" rules="required" value="work" /> <x-web_form::form.control-group.error control-name="{{ $fieldName }}[0][value]" /> @break @case('checkbox') @php $options = $parentAttribute->lookup_type ? app('Webkul\Attribute\Repositories\AttributeRepository')->getLookUpOptions($parentAttribute->lookup_type) : $parentAttribute->options()->orderBy('sort_order')->get(); @endphp @foreach ($options as $option) <x-web_form::form.control-group class="!mb-2 flex select-none items-center gap-2.5"> <x-web_form::form.control-group.control type="checkbox" name="{{ $fieldName }}[]" id="{{ $fieldName }}[]" value="{{ $option->id }}" for="{{ $fieldName }}[]" /> <label class="cursor-pointer text-xs font-medium text-gray-600 dark:text-gray-300" for="{{ $fieldName }}[]" > @lang('web_form::app.catalog.attributes.edit.is-required') </label> </x-web_form::form.control-group> @endforeach @case('file') @case('image') <x-web_form::form.control-group.control type="file" :name="$fieldName" :id="$fieldName" :rules="$validations" :placeholder="$attribute->placeholder" :label="$attribute->name ?? $parentAttribute->name" /> <x-web_form::form.control-group.error control-name="{{ $fieldName }}" /> @break; @case('phone') <x-web_form::form.control-group.control type="text" name="{{ $fieldName }}[0][value]" id="{{ $fieldName }}[0][value]" rules="{{ $validations }}|phone" :label="$attribute->name ?? $parentAttribute->name" :placeholder="$attribute->placeholder" /> <x-web_form::form.control-group.control type="hidden" name="{{ $fieldName }}[0][label]" id="{{ $fieldName }}[0][label]" rules="required" value="work" /> <x-web_form::form.control-group.error control-name="{{ $fieldName }}[0][value]" /> @break @case('date') <x-web_form::form.control-group.control type="date" :name="$fieldName" :id="$fieldName" :rules="$validations" :label="$attribute->name ?? $parentAttribute->name" :placeholder="$attribute->placeholder" /> <x-web_form::form.control-group.error :control-name="$fieldName" /> @break @case('datetime') <x-web_form::form.control-group.control type="datetime" :name="$fieldName" :id="$fieldName" :rules="$validations" :label="$attribute->name ?? $parentAttribute->name" :placeholder="$attribute->placeholder" /> <x-web_form::form.control-group.error :control-name="$fieldName" /> @break @case('select') @case('lookup') @php $options = $parentAttribute->lookup_type ? app('Webkul\Attribute\Repositories\AttributeRepository')->getLookUpOptions($parentAttribute->lookup_type) : $parentAttribute->options()->orderBy('sort_order')->get(); @endphp <x-web_form::form.control-group.control type="select" :name="$fieldName" :id="$fieldName" :rules="$validations" :label="$attribute->name ?? $parentAttribute->name" :placeholder="$attribute->placeholder" > @foreach ($options as $option) <option value="{{ $option->id }}">{{ $option->name }}</option> @endforeach </x-web_form::form.control-group.control> <x-web_form::form.control-group.error :control-name="$fieldName" /> @break @case('multiselect') @php $options = $parentAttribute->lookup_type ? app('Webkul\Attribute\Repositories\AttributeRepository')->getLookUpOptions($parentAttribute->lookup_type) : $parentAttribute->options()->orderBy('sort_order')->get(); @endphp <x-web_form::form.control-group.control type="select" id="{{ $fieldName }}" name="{{ $fieldName }}[]" :rules="$validations" :label="$attribute->name ?? $parentAttribute->name" :placeholder="$attribute->placeholder" > @foreach ($options as $option) <option value="{{ $option->id }}">{{ $option->name }}</option> @endforeach </x-web_form::form.control-group.control> <x-web_form::form.control-group.error :control-name="$fieldName" /> @break @case('checkbox') <div class="checkbox-control"> @php $options = $parentAttribute->lookup_type ? app('Webkul\Attribute\Repositories\AttributeRepository')->getLookUpOptions($parentAttribute->lookup_type) : $parentAttribute->options()->orderBy('sort_order')->get(); @endphp @foreach ($options as $option) <span class="checkbox"> <input type="checkbox" name="{{ $fieldName }}[]" value="{{ $option->id }}" /> <label class="checkbox-view" style="display: inline;"></label> {{ $option->name }} </span> @endforeach </div> <p id="{{ $fieldName }}[]-error" class="error-message mt-1 text-xs italic text-red-600" ></p> @break @case('boolean') <x-web_form::form.control-group.control type="select" :name="$fieldName" :id="$fieldName" :rules="$validations" :label="$attribute->name ?? $parentAttribute->name" :placeholder="$attribute->placeholder" > <option value="1">Yes</option> <option value="0">No</option> </x-web_form::form.control-group.control> <x-web_form::form.control-group.error :control-name="$fieldName" /> @break @endswitch </x-web_form::form.control-group> @endforeach
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Resources/views/components/layouts/index.blade.php
packages/Webkul/WebForm/src/Resources/views/components/layouts/index.blade.php
<!DOCTYPE html> <html lang="{{ app()->getLocale() }}" dir="{{ in_array(app()->getLocale(), ['fa', 'ar']) ? 'rtl' : 'ltr' }}" > <head> <title>{{ $title ?? '' }}</title> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge" > <meta http-equiv="content-language" content="{{ app()->getLocale() }}" > <meta name="viewport" content="width=device-width, initial-scale=1" > <meta name="base-url" content="{{ url()->to('/') }}" > @stack('meta') {{ vite()->set(['src/Resources/assets/css/app.css', 'src/Resources/assets/js/app.js'], 'webform') }} <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800&display=swap" rel="stylesheet" /> <link href="https://fonts.googleapis.com/css2?family=DM+Serif+Display&display=swap" rel="stylesheet" /> @if ($favicon = core()->getConfigData('general.design.admin_logo.favicon')) <link type="image/x-icon" href="{{ Storage::url($favicon) }}" rel="shortcut icon" sizes="16x16" > @else <link type="image/x-icon" href="{{ vite()->asset('images/favicon.ico') }}" rel="shortcut icon" sizes="16x16" /> @endif @stack('styles') <style> {!! core()->getConfigData('general.content.custom_scripts.custom_css') !!} </style> {!! view_render_event('webform.layout.head') !!} </head> <body> {!! view_render_event('webform.layout.body.before') !!} <div id="app"> <!-- Flash Message Blade Component --> <x-web_form::flash-group /> {!! view_render_event('webform.layout.content.before') !!} <!-- Page Content Blade Component --> {{ $slot }} {!! view_render_event('webform.layout.content.after') !!} </div> {!! view_render_event('webform.layout.body.after') !!} @stack('scripts') {!! view_render_event('webform.layout.vue-app-mount.before') !!} <script> /** * Load event, the purpose of using the event is to mount the application * after all of our Vue components which is present in blade file have * been registered in the app. No matter what app.mount() should be * called in the last. */ window.addEventListener("load", function(event) { app.mount("#app"); }); </script> {!! view_render_event('webform.layout.vue-app-mount.after') !!} <script type="text/javascript"> {!! core()->getConfigData('general.content.custom_scripts.custom_javascript') !!} </script> </body> </html>
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Resources/views/components/button/index.blade.php
packages/Webkul/WebForm/src/Resources/views/components/button/index.blade.php
<v-button {{ $attributes }}></v-button> @pushOnce('scripts') <script type="text/x-template" id="v-button-template" > <button v-if="! loading" :class="[buttonClass, '']" > @{{ title }} </button> <button v-else :class="[buttonClass, '']" > <!-- Spinner --> <x-admin::spinner class="absolute" /> <span class="realative h-full w-full opacity-0"> @{{ title }} </span> </button> </script> <script type="module"> app.component('v-button', { template: '#v-button-template', props: { loading: Boolean, buttonType: String, title: String, buttonClass: String, }, }); </script> @endPushOnce
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Resources/views/components/flash-group/index.blade.php
packages/Webkul/WebForm/src/Resources/views/components/flash-group/index.blade.php
<v-flash-group ref='flashes'></v-flash-group> @pushOnce('scripts') <script type="text/x-template" id="v-flash-group-template" > <transition-group tag='div' name="flash-group" enter-from-class="ltr:translate-y-full rtl:-translate-y-full" enter-active-class="transform transition duration-300 ease-[cubic-bezier(.4,0,.2,1)]" enter-to-class="ltr:translate-y-0 rtl:-translate-y-0" leave-from-class="ltr:translate-y-0 rtl:-translate-y-0" leave-active-class="transform transition duration-300 ease-[cubic-bezier(.4,0,.2,1)]" leave-to-class="ltr:translate-y-full rtl:-translate-y-full" class='fixed bottom-5 left-1/2 z-[10003] grid -translate-x-1/2 justify-items-end gap-2.5' > <x-admin::flash-group.item /> </transition-group> </script> <script type="module"> app.component('v-flash-group', { template: '#v-flash-group-template', data() { return { uid: 0, flashes: [] } }, created() { @foreach (['success', 'warning', 'error', 'info'] as $key) @if (session()->has($key)) this.flashes.push({'type': '{{ $key }}', 'message': "{{ session($key) }}", 'uid': this.uid++}); @endif @endforeach this.registerGlobalEvents(); }, methods: { add(flash) { flash.uid = this.uid++; this.flashes.push(flash); }, remove(flash) { let index = this.flashes.indexOf(flash); this.flashes.splice(index, 1); }, registerGlobalEvents() { this.$emitter.on('add-flash', this.add); }, } }); </script> @endpushOnce
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Resources/views/components/flash-group/item.blade.php
packages/Webkul/WebForm/src/Resources/views/components/flash-group/item.blade.php
<v-flash-item v-for='flash in flashes' :key='flash.uid' :flash="flash" @onRemove="remove($event)" > </v-flash-item> @pushOnce('scripts') <script type="text/x-template" id="v-flash-item-template" > <div class="flex w-max items-start justify-between gap-2 rounded-lg bg-white p-3 shadow-[0px_10px_20px_0px_rgba(0,0,0,0.12)] dark:bg-gray-950" :style="typeStyles[flash.type]['container']" @mouseenter="pauseTimer" @mouseleave="resumeTimer" > <!-- Icon --> <span class="icon-toast-done rounded-full bg-white text-2xl dark:bg-gray-900" :class="iconClasses[flash.type]" :style="typeStyles[flash.type]['icon']" ></span> <div class="flex flex-col gap-1.5"> <!-- Heading --> <p class="text-base font-semibold dark:text-white"> @{{ typeHeadings[flash.type] }} </p> <!-- Message --> <p class="flex items-center break-all text-sm dark:text-white" :style="typeStyles[flash.type]['message']" > @{{ flash.message }} </p> </div> <button class="relative ml-4 inline-flex rounded-full bg-white p-1.5 text-gray-400 dark:bg-gray-950" @click="remove" > <span class="icon-cross-large text-2xl text-slate-800"></span> <svg class="absolute inset-0 h-full w-full -rotate-90" viewBox="0 0 24 24"> <circle class="text-gray-200" stroke-width="1.5" stroke="#D0D4DA" fill="transparent" r="10" cx="12" cy="12" /> <circle class="text-blue-600 transition-all duration-100 ease-out" stroke-width="1.5" :stroke-dasharray="circumference" :stroke-dashoffset="strokeDashoffset" stroke-linecap="round" :stroke="typeStyles[flash.type]['stroke']" fill="transparent" r="10" cx="12" cy="12" /> </svg> </button> </div> </script> <script type="module"> app.component('v-flash-item', { template: '#v-flash-item-template', props: ['flash'], data() { return { iconClasses: { success: 'icon-success', error: 'icon-error', warning: 'icon-warning', info: 'icon-info', }, typeHeadings: { success: "@lang('admin::app.components.flash-group.success')", error: "@lang('admin::app.components.flash-group.error')", warning: "@lang('admin::app.components.flash-group.warning')", info: "@lang('admin::app.components.flash-group.info')", }, typeStyles: { success: { container: 'border-left: 8px solid #16A34A', icon: 'color: #16A34A', stroke: '#16A34A', }, error: { container: 'border-left: 8px solid #FF4D50', icon: 'color: #FF4D50', stroke: '#FF4D50', }, warning: { container: 'border-left: 8px solid #FBAD15', icon: 'color: #FBAD15', stroke: '#FBAD15', }, info: { container: 'border-left: 8px solid #0E90D9', icon: 'color: #0E90D9', stroke: '#0E90D9', }, }, duration: 5000, progress: 0, circumference: 2 * Math.PI * 10, timer: null, isPaused: false, remainingTime: 5000, }; }, computed: { strokeDashoffset() { return this.circumference - (this.progress / 100) * this.circumference; } }, created() { this.startTimer(); }, beforeUnmount() { this.stopTimer(); }, methods: { remove() { this.$emit('onRemove', this.flash) }, startTimer() { const interval = 100; const step = (100 / (this.duration / interval)); this.timer = setInterval(() => { if (! this.isPaused) { this.progress += step; this.remainingTime -= interval; if (this.progress >= 100) { this.stopTimer(); this.remove(); } } }, interval); }, stopTimer() { clearInterval(this.timer); }, pauseTimer() { this.isPaused = true; }, resumeTimer() { this.isPaused = false; }, } }); </script> @endpushOnce
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Resources/views/components/form/index.blade.php
packages/Webkul/WebForm/src/Resources/views/components/form/index.blade.php
<!-- If a component has the as attribute, it indicates that it uses the ajaxified form or some customized slot form. --> @if ($attributes->has('as')) <v-form {{ $attributes }}> {{ $slot }} </v-form> <!-- Otherwise, a traditional form will be provided with a minimal set of configurations. --> @else @props([ 'method' => 'POST', ]) @php $method = strtoupper($method); @endphp <v-form method="{{ $method === 'GET' ? 'GET' : 'POST' }}" :initial-errors="{{ json_encode($errors->getMessages()) }}" v-slot="{ meta, errors, setValues }" @invalid-submit="onInvalidSubmit" {{ $attributes }} > @unless(in_array($method, ['HEAD', 'GET', 'OPTIONS'])) @csrf @endunless @if (! in_array($method, ['GET', 'POST'])) @method($method) @endif {{ $slot }} </v-form> @endif
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Resources/views/components/form/control-group/control.blade.php
packages/Webkul/WebForm/src/Resources/views/components/form/control-group/control.blade.php
@props([ 'type' => 'text', 'name' => '', ]) @switch($type) @case('hidden') @case('text') @case('email') @case('password') @case('number') <v-field v-slot="{ field, errors }" {{ $attributes->only(['name', ':name', 'value', ':value', 'v-model', 'rules', ':rules', 'label', ':label']) }} name="{{ $name }}" > <input type="{{ $type }}" name="{{ $name }}" v-bind="field" :class="[errors.length ? 'border !border-red-600 hover:border-red-600' : '']" {{ $attributes->except(['value', ':value', 'v-model', 'rules', ':rules', 'label', ':label'])->merge(['class' => 'w-full rounded border border-gray-200 px-2.5 py-2 text-sm font-normal text-gray-800 transition-all hover:border-gray-400 focus:border-gray-400 dark:border-gray-800 dark:bg-gray-900 dark:text-gray-300 dark:hover:border-gray-400 dark:focus:border-gray-400']) }} /> </v-field> @break @case('price') <v-field v-slot="{ field, errors }" {{ $attributes->only(['name', ':name', 'value', ':value', 'v-model', 'rules', ':rules', 'label', ':label']) }} name="{{ $name }}" > <div class="flex w-full items-center overflow-hidden rounded-md border text-sm text-gray-600 transition-all focus-within:border-gray-400 hover:border-gray-400 dark:border-gray-800 dark:bg-gray-900 dark:text-gray-300 dark:hover:border-gray-400 dark:focus:border-gray-400" :class="[errors.length ? 'border !border-red-600 hover:border-red-600' : '']" > @if (isset($currency)) <span {{ $currency->attributes->merge(['class' => 'py-2.5 text-gray-500 ltr:pl-4 rtl:pr-4']) }}> {{ $currency }} </span> @else <span class="py-2.5 text-gray-500 ltr:pl-4 rtl:pr-4"> {{ config('app.currency') }} </span> @endif <input type="text" name="{{ $name }}" v-bind="field" {{ $attributes->except(['value', ':value', 'v-model', 'rules', ':rules', 'label', ':label'])->merge(['class' => 'w-full p-2.5 text-sm text-gray-600 dark:bg-gray-900 dark:text-gray-300']) }} /> </div> </v-field> @break @case('file') <v-field v-slot="{ field, errors, handleChange, handleBlur }" {{ $attributes->only(['name', ':name', 'value', ':value', 'v-model', 'rules', ':rules', 'label', ':label']) }} name="{{ $name }}" > <input type="{{ $type }}" v-bind="{ name: field.name }" :class="[errors.length ? 'border !border-red-600 hover:border-red-600' : '']" {{ $attributes->except(['value', ':value', 'v-model', 'rules', ':rules', 'label', ':label'])->merge(['class' => 'w-full rounded-md border px-3 py-2.5 text-sm text-gray-600 transition-all hover:border-gray-400 focus:border-gray-400 dark:border-gray-800 dark:bg-gray-900 dark:text-gray-300 dark:file:bg-gray-800 dark:file:dark:text-white dark:hover:border-gray-400 dark:focus:border-gray-400']) }} @change="handleChange" @blur="handleBlur" /> </v-field> @break @case('color') <v-field name="{{ $name }}" v-slot="{ field, errors }" {{ $attributes->except('class') }} > <input type="{{ $type }}" :class="[errors.length ? 'border border-red-500' : '']" v-bind="field" {{ $attributes->except(['value'])->merge(['class' => 'w-full appearance-none rounded-md border text-sm text-gray-600 transition-all hover:border-gray-400 dark:text-gray-300 dark:hover:border-gray-400']) }} > </v-field> @break @case('textarea') <v-field v-slot="{ field, errors }" {{ $attributes->only(['name', ':name', 'value', ':value', 'v-model', 'rules', ':rules', 'label', ':label']) }} name="{{ $name }}" > <textarea type="{{ $type }}" name="{{ $name }}" v-bind="field" :class="[errors.length ? 'border !border-red-600 hover:border-red-600' : '']" {{ $attributes->except(['value', ':value', 'v-model', 'rules', ':rules', 'label', ':label'])->merge(['class' => 'w-full rounded border border-gray-200 px-2.5 py-2 text-sm font-normal text-gray-800 transition-all hover:border-gray-400 focus:border-gray-400 dark:border-gray-800 dark:bg-gray-900 dark:text-gray-300 dark:hover:border-gray-400 dark:focus:border-gray-400']) }} > </textarea> @if ($attributes->get('tinymce', false) || $attributes->get(':tinymce', false)) <x-admin::tinymce :selector="'textarea#' . $attributes->get('id')" ::field="field" /> @endif </v-field> @break @case('date') <v-field v-slot="{ field, errors }" {{ $attributes->only(['name', ':name', 'value', ':value', 'v-model', 'rules', ':rules', 'label', ':label'])->merge(['rules' => 'regex:^\d{4}-\d{2}-\d{2}$']) }} name="{{ $name }}" > <x-admin::flat-picker.date> <input name="{{ $name }}" v-bind="field" :class="[errors.length ? 'border !border-red-600 hover:border-red-600' : '']" {{ $attributes->except(['value', ':value', 'v-model', 'rules', ':rules', 'label', ':label'])->merge(['class' => 'w-full rounded border border-gray-200 px-2.5 py-2 text-sm font-normal text-gray-800 transition-all hover:border-gray-400 focus:border-gray-400 dark:border-gray-800 dark:bg-gray-900 dark:text-gray-300 dark:hover:border-gray-400 dark:focus:border-gray-400']) }} autocomplete="off" /> </x-admin::flat-picker.date> </v-field> @break @case('datetime') <v-field v-slot="{ field, errors }" {{ $attributes->only(['name', ':name', 'value', ':value', 'v-model', 'rules', ':rules', 'label', ':label'])->merge(['rules' => 'regex:^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$']) }} name="{{ $name }}" > <x-admin::flat-picker.datetime> <input name="{{ $name }}" v-bind="field" :class="[errors.length ? 'border !border-red-600 hover:border-red-600' : '']" {{ $attributes->except(['value', ':value', 'v-model', 'rules', ':rules', 'label', ':label'])->merge(['class' => 'w-full rounded border border-gray-200 px-2.5 py-2 text-sm font-normal text-gray-800 transition-all hover:border-gray-400 focus:border-gray-400 dark:border-gray-800 dark:bg-gray-900 dark:text-gray-300 dark:hover:border-gray-400 dark:focus:border-gray-400']) }} autocomplete="off" > </x-admin::flat-picker.datetime> </v-field> @break @case('select') <v-field v-slot="{ field, errors }" {{ $attributes->only(['name', ':name', 'value', ':value', 'v-model', 'rules', ':rules', 'label', ':label']) }} name="{{ $name }}" > <select name="{{ $name }}" v-bind="field" :class="[errors.length ? 'border border-red-500' : '']" {{ $attributes->except(['value', ':value', 'v-model', 'rules', ':rules', 'label', ':label'])->merge(['class' => 'custom-select w-full rounded border border-gray-200 px-2.5 py-2 text-sm font-normal text-gray-800 transition-all hover:border-gray-400 focus:border-gray-400 dark:border-gray-800 dark:bg-gray-900 dark:text-gray-300 dark:hover:border-gray-400']) }} > {{ $slot }} </select> </v-field> @break @case('multiselect') <v-field as="select" v-slot="{ value }" :class="[errors && errors['{{ $name }}'] ? 'border !border-red-600 hover:border-red-600' : '']" {{ $attributes->except([])->merge(['class' => 'flex w-full flex-col rounded-md border bg-white px-3 py-2.5 text-sm font-normal text-gray-600 transition-all hover:border-gray-400 dark:border-gray-800 dark:bg-gray-900 dark:text-gray-300 dark:hover:border-gray-400']) }} name="{{ $name }}" multiple > {{ $slot }} </v-field> @break @case('checkbox') <v-field v-slot="{ field }" type="checkbox" class="hidden" {{ $attributes->only(['name', ':name', 'value', ':value', 'v-model', 'rules', ':rules', 'label', ':label', 'key', ':key']) }} name="{{ $name }}" > <input type="checkbox" name="{{ $name }}" v-bind="field" class="peer sr-only" {{ $attributes->except(['rules', 'label', ':label', 'key', ':key']) }} /> <v-checked-handler :field="field" checked="{{ $attributes->get('checked') }}" > </v-checked-handler> </v-field> <label {{ $attributes ->except(['value', ':value', 'v-model', 'rules', ':rules', 'label', ':label', 'key', ':key']) ->merge(['class' => 'text-gray-500 icon-checkbox-outline peer-checked:icon-checkbox-select text-2xl peer-checked:text-blue-600']) ->merge(['class' => $attributes->get('disabled') ? 'cursor-not-allowed opacity-70' : 'cursor-pointer']) }} > </label> @break @case('radio') <v-field type="radio" class="hidden" v-slot="{ field }" {{ $attributes->only(['name', ':name', 'value', ':value', 'v-model', 'rules', ':rules', 'label', ':label', 'key', ':key']) }} name="{{ $name }}" > <input type="radio" name="{{ $name }}" v-bind="field" {{ $attributes->except(['rules', 'label', ':label', 'key', ':key'])->merge(['class' => 'peer sr-only']) }} /> <v-checked-handler class="hidden" :field="field" checked="{{ $attributes->get('checked') }}" > </v-checked-handler> </v-field> <label {{ $attributes->except(['value', ':value', 'v-model', 'rules', ':rules', 'label', ':label', 'key', ':key'])->merge(['class' => 'icon-radio-normal peer-checked:icon-radio-selected cursor-pointer text-2xl peer-checked:text-blue-600']) }} > </label> @break @case('switch') <label class="relative inline-flex cursor-pointer items-center"> <v-field type="checkbox" class="hidden" v-slot="{ field }" {{ $attributes->only(['name', ':name', 'value', ':value', 'v-model', 'rules', ':rules', 'label', ':label', 'key', ':key']) }} name="{{ $name }}" > <input type="checkbox" name="{{ $name }}" id="{{ $name }}" class="peer sr-only" v-bind="field" {{ $attributes->except(['v-model', 'rules', ':rules', 'label', ':label', 'key', ':key']) }} /> <v-checked-handler class="hidden" :field="field" checked="{{ $attributes->get('checked') }}" > </v-checked-handler> </v-field> <label class="peer h-5 w-9 cursor-pointer rounded-full bg-gray-200 after:absolute after:top-0.5 after:h-4 after:w-4 after:rounded-full after:border after:border-gray-300 after:bg-white after:transition-all after:content-[''] peer-checked:bg-blue-600 peer-checked:after:border-white peer-focus:outline-none peer-focus:ring-blue-300 after:ltr:left-0.5 peer-checked:after:ltr:translate-x-full after:rtl:right-0.5 peer-checked:after:rtl:-translate-x-full dark:bg-gray-800 dark:after:border-white dark:after:bg-white dark:peer-checked:bg-gray-950" for="{{ $name }}" ></label> </label> @break @case('image') <x-admin::media.images name="{{ $name }}" ::class="[errors && errors['{{ $name }}'] ? 'border !border-red-600 hover:border-red-600' : '']" {{ $attributes }} /> @break @case('inline') <x-admin::form.control-group.controls.inline.text {{ $attributes }}/> @break @case('custom') <v-field {{ $attributes }}> {{ $slot }} </v-field> @break @case('tags') <x-admin::form.control-group.controls.tags :name="$name" :data="$attributes->get(':data') ?? $attributes->get('data')" {{ $attributes}} /> @break @endswitch @pushOnce('scripts') <script type="text/x-template" id="v-checked-handler-template" > </script> <script type="module"> app.component('v-checked-handler', { template: '#v-checked-handler-template', props: ['field', 'checked'], mounted() { if (this.checked == '') { return; } this.field.checked = true; this.field.onChange(); }, }); </script> @endpushOnce
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Resources/views/components/form/control-group/label.blade.php
packages/Webkul/WebForm/src/Resources/views/components/form/control-group/label.blade.php
<label {{ $attributes->merge(['class' => 'mb-1.5 flex items-center gap-1 text-sm font-normal text-gray-800 dark:text-white']) }}> {{ $slot }} </label>
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Resources/views/components/form/control-group/index.blade.php
packages/Webkul/WebForm/src/Resources/views/components/form/control-group/index.blade.php
<div {{ $attributes->merge(['class' => 'mb-4']) }}> {{ $slot }} </div>
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Resources/views/components/form/control-group/error.blade.php
packages/Webkul/WebForm/src/Resources/views/components/form/control-group/error.blade.php
@props([ 'name' => null, 'controlName' => '', ]) <v-error-message {{ $attributes }} name="{{ $name ?? $controlName }}" v-slot="{ message }" > <p {{ $attributes->merge(['class' => 'mt-1 text-xs italic text-red-600']) }} v-text="message" > </p> </v-error-message>
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Resources/views/components/spinner/index.blade.php
packages/Webkul/WebForm/src/Resources/views/components/spinner/index.blade.php
<!-- Spinner --> @props(['color' => 'currentColor']) <svg xmlns="http://www.w3.org/2000/svg" fill="none" aria-hidden="true" viewBox="0 0 24 24" {{ $attributes->merge(['class' => 'h-5 w-5 animate-spin']) }} > <circle class="opacity-25" cx="12" cy="12" r="10" stroke="{{ $color }}" stroke-width="4" > </circle> <path class="opacity-75" fill="{{ $color }}" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" > </path> </svg>
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Models/WebFormAttribute.php
packages/Webkul/WebForm/src/Models/WebFormAttribute.php
<?php namespace Webkul\WebForm\Models; use Illuminate\Database\Eloquent\Model; use Webkul\Attribute\Models\AttributeProxy; use Webkul\WebForm\Contracts\WebFormAttribute as WebFormAttributeContract; class WebFormAttribute extends Model implements WebFormAttributeContract { /** * Indicates if the model should be timestamped. * * @var string */ public $timestamps = false; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'placeholder', 'is_required', 'is_hidden', 'sort_order', 'attribute_id', 'web_form_id', ]; /** * Get the attribute that owns the attribute. */ public function attribute() { return $this->belongsTo(AttributeProxy::modelClass()); } /** * Get the web_form that owns the attribute. */ public function web_form() { return $this->belongsTo(WebFormProxy::modelClass()); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Models/WebFormAttributeProxy.php
packages/Webkul/WebForm/src/Models/WebFormAttributeProxy.php
<?php namespace Webkul\WebForm\Models; use Konekt\Concord\Proxies\ModelProxy; class WebFormAttributeProxy extends ModelProxy {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Models/WebForm.php
packages/Webkul/WebForm/src/Models/WebForm.php
<?php namespace Webkul\WebForm\Models; use Illuminate\Database\Eloquent\Model; use Webkul\WebForm\Contracts\WebForm as WebFormContract; class WebForm extends Model implements WebFormContract { protected $fillable = [ 'form_id', 'title', 'description', 'submit_button_label', 'submit_success_action', 'submit_success_content', 'create_lead', 'background_color', 'form_background_color', 'form_title_color', 'form_submit_button_color', 'attribute_label_color', ]; /** * The attributes that belong to the activity. */ public function attributes() { return $this->hasMany(WebFormAttributeProxy::modelClass()); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Models/WebFormProxy.php
packages/Webkul/WebForm/src/Models/WebFormProxy.php
<?php namespace Webkul\WebForm\Models; use Konekt\Concord\Proxies\ModelProxy; class WebFormProxy extends ModelProxy {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/DataGrids/WebFormDataGrid.php
packages/Webkul/WebForm/src/DataGrids/WebFormDataGrid.php
<?php namespace Webkul\WebForm\DataGrids; use Illuminate\Contracts\Database\Query\Builder; use Illuminate\Support\Facades\DB; use Webkul\DataGrid\DataGrid; class WebFormDataGrid extends DataGrid { /** * Prepare query builder. */ public function prepareQueryBuilder(): Builder { $queryBuilder = DB::table('web_forms') ->addSelect( 'web_forms.id', 'web_forms.title', ); $this->addFilter('id', 'web_forms.id'); return $queryBuilder; } /** * Prepare columns. */ public function prepareColumns(): void { $this->addColumn([ 'index' => 'id', 'label' => trans('admin::app.settings.webforms.index.datagrid.id'), 'type' => 'string', 'sortable' => true, ]); $this->addColumn([ 'index' => 'title', 'label' => trans('admin::app.settings.webforms.index.datagrid.title'), 'type' => 'string', 'sortable' => true, 'searchable' => true, 'filterable' => true, ]); } /** * Prepare actions. */ public function prepareActions(): void { if (bouncer()->hasPermission('settings.other_settings.web_forms.view')) { $this->addAction([ 'index' => 'view', 'icon' => 'icon-eye', 'title' => trans('admin::app.settings.webforms.index.datagrid.view'), 'method' => 'GET', 'url' => fn ($row) => route('admin.settings.web_forms.view', $row->id), ]); } if (bouncer()->hasPermission('settings.other_settings.web_forms.edit')) { $this->addAction([ 'index' => 'edit', 'icon' => 'icon-edit', 'title' => trans('admin::app.settings.webforms.index.datagrid.edit'), 'method' => 'GET', 'url' => fn ($row) => route('admin.settings.web_forms.edit', $row->id), ]); } if (bouncer()->hasPermission('settings.other_settings.web_forms.delete')) { $this->addAction([ 'index' => 'delete', 'icon' => 'icon-delete', 'title' => trans('admin::app.settings.webforms.index.datagrid.delete'), 'method' => 'DELETE', 'url' => fn ($row) => route('admin.settings.web_forms.delete', $row->id), ]); } } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Repositories/WebFormRepository.php
packages/Webkul/WebForm/src/Repositories/WebFormRepository.php
<?php namespace Webkul\WebForm\Repositories; use Illuminate\Container\Container; use Illuminate\Support\Str; use Webkul\Core\Eloquent\Repository; use Webkul\WebForm\Contracts\WebForm; class WebFormRepository extends Repository { /** * Create a new repository instance. * * @return void */ public function __construct( protected WebFormAttributeRepository $webFormAttributeRepository, Container $container ) { parent::__construct($container); } /** * Specify model class name. * * @return mixed */ public function model() { return WebForm::class; } /** * Create Web Form. * * @return \Webkul\WebForm\Contracts\WebForm */ public function create(array $data) { $webForm = $this->model->create(array_merge($data, [ 'form_id' => Str::random(50), ])); foreach ($data['attributes'] as $attributeData) { $this->webFormAttributeRepository->create(array_merge([ 'web_form_id' => $webForm->id, ], $attributeData)); } return $webForm; } /** * Update Web Form. * * @param int $id * @param string $attribute * @return \Webkul\WebForm\Contracts\WebForm */ public function update(array $data, $id, $attribute = 'id') { $webForm = parent::update($data, $id); $previousAttributeIds = $webForm->attributes()->pluck('id'); foreach ($data['attributes'] as $attributeId => $attributeData) { if (Str::contains($attributeId, 'attribute_')) { $this->webFormAttributeRepository->create(array_merge([ 'web_form_id' => $webForm->id, ], $attributeData)); } else { if (is_numeric($index = $previousAttributeIds->search($attributeId))) { $previousAttributeIds->forget($index); } $this->webFormAttributeRepository->update($attributeData, $attributeId); } } foreach ($previousAttributeIds as $attributeId) { $this->webFormAttributeRepository->delete($attributeId); } return $webForm; } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Repositories/WebFormAttributeRepository.php
packages/Webkul/WebForm/src/Repositories/WebFormAttributeRepository.php
<?php namespace Webkul\WebForm\Repositories; use Webkul\Core\Eloquent\Repository; class WebFormAttributeRepository extends Repository { /** * Specify Model class name * * @return mixed */ public function model() { return 'Webkul\WebForm\Contracts\WebFormAttribute'; } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Providers/WebFormServiceProvider.php
packages/Webkul/WebForm/src/Providers/WebFormServiceProvider.php
<?php namespace Webkul\WebForm\Providers; use Illuminate\Support\Facades\Blade; use Illuminate\Support\ServiceProvider; class WebFormServiceProvider extends ServiceProvider { /** * Bootstrap services. */ public function boot(): void { $this->loadRoutesFrom(__DIR__.'/../Routes/routes.php'); $this->loadTranslationsFrom(__DIR__.'/../Resources/lang', 'web_form'); $this->loadViewsFrom(__DIR__.'/../Resources/views', 'web_form'); Blade::anonymousComponentPath(__DIR__.'/../Resources/views/components'); $this->loadMigrationsFrom(__DIR__.'/../Database/Migrations'); $this->app->register(ModuleServiceProvider::class); } /** * Register services. */ public function register(): void { $this->registerConfig(); } /** * Register package config. */ protected function registerConfig(): void { $this->mergeConfigFrom(dirname(__DIR__).'/Config/menu.php', 'menu.admin'); $this->mergeConfigFrom(dirname(__DIR__).'/Config/acl.php', 'acl'); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Providers/ModuleServiceProvider.php
packages/Webkul/WebForm/src/Providers/ModuleServiceProvider.php
<?php namespace Webkul\WebForm\Providers; use Webkul\Core\Providers\BaseModuleServiceProvider; class ModuleServiceProvider extends BaseModuleServiceProvider { protected $models = [ \Webkul\WebForm\Models\WebForm::class, \Webkul\WebForm\Models\WebFormAttribute::class, ]; }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/WebForm/src/Routes/routes.php
packages/Webkul/WebForm/src/Routes/routes.php
<?php use Illuminate\Support\Facades\Route; use Webkul\WebForm\Http\Controllers\WebFormController; Route::controller(WebFormController::class)->middleware(['web', 'admin_locale'])->prefix('web-forms')->group(function () { Route::get('forms/{id}/form.js', 'formJS')->name('admin.settings.web_forms.form_js'); Route::get('forms/{id}/form.html', 'preview')->name('admin.settings.web_forms.preview'); Route::post('forms/{id}', 'formStore')->name('admin.settings.web_forms.form_store'); Route::group(['middleware' => ['user']], function () { Route::get('form/{id}/form.html', 'view')->name('admin.settings.web_forms.view'); }); });
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Product/src/Contracts/Product.php
packages/Webkul/Product/src/Contracts/Product.php
<?php namespace Webkul\Product\Contracts; interface Product {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Product/src/Contracts/ProductInventory.php
packages/Webkul/Product/src/Contracts/ProductInventory.php
<?php namespace Webkul\Product\Contracts; interface ProductInventory {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Product/src/Database/Migrations/2024_08_10_150340_create_product_tags_table.php
packages/Webkul/Product/src/Database/Migrations/2024_08_10_150340_create_product_tags_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('product_tags', function (Blueprint $table) { $table->integer('tag_id')->unsigned(); $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade'); $table->integer('product_id')->unsigned(); $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('product_tags'); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Product/src/Database/Migrations/2021_04_09_065617_create_products_table.php
packages/Webkul/Product/src/Database/Migrations/2021_04_09_065617_create_products_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('products', function (Blueprint $table) { $table->increments('id'); $table->string('sku')->unique(); $table->string('name')->nullable(); $table->string('description')->nullable(); $table->integer('quantity')->default(0); $table->decimal('price', 12, 4)->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('products'); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Product/src/Database/Migrations/2024_08_10_150329_create_product_activities_table.php
packages/Webkul/Product/src/Database/Migrations/2024_08_10_150329_create_product_activities_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('product_activities', function (Blueprint $table) { $table->integer('activity_id')->unsigned(); $table->foreign('activity_id')->references('id')->on('activities')->onDelete('cascade'); $table->integer('product_id')->unsigned(); $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('product_activities'); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Product/src/Database/Migrations/2024_09_06_065808_alter_product_inventories_table.php
packages/Webkul/Product/src/Database/Migrations/2024_09_06_065808_alter_product_inventories_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up() { Schema::table('product_inventories', function (Blueprint $table) { $table->dropForeign(['warehouse_location_id']); $table->foreign('warehouse_location_id')->references('id')->on('warehouse_locations')->onDelete('cascade'); }); } public function down() { Schema::table('product_inventories', function (Blueprint $table) { $table->dropForeign(['warehouse_location_id']); $table->foreign('warehouse_location_id')->references('id')->on('warehouse_locations')->onDelete('set null'); }); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Product/src/Database/Migrations/2024_06_28_154009_create_product_inventories_table.php
packages/Webkul/Product/src/Database/Migrations/2024_06_28_154009_create_product_inventories_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('product_inventories', function (Blueprint $table) { $table->increments('id'); $table->integer('in_stock')->default(0); $table->integer('allocated')->default(0); $table->integer('product_id')->unsigned(); $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade'); $table->integer('warehouse_id')->unsigned()->nullable(); $table->foreign('warehouse_id')->references('id')->on('warehouses')->onDelete('cascade'); $table->integer('warehouse_location_id')->unsigned()->nullable(); $table->foreign('warehouse_location_id')->references('id')->on('warehouse_locations')->onDelete('SET NULL'); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('product_inventories'); } };
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Product/src/Models/ProductProxy.php
packages/Webkul/Product/src/Models/ProductProxy.php
<?php namespace Webkul\Product\Models; use Konekt\Concord\Proxies\ModelProxy; class ProductProxy extends ModelProxy {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Product/src/Models/Product.php
packages/Webkul/Product/src/Models/Product.php
<?php namespace Webkul\Product\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; use Webkul\Activity\Models\ActivityProxy; use Webkul\Activity\Traits\LogsActivity; use Webkul\Attribute\Traits\CustomAttribute; use Webkul\Product\Contracts\Product as ProductContract; use Webkul\Tag\Models\TagProxy; use Webkul\Warehouse\Models\LocationProxy; use Webkul\Warehouse\Models\WarehouseProxy; class Product extends Model implements ProductContract { use CustomAttribute, LogsActivity; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'sku', 'description', 'quantity', 'price', ]; /** * Get the product warehouses that owns the product. */ public function warehouses(): BelongsToMany { return $this->belongsToMany(WarehouseProxy::modelClass(), 'product_inventories'); } /** * Get the product locations that owns the product. */ public function locations(): BelongsToMany { return $this->belongsToMany(LocationProxy::modelClass(), 'product_inventories', 'product_id', 'warehouse_location_id'); } /** * Get the product inventories that owns the product. */ public function inventories(): HasMany { return $this->hasMany(ProductInventoryProxy::modelClass()); } /** * The tags that belong to the Products. */ public function tags() { return $this->belongsToMany(TagProxy::modelClass(), 'product_tags'); } /** * Get the activities. */ public function activities() { return $this->belongsToMany(ActivityProxy::modelClass(), 'product_activities'); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Product/src/Models/ProductInventory.php
packages/Webkul/Product/src/Models/ProductInventory.php
<?php namespace Webkul\Product\Models; use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Webkul\Product\Contracts\ProductInventory as ProductInventoryContract; use Webkul\Warehouse\Models\LocationProxy; use Webkul\Warehouse\Models\WarehouseProxy; class ProductInventory extends Model implements ProductInventoryContract { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'in_stock', 'allocated', 'product_id', 'warehouse_id', 'warehouse_location_id', ]; /** * Interact with the name. */ protected function onHand(): Attribute { return Attribute::make( get: fn ($value) => $this->in_stock - $this->allocated, set: fn ($value) => $this->in_stock - $this->allocated ); } /** * Get the product that owns the product inventory. */ public function product(): BelongsTo { return $this->belongsTo(ProductProxy::modelClass()); } /** * Get the product attribute family that owns the product. */ public function warehouse(): BelongsTo { return $this->belongsTo(WarehouseProxy::modelClass()); } /** * Get the product attribute family that owns the product. */ public function location(): BelongsTo { return $this->belongsTo(LocationProxy::modelClass(), 'warehouse_location_id'); } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Product/src/Models/ProductInventoryProxy.php
packages/Webkul/Product/src/Models/ProductInventoryProxy.php
<?php namespace Webkul\Product\Models; use Konekt\Concord\Proxies\ModelProxy; class ProductInventoryProxy extends ModelProxy {}
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Product/src/Repositories/ProductRepository.php
packages/Webkul/Product/src/Repositories/ProductRepository.php
<?php namespace Webkul\Product\Repositories; use Illuminate\Container\Container; use Illuminate\Support\Str; use Webkul\Attribute\Repositories\AttributeRepository; use Webkul\Attribute\Repositories\AttributeValueRepository; use Webkul\Core\Eloquent\Repository; use Webkul\Product\Contracts\Product; class ProductRepository extends Repository { /** * Searchable fields. */ protected $fieldSearchable = [ 'sku', 'name', 'description', ]; /** * Create a new repository instance. * * @return void */ public function __construct( protected AttributeRepository $attributeRepository, protected AttributeValueRepository $attributeValueRepository, protected ProductInventoryRepository $productInventoryRepository, Container $container ) { parent::__construct($container); } /** * Specify model class name. * * @return mixed */ public function model() { return Product::class; } /** * Create. * * @return \Webkul\Product\Contracts\Product */ public function create(array $data) { $product = parent::create($data); $this->attributeValueRepository->save(array_merge($data, [ 'entity_id' => $product->id, ])); return $product; } /** * Update. * * @param int $id * @param array $attribute * @return \Webkul\Product\Contracts\Product */ public function update(array $data, $id, $attributes = []) { $product = parent::update($data, $id); /** * If attributes are provided then only save the provided attributes and return. */ if (! empty($attributes)) { $conditions = ['entity_type' => $data['entity_type']]; if (isset($data['quick_add'])) { $conditions['quick_add'] = 1; } $attributes = $this->attributeRepository->where($conditions) ->whereIn('code', $attributes) ->get(); $this->attributeValueRepository->save(array_merge($data, [ 'entity_id' => $product->id, ]), $attributes); return $product; } $this->attributeValueRepository->save(array_merge($data, [ 'entity_id' => $product->id, ])); return $product; } /** * Save inventories. * * @param int $id * @param ?int $warehouseId * @return void */ public function saveInventories(array $data, $id, $warehouseId = null) { $productInventories = $this->productInventoryRepository->where('product_id', $id); if ($warehouseId) { $productInventories = $productInventories->where('warehouse_id', $warehouseId); } $previousInventoryIds = $productInventories->pluck('id'); if (isset($data['inventories'])) { foreach ($data['inventories'] as $inventoryId => $inventoryData) { if (Str::contains($inventoryId, 'inventory_')) { $this->productInventoryRepository->create(array_merge($inventoryData, [ 'product_id' => $id, 'warehouse_id' => $warehouseId, ])); } else { if (is_numeric($index = $previousInventoryIds->search($inventoryId))) { $previousInventoryIds->forget($index); } $this->productInventoryRepository->update($inventoryData, $inventoryId); } } } foreach ($previousInventoryIds as $inventoryId) { $this->productInventoryRepository->delete($inventoryId); } } /** * Retrieves customers count based on date. * * @return int */ public function getProductCount($startDate, $endDate) { return $this ->whereBetween('created_at', [$startDate, $endDate]) ->get() ->count(); } /** * Get inventories grouped by warehouse. * * @param int $id * @return array */ public function getInventoriesGroupedByWarehouse($id) { $product = $this->findOrFail($id); $warehouses = []; foreach ($product->inventories as $inventory) { if (! isset($warehouses[$inventory->warehouse_id])) { $warehouses[$inventory->warehouse_id] = [ 'id' => $inventory->warehouse_id, 'name' => $inventory->warehouse->name, 'in_stock' => $inventory->in_stock, 'allocated' => $inventory->allocated, 'on_hand' => $inventory->on_hand, ]; } else { $warehouses[$inventory->warehouse_id]['in_stock'] += $inventory->in_stock; $warehouses[$inventory->warehouse_id]['allocated'] += $inventory->allocated; $warehouses[$inventory->warehouse_id]['on_hand'] += $inventory->on_hand; } $warehouses[$inventory->warehouse_id]['locations'][] = [ 'id' => $inventory->warehouse_location_id, 'name' => $inventory->location->name, 'in_stock' => $inventory->in_stock, 'allocated' => $inventory->allocated, 'on_hand' => $inventory->on_hand, ]; } return $warehouses; } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Product/src/Repositories/ProductInventoryRepository.php
packages/Webkul/Product/src/Repositories/ProductInventoryRepository.php
<?php namespace Webkul\Product\Repositories; use Webkul\Core\Eloquent\Repository; class ProductInventoryRepository extends Repository { /** * Specify Model class name * * @return mixed */ public function model() { return 'Webkul\Product\Contracts\ProductInventory'; } }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Product/src/Providers/ProductServiceProvider.php
packages/Webkul/Product/src/Providers/ProductServiceProvider.php
<?php namespace Webkul\Product\Providers; use Illuminate\Routing\Router; use Illuminate\Support\ServiceProvider; class ProductServiceProvider extends ServiceProvider { /** * Bootstrap services. * * @return void */ public function boot(Router $router) { $this->loadMigrationsFrom(__DIR__.'/../Database/Migrations'); } /** * Register services. * * @return void */ public function register() {} }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
krayin/laravel-crm
https://github.com/krayin/laravel-crm/blob/6b6fadfecea0ff5d80aedb9345602ff79e11922d/packages/Webkul/Product/src/Providers/ModuleServiceProvider.php
packages/Webkul/Product/src/Providers/ModuleServiceProvider.php
<?php namespace Webkul\Product\Providers; use Webkul\Core\Providers\BaseModuleServiceProvider; class ModuleServiceProvider extends BaseModuleServiceProvider { protected $models = [ \Webkul\Product\Models\Product::class, \Webkul\Product\Models\ProductInventory::class, ]; }
php
MIT
6b6fadfecea0ff5d80aedb9345602ff79e11922d
2026-01-04T15:02:34.361572Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/rector.php
rector.php
<?php use Rector\Config\RectorConfig; use Rector\TypeDeclaration\Rector\Property\TypedPropertyFromStrictConstructorRector; use RectorLaravel\Set\LaravelLevelSetList; use RectorLaravel\Set\LaravelSetList; return RectorConfig::configure() // register single rule ->withPaths([ __DIR__.'/app', __DIR__.'/routes', __DIR__.'/config', ]) ->withSets([ LaravelLevelSetList::UP_TO_LARAVEL_110, LaravelSetList::LARAVEL_ARRAY_STR_FUNCTION_TO_STATIC_CALL, LaravelSetList::LARAVEL_CODE_QUALITY, LaravelSetList::LARAVEL_COLLECTION, LaravelSetList::LARAVEL_CONTAINER_STRING_TO_FULLY_QUALIFIED_NAME, LaravelSetList::LARAVEL_ELOQUENT_MAGIC_METHOD_TO_QUERY_BUILDER, ]) ->withRules([ TypedPropertyFromStrictConstructorRector::class, ]) ->withPreparedSets( deadCode: true, codeQuality: true, naming: true, privatization: true, earlyReturn: true, );
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/lang/en/passwords.php
lang/en/passwords.php
<?php return [ /* |-------------------------------------------------------------------------- | Password Reset Language Lines |-------------------------------------------------------------------------- | | The following language lines are the default lines which match reasons | that are given by the password broker for a password update attempt | outcome such as failure due to an invalid password / reset token. | */ 'reset' => 'Your password has been reset.', 'sent' => 'If an account exists with this email address, you will receive a password reset link shortly.', 'throttled' => 'Please wait before retrying.', 'token' => 'This password reset token is invalid.', 'user' => 'If an account exists with this email address, you will receive a password reset link shortly.', ];
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/SendMessageToPushoverJob.php
app/Jobs/SendMessageToPushoverJob.php
<?php namespace App\Jobs; use App\Notifications\Dto\PushoverMessage; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Http; class SendMessageToPushoverJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * The number of times the job may be attempted. * * @var int */ public $tries = 5; public $backoff = 10; /** * The maximum number of unhandled exceptions to allow before failing. */ public int $maxExceptions = 5; public function __construct( public PushoverMessage $message, public string $token, public string $user, ) { $this->onQueue('high'); } /** * Execute the job. */ public function handle(): void { $response = Http::post('https://api.pushover.net/1/messages.json', $this->message->toPayload($this->token, $this->user)); if ($response->failed()) { throw new \RuntimeException('Pushover notification failed with '.$response->status().' status code.'.$response->body()); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/ApplicationPullRequestUpdateJob.php
app/Jobs/ApplicationPullRequestUpdateJob.php
<?php namespace App\Jobs; use App\Enums\ProcessStatus; use App\Models\Application; use App\Models\ApplicationPreview; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class ApplicationPullRequestUpdateJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public string $build_logs_url; public string $body; public function __construct( public Application $application, public ApplicationPreview $preview, public ProcessStatus $status, public ?string $deployment_uuid = null ) { $this->onQueue('high'); } public function handle() { try { if ($this->application->is_public_repository()) { return; } $serviceName = $this->application->name; if ($this->status === ProcessStatus::CLOSED) { $this->delete_comment(); return; } match ($this->status) { ProcessStatus::QUEUED => $this->body = "The preview deployment for **{$serviceName}** is queued. ⏳\n\n", ProcessStatus::IN_PROGRESS => $this->body = "The preview deployment for **{$serviceName}** is in progress. 🟡\n\n", ProcessStatus::FINISHED => $this->body = "The preview deployment for **{$serviceName}** is ready. 🟢\n\n".($this->preview->fqdn ? "[Open Preview]({$this->preview->fqdn}) | " : ''), ProcessStatus::ERROR => $this->body = "The preview deployment for **{$serviceName}** failed. 🔴\n\n", ProcessStatus::KILLED => $this->body = "The preview deployment for **{$serviceName}** was killed. ⚫\n\n", ProcessStatus::CANCELLED => $this->body = "The preview deployment for **{$serviceName}** was cancelled. 🚫\n\n", ProcessStatus::CLOSED => '', // Already handled above, but included for completeness }; $this->build_logs_url = base_url()."/project/{$this->application->environment->project->uuid}/environment/{$this->application->environment->uuid}/application/{$this->application->uuid}/deployment/{$this->deployment_uuid}"; $this->body .= '[Open Build Logs]('.$this->build_logs_url.")\n\n\n"; $this->body .= 'Last updated at: '.now()->toDateTimeString().' CET'; if ($this->preview->pull_request_issue_comment_id) { $this->update_comment(); } else { $this->create_comment(); } } catch (\Throwable $e) { return $e; } } private function update_comment() { ['data' => $data] = githubApi(source: $this->application->source, endpoint: "/repos/{$this->application->git_repository}/issues/comments/{$this->preview->pull_request_issue_comment_id}", method: 'patch', data: [ 'body' => $this->body, ], throwError: false); if (data_get($data, 'message') === 'Not Found') { $this->create_comment(); } } private function create_comment() { ['data' => $data] = githubApi(source: $this->application->source, endpoint: "/repos/{$this->application->git_repository}/issues/{$this->preview->pull_request_id}/comments", method: 'post', data: [ 'body' => $this->body, ]); $this->preview->pull_request_issue_comment_id = $data['id']; $this->preview->save(); } private function delete_comment() { githubApi(source: $this->application->source, endpoint: "/repos/{$this->application->git_repository}/issues/comments/{$this->preview->pull_request_issue_comment_id}", method: 'delete'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/ServerPatchCheckJob.php
app/Jobs/ServerPatchCheckJob.php
<?php namespace App\Jobs; use App\Actions\Server\CheckUpdates; use App\Models\Server; use App\Notifications\Server\ServerPatchCheck; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\Middleware\WithoutOverlapping; use Illuminate\Queue\SerializesModels; class ServerPatchCheckJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $tries = 3; public $timeout = 600; public function middleware(): array { return [(new WithoutOverlapping('server-patch-check-'.$this->server->uuid))->expireAfter(600)->dontRelease()]; } public function __construct(public Server $server) {} public function handle(): void { try { if ($this->server->serverStatus() === false) { return; } $team = data_get($this->server, 'team'); if (! $team) { return; } // Check for updates $patchData = CheckUpdates::run($this->server); if (isset($patchData['error'])) { $team->notify(new ServerPatchCheck($this->server, $patchData)); return; // Skip if there's an error checking for updates } $totalUpdates = $patchData['total_updates'] ?? 0; // Only send notification if there are updates available if ($totalUpdates > 0) { $team->notify(new ServerPatchCheck($this->server, $patchData)); } } catch (\Throwable $e) { // Log error but don't fail the job \Illuminate\Support\Facades\Log::error('ServerPatchCheckJob failed: '.$e->getMessage(), [ 'server_id' => $this->server->id, 'server_name' => $this->server->name, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString(), ]); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/CleanupStaleMultiplexedConnections.php
app/Jobs/CleanupStaleMultiplexedConnections.php
<?php namespace App\Jobs; use App\Models\Server; use Carbon\Carbon; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Process; use Illuminate\Support\Facades\Storage; class CleanupStaleMultiplexedConnections implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public function handle() { $this->cleanupStaleConnections(); $this->cleanupNonExistentServerConnections(); } private function cleanupStaleConnections() { $muxFiles = Storage::disk('ssh-mux')->files(); foreach ($muxFiles as $muxFile) { $serverUuid = $this->extractServerUuidFromMuxFile($muxFile); $server = Server::where('uuid', $serverUuid)->first(); if (! $server) { $this->removeMultiplexFile($muxFile); continue; } $muxSocket = "/var/www/html/storage/app/ssh/mux/{$muxFile}"; $checkCommand = "ssh -O check -o ControlPath={$muxSocket} {$server->user}@{$server->ip} 2>/dev/null"; $checkProcess = Process::run($checkCommand); if ($checkProcess->exitCode() !== 0) { $this->removeMultiplexFile($muxFile); } else { $muxContent = Storage::disk('ssh-mux')->get($muxFile); $establishedAt = Carbon::parse(substr($muxContent, 37)); $expirationTime = $establishedAt->addSeconds(config('constants.ssh.mux_persist_time')); if (Carbon::now()->isAfter($expirationTime)) { $this->removeMultiplexFile($muxFile); } } } } private function cleanupNonExistentServerConnections() { $muxFiles = Storage::disk('ssh-mux')->files(); $existingServerUuids = Server::pluck('uuid')->toArray(); foreach ($muxFiles as $muxFile) { $serverUuid = $this->extractServerUuidFromMuxFile($muxFile); if (! in_array($serverUuid, $existingServerUuids)) { $this->removeMultiplexFile($muxFile); } } } private function extractServerUuidFromMuxFile($muxFile) { return substr($muxFile, 4); } private function removeMultiplexFile($muxFile) { $muxSocket = "/var/www/html/storage/app/ssh/mux/{$muxFile}"; $closeCommand = "ssh -O exit -o ControlPath={$muxSocket} localhost 2>/dev/null"; Process::run($closeCommand); Storage::disk('ssh-mux')->delete($muxFile); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/ServerCheckJob.php
app/Jobs/ServerCheckJob.php
<?php namespace App\Jobs; use App\Actions\Docker\GetContainersStatus; use App\Actions\Proxy\CheckProxy; use App\Actions\Proxy\StartProxy; use App\Actions\Server\StartLogDrain; use App\Models\Server; use App\Notifications\Container\ContainerRestarted; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\Middleware\WithoutOverlapping; use Illuminate\Queue\SerializesModels; class ServerCheckJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $tries = 1; public $timeout = 60; public $containers; public function middleware(): array { return [(new WithoutOverlapping('server-check-'.$this->server->uuid))->expireAfter(60)->dontRelease()]; } public function __construct(public Server $server) {} public function handle() { try { if ($this->server->serverStatus() === false) { return 'Server is not reachable or not ready.'; } if (! $this->server->isSwarmWorker() && ! $this->server->isBuildServer()) { ['containers' => $this->containers, 'containerReplicates' => $containerReplicates] = $this->server->getContainers(); if (is_null($this->containers)) { return 'No containers found.'; } GetContainersStatus::run($this->server, $this->containers, $containerReplicates); if ($this->server->isSentinelEnabled()) { CheckAndStartSentinelJob::dispatch($this->server); } if ($this->server->isLogDrainEnabled()) { $this->checkLogDrainContainer(); } if ($this->server->proxySet() && ! $this->server->proxy->force_stop) { $this->server->proxyType(); $foundProxyContainer = $this->containers->filter(function ($value, $key) { if ($this->server->isSwarm()) { return data_get($value, 'Spec.Name') === 'coolify-proxy_traefik'; } else { return data_get($value, 'Name') === '/coolify-proxy'; } })->first(); if (! $foundProxyContainer) { try { $shouldStart = CheckProxy::run($this->server); if ($shouldStart) { StartProxy::run($this->server, async: false); $this->server->team?->notify(new ContainerRestarted('coolify-proxy', $this->server)); } } catch (\Throwable $e) { } } else { $this->server->proxy->status = data_get($foundProxyContainer, 'State.Status'); $this->server->save(); ConnectProxyToNetworksJob::dispatchSync($this->server); } } } } catch (\Throwable $e) { return handleError($e); } } private function checkLogDrainContainer() { $foundLogDrainContainer = $this->containers->filter(function ($value, $key) { return data_get($value, 'Name') === '/coolify-log-drain'; })->first(); if ($foundLogDrainContainer) { $status = data_get($foundLogDrainContainer, 'State.Status'); if ($status !== 'running') { StartLogDrain::dispatch($this->server); } } else { StartLogDrain::dispatch($this->server); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/PullTemplatesFromCDN.php
app/Jobs/PullTemplatesFromCDN.php
<?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Http; class PullTemplatesFromCDN implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $timeout = 10; public function __construct() { $this->onQueue('high'); } public function handle(): void { try { if (isDev()) { return; } $response = Http::retry(3, 1000)->get(config('constants.services.official')); if ($response->successful()) { $services = $response->json(); File::put(base_path('templates/'.config('constants.services.file_name')), json_encode($services)); } else { send_internal_notification('PullTemplatesAndVersions failed with: '.$response->status().' '.$response->body()); } } catch (\Throwable $e) { send_internal_notification('PullTemplatesAndVersions failed with: '.$e->getMessage()); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/ServerManagerJob.php
app/Jobs/ServerManagerJob.php
<?php namespace App\Jobs; use App\Models\InstanceSettings; use App\Models\Server; use App\Models\Team; use Cron\CronExpression; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Carbon; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; class ServerManagerJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * The time when this job execution started. */ private ?Carbon $executionTime = null; private InstanceSettings $settings; private string $instanceTimezone; private string $checkFrequency = '* * * * *'; /** * Create a new job instance. */ public function __construct() { $this->onQueue('high'); } public function handle(): void { // Freeze the execution time at the start of the job $this->executionTime = Carbon::now(); if (isCloud()) { $this->checkFrequency = '*/5 * * * *'; } $this->settings = instanceSettings(); $this->instanceTimezone = $this->settings->instance_timezone ?: config('app.timezone'); if (validate_timezone($this->instanceTimezone) === false) { $this->instanceTimezone = config('app.timezone'); } // Get all servers to process $servers = $this->getServers(); // Dispatch ServerConnectionCheck for all servers efficiently $this->dispatchConnectionChecks($servers); // Process server-specific scheduled tasks $this->processScheduledTasks($servers); } private function getServers(): Collection { $allServers = Server::where('ip', '!=', '1.2.3.4'); if (isCloud()) { $servers = $allServers->whereRelation('team.subscription', 'stripe_invoice_paid', true)->get(); $own = Team::find(0)->servers; return $servers->merge($own); } else { return $allServers->get(); } } private function dispatchConnectionChecks(Collection $servers): void { if ($this->shouldRunNow($this->checkFrequency)) { $servers->each(function (Server $server) { try { ServerConnectionCheckJob::dispatch($server); } catch (\Exception $e) { Log::channel('scheduled-errors')->error('Failed to dispatch ServerConnectionCheck', [ 'server_id' => $server->id, 'server_name' => $server->name, 'error' => get_class($e).': '.$e->getMessage(), ]); } }); } } private function processScheduledTasks(Collection $servers): void { foreach ($servers as $server) { try { $this->processServerTasks($server); } catch (\Exception $e) { Log::channel('scheduled-errors')->error('Error processing server tasks', [ 'server_id' => $server->id, 'server_name' => $server->name, 'error' => get_class($e).': '.$e->getMessage(), ]); } } } private function processServerTasks(Server $server): void { // Get server timezone (used for all scheduled tasks) $serverTimezone = data_get($server->settings, 'server_timezone', $this->instanceTimezone); if (validate_timezone($serverTimezone) === false) { $serverTimezone = config('app.timezone'); } // Check if we should run sentinel-based checks $lastSentinelUpdate = $server->sentinel_updated_at; $waitTime = $server->waitBeforeDoingSshCheck(); $sentinelOutOfSync = Carbon::parse($lastSentinelUpdate)->isBefore($this->executionTime->copy()->subSeconds($waitTime)); if ($sentinelOutOfSync) { // Dispatch ServerCheckJob if Sentinel is out of sync if ($this->shouldRunNow($this->checkFrequency, $serverTimezone)) { ServerCheckJob::dispatch($server); } } $isSentinelEnabled = $server->isSentinelEnabled(); $shouldRestartSentinel = $isSentinelEnabled && $this->shouldRunNow('0 0 * * *', $serverTimezone); // Dispatch Sentinel restart if due (daily for Sentinel-enabled servers) if ($shouldRestartSentinel) { dispatch(function () use ($server) { $server->restartContainer('coolify-sentinel'); }); } // Dispatch ServerStorageCheckJob if due (only when Sentinel is out of sync or disabled) // When Sentinel is active, PushServerUpdateJob handles storage checks with real-time data if ($sentinelOutOfSync) { $serverDiskUsageCheckFrequency = data_get($server->settings, 'server_disk_usage_check_frequency', '0 23 * * *'); if (isset(VALID_CRON_STRINGS[$serverDiskUsageCheckFrequency])) { $serverDiskUsageCheckFrequency = VALID_CRON_STRINGS[$serverDiskUsageCheckFrequency]; } $shouldRunStorageCheck = $this->shouldRunNow($serverDiskUsageCheckFrequency, $serverTimezone); if ($shouldRunStorageCheck) { ServerStorageCheckJob::dispatch($server); } } // Dispatch ServerPatchCheckJob if due (weekly) $shouldRunPatchCheck = $this->shouldRunNow('0 0 * * 0', $serverTimezone); if ($shouldRunPatchCheck) { // Weekly on Sunday at midnight ServerPatchCheckJob::dispatch($server); } // Sentinel update checks (hourly) - check for updates to Sentinel version // No timezone needed for hourly - runs at top of every hour if ($isSentinelEnabled && $this->shouldRunNow('0 * * * *')) { CheckAndStartSentinelJob::dispatch($server); } } private function shouldRunNow(string $frequency, ?string $timezone = null): bool { $cron = new CronExpression($frequency); // Use the frozen execution time, not the current time $baseTime = $this->executionTime ?? Carbon::now(); $executionTime = $baseTime->copy()->setTimezone($timezone ?? config('app.timezone')); return $cron->isDue($executionTime); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/VerifyStripeSubscriptionStatusJob.php
app/Jobs/VerifyStripeSubscriptionStatusJob.php
<?php namespace App\Jobs; use App\Models\Subscription; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class VerifyStripeSubscriptionStatusJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public int $tries = 3; public array $backoff = [10, 30, 60]; public function __construct(public Subscription $subscription) { $this->onQueue('high'); } public function handle(): void { // If no subscription ID yet, try to find it via customer if (! $this->subscription->stripe_subscription_id && $this->subscription->stripe_customer_id) { try { $stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key')); $subscriptions = $stripe->subscriptions->all([ 'customer' => $this->subscription->stripe_customer_id, 'limit' => 1, ]); if ($subscriptions->data) { $this->subscription->update([ 'stripe_subscription_id' => $subscriptions->data[0]->id, ]); } } catch (\Exception $e) { // Continue without subscription ID } } if (! $this->subscription->stripe_subscription_id) { return; } try { $stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key')); $stripeSubscription = $stripe->subscriptions->retrieve( $this->subscription->stripe_subscription_id ); switch ($stripeSubscription->status) { case 'active': $this->subscription->update([ 'stripe_invoice_paid' => true, 'stripe_past_due' => false, 'stripe_cancel_at_period_end' => $stripeSubscription->cancel_at_period_end, ]); break; case 'past_due': // Keep subscription active but mark as past_due $this->subscription->update([ 'stripe_invoice_paid' => true, 'stripe_past_due' => true, 'stripe_cancel_at_period_end' => $stripeSubscription->cancel_at_period_end, ]); break; case 'canceled': case 'incomplete_expired': case 'unpaid': // Ensure subscription is marked as inactive $this->subscription->update([ 'stripe_invoice_paid' => false, 'stripe_past_due' => false, ]); // Trigger subscription ended logic if canceled if ($stripeSubscription->status === 'canceled') { $team = $this->subscription->team; if ($team) { $team->subscriptionEnded(); } } break; default: send_internal_notification( 'Unknown subscription status in VerifyStripeSubscriptionStatusJob: '.$stripeSubscription->status. ' for customer: '.$this->subscription->stripe_customer_id ); break; } } catch (\Exception $e) { send_internal_notification( 'VerifyStripeSubscriptionStatusJob failed for subscription ID '.$this->subscription->id.': '.$e->getMessage() ); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/ServerCleanupMux.php
app/Jobs/ServerCleanupMux.php
<?php namespace App\Jobs; use App\Helpers\SshMultiplexingHelper; use App\Models\Server; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class ServerCleanupMux implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $tries = 1; public $timeout = 60; public function backoff(): int { return isDev() ? 1 : 3; } public function __construct(public Server $server) {} public function handle() { try { if ($this->server->serverStatus() === false) { return 'Server is not reachable or not ready.'; } SshMultiplexingHelper::removeMuxFile($this->server); } catch (\Throwable $e) { return handleError($e); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/CoolifyTask.php
app/Jobs/CoolifyTask.php
<?php namespace App\Jobs; use App\Actions\CoolifyTask\RunRemoteProcess; use App\Enums\ProcessStatus; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Log; use Spatie\Activitylog\Models\Activity; class CoolifyTask implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * The number of times the job may be attempted. */ public $tries = 3; /** * The maximum number of unhandled exceptions to allow before failing. */ public $maxExceptions = 1; /** * The number of seconds the job can run before timing out. */ public $timeout = 600; /** * Create a new job instance. */ public function __construct( public Activity $activity, public bool $ignore_errors, public $call_event_on_finish, public $call_event_data, ) { $this->onQueue('high'); } /** * Execute the job. */ public function handle(): void { $remote_process = resolve(RunRemoteProcess::class, [ 'activity' => $this->activity, 'ignore_errors' => $this->ignore_errors, 'call_event_on_finish' => $this->call_event_on_finish, 'call_event_data' => $this->call_event_data, ]); $remote_process(); } /** * Calculate the number of seconds to wait before retrying the job. */ public function backoff(): array { return [30, 90, 180]; // 30s, 90s, 180s between retries } /** * Handle a job failure. */ public function failed(?\Throwable $exception): void { Log::channel('scheduled-errors')->error('CoolifyTask permanently failed', [ 'job' => 'CoolifyTask', 'activity_id' => $this->activity->id, 'server_uuid' => $this->activity->getExtraProperty('server_uuid'), 'command_preview' => substr($this->activity->getExtraProperty('command') ?? '', 0, 200), 'error' => $exception?->getMessage(), 'total_attempts' => $this->attempts(), 'trace' => $exception?->getTraceAsString(), ]); // Update activity status to reflect permanent failure $this->activity->properties = $this->activity->properties->merge([ 'status' => ProcessStatus::ERROR->value, 'error' => $exception?->getMessage() ?? 'Job permanently failed', 'failed_at' => now()->toIso8601String(), ]); $this->activity->save(); // Dispatch cleanup event on failure (same as on success) if ($this->call_event_on_finish) { try { $eventClass = "App\\Events\\$this->call_event_on_finish"; if (! is_null($this->call_event_data)) { event(new $eventClass($this->call_event_data)); } else { event(new $eventClass($this->activity->causer_id)); } Log::info('Cleanup event dispatched after job failure', [ 'event' => $this->call_event_on_finish, ]); } catch (\Throwable $e) { Log::error('Error dispatching cleanup event on failure: '.$e->getMessage()); } } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/ServerStorageCheckJob.php
app/Jobs/ServerStorageCheckJob.php
<?php namespace App\Jobs; use App\Models\Server; use App\Notifications\Server\HighDiskUsage; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\RateLimiter; use Laravel\Horizon\Contracts\Silenced; class ServerStorageCheckJob implements ShouldBeEncrypted, ShouldQueue, Silenced { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $tries = 1; public $timeout = 60; public function backoff(): int { return isDev() ? 1 : 3; } public function __construct(public Server $server, public int|string|null $percentage = null) {} public function handle() { try { if ($this->server->isFunctional() === false) { return 'Server is not functional.'; } $team = data_get($this->server, 'team'); $serverDiskUsageNotificationThreshold = data_get($this->server, 'settings.server_disk_usage_notification_threshold'); if (is_null($this->percentage)) { $this->percentage = $this->server->storageCheck(); } if (! $this->percentage) { return 'No percentage could be retrieved.'; } if ($this->percentage > $serverDiskUsageNotificationThreshold) { $executed = RateLimiter::attempt( 'high-disk-usage:'.$this->server->id, $maxAttempts = 0, function () use ($team, $serverDiskUsageNotificationThreshold) { $team->notify(new HighDiskUsage($this->server, $this->percentage, $serverDiskUsageNotificationThreshold)); }, $decaySeconds = 3600, ); if (! $executed) { return 'Too many messages sent!'; } } else { RateLimiter::hit('high-disk-usage:'.$this->server->id, 600); } } catch (\Throwable $e) { return handleError($e); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/CheckForUpdatesJob.php
app/Jobs/CheckForUpdatesJob.php
<?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; class CheckForUpdatesJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public function handle(): void { try { if (isDev() || isCloud()) { return; } $settings = instanceSettings(); $response = Http::retry(3, 1000)->get(config('constants.coolify.versions_url')); if ($response->successful()) { $versions = $response->json(); $latest_version = data_get($versions, 'coolify.v4.version'); $current_version = config('constants.coolify.version'); // Read existing cached version $existingVersions = null; $existingCoolifyVersion = null; if (File::exists(base_path('versions.json'))) { $existingVersions = json_decode(File::get(base_path('versions.json')), true); $existingCoolifyVersion = data_get($existingVersions, 'coolify.v4.version'); } // Determine the BEST version to use (CDN, cache, or current) $bestVersion = $latest_version; // Check if cache has newer version than CDN if ($existingCoolifyVersion && version_compare($existingCoolifyVersion, $bestVersion, '>')) { Log::warning('CDN served older Coolify version than cache', [ 'cdn_version' => $latest_version, 'cached_version' => $existingCoolifyVersion, 'current_version' => $current_version, ]); $bestVersion = $existingCoolifyVersion; } // CRITICAL: Never allow bestVersion to be older than currently running version if (version_compare($bestVersion, $current_version, '<')) { Log::warning('Version downgrade prevented in CheckForUpdatesJob', [ 'cdn_version' => $latest_version, 'cached_version' => $existingCoolifyVersion, 'current_version' => $current_version, 'attempted_best' => $bestVersion, 'using' => $current_version, ]); $bestVersion = $current_version; } // Use data_set() for safe mutation (fixes #3) data_set($versions, 'coolify.v4.version', $bestVersion); $latest_version = $bestVersion; // ALWAYS write versions.json (for Sentinel, Helper, Traefik updates) File::put(base_path('versions.json'), json_encode($versions, JSON_PRETTY_PRINT)); // Invalidate cache to ensure fresh data is loaded invalidate_versions_cache(); // Only mark new version available if Coolify version actually increased if (version_compare($latest_version, $current_version, '>')) { // New version available $settings->update(['new_version_available' => true]); } else { $settings->update(['new_version_available' => false]); } } } catch (\Throwable $e) { // Consider implementing a notification to administrators } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/ScheduledTaskJob.php
app/Jobs/ScheduledTaskJob.php
<?php namespace App\Jobs; use App\Events\ScheduledTaskDone; use App\Exceptions\NonReportableException; use App\Models\Application; use App\Models\ScheduledTask; use App\Models\ScheduledTaskExecution; use App\Models\Server; use App\Models\Service; use App\Models\Team; use App\Notifications\ScheduledTask\TaskFailed; use App\Notifications\ScheduledTask\TaskSuccess; use Carbon\Carbon; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Log; class ScheduledTaskJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * The number of times the job may be attempted. */ public $tries = 3; /** * The maximum number of unhandled exceptions to allow before failing. */ public $maxExceptions = 1; /** * The number of seconds the job can run before timing out. */ public $timeout = 300; public Team $team; public ?Server $server = null; public ScheduledTask $task; public Application|Service $resource; public ?ScheduledTaskExecution $task_log = null; /** * Store execution ID to survive job serialization for timeout handling. */ protected ?int $executionId = null; public string $task_status = 'failed'; public ?string $task_output = null; public array $containers = []; public string $server_timezone; public function __construct($task) { $this->onQueue('high'); $this->task = $task; if ($service = $task->service()->first()) { $this->resource = $service; } elseif ($application = $task->application()->first()) { $this->resource = $application; } else { throw new \RuntimeException('ScheduledTaskJob failed: No resource found.'); } $this->team = Team::findOrFail($task->team_id); $this->server_timezone = $this->getServerTimezone(); // Set timeout from task configuration $this->timeout = $this->task->timeout ?? 300; } private function getServerTimezone(): string { if ($this->resource instanceof Application) { return $this->resource->destination->server->settings->server_timezone; } elseif ($this->resource instanceof Service) { return $this->resource->server->settings->server_timezone; } return 'UTC'; } public function handle(): void { $startTime = Carbon::now(); try { $this->task_log = ScheduledTaskExecution::create([ 'scheduled_task_id' => $this->task->id, 'started_at' => $startTime, 'retry_count' => $this->attempts() - 1, ]); // Store execution ID for timeout handling $this->executionId = $this->task_log->id; $this->server = $this->resource->destination->server; if ($this->resource->type() === 'application') { $containers = getCurrentApplicationContainerStatus($this->server, $this->resource->id, 0); if ($containers->count() > 0) { $containers->each(function ($container) { $this->containers[] = str_replace('/', '', $container['Names']); }); } } elseif ($this->resource->type() === 'service') { $this->resource->applications()->get()->each(function ($application) { if (str(data_get($application, 'status'))->contains('running')) { $this->containers[] = data_get($application, 'name').'-'.data_get($this->resource, 'uuid'); } }); $this->resource->databases()->get()->each(function ($database) { if (str(data_get($database, 'status'))->contains('running')) { $this->containers[] = data_get($database, 'name').'-'.data_get($this->resource, 'uuid'); } }); } if (count($this->containers) == 0) { throw new \Exception('ScheduledTaskJob failed: No containers running.'); } if (count($this->containers) > 1 && empty($this->task->container)) { throw new \Exception('ScheduledTaskJob failed: More than one container exists but no container name was provided.'); } foreach ($this->containers as $containerName) { if (count($this->containers) == 1 || str_starts_with($containerName, $this->task->container.'-'.$this->resource->uuid)) { $cmd = "sh -c '".str_replace("'", "'\''", $this->task->command)."'"; $exec = "docker exec {$containerName} {$cmd}"; // Disable SSH multiplexing to prevent race conditions when multiple tasks run concurrently // See: https://github.com/coollabsio/coolify/issues/6736 $this->task_output = instant_remote_process([$exec], $this->server, true, false, $this->timeout, disableMultiplexing: true); $this->task_log->update([ 'status' => 'success', 'message' => $this->task_output, ]); $this->team?->notify(new TaskSuccess($this->task, $this->task_output)); return; } } // No valid container was found. throw new NonReportableException('ScheduledTaskJob failed: No valid container was found. Is the container name correct?'); } catch (\Throwable $e) { if ($this->task_log) { $this->task_log->update([ 'status' => 'failed', 'message' => $this->task_output ?? $e->getMessage(), ]); } // Log the error to the scheduled-errors channel Log::channel('scheduled-errors')->error('ScheduledTask execution failed', [ 'job' => 'ScheduledTaskJob', 'task_id' => $this->task->uuid, 'task_name' => $this->task->name, 'server' => $this->server?->name ?? 'unknown', 'attempt' => $this->attempts(), 'error' => $e->getMessage(), ]); // Only notify and throw on final failure // Re-throw to trigger Laravel's retry mechanism with backoff throw $e; } finally { ScheduledTaskDone::dispatch($this->team->id); if ($this->task_log) { $finishedAt = Carbon::now(); $duration = round($startTime->floatDiffInSeconds($finishedAt), 2); $this->task_log->update([ 'finished_at' => $finishedAt->toImmutable(), 'duration' => $duration, ]); } } } /** * Calculate the number of seconds to wait before retrying the job. */ public function backoff(): array { return [30, 60, 120]; // 30s, 60s, 120s between retries } /** * Handle a job failure. */ public function failed(?\Throwable $exception): void { Log::channel('scheduled-errors')->error('ScheduledTask permanently failed', [ 'job' => 'ScheduledTaskJob', 'task_id' => $this->task->uuid, 'task_name' => $this->task->name, 'server' => $this->server?->name ?? 'unknown', 'total_attempts' => $this->attempts(), 'error' => $exception?->getMessage(), 'trace' => $exception?->getTraceAsString(), ]); // Reload execution log from database // When a job times out, failed() is called in a fresh process with the original // queue payload, so $executionId will be null. We need to query for the latest execution. $execution = null; // Try to find execution using stored ID first (works for non-timeout failures) if ($this->executionId) { $execution = ScheduledTaskExecution::find($this->executionId); } // If no stored ID or not found, query for the most recent execution log for this task if (! $execution) { $execution = ScheduledTaskExecution::query() ->where('scheduled_task_id', $this->task->id) ->orderBy('created_at', 'desc') ->first(); } // Last resort: check task_log property if (! $execution && $this->task_log) { $execution = $this->task_log; } if ($execution) { $errorMessage = 'Job permanently failed after '.$this->attempts().' attempts'; if ($exception) { $errorMessage .= ': '.$exception->getMessage(); } $execution->update([ 'status' => 'failed', 'message' => $errorMessage, 'error_details' => $exception?->getTraceAsString(), 'finished_at' => Carbon::now()->toImmutable(), ]); } else { Log::channel('scheduled-errors')->warning('Could not find execution log to update', [ 'execution_id' => $this->executionId, 'task_id' => $this->task->uuid, ]); } // Notify team about permanent failure $this->team?->notify(new TaskFailed($this->task, $exception?->getMessage() ?? 'Unknown error')); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/ServerFilesFromServerJob.php
app/Jobs/ServerFilesFromServerJob.php
<?php namespace App\Jobs; use App\Models\Application; use App\Models\ServiceApplication; use App\Models\ServiceDatabase; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class ServerFilesFromServerJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public function __construct(public ServiceApplication|ServiceDatabase|Application $resource) { $this->onQueue('high'); } public function handle() { $this->resource->getFilesFromServer(isInit: true); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/GithubAppPermissionJob.php
app/Jobs/GithubAppPermissionJob.php
<?php namespace App\Jobs; use App\Models\GithubApp; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Http; class GithubAppPermissionJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $tries = 4; public function backoff(): int { return isDev() ? 1 : 3; } public function __construct(public GithubApp $github_app) {} public function handle() { try { $github_access_token = generateGithubJwt($this->github_app); $response = Http::withHeaders([ 'Authorization' => "Bearer $github_access_token", 'Accept' => 'application/vnd.github+json', ])->get("{$this->github_app->api_url}/app"); if (! $response->successful()) { throw new \RuntimeException('Failed to fetch GitHub app permissions: '.$response->body()); } $response = $response->json(); $permissions = data_get($response, 'permissions'); $this->github_app->contents = data_get($permissions, 'contents'); $this->github_app->metadata = data_get($permissions, 'metadata'); $this->github_app->pull_requests = data_get($permissions, 'pull_requests'); $this->github_app->administration = data_get($permissions, 'administration'); $this->github_app->save(); $this->github_app->makeVisible('client_secret')->makeVisible('webhook_secret'); } catch (\Throwable $e) { send_internal_notification('GithubAppPermissionJob failed with: '.$e->getMessage()); throw $e; } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/ServerConnectionCheckJob.php
app/Jobs/ServerConnectionCheckJob.php
<?php namespace App\Jobs; use App\Models\Server; use App\Services\ConfigurationRepository; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\Middleware\WithoutOverlapping; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Log; class ServerConnectionCheckJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $tries = 1; public $timeout = 30; public function __construct( public Server $server, public bool $disableMux = true ) {} public function middleware(): array { return [(new WithoutOverlapping('server-connection-check-'.$this->server->uuid))->expireAfter(45)->dontRelease()]; } private function disableSshMux(): void { $configRepository = app(ConfigurationRepository::class); $configRepository->disableSshMux(); } public function handle() { try { // Check if server is disabled if ($this->server->settings->force_disabled) { $this->server->settings->update([ 'is_reachable' => false, 'is_usable' => false, ]); Log::debug('ServerConnectionCheck: Server is disabled', [ 'server_id' => $this->server->id, 'server_name' => $this->server->name, ]); return; } // Check Hetzner server status if applicable if ($this->server->hetzner_server_id && $this->server->cloudProviderToken) { $this->checkHetznerStatus(); } // Temporarily disable mux if requested if ($this->disableMux) { $this->disableSshMux(); } // Check basic connectivity first $isReachable = $this->checkConnection(); if (! $isReachable) { $this->server->settings->update([ 'is_reachable' => false, 'is_usable' => false, ]); Log::warning('ServerConnectionCheck: Server not reachable', [ 'server_id' => $this->server->id, 'server_name' => $this->server->name, 'server_ip' => $this->server->ip, ]); return; } // Server is reachable, check if Docker is available $isUsable = $this->checkDockerAvailability(); $this->server->settings->update([ 'is_reachable' => true, 'is_usable' => $isUsable, ]); } catch (\Throwable $e) { Log::error('ServerConnectionCheckJob failed', [ 'error' => $e->getMessage(), 'server_id' => $this->server->id, ]); $this->server->settings->update([ 'is_reachable' => false, 'is_usable' => false, ]); throw $e; } } private function checkHetznerStatus(): void { try { $hetznerService = new \App\Services\HetznerService($this->server->cloudProviderToken->token); $serverData = $hetznerService->getServer($this->server->hetzner_server_id); $status = $serverData['status'] ?? null; } catch (\Throwable $e) { Log::debug('ServerConnectionCheck: Hetzner status check failed', [ 'server_id' => $this->server->id, 'error' => $e->getMessage(), ]); } if ($this->server->hetzner_server_status !== $status) { $this->server->update(['hetzner_server_status' => $status]); $this->server->hetzner_server_status = $status; if ($status === 'off') { ray('Server is powered off, marking as unreachable'); throw new \Exception('Server is powered off'); } } } private function checkConnection(): bool { try { // Use instant_remote_process with a simple command // This will automatically handle mux, sudo, IPv6, Cloudflare tunnel, etc. $output = instant_remote_process_with_timeout( ['ls -la /'], $this->server, false // don't throw error ); return $output !== null; } catch (\Throwable $e) { Log::debug('ServerConnectionCheck: Connection check failed', [ 'server_id' => $this->server->id, 'error' => $e->getMessage(), ]); return false; } } private function checkDockerAvailability(): bool { try { // Use instant_remote_process to check Docker // The function will automatically handle sudo for non-root users $output = instant_remote_process_with_timeout( ['docker version --format json'], $this->server, false // don't throw error ); if ($output === null) { return false; } // Try to parse the JSON output to ensure Docker is really working $output = trim($output); if (! empty($output)) { $dockerInfo = json_decode($output, true); return isset($dockerInfo['Server']['Version']); } return false; } catch (\Throwable $e) { Log::debug('ServerConnectionCheck: Docker check failed', [ 'server_id' => $this->server->id, 'error' => $e->getMessage(), ]); return false; } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/UpdateCoolifyJob.php
app/Jobs/UpdateCoolifyJob.php
<?php namespace App\Jobs; use App\Actions\Server\UpdateCoolify; use App\Models\Server; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Log; class UpdateCoolifyJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $timeout = 600; public function __construct() { $this->onQueue('high'); } public function handle(): void { try { CheckForUpdatesJob::dispatchSync(); $settings = instanceSettings(); if (! $settings->new_version_available) { Log::info('No new version available. Skipping update.'); return; } $server = Server::findOrFail(0); if (! $server) { Log::error('Server not found. Cannot proceed with update.'); return; } Log::info('Starting Coolify update process...'); UpdateCoolify::run(false); // false means it's not a manual update $settings->update(['new_version_available' => false]); Log::info('Coolify update completed successfully.'); } catch (\Throwable $e) { Log::error('UpdateCoolifyJob failed: '.$e->getMessage()); // Consider implementing a notification to administrators } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/DeleteResourceJob.php
app/Jobs/DeleteResourceJob.php
<?php namespace App\Jobs; use App\Actions\Application\StopApplication; use App\Actions\Database\StopDatabase; use App\Actions\Server\CleanupDocker; use App\Actions\Service\DeleteService; use App\Actions\Service\StopService; use App\Models\Application; use App\Models\ApplicationPreview; use App\Models\Service; use App\Models\StandaloneClickhouse; use App\Models\StandaloneDragonfly; use App\Models\StandaloneKeydb; use App\Models\StandaloneMariadb; use App\Models\StandaloneMongodb; use App\Models\StandaloneMysql; use App\Models\StandalonePostgresql; use App\Models\StandaloneRedis; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Artisan; class DeleteResourceJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public function __construct( public Application|ApplicationPreview|Service|StandalonePostgresql|StandaloneRedis|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse $resource, public bool $deleteVolumes = true, public bool $deleteConnectedNetworks = true, public bool $deleteConfigurations = true, public bool $dockerCleanup = true ) { $this->onQueue('high'); } public function handle() { try { // Handle ApplicationPreview instances separately if ($this->resource instanceof ApplicationPreview) { $this->deleteApplicationPreview(); return; } switch ($this->resource->type()) { case 'application': StopApplication::run($this->resource, previewDeployments: true, dockerCleanup: $this->dockerCleanup); break; case 'standalone-postgresql': case 'standalone-redis': case 'standalone-mongodb': case 'standalone-mysql': case 'standalone-mariadb': case 'standalone-keydb': case 'standalone-dragonfly': case 'standalone-clickhouse': StopDatabase::run($this->resource, dockerCleanup: $this->dockerCleanup); break; case 'service': StopService::run($this->resource, $this->deleteConnectedNetworks, $this->dockerCleanup); DeleteService::run($this->resource, $this->deleteVolumes, $this->deleteConnectedNetworks, $this->deleteConfigurations, $this->dockerCleanup); return; } if ($this->deleteConfigurations) { $this->resource->deleteConfigurations(); } if ($this->deleteVolumes) { $this->resource->deleteVolumes(); $this->resource->persistentStorages()->delete(); } $this->resource->fileStorages()->delete(); // these are file mounts which should probably have their own flag $isDatabase = $this->resource instanceof StandalonePostgresql || $this->resource instanceof StandaloneRedis || $this->resource instanceof StandaloneMongodb || $this->resource instanceof StandaloneMysql || $this->resource instanceof StandaloneMariadb || $this->resource instanceof StandaloneKeydb || $this->resource instanceof StandaloneDragonfly || $this->resource instanceof StandaloneClickhouse; if ($isDatabase) { $this->resource->sslCertificates()->delete(); $this->resource->scheduledBackups()->delete(); $this->resource->tags()->detach(); } $this->resource->environment_variables()->delete(); if ($this->deleteConnectedNetworks && $this->resource->type() === 'application') { $this->resource->deleteConnectedNetworks(); } } catch (\Throwable $e) { throw $e; } finally { $this->resource->forceDelete(); if ($this->dockerCleanup) { $server = data_get($this->resource, 'server') ?? data_get($this->resource, 'destination.server'); if ($server) { CleanupDocker::dispatch($server, false, false); } } Artisan::queue('cleanup:stucked-resources'); } } private function deleteApplicationPreview() { $application = $this->resource->application; $server = $application->destination->server; $pull_request_id = $this->resource->pull_request_id; // Ensure the preview is soft deleted (may already be done in Livewire component) if (! $this->resource->trashed()) { $this->resource->delete(); } // Cancel any active deployments for this PR (same logic as API cancel_deployment) $activeDeployments = \App\Models\ApplicationDeploymentQueue::where('application_id', $application->id) ->where('pull_request_id', $pull_request_id) ->whereIn('status', [ \App\Enums\ApplicationDeploymentStatus::QUEUED->value, \App\Enums\ApplicationDeploymentStatus::IN_PROGRESS->value, ]) ->get(); foreach ($activeDeployments as $activeDeployment) { try { // Mark deployment as cancelled $activeDeployment->update([ 'status' => \App\Enums\ApplicationDeploymentStatus::CANCELLED_BY_USER->value, ]); // Add cancellation log entry $activeDeployment->addLogEntry('Deployment cancelled: Pull request closed.', 'stderr'); // Check if helper container exists and kill it $deployment_uuid = $activeDeployment->deployment_uuid; $escapedDeploymentUuid = escapeshellarg($deployment_uuid); $checkCommand = "docker ps -a --filter name={$escapedDeploymentUuid} --format '{{.Names}}'"; $containerExists = instant_remote_process([$checkCommand], $server); if ($containerExists && str($containerExists)->trim()->isNotEmpty()) { instant_remote_process(["docker rm -f {$escapedDeploymentUuid}"], $server); $activeDeployment->addLogEntry('Deployment container stopped.'); } else { $activeDeployment->addLogEntry('Helper container not yet started. Deployment will be cancelled when job checks status.'); } } catch (\Throwable $e) { // Silently handle errors during deployment cancellation } } try { if ($server->isSwarm()) { $escapedStackName = escapeshellarg("{$application->uuid}-{$pull_request_id}"); instant_remote_process(["docker stack rm {$escapedStackName}"], $server); } else { $containers = getCurrentApplicationContainerStatus($server, $application->id, $pull_request_id)->toArray(); $this->stopPreviewContainers($containers, $server); } } catch (\Throwable $e) { // Log the error but don't fail the job \Log::warning('Error stopping preview containers for application '.$application->uuid.', PR #'.$pull_request_id.': '.$e->getMessage()); } // Finally, force delete to trigger resource cleanup $this->resource->forceDelete(); } private function stopPreviewContainers(array $containers, $server, int $timeout = 30) { if (empty($containers)) { return; } $containerNames = []; foreach ($containers as $container) { $containerNames[] = str_replace('/', '', $container['Names']); } $containerList = implode(' ', array_map('escapeshellarg', $containerNames)); $commands = [ "docker stop -t $timeout $containerList", "docker rm -f $containerList", ]; instant_remote_process( command: $commands, server: $server, throwError: false ); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/ServerStorageSaveJob.php
app/Jobs/ServerStorageSaveJob.php
<?php namespace App\Jobs; use App\Models\LocalFileVolume; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class ServerStorageSaveJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public function __construct(public LocalFileVolume $localFileVolume) { $this->onQueue('high'); } public function handle() { $this->localFileVolume->saveStorageOnServer(); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/SyncStripeSubscriptionsJob.php
app/Jobs/SyncStripeSubscriptionsJob.php
<?php namespace App\Jobs; use App\Models\Subscription; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class SyncStripeSubscriptionsJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public int $tries = 1; public int $timeout = 1800; // 30 minutes max public function __construct(public bool $fix = false) { $this->onQueue('high'); } public function handle(): array { if (! isCloud() || ! isStripe()) { return ['error' => 'Not running on Cloud or Stripe not configured']; } $subscriptions = Subscription::whereNotNull('stripe_subscription_id') ->where('stripe_invoice_paid', true) ->get(); $stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key')); $discrepancies = []; $errors = []; foreach ($subscriptions as $subscription) { try { $stripeSubscription = $stripe->subscriptions->retrieve( $subscription->stripe_subscription_id ); // Check if Stripe says cancelled but we think it's active if (in_array($stripeSubscription->status, ['canceled', 'incomplete_expired', 'unpaid'])) { $discrepancies[] = [ 'subscription_id' => $subscription->id, 'team_id' => $subscription->team_id, 'stripe_subscription_id' => $subscription->stripe_subscription_id, 'stripe_status' => $stripeSubscription->status, ]; // Only fix if --fix flag is passed if ($this->fix) { $subscription->update([ 'stripe_invoice_paid' => false, 'stripe_past_due' => false, ]); if ($stripeSubscription->status === 'canceled') { $subscription->team?->subscriptionEnded(); } } } // Small delay to avoid Stripe rate limits usleep(100000); // 100ms } catch (\Exception $e) { $errors[] = [ 'subscription_id' => $subscription->id, 'error' => $e->getMessage(), ]; } } // Only notify if discrepancies found and fixed if ($this->fix && count($discrepancies) > 0) { send_internal_notification( 'SyncStripeSubscriptionsJob: Fixed '.count($discrepancies)." discrepancies:\n". json_encode($discrepancies, JSON_PRETTY_PRINT) ); } return [ 'total_checked' => $subscriptions->count(), 'discrepancies' => $discrepancies, 'errors' => $errors, 'fixed' => $this->fix, ]; } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/RestartProxyJob.php
app/Jobs/RestartProxyJob.php
<?php namespace App\Jobs; use App\Actions\Proxy\GetProxyConfiguration; use App\Actions\Proxy\SaveProxyConfiguration; use App\Enums\ProxyTypes; use App\Events\ProxyStatusChangedUI; use App\Models\Server; use App\Services\ProxyDashboardCacheService; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\Middleware\WithoutOverlapping; use Illuminate\Queue\SerializesModels; class RestartProxyJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $tries = 1; public $timeout = 120; public ?int $activity_id = null; public function middleware(): array { return [(new WithoutOverlapping('restart-proxy-'.$this->server->uuid))->expireAfter(120)->dontRelease()]; } public function __construct(public Server $server) {} public function handle() { try { // Set status to restarting $this->server->proxy->status = 'restarting'; $this->server->proxy->force_stop = false; $this->server->save(); // Build combined stop + start commands for a single activity $commands = $this->buildRestartCommands(); // Create activity and dispatch immediately - returns Activity right away // The remote_process runs asynchronously, so UI gets activity ID instantly $activity = remote_process( $commands, $this->server, callEventOnFinish: 'ProxyStatusChanged', callEventData: $this->server->id ); // Store activity ID and notify UI immediately with it $this->activity_id = $activity->id; ProxyStatusChangedUI::dispatch($this->server->team_id, $this->activity_id); } catch (\Throwable $e) { // Set error status $this->server->proxy->status = 'error'; $this->server->save(); // Notify UI of error ProxyStatusChangedUI::dispatch($this->server->team_id); // Clear dashboard cache on error ProxyDashboardCacheService::clearCache($this->server); return handleError($e); } } /** * Build combined stop + start commands for proxy restart. * This creates a single command sequence that shows all logs in one activity. */ private function buildRestartCommands(): array { $proxyType = $this->server->proxyType(); $containerName = $this->server->isSwarm() ? 'coolify-proxy_traefik' : 'coolify-proxy'; $proxy_path = $this->server->proxyPath(); $stopTimeout = 30; // Get proxy configuration $configuration = GetProxyConfiguration::run($this->server); if (! $configuration) { throw new \Exception('Configuration is not synced'); } SaveProxyConfiguration::run($this->server, $configuration); $docker_compose_yml_base64 = base64_encode($configuration); $this->server->proxy->last_applied_settings = str($docker_compose_yml_base64)->pipe('md5')->value(); $this->server->save(); $commands = collect([]); // === STOP PHASE === $commands = $commands->merge([ "echo 'Stopping proxy...'", "docker stop -t=$stopTimeout $containerName 2>/dev/null || true", "docker rm -f $containerName 2>/dev/null || true", '# Wait for container to be fully removed', 'for i in {1..15}; do', " if ! docker ps -a --format \"{{.Names}}\" | grep -q \"^$containerName$\"; then", " echo 'Container removed successfully.'", ' break', ' fi', ' echo "Waiting for container to be removed... ($i/15)"', ' sleep 1', ' # Force remove on each iteration in case it got stuck', " docker rm -f $containerName 2>/dev/null || true", 'done', '# Final verification and force cleanup', "if docker ps -a --format \"{{.Names}}\" | grep -q \"^$containerName$\"; then", " echo 'Container still exists after wait, forcing removal...'", " docker rm -f $containerName 2>/dev/null || true", ' sleep 2', 'fi', "echo 'Proxy stopped successfully.'", ]); // === START PHASE === if ($this->server->isSwarmManager()) { $commands = $commands->merge([ "echo 'Starting proxy (Swarm mode)...'", "mkdir -p $proxy_path/dynamic", "cd $proxy_path", "echo 'Creating required Docker Compose file.'", "echo 'Starting coolify-proxy.'", 'docker stack deploy --detach=true -c docker-compose.yml coolify-proxy', "echo 'Successfully started coolify-proxy.'", ]); } else { if (isDev() && $proxyType === ProxyTypes::CADDY->value) { $proxy_path = '/data/coolify/proxy/caddy'; } $caddyfile = 'import /dynamic/*.caddy'; $commands = $commands->merge([ "echo 'Starting proxy...'", "mkdir -p $proxy_path/dynamic", "cd $proxy_path", "echo '$caddyfile' > $proxy_path/dynamic/Caddyfile", "echo 'Creating required Docker Compose file.'", "echo 'Pulling docker image.'", 'docker compose pull', ]); // Ensure required networks exist BEFORE docker compose up $commands = $commands->merge(ensureProxyNetworksExist($this->server)); $commands = $commands->merge([ "echo 'Starting coolify-proxy.'", 'docker compose up -d --wait --remove-orphans', "echo 'Successfully started coolify-proxy.'", ]); $commands = $commands->merge(connectProxyToNetworks($this->server)); } return $commands->toArray(); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/CheckAndStartSentinelJob.php
app/Jobs/CheckAndStartSentinelJob.php
<?php namespace App\Jobs; use App\Actions\Server\StartSentinel; use App\Models\Server; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class CheckAndStartSentinelJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $timeout = 120; public function __construct(public Server $server) {} public function handle(): void { $latestVersion = get_latest_sentinel_version(); // Check if sentinel is running $sentinelFound = instant_remote_process_with_timeout(['docker inspect coolify-sentinel'], $this->server, false, 10); $sentinelFoundJson = json_decode($sentinelFound, true); $sentinelStatus = data_get($sentinelFoundJson, '0.State.Status', 'exited'); if ($sentinelStatus !== 'running') { StartSentinel::run(server: $this->server, restart: true, latestVersion: $latestVersion); return; } // If sentinel is running, check if it needs an update $runningVersion = instant_remote_process_with_timeout(['docker exec coolify-sentinel sh -c "curl http://127.0.0.1:8888/api/version"'], $this->server, false); if (empty($runningVersion)) { $runningVersion = '0.0.0'; } if ($latestVersion === '0.0.0' && $runningVersion === '0.0.0') { StartSentinel::run(server: $this->server, restart: true, latestVersion: 'latest'); return; } else { if (version_compare($runningVersion, $latestVersion, '<')) { StartSentinel::run(server: $this->server, restart: true, latestVersion: $latestVersion); return; } } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/PullChangelog.php
app/Jobs/PullChangelog.php
<?php namespace App\Jobs; use Carbon\Carbon; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; class PullChangelog implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $timeout = 30; public function __construct() { $this->onQueue('high'); } public function handle(): void { try { // Fetch from CDN instead of GitHub API to avoid rate limits $cdnUrl = config('constants.coolify.releases_url'); $response = Http::retry(3, 1000) ->timeout(30) ->get($cdnUrl); if ($response->successful()) { $releases = $response->json(); // Limit to 10 releases for processing (same as before) $releases = array_slice($releases, 0, 10); $changelog = $this->transformReleasesToChangelog($releases); // Group entries by month and save them $this->saveChangelogEntries($changelog); } else { // Log error instead of sending notification Log::error('PullChangelogFromGitHub: Failed to fetch from CDN', [ 'status' => $response->status(), 'url' => $cdnUrl, ]); } } catch (\Throwable $e) { // Log error instead of sending notification Log::error('PullChangelogFromGitHub: Exception occurred', [ 'message' => $e->getMessage(), 'trace' => $e->getTraceAsString(), ]); } } private function transformReleasesToChangelog(array $releases): array { $entries = []; foreach ($releases as $release) { // Skip drafts and pre-releases if desired if ($release['draft']) { continue; } $publishedAt = Carbon::parse($release['published_at']); $entry = [ 'tag_name' => $release['tag_name'], 'title' => $release['name'] ?: $release['tag_name'], 'content' => $release['body'] ?: 'No release notes available.', 'published_at' => $publishedAt->toISOString(), ]; $entries[] = $entry; } return $entries; } private function saveChangelogEntries(array $entries): void { // Create changelogs directory if it doesn't exist $changelogsDir = base_path('changelogs'); if (! File::exists($changelogsDir)) { File::makeDirectory($changelogsDir, 0755, true); } // Group entries by year-month $groupedEntries = []; foreach ($entries as $entry) { $date = Carbon::parse($entry['published_at']); $monthKey = $date->format('Y-m'); if (! isset($groupedEntries[$monthKey])) { $groupedEntries[$monthKey] = []; } $groupedEntries[$monthKey][] = $entry; } // Save each month's entries to separate files foreach ($groupedEntries as $month => $monthEntries) { // Sort entries by published date (newest first) usort($monthEntries, function ($a, $b) { return Carbon::parse($b['published_at'])->timestamp - Carbon::parse($a['published_at'])->timestamp; }); $monthData = [ 'entries' => $monthEntries, 'last_updated' => now()->toISOString(), ]; $filePath = base_path("changelogs/{$month}.json"); File::put($filePath, json_encode($monthData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/ServerLimitCheckJob.php
app/Jobs/ServerLimitCheckJob.php
<?php namespace App\Jobs; use App\Models\Team; use App\Notifications\Server\ForceDisabled; use App\Notifications\Server\ForceEnabled; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class ServerLimitCheckJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $tries = 4; public function backoff(): int { return isDev() ? 1 : 3; } public function __construct(public Team $team) {} public function handle() { try { $servers = $this->team->servers; $servers_count = $servers->count(); $number_of_servers_to_disable = $servers_count - $this->team->limits; if ($number_of_servers_to_disable > 0) { $servers = $servers->sortbyDesc('created_at'); $servers_to_disable = $servers->take($number_of_servers_to_disable); $servers_to_disable->each(function ($server) { $server->forceDisableServer(); $this->team->notify(new ForceDisabled($server)); }); } elseif ($number_of_servers_to_disable === 0) { $servers->each(function ($server) { if ($server->isForceDisabled()) { $server->forceEnableServer(); $this->team->notify(new ForceEnabled($server)); } }); } } catch (\Throwable $e) { send_internal_notification('ServerLimitCheckJob failed with: '.$e->getMessage()); return handleError($e); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/RegenerateSslCertJob.php
app/Jobs/RegenerateSslCertJob.php
<?php namespace App\Jobs; use App\Helpers\SSLHelper; use App\Models\SslCertificate; use App\Models\Team; use App\Notifications\SslExpirationNotification; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Log; class RegenerateSslCertJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $tries = 3; public $backoff = 60; public function __construct( protected ?Team $team = null, protected ?int $server_id = null, protected bool $force_regeneration = false, ) {} public function handle() { $query = SslCertificate::query(); if ($this->server_id) { $query->where('server_id', $this->server_id); } if (! $this->force_regeneration) { $query->where('valid_until', '<=', now()->addDays(14)); } $query->where('is_ca_certificate', false); $regenerated = collect(); $query->cursor()->each(function ($certificate) use ($regenerated) { try { $caCert = $certificate->server->sslCertificates() ->where('is_ca_certificate', true) ->first(); if (! $caCert) { Log::error("No CA certificate found for server_id: {$certificate->server_id}"); return; } SSLHelper::generateSslCertificate( commonName: $certificate->common_name, subjectAlternativeNames: $certificate->subject_alternative_names, resourceType: $certificate->resource_type, resourceId: $certificate->resource_id, serverId: $certificate->server_id, configurationDir: $certificate->configuration_dir, mountPath: $certificate->mount_path, caCert: $caCert->ssl_certificate, caKey: $caCert->ssl_private_key, ); $regenerated->push($certificate); } catch (\Exception $e) { Log::error('Failed to regenerate SSL certificate: '.$e->getMessage()); } }); if ($regenerated->isNotEmpty()) { $this->team?->notify(new SslExpirationNotification($regenerated)); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/ScheduledJobManager.php
app/Jobs/ScheduledJobManager.php
<?php namespace App\Jobs; use App\Models\ScheduledDatabaseBackup; use App\Models\ScheduledTask; use App\Models\Server; use App\Models\Team; use Cron\CronExpression; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\Middleware\WithoutOverlapping; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Carbon; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; class ScheduledJobManager implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * The time when this job execution started. * Used to ensure all scheduled items are evaluated against the same point in time. */ private ?Carbon $executionTime = null; /** * Create a new job instance. */ public function __construct() { $this->onQueue($this->determineQueue()); } private function determineQueue(): string { $preferredQueue = 'crons'; $fallbackQueue = 'high'; $configuredQueues = explode(',', env('HORIZON_QUEUES', 'high,default')); return in_array($preferredQueue, $configuredQueues) ? $preferredQueue : $fallbackQueue; } /** * Get the middleware the job should pass through. */ public function middleware(): array { return [ (new WithoutOverlapping('scheduled-job-manager')) ->expireAfter(90) // Lock expires after 90s to handle high-load environments with many tasks ->dontRelease(), // Don't re-queue on lock conflict ]; } public function handle(): void { // Freeze the execution time at the start of the job $this->executionTime = Carbon::now(); // Process backups - don't let failures stop task processing try { $this->processScheduledBackups(); } catch (\Exception $e) { Log::channel('scheduled-errors')->error('Failed to process scheduled backups', [ 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString(), ]); } // Process tasks - don't let failures stop the job manager try { $this->processScheduledTasks(); } catch (\Exception $e) { Log::channel('scheduled-errors')->error('Failed to process scheduled tasks', [ 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString(), ]); } // Process Docker cleanups - don't let failures stop the job manager try { $this->processDockerCleanups(); } catch (\Exception $e) { Log::channel('scheduled-errors')->error('Failed to process docker cleanups', [ 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString(), ]); } } private function processScheduledBackups(): void { $backups = ScheduledDatabaseBackup::with(['database']) ->where('enabled', true) ->get(); foreach ($backups as $backup) { try { // Apply the same filtering logic as the original if (! $this->shouldProcessBackup($backup)) { continue; } $server = $backup->server(); $serverTimezone = data_get($server->settings, 'server_timezone', config('app.timezone')); if (validate_timezone($serverTimezone) === false) { $serverTimezone = config('app.timezone'); } $frequency = $backup->frequency; if (isset(VALID_CRON_STRINGS[$frequency])) { $frequency = VALID_CRON_STRINGS[$frequency]; } if ($this->shouldRunNow($frequency, $serverTimezone)) { DatabaseBackupJob::dispatch($backup); } } catch (\Exception $e) { Log::channel('scheduled-errors')->error('Error processing backup', [ 'backup_id' => $backup->id, 'error' => $e->getMessage(), ]); } } } private function processScheduledTasks(): void { $tasks = ScheduledTask::with(['service', 'application']) ->where('enabled', true) ->get(); foreach ($tasks as $task) { try { if (! $this->shouldProcessTask($task)) { continue; } $server = $task->server(); $serverTimezone = data_get($server->settings, 'server_timezone', config('app.timezone')); if (validate_timezone($serverTimezone) === false) { $serverTimezone = config('app.timezone'); } $frequency = $task->frequency; if (isset(VALID_CRON_STRINGS[$frequency])) { $frequency = VALID_CRON_STRINGS[$frequency]; } if ($this->shouldRunNow($frequency, $serverTimezone)) { ScheduledTaskJob::dispatch($task); } } catch (\Exception $e) { Log::channel('scheduled-errors')->error('Error processing task', [ 'task_id' => $task->id, 'error' => $e->getMessage(), ]); } } } private function shouldProcessBackup(ScheduledDatabaseBackup $backup): bool { if (blank(data_get($backup, 'database'))) { $backup->delete(); return false; } $server = $backup->server(); if (blank($server)) { $backup->delete(); return false; } if ($server->isFunctional() === false) { return false; } if (isCloud() && data_get($server->team->subscription, 'stripe_invoice_paid', false) === false && $server->team->id !== 0) { return false; } return true; } private function shouldProcessTask(ScheduledTask $task): bool { $service = $task->service; $application = $task->application; $server = $task->server(); if (blank($server)) { $task->delete(); return false; } if ($server->isFunctional() === false) { return false; } if (isCloud() && data_get($server->team->subscription, 'stripe_invoice_paid', false) === false && $server->team->id !== 0) { return false; } if (! $service && ! $application) { $task->delete(); return false; } if ($application && str($application->status)->contains('running') === false) { return false; } if ($service && str($service->status)->contains('running') === false) { return false; } return true; } private function shouldRunNow(string $frequency, string $timezone): bool { $cron = new CronExpression($frequency); // Use the frozen execution time, not the current time // Fallback to current time if execution time is not set (shouldn't happen) $baseTime = $this->executionTime ?? Carbon::now(); $executionTime = $baseTime->copy()->setTimezone($timezone); return $cron->isDue($executionTime); } private function processDockerCleanups(): void { // Get all servers that need cleanup checks $servers = $this->getServersForCleanup(); foreach ($servers as $server) { try { if (! $this->shouldProcessDockerCleanup($server)) { continue; } $serverTimezone = data_get($server->settings, 'server_timezone', config('app.timezone')); if (validate_timezone($serverTimezone) === false) { $serverTimezone = config('app.timezone'); } $frequency = data_get($server->settings, 'docker_cleanup_frequency', '0 * * * *'); if (isset(VALID_CRON_STRINGS[$frequency])) { $frequency = VALID_CRON_STRINGS[$frequency]; } // Use the frozen execution time for consistent evaluation if ($this->shouldRunNow($frequency, $serverTimezone)) { DockerCleanupJob::dispatch( $server, false, $server->settings->delete_unused_volumes, $server->settings->delete_unused_networks ); } } catch (\Exception $e) { Log::channel('scheduled-errors')->error('Error processing docker cleanup', [ 'server_id' => $server->id, 'server_name' => $server->name, 'error' => $e->getMessage(), ]); } } } private function getServersForCleanup(): Collection { $query = Server::with('settings') ->where('ip', '!=', '1.2.3.4'); if (isCloud()) { $servers = $query->whereRelation('team.subscription', 'stripe_invoice_paid', true)->get(); $own = Team::find(0)->servers()->with('settings')->get(); return $servers->merge($own); } return $query->get(); } private function shouldProcessDockerCleanup(Server $server): bool { if (! $server->isFunctional()) { return false; } // In cloud, check subscription status (except team 0) if (isCloud() && $server->team_id !== 0) { if (data_get($server->team->subscription, 'stripe_invoice_paid', false) === false) { return false; } } return true; } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/CheckTraefikVersionForServerJob.php
app/Jobs/CheckTraefikVersionForServerJob.php
<?php namespace App\Jobs; use App\Events\ProxyStatusChangedUI; use App\Models\Server; use App\Notifications\Server\TraefikVersionOutdated; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class CheckTraefikVersionForServerJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $tries = 3; public $timeout = 60; /** * Create a new job instance. */ public function __construct( public Server $server, public array $traefikVersions ) {} /** * Execute the job. */ public function handle(): void { // Detect current version (makes SSH call) $currentVersion = getTraefikVersionFromDockerCompose($this->server); // Update detected version in database $this->server->update(['detected_traefik_version' => $currentVersion]); if (! $currentVersion) { ProxyStatusChangedUI::dispatch($this->server->team_id); return; } // Check if image tag is 'latest' by inspecting the image (makes SSH call) $imageTag = instant_remote_process([ "docker inspect coolify-proxy --format '{{.Config.Image}}' 2>/dev/null", ], $this->server, false); // Handle empty/null response from SSH command if (empty(trim($imageTag))) { ProxyStatusChangedUI::dispatch($this->server->team_id); return; } if (str_contains(strtolower(trim($imageTag)), ':latest')) { ProxyStatusChangedUI::dispatch($this->server->team_id); return; } // Parse current version to extract major.minor.patch $current = ltrim($currentVersion, 'v'); if (! preg_match('/^(\d+\.\d+)\.(\d+)$/', $current, $matches)) { ProxyStatusChangedUI::dispatch($this->server->team_id); return; } $currentBranch = $matches[1]; // e.g., "3.6" // Find the latest version for this branch $latestForBranch = $this->traefikVersions["v{$currentBranch}"] ?? null; if (! $latestForBranch) { // User is on a branch we don't track - check if newer branches exist $newerBranchInfo = $this->getNewerBranchInfo($currentBranch); if ($newerBranchInfo) { $this->storeOutdatedInfo($current, $newerBranchInfo['latest'], 'minor_upgrade', $newerBranchInfo['target']); } else { // No newer branch found, clear outdated info $this->server->update(['traefik_outdated_info' => null]); } ProxyStatusChangedUI::dispatch($this->server->team_id); return; } // Compare patch version within the same branch $latest = ltrim($latestForBranch, 'v'); // Always check for newer branches first $newerBranchInfo = $this->getNewerBranchInfo($currentBranch); if (version_compare($current, $latest, '<')) { // Patch update available $this->storeOutdatedInfo($current, $latest, 'patch_update', null, $newerBranchInfo); } elseif ($newerBranchInfo) { // Only newer branch available (no patch update) $this->storeOutdatedInfo($current, $newerBranchInfo['latest'], 'minor_upgrade', $newerBranchInfo['target']); } else { // Fully up to date $this->server->update(['traefik_outdated_info' => null]); } // Dispatch UI update event so warning state refreshes in real-time ProxyStatusChangedUI::dispatch($this->server->team_id); } /** * Get information about newer branches if available. */ private function getNewerBranchInfo(string $currentBranch): ?array { $newestBranch = null; $newestVersion = null; foreach ($this->traefikVersions as $branch => $version) { $branchNum = ltrim($branch, 'v'); if (version_compare($branchNum, $currentBranch, '>')) { if (! $newestVersion || version_compare($version, $newestVersion, '>')) { $newestBranch = $branchNum; $newestVersion = $version; } } } if ($newestVersion) { return [ 'target' => "v{$newestBranch}", 'latest' => ltrim($newestVersion, 'v'), ]; } return null; } /** * Store outdated information in database and send immediate notification. */ private function storeOutdatedInfo(string $current, string $latest, string $type, ?string $upgradeTarget = null, ?array $newerBranchInfo = null): void { $outdatedInfo = [ 'current' => $current, 'latest' => $latest, 'type' => $type, 'checked_at' => now()->toIso8601String(), ]; // For minor upgrades, add the upgrade_target field (e.g., "v3.6") if ($type === 'minor_upgrade' && $upgradeTarget) { $outdatedInfo['upgrade_target'] = $upgradeTarget; } // If there's a newer branch available (even for patch updates), include that info if ($newerBranchInfo) { $outdatedInfo['newer_branch_target'] = $newerBranchInfo['target']; $outdatedInfo['newer_branch_latest'] = $newerBranchInfo['latest']; } $this->server->update(['traefik_outdated_info' => $outdatedInfo]); // Send immediate notification to the team $this->sendNotification($outdatedInfo); } /** * Send notification to team about outdated Traefik. */ private function sendNotification(array $outdatedInfo): void { // Attach the outdated info as a dynamic property for the notification $this->server->outdatedInfo = $outdatedInfo; // Get the team and send notification $team = $this->server->team()->first(); if ($team) { $team->notify(new TraefikVersionOutdated(collect([$this->server]))); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/ConnectProxyToNetworksJob.php
app/Jobs/ConnectProxyToNetworksJob.php
<?php namespace App\Jobs; use App\Models\Server; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\Middleware\WithoutOverlapping; use Illuminate\Queue\SerializesModels; use Laravel\Horizon\Contracts\Silenced; /** * Asynchronously connects the coolify-proxy to Docker networks. * * This job is dispatched from PushServerUpdateJob when the proxy is found running * to ensure it's connected to all required networks without blocking the status update. */ class ConnectProxyToNetworksJob implements ShouldBeEncrypted, ShouldQueue, Silenced { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $tries = 1; public $timeout = 60; public function middleware(): array { // Prevent overlapping executions for the same server and throttle to max once per 10 seconds return [ (new WithoutOverlapping('connect-proxy-networks-'.$this->server->uuid)) ->expireAfter(60) ->dontRelease(), ]; } public function __construct(public Server $server) {} public function handle() { if (! $this->server->isFunctional()) { return; } $connectProxyToDockerNetworks = connectProxyToNetworks($this->server); if (empty($connectProxyToDockerNetworks)) { return; } instant_remote_process($connectProxyToDockerNetworks, $this->server, false); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/DockerCleanupJob.php
app/Jobs/DockerCleanupJob.php
<?php namespace App\Jobs; use App\Actions\Server\CleanupDocker; use App\Events\DockerCleanupDone; use App\Models\DockerCleanupExecution; use App\Models\Server; use App\Notifications\Server\DockerCleanupFailed; use App\Notifications\Server\DockerCleanupSuccess; use Carbon\Carbon; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\Middleware\WithoutOverlapping; use Illuminate\Queue\SerializesModels; class DockerCleanupJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $timeout = 600; public $tries = 1; public ?string $usageBefore = null; public ?DockerCleanupExecution $execution_log = null; public function middleware(): array { return [(new WithoutOverlapping('docker-cleanup-'.$this->server->uuid))->expireAfter(600)->dontRelease()]; } public function __construct( public Server $server, public bool $manualCleanup = false, public bool $deleteUnusedVolumes = false, public bool $deleteUnusedNetworks = false ) {} public function handle(): void { try { if (! $this->server->isFunctional()) { return; } $this->execution_log = DockerCleanupExecution::create([ 'server_id' => $this->server->id, ]); $this->usageBefore = $this->server->getDiskUsage(); if ($this->manualCleanup || $this->server->settings->force_docker_cleanup) { $cleanup_log = CleanupDocker::run( server: $this->server, deleteUnusedVolumes: $this->deleteUnusedVolumes, deleteUnusedNetworks: $this->deleteUnusedNetworks ); $usageAfter = $this->server->getDiskUsage(); $message = ($this->manualCleanup ? 'Manual' : 'Forced').' Docker cleanup job executed successfully. Disk usage before: '.$this->usageBefore.'%, Disk usage after: '.$usageAfter.'%.'; $this->execution_log->update([ 'status' => 'success', 'message' => $message, 'cleanup_log' => $cleanup_log, ]); $this->server->team?->notify(new DockerCleanupSuccess($this->server, $message)); event(new DockerCleanupDone($this->execution_log)); return; } if (str($this->usageBefore)->isEmpty() || $this->usageBefore === null || $this->usageBefore === 0) { $cleanup_log = CleanupDocker::run( server: $this->server, deleteUnusedVolumes: $this->deleteUnusedVolumes, deleteUnusedNetworks: $this->deleteUnusedNetworks ); $message = 'Docker cleanup job executed successfully, but no disk usage could be determined.'; $this->execution_log->update([ 'status' => 'success', 'message' => $message, 'cleanup_log' => $cleanup_log, ]); $this->server->team?->notify(new DockerCleanupSuccess($this->server, $message)); event(new DockerCleanupDone($this->execution_log)); } if ($this->usageBefore >= $this->server->settings->docker_cleanup_threshold) { $cleanup_log = CleanupDocker::run( server: $this->server, deleteUnusedVolumes: $this->deleteUnusedVolumes, deleteUnusedNetworks: $this->deleteUnusedNetworks ); $usageAfter = $this->server->getDiskUsage(); $diskSaved = $this->usageBefore - $usageAfter; if ($diskSaved > 0) { $message = 'Saved '.$diskSaved.'% disk space. Disk usage before: '.$this->usageBefore.'%, Disk usage after: '.$usageAfter.'%.'; } else { $message = 'Docker cleanup job executed successfully, but no disk space was saved. Disk usage before: '.$this->usageBefore.'%, Disk usage after: '.$usageAfter.'%.'; } $this->execution_log->update([ 'status' => 'success', 'message' => $message, 'cleanup_log' => $cleanup_log, ]); $this->server->team?->notify(new DockerCleanupSuccess($this->server, $message)); event(new DockerCleanupDone($this->execution_log)); } else { $message = 'No cleanup needed for '.$this->server->name; $this->execution_log->update([ 'status' => 'success', 'message' => $message, ]); $this->server->team?->notify(new DockerCleanupSuccess($this->server, $message)); event(new DockerCleanupDone($this->execution_log)); } } catch (\Throwable $e) { if ($this->execution_log) { $this->execution_log->update([ 'status' => 'failed', 'message' => $e->getMessage(), ]); event(new DockerCleanupDone($this->execution_log)); } $this->server->team?->notify(new DockerCleanupFailed($this->server, 'Docker cleanup job failed with the following error: '.$e->getMessage())); throw $e; } finally { if ($this->execution_log) { $this->execution_log->update([ 'finished_at' => Carbon::now()->toImmutable(), ]); } } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/SendMessageToTelegramJob.php
app/Jobs/SendMessageToTelegramJob.php
<?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Http; use Illuminate\Support\Str; class SendMessageToTelegramJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * The number of times the job may be attempted. * * @var int */ public $tries = 5; /** * The maximum number of unhandled exceptions to allow before failing. */ public int $maxExceptions = 3; public function __construct( public string $text, public array $buttons, public string $token, public string $chatId, public ?string $threadId = null, ) { $this->onQueue('high'); } /** * Execute the job. */ public function handle(): void { $url = 'https://api.telegram.org/bot'.$this->token.'/sendMessage'; $inlineButtons = []; if (! empty($this->buttons)) { foreach ($this->buttons as $button) { $buttonUrl = data_get($button, 'url'); $text = data_get($button, 'text', 'Click here'); if ($buttonUrl && Str::contains($buttonUrl, 'http://localhost')) { $buttonUrl = str_replace('http://localhost', config('app.url'), $buttonUrl); } $inlineButtons[] = [ 'text' => $text, 'url' => $buttonUrl, ]; } } $payload = [ // 'parse_mode' => 'markdown', 'reply_markup' => json_encode([ 'inline_keyboard' => [ [...$inlineButtons], ], ]), 'chat_id' => $this->chatId, 'text' => $this->text, ]; if ($this->threadId) { $payload['message_thread_id'] = $this->threadId; } $response = Http::post($url, $payload); if ($response->failed()) { throw new \RuntimeException('Telegram notification failed with '.$response->status().' status code.'.$response->body()); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/StripeProcessJob.php
app/Jobs/StripeProcessJob.php
<?php namespace App\Jobs; use App\Models\Subscription; use App\Models\Team; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; use Illuminate\Support\Str; class StripeProcessJob implements ShouldQueue { use Queueable; public $type; public $webhook; public $tries = 3; public function __construct(public $event) { $this->onQueue('high'); } public function handle(): void { try { $excludedPlans = config('subscription.stripe_excluded_plans'); $type = data_get($this->event, 'type'); $this->type = $type; $data = data_get($this->event, 'data.object'); switch ($type) { case 'radar.early_fraud_warning.created': $stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key')); $id = data_get($data, 'id'); $charge = data_get($data, 'charge'); if ($charge) { $stripe->refunds->create(['charge' => $charge]); } $pi = data_get($data, 'payment_intent'); $piData = $stripe->paymentIntents->retrieve($pi, []); $customerId = data_get($piData, 'customer'); $subscription = Subscription::where('stripe_customer_id', $customerId)->first(); if ($subscription) { $subscriptionId = data_get($subscription, 'stripe_subscription_id'); $stripe->subscriptions->cancel($subscriptionId, []); $subscription->update([ 'stripe_invoice_paid' => false, ]); send_internal_notification("Early fraud warning created Refunded, subscription canceled. Charge: {$charge}, id: {$id}, pi: {$pi}"); } else { send_internal_notification("Early fraud warning: subscription not found. Charge: {$charge}, id: {$id}, pi: {$pi}"); throw new \RuntimeException("Early fraud warning: subscription not found. Charge: {$charge}, id: {$id}, pi: {$pi}"); } break; case 'checkout.session.completed': $clientReferenceId = data_get($data, 'client_reference_id'); if (is_null($clientReferenceId)) { // send_internal_notification('Checkout session completed without client reference id.'); break; } $userId = Str::before($clientReferenceId, ':'); $teamId = Str::after($clientReferenceId, ':'); $subscriptionId = data_get($data, 'subscription'); $customerId = data_get($data, 'customer'); $team = Team::find($teamId); $found = $team->members->where('id', $userId)->first(); if (! $found->isAdmin()) { // send_internal_notification("User {$userId} is not an admin or owner of team {$team->id}, customerid: {$customerId}, subscriptionid: {$subscriptionId}."); throw new \RuntimeException("User {$userId} is not an admin or owner of team {$team->id}, customerid: {$customerId}, subscriptionid: {$subscriptionId}."); } $subscription = Subscription::where('team_id', $teamId)->first(); if ($subscription) { // send_internal_notification('Old subscription activated for team: '.$teamId); $subscription->update([ 'stripe_subscription_id' => $subscriptionId, 'stripe_customer_id' => $customerId, 'stripe_invoice_paid' => true, 'stripe_past_due' => false, ]); } else { // send_internal_notification('New subscription for team: '.$teamId); Subscription::create([ 'team_id' => $teamId, 'stripe_subscription_id' => $subscriptionId, 'stripe_customer_id' => $customerId, 'stripe_invoice_paid' => true, 'stripe_past_due' => false, ]); } break; case 'invoice.paid': $customerId = data_get($data, 'customer'); $invoiceAmount = data_get($data, 'amount_paid', 0); $subscriptionId = data_get($data, 'subscription'); $planId = data_get($data, 'lines.data.0.plan.id'); if (Str::contains($excludedPlans, $planId)) { // send_internal_notification('Subscription excluded.'); break; } $subscription = Subscription::where('stripe_customer_id', $customerId)->first(); if (! $subscription) { throw new \RuntimeException("No subscription found for customer: {$customerId}"); } if ($subscription->stripe_subscription_id) { try { $stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key')); $stripeSubscription = $stripe->subscriptions->retrieve( $subscription->stripe_subscription_id ); switch ($stripeSubscription->status) { case 'active': $subscription->update([ 'stripe_invoice_paid' => true, 'stripe_past_due' => false, ]); break; case 'past_due': $subscription->update([ 'stripe_invoice_paid' => true, 'stripe_past_due' => true, ]); break; case 'canceled': case 'incomplete_expired': case 'unpaid': send_internal_notification( "Invoice paid for {$stripeSubscription->status} subscription. ". "Customer: {$customerId}, Amount: \${$invoiceAmount}" ); break; default: VerifyStripeSubscriptionStatusJob::dispatch($subscription) ->delay(now()->addSeconds(20)); break; } } catch (\Exception $e) { VerifyStripeSubscriptionStatusJob::dispatch($subscription) ->delay(now()->addSeconds(20)); send_internal_notification( 'Failed to verify subscription status in invoice.paid: '.$e->getMessage() ); } } else { VerifyStripeSubscriptionStatusJob::dispatch($subscription) ->delay(now()->addSeconds(20)); } break; case 'invoice.payment_failed': $customerId = data_get($data, 'customer'); $invoiceId = data_get($data, 'id'); $paymentIntentId = data_get($data, 'payment_intent'); $subscription = Subscription::where('stripe_customer_id', $customerId)->first(); if (! $subscription) { // send_internal_notification('invoice.payment_failed failed but no subscription found in Coolify for customer: '.$customerId); throw new \RuntimeException("No subscription found for customer: {$customerId}"); } $team = data_get($subscription, 'team'); if (! $team) { // send_internal_notification('invoice.payment_failed failed but no team found in Coolify for customer: '.$customerId); throw new \RuntimeException("No team found in Coolify for customer: {$customerId}"); } // Verify payment status with Stripe API before sending failure notification if ($paymentIntentId) { try { $stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key')); $paymentIntent = $stripe->paymentIntents->retrieve($paymentIntentId); if (in_array($paymentIntent->status, ['processing', 'succeeded', 'requires_action', 'requires_confirmation'])) { break; } if (! $subscription->stripe_invoice_paid && $subscription->created_at->diffInMinutes(now()) < 5) { SubscriptionInvoiceFailedJob::dispatch($team)->delay(now()->addSeconds(60)); break; } } catch (\Exception $e) { } } if (! $subscription->stripe_invoice_paid) { SubscriptionInvoiceFailedJob::dispatch($team); // send_internal_notification('Invoice payment failed: '.$customerId); } break; case 'payment_intent.payment_failed': $customerId = data_get($data, 'customer'); $subscription = Subscription::where('stripe_customer_id', $customerId)->first(); if (! $subscription) { // send_internal_notification('payment_intent.payment_failed, no subscription found in Coolify for customer: '.$customerId); throw new \RuntimeException("No subscription found in Coolify for customer: {$customerId}"); } if ($subscription->stripe_invoice_paid) { // send_internal_notification('payment_intent.payment_failed but invoice is active for customer: '.$customerId); return; } // send_internal_notification('Subscription payment failed for customer: '.$customerId); break; case 'customer.subscription.created': $customerId = data_get($data, 'customer'); $subscriptionId = data_get($data, 'id'); $teamId = data_get($data, 'metadata.team_id'); $userId = data_get($data, 'metadata.user_id'); if (! $teamId || ! $userId) { $subscription = Subscription::where('stripe_customer_id', $customerId)->first(); if ($subscription) { throw new \RuntimeException("Subscription already exists for customer: {$customerId}"); } throw new \RuntimeException('No team id or user id found'); } $team = Team::find($teamId); $found = $team->members->where('id', $userId)->first(); if (! $found->isAdmin()) { // send_internal_notification("User {$userId} is not an admin or owner of team {$team->id}, customerid: {$customerId}."); throw new \RuntimeException("User {$userId} is not an admin or owner of team {$team->id}, customerid: {$customerId}."); } $subscription = Subscription::where('team_id', $teamId)->first(); if ($subscription) { // send_internal_notification("Subscription already exists for team: {$teamId}"); throw new \RuntimeException("Subscription already exists for team: {$teamId}"); } else { Subscription::create([ 'team_id' => $teamId, 'stripe_subscription_id' => $subscriptionId, 'stripe_customer_id' => $customerId, 'stripe_invoice_paid' => false, ]); } case 'customer.subscription.updated': $teamId = data_get($data, 'metadata.team_id'); $userId = data_get($data, 'metadata.user_id'); $customerId = data_get($data, 'customer'); $status = data_get($data, 'status'); $subscriptionId = data_get($data, 'items.data.0.subscription') ?? data_get($data, 'id'); $planId = data_get($data, 'items.data.0.plan.id') ?? data_get($data, 'plan.id'); if (Str::contains($excludedPlans, $planId)) { // send_internal_notification('Subscription excluded.'); break; } $subscription = Subscription::where('stripe_customer_id', $customerId)->first(); if (! $subscription) { if ($status === 'incomplete_expired') { // send_internal_notification('Subscription incomplete expired'); throw new \RuntimeException('Subscription incomplete expired'); } if ($teamId) { $subscription = Subscription::create([ 'team_id' => $teamId, 'stripe_subscription_id' => $subscriptionId, 'stripe_customer_id' => $customerId, 'stripe_invoice_paid' => false, ]); } else { // send_internal_notification('No subscription and team id found'); throw new \RuntimeException('No subscription and team id found'); } } $cancelAtPeriodEnd = data_get($data, 'cancel_at_period_end'); $feedback = data_get($data, 'cancellation_details.feedback'); $comment = data_get($data, 'cancellation_details.comment'); $lookup_key = data_get($data, 'items.data.0.price.lookup_key'); if (str($lookup_key)->contains('dynamic')) { $quantity = data_get($data, 'items.data.0.quantity', 2); $team = data_get($subscription, 'team'); if ($team) { $team->update([ 'custom_server_limit' => $quantity, ]); } ServerLimitCheckJob::dispatch($team); } $subscription->update([ 'stripe_feedback' => $feedback, 'stripe_comment' => $comment, 'stripe_plan_id' => $planId, 'stripe_cancel_at_period_end' => $cancelAtPeriodEnd, ]); if ($status === 'paused' || $status === 'incomplete_expired') { if ($subscription->stripe_subscription_id === $subscriptionId) { $subscription->update([ 'stripe_invoice_paid' => false, ]); } } if ($status === 'past_due') { if ($subscription->stripe_subscription_id === $subscriptionId) { $subscription->update([ 'stripe_past_due' => true, ]); // send_internal_notification('Past Due: '.$customerId.'Subscription ID: '.$subscriptionId); } } if ($status === 'unpaid') { if ($subscription->stripe_subscription_id === $subscriptionId) { $subscription->update([ 'stripe_invoice_paid' => false, ]); // send_internal_notification('Unpaid: '.$customerId.'Subscription ID: '.$subscriptionId); } $team = data_get($subscription, 'team'); if ($team) { $team->subscriptionEnded(); } else { // send_internal_notification('Subscription unpaid but no team found in Coolify for customer: '.$customerId); throw new \RuntimeException("No team found in Coolify for customer: {$customerId}"); } } if ($status === 'active') { if ($subscription->stripe_subscription_id === $subscriptionId) { $subscription->update([ 'stripe_past_due' => false, 'stripe_invoice_paid' => true, ]); } } if ($feedback) { $reason = "Cancellation feedback for {$customerId}: '".$feedback."'"; if ($comment) { $reason .= ' with comment: \''.$comment."'"; } } break; case 'customer.subscription.deleted': $customerId = data_get($data, 'customer'); $subscriptionId = data_get($data, 'id'); $subscription = Subscription::where('stripe_customer_id', $customerId)->where('stripe_subscription_id', $subscriptionId)->first(); if ($subscription) { $team = data_get($subscription, 'team'); if ($team) { $team->subscriptionEnded(); } else { // send_internal_notification('Subscription deleted but no team found in Coolify for customer: '.$customerId); throw new \RuntimeException("No team found in Coolify for customer: {$customerId}"); } } else { // send_internal_notification('Subscription deleted but no subscription found in Coolify for customer: '.$customerId); throw new \RuntimeException("No subscription found in Coolify for customer: {$customerId}"); } break; default: throw new \RuntimeException("Unhandled event type: {$type}"); } } catch (\Exception $e) { send_internal_notification('StripeProcessJob error: '.$e->getMessage()); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/CleanupInstanceStuffsJob.php
app/Jobs/CleanupInstanceStuffsJob.php
<?php namespace App\Jobs; use App\Models\TeamInvitation; use App\Models\User; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\Middleware\WithoutOverlapping; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Log; class CleanupInstanceStuffsJob implements ShouldBeEncrypted, ShouldBeUnique, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $timeout = 60; public function __construct() {} public function middleware(): array { return [(new WithoutOverlapping('cleanup-instance-stuffs'))->expireAfter(60)->dontRelease()]; } public function handle(): void { try { $this->cleanupInvitationLink(); $this->cleanupExpiredEmailChangeRequests(); } catch (\Throwable $e) { Log::error('CleanupInstanceStuffsJob failed with error: '.$e->getMessage()); } } private function cleanupInvitationLink() { $invitation = TeamInvitation::all(); foreach ($invitation as $item) { $item->isValid(); } } private function cleanupExpiredEmailChangeRequests() { User::whereNotNull('email_change_code_expires_at') ->where('email_change_code_expires_at', '<', now()) ->update([ 'pending_email' => null, 'email_change_code' => null, 'email_change_code_expires_at' => null, ]); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/SubscriptionInvoiceFailedJob.php
app/Jobs/SubscriptionInvoiceFailedJob.php
<?php namespace App\Jobs; use App\Models\Team; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class SubscriptionInvoiceFailedJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public function __construct(protected Team $team) { $this->onQueue('high'); } public function handle() { try { // Double-check subscription status before sending failure notification $subscription = $this->team->subscription; if ($subscription && $subscription->stripe_customer_id) { try { $stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key')); if ($subscription->stripe_subscription_id) { $stripeSubscription = $stripe->subscriptions->retrieve($subscription->stripe_subscription_id); if (in_array($stripeSubscription->status, ['active', 'trialing'])) { if (! $subscription->stripe_invoice_paid) { $subscription->update([ 'stripe_invoice_paid' => true, 'stripe_past_due' => false, ]); } return; } } $invoices = $stripe->invoices->all([ 'customer' => $subscription->stripe_customer_id, 'limit' => 3, ]); foreach ($invoices->data as $invoice) { if ($invoice->paid && $invoice->created > (time() - 3600)) { $subscription->update([ 'stripe_invoice_paid' => true, 'stripe_past_due' => false, ]); return; } } } catch (\Exception $e) { } } // If we reach here, payment genuinely failed $session = getStripeCustomerPortalSession($this->team); $mail = new MailMessage; $mail->view('emails.subscription-invoice-failed', [ 'stripeCustomerPortal' => $session->url, ]); $mail->subject('Your last payment was failed for Coolify Cloud.'); $this->team->members()->each(function ($member) use ($mail) { if ($member->isAdmin()) { send_user_an_email($mail, $member->email); } }); } catch (\Throwable $e) { send_internal_notification('SubscriptionInvoiceFailedJob failed with: '.$e->getMessage()); throw $e; } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/UpdateStripeCustomerEmailJob.php
app/Jobs/UpdateStripeCustomerEmailJob.php
<?php namespace App\Jobs; use App\Models\Team; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Log; use Stripe\Stripe; class UpdateStripeCustomerEmailJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $tries = 3; public $backoff = [10, 30, 60]; public function __construct( private Team $team, private int $userId, private string $newEmail, private string $oldEmail ) { $this->onQueue('high'); } public function handle(): void { try { if (! isCloud() || ! $this->team->subscription) { Log::info('Skipping Stripe email update - not cloud or no subscription', [ 'team_id' => $this->team->id, 'user_id' => $this->userId, ]); return; } // Check if the user changing email is a team owner $isOwner = $this->team->members() ->wherePivot('role', 'owner') ->where('users.id', $this->userId) ->exists(); if (! $isOwner) { Log::info('Skipping Stripe email update - user is not team owner', [ 'team_id' => $this->team->id, 'user_id' => $this->userId, ]); return; } // Get current Stripe customer email to verify it matches the user's old email $stripe_customer_id = data_get($this->team, 'subscription.stripe_customer_id'); if (! $stripe_customer_id) { Log::info('Skipping Stripe email update - no Stripe customer ID', [ 'team_id' => $this->team->id, 'user_id' => $this->userId, ]); return; } Stripe::setApiKey(config('subscription.stripe_api_key')); try { $stripeCustomer = \Stripe\Customer::retrieve($stripe_customer_id); $currentStripeEmail = $stripeCustomer->email; // Only update if the current Stripe email matches the user's old email if (strtolower($currentStripeEmail) !== strtolower($this->oldEmail)) { Log::info('Skipping Stripe email update - Stripe customer email does not match user old email', [ 'team_id' => $this->team->id, 'user_id' => $this->userId, 'stripe_email' => $currentStripeEmail, 'user_old_email' => $this->oldEmail, ]); return; } // Update Stripe customer email \Stripe\Customer::update($stripe_customer_id, ['email' => $this->newEmail]); } catch (\Exception $e) { Log::error('Failed to retrieve or update Stripe customer', [ 'team_id' => $this->team->id, 'user_id' => $this->userId, 'stripe_customer_id' => $stripe_customer_id, 'error' => $e->getMessage(), ]); throw $e; } Log::info('Successfully updated Stripe customer email', [ 'team_id' => $this->team->id, 'user_id' => $this->userId, 'old_email' => $this->oldEmail, 'new_email' => $this->newEmail, ]); } catch (\Exception $e) { Log::error('Failed to update Stripe customer email', [ 'team_id' => $this->team->id, 'user_id' => $this->userId, 'old_email' => $this->oldEmail, 'new_email' => $this->newEmail, 'error' => $e->getMessage(), 'attempt' => $this->attempts(), ]); // Re-throw to trigger retry throw $e; } } public function failed(\Throwable $exception): void { Log::error('Permanently failed to update Stripe customer email after all retries', [ 'team_id' => $this->team->id, 'user_id' => $this->userId, 'old_email' => $this->oldEmail, 'new_email' => $this->newEmail, 'error' => $exception->getMessage(), ]); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/SendWebhookJob.php
app/Jobs/SendWebhookJob.php
<?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Http; class SendWebhookJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * The number of times the job may be attempted. * * @var int */ public $tries = 5; public $backoff = 10; /** * The maximum number of unhandled exceptions to allow before failing. */ public int $maxExceptions = 5; public function __construct( public array $payload, public string $webhookUrl ) { $this->onQueue('high'); } /** * Execute the job. */ public function handle(): void { if (isDev()) { ray('Sending webhook notification', [ 'url' => $this->webhookUrl, 'payload' => $this->payload, ]); } $response = Http::post($this->webhookUrl, $this->payload); if (isDev()) { ray('Webhook response', [ 'status' => $response->status(), 'body' => $response->body(), 'successful' => $response->successful(), ]); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/DatabaseBackupJob.php
app/Jobs/DatabaseBackupJob.php
<?php namespace App\Jobs; use App\Events\BackupCreated; use App\Models\S3Storage; use App\Models\ScheduledDatabaseBackup; use App\Models\ScheduledDatabaseBackupExecution; use App\Models\Server; use App\Models\ServiceDatabase; use App\Models\StandaloneMariadb; use App\Models\StandaloneMongodb; use App\Models\StandaloneMysql; use App\Models\StandalonePostgresql; use App\Models\Team; use App\Notifications\Database\BackupFailed; use App\Notifications\Database\BackupSuccess; use App\Notifications\Database\BackupSuccessWithS3Warning; use Carbon\Carbon; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Log; use Illuminate\Support\Str; use Throwable; use Visus\Cuid2\Cuid2; class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $maxExceptions = 1; public ?Team $team = null; public Server $server; public StandalonePostgresql|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|ServiceDatabase $database; public ?string $container_name = null; public ?string $directory_name = null; public ?ScheduledDatabaseBackupExecution $backup_log = null; public string $backup_status = 'failed'; public ?string $backup_location = null; public string $backup_dir; public string $backup_file; public int $size = 0; public ?string $backup_output = null; public ?string $error_output = null; public bool $s3_uploaded = false; public ?string $postgres_password = null; public ?string $mongo_root_username = null; public ?string $mongo_root_password = null; public ?S3Storage $s3 = null; public $timeout = 3600; public ?string $backup_log_uuid = null; public function __construct(public ScheduledDatabaseBackup $backup) { $this->onQueue('high'); $this->timeout = $backup->timeout ?? 3600; } public function handle(): void { try { $databasesToBackup = null; $this->team = Team::find($this->backup->team_id); if (! $this->team) { $this->backup->delete(); return; } if (data_get($this->backup, 'database_type') === \App\Models\ServiceDatabase::class) { $this->database = data_get($this->backup, 'database'); $this->server = $this->database->service->server; $this->s3 = $this->backup->s3; } else { $this->database = data_get($this->backup, 'database'); $this->server = $this->database->destination->server; $this->s3 = $this->backup->s3; } if (is_null($this->server)) { throw new \Exception('Server not found?!'); } if (is_null($this->database)) { throw new \Exception('Database not found?!'); } BackupCreated::dispatch($this->team->id); $status = str(data_get($this->database, 'status')); if (! $status->startsWith('running') && $this->database->id !== 0) { return; } if (data_get($this->backup, 'database_type') === \App\Models\ServiceDatabase::class) { $databaseType = $this->database->databaseType(); $serviceUuid = $this->database->service->uuid; $serviceName = str($this->database->service->name)->slug(); if (str($databaseType)->contains('postgres')) { $this->container_name = "{$this->database->name}-$serviceUuid"; $this->directory_name = $serviceName.'-'.$this->container_name; $commands[] = "docker exec $this->container_name env | grep POSTGRES_"; $envs = instant_remote_process($commands, $this->server, true, false, null, disableMultiplexing: true); $envs = str($envs)->explode("\n"); $user = $envs->filter(function ($env) { return str($env)->startsWith('POSTGRES_USER='); })->first(); if ($user) { $this->database->postgres_user = str($user)->after('POSTGRES_USER=')->value(); } else { $this->database->postgres_user = 'postgres'; } $db = $envs->filter(function ($env) { return str($env)->startsWith('POSTGRES_DB='); })->first(); if ($db) { $databasesToBackup = str($db)->after('POSTGRES_DB=')->value(); } else { $databasesToBackup = $this->database->postgres_user; } $this->postgres_password = $envs->filter(function ($env) { return str($env)->startsWith('POSTGRES_PASSWORD='); })->first(); if ($this->postgres_password) { $this->postgres_password = str($this->postgres_password)->after('POSTGRES_PASSWORD=')->value(); } } elseif (str($databaseType)->contains('mysql')) { $this->container_name = "{$this->database->name}-$serviceUuid"; $this->directory_name = $serviceName.'-'.$this->container_name; $commands[] = "docker exec $this->container_name env | grep MYSQL_"; $envs = instant_remote_process($commands, $this->server, true, false, null, disableMultiplexing: true); $envs = str($envs)->explode("\n"); $rootPassword = $envs->filter(function ($env) { return str($env)->startsWith('MYSQL_ROOT_PASSWORD='); })->first(); if ($rootPassword) { $this->database->mysql_root_password = str($rootPassword)->after('MYSQL_ROOT_PASSWORD=')->value(); } $db = $envs->filter(function ($env) { return str($env)->startsWith('MYSQL_DATABASE='); })->first(); if ($db) { $databasesToBackup = str($db)->after('MYSQL_DATABASE=')->value(); } else { throw new \Exception('MYSQL_DATABASE not found'); } } elseif (str($databaseType)->contains('mariadb')) { $this->container_name = "{$this->database->name}-$serviceUuid"; $this->directory_name = $serviceName.'-'.$this->container_name; $commands[] = "docker exec $this->container_name env"; $envs = instant_remote_process($commands, $this->server, true, false, null, disableMultiplexing: true); $envs = str($envs)->explode("\n"); $rootPassword = $envs->filter(function ($env) { return str($env)->startsWith('MARIADB_ROOT_PASSWORD='); })->first(); if ($rootPassword) { $this->database->mariadb_root_password = str($rootPassword)->after('MARIADB_ROOT_PASSWORD=')->value(); } else { $rootPassword = $envs->filter(function ($env) { return str($env)->startsWith('MYSQL_ROOT_PASSWORD='); })->first(); if ($rootPassword) { $this->database->mariadb_root_password = str($rootPassword)->after('MYSQL_ROOT_PASSWORD=')->value(); } } $db = $envs->filter(function ($env) { return str($env)->startsWith('MARIADB_DATABASE='); })->first(); if ($db) { $databasesToBackup = str($db)->after('MARIADB_DATABASE=')->value(); } else { $db = $envs->filter(function ($env) { return str($env)->startsWith('MYSQL_DATABASE='); })->first(); if ($db) { $databasesToBackup = str($db)->after('MYSQL_DATABASE=')->value(); } else { throw new \Exception('MARIADB_DATABASE or MYSQL_DATABASE not found'); } } } elseif (str($databaseType)->contains('mongo')) { $databasesToBackup = ['*']; $this->container_name = "{$this->database->name}-$serviceUuid"; $this->directory_name = $serviceName.'-'.$this->container_name; // Try to extract MongoDB credentials from environment variables try { $commands = []; $commands[] = "docker exec $this->container_name env | grep MONGO_INITDB_"; $envs = instant_remote_process($commands, $this->server, true, false, null, disableMultiplexing: true); if (filled($envs)) { $envs = str($envs)->explode("\n"); $rootPassword = $envs->filter(function ($env) { return str($env)->startsWith('MONGO_INITDB_ROOT_PASSWORD='); })->first(); if ($rootPassword) { $this->mongo_root_password = str($rootPassword)->after('MONGO_INITDB_ROOT_PASSWORD=')->value(); } $rootUsername = $envs->filter(function ($env) { return str($env)->startsWith('MONGO_INITDB_ROOT_USERNAME='); })->first(); if ($rootUsername) { $this->mongo_root_username = str($rootUsername)->after('MONGO_INITDB_ROOT_USERNAME=')->value(); } } } catch (\Throwable $e) { // Continue without env vars - will be handled in backup_standalone_mongodb method } } } else { $databaseName = str($this->database->name)->slug()->value(); $this->container_name = $this->database->uuid; $this->directory_name = $databaseName.'-'.$this->container_name; $databaseType = $this->database->type(); $databasesToBackup = data_get($this->backup, 'databases_to_backup'); } if (blank($databasesToBackup)) { if (str($databaseType)->contains('postgres')) { $databasesToBackup = [$this->database->postgres_db]; } elseif (str($databaseType)->contains('mongo')) { $databasesToBackup = ['*']; } elseif (str($databaseType)->contains('mysql')) { $databasesToBackup = [$this->database->mysql_database]; } elseif (str($databaseType)->contains('mariadb')) { $databasesToBackup = [$this->database->mariadb_database]; } else { return; } } else { if (str($databaseType)->contains('postgres')) { // Format: db1,db2,db3 $databasesToBackup = explode(',', $databasesToBackup); $databasesToBackup = array_map('trim', $databasesToBackup); } elseif (str($databaseType)->contains('mongo')) { // Format: db1:collection1,collection2|db2:collection3,collection4 // Only explode if it's a string, not if it's already an array if (is_string($databasesToBackup)) { $databasesToBackup = explode('|', $databasesToBackup); $databasesToBackup = array_map('trim', $databasesToBackup); } } elseif (str($databaseType)->contains('mysql')) { // Format: db1,db2,db3 $databasesToBackup = explode(',', $databasesToBackup); $databasesToBackup = array_map('trim', $databasesToBackup); } elseif (str($databaseType)->contains('mariadb')) { // Format: db1,db2,db3 $databasesToBackup = explode(',', $databasesToBackup); $databasesToBackup = array_map('trim', $databasesToBackup); } else { return; } } $this->backup_dir = backup_dir().'/databases/'.str($this->team->name)->slug().'-'.$this->team->id.'/'.$this->directory_name; if ($this->database->name === 'coolify-db') { $databasesToBackup = ['coolify']; $this->directory_name = $this->container_name = 'coolify-db'; $ip = Str::slug($this->server->ip); $this->backup_dir = backup_dir().'/coolify'."/coolify-db-$ip"; } foreach ($databasesToBackup as $database) { // Generate unique UUID for each database backup execution $attempts = 0; do { $this->backup_log_uuid = (string) new Cuid2; $exists = ScheduledDatabaseBackupExecution::where('uuid', $this->backup_log_uuid)->exists(); $attempts++; if ($attempts >= 3 && $exists) { throw new \Exception('Unable to generate unique UUID for backup execution after 3 attempts'); } } while ($exists); $size = 0; $localBackupSucceeded = false; $s3UploadError = null; // Step 1: Create local backup try { if (str($databaseType)->contains('postgres')) { $this->backup_file = "/pg-dump-$database-".Carbon::now()->timestamp.'.dmp'; if ($this->backup->dump_all) { $this->backup_file = '/pg-dump-all-'.Carbon::now()->timestamp.'.gz'; } $this->backup_location = $this->backup_dir.$this->backup_file; $this->backup_log = ScheduledDatabaseBackupExecution::create([ 'uuid' => $this->backup_log_uuid, 'database_name' => $database, 'filename' => $this->backup_location, 'scheduled_database_backup_id' => $this->backup->id, 'local_storage_deleted' => false, ]); $this->backup_standalone_postgresql($database); } elseif (str($databaseType)->contains('mongo')) { if ($database === '*') { $database = 'all'; $databaseName = 'all'; } else { if (str($database)->contains(':')) { $databaseName = str($database)->before(':'); } else { $databaseName = $database; } } $this->backup_file = "/mongo-dump-$databaseName-".Carbon::now()->timestamp.'.tar.gz'; $this->backup_location = $this->backup_dir.$this->backup_file; $this->backup_log = ScheduledDatabaseBackupExecution::create([ 'uuid' => $this->backup_log_uuid, 'database_name' => $databaseName, 'filename' => $this->backup_location, 'scheduled_database_backup_id' => $this->backup->id, 'local_storage_deleted' => false, ]); $this->backup_standalone_mongodb($database); } elseif (str($databaseType)->contains('mysql')) { $this->backup_file = "/mysql-dump-$database-".Carbon::now()->timestamp.'.dmp'; if ($this->backup->dump_all) { $this->backup_file = '/mysql-dump-all-'.Carbon::now()->timestamp.'.gz'; } $this->backup_location = $this->backup_dir.$this->backup_file; $this->backup_log = ScheduledDatabaseBackupExecution::create([ 'uuid' => $this->backup_log_uuid, 'database_name' => $database, 'filename' => $this->backup_location, 'scheduled_database_backup_id' => $this->backup->id, 'local_storage_deleted' => false, ]); $this->backup_standalone_mysql($database); } elseif (str($databaseType)->contains('mariadb')) { $this->backup_file = "/mariadb-dump-$database-".Carbon::now()->timestamp.'.dmp'; if ($this->backup->dump_all) { $this->backup_file = '/mariadb-dump-all-'.Carbon::now()->timestamp.'.gz'; } $this->backup_location = $this->backup_dir.$this->backup_file; $this->backup_log = ScheduledDatabaseBackupExecution::create([ 'uuid' => $this->backup_log_uuid, 'database_name' => $database, 'filename' => $this->backup_location, 'scheduled_database_backup_id' => $this->backup->id, 'local_storage_deleted' => false, ]); $this->backup_standalone_mariadb($database); } else { throw new \Exception('Unsupported database type'); } $size = $this->calculate_size(); // Verify local backup succeeded if ($size > 0) { $localBackupSucceeded = true; } else { throw new \Exception('Local backup file is empty or was not created'); } } catch (\Throwable $e) { // Local backup failed if ($this->backup_log) { $this->backup_log->update([ 'status' => 'failed', 'message' => $this->error_output ?? $this->backup_output ?? $e->getMessage(), 'size' => $size, 'filename' => null, 's3_uploaded' => null, ]); } $this->team?->notify(new BackupFailed($this->backup, $this->database, $this->error_output ?? $this->backup_output ?? $e->getMessage(), $database)); continue; } // Step 2: Upload to S3 if enabled (independent of local backup) $localStorageDeleted = false; if ($this->backup->save_s3 && $localBackupSucceeded) { try { $this->upload_to_s3(); // If local backup is disabled, delete the local file immediately after S3 upload if ($this->backup->disable_local_backup) { deleteBackupsLocally($this->backup_location, $this->server); $localStorageDeleted = true; } } catch (\Throwable $e) { // S3 upload failed but local backup succeeded $s3UploadError = $e->getMessage(); } } // Step 3: Update status and send notifications based on results if ($localBackupSucceeded) { $message = $this->backup_output; if ($s3UploadError) { $message = $message ? $message."\n\nWarning: S3 upload failed: ".$s3UploadError : 'Warning: S3 upload failed: '.$s3UploadError; } $this->backup_log->update([ 'status' => 'success', 'message' => $message, 'size' => $size, 's3_uploaded' => $this->backup->save_s3 ? $this->s3_uploaded : null, 'local_storage_deleted' => $localStorageDeleted, ]); // Send appropriate notification if ($s3UploadError) { $this->team->notify(new BackupSuccessWithS3Warning($this->backup, $this->database, $database, $s3UploadError)); } else { $this->team->notify(new BackupSuccess($this->backup, $this->database, $database)); } } } if ($this->backup_log && $this->backup_log->status === 'success') { removeOldBackups($this->backup); } } catch (\Throwable $e) { throw $e; } finally { if ($this->team) { BackupCreated::dispatch($this->team->id); } if ($this->backup_log) { $this->backup_log->update([ 'finished_at' => Carbon::now()->toImmutable(), ]); } } } private function backup_standalone_mongodb(string $databaseWithCollections): void { try { $url = $this->database->internal_db_url; if (blank($url)) { // For service-based MongoDB, try to build URL from environment variables if (filled($this->mongo_root_username) && filled($this->mongo_root_password)) { // Use container name instead of server IP for service-based MongoDB $url = "mongodb://{$this->mongo_root_username}:{$this->mongo_root_password}@{$this->container_name}:27017"; } else { // If no environment variables are available, throw an exception throw new \Exception('MongoDB credentials not found. Ensure MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD environment variables are available in the container.'); } } \Log::info('MongoDB backup URL configured', ['has_url' => filled($url), 'using_env_vars' => blank($this->database->internal_db_url)]); if ($databaseWithCollections === 'all') { $commands[] = 'mkdir -p '.$this->backup_dir; if (str($this->database->image)->startsWith('mongo:4')) { $commands[] = "docker exec $this->container_name mongodump --uri=\"$url\" --gzip --archive > $this->backup_location"; } else { $commands[] = "docker exec $this->container_name mongodump --authenticationDatabase=admin --uri=\"$url\" --gzip --archive > $this->backup_location"; } } else { if (str($databaseWithCollections)->contains(':')) { $databaseName = str($databaseWithCollections)->before(':'); $collectionsToExclude = str($databaseWithCollections)->after(':')->explode(','); } else { $databaseName = $databaseWithCollections; $collectionsToExclude = collect(); } $commands[] = 'mkdir -p '.$this->backup_dir; // Validate and escape database name to prevent command injection validateShellSafePath($databaseName, 'database name'); $escapedDatabaseName = escapeshellarg($databaseName); if ($collectionsToExclude->count() === 0) { if (str($this->database->image)->startsWith('mongo:4')) { $commands[] = "docker exec $this->container_name mongodump --uri=\"$url\" --gzip --archive > $this->backup_location"; } else { $commands[] = "docker exec $this->container_name mongodump --authenticationDatabase=admin --uri=\"$url\" --db $escapedDatabaseName --gzip --archive > $this->backup_location"; } } else { if (str($this->database->image)->startsWith('mongo:4')) { $commands[] = "docker exec $this->container_name mongodump --uri=$url --gzip --excludeCollection ".$collectionsToExclude->implode(' --excludeCollection ')." --archive > $this->backup_location"; } else { $commands[] = "docker exec $this->container_name mongodump --authenticationDatabase=admin --uri=\"$url\" --db $escapedDatabaseName --gzip --excludeCollection ".$collectionsToExclude->implode(' --excludeCollection ')." --archive > $this->backup_location"; } } } $this->backup_output = instant_remote_process($commands, $this->server, true, false, $this->timeout, disableMultiplexing: true); $this->backup_output = trim($this->backup_output); if ($this->backup_output === '') { $this->backup_output = null; } } catch (\Throwable $e) { $this->add_to_error_output($e->getMessage()); throw $e; } } private function backup_standalone_postgresql(string $database): void { try { $commands[] = 'mkdir -p '.$this->backup_dir; $backupCommand = 'docker exec'; if ($this->postgres_password) { $backupCommand .= " -e PGPASSWORD=\"{$this->postgres_password}\""; } if ($this->backup->dump_all) { $backupCommand .= " $this->container_name pg_dumpall --username {$this->database->postgres_user} | gzip > $this->backup_location"; } else { // Validate and escape database name to prevent command injection validateShellSafePath($database, 'database name'); $escapedDatabase = escapeshellarg($database); $backupCommand .= " $this->container_name pg_dump --format=custom --no-acl --no-owner --username {$this->database->postgres_user} $escapedDatabase > $this->backup_location"; } $commands[] = $backupCommand; $this->backup_output = instant_remote_process($commands, $this->server, true, false, $this->timeout, disableMultiplexing: true); $this->backup_output = trim($this->backup_output); if ($this->backup_output === '') { $this->backup_output = null; } } catch (\Throwable $e) { $this->add_to_error_output($e->getMessage()); throw $e; } } private function backup_standalone_mysql(string $database): void { try { $commands[] = 'mkdir -p '.$this->backup_dir; if ($this->backup->dump_all) { $commands[] = "docker exec $this->container_name mysqldump -u root -p\"{$this->database->mysql_root_password}\" --all-databases --single-transaction --quick --lock-tables=false --compress | gzip > $this->backup_location"; } else { // Validate and escape database name to prevent command injection validateShellSafePath($database, 'database name'); $escapedDatabase = escapeshellarg($database); $commands[] = "docker exec $this->container_name mysqldump -u root -p\"{$this->database->mysql_root_password}\" $escapedDatabase > $this->backup_location"; } $this->backup_output = instant_remote_process($commands, $this->server, true, false, $this->timeout, disableMultiplexing: true); $this->backup_output = trim($this->backup_output); if ($this->backup_output === '') { $this->backup_output = null; } } catch (\Throwable $e) { $this->add_to_error_output($e->getMessage()); throw $e; } } private function backup_standalone_mariadb(string $database): void { try { $commands[] = 'mkdir -p '.$this->backup_dir; if ($this->backup->dump_all) { $commands[] = "docker exec $this->container_name mariadb-dump -u root -p\"{$this->database->mariadb_root_password}\" --all-databases --single-transaction --quick --lock-tables=false --compress > $this->backup_location"; } else { // Validate and escape database name to prevent command injection validateShellSafePath($database, 'database name'); $escapedDatabase = escapeshellarg($database); $commands[] = "docker exec $this->container_name mariadb-dump -u root -p\"{$this->database->mariadb_root_password}\" $escapedDatabase > $this->backup_location"; } $this->backup_output = instant_remote_process($commands, $this->server, true, false, $this->timeout, disableMultiplexing: true); $this->backup_output = trim($this->backup_output); if ($this->backup_output === '') { $this->backup_output = null; } } catch (\Throwable $e) { $this->add_to_error_output($e->getMessage()); throw $e; } } private function add_to_backup_output($output): void { if ($this->backup_output) { $this->backup_output = $this->backup_output."\n".$output; } else { $this->backup_output = $output; } } private function add_to_error_output($output): void { if ($this->error_output) { $this->error_output = $this->error_output."\n".$output; } else { $this->error_output = $output; } } private function calculate_size() { return instant_remote_process(["du -b $this->backup_location | cut -f1"], $this->server, false, false, null, disableMultiplexing: true); } private function upload_to_s3(): void { try { if (is_null($this->s3)) { return; } $key = $this->s3->key; $secret = $this->s3->secret; // $region = $this->s3->region; $bucket = $this->s3->bucket; $endpoint = $this->s3->endpoint; $this->s3->testConnection(shouldSave: true); if (data_get($this->backup, 'database_type') === \App\Models\ServiceDatabase::class) { $network = $this->database->service->destination->network; } else { $network = $this->database->destination->network; } $fullImageName = $this->getFullImageName(); $containerExists = instant_remote_process(["docker ps -a -q -f name=backup-of-{$this->backup_log_uuid}"], $this->server, false, false, null, disableMultiplexing: true); if (filled($containerExists)) { instant_remote_process(["docker rm -f backup-of-{$this->backup_log_uuid}"], $this->server, false, false, null, disableMultiplexing: true); } if (isDev()) { if ($this->database->name === 'coolify-db') { $backup_location_from = '/var/lib/docker/volumes/coolify_dev_backups_data/_data/coolify/coolify-db-'.$this->server->ip.$this->backup_file; $commands[] = "docker run -d --network {$network} --name backup-of-{$this->backup_log_uuid} --rm -v $backup_location_from:$this->backup_location:ro {$fullImageName}"; } else { $backup_location_from = '/var/lib/docker/volumes/coolify_dev_backups_data/_data/databases/'.str($this->team->name)->slug().'-'.$this->team->id.'/'.$this->directory_name.$this->backup_file;
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
true
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/ValidateAndInstallServerJob.php
app/Jobs/ValidateAndInstallServerJob.php
<?php namespace App\Jobs; use App\Actions\Proxy\CheckProxy; use App\Actions\Proxy\StartProxy; use App\Events\ServerReachabilityChanged; use App\Events\ServerValidated; use App\Models\Server; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Log; class ValidateAndInstallServerJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $timeout = 600; // 10 minutes public int $maxTries = 3; public function __construct( public Server $server, public int $numberOfTries = 0 ) { $this->onQueue('high'); } public function handle(): void { try { // Mark validation as in progress $this->server->update(['is_validating' => true]); Log::info('ValidateAndInstallServer: Starting validation', [ 'server_id' => $this->server->id, 'server_name' => $this->server->name, 'attempt' => $this->numberOfTries + 1, ]); // Validate connection ['uptime' => $uptime, 'error' => $error] = $this->server->validateConnection(); if (! $uptime) { $errorMessage = 'Server is not reachable. Please validate your configuration and connection.<br>Check this <a target="_blank" class="underline" href="https://coolify.io/docs/knowledge-base/server/openssh">documentation</a> for further help. <br><br>Error: '.$error; $this->server->update([ 'validation_logs' => $errorMessage, 'is_validating' => false, ]); Log::error('ValidateAndInstallServer: Server not reachable', [ 'server_id' => $this->server->id, 'error' => $error, ]); return; } // Validate OS $supportedOsType = $this->server->validateOS(); if (! $supportedOsType) { $errorMessage = 'Server OS type is not supported. Please install Docker manually before continuing: <a target="_blank" class="underline" href="https://docs.docker.com/engine/install/#server">documentation</a>.'; $this->server->update([ 'validation_logs' => $errorMessage, 'is_validating' => false, ]); Log::error('ValidateAndInstallServer: OS not supported', [ 'server_id' => $this->server->id, ]); return; } // Check and install prerequisites $validationResult = $this->server->validatePrerequisites(); if (! $validationResult['success']) { if ($this->numberOfTries >= $this->maxTries) { $missingCommands = implode(', ', $validationResult['missing']); $errorMessage = "Prerequisites ({$missingCommands}) could not be installed after {$this->maxTries} attempts. Please install them manually before continuing."; $this->server->update([ 'validation_logs' => $errorMessage, 'is_validating' => false, ]); Log::error('ValidateAndInstallServer: Prerequisites installation failed after max tries', [ 'server_id' => $this->server->id, 'attempts' => $this->numberOfTries, 'missing_commands' => $validationResult['missing'], 'found_commands' => $validationResult['found'], ]); return; } Log::info('ValidateAndInstallServer: Installing prerequisites', [ 'server_id' => $this->server->id, 'attempt' => $this->numberOfTries + 1, 'missing_commands' => $validationResult['missing'], 'found_commands' => $validationResult['found'], ]); // Install prerequisites $this->server->installPrerequisites(); // Retry validation after installation self::dispatch($this->server, $this->numberOfTries + 1)->delay(now()->addSeconds(30)); return; } // Check if Docker is installed $dockerInstalled = $this->server->validateDockerEngine(); $dockerComposeInstalled = $this->server->validateDockerCompose(); if (! $dockerInstalled || ! $dockerComposeInstalled) { // Try to install Docker if ($this->numberOfTries >= $this->maxTries) { $errorMessage = 'Docker Engine could not be installed after '.$this->maxTries.' attempts. Please install Docker manually before continuing: <a target="_blank" class="underline" href="https://docs.docker.com/engine/install/#server">documentation</a>.'; $this->server->update([ 'validation_logs' => $errorMessage, 'is_validating' => false, ]); Log::error('ValidateAndInstallServer: Docker installation failed after max tries', [ 'server_id' => $this->server->id, 'attempts' => $this->numberOfTries, ]); return; } Log::info('ValidateAndInstallServer: Installing Docker', [ 'server_id' => $this->server->id, 'attempt' => $this->numberOfTries + 1, ]); // Install Docker $this->server->installDocker(); // Retry validation after installation self::dispatch($this->server, $this->numberOfTries + 1)->delay(now()->addSeconds(30)); return; } // Validate Docker version $dockerVersion = $this->server->validateDockerEngineVersion(); if (! $dockerVersion) { $requiredDockerVersion = str(config('constants.docker.minimum_required_version'))->before('.'); $errorMessage = 'Minimum Docker Engine version '.$requiredDockerVersion.' is not installed. Please install Docker manually before continuing: <a target="_blank" class="underline" href="https://docs.docker.com/engine/install/#server">documentation</a>.'; $this->server->update([ 'validation_logs' => $errorMessage, 'is_validating' => false, ]); Log::error('ValidateAndInstallServer: Docker version not sufficient', [ 'server_id' => $this->server->id, ]); return; } // Validation successful! Log::info('ValidateAndInstallServer: Validation successful', [ 'server_id' => $this->server->id, 'server_name' => $this->server->name, ]); // Start proxy if needed if (! $this->server->isBuildServer()) { $proxyShouldRun = CheckProxy::run($this->server, true); if ($proxyShouldRun) { // Ensure networks exist BEFORE dispatching async proxy startup // This prevents race condition where proxy tries to start before networks are created instant_remote_process(ensureProxyNetworksExist($this->server)->toArray(), $this->server, false); StartProxy::dispatch($this->server); } } // Mark validation as complete $this->server->update(['is_validating' => false]); // Refresh server to get latest state $this->server->refresh(); // Broadcast events to update UI ServerValidated::dispatch($this->server->team_id, $this->server->uuid); ServerReachabilityChanged::dispatch($this->server); } catch (\Throwable $e) { Log::error('ValidateAndInstallServer: Exception occurred', [ 'server_id' => $this->server->id, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString(), ]); $this->server->update([ 'validation_logs' => 'An error occurred during validation: '.$e->getMessage(), 'is_validating' => false, ]); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/CheckTraefikVersionJob.php
app/Jobs/CheckTraefikVersionJob.php
<?php namespace App\Jobs; use App\Enums\ProxyTypes; use App\Models\Server; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class CheckTraefikVersionJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $tries = 3; public function handle(): void { // Load versions from cached data $traefikVersions = get_traefik_versions(); if (empty($traefikVersions)) { return; } // Query all servers with Traefik proxy that are reachable $servers = Server::whereNotNull('proxy') ->whereProxyType(ProxyTypes::TRAEFIK->value) ->whereRelation('settings', 'is_reachable', true) ->whereRelation('settings', 'is_usable', true) ->get(); if ($servers->isEmpty()) { return; } // Dispatch individual server check jobs in parallel // Each job will send immediate notifications when outdated Traefik is detected foreach ($servers as $server) { CheckTraefikVersionForServerJob::dispatch($server, $traefikVersions); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/PushServerUpdateJob.php
app/Jobs/PushServerUpdateJob.php
<?php namespace App\Jobs; use App\Actions\Database\StartDatabaseProxy; use App\Actions\Database\StopDatabaseProxy; use App\Actions\Proxy\CheckProxy; use App\Actions\Proxy\StartProxy; use App\Actions\Server\StartLogDrain; use App\Actions\Shared\ComplexStatusCheck; use App\Models\Application; use App\Models\ApplicationPreview; use App\Models\Server; use App\Models\ServiceApplication; use App\Models\ServiceDatabase; use App\Notifications\Container\ContainerRestarted; use App\Services\ContainerStatusAggregator; use App\Traits\CalculatesExcludedStatus; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\Middleware\WithoutOverlapping; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Collection; use Laravel\Horizon\Contracts\Silenced; class PushServerUpdateJob implements ShouldBeEncrypted, ShouldQueue, Silenced { use CalculatesExcludedStatus; use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $tries = 1; public $timeout = 30; public Collection $containers; public Collection $applications; public Collection $previews; public Collection $databases; public Collection $services; public Collection $allApplicationIds; public Collection $allDatabaseUuids; public Collection $allTcpProxyUuids; public Collection $allServiceApplicationIds; public Collection $allApplicationPreviewsIds; public Collection $allServiceDatabaseIds; public Collection $allApplicationsWithAdditionalServers; public Collection $foundApplicationIds; public Collection $foundDatabaseUuids; public Collection $foundServiceApplicationIds; public Collection $foundServiceDatabaseIds; public Collection $foundApplicationPreviewsIds; public Collection $applicationContainerStatuses; public Collection $serviceContainerStatuses; public bool $foundProxy = false; public bool $foundLogDrainContainer = false; public function middleware(): array { return [(new WithoutOverlapping('push-server-update-'.$this->server->uuid))->expireAfter(30)->dontRelease()]; } public function backoff(): int { return isDev() ? 1 : 3; } public function __construct(public Server $server, public $data) { $this->containers = collect(); $this->foundApplicationIds = collect(); $this->foundDatabaseUuids = collect(); $this->foundServiceApplicationIds = collect(); $this->foundApplicationPreviewsIds = collect(); $this->foundServiceDatabaseIds = collect(); $this->applicationContainerStatuses = collect(); $this->serviceContainerStatuses = collect(); $this->allApplicationIds = collect(); $this->allDatabaseUuids = collect(); $this->allTcpProxyUuids = collect(); $this->allServiceApplicationIds = collect(); $this->allServiceDatabaseIds = collect(); } public function handle() { // Defensive initialization for Collection properties to handle queue deserialization edge cases $this->serviceContainerStatuses ??= collect(); $this->applicationContainerStatuses ??= collect(); $this->foundApplicationIds ??= collect(); $this->foundDatabaseUuids ??= collect(); $this->foundServiceApplicationIds ??= collect(); $this->foundApplicationPreviewsIds ??= collect(); $this->foundServiceDatabaseIds ??= collect(); $this->allApplicationIds ??= collect(); $this->allDatabaseUuids ??= collect(); $this->allTcpProxyUuids ??= collect(); $this->allServiceApplicationIds ??= collect(); $this->allServiceDatabaseIds ??= collect(); // TODO: Swarm is not supported yet if (! $this->data) { throw new \Exception('No data provided'); } $data = collect($this->data); $this->server->sentinelHeartbeat(); $this->containers = collect(data_get($data, 'containers')); $filesystemUsageRoot = data_get($data, 'filesystem_usage_root.used_percentage'); ServerStorageCheckJob::dispatch($this->server, $filesystemUsageRoot); if ($this->containers->isEmpty()) { return; } $this->applications = $this->server->applications(); $this->databases = $this->server->databases(); $this->previews = $this->server->previews(); // Eager load service applications and databases to avoid N+1 queries $this->services = $this->server->services() ->with(['applications:id,service_id', 'databases:id,service_id']) ->get(); $this->allApplicationIds = $this->applications->filter(function ($application) { return $application->additional_servers_count === 0; })->pluck('id'); $this->allApplicationsWithAdditionalServers = $this->applications->filter(function ($application) { return $application->additional_servers_count > 0; }); $this->allApplicationPreviewsIds = $this->previews->map(function ($preview) { return $preview->application_id.':'.$preview->pull_request_id; }); $this->allDatabaseUuids = $this->databases->pluck('uuid'); $this->allTcpProxyUuids = $this->databases->where('is_public', true)->pluck('uuid'); // Use eager-loaded relationships instead of querying in loop $this->allServiceApplicationIds = $this->services->flatMap(fn ($service) => $service->applications->pluck('id')); $this->allServiceDatabaseIds = $this->services->flatMap(fn ($service) => $service->databases->pluck('id')); foreach ($this->containers as $container) { $containerStatus = data_get($container, 'state', 'exited'); $rawHealthStatus = data_get($container, 'health_status'); $containerHealth = $rawHealthStatus ?? 'unknown'; // Only append health status if container is not exited if ($containerStatus !== 'exited') { $containerStatus = "$containerStatus:$containerHealth"; } $labels = collect(data_get($container, 'labels')); $coolify_managed = $labels->has('coolify.managed'); if (! $coolify_managed) { continue; } $name = data_get($container, 'name'); if ($name === 'coolify-log-drain' && $this->isRunning($containerStatus)) { $this->foundLogDrainContainer = true; } if ($labels->has('coolify.applicationId')) { $applicationId = $labels->get('coolify.applicationId'); $pullRequestId = $labels->get('coolify.pullRequestId', '0'); try { if ($pullRequestId === '0') { if ($this->allApplicationIds->contains($applicationId)) { $this->foundApplicationIds->push($applicationId); } // Store container status for aggregation if (! $this->applicationContainerStatuses->has($applicationId)) { $this->applicationContainerStatuses->put($applicationId, collect()); } $containerName = $labels->get('com.docker.compose.service'); if ($containerName) { $this->applicationContainerStatuses->get($applicationId)->put($containerName, $containerStatus); } } else { $previewKey = $applicationId.':'.$pullRequestId; if ($this->allApplicationPreviewsIds->contains($previewKey)) { $this->foundApplicationPreviewsIds->push($previewKey); } $this->updateApplicationPreviewStatus($applicationId, $pullRequestId, $containerStatus); } } catch (\Exception $e) { } } elseif ($labels->has('coolify.serviceId')) { $serviceId = $labels->get('coolify.serviceId'); $subType = $labels->get('coolify.service.subType'); $subId = $labels->get('coolify.service.subId'); if ($subType === 'application') { $this->foundServiceApplicationIds->push($subId); // Store container status for aggregation $key = $serviceId.':'.$subType.':'.$subId; if (! $this->serviceContainerStatuses->has($key)) { $this->serviceContainerStatuses->put($key, collect()); } $containerName = $labels->get('com.docker.compose.service'); if ($containerName) { $this->serviceContainerStatuses->get($key)->put($containerName, $containerStatus); } } elseif ($subType === 'database') { $this->foundServiceDatabaseIds->push($subId); // Store container status for aggregation $key = $serviceId.':'.$subType.':'.$subId; if (! $this->serviceContainerStatuses->has($key)) { $this->serviceContainerStatuses->put($key, collect()); } $containerName = $labels->get('com.docker.compose.service'); if ($containerName) { $this->serviceContainerStatuses->get($key)->put($containerName, $containerStatus); } } } else { $uuid = $labels->get('com.docker.compose.service'); $type = $labels->get('coolify.type'); if ($name === 'coolify-proxy' && $this->isRunning($containerStatus)) { $this->foundProxy = true; } elseif ($type === 'service' && $this->isRunning($containerStatus)) { } else { if ($this->allDatabaseUuids->contains($uuid) && $this->isActiveOrTransient($containerStatus)) { $this->foundDatabaseUuids->push($uuid); // TCP proxy should only be started/managed when database is actually running if ($this->allTcpProxyUuids->contains($uuid) && $this->isRunning($containerStatus)) { $this->updateDatabaseStatus($uuid, $containerStatus, tcpProxy: true); } else { $this->updateDatabaseStatus($uuid, $containerStatus, tcpProxy: false); } } } } } $this->updateProxyStatus(); $this->updateNotFoundApplicationStatus(); $this->updateNotFoundApplicationPreviewStatus(); $this->updateNotFoundDatabaseStatus(); $this->updateNotFoundServiceStatus(); $this->updateAdditionalServersStatus(); // Aggregate multi-container application statuses $this->aggregateMultiContainerStatuses(); // Aggregate multi-container service statuses $this->aggregateServiceContainerStatuses(); $this->checkLogDrainContainer(); } private function aggregateMultiContainerStatuses() { if ($this->applicationContainerStatuses->isEmpty()) { return; } foreach ($this->applicationContainerStatuses as $applicationId => $containerStatuses) { $application = $this->applications->where('id', $applicationId)->first(); if (! $application) { continue; } // Parse docker compose to check for excluded containers $dockerComposeRaw = data_get($application, 'docker_compose_raw'); $excludedContainers = $this->getExcludedContainersFromDockerCompose($dockerComposeRaw); // Filter out excluded containers $relevantStatuses = $containerStatuses->filter(function ($status, $containerName) use ($excludedContainers) { return ! $excludedContainers->contains($containerName); }); // If all containers are excluded, calculate status from excluded containers if ($relevantStatuses->isEmpty()) { $aggregatedStatus = $this->calculateExcludedStatusFromStrings($containerStatuses); if ($aggregatedStatus && $application->status !== $aggregatedStatus) { $application->status = $aggregatedStatus; $application->save(); } continue; } // Use ContainerStatusAggregator service for state machine logic // Use preserveRestarting: true so applications show "Restarting" instead of "Degraded" $aggregator = new ContainerStatusAggregator; $aggregatedStatus = $aggregator->aggregateFromStrings($relevantStatuses, 0, preserveRestarting: true); // Update application status with aggregated result if ($aggregatedStatus && $application->status !== $aggregatedStatus) { $application->status = $aggregatedStatus; $application->save(); } } } private function aggregateServiceContainerStatuses() { if ($this->serviceContainerStatuses->isEmpty()) { return; } foreach ($this->serviceContainerStatuses as $key => $containerStatuses) { // Parse key: serviceId:subType:subId [$serviceId, $subType, $subId] = explode(':', $key); $service = $this->services->where('id', $serviceId)->first(); if (! $service) { continue; } // Get the service sub-resource (ServiceApplication or ServiceDatabase) $subResource = null; if ($subType === 'application') { $subResource = $service->applications()->where('id', $subId)->first(); } elseif ($subType === 'database') { $subResource = $service->databases()->where('id', $subId)->first(); } if (! $subResource) { continue; } // Parse docker compose from service to check for excluded containers $dockerComposeRaw = data_get($service, 'docker_compose_raw'); $excludedContainers = $this->getExcludedContainersFromDockerCompose($dockerComposeRaw); // Filter out excluded containers $relevantStatuses = $containerStatuses->filter(function ($status, $containerName) use ($excludedContainers) { return ! $excludedContainers->contains($containerName); }); // If all containers are excluded, calculate status from excluded containers if ($relevantStatuses->isEmpty()) { $aggregatedStatus = $this->calculateExcludedStatusFromStrings($containerStatuses); if ($aggregatedStatus && $subResource->status !== $aggregatedStatus) { $subResource->status = $aggregatedStatus; $subResource->save(); } continue; } // Use ContainerStatusAggregator service for state machine logic // NOTE: Sentinel does NOT provide restart count data, so maxRestartCount is always 0 // Use preserveRestarting: true so individual sub-resources show "Restarting" instead of "Degraded" $aggregator = new ContainerStatusAggregator; $aggregatedStatus = $aggregator->aggregateFromStrings($relevantStatuses, 0, preserveRestarting: true); // Update service sub-resource status with aggregated result if ($aggregatedStatus && $subResource->status !== $aggregatedStatus) { $subResource->status = $aggregatedStatus; $subResource->save(); } } } private function updateApplicationStatus(string $applicationId, string $containerStatus) { $application = $this->applications->where('id', $applicationId)->first(); if (! $application) { return; } if ($application->status !== $containerStatus) { $application->status = $containerStatus; $application->save(); } } private function updateApplicationPreviewStatus(string $applicationId, string $pullRequestId, string $containerStatus) { $application = $this->previews->where('application_id', $applicationId) ->where('pull_request_id', $pullRequestId) ->first(); if (! $application) { return; } if ($application->status !== $containerStatus) { $application->status = $containerStatus; $application->save(); } } private function updateNotFoundApplicationStatus() { $notFoundApplicationIds = $this->allApplicationIds->diff($this->foundApplicationIds); if ($notFoundApplicationIds->isEmpty()) { return; } // Only protection: Verify we received any container data at all // If containers collection is completely empty, Sentinel might have failed if ($this->containers->isEmpty()) { return; } // Batch update: mark all not-found applications as exited (excluding already exited ones) Application::whereIn('id', $notFoundApplicationIds) ->where('status', 'not like', 'exited%') ->update(['status' => 'exited']); } private function updateNotFoundApplicationPreviewStatus() { $notFoundApplicationPreviewsIds = $this->allApplicationPreviewsIds->diff($this->foundApplicationPreviewsIds); if ($notFoundApplicationPreviewsIds->isEmpty()) { return; } // Only protection: Verify we received any container data at all // If containers collection is completely empty, Sentinel might have failed if ($this->containers->isEmpty()) { return; } // Collect IDs of previews that need to be marked as exited $previewIdsToUpdate = collect(); foreach ($notFoundApplicationPreviewsIds as $previewKey) { // Parse the previewKey format "application_id:pull_request_id" $parts = explode(':', $previewKey); if (count($parts) !== 2) { continue; } $applicationId = $parts[0]; $pullRequestId = $parts[1]; $applicationPreview = $this->previews->where('application_id', $applicationId) ->where('pull_request_id', $pullRequestId) ->first(); if ($applicationPreview && ! str($applicationPreview->status)->startsWith('exited')) { $previewIdsToUpdate->push($applicationPreview->id); } } // Batch update all collected preview IDs if ($previewIdsToUpdate->isNotEmpty()) { ApplicationPreview::whereIn('id', $previewIdsToUpdate)->update(['status' => 'exited']); } } private function updateProxyStatus() { // If proxy is not found, start it if ($this->server->isProxyShouldRun()) { if ($this->foundProxy === false) { try { if (CheckProxy::run($this->server)) { StartProxy::run($this->server, async: false); $this->server->team?->notify(new ContainerRestarted('coolify-proxy', $this->server)); } } catch (\Throwable $e) { } } else { // Connect proxy to networks asynchronously to avoid blocking the status update ConnectProxyToNetworksJob::dispatch($this->server); } } } private function updateDatabaseStatus(string $databaseUuid, string $containerStatus, bool $tcpProxy = false) { $database = $this->databases->where('uuid', $databaseUuid)->first(); if (! $database) { return; } if ($database->status !== $containerStatus) { $database->status = $containerStatus; $database->save(); } if ($this->isRunning($containerStatus) && $tcpProxy) { $tcpProxyContainerFound = $this->containers->filter(function ($value, $key) use ($databaseUuid) { return data_get($value, 'name') === "$databaseUuid-proxy" && data_get($value, 'state') === 'running'; })->first(); if (! $tcpProxyContainerFound) { StartDatabaseProxy::dispatch($database); $this->server->team?->notify(new ContainerRestarted("TCP Proxy for {$database->name}", $this->server)); } else { } } } private function updateNotFoundDatabaseStatus() { $notFoundDatabaseUuids = $this->allDatabaseUuids->diff($this->foundDatabaseUuids); if ($notFoundDatabaseUuids->isEmpty()) { return; } // Only protection: Verify we received any container data at all // If containers collection is completely empty, Sentinel might have failed if ($this->containers->isEmpty()) { return; } $notFoundDatabaseUuids->each(function ($databaseUuid) { $database = $this->databases->where('uuid', $databaseUuid)->first(); if ($database) { if (! str($database->status)->startsWith('exited')) { $database->status = 'exited'; $database->save(); } if ($database->is_public) { StopDatabaseProxy::dispatch($database); } } }); } private function updateServiceSubStatus(string $serviceId, string $subType, string $subId, string $containerStatus) { $service = $this->services->where('id', $serviceId)->first(); if (! $service) { return; } if ($subType === 'application') { $application = $service->applications()->where('id', $subId)->first(); if ($application) { if ($application->status !== $containerStatus) { $application->status = $containerStatus; $application->save(); } } } elseif ($subType === 'database') { $database = $service->databases()->where('id', $subId)->first(); if ($database) { if ($database->status !== $containerStatus) { $database->status = $containerStatus; $database->save(); } } } } private function updateNotFoundServiceStatus() { $notFoundServiceApplicationIds = $this->allServiceApplicationIds->diff($this->foundServiceApplicationIds); $notFoundServiceDatabaseIds = $this->allServiceDatabaseIds->diff($this->foundServiceDatabaseIds); // Batch update service applications if ($notFoundServiceApplicationIds->isNotEmpty()) { ServiceApplication::whereIn('id', $notFoundServiceApplicationIds) ->where('status', '!=', 'exited') ->update(['status' => 'exited']); } // Batch update service databases if ($notFoundServiceDatabaseIds->isNotEmpty()) { ServiceDatabase::whereIn('id', $notFoundServiceDatabaseIds) ->where('status', '!=', 'exited') ->update(['status' => 'exited']); } } private function updateAdditionalServersStatus() { $this->allApplicationsWithAdditionalServers->each(function ($application) { ComplexStatusCheck::run($application); }); } private function isRunning(string $containerStatus) { return str($containerStatus)->contains('running'); } /** * Check if container is in an active or transient state. * Active states: running * Transient states: restarting, starting, created, paused * * These states indicate the container exists and should be tracked. * Terminal states (exited, dead, removing) should NOT be tracked. */ private function isActiveOrTransient(string $containerStatus): bool { return str($containerStatus)->contains('running') || str($containerStatus)->contains('restarting') || str($containerStatus)->contains('starting') || str($containerStatus)->contains('created') || str($containerStatus)->contains('paused'); } private function checkLogDrainContainer() { if ($this->server->isLogDrainEnabled() && $this->foundLogDrainContainer === false) { StartLogDrain::dispatch($this->server); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/ApplicationDeploymentJob.php
app/Jobs/ApplicationDeploymentJob.php
<?php namespace App\Jobs; use App\Actions\Docker\GetContainersStatus; use App\Enums\ApplicationDeploymentStatus; use App\Enums\ProcessStatus; use App\Events\ApplicationConfigurationChanged; use App\Events\ServiceStatusChanged; use App\Exceptions\DeploymentException; use App\Models\Application; use App\Models\ApplicationDeploymentQueue; use App\Models\ApplicationPreview; use App\Models\EnvironmentVariable; use App\Models\GithubApp; use App\Models\GitlabApp; use App\Models\Server; use App\Models\StandaloneDocker; use App\Models\SwarmDocker; use App\Notifications\Application\DeploymentFailed; use App\Notifications\Application\DeploymentSuccess; use App\Traits\EnvironmentVariableAnalyzer; use App\Traits\ExecuteRemoteCommand; use Carbon\Carbon; use Exception; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Collection; use Illuminate\Support\Sleep; use Illuminate\Support\Str; use Spatie\Url\Url; use Symfony\Component\Yaml\Yaml; use Throwable; use Visus\Cuid2\Cuid2; class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, EnvironmentVariableAnalyzer, ExecuteRemoteCommand, InteractsWithQueue, Queueable, SerializesModels; public const BUILD_TIME_ENV_PATH = '/artifacts/build-time.env'; private const BUILD_SCRIPT_PATH = '/artifacts/build.sh'; private const NIXPACKS_PLAN_PATH = '/artifacts/thegameplan.json'; public $tries = 1; public $timeout = 3600; public static int $batch_counter = 0; private bool $newVersionIsHealthy = false; private ApplicationDeploymentQueue $application_deployment_queue; private Application $application; private string $deployment_uuid; private int $pull_request_id; private string $commit; private bool $rollback; private bool $force_rebuild; private bool $restart_only; private ?string $dockerImage = null; private ?string $dockerImageTag = null; private GithubApp|GitlabApp|string $source = 'other'; private StandaloneDocker|SwarmDocker $destination; // Deploy to Server private Server $server; // Build Server private Server $build_server; private bool $use_build_server = false; // Save original server between phases private Server $original_server; private Server $mainServer; private bool $is_this_additional_server = false; private ?ApplicationPreview $preview = null; private ?string $git_type = null; private bool $only_this_server = false; private string $container_name; private ?string $currently_running_container_name = null; private string $basedir; private string $workdir; private ?string $build_pack = null; private string $configuration_dir; private string $build_image_name; private string $production_image_name; private bool $is_debug_enabled; private Collection|string $build_args; private $env_args; private $env_nixpacks_args; private $docker_compose; private $docker_compose_base64; private ?string $nixpacks_plan = null; private Collection $nixpacks_plan_json; private ?string $nixpacks_type = null; private string $dockerfile_location = '/Dockerfile'; private string $docker_compose_location = '/docker-compose.yaml'; private ?string $docker_compose_custom_start_command = null; private ?string $docker_compose_custom_build_command = null; private ?string $addHosts = null; private ?string $buildTarget = null; private bool $disableBuildCache = false; private Collection $saved_outputs; private ?string $secrets_hash_key = null; private ?string $full_healthcheck_url = null; private string $serverUser = 'root'; private string $serverUserHomeDir = '/root'; private string $dockerConfigFileExists = 'NOK'; private int $customPort = 22; private ?string $customRepository = null; private ?string $fullRepoUrl = null; private ?string $branch = null; private ?string $coolify_variables = null; private bool $preserveRepository = false; private bool $dockerBuildkitSupported = false; private bool $skip_build = false; private Collection|string $build_secrets; public function tags() { // Do not remove this one, it needs to properly identify which worker is running the job return ['App\Models\ApplicationDeploymentQueue:'.$this->application_deployment_queue_id]; } public function __construct(public int $application_deployment_queue_id) { $this->onQueue('high'); $this->application_deployment_queue = ApplicationDeploymentQueue::find($this->application_deployment_queue_id); $this->nixpacks_plan_json = collect([]); $this->application = Application::find($this->application_deployment_queue->application_id); $this->build_pack = data_get($this->application, 'build_pack'); $this->build_args = collect([]); $this->build_secrets = ''; $this->deployment_uuid = $this->application_deployment_queue->deployment_uuid; $this->pull_request_id = $this->application_deployment_queue->pull_request_id; $this->commit = $this->application_deployment_queue->commit; $this->rollback = $this->application_deployment_queue->rollback; $this->disableBuildCache = $this->application->settings->disable_build_cache; $this->force_rebuild = $this->application_deployment_queue->force_rebuild; if ($this->disableBuildCache) { $this->force_rebuild = true; } $this->restart_only = $this->application_deployment_queue->restart_only; $this->restart_only = $this->restart_only && $this->application->build_pack !== 'dockerimage' && $this->application->build_pack !== 'dockerfile'; $this->only_this_server = $this->application_deployment_queue->only_this_server; $this->git_type = data_get($this->application_deployment_queue, 'git_type'); $source = data_get($this->application, 'source'); if ($source) { $this->source = $source->getMorphClass()::where('id', $this->application->source->id)->first(); } $this->server = Server::find($this->application_deployment_queue->server_id); $this->timeout = $this->server->settings->dynamic_timeout; $this->destination = $this->server->destinations()->where('id', $this->application_deployment_queue->destination_id)->first(); $this->server = $this->mainServer = $this->destination->server; $this->serverUser = $this->server->user; $this->is_this_additional_server = $this->application->additional_servers()->wherePivot('server_id', $this->server->id)->count() > 0; $this->preserveRepository = $this->application->settings->is_preserve_repository_enabled; $this->basedir = $this->application->generateBaseDir($this->deployment_uuid); $this->workdir = "{$this->basedir}".rtrim($this->application->base_directory, '/'); $this->configuration_dir = application_configuration_dir()."/{$this->application->uuid}"; $this->is_debug_enabled = $this->application->settings->is_debug_enabled; $this->container_name = generateApplicationContainerName($this->application, $this->pull_request_id); if ($this->application->settings->custom_internal_name && ! $this->application->settings->is_consistent_container_name_enabled) { if ($this->pull_request_id === 0) { $this->container_name = $this->application->settings->custom_internal_name; } else { $this->container_name = addPreviewDeploymentSuffix($this->application->settings->custom_internal_name, $this->pull_request_id); } } $this->saved_outputs = collect(); // Set preview fqdn if ($this->pull_request_id !== 0) { $this->preview = ApplicationPreview::findPreviewByApplicationAndPullId($this->application->id, $this->pull_request_id); if ($this->preview) { if ($this->application->build_pack === 'dockercompose') { $this->preview->generate_preview_fqdn_compose(); } else { $this->preview->generate_preview_fqdn(); } } if ($this->application->is_github_based()) { ApplicationPullRequestUpdateJob::dispatch(application: $this->application, preview: $this->preview, deployment_uuid: $this->deployment_uuid, status: ProcessStatus::IN_PROGRESS); } if ($this->application->build_pack === 'dockerfile') { if (data_get($this->application, 'dockerfile_location')) { $this->dockerfile_location = $this->application->dockerfile_location; } } } } public function handle(): void { // Check if deployment was cancelled before we even started $this->application_deployment_queue->refresh(); if ($this->application_deployment_queue->status === ApplicationDeploymentStatus::CANCELLED_BY_USER->value) { $this->application_deployment_queue->addLogEntry('Deployment was cancelled before starting.'); return; } $this->application_deployment_queue->update([ 'status' => ApplicationDeploymentStatus::IN_PROGRESS->value, 'horizon_job_worker' => gethostname(), ]); if ($this->server->isFunctional() === false) { $this->application_deployment_queue->addLogEntry('Server is not functional.'); $this->fail('Server is not functional.'); return; } try { // Make sure the private key is stored in the filesystem $this->server->privateKey->storeInFileSystem(); // Generate custom host<->ip mapping $allContainers = instant_remote_process(["docker network inspect {$this->destination->network} -f '{{json .Containers}}' "], $this->server); if (! is_null($allContainers)) { $allContainers = format_docker_command_output_to_json($allContainers); $ips = collect([]); if (count($allContainers) > 0) { $allContainers = $allContainers[0]; $allContainers = collect($allContainers)->sort()->values(); foreach ($allContainers as $container) { $containerName = data_get($container, 'Name'); if ($containerName === 'coolify-proxy') { continue; } if (preg_match('/-(\d{12})/', $containerName)) { continue; } $containerIp = data_get($container, 'IPv4Address'); if ($containerName && $containerIp) { $containerIp = str($containerIp)->before('/'); $ips->put($containerName, $containerIp->value()); } } } $this->addHosts = $ips->map(function ($ip, $name) { return "--add-host $name:$ip"; })->implode(' '); } if ($this->application->dockerfile_target_build) { $this->buildTarget = " --target {$this->application->dockerfile_target_build} "; } // Check custom port ['repository' => $this->customRepository, 'port' => $this->customPort] = $this->application->customRepository(); if (data_get($this->application, 'settings.is_build_server_enabled')) { $teamId = data_get($this->application, 'environment.project.team.id'); $buildServers = Server::buildServers($teamId)->get(); if ($buildServers->count() === 0) { $this->application_deployment_queue->addLogEntry('No suitable build server found. Using the deployment server.'); $this->build_server = $this->server; $this->original_server = $this->server; } else { $this->build_server = $buildServers->random(); $this->application_deployment_queue->build_server_id = $this->build_server->id; $this->application_deployment_queue->addLogEntry("Found a suitable build server ({$this->build_server->name})."); $this->original_server = $this->server; $this->use_build_server = true; } } else { // Set build server & original_server to the same as deployment server $this->build_server = $this->server; $this->original_server = $this->server; } $this->detectBuildKitCapabilities(); $this->decide_what_to_do(); } catch (Exception $e) { if ($this->pull_request_id !== 0 && $this->application->is_github_based()) { ApplicationPullRequestUpdateJob::dispatch(application: $this->application, preview: $this->preview, deployment_uuid: $this->deployment_uuid, status: ProcessStatus::ERROR); } $this->fail($e); throw $e; } finally { // Wrap cleanup operations in try-catch to prevent exceptions from interfering // with Laravel's job failure handling and status updates try { $this->application_deployment_queue->update([ 'finished_at' => Carbon::now()->toImmutable(), ]); } catch (Exception $e) { // Log but don't fail - finished_at is not critical \Log::warning('Failed to update finished_at for deployment '.$this->deployment_uuid.': '.$e->getMessage()); } try { if ($this->use_build_server) { $this->server = $this->build_server; } else { $this->write_deployment_configurations(); } } catch (Exception $e) { // Log but don't fail - configuration writing errors shouldn't prevent status updates $this->application_deployment_queue->addLogEntry('Warning: Failed to write deployment configurations: '.$e->getMessage(), 'stderr'); } try { $this->application_deployment_queue->addLogEntry("Gracefully shutting down build container: {$this->deployment_uuid}"); $this->graceful_shutdown_container($this->deployment_uuid, skipRemove: true); } catch (Exception $e) { // Log but don't fail - container cleanup errors are expected when container is already gone \Log::warning('Failed to shutdown container '.$this->deployment_uuid.': '.$e->getMessage()); } try { ServiceStatusChanged::dispatch(data_get($this->application, 'environment.project.team.id')); } catch (Exception $e) { // Log but don't fail - event dispatch errors shouldn't prevent status updates \Log::warning('Failed to dispatch ServiceStatusChanged for deployment '.$this->deployment_uuid.': '.$e->getMessage()); } } } private function detectBuildKitCapabilities(): void { // If build secrets are not enabled, skip detection and use traditional args if (! $this->application->settings->use_build_secrets) { $this->dockerBuildkitSupported = false; return; } $serverToCheck = $this->use_build_server ? $this->build_server : $this->server; $serverName = $this->use_build_server ? "build server ({$serverToCheck->name})" : "deployment server ({$serverToCheck->name})"; try { $dockerVersion = instant_remote_process( ["docker version --format '{{.Server.Version}}'"], $serverToCheck ); $versionParts = explode('.', $dockerVersion); $majorVersion = (int) $versionParts[0]; $minorVersion = (int) ($versionParts[1] ?? 0); if ($majorVersion < 18 || ($majorVersion == 18 && $minorVersion < 9)) { $this->dockerBuildkitSupported = false; $this->application_deployment_queue->addLogEntry("Docker {$dockerVersion} on {$serverName} does not support BuildKit (requires 18.09+). Build secrets feature disabled."); return; } $buildkitEnabled = instant_remote_process( ["docker buildx version >/dev/null 2>&1 && echo 'available' || echo 'not-available'"], $serverToCheck ); if (trim($buildkitEnabled) !== 'available') { $buildkitTest = instant_remote_process( ["DOCKER_BUILDKIT=1 docker build --help 2>&1 | grep -q 'secret' && echo 'supported' || echo 'not-supported'"], $serverToCheck ); if (trim($buildkitTest) === 'supported') { $this->dockerBuildkitSupported = true; $this->application_deployment_queue->addLogEntry("Docker {$dockerVersion} with BuildKit secrets support detected on {$serverName}."); $this->application_deployment_queue->addLogEntry('Build secrets are enabled and will be used for enhanced security.'); } else { $this->dockerBuildkitSupported = false; $this->application_deployment_queue->addLogEntry("Docker {$dockerVersion} on {$serverName} does not have BuildKit secrets support."); $this->application_deployment_queue->addLogEntry('Build secrets feature is enabled but not supported. Using traditional build arguments.'); } } else { // Buildx is available, which means BuildKit is available // Now specifically test for secrets support $secretsTest = instant_remote_process( ["docker build --help 2>&1 | grep -q 'secret' && echo 'supported' || echo 'not-supported'"], $serverToCheck ); if (trim($secretsTest) === 'supported') { $this->dockerBuildkitSupported = true; $this->application_deployment_queue->addLogEntry("Docker {$dockerVersion} with BuildKit and Buildx detected on {$serverName}."); $this->application_deployment_queue->addLogEntry('Build secrets are enabled and will be used for enhanced security.'); } else { $this->dockerBuildkitSupported = false; $this->application_deployment_queue->addLogEntry("Docker {$dockerVersion} with Buildx on {$serverName}, but secrets not supported."); $this->application_deployment_queue->addLogEntry('Build secrets feature is enabled but not supported. Using traditional build arguments.'); } } } catch (\Exception $e) { $this->dockerBuildkitSupported = false; $this->application_deployment_queue->addLogEntry("Could not detect BuildKit capabilities on {$serverName}: {$e->getMessage()}"); $this->application_deployment_queue->addLogEntry('Build secrets feature is enabled but detection failed. Using traditional build arguments.'); } } private function decide_what_to_do() { if ($this->restart_only) { $this->just_restart(); return; } elseif ($this->pull_request_id !== 0) { $this->deploy_pull_request(); } elseif ($this->application->dockerfile) { $this->deploy_simple_dockerfile(); } elseif ($this->application->build_pack === 'dockercompose') { $this->deploy_docker_compose_buildpack(); } elseif ($this->application->build_pack === 'dockerimage') { $this->deploy_dockerimage_buildpack(); } elseif ($this->application->build_pack === 'dockerfile') { $this->deploy_dockerfile_buildpack(); } elseif ($this->application->build_pack === 'static') { $this->deploy_static_buildpack(); } else { $this->deploy_nixpacks_buildpack(); } $this->post_deployment(); } private function post_deployment() { // Mark deployment as complete FIRST, before any other operations // This ensures the deployment status is FINISHED even if subsequent operations fail $this->completeDeployment(); // Then handle side effects - these should not fail the deployment try { GetContainersStatus::dispatch($this->server); } catch (\Exception $e) { \Log::warning('Failed to dispatch GetContainersStatus for deployment '.$this->deployment_uuid.': '.$e->getMessage()); } if ($this->pull_request_id !== 0) { if ($this->application->is_github_based()) { try { ApplicationPullRequestUpdateJob::dispatch(application: $this->application, preview: $this->preview, deployment_uuid: $this->deployment_uuid, status: ProcessStatus::FINISHED); } catch (\Exception $e) { \Log::warning('Failed to dispatch PR update for deployment '.$this->deployment_uuid.': '.$e->getMessage()); } } } try { $this->run_post_deployment_command(); } catch (\Exception $e) { \Log::warning('Post deployment command failed for '.$this->deployment_uuid.': '.$e->getMessage()); } try { $this->application->isConfigurationChanged(true); } catch (\Exception $e) { \Log::warning('Failed to mark configuration as changed for deployment '.$this->deployment_uuid.': '.$e->getMessage()); } } private function deploy_simple_dockerfile() { if ($this->use_build_server) { $this->server = $this->build_server; } $dockerfile_base64 = base64_encode($this->application->dockerfile); $this->application_deployment_queue->addLogEntry("Starting deployment of {$this->application->name} to {$this->server->name}."); $this->prepare_builder_image(); $this->execute_remote_command( [ executeInDocker($this->deployment_uuid, "echo '$dockerfile_base64' | base64 -d | tee {$this->workdir}{$this->dockerfile_location} > /dev/null"), ], ); $this->generate_image_names(); $this->generate_compose_file(); // Save build-time .env file BEFORE the build $this->save_buildtime_environment_variables(); $this->generate_build_env_variables(); $this->add_build_env_variables_to_dockerfile(); $this->build_image(); // Save runtime environment variables AFTER the build // This overwrites the build-time .env with ALL variables (build-time + runtime) $this->save_runtime_environment_variables(); $this->push_to_docker_registry(); $this->rolling_update(); } private function deploy_dockerimage_buildpack() { $this->dockerImage = $this->application->docker_registry_image_name; if (str($this->application->docker_registry_image_tag)->isEmpty()) { $this->dockerImageTag = 'latest'; } else { $this->dockerImageTag = $this->application->docker_registry_image_tag; } // Check if this is an image hash deployment $isImageHash = str($this->dockerImageTag)->startsWith('sha256-'); $displayName = $isImageHash ? "{$this->dockerImage}@sha256:".str($this->dockerImageTag)->after('sha256-') : "{$this->dockerImage}:{$this->dockerImageTag}"; $this->application_deployment_queue->addLogEntry("Starting deployment of {$displayName} to {$this->server->name}."); $this->generate_image_names(); $this->prepare_builder_image(); $this->generate_compose_file(); // Save runtime environment variables (including empty .env file if no variables defined) $this->save_runtime_environment_variables(); $this->rolling_update(); } private function deploy_docker_compose_buildpack() { if (data_get($this->application, 'docker_compose_location')) { $this->docker_compose_location = $this->application->docker_compose_location; } if (data_get($this->application, 'docker_compose_custom_start_command')) { $this->docker_compose_custom_start_command = $this->application->docker_compose_custom_start_command; if (! str($this->docker_compose_custom_start_command)->contains('--project-directory')) { $this->docker_compose_custom_start_command = str($this->docker_compose_custom_start_command)->replaceFirst('compose', 'compose --project-directory '.$this->workdir)->value(); } } if (data_get($this->application, 'docker_compose_custom_build_command')) { $this->docker_compose_custom_build_command = $this->application->docker_compose_custom_build_command; if (! str($this->docker_compose_custom_build_command)->contains('--project-directory')) { $this->docker_compose_custom_build_command = str($this->docker_compose_custom_build_command)->replaceFirst('compose', 'compose --project-directory '.$this->workdir)->value(); } } if ($this->pull_request_id === 0) { $this->application_deployment_queue->addLogEntry("Starting deployment of {$this->application->name} to {$this->server->name}."); } else { $this->application_deployment_queue->addLogEntry("Starting pull request (#{$this->pull_request_id}) deployment of {$this->customRepository}:{$this->application->git_branch} to {$this->server->name}."); } $this->prepare_builder_image(); $this->check_git_if_build_needed(); $this->clone_repository(); if ($this->preserveRepository) { foreach ($this->application->fileStorages as $fileStorage) { $path = $fileStorage->fs_path; $saveName = 'file_stat_'.$fileStorage->id; $realPathInGit = str($path)->replace($this->application->workdir(), $this->workdir)->value(); // check if the file is a directory or a file inside the repository $this->execute_remote_command( [executeInDocker($this->deployment_uuid, "stat -c '%F' {$realPathInGit}"), 'hidden' => true, 'ignore_errors' => true, 'save' => $saveName] ); if ($this->saved_outputs->has($saveName)) { $fileStat = $this->saved_outputs->get($saveName); if ($fileStat->value() === 'directory' && ! $fileStorage->is_directory) { $fileStorage->is_directory = true; $fileStorage->content = null; $fileStorage->save(); $fileStorage->deleteStorageOnServer(); $fileStorage->saveStorageOnServer(); } elseif ($fileStat->value() === 'regular file' && $fileStorage->is_directory) { $fileStorage->is_directory = false; $fileStorage->is_based_on_git = true; $fileStorage->save(); $fileStorage->deleteStorageOnServer(); $fileStorage->saveStorageOnServer(); } } } } $this->generate_image_names(); $this->cleanup_git(); $this->generate_build_env_variables(); $this->application->loadComposeFile(isInit: false); if ($this->application->settings->is_raw_compose_deployment_enabled) { $this->application->oldRawParser(); $yaml = $composeFile = $this->application->docker_compose_raw; // For raw compose, we cannot automatically add secrets configuration // User must define it manually in their docker-compose file if ($this->application->settings->use_build_secrets && $this->dockerBuildkitSupported && ! empty($this->build_secrets)) { $this->application_deployment_queue->addLogEntry('Build secrets are configured. Ensure your docker-compose file includes build.secrets configuration for services that need them.'); } } else { $composeFile = $this->application->parse(pull_request_id: $this->pull_request_id, preview_id: data_get($this->preview, 'id'), commit: $this->commit); // Always add .env file to services $services = collect(data_get($composeFile, 'services', [])); $services = $services->map(function ($service, $name) { $service['env_file'] = ['.env']; return $service; }); $composeFile['services'] = $services->toArray(); if (empty($composeFile)) { $this->application_deployment_queue->addLogEntry('Failed to parse docker-compose file.'); $this->fail('Failed to parse docker-compose file.'); return; } // Add build secrets to compose file if enabled and BuildKit is supported if ($this->application->settings->use_build_secrets && $this->dockerBuildkitSupported && ! empty($this->build_secrets)) { $composeFile = $this->add_build_secrets_to_compose($composeFile); } $yaml = Yaml::dump(convertToArray($composeFile), 10); } $this->docker_compose_base64 = base64_encode($yaml); $this->execute_remote_command([ executeInDocker($this->deployment_uuid, "echo '{$this->docker_compose_base64}' | base64 -d | tee {$this->workdir}{$this->docker_compose_location} > /dev/null"), 'hidden' => true, ]); // Modify Dockerfiles for ARGs and build secrets $this->modify_dockerfiles_for_compose($composeFile); // Build new container to limit downtime. $this->application_deployment_queue->addLogEntry('Pulling & building required images.'); // Save build-time .env file BEFORE the build $this->save_buildtime_environment_variables(); if ($this->docker_compose_custom_build_command) { // Auto-inject -f (compose file) and --env-file flags using helper function $build_command = injectDockerComposeFlags( $this->docker_compose_custom_build_command, "{$this->workdir}{$this->docker_compose_location}", self::BUILD_TIME_ENV_PATH ); // Prepend DOCKER_BUILDKIT=1 if BuildKit is supported if ($this->dockerBuildkitSupported) { $build_command = "DOCKER_BUILDKIT=1 {$build_command}"; } // Inject build arguments after build subcommand if not using build secrets if (! $this->application->settings->use_build_secrets && $this->build_args instanceof \Illuminate\Support\Collection && $this->build_args->isNotEmpty()) { $build_args_string = $this->build_args->implode(' '); // Escape single quotes for bash -c context used by executeInDocker $build_args_string = str_replace("'", "'\\''", $build_args_string); // Inject build args right after 'build' subcommand (not at the end) $original_command = $build_command; $build_command = injectDockerComposeBuildArgs($build_command, $build_args_string); // Only log if build args were actually injected (command was modified) if ($build_command !== $original_command) { $this->application_deployment_queue->addLogEntry('Adding build arguments to custom Docker Compose build command.'); } } $this->execute_remote_command( [executeInDocker($this->deployment_uuid, "cd {$this->basedir} && {$build_command}"), 'hidden' => true], ); } else { $command = "{$this->coolify_variables} docker compose";
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
true
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/CheckHelperImageJob.php
app/Jobs/CheckHelperImageJob.php
<?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Http; class CheckHelperImageJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $timeout = 1000; public function __construct() {} public function handle(): void { try { $response = Http::retry(3, 1000)->get(config('constants.coolify.versions_url')); if ($response->successful()) { $versions = $response->json(); $settings = instanceSettings(); $latest_version = data_get($versions, 'coolify.helper.version'); $current_version = $settings->helper_version; if (version_compare($latest_version, $current_version, '>')) { $settings->update(['helper_version' => $latest_version]); } } } catch (\Throwable $e) { send_internal_notification('CheckHelperImageJob failed with: '.$e->getMessage()); throw $e; } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/CleanupHelperContainersJob.php
app/Jobs/CleanupHelperContainersJob.php
<?php namespace App\Jobs; use App\Enums\ApplicationDeploymentStatus; use App\Models\ApplicationDeploymentQueue; use App\Models\Server; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class CleanupHelperContainersJob implements ShouldBeEncrypted, ShouldBeUnique, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public function __construct(public Server $server) {} public function handle(): void { try { // Get all active deployments on this server $activeDeployments = ApplicationDeploymentQueue::where('server_id', $this->server->id) ->whereIn('status', [ ApplicationDeploymentStatus::IN_PROGRESS->value, ApplicationDeploymentStatus::QUEUED->value, ]) ->pluck('deployment_uuid') ->toArray(); \Log::info('CleanupHelperContainersJob - Active deployments', [ 'server' => $this->server->name, 'active_deployment_uuids' => $activeDeployments, ]); $containers = instant_remote_process_with_timeout(['docker container ps --format \'{{json .}}\' | jq -s \'map(select(.Image | contains("'.config('constants.coolify.registry_url').'/coollabsio/coolify-helper")))\''], $this->server, false); $helperContainers = collect(json_decode($containers)); if ($helperContainers->count() > 0) { foreach ($helperContainers as $container) { $containerId = data_get($container, 'ID'); $containerName = data_get($container, 'Names'); // Check if this container belongs to an active deployment $isActiveDeployment = false; foreach ($activeDeployments as $deploymentUuid) { if (str_contains($containerName, $deploymentUuid)) { $isActiveDeployment = true; break; } } if ($isActiveDeployment) { \Log::info('CleanupHelperContainersJob - Skipping active deployment container', [ 'container' => $containerName, 'id' => $containerId, ]); continue; } \Log::info('CleanupHelperContainersJob - Removing orphaned helper container', [ 'container' => $containerName, 'id' => $containerId, ]); instant_remote_process_with_timeout(['docker container rm -f '.$containerId], $this->server, false); } } } catch (\Throwable $e) { send_internal_notification('CleanupHelperContainersJob failed with error: '.$e->getMessage()); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/VolumeCloneJob.php
app/Jobs/VolumeCloneJob.php
<?php namespace App\Jobs; use App\Models\LocalPersistentVolume; use App\Models\Server; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class VolumeCloneJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; protected string $cloneDir = '/data/coolify/clone'; public function __construct( protected string $sourceVolume, protected string $targetVolume, protected Server $sourceServer, protected ?Server $targetServer, protected LocalPersistentVolume $persistentVolume ) { $this->onQueue('high'); } public function handle() { try { if (! $this->targetServer || $this->targetServer->id === $this->sourceServer->id) { $this->cloneLocalVolume(); } else { $this->cloneRemoteVolume(); } } catch (\Exception $e) { \Log::error("Failed to copy volume data for {$this->sourceVolume}: ".$e->getMessage()); throw $e; } } protected function cloneLocalVolume() { instant_remote_process([ "docker volume create $this->targetVolume", "docker run --rm -v $this->sourceVolume:/source -v $this->targetVolume:/target alpine sh -c 'cp -a /source/. /target/ && chown -R 1000:1000 /target'", ], $this->sourceServer); } protected function cloneRemoteVolume() { $sourceCloneDir = "{$this->cloneDir}/{$this->sourceVolume}"; $targetCloneDir = "{$this->cloneDir}/{$this->targetVolume}"; try { instant_remote_process([ "mkdir -p $sourceCloneDir", "chmod 777 $sourceCloneDir", "docker run --rm -v $this->sourceVolume:/source -v $sourceCloneDir:/clone alpine sh -c 'cd /source && tar czf /clone/volume-data.tar.gz .'", ], $this->sourceServer); instant_remote_process([ "mkdir -p $targetCloneDir", "chmod 777 $targetCloneDir", ], $this->targetServer); instant_scp( "$sourceCloneDir/volume-data.tar.gz", "$targetCloneDir/volume-data.tar.gz", $this->sourceServer, $this->targetServer ); instant_remote_process([ "docker volume create $this->targetVolume", "docker run --rm -v $this->targetVolume:/target -v $targetCloneDir:/clone alpine sh -c 'cd /target && tar xzf /clone/volume-data.tar.gz && chown -R 1000:1000 /target'", ], $this->targetServer); } catch (\Exception $e) { \Log::error("Failed to clone volume {$this->sourceVolume} to {$this->targetVolume}: ".$e->getMessage()); throw $e; } finally { try { instant_remote_process([ "rm -rf $sourceCloneDir", ], $this->sourceServer, false); } catch (\Exception $e) { \Log::warning('Failed to clean up source server clone directory: '.$e->getMessage()); } try { if ($this->targetServer) { instant_remote_process([ "rm -rf $targetCloneDir", ], $this->targetServer, false); } } catch (\Exception $e) { \Log::warning('Failed to clean up target server clone directory: '.$e->getMessage()); } } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/CleanupOrphanedPreviewContainersJob.php
app/Jobs/CleanupOrphanedPreviewContainersJob.php
<?php namespace App\Jobs; use App\Models\ApplicationPreview; use App\Models\Server; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\Middleware\WithoutOverlapping; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Log; /** * Scheduled job to clean up orphaned PR preview containers. * * This job acts as a safety net for containers that weren't properly cleaned up * when a PR was closed (e.g., due to webhook failures, race conditions, etc.). * * It scans all functional servers for containers with the `coolify.pullRequestId` label * and removes any where the corresponding ApplicationPreview record no longer exists. */ class CleanupOrphanedPreviewContainersJob implements ShouldBeEncrypted, ShouldBeUnique, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $timeout = 600; // 10 minutes max public function __construct() {} public function middleware(): array { return [(new WithoutOverlapping('cleanup-orphaned-preview-containers'))->expireAfter(600)->dontRelease()]; } public function handle(): void { try { $servers = $this->getServersToCheck(); foreach ($servers as $server) { $this->cleanupOrphanedContainersOnServer($server); } } catch (\Throwable $e) { Log::error('CleanupOrphanedPreviewContainersJob failed: '.$e->getMessage()); send_internal_notification('CleanupOrphanedPreviewContainersJob failed with error: '.$e->getMessage()); } } /** * Get all functional servers to check for orphaned containers. */ private function getServersToCheck(): \Illuminate\Support\Collection { $query = Server::whereRelation('settings', 'is_usable', true) ->whereRelation('settings', 'is_reachable', true) ->where('ip', '!=', '1.2.3.4'); if (isCloud()) { $query = $query->whereRelation('team.subscription', 'stripe_invoice_paid', true); } return $query->get()->filter(fn ($server) => $server->isFunctional()); } /** * Find and clean up orphaned PR containers on a specific server. */ private function cleanupOrphanedContainersOnServer(Server $server): void { try { $prContainers = $this->getPRContainersOnServer($server); if ($prContainers->isEmpty()) { return; } $orphanedCount = 0; foreach ($prContainers as $container) { if ($this->isOrphanedContainer($container)) { $this->removeContainer($container, $server); $orphanedCount++; } } if ($orphanedCount > 0) { Log::info("CleanupOrphanedPreviewContainersJob - Removed {$orphanedCount} orphaned PR containers", [ 'server' => $server->name, ]); } } catch (\Throwable $e) { Log::warning("CleanupOrphanedPreviewContainersJob - Error on server {$server->name}: {$e->getMessage()}"); } } /** * Get all PR containers on a server (containers with pullRequestId > 0). */ private function getPRContainersOnServer(Server $server): \Illuminate\Support\Collection { try { $output = instant_remote_process([ "docker ps -a --filter 'label=coolify.pullRequestId' --format '{{json .}}'", ], $server, false); if (empty($output)) { return collect(); } return format_docker_command_output_to_json($output) ->filter(function ($container) { // Only include PR containers (pullRequestId > 0) $prId = $this->extractPullRequestId($container); return $prId !== null && $prId > 0; }); } catch (\Throwable $e) { Log::debug("Failed to get PR containers on server {$server->name}: {$e->getMessage()}"); return collect(); } } /** * Extract pull request ID from container labels. */ private function extractPullRequestId($container): ?int { $labels = data_get($container, 'Labels', ''); if (preg_match('/coolify\.pullRequestId=(\d+)/', $labels, $matches)) { return (int) $matches[1]; } return null; } /** * Extract application ID from container labels. */ private function extractApplicationId($container): ?int { $labels = data_get($container, 'Labels', ''); if (preg_match('/coolify\.applicationId=(\d+)/', $labels, $matches)) { return (int) $matches[1]; } return null; } /** * Check if a container is orphaned (no corresponding ApplicationPreview record). */ private function isOrphanedContainer($container): bool { $applicationId = $this->extractApplicationId($container); $pullRequestId = $this->extractPullRequestId($container); if ($applicationId === null || $pullRequestId === null) { return false; } // Check if ApplicationPreview record exists (including soft-deleted) $previewExists = ApplicationPreview::withTrashed() ->where('application_id', $applicationId) ->where('pull_request_id', $pullRequestId) ->exists(); // If preview exists (even soft-deleted), container should be handled by DeleteResourceJob // If preview doesn't exist at all, it's truly orphaned return ! $previewExists; } /** * Remove an orphaned container from the server. */ private function removeContainer($container, Server $server): void { $containerName = data_get($container, 'Names'); if (empty($containerName)) { Log::warning('CleanupOrphanedPreviewContainersJob - Cannot remove container: missing container name', [ 'container_data' => $container, 'server' => $server->name, ]); return; } $applicationId = $this->extractApplicationId($container); $pullRequestId = $this->extractPullRequestId($container); Log::info('CleanupOrphanedPreviewContainersJob - Removing orphaned container', [ 'container' => $containerName, 'application_id' => $applicationId, 'pull_request_id' => $pullRequestId, 'server' => $server->name, ]); $escapedContainerName = escapeshellarg($containerName); try { instant_remote_process( ["docker rm -f {$escapedContainerName}"], $server, false ); } catch (\Throwable $e) { Log::warning("Failed to remove orphaned container {$containerName}: {$e->getMessage()}"); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/SendMessageToSlackJob.php
app/Jobs/SendMessageToSlackJob.php
<?php namespace App\Jobs; use App\Notifications\Dto\SlackMessage; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Http; class SendMessageToSlackJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public function __construct( private SlackMessage $message, private string $webhookUrl ) { $this->onQueue('high'); } public function handle(): void { Http::post($this->webhookUrl, [ 'text' => $this->message->title, 'blocks' => [ [ 'type' => 'section', 'text' => [ 'type' => 'plain_text', 'text' => 'Coolify Notification', ], ], ], 'attachments' => [ [ 'color' => $this->message->color, 'blocks' => [ [ 'type' => 'header', 'text' => [ 'type' => 'plain_text', 'text' => $this->message->title, ], ], [ 'type' => 'section', 'text' => [ 'type' => 'mrkdwn', 'text' => $this->message->description, ], ], ], ], ], ]); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Jobs/SendMessageToDiscordJob.php
app/Jobs/SendMessageToDiscordJob.php
<?php namespace App\Jobs; use App\Notifications\Dto\DiscordMessage; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Http; class SendMessageToDiscordJob implements ShouldBeEncrypted, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * The number of times the job may be attempted. * * @var int */ public $tries = 5; public $backoff = 10; /** * The maximum number of unhandled exceptions to allow before failing. */ public int $maxExceptions = 5; public function __construct( public DiscordMessage $message, public string $webhookUrl ) { $this->onQueue('high'); } /** * Execute the job. */ public function handle(): void { Http::post($this->webhookUrl, $this->message->toPayload()); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/LayoutPopups.php
app/Livewire/LayoutPopups.php
<?php namespace App\Livewire; use Livewire\Component; class LayoutPopups extends Component { public function getListeners() { $teamId = auth()->user()->currentTeam()->id; return [ "echo-private:team.{$teamId},TestEvent" => 'testEvent', ]; } public function testEvent() { $this->dispatch('success', 'Realtime events configured!'); } public function render() { return view('livewire.layout-popups'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/GlobalSearch.php
app/Livewire/GlobalSearch.php
<?php namespace App\Livewire; use App\Models\Application; use App\Models\Environment; use App\Models\Project; use App\Models\Server; use App\Models\Service; use App\Models\StandaloneClickhouse; use App\Models\StandaloneDragonfly; use App\Models\StandaloneKeydb; use App\Models\StandaloneMariadb; use App\Models\StandaloneMongodb; use App\Models\StandaloneMysql; use App\Models\StandalonePostgresql; use App\Models\StandaloneRedis; use Illuminate\Support\Facades\Cache; use Livewire\Component; class GlobalSearch extends Component { public $searchQuery = ''; private $previousTrimmedQuery = ''; public $isModalOpen = false; public $searchResults = []; public $allSearchableItems = []; public $isCreateMode = false; public $creatableItems = []; public $autoOpenResource = null; // Resource selection state public $isSelectingResource = false; public $selectedResourceType = null; public $loadingServers = false; public $loadingProjects = false; public $loadingEnvironments = false; public $availableServers = []; public $availableProjects = []; public $availableEnvironments = []; public $selectedServerId = null; public $selectedDestinationUuid = null; public $selectedProjectUuid = null; public $selectedEnvironmentUuid = null; public $availableDestinations = []; public $loadingDestinations = false; public function mount() { $this->searchQuery = ''; $this->isModalOpen = false; $this->searchResults = []; $this->allSearchableItems = []; $this->isCreateMode = false; $this->creatableItems = []; $this->autoOpenResource = null; $this->isSelectingResource = false; } public function openSearchModal() { $this->isModalOpen = true; $this->loadSearchableItems(); $this->loadCreatableItems(); $this->dispatch('search-modal-opened'); } public function closeSearchModal() { $this->isModalOpen = false; $this->searchQuery = ''; $this->previousTrimmedQuery = ''; $this->searchResults = []; } public static function getCacheKey($teamId) { return 'global_search_items_'.$teamId; } public static function clearTeamCache($teamId) { Cache::forget(self::getCacheKey($teamId)); } public function updatedSearchQuery() { $trimmedQuery = trim($this->searchQuery); // If only spaces were added/removed, don't trigger a search if ($trimmedQuery === $this->previousTrimmedQuery) { return; } $this->previousTrimmedQuery = $trimmedQuery; // If search query is empty, just clear results without processing if (empty($trimmedQuery)) { $this->searchResults = []; $this->isCreateMode = false; $this->creatableItems = []; $this->autoOpenResource = null; $this->isSelectingResource = false; $this->cancelResourceSelection(); return; } $query = strtolower($trimmedQuery); // Reset keyboard navigation index $this->dispatch('reset-selected-index'); // Only enter create mode if query is exactly "new" or starts with "new " (space after) if ($query === 'new' || str_starts_with($query, 'new ')) { $this->isCreateMode = true; $this->loadCreatableItems(); // Check for sub-commands like "new project", "new server", etc. $detectedType = $this->detectSpecificResource($query); if ($detectedType) { $this->navigateToResource($detectedType); } else { // If no specific resource detected, reset selection state $this->cancelResourceSelection(); } // Also search for existing resources that match the query // This allows users to find resources with "new" in their name $this->search(); } else { $this->isCreateMode = false; $this->creatableItems = []; $this->autoOpenResource = null; $this->isSelectingResource = false; $this->search(); } } private function detectSpecificResource(string $query): ?string { // Map of keywords to resource types - order matters for multi-word matches $resourceMap = [ // Quick Actions 'new project' => 'project', 'new server' => 'server', 'new team' => 'team', 'new storage' => 'storage', 'new s3' => 'storage', 'new private key' => 'private-key', 'new privatekey' => 'private-key', 'new key' => 'private-key', 'new github app' => 'source', 'new github' => 'source', 'new source' => 'source', // Applications - Git-based 'new public' => 'public', 'new public git' => 'public', 'new public repo' => 'public', 'new public repository' => 'public', 'new private github' => 'private-gh-app', 'new private gh' => 'private-gh-app', 'new private deploy' => 'private-deploy-key', 'new deploy key' => 'private-deploy-key', // Applications - Docker-based 'new dockerfile' => 'dockerfile', 'new docker compose' => 'docker-compose-empty', 'new compose' => 'docker-compose-empty', 'new docker image' => 'docker-image', 'new image' => 'docker-image', // Databases 'new postgresql' => 'postgresql', 'new postgres' => 'postgresql', 'new mysql' => 'mysql', 'new mariadb' => 'mariadb', 'new redis' => 'redis', 'new keydb' => 'keydb', 'new dragonfly' => 'dragonfly', 'new mongodb' => 'mongodb', 'new mongo' => 'mongodb', 'new clickhouse' => 'clickhouse', ]; foreach ($resourceMap as $command => $type) { if ($query === $command) { // Check if user has permission for this resource type if ($this->canCreateResource($type)) { return $type; } } } return null; } private function canCreateResource(string $type): bool { $user = auth()->user(); // Quick Actions if (in_array($type, ['server', 'storage', 'private-key'])) { return $user->isAdmin() || $user->isOwner(); } if ($type === 'team') { return true; } // Applications, Databases, Services, and other resources if (in_array($type, [ 'project', 'source', // Applications 'public', 'private-gh-app', 'private-deploy-key', 'dockerfile', 'docker-compose-empty', 'docker-image', // Databases 'postgresql', 'mysql', 'mariadb', 'redis', 'keydb', 'dragonfly', 'mongodb', 'clickhouse', ]) || str_starts_with($type, 'one-click-service-')) { return $user->can('createAnyResource'); } return false; } private function loadSearchableItems() { // Try to get from Redis cache first $cacheKey = self::getCacheKey(auth()->user()->currentTeam()->id); $this->allSearchableItems = Cache::remember($cacheKey, 300, function () { ray()->showQueries(); $items = collect(); $team = auth()->user()->currentTeam(); // Get all applications $applications = Application::ownedByCurrentTeam() ->with(['environment.project']) ->get() ->map(function ($app) { // Collect all FQDNs from the application $fqdns = collect([]); // For regular applications if ($app->fqdn) { $fqdns = collect(explode(',', $app->fqdn))->map(fn ($fqdn) => trim($fqdn)); } // For docker compose based applications if ($app->build_pack === 'dockercompose' && $app->docker_compose_domains) { try { $composeDomains = json_decode($app->docker_compose_domains, true); if (is_array($composeDomains)) { foreach ($composeDomains as $serviceName => $domains) { if (is_array($domains)) { $fqdns = $fqdns->merge($domains); } } } } catch (\Exception $e) { // Ignore JSON parsing errors } } $fqdnsString = $fqdns->implode(' '); return [ 'id' => $app->id, 'name' => $app->name, 'type' => 'application', 'uuid' => $app->uuid, 'description' => $app->description, 'link' => $app->link(), 'project' => $app->environment->project->name ?? null, 'environment' => $app->environment->name ?? null, 'fqdns' => $fqdns->take(2)->implode(', '), // Show first 2 FQDNs in UI 'search_text' => strtolower($app->name.' '.$app->description.' '.$fqdnsString.' application applications app apps'), ]; }); // Get all services $services = Service::ownedByCurrentTeam() ->with(['environment.project', 'applications']) ->get() ->map(function ($service) { // Collect all FQDNs from service applications $fqdns = collect([]); foreach ($service->applications as $app) { if ($app->fqdn) { $appFqdns = collect(explode(',', $app->fqdn))->map(fn ($fqdn) => trim($fqdn)); $fqdns = $fqdns->merge($appFqdns); } } $fqdnsString = $fqdns->implode(' '); return [ 'id' => $service->id, 'name' => $service->name, 'type' => 'service', 'uuid' => $service->uuid, 'description' => $service->description, 'link' => $service->link(), 'project' => $service->environment->project->name ?? null, 'environment' => $service->environment->name ?? null, 'fqdns' => $fqdns->take(2)->implode(', '), // Show first 2 FQDNs in UI 'search_text' => strtolower($service->name.' '.$service->description.' '.$fqdnsString.' service services'), ]; }); // Get all standalone databases $databases = collect(); // PostgreSQL $databases = $databases->merge( StandalonePostgresql::ownedByCurrentTeam() ->with(['environment.project']) ->get() ->map(function ($db) { return [ 'id' => $db->id, 'name' => $db->name, 'type' => 'database', 'subtype' => 'postgresql', 'uuid' => $db->uuid, 'description' => $db->description, 'link' => $db->link(), 'project' => $db->environment->project->name ?? null, 'environment' => $db->environment->name ?? null, 'search_text' => strtolower($db->name.' postgresql '.$db->description.' database databases db'), ]; }) ); // MySQL $databases = $databases->merge( StandaloneMysql::ownedByCurrentTeam() ->with(['environment.project']) ->get() ->map(function ($db) { return [ 'id' => $db->id, 'name' => $db->name, 'type' => 'database', 'subtype' => 'mysql', 'uuid' => $db->uuid, 'description' => $db->description, 'link' => $db->link(), 'project' => $db->environment->project->name ?? null, 'environment' => $db->environment->name ?? null, 'search_text' => strtolower($db->name.' mysql '.$db->description.' database databases db'), ]; }) ); // MariaDB $databases = $databases->merge( StandaloneMariadb::ownedByCurrentTeam() ->with(['environment.project']) ->get() ->map(function ($db) { return [ 'id' => $db->id, 'name' => $db->name, 'type' => 'database', 'subtype' => 'mariadb', 'uuid' => $db->uuid, 'description' => $db->description, 'link' => $db->link(), 'project' => $db->environment->project->name ?? null, 'environment' => $db->environment->name ?? null, 'search_text' => strtolower($db->name.' mariadb '.$db->description.' database databases db'), ]; }) ); // MongoDB $databases = $databases->merge( StandaloneMongodb::ownedByCurrentTeam() ->with(['environment.project']) ->get() ->map(function ($db) { return [ 'id' => $db->id, 'name' => $db->name, 'type' => 'database', 'subtype' => 'mongodb', 'uuid' => $db->uuid, 'description' => $db->description, 'link' => $db->link(), 'project' => $db->environment->project->name ?? null, 'environment' => $db->environment->name ?? null, 'search_text' => strtolower($db->name.' mongodb '.$db->description.' database databases db'), ]; }) ); // Redis $databases = $databases->merge( StandaloneRedis::ownedByCurrentTeam() ->with(['environment.project']) ->get() ->map(function ($db) { return [ 'id' => $db->id, 'name' => $db->name, 'type' => 'database', 'subtype' => 'redis', 'uuid' => $db->uuid, 'description' => $db->description, 'link' => $db->link(), 'project' => $db->environment->project->name ?? null, 'environment' => $db->environment->name ?? null, 'search_text' => strtolower($db->name.' redis '.$db->description.' database databases db'), ]; }) ); // KeyDB $databases = $databases->merge( StandaloneKeydb::ownedByCurrentTeam() ->with(['environment.project']) ->get() ->map(function ($db) { return [ 'id' => $db->id, 'name' => $db->name, 'type' => 'database', 'subtype' => 'keydb', 'uuid' => $db->uuid, 'description' => $db->description, 'link' => $db->link(), 'project' => $db->environment->project->name ?? null, 'environment' => $db->environment->name ?? null, 'search_text' => strtolower($db->name.' keydb '.$db->description.' database databases db'), ]; }) ); // Dragonfly $databases = $databases->merge( StandaloneDragonfly::ownedByCurrentTeam() ->with(['environment.project']) ->get() ->map(function ($db) { return [ 'id' => $db->id, 'name' => $db->name, 'type' => 'database', 'subtype' => 'dragonfly', 'uuid' => $db->uuid, 'description' => $db->description, 'link' => $db->link(), 'project' => $db->environment->project->name ?? null, 'environment' => $db->environment->name ?? null, 'search_text' => strtolower($db->name.' dragonfly '.$db->description.' database databases db'), ]; }) ); // Clickhouse $databases = $databases->merge( StandaloneClickhouse::ownedByCurrentTeam() ->with(['environment.project']) ->get() ->map(function ($db) { return [ 'id' => $db->id, 'name' => $db->name, 'type' => 'database', 'subtype' => 'clickhouse', 'uuid' => $db->uuid, 'description' => $db->description, 'link' => $db->link(), 'project' => $db->environment->project->name ?? null, 'environment' => $db->environment->name ?? null, 'search_text' => strtolower($db->name.' clickhouse '.$db->description.' database databases db'), ]; }) ); // Get all servers $servers = Server::ownedByCurrentTeam() ->get() ->map(function ($server) { return [ 'id' => $server->id, 'name' => $server->name, 'type' => 'server', 'uuid' => $server->uuid, 'description' => $server->description, 'link' => $server->url(), 'project' => null, 'environment' => null, 'search_text' => strtolower($server->name.' '.$server->ip.' '.$server->description.' server servers'), ]; }); ray($servers); // Get all projects $projects = Project::ownedByCurrentTeam() ->withCount(['environments', 'applications', 'services']) ->get() ->map(function ($project) { $resourceCount = $project->applications_count + $project->services_count; $resourceSummary = $resourceCount > 0 ? "{$resourceCount} resource".($resourceCount !== 1 ? 's' : '') : 'No resources'; return [ 'id' => $project->id, 'name' => $project->name, 'type' => 'project', 'uuid' => $project->uuid, 'description' => $project->description, 'link' => $project->navigateTo(), 'project' => null, 'environment' => null, 'resource_count' => $resourceSummary, 'environment_count' => $project->environments_count, 'search_text' => strtolower($project->name.' '.$project->description.' project projects'), ]; }); // Get all environments $environments = Environment::ownedByCurrentTeam() ->with('project') ->withCount(['applications', 'services']) ->get() ->map(function ($environment) { $resourceCount = $environment->applications_count + $environment->services_count; $resourceSummary = $resourceCount > 0 ? "{$resourceCount} resource".($resourceCount !== 1 ? 's' : '') : 'No resources'; // Build description with project context $descriptionParts = []; if ($environment->project) { $descriptionParts[] = "Project: {$environment->project->name}"; } if ($environment->description) { $descriptionParts[] = $environment->description; } if (empty($descriptionParts)) { $descriptionParts[] = $resourceSummary; } return [ 'id' => $environment->id, 'name' => $environment->name, 'type' => 'environment', 'uuid' => $environment->uuid, 'description' => implode(' • ', $descriptionParts), 'link' => route('project.resource.index', [ 'project_uuid' => $environment->project->uuid, 'environment_uuid' => $environment->uuid, ]), 'project' => $environment->project->name ?? null, 'environment' => null, 'resource_count' => $resourceSummary, 'search_text' => strtolower($environment->name.' '.$environment->description.' '.$environment->project->name.' environment'), ]; }); // Add navigation routes $navigation = collect([ [ 'name' => 'Dashboard', 'type' => 'navigation', 'description' => 'Go to main dashboard', 'link' => route('dashboard'), 'search_text' => 'dashboard home main overview', ], [ 'name' => 'Servers', 'type' => 'navigation', 'description' => 'View all servers', 'link' => route('server.index'), 'search_text' => 'servers all list view', ], [ 'name' => 'Projects', 'type' => 'navigation', 'description' => 'View all projects', 'link' => route('project.index'), 'search_text' => 'projects all list view', ], [ 'name' => 'Destinations', 'type' => 'navigation', 'description' => 'View all destinations', 'link' => route('destination.index'), 'search_text' => 'destinations docker networks', ], [ 'name' => 'Security', 'type' => 'navigation', 'description' => 'Manage private keys and API tokens', 'link' => route('security.private-key.index'), 'search_text' => 'security private keys ssh api tokens cloud-init scripts', ], [ 'name' => 'Cloud-Init Scripts', 'type' => 'navigation', 'description' => 'Manage reusable cloud-init scripts', 'link' => route('security.cloud-init-scripts'), 'search_text' => 'cloud-init scripts cloud init cloudinit initialization startup server setup', ], [ 'name' => 'Sources', 'type' => 'navigation', 'description' => 'Manage GitHub apps and Git sources', 'link' => route('source.all'), 'search_text' => 'sources github apps git repositories', ], [ 'name' => 'Storages', 'type' => 'navigation', 'description' => 'Manage S3 storage for backups', 'link' => route('storage.index'), 'search_text' => 'storages s3 backups', ], [ 'name' => 'Shared Variables', 'type' => 'navigation', 'description' => 'View all shared variables', 'link' => route('shared-variables.index'), 'search_text' => 'shared variables environment all', ], [ 'name' => 'Team Shared Variables', 'type' => 'navigation', 'description' => 'Manage team-wide shared variables', 'link' => route('shared-variables.team.index'), 'search_text' => 'shared variables team environment', ], [ 'name' => 'Project Shared Variables', 'type' => 'navigation', 'description' => 'Manage project shared variables', 'link' => route('shared-variables.project.index'), 'search_text' => 'shared variables project environment', ], [ 'name' => 'Environment Shared Variables', 'type' => 'navigation', 'description' => 'Manage environment shared variables', 'link' => route('shared-variables.environment.index'), 'search_text' => 'shared variables environment', ], [ 'name' => 'Tags', 'type' => 'navigation', 'description' => 'View resources by tags', 'link' => route('tags.show'), 'search_text' => 'tags labels organize', ], [ 'name' => 'Terminal', 'type' => 'navigation', 'description' => 'Access server terminal', 'link' => route('terminal'), 'search_text' => 'terminal ssh console shell command line', ], [ 'name' => 'Profile', 'type' => 'navigation', 'description' => 'Manage your profile and preferences', 'link' => route('profile'), 'search_text' => 'profile account user settings preferences', ], [ 'name' => 'Team', 'type' => 'navigation', 'description' => 'Manage team members and settings', 'link' => route('team.index'), 'search_text' => 'team settings members users invitations', ], [ 'name' => 'Notifications', 'type' => 'navigation', 'description' => 'Configure email, Discord, Telegram notifications', 'link' => route('notifications.email'), 'search_text' => 'notifications alerts email discord telegram slack pushover', ], ]); // Add instance settings only for self-hosted and root team if (! isCloud() && $team->id === 0) { $navigation->push([ 'name' => 'Settings', 'type' => 'navigation', 'description' => 'Instance settings and configuration', 'link' => route('settings.index'), 'search_text' => 'settings configuration instance', ]); } // Merge all collections $items = $items->merge($navigation) ->merge($applications) ->merge($services) ->merge($databases) ->merge($servers) ->merge($projects) ->merge($environments); return $items->toArray(); }); } private function search() { if (strlen($this->searchQuery) < 1) { $this->searchResults = []; return; } $query = strtolower($this->searchQuery); // Detect resource category queries $categoryMapping = [ 'server' => ['server', 'type' => 'server'], 'servers' => ['server', 'type' => 'server'], 'app' => ['application', 'type' => 'application'], 'apps' => ['application', 'type' => 'application'], 'application' => ['application', 'type' => 'application'], 'applications' => ['application', 'type' => 'application'], 'db' => ['database', 'type' => 'standalone-postgresql'], 'database' => ['database', 'type' => 'standalone-postgresql'], 'databases' => ['database', 'type' => 'standalone-postgresql'], 'service' => ['service', 'category' => 'Services'], 'services' => ['service', 'category' => 'Services'], 'project' => ['project', 'type' => 'project'], 'projects' => ['project', 'type' => 'project'], ]; $priorityCreatableItem = null; // Check if query matches a resource category if (isset($categoryMapping[$query])) { $this->loadCreatableItems(); $mapping = $categoryMapping[$query]; // Find the matching creatable item $priorityCreatableItem = collect($this->creatableItems) ->first(function ($item) use ($mapping) { if (isset($mapping['type'])) { return $item['type'] === $mapping['type']; } if (isset($mapping['category'])) { return isset($item['category']) && $item['category'] === $mapping['category']; } return false; }); if ($priorityCreatableItem) { $priorityCreatableItem['is_creatable_suggestion'] = true; } } // Search for matching creatable resources to show as suggestions (if no priority item) if (! $priorityCreatableItem) { $this->loadCreatableItems(); // Search in regular creatable items (apps, databases, quick actions) $creatableSuggestions = collect($this->creatableItems) ->filter(function ($item) use ($query) { $searchText = strtolower($item['name'].' '.$item['description'].' '.($item['type'] ?? '')); // Use word boundary matching to avoid substring matches (e.g., "wordpress" shouldn't match "classicpress") return preg_match('/\b'.preg_quote($query, '/').'/i', $searchText); })
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
true
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/NavbarDeleteTeam.php
app/Livewire/NavbarDeleteTeam.php
<?php namespace App\Livewire; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use Livewire\Component; class NavbarDeleteTeam extends Component { public $team; public function mount() { $this->team = currentTeam()->name; } public function delete($password) { if (! verifyPasswordConfirmation($password, $this)) { return; } $currentTeam = currentTeam(); $currentTeam->delete(); $currentTeam->members->each(function ($user) use ($currentTeam) { if ($user->id === Auth::id()) { return; } $user->teams()->detach($currentTeam); $session = DB::table('sessions')->where('user_id', $user->id)->first(); if ($session) { DB::table('sessions')->where('id', $session->id)->delete(); } }); refreshSession(); return redirectRoute($this, 'team.index'); } public function render() { return view('livewire.navbar-delete-team'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/DeploymentsIndicator.php
app/Livewire/DeploymentsIndicator.php
<?php namespace App\Livewire; use App\Models\ApplicationDeploymentQueue; use App\Models\Server; use Livewire\Attributes\Computed; use Livewire\Component; class DeploymentsIndicator extends Component { public bool $expanded = false; #[Computed] public function deployments() { $servers = Server::ownedByCurrentTeamCached(); return ApplicationDeploymentQueue::with(['application.environment.project']) ->whereIn('status', ['in_progress', 'queued']) ->whereIn('server_id', $servers->pluck('id')) ->orderBy('id') ->get([ 'id', 'application_id', 'application_name', 'deployment_url', 'pull_request_id', 'server_name', 'server_id', 'status', ]); } #[Computed] public function deploymentCount() { return $this->deployments->count(); } #[Computed] public function shouldReduceOpacity(): bool { return request()->routeIs('project.application.deployment.*'); } public function toggleExpanded() { $this->expanded = ! $this->expanded; } public function render() { return view('livewire.deployments-indicator'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/VerifyEmail.php
app/Livewire/VerifyEmail.php
<?php namespace App\Livewire; use DanHarrin\LivewireRateLimiting\WithRateLimiting; use Livewire\Component; class VerifyEmail extends Component { use WithRateLimiting; public function again() { try { $this->rateLimit(1, 300); auth()->user()->sendVerificationEmail(); $this->dispatch('success', 'Email verification link sent!'); } catch (\Exception $e) { return handleError($e, $this); } } public function render() { return view('livewire.verify-email'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Upgrade.php
app/Livewire/Upgrade.php
<?php namespace App\Livewire; use App\Actions\Server\UpdateCoolify; use App\Models\InstanceSettings; use App\Models\Server; use Livewire\Component; class Upgrade extends Component { public bool $updateInProgress = false; public bool $isUpgradeAvailable = false; public string $latestVersion = ''; public string $currentVersion = ''; public bool $devMode = false; protected $listeners = ['updateAvailable' => 'checkUpdate']; public function mount() { $this->currentVersion = config('constants.coolify.version'); $this->devMode = isDev(); } public function checkUpdate() { try { $this->latestVersion = get_latest_version_of_coolify(); $this->currentVersion = config('constants.coolify.version'); $this->isUpgradeAvailable = data_get(InstanceSettings::get(), 'new_version_available', false); if (isDev()) { $this->isUpgradeAvailable = true; } } catch (\Throwable $e) { return handleError($e, $this); } } public function upgrade() { try { if ($this->updateInProgress) { return; } $this->updateInProgress = true; UpdateCoolify::run(manual_update: true); } catch (\Throwable $e) { return handleError($e, $this); } } public function getUpgradeStatus(): array { // Only root team members can view upgrade status if (auth()->user()?->currentTeam()?->id !== 0) { return ['status' => 'none']; } $server = Server::find(0); if (! $server) { return ['status' => 'none']; } $statusFile = '/data/coolify/source/.upgrade-status'; try { $content = instant_remote_process( ["cat {$statusFile} 2>/dev/null || echo ''"], $server, false ); $content = trim($content ?? ''); } catch (\Throwable $e) { return ['status' => 'none']; } if (empty($content)) { return ['status' => 'none']; } $parts = explode('|', $content); if (count($parts) < 3) { return ['status' => 'none']; } [$step, $message, $timestamp] = $parts; // Check if status is stale (older than 10 minutes) try { $statusTime = new \DateTime($timestamp); $now = new \DateTime; $diffMinutes = ($now->getTimestamp() - $statusTime->getTimestamp()) / 60; if ($diffMinutes > 10) { return ['status' => 'none']; } } catch (\Throwable $e) { return ['status' => 'none']; } if ($step === 'error') { return [ 'status' => 'error', 'step' => 0, 'message' => $message, ]; } $stepInt = (int) $step; $status = $stepInt >= 6 ? 'complete' : 'in_progress'; return [ 'status' => $status, 'step' => $stepInt, 'message' => $message, ]; } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Dashboard.php
app/Livewire/Dashboard.php
<?php namespace App\Livewire; use App\Models\PrivateKey; use App\Models\Project; use App\Models\Server; use Illuminate\Support\Collection; use Livewire\Component; class Dashboard extends Component { public Collection $projects; public Collection $servers; public Collection $privateKeys; public function mount() { $this->privateKeys = PrivateKey::ownedByCurrentTeamCached(); $this->servers = Server::ownedByCurrentTeamCached(); $this->projects = Project::ownedByCurrentTeam()->with('environments')->get(); } public function render() { return view('livewire.dashboard'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/SettingsBackup.php
app/Livewire/SettingsBackup.php
<?php namespace App\Livewire; use App\Models\InstanceSettings; use App\Models\S3Storage; use App\Models\ScheduledDatabaseBackup; use App\Models\Server; use App\Models\StandalonePostgresql; use Livewire\Attributes\Locked; use Livewire\Attributes\Validate; use Livewire\Component; class SettingsBackup extends Component { public InstanceSettings $settings; public Server $server; public ?StandalonePostgresql $database = null; public ScheduledDatabaseBackup|null|array $backup = []; #[Locked] public $s3s; #[Locked] public $executions = []; #[Validate(['required'])] public string $uuid; #[Validate(['required'])] public string $name; #[Validate(['nullable'])] public ?string $description = null; #[Validate(['required'])] public string $postgres_user; #[Validate(['required'])] public string $postgres_password; public function mount() { if (! isInstanceAdmin()) { return redirect()->route('dashboard'); } $settings = instanceSettings(); $this->server = Server::findOrFail(0); $this->database = StandalonePostgresql::whereName('coolify-db')->first(); $s3s = S3Storage::whereTeamId(0)->get() ?? []; if ($this->database) { $this->uuid = $this->database->uuid; $this->name = $this->database->name; $this->description = $this->database->description; $this->postgres_user = $this->database->postgres_user; $this->postgres_password = $this->database->postgres_password; if ($this->database->status !== 'running') { $this->database->status = 'running'; $this->database->save(); } $this->backup = $this->database->scheduledBackups->first(); if ($this->backup && ! $this->server->isFunctional()) { $this->backup->enabled = false; $this->backup->save(); } $this->executions = $this->backup->executions; } $this->settings = $settings; $this->s3s = $s3s; } public function addCoolifyDatabase() { try { $server = Server::findOrFail(0); $out = instant_remote_process(['docker inspect coolify-db'], $server); $envs = format_docker_envs_to_json($out); $postgres_password = $envs['POSTGRES_PASSWORD']; $postgres_user = $envs['POSTGRES_USER']; $postgres_db = $envs['POSTGRES_DB']; $this->database = StandalonePostgresql::create([ 'id' => 0, 'name' => 'coolify-db', 'description' => 'Coolify database', 'postgres_user' => $postgres_user, 'postgres_password' => $postgres_password, 'postgres_db' => $postgres_db, 'status' => 'running', 'destination_type' => \App\Models\StandaloneDocker::class, 'destination_id' => 0, ]); $this->backup = ScheduledDatabaseBackup::create([ 'id' => 0, 'enabled' => true, 'save_s3' => false, 'frequency' => '0 0 * * *', 'database_id' => $this->database->id, 'database_type' => \App\Models\StandalonePostgresql::class, 'team_id' => currentTeam()->id, ]); $this->database->refresh(); $this->backup->refresh(); $this->s3s = S3Storage::whereTeamId(0)->get(); $this->uuid = $this->database->uuid; $this->name = $this->database->name; $this->description = $this->database->description; $this->postgres_user = $this->database->postgres_user; $this->postgres_password = $this->database->postgres_password; $this->executions = $this->backup->executions; } catch (\Exception $e) { return handleError($e, $this); } } public function submit() { $this->validate(); $this->database->update([ 'name' => $this->name, 'description' => $this->description, 'postgres_user' => $this->postgres_user, 'postgres_password' => $this->postgres_password, ]); $this->dispatch('success', 'Backup updated.'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/SwitchTeam.php
app/Livewire/SwitchTeam.php
<?php namespace App\Livewire; use App\Models\Team; use Livewire\Component; class SwitchTeam extends Component { public string $selectedTeamId = 'default'; public function mount() { $this->selectedTeamId = auth()->user()->currentTeam()->id; } public function updatedSelectedTeamId() { $this->switch_to($this->selectedTeamId); } public function switch_to($team_id) { if (! auth()->user()->teams->contains($team_id)) { return; } $team_to_switch_to = Team::find($team_id); if (! $team_to_switch_to) { return; } refreshSession($team_to_switch_to); return redirect('dashboard'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/Help.php
app/Livewire/Help.php
<?php namespace App\Livewire; use DanHarrin\LivewireRateLimiting\WithRateLimiting; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Support\Facades\Http; use Livewire\Attributes\Validate; use Livewire\Component; class Help extends Component { use WithRateLimiting; #[Validate(['required', 'min:10', 'max:1000'])] public string $description; #[Validate(['required', 'min:3'])] public string $subject; public function submit() { try { $this->validate(); $this->rateLimit(3, 30); $settings = instanceSettings(); $mail = new MailMessage; $mail->view( 'emails.help', [ 'description' => $this->description, ] ); $mail->subject("[HELP]: {$this->subject}"); $type = set_transanctional_email_settings($settings); // Sending feedback through Cloud API if (blank($type)) { $url = 'https://app.coolify.io/api/feedback'; Http::post($url, [ 'content' => 'User: `'.auth()->user()?->email.'` with subject: `'.$this->subject.'` has the following problem: `'.$this->description.'`', ]); } else { send_user_an_email($mail, auth()->user()?->email, 'feedback@coollabs.io'); } $this->dispatch('success', 'Feedback sent.', 'We will get in touch with you as soon as possible.'); $this->reset('description', 'subject'); } catch (\Throwable $e) { return handleError($e, $this); } } public function render() { return view('livewire.help')->layout('layouts.app'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/SettingsOauth.php
app/Livewire/SettingsOauth.php
<?php namespace App\Livewire; use App\Models\OauthSetting; use Livewire\Component; class SettingsOauth extends Component { public $oauth_settings_map; protected function rules() { return OauthSetting::all()->reduce(function ($carry, $setting) { $carry["oauth_settings_map.$setting->provider.enabled"] = 'required'; $carry["oauth_settings_map.$setting->provider.client_id"] = 'nullable'; $carry["oauth_settings_map.$setting->provider.client_secret"] = 'nullable'; $carry["oauth_settings_map.$setting->provider.redirect_uri"] = 'nullable'; $carry["oauth_settings_map.$setting->provider.tenant"] = 'nullable'; $carry["oauth_settings_map.$setting->provider.base_url"] = 'nullable'; return $carry; }, []); } public function mount() { if (! isInstanceAdmin()) { return redirect()->route('home'); } $this->oauth_settings_map = OauthSetting::all()->sortBy('provider')->reduce(function ($carry, $setting) { $carry[$setting->provider] = [ 'id' => $setting->id, 'provider' => $setting->provider, 'enabled' => $setting->enabled, 'client_id' => $setting->client_id, 'client_secret' => $setting->client_secret, 'redirect_uri' => $setting->redirect_uri, 'tenant' => $setting->tenant, 'base_url' => $setting->base_url, ]; return $carry; }, []); } private function updateOauthSettings(?string $provider = null) { if ($provider) { $oauthData = $this->oauth_settings_map[$provider]; $oauth = OauthSetting::find($oauthData['id']); if (! $oauth) { throw new \Exception('OAuth setting for '.$provider.' not found. It may have been deleted.'); } $oauth->fill([ 'enabled' => $oauthData['enabled'], 'client_id' => $oauthData['client_id'], 'client_secret' => $oauthData['client_secret'], 'redirect_uri' => $oauthData['redirect_uri'], 'tenant' => $oauthData['tenant'], 'base_url' => $oauthData['base_url'], ]); if (! $oauth->couldBeEnabled()) { $oauth->update(['enabled' => false]); throw new \Exception('OAuth settings are not complete for '.$oauth->provider.'.<br/>Please fill in all required fields.'); } $oauth->save(); // Update the array with fresh data $this->oauth_settings_map[$provider] = [ 'id' => $oauth->id, 'provider' => $oauth->provider, 'enabled' => $oauth->enabled, 'client_id' => $oauth->client_id, 'client_secret' => $oauth->client_secret, 'redirect_uri' => $oauth->redirect_uri, 'tenant' => $oauth->tenant, 'base_url' => $oauth->base_url, ]; $this->dispatch('success', 'OAuth settings for '.$oauth->provider.' updated successfully!'); } else { $errors = []; foreach (array_values($this->oauth_settings_map) as $settingData) { $oauth = OauthSetting::find($settingData['id']); if (! $oauth) { $errors[] = "OAuth setting for provider '{$settingData['provider']}' not found. It may have been deleted."; continue; } $oauth->fill([ 'enabled' => $settingData['enabled'], 'client_id' => $settingData['client_id'], 'client_secret' => $settingData['client_secret'], 'redirect_uri' => $settingData['redirect_uri'], 'tenant' => $settingData['tenant'], 'base_url' => $settingData['base_url'], ]); if ($settingData['enabled'] && ! $oauth->couldBeEnabled()) { $oauth->enabled = false; $errors[] = "OAuth settings are incomplete for '{$oauth->provider}'. Required fields are missing. The provider has been disabled."; } $oauth->save(); // Update the array with fresh data $this->oauth_settings_map[$oauth->provider] = [ 'id' => $oauth->id, 'provider' => $oauth->provider, 'enabled' => $oauth->enabled, 'client_id' => $oauth->client_id, 'client_secret' => $oauth->client_secret, 'redirect_uri' => $oauth->redirect_uri, 'tenant' => $oauth->tenant, 'base_url' => $oauth->base_url, ]; } if (! empty($errors)) { $this->dispatch('error', implode('<br/>', $errors)); } } } public function instantSave(string $provider) { try { $this->updateOauthSettings($provider); } catch (\Exception $e) { return handleError($e, $this); } } public function submit() { $this->updateOauthSettings(); $this->dispatch('success', 'Instance settings updated successfully!'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/MonacoEditor.php
app/Livewire/MonacoEditor.php
<?php namespace App\Livewire; // use Livewire\Component; use Illuminate\View\Component; use Visus\Cuid2\Cuid2; class MonacoEditor extends Component { protected $listeners = [ 'configurationChanged' => '$refresh', ]; public function __construct( public ?string $id, public ?string $name, public ?string $type, public ?string $monacoContent, public ?string $value, public ?string $label, public ?string $placeholder, public bool $required, public bool $disabled, public bool $readonly, public bool $allowTab, public bool $spellcheck, public bool $autofocus, public ?string $helper, public bool $realtimeValidation, public bool $allowToPeak, public string $defaultClass, public string $defaultClassInput, public ?string $language ) { // } public function render() { if (is_null($this->id)) { $this->id = new Cuid2; } if (is_null($this->name)) { $this->name = $this->id; } return view('components.forms.monaco-editor'); } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/SettingsEmail.php
app/Livewire/SettingsEmail.php
<?php namespace App\Livewire; use App\Models\InstanceSettings; use App\Models\Team; use App\Notifications\TransactionalEmails\Test; use Illuminate\Support\Facades\RateLimiter; use Livewire\Attributes\Locked; use Livewire\Attributes\Validate; use Livewire\Component; class SettingsEmail extends Component { public InstanceSettings $settings; #[Locked] public Team $team; #[Validate(['boolean'])] public bool $smtpEnabled = false; #[Validate(['nullable', 'email'])] public ?string $smtpFromAddress = null; #[Validate(['nullable', 'string'])] public ?string $smtpFromName = null; #[Validate(['nullable', 'string'])] public ?string $smtpRecipients = null; #[Validate(['nullable', 'string'])] public ?string $smtpHost = null; #[Validate(['nullable', 'numeric', 'min:1', 'max:65535'])] public ?int $smtpPort = null; #[Validate(['nullable', 'string', 'in:starttls,tls,none'])] public ?string $smtpEncryption = 'starttls'; #[Validate(['nullable', 'string'])] public ?string $smtpUsername = null; #[Validate(['nullable', 'string'])] public ?string $smtpPassword = null; #[Validate(['nullable', 'numeric'])] public ?int $smtpTimeout = null; #[Validate(['boolean'])] public bool $resendEnabled = false; #[Validate(['nullable', 'string'])] public ?string $resendApiKey = null; #[Validate(['nullable', 'email'])] public ?string $testEmailAddress = null; public function mount() { if (isInstanceAdmin() === false) { return redirect()->route('dashboard'); } $this->settings = instanceSettings(); $this->syncData(); $this->team = auth()->user()->currentTeam(); $this->testEmailAddress = auth()->user()->email; } public function syncData(bool $toModel = false) { if ($toModel) { $this->validate(); $this->settings->smtp_enabled = $this->smtpEnabled; $this->settings->smtp_host = $this->smtpHost; $this->settings->smtp_port = $this->smtpPort; $this->settings->smtp_encryption = $this->smtpEncryption; $this->settings->smtp_username = $this->smtpUsername; $this->settings->smtp_password = $this->smtpPassword; $this->settings->smtp_timeout = $this->smtpTimeout; $this->settings->smtp_from_address = $this->smtpFromAddress; $this->settings->smtp_from_name = $this->smtpFromName; $this->settings->resend_enabled = $this->resendEnabled; $this->settings->resend_api_key = $this->resendApiKey; $this->settings->save(); } else { $this->smtpEnabled = $this->settings->smtp_enabled; $this->smtpHost = $this->settings->smtp_host; $this->smtpPort = $this->settings->smtp_port; $this->smtpEncryption = $this->settings->smtp_encryption; $this->smtpUsername = $this->settings->smtp_username; $this->smtpPassword = $this->settings->smtp_password; $this->smtpTimeout = $this->settings->smtp_timeout; $this->smtpFromAddress = $this->settings->smtp_from_address; $this->smtpFromName = $this->settings->smtp_from_name; $this->resendEnabled = $this->settings->resend_enabled; $this->resendApiKey = $this->settings->resend_api_key; } } public function submit() { try { $this->resetErrorBag(); $this->syncData(true); $this->dispatch('success', 'Transactional email settings updated.'); } catch (\Throwable $e) { return handleError($e, $this); } } public function instantSave(string $type) { try { $currentSmtpEnabled = $this->settings->smtp_enabled; $currentResendEnabled = $this->settings->resend_enabled; $this->resetErrorBag(); if ($type === 'SMTP') { $this->submitSmtp(); $this->resendEnabled = $this->settings->resend_enabled = false; } elseif ($type === 'Resend') { $this->submitResend(); $this->smtpEnabled = $this->settings->smtp_enabled = false; } $this->settings->save(); } catch (\Throwable $e) { if ($type === 'SMTP') { $this->smtpEnabled = $currentSmtpEnabled; } elseif ($type === 'Resend') { $this->resendEnabled = $currentResendEnabled; } return handleError($e, $this); } } public function submitSmtp() { try { $this->validate([ 'smtpEnabled' => 'boolean', 'smtpFromAddress' => 'required|email', 'smtpFromName' => 'required|string', 'smtpHost' => 'required|string', 'smtpPort' => 'required|numeric', 'smtpEncryption' => 'required|string|in:starttls,tls,none', 'smtpUsername' => 'nullable|string', 'smtpPassword' => 'nullable|string', 'smtpTimeout' => 'nullable|numeric', ], [ 'smtpFromAddress.required' => 'From Address is required.', 'smtpFromAddress.email' => 'Please enter a valid email address.', 'smtpFromName.required' => 'From Name is required.', 'smtpHost.required' => 'SMTP Host is required.', 'smtpPort.required' => 'SMTP Port is required.', 'smtpPort.numeric' => 'SMTP Port must be a number.', 'smtpEncryption.required' => 'Encryption type is required.', ]); $this->settings->smtp_enabled = $this->smtpEnabled; $this->settings->smtp_host = $this->smtpHost; $this->settings->smtp_port = $this->smtpPort; $this->settings->smtp_encryption = $this->smtpEncryption; $this->settings->smtp_username = $this->smtpUsername; $this->settings->smtp_password = $this->smtpPassword; $this->settings->smtp_timeout = $this->smtpTimeout; $this->settings->smtp_from_address = $this->smtpFromAddress; $this->settings->smtp_from_name = $this->smtpFromName; $this->settings->save(); $this->dispatch('success', 'SMTP settings updated.'); } catch (\Throwable $e) { $this->smtpEnabled = false; return handleError($e, $this); } } public function submitResend() { try { $this->validate([ 'resendEnabled' => 'boolean', 'resendApiKey' => 'required|string', 'smtpFromAddress' => 'required|email', 'smtpFromName' => 'required|string', ], [ 'resendApiKey.required' => 'Resend API Key is required.', 'smtpFromAddress.required' => 'From Address is required.', 'smtpFromAddress.email' => 'Please enter a valid email address.', 'smtpFromName.required' => 'From Name is required.', ]); $this->settings->resend_enabled = $this->resendEnabled; $this->settings->resend_api_key = $this->resendApiKey; $this->settings->smtp_from_address = $this->smtpFromAddress; $this->settings->smtp_from_name = $this->smtpFromName; $this->settings->save(); $this->dispatch('success', 'Resend settings updated.'); } catch (\Throwable $e) { $this->resendEnabled = false; return handleError($e, $this); } } public function sendTestEmail() { try { $this->validate([ 'testEmailAddress' => 'required|email', ], [ 'testEmailAddress.required' => 'Test email address is required.', 'testEmailAddress.email' => 'Please enter a valid email address.', ]); $executed = RateLimiter::attempt( 'test-email:'.$this->team->id, $perMinute = 0, function () { $this->team?->notifyNow(new Test($this->testEmailAddress)); $this->dispatch('success', 'Test Email sent.'); }, $decaySeconds = 10, ); if (! $executed) { throw new \Exception('Too many messages sent!'); } } catch (\Throwable $e) { return handleError($e, $this); } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false
coollabsio/coolify
https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Livewire/ActivityMonitor.php
app/Livewire/ActivityMonitor.php
<?php namespace App\Livewire; use App\Models\User; use Livewire\Component; use Spatie\Activitylog\Models\Activity; class ActivityMonitor extends Component { public ?string $header = null; public $activityId = null; public $eventToDispatch = 'activityFinished'; public $eventData = null; public $isPollingActive = false; public bool $fullHeight = false; public $activity; public bool $showWaiting = true; public static $eventDispatched = false; protected $listeners = ['activityMonitor' => 'newMonitorActivity']; public function newMonitorActivity($activityId, $eventToDispatch = 'activityFinished', $eventData = null, $header = null) { // Reset event dispatched flag for new activity self::$eventDispatched = false; $this->activityId = $activityId; $this->eventToDispatch = $eventToDispatch; $this->eventData = $eventData; // Update header if provided if ($header !== null) { $this->header = $header; } $this->hydrateActivity(); $this->isPollingActive = true; } public function hydrateActivity() { if ($this->activityId === null) { $this->activity = null; return; } $this->activity = Activity::find($this->activityId); } public function updatedActivityId($value) { if ($value) { $this->hydrateActivity(); $this->isPollingActive = true; self::$eventDispatched = false; } } public function polling() { $this->hydrateActivity(); $exit_code = data_get($this->activity, 'properties.exitCode'); if ($exit_code !== null) { $this->isPollingActive = false; if ($exit_code === 0) { if ($this->eventToDispatch !== null) { if (str($this->eventToDispatch)->startsWith('App\\Events\\')) { $causer_id = data_get($this->activity, 'causer_id'); $user = User::find($causer_id); if ($user) { $teamId = $user->currentTeam()->id; if (! self::$eventDispatched) { if (filled($this->eventData)) { $this->eventToDispatch::dispatch($teamId, $this->eventData); } else { $this->eventToDispatch::dispatch($teamId); } self::$eventDispatched = true; } } return; } if (! self::$eventDispatched) { if (filled($this->eventData)) { $this->dispatch($this->eventToDispatch, $this->eventData); } else { $this->dispatch($this->eventToDispatch); } self::$eventDispatched = true; } } } } } }
php
Apache-2.0
f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53
2026-01-04T15:02:34.115123Z
false