public static byte[] GetFileBinaryChunk(int packageId, string path, int offset, int length)
        {
            OS.OperatingSystem os       = GetOS(packageId);
            string             fullPath = GetFullPackagePath(packageId, path);

            return(os.GetFileBinaryChunk(fullPath, offset, length));
        }
Example #2
0
        public static int RestoreInternal(string taskId, int userId, int packageId, int serviceId, int serverId,
                                          int storePackageId, string storePackageBackupPath, string storeServerBackupPath)
        {
            try
            {
                // copy backup from remote or local server
                string backupFileName = (storePackageId > 0)
                                        ? Path.GetFileName(storePackageBackupPath) : Path.GetFileName(storeServerBackupPath);

                TaskManager.StartTask(taskId, "BACKUP", "RESTORE", backupFileName, SecurityContext.User.UserId);

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

                string backupFileNamePath = Path.Combine(tempFolder, backupFileName);
                if (storePackageId > 0)
                {
                    try
                    {
                        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,
                                                                                         storePackageBackupPath);

                            FileStream stream = new FileStream(backupFileNamePath, FileMode.Create, FileAccess.Write);

                            byte[] buffer = new byte[FILE_BUFFER_LENGTH];
                            int    offset = 0;
                            do
                            {
                                // read remote content
                                buffer = os.GetFileBinaryChunk(remoteBackupPath, offset, FILE_BUFFER_LENGTH);

                                // write remote content
                                stream.Write(buffer, 0, buffer.Length);

                                offset += FILE_BUFFER_LENGTH;
                            }while (buffer.Length == FILE_BUFFER_LENGTH);
                            stream.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        TaskManager.WriteError(ex, "Can't copy source backup set");
                        return(0);
                    }
                }
                else
                {
                    backupFileNamePath = storeServerBackupPath;
                }

                try
                {
                    // unpack archive
                    FileUtils.UnzipFiles(backupFileNamePath, tempFolder);
                }
                catch (Exception ex)
                {
                    TaskManager.WriteError(ex, "Can't unzip backup set");
                    return(0);
                }

                // load backup catalog
                XmlDocument doc = new XmlDocument();

                try
                {
                    doc.Load(Path.Combine(tempFolder, BACKUP_CATALOG_FILE_NAME));
                }
                catch (Exception ex)
                {
                    TaskManager.WriteError(ex, "Can't find/open backup catalog file");
                    return(0);
                }

                // validate XML document
                //if (!ValidateXmlDocument(doc))
                //{
                //    TaskManager.WriteError("Corrupted or altered backup catalog file has been read");
                //    return 0;
                //}

                // get the list of items to restore
                string condition = "";
                if (userId > 0)
                {
                    // get user spaces
                    List <PackageInfo> packages = new List <PackageInfo>();
                    packages.AddRange(PackageController.GetMyPackages(userId));
                    packages.AddRange(PackageController.GetPackages(userId));
                    List <string> parts = new List <string>();
                    foreach (PackageInfo package in packages)
                    {
                        parts.Add("@packageId = " + package.PackageId.ToString());
                    }
                    condition = "[" + String.Join(" or ", parts.ToArray()) + "]";
                }
                else if (packageId > 0)
                {
                    condition = "[@packageId = " + packageId + "]";
                }
                else if (serviceId > 0)
                {
                    condition = "[@serviceId = " + serviceId + "]";
                }
                else if (serverId > 0)
                {
                    // get server services
                    List <ServiceInfo> services = ServerController.GetServicesByServerId(serverId);
                    List <string>      parts    = new List <string>();
                    foreach (ServiceInfo service in services)
                    {
                        parts.Add("@serviceId = " + service.ServiceId.ToString());
                    }
                    condition = "[" + String.Join(" or ", parts.ToArray()) + "]";
                }

                XmlNodeList itemNodes = doc.SelectNodes("Backup/Items/Item" + condition);

                TaskManager.IndicatorMaximum = itemNodes.Count;
                TaskManager.IndicatorCurrent = 0;

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

                // sort by groups
                foreach (XmlNode itemNode in itemNodes)
                {
                    int itemTypeId = Utils.ParseInt(itemNode.Attributes["itemTypeId"].Value, 0);
                    // add to group
                    if (!groupedItems.ContainsKey(itemTypeId))
                    {
                        groupedItems[itemTypeId] = new List <XmlNode>();
                    }

                    groupedItems[itemTypeId].Add(itemNode);
                }

                // restore grouped items
                foreach (int itemTypeId in groupedItems.Keys)
                {
                    // load item type
                    ServiceProviderItemType itemTypeInfo = PackageController.GetServiceItemType(itemTypeId);
                    if (!itemTypeInfo.Backupable)
                    {
                        continue;
                    }

                    Type itemType = Type.GetType(itemTypeInfo.TypeName);

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

                    // instantiate controller
                    IBackupController controller = null;
                    try
                    {
                        controller = Activator.CreateInstance(Type.GetType(group.GroupController)) as IBackupController;
                        if (controller != null)
                        {
                            // backup items
                            foreach (XmlNode itemNode in groupedItems[itemTypeId])
                            {
                                int    itemId        = Utils.ParseInt(itemNode.Attributes["itemId"].Value, 0);
                                string itemName      = itemNode.Attributes["itemName"].Value;
                                int    itemPackageId = Utils.ParseInt(itemNode.Attributes["packageId"].Value, 0);
                                int    itemServiceId = Utils.ParseInt(itemNode.Attributes["serviceId"].Value, 0);

                                TaskManager.Write(String.Format("Restore {0} '{1}'",
                                                                itemTypeInfo.DisplayName, itemName));

                                try
                                {
                                    int restoreResult = controller.RestoreItem(tempFolder, itemNode,
                                                                               itemId, itemType, itemName, itemPackageId, itemServiceId, group);
                                }
                                catch (Exception ex)
                                {
                                    TaskManager.WriteError(ex, "Can't restore item");
                                }

                                TaskManager.IndicatorCurrent++;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        TaskManager.WriteError(ex);
                    }
                }

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

            return(0);
        }