Exemplo n.º 1
0
        public static bool RemoteServerFolderWriteAccessible(int packageId, string path)
        {
            try
            {
                // copy to space folder
                int osServiceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.Os);
                if (osServiceId > 0)
                {
                    OS.OperatingSystem os = new OS.OperatingSystem();
                    ServiceProviderProxy.Init(os, osServiceId);

                    string remoteServerPathCheck = FilesController.GetFullPackagePath(packageId,
                                                                                      Path.Combine(path, "check.txt"));

                    //
                    os.CreateFile(remoteServerPathCheck);
                    os.AppendFileBinaryContent(remoteServerPathCheck, Encoding.UTF8.GetBytes(remoteServerPathCheck));
                    os.DeleteFile(remoteServerPathCheck);
                }
                //
                return(true);
            }
            catch
            {                           //
                return(false);
            }
        }
Exemplo n.º 2
0
        public static int AppendFileBinaryChunk(int packageId, string path, byte[] chunk)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);

            if (accountCheck < 0)
            {
                return(accountCheck);
            }

            // check package
            int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);

            if (packageCheck < 0)
            {
                return(packageCheck);
            }

            OS.OperatingSystem os       = GetOS(packageId);
            string             fullPath = GetFullPackagePath(packageId, path);

            os.AppendFileBinaryContent(fullPath, chunk);

            return(0);
        }
Exemplo n.º 3
0
        public int RestoreItem(string tempFolder, System.Xml.XmlNode itemNode, int itemId, Type itemType, string itemName, int packageId, int serviceId, ResourceGroupInfo group)
        {
            if (itemType == typeof(HomeFolder))
            {
                OS.OperatingSystem os = GetOS(serviceId);

                // extract meta item
                XmlSerializer serializer = new XmlSerializer(typeof(HomeFolder));
                HomeFolder    homeFolder = (HomeFolder)serializer.Deserialize(
                    new XmlNodeReader(itemNode.SelectSingleNode("HomeFolder")));

                // create home folder if required
                if (!os.DirectoryExists(homeFolder.Name))
                {
                    os.CreatePackageFolder(homeFolder.Name);
                }

                // copy database backup to remote server
                XmlNode fileNode            = itemNode.SelectSingleNode("File[@name='SpaceFiles']");
                string  backupFileName      = fileNode.Attributes["path"].Value;
                long    backupFileLength    = Int64.Parse(fileNode.Attributes["size"].Value);
                string  localBackupFilePath = Path.Combine(tempFolder, backupFileName);

                if (new FileInfo(localBackupFilePath).Length != backupFileLength)
                {
                    return(-3);
                }

                FileStream stream = new FileStream(localBackupFilePath, FileMode.Open, FileAccess.Read);
                byte[]     buffer = new byte[FILE_BUFFER_LENGTH];

                int    readBytes        = 0;
                long   length           = 0;
                string remoteBackupPath = Path.Combine(homeFolder.Name, backupFileName);
                do
                {
                    // read package file
                    readBytes = stream.Read(buffer, 0, FILE_BUFFER_LENGTH);
                    length   += readBytes;

                    if (readBytes < FILE_BUFFER_LENGTH)
                    {
                        // resize buffer
                        Array.Resize <byte>(ref buffer, readBytes);
                    }

                    // write remote backup file
                    os.AppendFileBinaryContent(remoteBackupPath, buffer);
                }while (readBytes == FILE_BUFFER_LENGTH);
                stream.Close();

                // unzip files
                os.UnzipFiles(remoteBackupPath, homeFolder.Name);

                // delete archive
                if (os.FileExists(remoteBackupPath))
                {
                    os.DeleteFile(remoteBackupPath);
                }

                // add meta-item if required
                if (PackageController.GetPackageItemByName(packageId, itemName, typeof(HomeFolder)) == null)
                {
                    homeFolder.PackageId = packageId;
                    homeFolder.ServiceId = serviceId;
                    PackageController.AddPackageItem(homeFolder);
                }
            }
            else if (itemType == typeof(SystemDSN))
            {
                OS.OperatingSystem os = GetOS(serviceId);

                // extract meta item
                XmlSerializer serializer = new XmlSerializer(typeof(SystemDSN));
                SystemDSN     dsn        = (SystemDSN)serializer.Deserialize(
                    new XmlNodeReader(itemNode.SelectSingleNode("SystemDSN")));

                // create DSN if required
                if (os.GetDSN(itemName) == null)
                {
                    dsn.DatabasePassword = CryptoUtils.Decrypt(dsn.DatabasePassword);
                    os.CreateDSN(dsn);

                    // restore password
                    dsn.DatabasePassword = CryptoUtils.Encrypt(dsn.DatabasePassword);
                }

                // add meta-item if required
                if (PackageController.GetPackageItemByName(packageId, itemName, typeof(SystemDSN)) == null)
                {
                    dsn.PackageId = packageId;
                    dsn.ServiceId = serviceId;
                    PackageController.AddPackageItem(dsn);
                }
            }

            return(0);
        }
