Esempio n. 1
0
        public static TemplateObjectTO ParseJson(dynamic json)
        {
            TemplateObjectTO result = null;
            dynamic          templateObjectTOJson = json[CloudStackTypes.TemplateObjectTO];

            if (templateObjectTOJson != null)
            {
                result = new TemplateObjectTO()
                {
                    imageDataStore = templateObjectTOJson.imageDataStore,
                    format         = (string)templateObjectTOJson.format,
                    name           = (string)templateObjectTOJson.name,
                    uuid           = (string)templateObjectTOJson.uuid,
                    path           = (string)templateObjectTOJson.path,
                    checksum       = (string)templateObjectTOJson.checksum,
                    size           = (string)templateObjectTOJson.size,
                    id             = (string)templateObjectTOJson.id
                };
                result.s3DataStoreTO    = S3TO.ParseJson(templateObjectTOJson.imageDataStore);
                result.nfsDataStoreTO   = NFSTO.ParseJson(templateObjectTOJson.imageDataStore);
                result.primaryDataStore = PrimaryDataStoreTO.ParseJson(templateObjectTOJson.imageDataStore);
            }

            return(result);
        }
Esempio n. 2
0
        /// <summary>
        /// Copy file on network share to local volume.
        /// </summary>
        /// <remarks>
        /// Access to the network share is acheived by logging into the domain corresponding to the user credentials provided.
        /// Windows impersonation does not suffice, because impersonation is limited to domains with an established trust relationship.
        /// We have had to import Win32 API calls to allow login.  There are a number of examples online.  We follow the
        /// one at http://stackoverflow.com/a/2541569/939250 </remarks>
        /// <param name="filePathRelativeToShare"></param>
        /// <param name="cifsShareDetails"></param>
        /// <param name="destFile"></param>
        public static void DownloadCifsFileToLocalFile(string filePathRelativeToShare, NFSTO cifsShareDetails, string destFile)
        {
            String dest = "";
            if (filePathRelativeToShare.EndsWith(".iso") || filePathRelativeToShare.EndsWith(".vhd") || filePathRelativeToShare.EndsWith(".vhdx"))
            {
                dest = Path.Combine(cifsShareDetails.UncPath, filePathRelativeToShare);
                dest = Utils.NormalizePath(dest);
            }
            // if the filePathRelativeToShare string don't have filename and only a dir point then find the vhd files in that folder and use
            // In the clean setup, first copy command wont be having the filename it contains onlyu dir path.
            // we need to scan the folder point and then copy the file to destination.
            else if (!filePathRelativeToShare.EndsWith(".vhd") || !filePathRelativeToShare.EndsWith(".vhdx"))
            {
                // scan the folder and get the vhd filename.
                String uncPath = Path.Combine(cifsShareDetails.UncPath, Path.Combine(filePathRelativeToShare.Split('/')));
                //uncPath = uncPath.Replace("/", "\\");
                DirectoryInfo dir = new DirectoryInfo(uncPath);
                FileInfo[] vhdFiles = dir.GetFiles("*.vhd*");
                if (vhdFiles.Length > 0)
                {
                    FileInfo file = vhdFiles[0];
                    dest = file.FullName;
                }
            }

            s_logger.Info(CloudStackTypes.CopyCommand + ": copy " + Path.Combine(cifsShareDetails.UncPath, filePathRelativeToShare) + " to " + destFile);
            File.Copy(dest, destFile, true);
        }
Esempio n. 3
0
        public static NFSTO ParseJson(dynamic json)
        {
            NFSTO   result    = null;
            dynamic nfsTOJson = json[CloudStackTypes.NFSTO];

            if (nfsTOJson != null)
            {
                result = new NFSTO()
                {
                    _role = (string)nfsTOJson._role,
                };
                // Delete security credentials in original command.  Prevents logger from spilling the beans, as it were.
                String uriStr = (String)nfsTOJson._url;
                result.uri = new Uri(uriStr);
            }
            return(result);
        }
