Your IP : 216.73.216.189


Current Path : /proc/thread-self/root/snap/lxd/current/share/lxd-ui/assets/
Upload File :
Current File : //proc/thread-self/root/snap/lxd/current/share/lxd-ui/assets/CreateInstance-C0sO_I_E.js

import{r as v,I as je,b as Se,j as e,d as s,Q as Fe,H as Oe,S as Ue,x as Ae,T as ne,U as _e,V as J,J as oe,t as re,c as le,K as ie,k as ce,f as ue,W as de,s as Ie,X as Me,y as te,R as Y,Y as Ne,Z as me,w as X,_ as Re,$ as Pe,p as Te,a0 as pe,a1 as Ve,h as Be,a2 as Ge,a3 as De,a4 as $e}from"./index-BFGypnt-.js";import{l as ke,b as ze,L as ee,i as ae,a as se,c as he}from"./images-C6WqBeZG.js";import{M as ge,Y as Z,I as qe,D as fe,N as Ke,G as Ye,P as Qe,O as We,R as He,S as Xe,a as Je,b as Ze,B as et,C as tt,c as at,d as st,y as nt,o as ot}from"./YamlSwitch-BQqYYI1i.js";import{P as rt}from"./ProfileSelector-CI2l1cmT.js";import{g as lt}from"./architectures-BcTUUUGa.js";import{u as it,a as ct,c as ut,m as dt,i as mt}from"./useImages-DavKpFTt.js";import{b as pt}from"./useClusterGroups-BlRzika4.js";import{u as ht}from"./usePlacementGroups-C9iFT3T3.js";import{u as Ee}from"./useClusterMembers-B29_ixY7.js";import{P as gt,C as ft,S as bt,h as vt,a as Ct,b as be,D as xt,N as yt,G as jt,c as St,O as Ft,R as It,d as Nt,I as Rt,M as Pt,B as Tt,e as Et,f as wt}from"./NetworkDevicePanel-DHptDuuK.js";import{P as Lt}from"./PlacementGroupForm-CiijupxS.js";import{A as Ot}from"./AutoExpandingTextArea-WEdimI5c.js";import{S as Ut}from"./ScrollableForm-D-7nf2YI.js";import{P as At}from"./ProgressBar-BgH9rTvH.js";import{S as we}from"./StoragePoolSelector-CIzPJc24.js";import{C as _t}from"./ClusterMemberSelector-Bokudnyt.js";import{r as Mt,s as Vt,c as Bt,b as Gt,m as Dt,a as $t,d as kt,e as zt,f as qt,i as Kt}from"./instanceAndProfilePayloads-DSYCnS-r.js";import{B as Yt}from"./BaseLayout-ft99KK4_.js";import{F as Qt}from"./FormFooterLayout-CMGxv4XX.js";import{Y as Wt}from"./NetworkDefaultACLSelector-C5Ak_9zq.js";import{u as Ht}from"./useProfiles-CErbukD2.js";import{u as Xt,p as ve}from"./usePanelParams-CV5ZHNeu.js";import"./FormMenuItem-fhYfVpHc.js";import"./image-registries-YAuyq4CZ.js";import"./cluster-members-CG6XHzn4.js";import"./scroll-Dc7Cgzms.js";import"./ProfileRichChip-XiLIeCE5.js";import"./ProfileResourceLimits-DkY60ueM.js";import"./ConfigurationTable-CmO6jSmV.js";import"./ConfigFieldDescription-CY0sdTp6.js";import"./useStoragePools-qBtKr1j9.js";import"./ScrollableConfigurationTable-Cdfv_OdM.js";import"./StorageVolumeForm-CW2hs3vZ.js";import"./DiskSizeSelector-C_YZZUSe.js";import"./StoragePoolSize-ChYxPd_8.js";import"./Meter-VGEmUMfL.js";import"./ProjectRichChip-CtiU36yR.js";import"./snapshots-DETOqD-5.js";import"./useResources-D4gdq2PK.js";import"./formChangeCount-Dw7v2KcL.js";import"./StoragePoolRichChip-CxRTjvv2.js";import"./projects-DAlFlfjH.js";import"./useVolumes-CXLHz-Wc.js";import"./storage-volumes-CNe_c3nC.js";import"./FormLink-DYjWMIpw.js";import"./UploadCustomIso-CFeOJaFW.js";import"./useNetworks-B1lu5MbM.js";import"./ExpandableList-DK5_MQFC.js";import"./NetworkRichChip-D2iomVd3.js";import"./NetworkSelector-BaEsMhep.js";import"./useNetworkAcls-DNeSgtR0.js";import"./network-acls-DPo6Eh5Y.js";const H="any",Ce="container",xe="virtual-machine",Jt=({onSelect:a,onClose:l})=>{const[r,u]=v.useState(""),[d,o]=v.useState(""),[p,j]=v.useState(""),[m,C]=v.useState("amd64"),[S,E]=v.useState(void 0),[w,U]=v.useState(H),[F,R]=v.useState(!1),[O,D]=v.useState(""),[V,A]=v.useState(!1),{project:B}=je(),{data:h,isLoading:G}=Se(),{data:_,isLoading:L}=it(),{data:f=[],isLoading:c}=ct(B??"default");_?.error&&_?.error!==O&&(D(_?.error??""),A(!1));const i=!F&&L||c||G,Q=lt(h?.environment?.architectures??[]),$=i?[]:f.map(ke).sort(ze).concat(_?.images??[]).filter(t=>Q.includes(t.arch)),y=[...new Set($.map(t=>t.arch))].filter(t=>t!=="").sort(),x=[...new Set($.map(t=>t.variant))].sort();!i&&!y.includes(m)&&y.length>0&&C(y[0]);const I=(t,b=()=>!0)=>{const P=[...new Set($.filter(b).map(t))].sort().map(g=>({label:g,value:g}));return P.unshift({label:"Any",value:""}),P},N=$.filter(t=>{const b=t.server===ee;return S===xe&&ae(t)||S===Ce&&se(t)||m!==t.arch&&!b||w!==H&&w!==t.variant||d&&t.os!==d||p&&t.release!==p?!1:r?t.aliases.toLowerCase().includes(r)||t.arch.toLowerCase().includes(r)||t.os.toLowerCase().includes(r)||t.release.toLowerCase().includes(r):!0}).filter(t=>F?t.server===he||t.cached:!0).map(t=>{const P=t.type?t.type:se(t)?xe:ae(t)?Ce:"all",g=()=>{a(t,t.type??S)},K=t.os==="Ubuntu"&&t.release_title&&!t.release.includes(t.release_title)?t.release_title:t.release,M=t.os==="Ubuntu"&&t.release_title&&!t.variant&&!t.release.includes(t.release_title)?t.release:t.variant,z=()=>{let q="Custom";!t.cached&&t.created_at&&(q="Local"),t.registryName&&(q=t.registryBuiltIn?t.registryName.split("-").map(Oe).join(" "):t.registryName);const W=["images","ubuntu","ubuntu-minimal",""].includes(t.registryName??"");return t.server===ut&&W&&(q="Ubuntu"),t.server===dt&&W&&(q="Ubuntu Minimal"),t.server===mt&&W&&(q="LXD Images"),q};return{key:P+t.os+K+M+t.server+t.fingerprint+t.registryName,className:"u-row",columns:[{content:t.os,role:"rowheader","aria-label":"Distribution",onClick:g},{content:K,role:"cell","aria-label":"Release",onClick:g},{content:M,role:"cell","aria-label":"Variant",onClick:g},{content:P,role:"cell","aria-label":"Type",onClick:g},{className:"u-hide--small u-hide--medium",content:t.aliases.split(",").pop(),title:t.aliases.split(",").pop(),role:"cell","aria-label":"Alias",onClick:g},{content:z(),role:"cell","aria-label":"Source",onClick:g},{className:"u-hide--small u-hide--medium",content:t.cached?"Cached":"Remote",role:"cell","aria-label":"Cached",onClick:g},{className:"u-hide--small u-hide--medium",content:e.jsx(s.Button,{onClick:g,type:"button",dense:!0,className:"u-no-margin--bottom",appearance:t.cached||t.server===he?"positive":"default",children:"Select"}),role:"cell","aria-label":"Action",onClick:g}],sortData:{os:t.os.toLowerCase(),release:K.toLowerCase(),variant:M?.toLowerCase(),type:P,alias:t.aliases}}}),k=[{content:"Distribution",sortKey:"os"},{content:"Release",sortKey:"release"},{content:"Variant",sortKey:"variant"},{content:"Type",sortKey:"type"},{content:"Alias",sortKey:"alias",className:"u-hide--small u-hide--medium"},{content:"Source"},{className:"u-hide--small u-hide--medium",content:"Cached"},{className:"u-hide--small u-hide--medium",content:"","aria-label":"Actions"}];return e.jsx(s.Modal,{close:l,title:"Select base image",className:"image-select-modal",children:e.jsxs(s.Row,{className:"u-no-padding--left u-no-padding--right",children:[e.jsx(s.Col,{size:3,children:e.jsxs("div",{className:"image-select-filters",children:[e.jsx(s.Select,{id:"imageFilterDistribution",label:"Distribution",name:"distribution",onChange:t=>{o(t.target.value),j("")},options:I(t=>t.os),value:d}),e.jsx(s.Select,{id:"imageFilterRelease",label:"Release",name:"release",onChange:t=>{j(t.target.value)},options:I(t=>t.release,t=>t.os===d),value:p,disabled:d===""}),e.jsx(s.Select,{id:"imageFilterVariant",label:"Variant",name:"variant",onChange:t=>{U(t.target.value)},options:[{label:"Any",value:H}].concat(x.filter(t=>!!t).map(t=>({label:t??"",value:t??""}))),value:w}),e.jsx(s.Select,{id:"imageFilterArchitecture",label:"Architecture",name:"architecture",onChange:t=>{C(t.target.value)},options:y.map(t=>({label:t,value:t})),value:m}),e.jsx(s.Select,{id:"imageFilterType",label:"Type",name:"type",onChange:t=>{E(t.target.value===H?void 0:t.target.value)},options:[{label:"Any",value:H},...Fe],value:S??""}),e.jsx(s.CheckboxInput,{"aria-label":"Only show cached images",checked:F,label:"Show only cached images",onChange:()=>{R(t=>!t)}})]})}),e.jsxs(s.Col,{size:9,children:[e.jsx("div",{className:"image-select-header",children:O&&!V?e.jsx(s.Notification,{severity:"negative",title:"Failed loading images",onDismiss:()=>{A(!0)},children:O}):e.jsx("div",{children:e.jsx(s.SearchBox,{autoFocus:!0,className:"search-image",name:"search-image",type:"text",onChange:t=>{u(t.toLowerCase()),o(""),j("")},placeholder:"Search an image"})})}),e.jsx("div",{className:"image-list",children:e.jsx(s.ScrollableTable,{dependencies:[$],tableId:"image-selector-table",children:e.jsx(s.MainTable,{id:"image-selector-table",className:"table-image-select",emptyStateMsg:i?e.jsx(s.Spinner,{className:"u-loader",text:"Loading images..."}):"No matching images found",headers:k,rows:N,paginate:null,sortable:!0})})})]})]})})},Zt=({onSelect:a})=>{const{openPortal:l,closePortal:r,isOpen:u,Portal:d}=s.usePortal(),o=(p,j)=>{r(),a(p,j)};return e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{appearance:"positive",onClick:l,type:"button",id:"select-image",children:e.jsx("span",{children:"Browse images"})}),u&&e.jsx(d,{children:e.jsx(Jt,{onClose:r,onSelect:o})})]})},T={AUTO:"auto",CLUSTER_GROUP:"clusterGroup",CLUSTER_MEMBER:"clusterMember",PLACEMENT_GROUP:"placementGroup"},ea=a=>a.target?.startsWith(J)?T.CLUSTER_GROUP:a.placementGroup?T.PLACEMENT_GROUP:a.target?T.CLUSTER_MEMBER:T.AUTO,ta=a=>a?.startsWith(J)?a.split(J)[1]:"",ye=a=>!a||a.startsWith(J)?"":a,aa=({formik:a})=>{if(!Ue())return e.jsx(e.Fragment,{});const{canOverrideClusterTargetRestriction:r}=Ae(),{project:u}=ne(),d=ea(a.values),o=v.useRef(null),p=v.useRef(null),j=v.useRef(null),{data:m=[],isLoading:C}=pt(),S=u?.config.restricted==="true",E=u?.config["restricted.cluster.groups"],w=m.filter(c=>c.members.length<1?!1:S&&E?E.includes(c.name):!0).map(c=>({label:e.jsxs("div",{className:"label",children:[e.jsx("span",{className:"name",children:c.name}),e.jsx("span",{className:"members",children:c.members.length})]}),text:`${c.name} (${c.members.length} ${_e("member",c.members.length)})`,value:c.name})),{data:U=[]}=Ee(),F=U.map(c=>({label:c.server_name,value:c.server_name})),{data:R=[]}=ht(u?.name??"default"),O=()=>{a.setFieldValue("target",void 0),a.setFieldValue("placementGroup",void 0)},D=c=>{a.setFieldValue("target",`${J}${c}`),a.values.placementGroup&&a.setFieldValue("placementGroup",void 0)},V=c=>{a.setFieldValue("target",c),a.values.placementGroup&&a.setFieldValue("placementGroup",void 0)},A=c=>{a.setFieldValue("placementGroup",c),a.values.target&&a.setFieldValue("target",void 0)},B=R.find(c=>c.name===a.values.placementGroup),h=B&&B.used_by.length===0&&B.config.policy===Lt,G=u?.config["restricted.cluster.target"],_=S&&!r()&&(G==="block"||G===void 0),L=a.values.targetSelectedByVolume;if(C)return e.jsx(s.Spinner,{className:"u-loader",text:"Loading..."});if(L)return e.jsx(s.Input,{id:"clusterMember",label:"Cluster member",value:a.values.target,disabled:!0,help:"Member is determined by the selected ISO volume and can't be changed.",type:"text"});const f=a.values.image?void 0:"Please select an image before adding a placement group";return e.jsxs("div",{className:"instance-target-selector",children:[e.jsx(s.Select,{id:"target",label:e.jsxs(e.Fragment,{children:["Target"," ",e.jsx(s.Tooltip,{message:`LXD automatically selects a cluster member for the instance.
Placement groups allow you to control how instances are distributed across cluster members.`,children:e.jsx(s.Icon,{name:"information"})})]}),wrapperClassName:"select-input",value:d,options:[{label:"Auto",value:T.AUTO},{label:"Cluster group",value:T.CLUSTER_GROUP,disabled:w.length===0},{label:"Cluster member",value:T.CLUSTER_MEMBER,disabled:F.length===0||_},{label:"Placement group",value:T.PLACEMENT_GROUP}],onChange:c=>{const n=c.target.value;n===T.AUTO&&O(),n===T.CLUSTER_GROUP&&(D(w[0].value),setTimeout(()=>p.current?.open(),100)),n===T.CLUSTER_MEMBER&&(V(F[0].value),setTimeout(()=>o.current?.open(),100)),n===T.PLACEMENT_GROUP&&(A(R[0]?.name??"-"),R.length>0&&setTimeout(()=>j.current?.open(),100))},disabled:!a.values.image,error:d===T.PLACEMENT_GROUP&&R.length===0?"No placement groups found for this project.":"",title:f}),d===T.CLUSTER_GROUP&&e.jsx(s.CustomSelect,{id:"clusterGroup",label:"Cluster group",wrapperClassName:"select-input",dropdownClassName:"instance-target-dropdown",selectRef:p,onChange:D,value:ta(a.values.target),options:w,header:e.jsxs("div",{className:"header",children:[e.jsx("span",{className:"name",children:"Name"}),e.jsx("span",{className:"members",children:"Members"})]}),disabled:!a.values.image}),d===T.CLUSTER_MEMBER&&e.jsx(s.CustomSelect,{id:"clusterMember",label:"Cluster member",wrapperClassName:"select-input",dropdownClassName:"instance-target-dropdown",selectRef:o,onChange:V,value:ye(a.values.target),options:F,disabled:!a.values.image}),d===T.PLACEMENT_GROUP&&e.jsx(gt,{value:a.values.placementGroup,setValue:A,project:u?.name??"default",ref:j,disabled:!a.values.image,profileNames:a.values.profiles,isCreateInstance:!0}),h&&e.jsx(s.CustomSelect,{id:"clusterMember",label:"Anchor",wrapperClassName:"select-input",dropdownClassName:"instance-target-dropdown",selectRef:o,onChange:c=>{const n=c??void 0;a.setFieldValue("target",n)},value:ye(a.values.target),options:[{label:"Auto",value:""}].concat(...F),disabled:!a.values.image,help:"Cluster member to anchor the placement group"})]})},sa=({onSelect:a})=>{const{openPortal:l,closePortal:r,isOpen:u,Portal:d}=s.usePortal(),o=(p,j)=>{r(),a(p,j)};return e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{onClick:l,type:"button",id:"select-custom-iso",children:e.jsx("span",{children:"Use custom ISO"})}),u&&e.jsx(d,{children:e.jsx(ft,{onClose:r,onSelect:o})})]})},Le=({value:a,onChange:l})=>e.jsxs(e.Fragment,{children:[e.jsx("label",{htmlFor:"file-type",children:"Select upload file type"}),e.jsxs("div",{id:"file-type",children:[e.jsx("div",{className:"u-sv1",children:e.jsx(s.RadioInput,{label:"LXD backup archive (.tar.gz)",checked:a==="instance-backup",onChange:()=>{l("instance-backup")}})}),e.jsx("div",{className:"u-sv3",children:e.jsx(s.RadioInput,{label:e.jsxs("span",{children:["External format (.qcow2, .vmdk,"," ",e.jsx("abbr",{title:".qcow, .vdi, .vhdx",children:"etc..."}),")"]}),checked:a==="external-format",onChange:()=>{l("external-format")}})})]})]}),na=({close:a,uploadState:l,setUploadState:r,fileType:u,setFileType:d,defaultInstanceName:o})=>{const{project:p,isLoading:j}=ne(),m=oe(),C=s.useToastNotification(),S=s.useNotify(),E=re(),w=le(),[U,F]=v.useState(null),R=v.useState(null),{hasInstanceImportConversion:O}=ie(),D=f=>{const c=`${Y}/ui/project/${encodeURIComponent(p?.name??"")}/instance/${encodeURIComponent(f)}`,n=e.jsxs(e.Fragment,{children:["Created instance"," ",e.jsx(me,{instanceName:f,projectName:p?.name??""}),"."]}),i=[{label:"Configure",onClick:async()=>w(`${c}/configuration`)}];C.success(n,i)},V=f=>{C.failure("Instance creation failed.",new Error(f))},A=()=>{E.invalidateQueries({predicate:f=>f.queryKey[0]===X.instances})},B=f=>{const c=new AbortController;F(c),Me(f.instanceFile,f.name,p?.name,f.pool,r,c).then(n=>{C.info(e.jsxs(e.Fragment,{children:["Upload completed. Now creating instance"," ",e.jsx(te,{bold:!0,type:"instance",value:f.name}),"."]})),m.set(n.metadata.id,()=>{D(f.name)},V,A),G(),w(`${Y}/ui/project/${encodeURIComponent(p?.name??"")}/instances`)}).catch(n=>{const i=new Error(n.response?.data.error);S.failure("Instance upload failed",i),h.setSubmitting(!1),r(null)})},h=ce({initialValues:{name:o||"",pool:"",instanceFile:null},validateOnMount:!0,validationSchema:ue().shape({name:de(p?.name||"",R).optional()}),onSubmit:B}),G=v.useCallback(()=>{U?.abort(),r(null),F(null),h.resetForm(),a(),S.clear()},[U,h.resetForm,a,S]),_=async f=>{const{onChange:c}=h.getFieldProps("instanceFile");if(c(f),f.currentTarget.files){const n=f.currentTarget.files[0];if(await h.setFieldValue("instanceFile",n),!o){const i=Ne(n.name,"-import");await h.setFieldValue("name",i),await h.validateField("name"),h.setFieldTouched("name",!0,!0),h.errors.name||h.setFieldError("name",void 0)}}},L=h.values.instanceFile?"":"Please select a file before adding custom configuration.";return e.jsxs(e.Fragment,{children:[e.jsxs(s.Form,{onSubmit:h.handleSubmit,className:Ie({"u-hide":l}),children:[O&&e.jsx(Le,{value:u,onChange:d}),e.jsx(s.Input,{id:"instance-file",name:"instanceFile",type:"file",accept:".tar, application/gzip, application/x-bzip, application/x-xz, application/x-lzma, application/x-squashfs, application/x-qcow2, application/zstd",label:"Local file",labelClassName:O?"u-hide":"",onChange:f=>{_(f)}}),e.jsx(s.Input,{...h.getFieldProps("name"),id:"upload-instance-name",type:"text",label:"New instance name",placeholder:"Enter name",error:h.touched.name?h.errors.name:null,disabled:!!L,title:L}),e.jsx(we,{value:h.values.pool,setValue:f=>{h.setFieldValue("pool",f)},selectProps:{id:"pool",label:"Root storage pool",disabled:j||!!L,title:L}})]}),e.jsxs("footer",{className:"p-modal__footer",id:"modal-footer",children:[e.jsx(s.Button,{appearance:"base",className:"u-no-margin--bottom",type:"button",onClick:G,children:"Cancel"}),e.jsx(s.ActionButton,{appearance:"positive",className:"u-no-margin--bottom",loading:h.isSubmitting||!!l,disabled:!h.isValid||h.isSubmitting||j||!h.values.instanceFile,onClick:()=>{h.submitForm()},children:"Upload and create"})]})]})},oa=a=>[{value:"x86_64",label:"x86_64"},{value:"aarch64",label:"aarch64"},{value:"ppc64le",label:"ppc64le"},{value:"s390x",label:"s390x"}].filter(r=>a.includes(r.value)),ra=a=>{const l=a.file?.size||0,r=[];a.formatConversion&&r.push("format"),a.virtioConversion&&r.push("virtio");const u={source:{type:"conversion",mode:"push",conversion_options:r,source_disk_size:l},devices:{root:{path:"/",type:"disk",pool:a.pool}},type:"virtual-machine",name:a.name,architecture:a.architecture};return JSON.stringify(u)},la=(a,l,r,u)=>{const o=new WebSocket(a);return o.onopen=()=>{const p=new FileReader;let j=0;const m=()=>{if(!l)return;const C=l.slice(j,j+1048576);if(!C.size){o.close(1e3,"File upload complete");return}p.readAsArrayBuffer(C)};p.onload=C=>{if(!l||o.readyState===WebSocket.CLOSING||o.readyState===WebSocket.CLOSED)return;const S=C.target?.result;let E;S&&typeof S=="string"?E=new TextEncoder().encode(S).buffer:E=S,o.send(E),j+=E.byteLength,r&&r(j,l.size),setTimeout(m,0)},p.onerror=C=>{u&&u(C.target?.error?C.target.error:new Error("Failed to read read file"))},m()},o},ia=async a=>new Promise(l=>{const r=new FileReader;r.onload=u=>{const d=u.target?.result,o=new Uint8Array(d);o[510]===85&&o[511]===170?l(!0):l(!1)},r.onerror=()=>{l(!1)},r.readAsArrayBuffer(a.slice(0,512))}),ca=({close:a,uploadState:l,setUploadState:r,fileType:u,setFileType:d,defaultInstanceName:o})=>{const{project:p,isLoading:j}=ne(),m=v.useState(null),[C,S]=v.useState(),[E,w]=v.useState(""),U=s.useToastNotification(),F=s.useNotify(),R=le(),O=oe(),D=re(),{data:V}=Se(),{data:A=[]}=Ee(),B=(x,I,N)=>{r({percentage:Math.floor(I/N*100),loaded:I,total:N}),I===N&&(a(),U.info(e.jsxs(e.Fragment,{children:["Upload completed. Now creating instance"," ",e.jsx(te,{bold:!0,type:"instance",value:x}),"."]})),R(`${Y}/ui/project/${encodeURIComponent(p?.name??"")}/instances`))},h=x=>{F.failure("File upload failed.",x),r(null)},G=()=>{C&&C.readyState===WebSocket.OPEN&&C.close(1e3,"cancel upload"),O.remove(E)},_=x=>{const I=`${Y}/ui/project/${encodeURIComponent(p?.name??"")}/instance/${encodeURIComponent(x)}`,N=e.jsxs(e.Fragment,{children:["Created instance"," ",e.jsx(me,{instanceName:x,projectName:p?.name??""}),"."]}),k=[{label:"Configure",onClick:async()=>R(`${I}/configuration`)}];U.success(N,k)},L=x=>{U.failure("Instance creation failed.",new Error(x))},f=()=>{D.invalidateQueries({predicate:x=>x.queryKey[0]===X.instances})},c=x=>{Re(ra(x),p?.name||"",x.member).then(I=>{const N=I.metadata.id,k=I.metadata.metadata?.fs??"",t=Pe(I.metadata),P=`${location.protocol==="https:"?"wss":"ws"}://${location.host}${Y}/1.0/operations/${encodeURIComponent(N)}/websocket?secret=${encodeURIComponent(k)}`,g=la(P,i.values.file,B.bind(null,t),h);S(g),w(N),O.set(N,()=>{_(t)},L,f)}).catch(I=>{F.failure("Instance creation failed.",I),i.setSubmitting(!1),r(null)})},n=oa(V?.environment?.architectures||[]),i=ce({initialValues:{name:o||"",pool:"",member:A?.[0]?.server_name,file:null,formatConversion:!0,virtioConversion:!1,architecture:n[0]?.value},enableReinitialize:!0,validateOnMount:!0,validationSchema:ue().shape({name:de(p?.name||"",m).optional()}),onSubmit:c}),Q=async x=>{const{onChange:I}=i.getFieldProps("file");if(I(x),x.currentTarget.files){const N=x.currentTarget.files[0];if(await i.setFieldValue("file",N),!o){const t=Ne(N.name,"-import");await i.setFieldValue("name",t),await i.validateField("name"),i.setFieldTouched("name",!0,!0),i.errors.name||i.setFieldError("name",void 0)}const k=await ia(N);await i.setFieldValue("formatConversion",!k)}},$=v.useCallback(()=>{i.resetForm(),a(),F.clear(),G()},[i.resetForm,a,F,C]),y=i.values.file?"":"Please select a file before adding custom configuration.";return e.jsxs(e.Fragment,{children:[e.jsxs(s.Form,{onSubmit:i.handleSubmit,className:Ie({"u-hide":l}),children:[e.jsx(Le,{value:u,onChange:d}),e.jsx(s.Input,{id:"image-file",name:"file",type:"file",label:"Local file",accept:".img, .qcow, .qcow2, .vdi, .vhdx, .vmdk",labelClassName:"u-hide",onChange:x=>{Q(x)}}),e.jsx(s.Input,{...i.getFieldProps("name"),id:"upload-instance-name",type:"text",label:"New instance name",placeholder:"Enter name",error:i.touched.name?i.errors.name:null,disabled:!!y,title:y}),e.jsx(_t,{...i.getFieldProps("member"),id:"member",label:"Target cluster member"}),e.jsx(we,{value:i.values.pool,setValue:x=>{i.setFieldValue("pool",x)},selectProps:{id:"pool",label:"Root storage pool",disabled:!p||!!y,title:y}}),e.jsx(s.Select,{...i.getFieldProps("architecture"),id:"architecture",label:"Image architecture",options:n,disabled:!!y,title:y}),e.jsx("label",{htmlFor:"",children:"Conversion options"}),e.jsx(s.Input,{...i.getFieldProps("formatConversion"),type:"checkbox",label:e.jsxs("span",{title:y,children:["Convert to raw format"," ",e.jsx(s.Icon,{name:"information",title:y||"Can be skipped if the image is already in raw format to speed up the import."})]}),disabled:!!y,checked:i.values.formatConversion}),e.jsx(s.Input,{...i.getFieldProps("virtioConversion"),type:"checkbox",label:e.jsxs("span",{title:y,children:["Add Virtio drivers"," ",e.jsx(s.Icon,{name:"information",title:y||"Mandatory, if the image does not have Virtio drivers installed."})]}),disabled:!!y,checked:i.values.virtioConversion})]}),e.jsxs("footer",{className:"p-modal__footer",id:"modal-footer",children:[e.jsx(s.Button,{appearance:"base",className:"u-no-margin--bottom",type:"button",onClick:$,children:"Cancel"}),e.jsx(s.ActionButton,{appearance:"positive",className:"u-no-margin--bottom",loading:i.isSubmitting||!!l,disabled:!i.isValid||i.isSubmitting||j||!i.values.file,onClick:()=>{i.submitForm()},children:"Upload and create"})]})]})},ua=({close:a,name:l})=>{const[r,u]=v.useState("instance-backup"),[d,o]=v.useState(null);return e.jsxs(s.Modal,{close:a,className:"upload-instance-modal",title:"Upload instance file",closeOnOutsideClick:!1,children:[e.jsx(Te,{className:"u-no-padding u-no-margin"}),d&&e.jsxs(e.Fragment,{children:[e.jsx(At,{percentage:Math.floor(d.percentage)}),e.jsxs("p",{children:[pe(d.loaded)," loaded of"," ",pe(d.total??0)]})]}),r==="instance-backup"&&e.jsx(na,{close:a,uploadState:d,setUploadState:o,fileType:r,setFileType:u,defaultInstanceName:l}),r==="external-format"&&e.jsx(ca,{close:a,uploadState:d,setUploadState:o,fileType:r,setFileType:u,defaultInstanceName:l})]})},da=({name:a})=>{const{openPortal:l,closePortal:r,isOpen:u,Portal:d}=s.usePortal();return e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{onClick:l,type:"button",children:e.jsx("span",{children:"Upload instance file"})}),u&&e.jsx(d,{children:e.jsx(ua,{close:r,name:a})})]})},ma=({formik:a,onSelectImage:l,project:r})=>{const{hasCustomVolumeIso:u}=ie(),d=()=>{const o=a.values.image;return o?o.variant?.toLocaleLowerCase().includes("desktop")?`${o.os} ${o.release} ${o.aliases.split(",")[0]}`:o.variant==="iso"?`${o.os} - ${o.aliases.split(",")[0]}`:`${o.os} ${o.release} ${o.release_title}`:""};return e.jsxs(Ut,{children:[e.jsx(s.Row,{children:e.jsxs(s.Col,{size:12,children:[e.jsx(s.Input,{id:"name",name:"name",type:"text",label:"Instance name",placeholder:"Enter name",onBlur:a.handleBlur,onChange:a.handleChange,value:a.values.name,error:a.touched.name?a.errors.name:null}),e.jsx(Ot,{id:"description",name:"description",label:"Description",placeholder:"Enter description",onBlur:a.handleBlur,onChange:a.handleChange,value:a.values.description})]})}),e.jsx(s.Row,{children:e.jsxs(s.Col,{size:12,children:[e.jsx("p",{className:"p-form__label",children:"Base Image*"}),e.jsx("div",{className:"p-form__control u-clearfix base-image",children:a.values.image?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"u-text--muted u-truncate u-sv3 image-name",children:d()}),e.jsx(s.Button,{appearance:"base",type:"button",onClick:async()=>a.setFieldValue("image",void 0),title:"Clear",hasIcon:!0,children:e.jsx(s.Icon,{name:"close"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Zt,{onSelect:l}),u&&e.jsx(sa,{onSelect:l}),e.jsx(da,{name:a.values.name})]})}),e.jsx(s.Select,{id:"instanceType",label:"Instance type",name:"instanceType",onBlur:a.handleBlur,onChange:a.handleChange,options:Fe,value:a.values.instanceType,disabled:!a.values.image||ae(a.values.image)||se(a.values.image),title:a.values.image?"":"Please select an image before adding a type"}),e.jsx(aa,{formik:a})]})}),e.jsx(rt,{project:r,selected:a.values.profiles,setSelected:o=>{a.setFieldValue("profiles",o)},readOnly:!a.values.image,title:a.values.image?"":"Please select an image before adding profiles"}),e.jsx(bt,{formik:a,disabledReason:a.values.image?"":"Please select an image before adding SSH Keys"})]})},ds=()=>{const a=oe(),l=Ve(),r=le(),u=s.useToastNotification(),d=s.useNotify(),{project:o}=je(),p=re(),j=v.useState(null),[m,C]=v.useState(ge),{hasInstanceCreateStart:S,hasImageRegistries:E}=ie(),w=Xt();if(!o)return e.jsx(e.Fragment,{children:"Missing project"});const U=ue().shape({name:de(o,j).optional(),instanceType:Be().required("Instance type is required")}),F=()=>{Ge("form-contents","p-bottom-controls")};v.useEffect(F,[m]),s.useListener(window,F,"resize",!0);const R=()=>{p.invalidateQueries({queryKey:[X.instances]}),p.invalidateQueries({queryKey:[X.operations,o]}),p.invalidateQueries({queryKey:[X.projects,o]})},O=(t,b)=>{u.info(e.jsxs(e.Fragment,{children:["Creation for instance"," ",e.jsx(te,{bold:!0,type:b,value:t})," started."]}))},D=t=>{u.info(e.jsxs(e.Fragment,{children:["Created instance ",t,", now starting it."]})),R()},V=t=>{u.success(e.jsxs(e.Fragment,{children:["Created and started instance ",t,"."]})),R()},A=(t,b)=>{u.failure("The instance was created, but could not be started.",b,t),R()},B=(t,b)=>{u.success(e.jsxs(e.Fragment,{children:["Created instance ",t,".",b]})),R()},h=(t,b,P,g,K)=>{(g==="toast"?u:d).failure("Instance creation failed",t,null,[{label:"Check configuration",onClick:()=>{r(b,{state:{retryFormValues:P,retryFormSection:K}})}}]),R()},G=(t,b)=>{u.info(e.jsxs(e.Fragment,{children:["Instance ",e.jsx(te,{bold:!0,type:b,value:t})," ","creation has begun. The instance will automatically start upon completion."]}))},_=(t,b,P)=>{const g=e.jsx(me,{instanceName:t,projectName:o});if(b&&!S){D(g),$e({name:t,project:o}).then(z=>{a.set(z.metadata.id,()=>{V(g)},q=>{A(g,new Error(q))})}).catch(z=>{A(g,z)});return}const K=`${Y}/ui/project/${encodeURIComponent(o)}/instance/${encodeURIComponent(t)}/console`,M=P&&e.jsxs(e.Fragment,{children:[e.jsx("p",{children:"Continue the installation process from its console."}),e.jsxs(s.Button,{onClick:async()=>r(K),hasIcon:!0,children:[e.jsx(s.Icon,{name:"canvas"}),e.jsx("span",{children:"Open console"})]})]});b?V(g):B(g,M)},{data:L=[],isLoading:f}=Ht(o),c=(t,b=!0)=>{const P=t.yaml?nt(t.yaml):$(t);if(be(t,L)){C(fe);return}const g=l.pathname+l.search;r(`${Y}/ui/project/${encodeURIComponent(o)}/instances`);const K={...P,start:S?b:void 0};Re(JSON.stringify(K),o,t.target).then(M=>{const z=Pe(M.metadata);if(!z)return;b&&S?G(z,t.instanceType):O(z,t.instanceType);const q=t.image?.server===ee;a.set(M.metadata.id,()=>{_(z,b,q)},W=>{h(new Error(W),g,t,"toast",m)})}).catch(M=>{M.message!=="Cancelled"&&h(M,g,t,void 0,m)})},n=ce({initialValues:l.state?.retryFormValues??{instanceType:"container",profiles:["default"],devices:[],cloud_init_ssh_keys:[],readOnly:!1,entityType:"instance",isCreating:!0},validationSchema:U,onSubmit:t=>{c(t)}});v.useEffect(()=>{f||L.find(b=>b.name==="default")||n.setFieldValue("profiles",[])},[f,L]);const i=n.values.image?.server===ee,Q=(t,b)=>{n.setFieldValue("image",t);const P=n.values.devices.filter(g=>g.type!==De);if(t.server===ee){const g=Mt(t);P.push(g)}n.setFieldValue("devices",P),b?n.setFieldValue("instanceType",b):se(t)?n.setFieldValue("instanceType","virtual-machine"):ae(t)&&n.setFieldValue("instanceType","container"),t.volume?.location&&t.volume.location!=="none"?(n.setFieldValue("target",t.volume?.location),n.setFieldValue("targetSelectedByVolume",!0)):n.setFieldValue("targetSelectedByVolume",void 0)};v.useEffect(()=>{const t=l.state?.selectedImage;t&&Q(t,t.type)},[l.state?.selectedImage]),v.useEffect(()=>{l.state?.retryFormSection&&C(l.state.retryFormSection)},[l.state?.retryFormSection]);const $=t=>({...Kt(t,E),devices:qt(t.devices),config:{...zt(t),...kt(t),...$t(t),...Dt(t),...Gt(t),...Bt(t),...Vt(t),...t.placementGroup&&{"placement.group":t.placementGroup}}}),y=t=>{n.values.yaml&&t!==Z&&n.setFieldValue("yaml",void 0),C(t)};function x(){if(l.state?.retryFormSection===Z&&n.values.yaml)return n.values.yaml;const t=$(n.values);return ot(t)}const I=vt(n),N=Ct(n),k=!n.isValid||!n.values.image||I||N;return e.jsxs(Yt,{title:"Create an instance",contentClassName:"create-instance",children:[e.jsxs(s.Form,{onSubmit:n.handleSubmit,className:"form",children:[m!==Z&&e.jsx(qe,{active:m,setActive:y,isDisabled:!n.values.image,hasDiskError:I||be(n.values,L),hasNetworkError:N,formik:n}),e.jsx(s.Row,{className:"form-contents",children:e.jsxs(s.Col,{size:12,children:[e.jsx(Te,{}),m===ge&&e.jsx(ma,{formik:n,project:o,onSelectImage:Q}),m===fe&&e.jsx(xt,{formik:n,project:o}),m===Ke&&e.jsx(yt,{formik:n,project:o}),m===Ye&&e.jsx(jt,{formik:n,project:o}),m===Qe&&e.jsx(St,{formik:n,project:o}),m===We&&e.jsx(Ft,{formik:n,project:o}),m===He&&e.jsx(It,{formik:n}),m===Xe&&e.jsx(Nt,{formik:n,setSection:y}),m===Je&&e.jsx(Rt,{formik:n}),m===Ze&&e.jsx(Pt,{formik:n}),m===et&&e.jsx(Tt,{formik:n}),m===tt&&e.jsx(Et,{formik:n,project:o}),m===Z&&e.jsx(at,{yaml:x(),setYaml:t=>{n.setFieldValue("yaml",t)},children:e.jsx(Wt,{entity:"instance",docPath:"/instances"})})]})},m)]}),e.jsxs(Qt,{children:[e.jsx("div",{className:"yaml-switch",children:e.jsx(st,{formik:n,section:m,setSection:y,disableReason:n.values.image?void 0:"Please select an image before adding custom configuration"})}),e.jsx(s.Button,{appearance:"base",onClick:async()=>r(l.state?.cancelLocation??`${Y}/ui/project/${encodeURIComponent(o)}/instances`),children:"Cancel"}),e.jsx(s.ActionButton,{loading:n.isSubmitting,disabled:k||n.isSubmitting,appearance:i?"positive":"default",onClick:()=>{c(n.values,!1)},children:"Create"}),!i&&e.jsx(s.ActionButton,{appearance:"positive",loading:n.isSubmitting,disabled:k||n.isSubmitting,onClick:()=>{c(n.values)},children:"Create and start"})]}),(w.panel===ve.editNetworkDevice||w.panel===ve.createNetworkDevice)&&e.jsx(wt,{project:o,formik:n})]})};export{ds as default};