Exemplo n.º 4
0
        public static int BackupInternal(string taskId, int userId, int packageId, int serviceId, int serverId,
                                         string backupFileName, int storePackageId, string storePackageFolder, string storeServerFolder,
                                         bool deleteTempBackup)
        {
            try
            {
                TaskManager.StartTask(taskId, "BACKUP", "BACKUP", backupFileName, SecurityContext.User.UserId);

                // Set Ending .scpak
                if (!backupFileName.EndsWith(".scpak"))
                {
                    backupFileName += ".scpak";
                }

                // get the list of items to backup
                TaskManager.Write("Calculate items to backup");
                List <ServiceProviderItem> items = GetBackupItems(userId, packageId, serviceId, serverId);

                if (items.Count == 0)
                {
                    return(0);
                }

                // group items by item types
                Dictionary <int, List <ServiceProviderItem> > groupedItems = new Dictionary <int, List <ServiceProviderItem> >();

                // sort by groups
                foreach (ServiceProviderItem item in items)
                {
                    // add to group
                    if (!groupedItems.ContainsKey(item.TypeId))
                    {
                        groupedItems[item.TypeId] = new List <ServiceProviderItem>();
                    }

                    groupedItems[item.TypeId].Add(item);
                }

                // temp backup folder
                string tempFolder = GetTempBackupFolder();

                // create backup catalog file
                StringWriter  sw     = new StringWriter();
                XmlTextWriter writer = new XmlTextWriter(sw);

                // write backup file header
                writer.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");
                writer.WriteStartElement("Backup");
                writer.WriteStartElement("Info");
                writer.WriteElementString("Name", backupFileName);
                writer.WriteElementString("Created", DateTime.Now.ToString("r"));
                writer.WriteElementString("User", GetLoggedUsername());
                writer.WriteEndElement();                 // Info

                // determine the number of items to backup
                int totalItems = 0;
                foreach (int itemTypeId in groupedItems.Keys)
                {
                    // load item type
                    ServiceProviderItemType itemType = PackageController.GetServiceItemType(itemTypeId);
                    if (!itemType.Backupable)
                    {
                        continue;
                    }

                    totalItems += groupedItems[itemTypeId].Count;
                }

                TaskManager.IndicatorMaximum = totalItems + 2;
                TaskManager.IndicatorCurrent = 0;

                // backup grouped items
                writer.WriteStartElement("Items");
                foreach (int itemTypeId in groupedItems.Keys)
                {
                    // load item type
                    ServiceProviderItemType itemType = PackageController.GetServiceItemType(itemTypeId);
                    if (!itemType.Backupable)
                    {
                        continue;
                    }

                    // load group
                    ResourceGroupInfo group = ServerController.GetResourceGroup(itemType.GroupId);

                    // instantiate controller
                    IBackupController controller = null;
                    try
                    {
                        if (group.GroupController != null)
                        {
                            controller = Activator.CreateInstance(Type.GetType(group.GroupController)) as IBackupController;
                        }
                        if (controller != null)
                        {
                            // backup items
                            foreach (ServiceProviderItem item in groupedItems[itemTypeId])
                            {
                                TaskManager.Write(String.Format("Backup {0} of {1} - {2} '{3}'",
                                                                TaskManager.IndicatorCurrent + 1,
                                                                totalItems,
                                                                itemType.DisplayName,
                                                                item.Name));

                                try
                                {
                                    int backupResult = BackupItem(tempFolder, writer, item, group, controller);
                                }
                                catch (Exception ex)
                                {
                                    TaskManager.WriteError(ex, "Can't backup item");
                                }

                                // increment progress
                                TaskManager.IndicatorCurrent += 1;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        TaskManager.WriteError(ex);
                    }
                }
                writer.WriteEndElement();                 // Items

                // close catalog writer
                writer.WriteEndElement();                 // Backup
                writer.Close();

                // convert to Xml document
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(sw.ToString());

                // sign XML document
                //SignXmlDocument(doc);

                // save signed doc to file
                try
                {
                    doc.Save(Path.Combine(tempFolder, BACKUP_CATALOG_FILE_NAME));
                }
                catch (Exception ex)
                {
                    TaskManager.WriteError(ex, "Can't save backup catalog file: "
                                           + Path.Combine(tempFolder, BACKUP_CATALOG_FILE_NAME));
                    return(0);
                }

                TaskManager.Write("Packaging backup...");

                // compress backup files
                string[] zipFiles     = Directory.GetFiles(tempFolder);
                string[] zipFileNames = new string[zipFiles.Length];
                for (int i = 0; i < zipFiles.Length; i++)
                {
                    zipFileNames[i] = Path.GetFileName(zipFiles[i]);
                }


                string backupFileNamePath = Path.Combine(tempFolder, backupFileName);

                try
                {
                    FileUtils.ZipFiles(backupFileNamePath, tempFolder, zipFileNames);

                    // delete packed files
                    foreach (string zipFile in zipFiles)
                    {
                        File.Delete(zipFile);
                    }
                }
                catch (Exception ex)
                {
                    TaskManager.WriteError(ex, "Can't zip backed up files");
                    return(0);
                }

                TaskManager.IndicatorCurrent += 1;

                TaskManager.Write("Copying backup...");
                // move/copy backup file
                if (!String.IsNullOrEmpty(storeServerFolder))
                {
                    // copy to local folder or UNC
                    try
                    {
                        string destFile = Path.Combine(storeServerFolder, backupFileName);
                        File.Copy(backupFileNamePath, destFile, true);
                    }
                    catch (Exception ex)
                    {
                        TaskManager.WriteError(ex, "Can't copy backup to destination location");
                        return(0);
                    }
                }
                else if (storePackageId > 0)
                {
                    try
                    {
                        // copy to space folder
                        int osServiceId = PackageController.GetPackageServiceId(storePackageId, ResourceGroups.Os);
                        if (osServiceId > 0)
                        {
                            OS.OperatingSystem os = new OS.OperatingSystem();
                            ServiceProviderProxy.Init(os, osServiceId);

                            string remoteBackupPath = FilesController.GetFullPackagePath(storePackageId,
                                                                                         Path.Combine(storePackageFolder, backupFileName));

                            FileStream stream = new FileStream(backupFileNamePath, FileMode.Open, FileAccess.Read);
                            byte[]     buffer = new byte[FILE_BUFFER_LENGTH];

                            int readBytes = 0;
                            do
                            {
                                // read package file
                                readBytes = stream.Read(buffer, 0, FILE_BUFFER_LENGTH);

                                if (readBytes < FILE_BUFFER_LENGTH)
                                {
                                    // resize buffer
                                    Array.Resize <byte>(ref buffer, readBytes);
                                }

                                // write remote backup file
                                os.AppendFileBinaryContent(remoteBackupPath, buffer);
                            }while (readBytes == FILE_BUFFER_LENGTH);
                            stream.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        TaskManager.WriteError(ex, "Can't copy backup to destination hosting space");
                        return(0);
                    }
                }

                TaskManager.IndicatorCurrent += 1;

                // delete backup file if required
                if (deleteTempBackup)
                {
                    try
                    {
                        // delete backup folder and all its contents
                        Directory.Delete(tempFolder, true);
                    }
                    catch (Exception ex)
                    {
                        TaskManager.WriteError(ex, "Can't delete temporary backup folder");
                        return(0);
                    }
                }

                BackgroundTask topTask = TaskManager.TopTask;

                topTask.IndicatorCurrent = topTask.IndicatorMaximum;

                TaskController.UpdateTask(topTask);
            }
            catch (Exception ex)
            {
                TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }

            return(0);
        }