Esempio n. 4
0
        public static VolumeObjectTO ParseJson(dynamic json)
        {
            VolumeObjectTO result = null;

            if (json == null)
            {
                return(result);
            }

            dynamic volumeObjectTOJson = json[CloudStackTypes.VolumeObjectTO];

            if (volumeObjectTOJson != null)
            {
                result = new VolumeObjectTO()
                {
                    dataStore = volumeObjectTOJson.dataStore,
                    format    = ((string)volumeObjectTOJson.format),
                    name      = (string)volumeObjectTOJson.name,
                    path      = volumeObjectTOJson.path,
                    uuid      = (string)volumeObjectTOJson.uuid,
                    size      = (ulong)volumeObjectTOJson.size
                };
                result.primaryDataStore = PrimaryDataStoreTO.ParseJson(volumeObjectTOJson.dataStore);
                result.nfsDataStore     = NFSTO.ParseJson(volumeObjectTOJson.dataStore);

                // Assert
                if (result.dataStore == null || (result.primaryDataStore == null && result.nfsDataStore == null))
                {
                    String errMsg = "VolumeObjectTO missing dataStore in spec " + Utils.CleanString(volumeObjectTOJson.ToString());
                    logger.Error(errMsg);
                    throw new ArgumentNullException(errMsg);
                }

                GuessFileExtension(result);
            }
            return(result);
        }
