示例#1
0
 internal RequestObject(ProviderBase provider, IHostApi hostApi, Action<RequestObject> action)
 {
     // construct request object
     _hostApi = hostApi;
     Provider = provider;
     _action = action;
 }
示例#2
0
        public static int Run(IHostApi hostApi, Benchmark benchmark, BenchmarkActionCodegen codegenMode)
        {
            bool isDiagnoserAttached = hostApi.IsDiagnoserAttached;

            // the first thing to do is to let diagnosers hook in before anything happens
            // so all jit-related diagnosers can catch first jit compilation!
            if (isDiagnoserAttached)
            {
                hostApi.BeforeAnythingElse();
            }

            try
            {
                // we are not using Runnable here in any direct way in order to avoid strong dependency Main<=>Runnable
                // which could cause the jitting/assembly loading to happen before we do anything
                // we have some jitting diagnosers and we want them to catch all the informations!!

                var inProcessRunnableTypeName = $"{typeof(InProcessRunner).FullName}+{nameof(Runnable)}";
                var type = typeof(InProcessRunner).GetTypeInfo().Assembly.GetType(inProcessRunnableTypeName);
                if (type == null)
                {
                    throw new InvalidOperationException($"Bug: type {inProcessRunnableTypeName} not found.");
                }

                type.GetMethod(nameof(Runnable.RunCore), BindingFlags.Public | BindingFlags.Static)
                .Invoke(null, new object[] { hostApi, benchmark, codegenMode });

                return(0);
            }
            catch (Exception ex)
            {
                hostApi.WriteLine(ex.ToString());
                return(-1);
            }
        }
示例#3
0
        public IAsyncEnumerable <SoftwareIdentity> FindPackagesByUris(Uri[] uris, IHostApi requestObject)
        {
            if (requestObject == null)
            {
                throw new ArgumentNullException("requestObject");
            }

            if (uris == null)
            {
                throw new ArgumentNullException("uris");
            }

            if (uris.Length == 0)
            {
                return(new EmptyAsyncEnumerable <SoftwareIdentity>());
            }

            if (uris.Length == 1)
            {
                return(FindPackageByUri(uris[0], requestObject));
            }

            return(new SoftwareIdentityRequestObject(this, requestObject, request => {
                foreach (var uri in uris)
                {
                    Provider.FindPackageByUri(uri, 0, request);
                }
            }, Constants.PackageStatus.Available));
        }
        public IEnumerable <PackageProvider> SelectProviders(string providerName, IHostApi hostApi)
        {
            if (!string.IsNullOrWhiteSpace(providerName))
            {
                // match with wildcards
                var results = _packageProviders.Values.Where(each => each.ProviderName.IsWildcardMatch(providerName)).ReEnumerable();
                if (results.Any())
                {
                    return(results);
                }
                if (hostApi != null && !providerName.ContainsWildcards())
                {
                    // if the end user requested a provider that's not there. perhaps the bootstrap provider can find it.
                    if (RequirePackageProvider(null, providerName, Constants.MinVersion, hostApi))
                    {
                        // seems to think we found it.
                        if (_packageProviders.ContainsKey(providerName))
                        {
                            return(_packageProviders[providerName].SingleItemAsEnumerable());
                        }
                    }

                    // warn the user that that provider wasn't found.
                    hostApi.Warning(hostApi.FormatMessageString(Constants.Messages.UnknownProvider, providerName));
                }
                return(Enumerable.Empty <PackageProvider>());
            }

            return(PackageProviders);
        }
示例#5
0
 internal RequestObject(ProviderBase provider, IHostApi hostApi, Action <RequestObject> action)
 {
     // construct request object
     _hostApi = hostApi;
     Provider = provider;
     _action  = action;
 }
示例#6
0
        internal static IHostApi SuppressErrorsAndWarnings(this IHostApi parent, bool isProcessing)
        {
            return(new object[] {
                new {
                    Error = new Func <string, string, string, string, bool>((id, cat, targetobjectvalue, messageText) => {
#if DEBUG
                        parent.Verbose("Suppressed Error {0}".format(messageText));
#endif
                        return false;
                    }),
                    Warning = new Func <string, bool>((messageText) => {
#if DEBUG
                        parent.Verbose("Suppressed Warning {0}".format(messageText));
#endif
                        return true;
                    }),
                    Verbose = new Func <string, bool>((messageText) => {
                        if (isProcessing)
                        {
                            parent.Verbose(messageText);
                        }
#if DEBUG
                        else
                        {
                            parent.Verbose("Suppressed Verbose {0}".format(messageText));
                        }
#endif
                        return true;
                    }),
                },
                parent,
            }.As <IHostApi>());
        }