Esempio n. 5
0
        /// <summary>
        /// Copy file on network share to local volume.
        /// </summary>
        /// <remarks>
        /// Access to the network share is acheived by logging into the domain corresponding to the user credentials provided.
        /// Windows impersonation does not suffice, because impersonation is limited to domains with an established trust relationship.
        /// We have had to import Win32 API calls to allow login.  There are a number of examples online.  We follow the
        /// one at http://stackoverflow.com/a/2541569/939250 </remarks>
        /// <param name="filePathRelativeToShare"></param>
        /// <param name="cifsShareDetails"></param>
        /// <param name="destFile"></param>
        public static void DownloadCifsFileToLocalFile(string filePathRelativeToShare, NFSTO cifsShareDetails, string destFile)
        {
            try
            {
                IntPtr token = IntPtr.Zero;

                LogonUser(cifsShareDetails.User, cifsShareDetails.Domain, cifsShareDetails.Password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref token);
                using (WindowsImpersonationContext remoteIdentity = new WindowsIdentity(token).Impersonate())
                {
                    String dest = "";
                    if (filePathRelativeToShare.EndsWith(".iso") || filePathRelativeToShare.EndsWith(".vhd") || filePathRelativeToShare.EndsWith(".vhdx"))
                    {
                        dest = Path.Combine(cifsShareDetails.UncPath, filePathRelativeToShare);
                        dest = Utils.NormalizePath(dest);
                    }
                    // if the filePathRelativeToShare string don't have filename and only a dir point then find the vhd files in that folder and use
                    // In the clean setup, first copy command wont be having the filename it contains onlyu dir path.
                    // we need to scan the folder point and then copy the file to destination.
                    else if (!filePathRelativeToShare.EndsWith(".vhd") || !filePathRelativeToShare.EndsWith(".vhdx"))
                    {
                        // scan the folder and get the vhd filename.
                        String uncPath = Path.Combine(cifsShareDetails.UncPath, Path.Combine(filePathRelativeToShare.Split('/')));
                        //uncPath = uncPath.Replace("/", "\\");
                        DirectoryInfo dir = new DirectoryInfo(uncPath);
                        FileInfo[] vhdFiles = dir.GetFiles("*.vhd*");
                        if (vhdFiles.Length > 0)
                        {
                            FileInfo file = vhdFiles[0];
                            dest = file.FullName;
                        }
                    }

                    s_logger.Info(CloudStackTypes.CopyCommand + ": copy " + Path.Combine(cifsShareDetails.UncPath, filePathRelativeToShare) + " to " + destFile);
                    File.Copy(dest, destFile, true);
                    remoteIdentity.Undo();
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                string errMsg = "Invalid user or password for the share " + cifsShareDetails.UncPath;
                s_logger.Error(errMsg);

                throw new ArgumentException(errMsg, ex);
            }
        }
Esempio n. 6
0
 public static NFSTO ParseJson(dynamic json)
 {
     NFSTO result = null;
     if (json != null)
     {
         dynamic nfsTOJson = json[CloudStackTypes.NFSTO];
         if (nfsTOJson != null)
         {
             result = new NFSTO()
             {
                 _role = (string)nfsTOJson._role,
             };
             // Delete security credentials in original command.  Prevents logger from spilling the beans, as it were.
             String uriStr = (String)nfsTOJson._url;
             result.uri = new Uri(uriStr);
         }
     }
     return result;
 }
        public JContainer StartCommand([FromBody]dynamic cmd)
        {
            using (log4net.NDC.Push(Guid.NewGuid().ToString()))
            {
                logger.Info(CloudStackTypes.StartCommand + cmd.ToString()); // TODO: Security hole? VM data printed to log
                string details = null;
                bool result = false;

                try
                {
                    string systemVmIsoPath = systemVmIso;
                    lock (systemVmIso)
                    {
                        systemVmIsoPath = systemVmIso;
                        String uriStr = (String)cmd.secondaryStorage;
                        if (!String.IsNullOrEmpty(uriStr))
                        {
                            if (String.IsNullOrEmpty(systemVmIsoPath) || !File.Exists(systemVmIsoPath))
                            {
                                NFSTO share = new NFSTO();
                                share.uri = new Uri(uriStr);
                                string defaultDataPath = wmiCallsV2.GetDefaultDataRoot();

                                string secondaryPath = Utils.NormalizePath(Path.Combine(share.UncPath, "systemvm"));
                                string[] choices = choices = Directory.GetFiles(secondaryPath, "systemvm*.iso");
                                if (choices.Length != 1)
                                {
                                    String errMsg = "Couldn't locate the systemvm iso on " + secondaryPath;
                                    logger.Debug(errMsg);
                                }
                                else
                                {
                                    systemVmIsoPath = Utils.NormalizePath(Path.Combine(defaultDataPath, Path.GetFileName(choices[0])));
                                    if (!File.Exists(systemVmIsoPath))
                                    {
                                        Utils.DownloadCifsFileToLocalFile(choices[0], share, systemVmIsoPath);
                                    }
                                    systemVmIso = systemVmIsoPath;
                                }
                            }
                        }
                    }

                    wmiCallsV2.DeployVirtualMachine(cmd, systemVmIsoPath);
                    result = true;
                }
                catch (Exception wmiEx)
                {
                    details = CloudStackTypes.StartCommand + " fail on exception" + wmiEx.Message;
                    logger.Error(details, wmiEx);
                }

                object ansContent = new
                {
                    result = result,
                    details = details,
                    vm = cmd.vm,
                    contextMap = contextMap
                };
                return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.StartAnswer);
            }
        }
        public JContainer ModifyStoragePoolCommand([FromBody]dynamic cmd)
        {
            using (log4net.NDC.Push(Guid.NewGuid().ToString()))
            {
                logger.Info(CloudStackTypes.ModifyStoragePoolCommand + cmd.ToString());
                string details = null;
                string localPath;
                StoragePoolType poolType;
                object ansContent;

                bool result = ValidateStoragePoolCommand(cmd, out localPath, out poolType, ref details);
                if (!result)
                {
                    ansContent = new
                    {
                        result = result,
                        details = details,
                        contextMap = contextMap
                    };
                    return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer);
                }

                var tInfo = new Dictionary<string, string>();
                long capacityBytes = 0;
                long availableBytes = 0;
                if (poolType == StoragePoolType.Filesystem)
                {
                    GetCapacityForLocalPath(localPath, out capacityBytes, out availableBytes);
                }
                else if (poolType == StoragePoolType.NetworkFilesystem)
                {
                    NFSTO share = new NFSTO();
                    String uriStr = "cifs://" + (string)cmd.pool.host + (string)cmd.pool.path;
                    share.uri = new Uri(uriStr);
                    // Check access to share.
                    Utils.ConnectToRemote(share.UncPath, share.Domain, share.User, share.Password);
                    Utils.GetShareDetails(share.UncPath, out capacityBytes, out availableBytes);
                }
                else
                {
                    result = false;
                }

                String uuid = null;
                var poolInfo = new
                {
                    uuid = uuid,
                    host = cmd.pool.host,
                    localPath = cmd.pool.host,
                    hostPath = cmd.localPath,
                    poolType = cmd.pool.type,
                    capacityBytes = capacityBytes,
                    availableBytes = availableBytes
                };

                ansContent = new
                {
                    result = result,
                    details = details,
                    templateInfo = tInfo,
                    poolInfo = poolInfo,
                    contextMap = contextMap
                };

                return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.ModifyStoragePoolAnswer);
            }
        }
        public JContainer SetupCommand([FromBody]dynamic cmd)
        {
            using (log4net.NDC.Push(Guid.NewGuid().ToString()))
            {
                logger.Info(CloudStackTypes.SetupCommand + cmd.ToString());

                string details = null;
                bool result = false;

                try
                {
                    NFSTO share = new NFSTO();
                    String uriStr = (String)cmd.secondaryStorage;
                    share.uri = new Uri(uriStr);

                    string systemVmIso = (string)cmd.systemVmIso;
                    string defaultDataPath = wmiCallsV2.GetDefaultDataRoot();
                    string isoPath = Path.Combine(defaultDataPath, Path.GetFileName(systemVmIso));
                    if (!File.Exists(isoPath))
                    {
                        logger.Info("File " + isoPath + " not found. Copying it from the secondary share.");
                        Utils.DownloadCifsFileToLocalFile(systemVmIso, share, isoPath);
                    }
                    HypervResourceController.systemVmIso = isoPath;
                    result = true;
                }
                catch (Exception sysEx)
                {
                    details = CloudStackTypes.SetupCommand + " failed due to " + sysEx.Message;
                    logger.Error(details, sysEx);
                }

                object ansContent = new
                {
                    result = result,
                    details = "success - NOP",
                    _reconnect = false,
                    contextMap = contextMap
                };

                return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.SetupAnswer);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Copy file on network share to local volume.
        /// </summary>
        /// <remarks>
        /// Access to the network share is acheived by logging into the domain corresponding to the user credentials provided.
        /// Windows impersonation does not suffice, because impersonation is limited to domains with an established trust relationship.
        /// We have had to import Win32 API calls to allow login.  There are a number of examples online.  We follow the
        /// one at http://stackoverflow.com/a/2541569/939250 </remarks>
        /// <param name="filePathRelativeToShare"></param>
        /// <param name="cifsShareDetails"></param>
        /// <param name="destFile"></param>
        public static void DownloadCifsFileToLocalFile(string filePathRelativeToShare, NFSTO cifsShareDetails, string destFile)
        {
            try
            {
                IntPtr token = IntPtr.Zero;

                LogonUser(cifsShareDetails.User, cifsShareDetails.Domain, cifsShareDetails.Password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref token);
                using (WindowsImpersonationContext remoteIdentity = new WindowsIdentity(token).Impersonate())
                {
                    String dest = "";
                    if (filePathRelativeToShare.EndsWith(".iso") || filePathRelativeToShare.EndsWith(".vhd") || filePathRelativeToShare.EndsWith(".vhdx"))
                    {
                        dest = Path.Combine(cifsShareDetails.UncPath, filePathRelativeToShare);
                        dest = Utils.NormalizePath(dest);
                    }
                    // if the filePathRelativeToShare string don't have filename and only a dir point then find the vhd files in that folder and use
                    // In the clean setup, first copy command wont be having the filename it contains onlyu dir path.
                    // we need to scan the folder point and then copy the file to destination.
                    else if (!filePathRelativeToShare.EndsWith(".vhd") || !filePathRelativeToShare.EndsWith(".vhdx"))
                    {
                        // scan the folder and get the vhd filename.
                        String uncPath = Path.Combine(cifsShareDetails.UncPath, Path.Combine(filePathRelativeToShare.Split('/')));
                        //uncPath = uncPath.Replace("/", "\\");
                        DirectoryInfo dir      = new DirectoryInfo(uncPath);
                        FileInfo[]    vhdFiles = dir.GetFiles("*.vhd*");
                        if (vhdFiles.Length > 0)
                        {
                            FileInfo file = vhdFiles[0];
                            dest = file.FullName;
                        }
                    }

                    s_logger.Info(CloudStackTypes.CopyCommand + ": copy " + Path.Combine(cifsShareDetails.UncPath, filePathRelativeToShare) + " to " + destFile);
                    File.Copy(dest, destFile, true);
                    remoteIdentity.Undo();
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                string errMsg = "Invalid user or password for the share " + cifsShareDetails.UncPath;
                s_logger.Error(errMsg);

                throw new ArgumentException(errMsg, ex);
            }
        }
        private string GetStoragePoolPath(dynamic pool)
        {
            string poolTypeStr = pool.type;
            StoragePoolType poolType;
            if (!Enum.TryParse<StoragePoolType>(poolTypeStr, out poolType))
            {
                throw new ArgumentException("Invalid pool type " + poolTypeStr);
            }
            else if (poolType == StoragePoolType.SMB)
            {
                NFSTO share = new NFSTO();
                String uriStr = "cifs://" + (string)pool.host + (string)pool.path;
                share.uri = new Uri(uriStr);
                return Utils.NormalizePath(share.UncPath);
            }
            else if (poolType == StoragePoolType.Filesystem)
            {
                return pool.path;
            }

            throw new ArgumentException("Couldn't parse path for pool type " + poolTypeStr);
        }
        public JContainer ModifyStoragePoolCommand([FromBody]dynamic cmd)
        {
            using (log4net.NDC.Push(Guid.NewGuid().ToString()))
            {
                logger.Info(CloudStackTypes.ModifyStoragePoolCommand + Utils.CleanString(cmd.ToString()));
                string details = null;
                string localPath;
                StoragePoolType poolType;
                object ansContent;

                bool result = ValidateStoragePoolCommand(cmd, out localPath, out poolType, ref details);
                if (!result)
                {
                    ansContent = new
                    {
                        result = result,
                        details = details,
                        contextMap = contextMap
                    };
                    return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer);
                }

                var tInfo = new Dictionary<string, string>();
                long capacityBytes = 0;
                long availableBytes = 0;
                string hostPath = null;
                if (poolType == StoragePoolType.Filesystem)
                {
                    GetCapacityForLocalPath(localPath, out capacityBytes, out availableBytes);
                    hostPath = localPath;
                }
                else if (poolType == StoragePoolType.NetworkFilesystem ||
                    poolType == StoragePoolType.SMB)
                {
                    NFSTO share = new NFSTO();
                    String uriStr = "cifs://" + (string)cmd.pool.host + (string)cmd.pool.path;
                    share.uri = new Uri(uriStr);
                    hostPath = Utils.NormalizePath(share.UncPath);

                    // Check access to share.
                    Utils.GetShareDetails(share.UncPath, out capacityBytes, out availableBytes);
                    config.setPrimaryStorage((string)cmd.pool.uuid, hostPath);
                }
                else
                {
                    result = false;
                }

                String uuid = null;
                var poolInfo = new
                {
                    uuid = uuid,
                    host = cmd.pool.host,
                    hostPath = cmd.pool.path,
                    localPath = hostPath,
                    poolType = cmd.pool.type,
                    capacityBytes = capacityBytes,
                    availableBytes = availableBytes
                };

                ansContent = new
                {
                    result = result,
                    details = details,
                    localPath = hostPath,
                    templateInfo = tInfo,
                    poolInfo = poolInfo,
                    contextMap = contextMap
                };

                if (result)
                {
                    try
                    {
                        if ((bool)cmd.add)
                        {
                            logger.Info("Adding HeartBeat Task to task scheduler for pool " + (string)cmd.pool.uuid);
                            Utils.AddHeartBeatTask((string)cmd.pool.uuid, hostPath, config.PrivateIpAddress);
                        }
                        else
                        {
                            logger.Info("Deleting HeartBeat Task from task scheduler for pool " + (string)cmd.pool.uuid);
                            Utils.RemoveHeartBeatTask(cmd.pool.uuid);
                        }
                    }
                    catch (Exception e)
                    {
                        logger.Error("Error occurred in adding/delete HeartBeat Task to/from Task Scheduler : " + e.Message);
                    }
                }

                return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.ModifyStoragePoolAnswer);
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Copy file on network share to local volume.
        /// </summary>
        /// <remarks>
        /// Access to the network share is acheived by logging into the domain corresponding to the user credentials provided.
        /// Windows impersonation does not suffice, because impersonation is limited to domains with an established trust relationship.
        /// We have had to import Win32 API calls to allow login.  There are a number of examples online.  We follow the
        /// one at http://stackoverflow.com/a/2541569/939250 </remarks>
        /// <param name="filePathRelativeToShare"></param>
        /// <param name="cifsShareDetails"></param>
        /// <param name="destFile"></param>
        public static void DownloadCifsFileToLocalFile(string filePathRelativeToShare, NFSTO cifsShareDetails, string destFile)
        {
            String dest = "";

            if (filePathRelativeToShare.EndsWith(".iso") || filePathRelativeToShare.EndsWith(".vhd") || filePathRelativeToShare.EndsWith(".vhdx"))
            {
                dest = Path.Combine(cifsShareDetails.UncPath, filePathRelativeToShare);
                dest = Utils.NormalizePath(dest);
            }
            // if the filePathRelativeToShare string don't have filename and only a dir point then find the vhd files in that folder and use
            // In the clean setup, first copy command wont be having the filename it contains onlyu dir path.
            // we need to scan the folder point and then copy the file to destination.
            else if (!filePathRelativeToShare.EndsWith(".vhd") || !filePathRelativeToShare.EndsWith(".vhdx"))
            {
                // scan the folder and get the vhd filename.
                String uncPath = Path.Combine(cifsShareDetails.UncPath, Path.Combine(filePathRelativeToShare.Split('/')));
                //uncPath = uncPath.Replace("/", "\\");
                DirectoryInfo dir      = new DirectoryInfo(uncPath);
                FileInfo[]    vhdFiles = dir.GetFiles("*.vhd*");
                if (vhdFiles.Length > 0)
                {
                    FileInfo file = vhdFiles[0];
                    dest = file.FullName;
                }
            }

            s_logger.Info(CloudStackTypes.CopyCommand + ": copy " + Path.Combine(cifsShareDetails.UncPath, filePathRelativeToShare) + " to " + destFile);
            File.Copy(dest, destFile, true);
        }