示例#7
0
        private bool InstallPackageReference(Package provider, string fastPath, BootstrapRequest request, SoftwareIdentity[] packages)
        {
            IHostApi installRequest = request;

            if (packages[0].Provider.Name.EqualsIgnoreCase("PowerShellGet") && !request.ProviderServices.IsElevated)
            {
                // if we're not elevated, we want powershellget to install to the user scope

                installRequest = new object[] {
                    new {
                        GetOptionKeys   = new Func <IEnumerable <string> >(() => request.OptionKeys.ConcatSingleItem("Scope")),
                        GetOptionValues = new Func <string, IEnumerable <string> >((key) => {
                            if (key != null && key.EqualsIgnoreCase("Scope"))
                            {
                                return("CurrentUser".SingleItemAsEnumerable());
                            }
                            return(request.GetOptionValues(key));
                        })
                    }
                    , installRequest
                }.As <IHostApi>();
            }

            var installing = packages[0].Provider.InstallPackage(packages[0], installRequest);

            SoftwareIdentity lastPackage = null;

            foreach (var i in installing)
            {
                lastPackage = i;
                // should we echo each package back as it comes back?
                request.YieldSoftwareIdentity(i.FastPackageReference, i.Name, i.Version, i.VersionScheme, i.Summary, i.Source, i.SearchKey, i.FullPath, i.PackageFilename);

                if (request.IsCanceled)
                {
                    installing.Cancel();
                }
            }

            if (!request.IsCanceled && lastPackage != null)
            {
                if (provider.Name.EqualsIgnoreCase("PowerShellGet"))
                {
                    // special case. PSModules we can just ask the PowerShell provider to pick it up
                    // rather than try to scan for it.
                    PackageManagementService.TryLoadProviderViaMetaProvider("PowerShell", lastPackage.FullPath, request);
                    request.YieldFromSwidtag(provider, fastPath);
                    return(true);
                }

                // looks like it installed ok.
                request.YieldFromSwidtag(provider, fastPath);

                // rescan providers
                PackageManagementService.LoadProviders(request.As <IRequest>());
                return(true);
            }
            return(false);
        }
        /// <summary>
        ///     Searches for the assembly, interrogates it for it's providers and then proceeds to load
        /// </summary>
        /// <param name="request"></param>
        /// <param name="providerAssemblyName"></param>
        /// <returns></returns>
        internal bool TryToLoadProviderAssembly(string providerAssemblyName, IHostApi request)
        {
            request.Debug(request.FormatMessageString("Trying provider assembly: {0}", providerAssemblyName));

            var assemblyPath = FindAssembly(providerAssemblyName);

            if (assemblyPath != null)
            {
                try {
                    byte[] hash = null;
                    using (var stream = File.Open(assemblyPath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
                        hash = System.Security.Cryptography.MD5.Create().ComputeHash(stream);
                    }
                    lock (_providerFiles) {
                        if (_providerFiles.ContainsKey(assemblyPath))
                        {
                            // have we tried this file before?
                            if (_providerFiles[assemblyPath].SequenceEqual(hash))
                            {
                                // and it's the exact same file?
                                request.Debug(request.FormatMessageString("Skipping previously processed assembly: {0}", assemblyPath));
                                return(false);
                            }
                            request.Debug(request.FormatMessageString("New assembly in location: {0}", assemblyPath));
                            // it's a different file in the same path?
                            // we're gonna let it try the new file.
                            _providerFiles.Remove(assemblyPath);
                        }
                        else
                        {
                            request.Debug(request.FormatMessageString("Attempting loading of assembly: {0}", assemblyPath));
                        }

                        // record that this file is being loaded.
                        _providerFiles.Add(assemblyPath, hash);
                    }
                    if (AcquireProviders(assemblyPath, request))
                    {
                        request.Debug(request.FormatMessageString("SUCCESS provider assembly: {0}", providerAssemblyName));
                        return(true);
                    }
                } catch (Exception e) {
                    e.Dump();

                    lock (_providerFiles) {
                        // can't create hash from file?
                        // we're not going to try and load this.
                        // all we can do is record the name.
                        if (!_providerFiles.ContainsKey(assemblyPath))
                        {
                            _providerFiles.Add(assemblyPath, new byte[0]);
                        }
                    }
                }
            }
            request.Debug(request.FormatMessageString("FAILED provider assembly: {0}", providerAssemblyName));
            return(false);
        }
示例#9
0
        public IAsyncValue <int> StartFind(IHostApi requestObject)
        {
            if (requestObject == null)
            {
                throw new ArgumentNullException("requestObject");
            }

            return(new FuncRequestObject <int>(this, requestObject, request => Provider.StartFind(request)));
        }
示例#10
0
        public IAsyncEnumerable <SoftwareIdentity> FindPackageByUri(Uri uri, IHostApi requestObject)
        {
            if (!IsSupportedScheme(uri))
            {
                return(new EmptyAsyncEnumerable <SoftwareIdentity>());
            }

            return(new SoftwareIdentityRequestObject(this, requestObject ?? new object().As <IHostApi>(), request => Provider.FindPackageByUri(uri, 0, request), Constants.PackageStatus.Available));
        }
示例#11
0
 internal static IHostApi SuprressBootstrapping(this IHostApi parent, bool isProcessing)
 {
     return(new object[] {
         new {
             IsInvocation = new Func <bool>(() => false),
             ShouldBootstrapProvider = new Func <string, string, string, string, string, string, bool>((s1, s2, s3, s4, s5, s6) => false),
             IsInteractive = new Func <bool>(() => false),
         },
         parent,
     }.As <IHostApi>());
 }
 public bool Initialize(IHostApi request)
 {
     lock (_lockObject) {
         if (!_initialized)
         {
             LoadProviders(request);
             _initialized = true;
         }
     }
     return(_initialized);
 }
示例#13
0
        internal static string FormatMessageString(this IHostApi request, string messageText, params object[] args)
        {
            if (string.IsNullOrWhiteSpace(messageText))
            {
                return(string.Empty);
            }

            if (messageText.StartsWith(Constants.MSGPrefix, true, CultureInfo.CurrentCulture))
            {
                messageText = request.GetMessageString(messageText.Substring(Constants.MSGPrefix.Length), messageText) ?? messageText;
            }

            return(args == null || args.Length == 0 ? messageText : messageText.format(args));
        }
示例#14
0
        internal static string FormatMessageString(this IHostApi request, string messageText, params object[] args)
        {
            if (string.IsNullOrWhiteSpace(messageText))
            {
                return(string.Empty);
            }

            if (messageText.IndexOf(Constants.MSGPrefix, System.StringComparison.CurrentCultureIgnoreCase) == 0)
            {
                messageText = request.GetMessageString(messageText.Substring(Constants.MSGPrefix.Length), messageText) ?? messageText;
            }

            return(args == null || args.Length == 0 ? messageText : messageText.format(args));
        }
示例#15
0
        public SoftwareIdentity GetPackageDetails(SoftwareIdentity softwareIdentity, IHostApi requestObject)
        {
            if (requestObject == null)
            {
                throw new ArgumentNullException("requestObject");
            }

            if (softwareIdentity == null)
            {
                throw new ArgumentNullException("softwareIdentity");
            }

            new PackageDetailsRequestObject(this, requestObject, softwareIdentity, request => Provider.GetPackageDetails(softwareIdentity.FastPackageReference, request)).Wait();

            return(softwareIdentity);
        }
示例#16
0
        /// <summary>
        ///     Searches for the assembly, interrogates it for it's providers and then proceeds to load
        /// </summary>
        /// <param name="request"></param>
        /// <param name="providerAssemblyName"></param>
        /// <returns></returns>
        private bool TryToLoadProviderAssembly(string providerAssemblyName, IHostApi request)
        {
            // find all the matches for the assembly specified, order by version (descending)

            var assemblyPath = FindAssembly(providerAssemblyName);

            if (assemblyPath == null)
            {
                return(false);
            }

            if (!AcquireProviders(assemblyPath, request))
            {
                return(false);
            }

            return(true);
        }
示例#17
0
        internal static IHostApi ProviderSpecific(this IHostApi parent, PackageProvider provider)
        {
            var thisProviderIsCanceled = false;

            return(new object[] {
                new {
                    Error = new Func <string, string, string, string, bool>((id, cat, targetobjectvalue, messageText) => {
                        // turn errors into warnings when we're working in parallel
                        parent.Warning(messageText);

                        thisProviderIsCanceled = true;
                        // tell the provider that yeah, this request is canceled.
                        return thisProviderIsCanceled;
                    }),

                    GetIsCanceled = new Func <bool>(() => parent.IsCanceled || thisProviderIsCanceled)
                },
                parent,
            }.As <IHostApi>());
        }
示例#18
0
        private int ExecuteCore(IHostApi hostApi, Benchmark benchmark, ILogger logger)
        {
            int exitCode    = -1;
            var process     = Process.GetCurrentProcess();
            var oldPriority = process.PriorityClass;
            var oldAffinity = process.ProcessorAffinity;

            var affinity = benchmark.Job.ResolveValueAsNullable(EnvMode.AffinityCharacteristic);

            try
            {
                process.SetPriority(ProcessPriorityClass.High, logger);
                if (affinity != null)
                {
                    process.SetAffinity(affinity.Value, logger);
                }
                // TODO: set thread priority to highest

                exitCode = InProcessRunner.Run(hostApi, benchmark, CodegenMode);
            }
            catch (Exception ex)
            {
                logger.WriteLineError($"// ! {GetType().Name}, exception: {ex}");
            }
            finally
            {
                // TODO: restore thread priority

                process.SetPriority(oldPriority, logger);
                if (affinity != null)
                {
                    process.EnsureProcessorAffinity(oldAffinity);
                }
            }

            return(exitCode);
        }
        private Downloader RegisterDownloader(IDownloader provider, FourPartVersion asmVersion, IHostApi request) {
            string name = null;
            try {
                FourPartVersion ver = provider.GetProviderVersion();
                var version = ver == 0 ? asmVersion : ver;
                name = provider.GetDownloaderName();
                if (String.IsNullOrWhiteSpace(name)) {
                    return null;
                }

                // Initialize the provider before locking the collection
                // that way we're not blocking others on non-deterministic actions.
                request.Debug("Initializing provider '{0}'".format(name));
                provider.InitializeProvider(request.As<IRequest>());
                request.Debug("Provider '{0}' Initialized".format(name));

                lock (Downloaders) {
                    if (Downloaders.ContainsKey(name)) {
                        if (version > Downloaders[name].Version) {
                            // remove the old provider first.
                            // todo: this won't remove the plugin domain and unload the code yet
                            // we'll have to do that later.

                            Downloaders.Remove(name);
                        } else {
                            return null;
                        }
                    }
                    request.Debug("Using Downloader Provider {0}".format(name));

                    var downloader = new Downloader(provider) {
                        Version = version,
                        IsLoaded = true
                    };

                    downloader.Initialize(request);
                    Downloaders.AddOrSet(name, downloader);
                    return downloader;
                }
            } catch (Exception e) {
                request.Debug("Provider '{0}' Failed".format(name));
                e.Dump();
            }
            return null;
        }
示例#20
0
 internal RequestObject(ProviderBase provider, IHostApi hostApi)
 {
     // construct request object
     _hostApi = hostApi;
     Provider = provider;
 }
示例#21
0
 public void FetchPackageDetails(IHostApi api) {
     Provider.GetPackageDetails(this, api);
 }
        /// <summary>
        ///     Searches for the assembly, interrogates it for it's providers and then proceeds to load
        /// </summary>
        /// <param name="request"></param>
        /// <param name="providerAssemblyName"></param>
        /// <returns></returns>
        public bool LoadProviderAssembly(IHostApi request, string providerAssemblyName) {
            request.Debug(request.FormatMessageString("Trying provider assembly: {0}", providerAssemblyName));

            var assemblyPath = FindAssembly(providerAssemblyName);
            if (assemblyPath != null) {

                try {
                    byte[] hash = null;
                    using (var stream = File.Open(assemblyPath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
                        hash = MD5.Create().ComputeHash(stream);
                    }
                    lock (_providerFiles) {
                        if (_providerFiles.ContainsKey(assemblyPath)) {
                            // have we tried this file before?
                            if (_providerFiles[assemblyPath].SequenceEqual(hash)) {
                                // and it's the exact same file?
                                request.Debug(request.FormatMessageString("Skipping previously processed assembly: {0}", assemblyPath));
                                return false;
                            }
                            request.Debug(request.FormatMessageString("New assembly in location: {0}", assemblyPath));
                            // it's a different file in the same path? 
                            // we're gonna let it try the new file. 
                            _providerFiles.Remove(assemblyPath);
                        } else {
                            request.Debug(request.FormatMessageString("Attempting loading of assembly: {0}", assemblyPath));
                        }

                        // record that this file is being loaded.
                        _providerFiles.Add(assemblyPath, hash);
                    }
                    if (AcquireProviders(assemblyPath, request)) {
                        request.Debug(request.FormatMessageString("SUCCESS provider assembly: {0}", providerAssemblyName));
                        return true;
                    }
                } catch (Exception e) {
                    e.Dump();

                    lock (_providerFiles) {
                        // can't create hash from file? 
                        // we're not going to try and load this.
                        // all we can do is record the name.
                        if (!_providerFiles.ContainsKey(assemblyPath)) {
                            _providerFiles.Add(assemblyPath, new byte[0]);
                        }
                    }
                }
            }
            request.Debug(request.FormatMessageString("FAILED provider assembly: {0}", providerAssemblyName));
            return false;
        }
        private PackageProvider RegisterPackageProvider(IPackageProvider provider, string name, FourPartVersion asmVersion, IHostApi request) {
           // string name = null;
            try {
                FourPartVersion ver = provider.GetProviderVersion();
                var version = ver == 0 ? asmVersion : ver;

                //TODO: Need to write a blog file name is the provider name. Provider is no longer required to impl ProvierName property
                //name = provider.GetPackageProviderName();
                //if (String.IsNullOrWhiteSpace(name)) {
                //    return null;
                //}

                // Initialize the provider before locking the collection
                // that way we're not blocking others on non-deterministic actions.
                request.Debug("Initializing provider '{0}'".format(name));
                provider.InitializeProvider(request.As<IRequest>());
                request.Debug("Provider '{0}' Initialized".format(name));


                lock (_packageProviders) {
                    if (_packageProviders.ContainsKey(name)) {
                        if (version > _packageProviders[name].Version) {
                            // remove the old provider first.
                            // todo: this won't remove the plugin domain and unload the code yet
                            // we'll have to do that later.

                            _packageProviders.Remove(name);
                        } else {
                            return null;
                        }
                    }
                }

                request.Debug("Using Package Provider {0}".format(name));
                var packageProvider = new PackageProvider(provider) {
                    Version = version,
                    IsLoaded = true
                };
                packageProvider.Initialize(request);

                // addOrSet locks the collection anyway.
                _packageProviders.AddOrSet(name, packageProvider);
                return packageProvider;
            } catch (Exception e) {
                request.Debug("Provider '{0}' Failed".format(name));
                e.Dump();
            }
            return null;
        }
        private PackageProvider ImportProvider(IHostApi request, string providerName, IMetaProvider powerShellMetaProvider)
        {


            //foreach (var providerName in providers)
            {
                //var matchedProviderName = provider.As<DefaultPackageProvider>().GetPackageProviderName();
                //TODO pass in Maxi, mini, and requiredVersion to LoadAvailableProvider
                var instance = powerShellMetaProvider.LoadAvailableProvider(request.As<IRequest>(), providerName);
                if (instance == null)
                {
                   return null;
                }

                //Register newly created provider
                if (typeof(IPackageProvider).CanDynamicCastFrom(instance))
                {

                    var packageProvider = RegisterPackageProvider(instance.As<IPackageProvider>(), providerName, String.Empty, request);

                    if (packageProvider != null)
                    {
                        packageProvider.ProviderPath = powerShellMetaProvider.GetProviderPath(providerName);
                        return packageProvider;
                    }
                }
                else
                {
                    //A provider is not found
                    request.Error(Constants.Messages.UnknownProvider, ErrorCategory.InvalidOperation.ToString(),
                        providerName, request.FormatMessageString(Constants.Messages.UnknownProvider, providerName));
                }
            }
        }
        /// <summary>
        ///     This initializes the provider registry with the list of package providers.
        ///     (currently a hardcoded list, soon, registry driven)
        /// </summary>
        /// <param name="request"></param>
        internal void LoadProviders(IHostApi request) {
            if (request == null) {
                throw new ArgumentNullException("request");
            }

            var providerAssemblies = (_initialized ? Enumerable.Empty<string>() : _defaultProviders)
                .Concat(GetProvidersFromRegistry(Registry.LocalMachine, "SOFTWARE\\MICROSOFT\\PACKAGEMANAGEMENT"))
                .Concat(GetProvidersFromRegistry(Registry.CurrentUser, "SOFTWARE\\MICROSOFT\\PACKAGEMANAGEMENT"))
                .Concat(AutoloadedAssemblyLocations.SelectMany(location => {
                    if (Directory.Exists(location)) {
                        return Directory.EnumerateFiles(location).Where(each => (each.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) || each.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)));
                    }
                    return Enumerable.Empty<string>();
                }));

#if DEEP_DEBUG
            providerAssemblies = providerAssemblies.ToArray();

            foreach (var each in providerAssemblies) {
                request.Debug("possible assembly: {0}".format(each));
            }
#endif

            // find modules that have manifests
            // todo: expand this out to validate the assembly is ok for this instance of PackageManagement.
            providerAssemblies = providerAssemblies.Where(each => Manifest.LoadFrom(each).Any(manifest => Swidtag.IsSwidtag(manifest) && new Swidtag(manifest).IsApplicable(new Hashtable())));

            // add inbox assemblies (don't require manifests, because they are versioned with the core)

#if !COMMUNITY_BUILD
            // todo: these should just be strong-named references. for now, just load them from the same directory.
            providerAssemblies = providerAssemblies.Concat(new[] {
                Path.Combine(BaseDir, "Microsoft.PackageManagement.MetaProvider.PowerShell.dll"),
                Path.Combine(BaseDir, "Microsoft.PackageManagement.ArchiverProviders.dll"),
                Path.Combine(BaseDir, "Microsoft.PackageManagement.CoreProviders.dll"),
                Path.Combine(BaseDir, "Microsoft.PackageManagement.MsuProvider.dll"),
                Path.Combine(BaseDir, "Microsoft.PackageManagement.MsiProvider.dll")
            });
#endif

#if DEEP_DEBUG
            providerAssemblies = providerAssemblies.ToArray();

            foreach (var each in providerAssemblies) {
                request.Debug("possible assembly with manifest: {0}".format(each));
            }
#endif

            providerAssemblies = providerAssemblies.OrderByDescending(each => {
                try {
                    // try to get a version from the file first
                    return (ulong)(FourPartVersion)FileVersionInfo.GetVersionInfo(each);
                } catch {
                    // otherwise we can't make a distinction.
                    return (ulong)0;
                }
            });
            providerAssemblies = providerAssemblies.Distinct(new PathEqualityComparer(PathCompareOption.FileWithoutExtension));

            // there is no trouble with loading providers concurrently.
#if DEEP_DEBUG
            providerAssemblies.SerialForEach(providerAssemblyName => {
#else
            providerAssemblies.ParallelForEach(providerAssemblyName => {
#endif
                LoadProviderAssembly(request, providerAssemblyName);
            });
#if DEEP_DEBUG
            WaitForDebugger();
#endif
        }
示例#26
0
 public IAsyncEnumerable <SoftwareIdentity> FindPackageByFile(string filename, IHostApi requestObject)
 {
     if (!IsSupportedFile(filename))
     {
         return(new EmptyAsyncEnumerable <SoftwareIdentity>());
     }
     return(new SoftwareIdentityRequestObject(this, requestObject ?? new object().As <IHostApi>(), request => Provider.FindPackageByFile(filename, 0, request), Constants.PackageStatus.Available));
 }
        private IEnumerable<PackageProvider> ImportPackageProviderViaPath(IHostApi request, string providerName) {
            var extension = Path.GetExtension(providerName);
            if (extension != null && extension.Equals(".dll")) {
                //TODO need to check if the assembly is from the known designated folder

               // List<string> knownAssemblyFolders = new List<string>();
                //todo: get the current ps module folder instead of program files
                //todo build a internal asemlby table for Get-packageprovider to display.
                //todo: PackageProviderItem: providername, version, path, loaded, type (PS or dll), providerobject sorted by loaded

                var exist = AutoloadedAssemblyLocations.Where(each => each.Equals(Path.GetDirectoryName(providerName))).Any();

                
                //if (knownAssemblyFolders.Contains(Path.GetDirectoryName(providerName))) {
                if (exist)
                {
                    //If so, load it.
                    var loaded = LoadProviderAssembly(request, providerName);
                    if (loaded)
                    {
                        request.Verbose("loaded successfully");
                        //TODO  not need to be so sily, reference to the key of master list is enough
                        yield return _packageProviders[Path.GetFileNameWithoutExtension(providerName)];
                        //return SelectProviders(Path.GetFileNameWithoutExtension(providerName), request);
                    }

                    request.Warning(string.Format("cannot load assembly '{0}'. you need to add your assembly here...", providerName));
                    yield return null;
                }
                else
                {
                    request.Warning(string.Format("The specified provider '{0}' was not loaded because no valid provider file was found", providerName));
                }
                
            }

            //deal with modules with full path
            var powerShellMetaProvider = GetMetaProviderObject(request);
            if (powerShellMetaProvider == null)
            {
                yield return null;
            }

            //load the proviver
            //TODO firstordefault
            yield return ImportProvider(request, providerName, powerShellMetaProvider);
        }
        //Return all providers under the providerAssemblies folder
        internal IEnumerable<string> AllProvidersFromProviderAssembliesLocation(IHostApi request) {
            try {

                return ScanAllProvidersFromProviderAssembliesLocation(request, null, null, null, null, ProviderOption.AllProvider).WhereNotNull().ToArray();
            } catch (Exception ex) {
                request.Debug(ex.Message);
            }
            return Enumerable.Empty<string>();
        }
        //return the providers with latest version under the providerAssemblies folder
        private IEnumerable<string> ProvidersWithLatestVersionFromProviderAssembliesLocation(IHostApi request) {
            try {
                var providerPaths = ScanAllProvidersFromProviderAssembliesLocation(request, null, null, null, null, ProviderOption.LatestVersion).WhereNotNull().ToArray();

                var notRootAssemblies = providerPaths.Where(each => !ProviderAssembliesLocation.ContainsIgnoreCase(Path.GetDirectoryName(each))).ToArray();
                var rootAssemblies = providerPaths.Where(each => ProviderAssembliesLocation.ContainsIgnoreCase(Path.GetDirectoryName(each))).ToArray();

                var equalityComparer = new PathEqualityComparer(PathCompareOption.File);
                //return the assemblies that are installed not directly under ProviderAssemblies root folder.
                //For the assemblies under the root directory, we need to check further if the provider that has the later version 
                //installed under providername\version folder
                //Convention: the providers are installed under providerassemblies\providername\version folder has the later version
                //than those at the top root folder.
                var assembliesUnderRootFolder = rootAssemblies.Where(rootPath => !notRootAssemblies.Any(element => equalityComparer.Equals(element, rootPath)));

                //for these assemblies not under the providerassemblies root folders but they have the same provider names, we return the latest version               
                var assembliesUnderVersionFolder = notRootAssemblies.GroupBy(Path.GetFileName).Select(
                    each => each.OrderByDescending(file => {
                        var versionFolder = Path.GetDirectoryName(file);
                        Version ver;
                        return !System.Version.TryParse(Path.GetFileName(versionFolder), out ver) ? new Version("0.0") : ver;
                    }).FirstOrDefault()).WhereNotNull();

                return assembliesUnderVersionFolder.Concat(assembliesUnderRootFolder);
            } catch (Exception ex) {
                request.Debug(ex.Message);
            }
            return Enumerable.Empty<string>();
        }
        //Scan through the well-known providerAssemblies folder to find the providers that met the condition.
        internal IEnumerable<string> ScanAllProvidersFromProviderAssembliesLocation(
            IHostApi request,
            string providerName,
            Version requiredVersion,
            Version minimumVersion,
            Version maximumVersion,
            ProviderOption providerOption = ProviderOption.LatestVersion) {

            //if provider is installed in providername\version format
            var providerFolder = ProviderAssembliesLocation.Distinct(new PathEqualityComparer(PathCompareOption.Full)).SelectMany(Directory.EnumerateDirectories);

            foreach (var providerNameFolder in providerFolder) {

                var name = Path.GetFileName(providerNameFolder);

                //check the providername folder
                if (!string.IsNullOrWhiteSpace(providerName)) {

                    if (string.IsNullOrWhiteSpace(providerNameFolder)) {
                        continue;
                    }
                   
                    if (string.IsNullOrWhiteSpace(name) || !name.IsWildcardMatch(providerName)) {
                        continue;
                    }
                }

                var selectedVersions = Directory.EnumerateDirectories(providerNameFolder).Select(versionFolder => {
                    //check if the version is in a valid format. Ver will be 0 if TryParse fails and it won't be selected
                    Version ver;
                    if (System.Version.TryParse(Path.GetFileName(versionFolder), out ver)) {
                        return new {
                            folder = versionFolder,
                            version = (FourPartVersion)ver
                        };
                    }
                    return null;
                }).Where(each => each != null && each.version > 0L);

                selectedVersions = selectedVersions.Where(eachVersion => {
                    if ((requiredVersion == null) || eachVersion.version == (FourPartVersion)requiredVersion) {
                        if ((minimumVersion == null) || eachVersion.version >= (FourPartVersion)minimumVersion) {
                            if ((maximumVersion == null) || eachVersion.version <= (FourPartVersion)maximumVersion) {
                                return true;
                            }
                        }
                    }
                    return false;
                });

                //Get the version folders
                var versionFolders = (providerOption == ProviderOption.AllProvider) ?
                    selectedVersions.Select(each => each.folder).Where(Directory.Exists) :
                    new[] {selectedVersions.OrderByDescending(each => each.version).Select(each => each.folder).FirstOrDefault(Directory.Exists)};

                foreach (var assemblyFolder in versionFolders.WhereNotNull()) {
                    //we reached the provider assembly file path now

                    var files = Directory.EnumerateFiles(assemblyFolder)
                        .Where(file => (file != null) && (Path.GetExtension(file).EqualsIgnoreCase(".dll") || Path.GetExtension(file).EqualsIgnoreCase(".exe"))).ToArray();

                    //if found more than one dll is installed under a version folder, this is not allowed. warning here as enumerating for providers should continue
                    if (files.Any() && files.Count() > 1) {
                        request.Warning(string.Format(CultureInfo.CurrentCulture, Resources.Messages.SingleAssemblyAllowed, files.JoinWithComma()));
                        continue;
                    }
                    // find modules that have the provider manifests
                    var filelist = files.Where(each => Manifest.LoadFrom(each).Any(manifest => Swidtag.IsSwidtag(manifest) && new Swidtag(manifest).IsApplicable(new Hashtable())));

                    if (!filelist.Any()) {
                        continue;
                    }
                    var version = Path.GetFileName(assemblyFolder);
                    var defaultPkgProvider = new DefaultPackageProvider(name, version);
                    var providerPath = files.FirstOrDefault();

                    var pkgProvider = new PackageProvider(defaultPkgProvider)
                    {
                        ProviderPath = providerPath,
                        Version = version,
                        IsLoaded = false
                    };

                    AddToProviderCacheTable(name, pkgProvider);
                    yield return providerPath;
                }
            }

            //check if assembly is installed at the top leverl folder.
            var providerFiles = ProviderAssembliesLocation.Distinct(new PathEqualityComparer(PathCompareOption.Full)).SelectMany(Directory.EnumerateFiles)
                .Where(each => each.FileExists() && (Path.GetExtension(each).EqualsIgnoreCase(".dll") || Path.GetExtension(each).EqualsIgnoreCase(".exe"))).ReEnumerable();

            // found the assemblies at the top level folder.
            // if a user is looking for a specific version & provider name, we are not be able to know the provider name or version without loading it.
            // Thus, for the top level providers, we just need to load them for the backward compatibility. 
            if (providerFiles.Any()) {
                request.Verbose(string.Format(CultureInfo.CurrentCulture, Resources.Messages.ProviderNameAndVersionNotAvailableFromFilePath, providerFiles.JoinWithComma()));
                foreach (var provider in providerFiles) {
                    //the provider is installed at the top level.

                    // find modules that have the provider manifests
                    if (Manifest.LoadFrom(provider).Any(manifest => Swidtag.IsSwidtag(manifest) && new Swidtag(manifest).IsApplicable(new Hashtable()))) {

                        yield return provider;
                    }
                }
            }
        }
        private IMetaProvider GetMetaProviderObject(IHostApi request)
        {
            //retrieve the powershell metaprovider object
            if (_metaProviders.ContainsKey("PowerShell")) {
                var powerShellMetaProvider = _metaProviders["PowerShell"];
                if (powerShellMetaProvider != null) {
                    return powerShellMetaProvider;
                }
            } 

            request.Verbose(string.Format(CultureInfo.CurrentCulture, Resources.Messages.FailedPowerShellMetaProvider));
            return null;
        }
        private IEnumerable<PackageProvider> ImportPowerShellProvider(IHostApi request, string modulePath, Version requiredVersion, bool shouldRefreshCache)
        {
            request.Debug(string.Format(CultureInfo.CurrentCulture, "Calling ImportPowerShellProvider. providerName = '{0}', requiredVersion='{1}'", 
                modulePath, requiredVersion));

            var powerShellMetaProvider = GetMetaProviderObject(request);
            if (powerShellMetaProvider == null) {
                yield break;
            }

            //providerName can be a file path or name.
            var instances = powerShellMetaProvider.LoadAvailableProvider(request.As<IRequest>(), modulePath, requiredVersion, shouldRefreshCache).ReEnumerable();

            if (!instances.Any()) {
                //A provider is not found
                request.Error(Constants.Messages.UnknownProvider, ErrorCategory.InvalidOperation.ToString(),
                    modulePath, string.Format(Resources.Messages.UnknownProvider, modulePath));
                yield break;

            }

            foreach (var instance in instances) {
                //Register the provider
                var provider = instance.As<PackageProvider>();
                if (provider != null) {
                    //initialize the actual powershell package provider
                    if (provider.Provider == null) {
                        continue;
                    }
                    provider.Provider.InitializeProvider(request.As<IRequest>());

                    AddToProviderCacheTable(provider.ProviderName, provider);

                    //initialize the warpper package provider
                    provider.Initialize(request);

                    // addOrSet locks the collection anyway.
                    _packageProviders.AddOrSet(provider.ProviderName, provider);

                    yield return provider;
                }
            }
        }
        private IEnumerable<PackageProvider> FindMatchedProvidersFromInternalCacheTable(
            IHostApi request,
            string providerName,
            Version requiredVersion,
            Version minimumVersion,
            Version maximumVersion,
            bool force) {

            //Search from the internal table to see if we can the matched provider
            //check if the provider name matches
            var providersTable = _providerCacheTable.Where(each => each.Key.IsWildcardMatch(providerName))
                .Select(each => each.Value).ToArray();
            //check if version matches
            var providers = providersTable.Select(list => list.Where(each => {
                bool foundMatch = true;
                if (requiredVersion != null) {
                    return each.Version.Equals(requiredVersion);
                }

                if (minimumVersion != null) {
                    foundMatch = each.Version >= (FourPartVersion)minimumVersion;
                }
                if (maximumVersion != null) {
                    foundMatch |= each.Version <= (FourPartVersion)maximumVersion;
                }

                return foundMatch;
            }).Select(each => each)).ToArray();

            var selectedProviders = providers.Select(each => each.OrderByDescending(p => p.Version).FirstOrDefault()).WhereNotNull();
            
            foreach (var instance in selectedProviders) {
                if (instance.IsLoaded) {
                    //Initialize the provider
                    instance.Initialize(request);

                    //Add it to the provider list that all imported and in use
                    _packageProviders.AddOrSet(instance.ProviderName, instance);
                    request.Verbose(string.Format(Resources.Messages.ImportPackageProvider, instance.ProviderName));                   
                    yield return instance;
                } else {
                    if (Path.GetExtension(instance.ProviderPath).EqualsIgnoreCase(".psm1")) {

                        //it's a powershell provider
                        var psProviders = ImportPowerShellProvider(request, instance.ProviderPath, instance.Version, shouldRefreshCache: force);
                        foreach (var p in psProviders) {
                            yield return p;
                        }

                    } else {
                        LoadProviderAssembly(request, instance.ProviderPath, shouldRefreshCache: force);
                        var foo = _packageProviders.Where(each => each.Key.IsWildcardMatch(providerName));
                        foreach (var p in foo) {
                            yield return p.Value;
                        }
                    }
                }
            }
        }
示例#34
0
        public IAsyncEnumerable <SoftwareIdentity> FindPackages(string[] names, string requiredVersion, string minimumVersion, string maximumVersion, IHostApi requestObject)
        {
            if (requestObject == null)
            {
                throw new ArgumentNullException("requestObject");
            }

            if (names == null)
            {
                throw new ArgumentNullException("names");
            }

            if (names.Length == 0)
            {
                return(FindPackage(null, requiredVersion, minimumVersion, maximumVersion, requestObject));
            }

            if (names.Length == 1)
            {
                return(FindPackage(names[0], requiredVersion, minimumVersion, maximumVersion, requestObject));
            }

            return(new SoftwareIdentityRequestObject(this, requestObject, request => {
                foreach (var name in names)
                {
                    Provider.FindPackage(name, requiredVersion, minimumVersion, maximumVersion, 0, request);
                }
            }, Constants.PackageStatus.Available));
        }
        //TODO Name, Version,....
        public IEnumerable<PackageProvider> ImportPackageProvider(IHostApi request, string providerName, bool isPathRooted) {
            if (providerName.IsNullOrEmpty())
            {
                return Enumerable.Empty<PackageProvider>();
            }

            //foreach (var name in providerNames) {
                //check if it;s loaded.
            var results = _packageProviders.Values.Where(each => each.ProviderName.IsWildcardMatch(providerName)).ReEnumerable();

            if (results.Any())
            {
                //the provider is already loaded and tracked in the loaded master list: _packageProviders 
                request.Verbose(string.Format("The provider '{0}' has already been imported.", providerName));
                return Enumerable.Empty<PackageProvider>();
                
            }

                if (isPathRooted)
                {
                    if (File.Exists(providerName))
                    {
                        // looks like we have something that could definitely be a
                        // a module path.
                        //yield return new KeyValuePair<string, string>(fullPath, (moduleVersion ?? new Version(0, 0)).ToString());
                        return ImportPackageProviderViaPath(request, providerName);
                    } else {
                        //error out
                        request.Warning(String.Format("{0} is not found", providerName));
                    }
                } else {
                     return ImportPackageProviderViaName(request, providerName);
                }
                // return providerNames.SelectMany(each => ImportPackageProvider(request, each));
           // }
            return Enumerable.Empty<PackageProvider>();

        }
示例#36
0
        // Friendly APIs

        public IAsyncEnumerable <PackageSource> AddPackageSource(string name, string location, bool trusted, IHostApi requestObject)
        {
            return(new PackageSourceRequestObject(this, requestObject ?? new object().As <IHostApi>(), request => Provider.AddPackageSource(name, location, trusted, request)));
        }
        private IEnumerable<PackageProvider> ImportPackageProviderViaName(IHostApi request, string providerName)
        {
            var powerShellMetaProvider = GetMetaProviderObject(request);
            if (powerShellMetaProvider == null) {
                yield break;
            }

            //var availableProvider = powerShellMetaProvider.GetAvailableLocallyProviders(request.As<IRequest>()).ReEnumerable();
            var availableProviderNames = powerShellMetaProvider.GetProviderNames(); //.ReEnumerable();

            if (!availableProviderNames.Any())
            {
                //No available providers.
                if (!String.IsNullOrWhiteSpace(providerName)) {
                    //Error out if a user specific -Name
                    request.Error(Constants.Messages.UnknownProvider, ErrorCategory.InvalidOperation.ToString(),
                        providerName, request.FormatMessageString(Constants.Messages.UnknownProvider, providerName));
                }
                yield break;
            }

            // a user inputs "-Name" property, we load the specific provider

            //Find if it exists in the available list
            var matches = availableProviderNames.Where(each => each.IsWildcardMatch(providerName)).ReEnumerable();
            if (!matches.Any()) {
                request.Error(Constants.Messages.UnknownProvider, ErrorCategory.InvalidOperation.ToString(),
                    providerName, request.FormatMessageString(Constants.Messages.UnknownProvider, providerName));
            }
            foreach (var match in matches) {


                //var matchedProviderName = match.As<DefaultPackageProvider>().GetPackageProviderName();

                yield return ImportProvider(request, match, powerShellMetaProvider);

                //var instance = powerShellMetaProvider.LoadAvailableProvider(request.As<IRequest>(), matchedProviderName);
                //if (instance == null) {
                //    yield break;
                //}

                ////Register newly created provider
                //if (typeof (IPackageProvider).CanDynamicCastFrom(instance)) {

                //    var packageProvider = RegisterPackageProvider(instance.As<IPackageProvider>(), String.Empty, request);

                //    if (packageProvider != null) {
                //        packageProvider.ProviderPath = powerShellMetaProvider.GetProviderPath(matchedProviderName);
                //        yield return packageProvider;
                //    }
                //} else {
                //    //A provider is not found
                //    request.Error(Constants.Messages.UnknownProvider, ErrorCategory.InvalidOperation.ToString(),
                //        providerName, request.FormatMessageString(Constants.Messages.UnknownProvider, providerName));
                //}
            }
        }
示例#38
0
        public IAsyncEnumerable <SoftwareIdentity> DownloadPackage(SoftwareIdentity softwareIdentity, string destinationFilename, IHostApi requestObject)
        {
            if (requestObject == null)
            {
                throw new ArgumentNullException("requestObject");
            }

            if (softwareIdentity == null)
            {
                throw new ArgumentNullException("softwareIdentity");
            }

            return(new SoftwareIdentityRequestObject(this, requestObject, request => Provider.DownloadPackage(softwareIdentity.FastPackageReference, destinationFilename, request), Constants.PackageStatus.Downloaded));
        }
        private IMetaProvider GetMetaProviderObject(IHostApi requestObject) {
            if (_metaProviders.ContainsKey("powershell")) {
                var powerShellMetaProvider = _metaProviders["powershell"];
                if (powerShellMetaProvider != null) {
                    return powerShellMetaProvider;
                }
            }

            requestObject.Error(Constants.Messages.FailedPowerShellMetaProvider, ErrorCategory.InvalidOperation.ToString(), "LoadProvider", requestObject.FormatMessageString(Constants.Messages.FailedPowerShellMetaProvider));
            return null;
        }
示例#40
0
 public IAsyncEnumerable <PackageSource> ResolvePackageSources(IHostApi requestObject)
 {
     return(new PackageSourceRequestObject(this, requestObject ?? new object().As <IHostApi>(), request => Provider.ResolvePackageSources(request)));
 }
 public IEnumerable<PackageSource> GetAllSourceNames(IHostApi request) {
     return _packageProviders.Values.SelectMany(each => each.ResolvePackageSources(request));
 }
示例#42
0
 public IAsyncEnumerable <SoftwareIdentity> UninstallPackage(SoftwareIdentity softwareIdentity, IHostApi requestObject)
 {
     return(new SoftwareIdentityRequestObject(this, requestObject ?? new object().As <IHostApi>(), request => Provider.UninstallPackage(softwareIdentity.FastPackageReference, request), Constants.PackageStatus.Uninstalled));
 }
        internal bool AcquireProviders(string assemblyPath, IHostApi request) {
            var found = false;
            try {
                var assembly = Assembly.LoadFrom(assemblyPath);

                if (assembly == null) {
                    return false;
                }

                var asmVersion = GetAssemblyVersion(assembly);

                assembly.FindCompatibleTypes<IMetaProvider>().AsyncForEach(metaProviderClass => {
                    found |= RegisterProvidersViaMetaProvider(metaProviderClass.Create<IMetaProvider>(),
                        Path.GetFileNameWithoutExtension(assembly.Location), asmVersion, request);
                })
                    .Concat(assembly.FindCompatibleTypes<IPackageProvider>().AsyncForEach(packageProviderClass => {
                        var packageProvider = RegisterPackageProvider(packageProviderClass.Create<IPackageProvider>(), asmVersion, request);
                        if (packageProvider != null) {
                            found = true;
                            packageProvider.ProviderPath = assemblyPath;
                        }
                    }))

                    .Concat(assembly.FindCompatibleTypes<IArchiver>().AsyncForEach(serviceProviderClass => {
                        var archiver = RegisterArchiver(serviceProviderClass.Create<IArchiver>(), asmVersion, request);
                        if (archiver != null) {
                            found = true;
                            archiver.ProviderPath = assemblyPath;
                        }
                    }))
                    .Concat(assembly.FindCompatibleTypes<IDownloader>().AsyncForEach(serviceProviderClass => {
                        var downloader = RegisterDownloader(serviceProviderClass.Create<IDownloader>(), asmVersion, request);
                        if (downloader != null) {
                            found = true;
                            downloader.ProviderPath = assemblyPath;
                        }
                    })).WaitAll();

            } catch (Exception e) {
                e.Dump();
            }
            return found;
        }
示例#44
0
        public IAsyncEnumerable <SoftwareIdentity> InstallPackage(SoftwareIdentity softwareIdentity, IHostApi requestObject)
        {
            if (requestObject == null)
            {
                throw new ArgumentNullException("requestObject");
            }

            if (softwareIdentity == null)
            {
                throw new ArgumentNullException("softwareIdentity");
            }

            // if the provider didn't say this was trusted, we should ask the user if it's ok.
            if (!softwareIdentity.FromTrustedSource)
            {
                try {
                    if (!requestObject.ShouldContinueWithUntrustedPackageSource(softwareIdentity.Name, softwareIdentity.Source))
                    {
                        requestObject.Warning(requestObject.FormatMessageString(Constants.Messages.UserDeclinedUntrustedPackageInstall, softwareIdentity.Name));
                        return(new EmptyAsyncEnumerable <SoftwareIdentity>());
                    }
                } catch {
                    return(new EmptyAsyncEnumerable <SoftwareIdentity>());
                }
            }

            return(new SoftwareIdentityRequestObject(this, requestObject ?? new object().As <IHostApi>(), request => Provider.InstallPackage(softwareIdentity.FastPackageReference, request), Constants.PackageStatus.Installed));
        }
        public IEnumerable<SoftwareIdentity> FindPackageByCanonicalId(string packageId, IHostApi hostApi) {
            Uri pkgId;
            if (Uri.TryCreate(packageId, UriKind.Absolute, out pkgId)) {
                var segments = pkgId.Segments;
                if (segments.Length > 0) {
                    var provider = SelectProviders(pkgId.Scheme, hostApi).FirstOrDefault();
                    if (provider != null) {
                        var name = Uri.UnescapeDataString(segments[0].Trim('/', '\\'));
                        var version = (segments.Length > 1) ? Uri.UnescapeDataString(segments[1]) : null;
                        var source = pkgId.Fragment.TrimStart('#');
                        var sources = (String.IsNullOrWhiteSpace(source) ? hostApi.Sources : Uri.UnescapeDataString(source).SingleItemAsEnumerable()).ToArray();

                        var host = new object[] {
                            new {
                                GetSources = new Func<IEnumerable<string>>(() => sources),
                                GetOptionValues = new Func<string, IEnumerable<string>>(key => key.EqualsIgnoreCase("FindByCanonicalId") ? new[] {"true"} : hostApi.GetOptionValues(key)),
                                GetOptionKeys = new Func<IEnumerable<string>>(() => hostApi.OptionKeys.ConcatSingleItem("FindByCanonicalId")),
                            },
                            hostApi,
                        }.As<IHostApi>();

                        return provider.FindPackage(name, version, null, null, host).Select(each => {
                            each.Status = Constants.PackageStatus.Dependency;
                            return each;
                        }).ReEnumerable();
                    }
                }
            }
            return new SoftwareIdentity[0];
        }
        public bool RequirePackageProvider(string requestor, string packageProviderName, string minimumVersion, IHostApi hostApi) {
            // check if the package provider is already installed
            if (_packageProviders.ContainsKey(packageProviderName)) {
                var current = _packageProviders[packageProviderName].Version;
                if (current >= minimumVersion) {
                    return true;
                }
            }

            var currentCallCount = hostApi.CallCount;

            if (_lastCallCount >= currentCallCount) {
                // we've already been here this call.

                // are they asking for the same provider again?
                if (_providersTriedThisCall.Contains(packageProviderName)) {
                    hostApi.Debug("Skipping RequirePackageProvider -- tried once this call previously.");
                    return false;
                }
                // remember this in case we come back again.
                _providersTriedThisCall.Add(packageProviderName);
            } else {
                _lastCallCount = currentCallCount;
                _providersTriedThisCall = new HashSet<string> {
                    packageProviderName
                };
            }

            if (!hostApi.IsInteractive) {
                hostApi.Debug("Skipping RequirePackageProvider due to not interactive");
                // interactive indicates that the host can respond to queries -- this doesn't happen
                // in powershell during tab-completion.
                return false;
            }

            // no?
            // ask the bootstrap provider if there is a package provider with that name available.
            if (!_packageProviders.ContainsKey(packageProviderName)){
                return false;
            }
            var bootstrap = _packageProviders["Bootstrap"];
            if (bootstrap == null) {
                hostApi.Debug("Skipping RequirePackageProvider due to missing bootstrap provider");
                return false;
            }

            var pkg = bootstrap.FindPackage(packageProviderName, null, minimumVersion, null, hostApi).OrderByDescending(p =>  p, SoftwareIdentityVersionComparer.Instance).GroupBy(package => package.Name).ToArray();
            if (pkg.Length == 1) {
                // Yeah? Install it.
                var package = pkg[0].FirstOrDefault();
                var metaWithProviderType = package.Meta.FirstOrDefault(each => each.ContainsKey("providerType"));
                var providerType = metaWithProviderType == null ? "unknown" : metaWithProviderType.GetAttribute("providerType");
                var destination = providerType == "assembly" ? (AdminPrivilege.IsElevated ? SystemAssemblyLocation : UserAssemblyLocation) : String.Empty;
                var link = package.Links.FirstOrDefault(each => each.Relationship == "installationmedia");
                var location = String.Empty;
                if (link != null) {
                    location = link.HRef.ToString();
                }

                // what can't find an installationmedia link?
                // todo: what should we say here?
                if (hostApi.ShouldBootstrapProvider(requestor, package.Name, package.Version, providerType, location, destination)) {
                    var newRequest = hostApi.Extend<IHostApi>(new {
                        GetOptionValues = new Func<string, IEnumerable<string>>(key => {
                            if (key == "DestinationPath") {
                                return new[] {
                                    destination
                                };
                            }
                            return new string[0];
                        })
                    });
                    var packagesInstalled = bootstrap.InstallPackage(package, newRequest).LastOrDefault();
                    if (packagesInstalled == null) {
                        // that's sad.
                        hostApi.Error(Constants.Messages.FailedProviderBootstrap, ErrorCategory.InvalidOperation.ToString(), package.Name, hostApi.FormatMessageString(Constants.Messages.FailedProviderBootstrap, package.Name));
                        return false;
                    }
                    // so it installed something
                    // we must tell the plugin loader to reload the plugins again.
                    LoadProviders(hostApi);
                    return true;
                }
            }

            return false;
        }
示例#47
0
 internal RemotableHostApi(IHostApi host)
 {
     _hostApi = host;
 }
        /// <summary>
        /// Get available unloaded providers. if not loaded, load those specified in providerNames.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="providerNames">providers to be loaded.</param>
        /// <param name="listAvailable"></param>
        public IEnumerable<PackageProvider> GetAvailableProviders(IHostApi request, string[] providerNames, bool listAvailable) {

            var powerShellMetaProvider = GetMetaProviderObject(request);
            if (powerShellMetaProvider == null) {
                return Enumerable.Empty<PackageProvider>();
            }

            //Handling two cases
            //1. Both "-Name" and "-Listavailable" exist
            //2. "-Name" only. This should be the same behavior as #1

            if (!providerNames.IsNullOrEmpty()) {
                return providerNames.SelectMany(each => GetAvailableProvider(request, each, powerShellMetaProvider));
            }

            if (!listAvailable) {
                //Noop if a user input No -Name nor -ListAvailable 
                return Enumerable.Empty<PackageProvider>();
            }

            //no -Name but -ListAvailable
            return GetAvailableProvider(request, String.Empty, powerShellMetaProvider);
        }
示例#49
0
 public ActionRequestObject(ProviderBase provider, IHostApi hostApi, Action <RequestObject> action) : base(provider, hostApi, action)
 {
     InvokeImpl();
 }
        /// <summary>
        /// Get available provider if -ListAvailable present;load a provider specified in providerName.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="providerName">provider to be loaded.</param>
        /// <param name="powerShellMetaProvider"></param>
        private IEnumerable<PackageProvider> GetAvailableProvider(IHostApi request, string providerName, IMetaProvider powerShellMetaProvider)
        {
            var results = _packageProviders.Values.Where(each => each.ProviderName.IsWildcardMatch(providerName)).ReEnumerable();

            if (results.Any()) {
                //the provider is already loaded and tracked in the loaded master list: _packageProviders 
                yield break;
            }

            //Get available powershell providers
            var availableProviders = powerShellMetaProvider.GetAvailableLocallyProviders(request.As<IRequest>()).ReEnumerable();                        

            if (!availableProviders.Any()) {
                //No available providers.
                if (!String.IsNullOrWhiteSpace(providerName)) {
                    //Error out if a user specific -Name
                    request.Error(Constants.Messages.UnknownProvider, ErrorCategory.InvalidOperation.ToString(),
                        providerName, request.FormatMessageString(Constants.Messages.UnknownProvider, providerName));
                }
                yield break;
            }

            if (String.IsNullOrWhiteSpace(providerName)) {
                // "-Name" does not exist, we return all we can find
                foreach (var module in availableProviders) {
                    yield return new PackageProvider(module.As<DefaultPackageProvider>());
                }
            } else {
                //A user inputs both -Name and -ListAvailable


                var matches = powerShellMetaProvider.GetProviderNames().Where(each => each.IsWildcardMatch(providerName)).ReEnumerable();
                if (!matches.Any()) {
                    request.Error(Constants.Messages.UnknownProvider, ErrorCategory.InvalidOperation.ToString(),
                        providerName, request.FormatMessageString(Constants.Messages.UnknownProvider, providerName));
                }

                foreach (var match in matches) {
                    yield return new PackageProvider(powerShellMetaProvider.GetAvailableLocallyProvider(match).As<DefaultPackageProvider>());
                    //yield return new PackageProvider(availableProviders[match].As<DefaultPackageProvider>());
                }
            }
        }
        internal bool TryLoadProviderViaMetaProvider(string metaproviderName, string providerNameOrPath, IHostApi request ) {
            if (_metaProviders.ContainsKey(metaproviderName)) {
                var metaProvider = _metaProviders[metaproviderName];

                request.Debug("Using MetaProvider '{0}' to attempt to load provider from '{1}'".format(metaproviderName, providerNameOrPath));

                return LoadViaMetaProvider( _metaProviders[metaproviderName], providerNameOrPath, metaProvider.GetProviderVersion(),request);
            }
            request.Debug("MetaProvider '{0}' is not recognized".format(metaproviderName));
            return false;
        }
示例#52
0
 public IAsyncEnumerable <PackageSource> RemovePackageSource(string name, IHostApi requestObject)
 {
     return(new PackageSourceRequestObject(this, requestObject ?? new object().As <IHostApi>(), request => Provider.RemovePackageSource(name, request)));
 }
 public SoftwareIdentityRequestObject(ProviderBase provider, IHostApi request, Action <RequestObject> action, string status)
     : base(provider, request, action)
 {
     _status = status;
     InvokeImpl();
 }
        internal bool RegisterProvidersViaMetaProvider(IMetaProvider provider, FourPartVersion asmVersion, IHostApi request) {
            var found = false;
            var metaProviderName = provider.GetMetaProviderName();

            lock (_metaProviders) {
                if (!_metaProviders.ContainsKey(metaProviderName)) {
                    // Meta Providers can't be replaced at this point
                    _metaProviders.AddOrSet(metaProviderName.ToLowerInvariant(), provider);
                }
            }

            try {
                provider.InitializeProvider(request.As<IRequest>());
                provider.GetProviderNames().ParallelForEach(name => {
                    found = LoadViaMetaProvider(provider, name,asmVersion, request);
                });
            } catch (Exception e) {
                e.Dump();
            }
            return found;
        }
 public PackageDetailsRequestObject(ProviderBase provider, IHostApi hostApi, SoftwareIdentity softwareIdentity, Action<RequestObject> action)
     : base(provider, hostApi, action) {
     _softwareIdentity = softwareIdentity;
     InvokeImpl();
 }
        private bool LoadViaMetaProvider(IMetaProvider metaProvider, string name, FourPartVersion asmVersion, IHostApi request ) {
            var found = false;

            var instance = metaProvider.CreateProvider(name);
            if (instance != null) {
                // check if it's a Package Provider
                if (typeof (IPackageProvider).CanDynamicCastFrom(instance)) {
                    try {
                        var packageProvider = RegisterPackageProvider(instance.As<IPackageProvider>(), name, asmVersion, request);
                        if (packageProvider != null) {
                            found = true;
                            packageProvider.IsLoaded = true;
                            packageProvider.ProviderPath = metaProvider.GetProviderPath(name);
                        }
                    } catch (Exception e) {
                        e.Dump();
                    }
                }

                // check if it's a Services Provider
                if (typeof (IArchiver).CanDynamicCastFrom(instance)) {
                    try {
                        var archiver = RegisterArchiver(instance.As<IArchiver>(), asmVersion, request);
                        if (archiver != null) {
                            found = true;
                            archiver.ProviderPath = metaProvider.GetProviderPath(name);
                            archiver.IsLoaded = true;
                        }
                    } catch (Exception e) {
                        e.Dump();
                    }
                }

                if (typeof (IDownloader).CanDynamicCastFrom(instance)) {
                    try {
                        var downloader = RegisterDownloader(instance.As<IDownloader>(), asmVersion, request);
                        if (downloader != null) {
                            found = true;
                            downloader.ProviderPath = metaProvider.GetProviderPath(name);
                            downloader.IsLoaded = true;
                        }
                    } catch (Exception e) {
                        e.Dump();
                    }
                }
            }
            return found;
        }
        private static void InstallPackageViaPowerShellGet(PackageJson packageJson, PackageSourceListRequest request, SoftwareIdentity[] packages)
        {
            var provider = PackageSourceListRequest.FindProvider(request, packageJson.Type, request, true);

            if (provider == null)
            {
                return;
            }

            IHostApi installRequest = request;

            if (provider.Name.EqualsIgnoreCase(Constants.ProviderNames.PowerShellGet) && !request.ProviderServices.IsElevated)
            {
                // if we're not elevated, we want powershellget to install to the user scope
                installRequest = PackageSourceListRequest.ExtendRequest(
                    new Dictionary <string, string[]> {
                    { "Scope", new[] { "CurrentUser" } }
                }, null, packageJson.IsTrustedSource, request);
            }
            else
            {
                installRequest = PackageSourceListRequest.ExtendRequest(
                    new Dictionary <string, string[]> {
                    { "Destination", new[] { packageJson.Destination ?? "" } }
                }, null, packageJson.IsTrustedSource, request);
            }

            request.Debug("Calling '{0}' provider to install the package '{1}.{2}'", provider.Name, packageJson.Name, packageJson.Version);

            var installing = provider.InstallPackage(packages[0], installRequest);

            if (installing == null || !installing.Any())
            {
                request.Verbose(Resources.Messages.NumberOfPackagesRecevied, 0, provider.Name, "InstallPackage");
                request.Warning(Resources.Messages.FailToInstallPackage, Constants.ProviderName, packages[0].Name);
                return;
            }

            int packagesReceived = 0;

            foreach (var i in installing)
            {
                request.YieldSoftwareIdentity(i.FastPackageReference, i.Name, i.Version, i.VersionScheme, i.Summary, i.Source, i.SearchKey, i.FullPath, i.PackageFilename);

                if (request.IsCanceled)
                {
                    installing.Cancel();
                }
                else
                {
                    request.Verbose(Resources.Messages.SuccessfullyInstalled, "{0}.{1}".format(packageJson.Name, packageJson.Version));
                    //load provider
                    if (packageJson.IsPackageProvider)
                    {
                        //Per provider development guidance: provider name and module name should be the same otherwise we can not import it.
                        request.PackageManagementService.ImportPackageProvider(request, packageJson.Name, null, null, null, isRooted: false, force: false);
                    }
                }
                packagesReceived++;
            }

            request.Verbose(Resources.Messages.NumberOfPackagesRecevied, packagesReceived, provider.Name, "install-package");
        }
 public bool Initialize(IHostApi request) {
     lock (_lockObject) {
         if (!_initialized) {
             LoadProviders(request);
             _initialized = true;
         }
     }
     return _initialized;
 }
示例#59
0
 internal RequestObject(ProviderBase provider, IHostApi hostApi)
 {
     // construct request object
     _hostApi = hostApi;
     Provider = provider;
 }
        public IEnumerable<PackageProvider> SelectProviders(string providerName, IHostApi hostApi) {
            if (!String.IsNullOrWhiteSpace(providerName)) {
                // match with wildcards
                var results = _packageProviders.Values.Where(each => each.ProviderName.IsWildcardMatch(providerName)).ReEnumerable();
                if (results.Any()) {
                    return results;
                }
                if (hostApi != null && !providerName.ContainsWildcards()) {
                    // if the end user requested a provider that's not there. perhaps the bootstrap provider can find it.
                    if (RequirePackageProvider(null, providerName, Constants.MinVersion, hostApi)) {
                        // seems to think we found it.
                        if (_packageProviders.ContainsKey(providerName)) {
                            return _packageProviders[providerName].SingleItemAsEnumerable();
                        }
                    }
                   
                    // SelectProviders() is iterating through the loaded provider list. As we still need to go through the
                    // unloaded provider list, we should not warn users yet at this point of time.
                    // If the provider is not found, eventually we will error out in SelectProviders()/cmdletbase.cs(). 
                    
                    //hostApi.Warn(hostApi.FormatMessageString(Constants.Messages.UnknownProvider, providerName));                   
                }
                return Enumerable.Empty<PackageProvider>();
            }

            return PackageProviders;
        }