Ejemplo n.º 1
0
        public void InitializeProvider(PsRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            request.Debug("Initializing PowerShell MetaProvider");

            // to do : get modules to load (from configuration ?)
            var modules = ScanForModules(request).Distinct().ToArray();

            // try to create each module at least once.
            modules.ParallelForEach(modulePath => {
                request.Debug("Attempting to load PowerShell Provider Module [{0}]", modulePath);
                var provider = Create(request, modulePath);
                if (provider != null)
                {
                    if (provider.GetPackageProviderName() != null)
                    {
                        request.Debug("Loaded PowerShell Package Provider Module: [{0}]", modulePath);
                        // looks good to me, let's add this to the list of moduels this meta provider can create.
                        _packageProviders.AddOrSet(provider.GetPackageProviderName(), provider);
                    }
                    else
                    {
                        provider.Dispose();
                        provider = null;
                    }
                }
            });

            request.Debug("Loaded PowerShell Provider Modules ");
        }
Ejemplo n.º 2
0
        private PowerShellPackageProvider Create(PsRequest req, string psModule)
        {
            var ps = new DynamicPowershell();

            try {
                // load the powershell provider functions into this runspace.
                var psf = ps.ImportModule(PowerShellProviderFunctions, true);
                DynamicPowershellResult result = ps.ImportModule(psModule, true);

                if (!result.LastIsTerminatingError)
                {
                    var providerModule = result.Value as PSModuleInfo;
                    if (result.Success && providerModule != null)
                    {
                        try {
                            return(new PowerShellPackageProvider(ps, providerModule));
                        } catch (Exception e) {
                            e.Dump();
                        }
                    }
                }
            } catch (Exception e) {
                // something didn't go well.
                // skip it.
                e.Dump();
            }

            // didn't import correctly.
            ps.Dispose();
            return(null);
        }
Ejemplo n.º 3
0
 public override bool YieldResult(PsRequest r)
 {
     if (r == null)
     {
         throw new ArgumentNullException("r");
     }
     return(r.YieldDynamicOption(Name, ExpectedType.ToString(), IsRequired) && PermittedValues.WhereNotNull().Select(each => each.ToString()).ToArray().All(v => r.YieldKeyValuePair(Name, v)));
 }
Ejemplo n.º 4
0
 protected virtual bool YieldEntities(PsRequest r)
 {
     if (_links != null)
     {
         return(_entities.OfType <Entity>().All(entity => r.YieldEntity(FastPackageReference, entity.Name, entity.RegId, entity.Role, entity.Thumbprint)));
     }
     return(true);
 }
Ejemplo n.º 5
0
 protected virtual bool YieldLinks(PsRequest r)
 {
     if (_links != null)
     {
         return(_links.OfType <Link>().All(link => r.YieldLink(FastPackageReference, link.HRef, link.Relationship, link.MediaType, link.Ownership, link.Use, link.AppliesToMedia, link.Artifact)));
     }
     return(true);
 }
Ejemplo n.º 6
0
        public override bool YieldResult(PsRequest r)
        {
            if (r == null)
            {
                throw new ArgumentNullException("r");
            }

            return(r.YieldPackageSource(Name, Location, IsTrusted, IsRegistered, IsValidated) && YieldDetails(r));
        }
Ejemplo n.º 7
0
 protected override bool YieldDetails(PsRequest r)
 {
     if (_details != null && _details.Count > 0)
     {
         // we need to send this back as a set of key/path & value  pairs.
         return(_details.Flatten().All(kvp => r.YieldSoftwareMetadata(FastPackageReference, kvp.Key, kvp.Value)));
     }
     return(true);
 }
Ejemplo n.º 8
0
        public override bool YieldResult(PsRequest r)
        {
            if (r == null)
            {
                throw new ArgumentNullException("r");
            }

            return(r.YieldSoftwareIdentity(FastPackageReference, Name, Version, VersionScheme, Summary, Source, SearchKey, FullPath, Filename) && YieldDetails(r) && YieldEntities(r) && YieldLinks(r) && r.YieldSoftwareMetadata(FastPackageReference, "FromTrustedSource", FromTrustedSource.ToString()));
        }
Ejemplo n.º 9
0
 protected virtual bool YieldDetails(PsRequest r)
 {
     if (_details != null && _details.Count > 0)
     {
         // we need to send this back as a set of key/path & value  pairs.
         return(_details.Flatten().All(kvp => r.YieldKeyValuePair(kvp.Key, kvp.Value)));
     }
     return(true);
 }
Ejemplo n.º 10
0
 public override bool YieldResult(PsRequest r)
 {
     if (r == null)
     {
         throw new ArgumentNullException("r");
     }
     if (_pair.Value.Length == 0)
     {
         return(r.YieldKeyValuePair(_pair.Key, null));
     }
     return(_pair.Value.All(each => r.YieldKeyValuePair(_pair.Key, each)));
 }
Ejemplo n.º 11
0
        // lock is on this instance only

        internal void ReportErrors(PsRequest request, IEnumerable <ErrorRecord> errors)
        {
            foreach (var error in errors)
            {
                request.Error(error.FullyQualifiedErrorId, error.CategoryInfo.Category.ToString(), error.TargetObject == null ? null : error.TargetObject.ToString(), error.ErrorDetails == null ? error.Exception.Message : error.ErrorDetails.Message);
                if (!string.IsNullOrWhiteSpace(error.ScriptStackTrace))
                {
                    // give a debug hint if we have a script stack trace. How nice of us.
                    request.Debug(Constants.ScriptStackTrace, error.ScriptStackTrace);
                }
            }
        }
Ejemplo n.º 12
0
        private IEnumerable <string> AlternativeModuleScan(PsRequest request)
        {
            var psModulePath = Environment.GetEnvironmentVariable("PSModulePath") ?? "";

            IEnumerable <string> paths = psModulePath.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            var sysRoot     = Environment.GetEnvironmentVariable("systemroot");
            var userProfile = Environment.GetEnvironmentVariable("userprofile");

            // add assumed paths just in case the environment variable isn't really set.
            paths = paths.ConcatSingleItem(Path.Combine(sysRoot, @"system32\WindowsPowerShell\v1.0\Modules"));
            paths = paths.ConcatSingleItem(Path.Combine(userProfile, @"Documents\WindowsPowerShell\Modules"));

            if (!string.IsNullOrWhiteSpace(BaseFolder) && BaseFolder.DirectoryExists())
            {
                paths = paths.ConcatSingleItem(BaseFolder);
            }

            paths = paths.Distinct().ToArray();

            return(paths.Where(each => each.DirectoryExists()).SelectMany(each => Directory.EnumerateDirectories(each).Where(dir => !_exclusionList.Contains(Path.GetFileName(dir))), (p, child) => Path.Combine(child, Path.GetFileName(child) + ".psd1")).Where(moduleName => File.Exists(moduleName) && File.ReadAllText(moduleName).IndexOf("OneGetProviders", StringComparison.OrdinalIgnoreCase) > -1));
        }
Ejemplo n.º 13
0
        internal IEnumerable <string> ScanForModules(PsRequest request)
        {
            // two places we search for modules
            // 1. in this assembly's folder, look for all psd1 and psm1 files.
            //
            // 2. modules in the PSMODULEPATH
            //
            // Import each one of those, and check to see if they have a OneGet.Providers section in their private data

            using (var ps = new DynamicPowershell()) {
                // load the powershell functions into this runspace in case something needed it on module load.
                var psf = ps.ImportModule(PowerShellProviderFunctions, true);

                // scan all the ps modules in the folders provided
                foreach (var each in AlternativeModuleScan(request))
                {
                    foreach (var ogModule in ps.TestModuleManifest(each).SelectMany(GetOneGetModules))
                    {
                        yield return(ogModule);
                    }
                }
            }
        }
Ejemplo n.º 14
0
 private object Call(string function, IRequest requestObject, params object[] args)
 {
     return(PsRequest.New(requestObject, this, function).CallPowerShell(args));
 }
Ejemplo n.º 15
0
        internal object CallPowerShell(PsRequest request, params object[] args)
        {
            // the lock ensures that we're not re-entrant into the same powershell runspace
            lock (_lock) {
                if (!_reentrancyLock.WaitOne(0))
                {
                    // this lock is set to false, meaning we're still in a call **ON THIS THREAD**
                    // this is bad karma -- powershell won't let us call into the runspace again
                    // we're going to throw an error here because this indicates that the currently
                    // running powershell call is calling back into OneGet, and it has called back
                    // into this provider. That's just bad bad bad.
                    throw new Exception("Re-entrancy Violation in powershell module");
                }

                try {
                    // otherwise, this is the first time we've been here during this call.
                    _reentrancyLock.Reset();

                    _powershell["request"] = request;

                    DynamicPowershellResult result = null;

                    // request.Debug("INVOKING PowerShell Fn {0} in {1}", request.CommandInfo.Name, _module.Name);
                    // make sure we don't pass the request to the function.
                    result = _powershell.NewTryInvokeMemberEx(request.CommandInfo.Name, new string[0], args);

                    // instead, loop thru results and get
                    if (result == null)
                    {
                        // failure!
                        throw new Exception(Messages.PowershellScriptFunctionFailed.format(_module.Name, request.CommandInfo.Name));
                    }

                    object finalValue = null;

                    foreach (var value in result)
                    {
                        if (result.ContainsErrors)
                        {
                            ReportErrors(request, result.Errors);
                            return(null);
                        }

                        var y = value as Yieldable;
                        if (y != null)
                        {
                            y.YieldResult(request);
                        }
                        else
                        {
                            finalValue = value;
                        }
                    }

                    if (result.ContainsErrors)
                    {
                        ReportErrors(request, result.Errors);
                        return(null);
                    }

                    return(finalValue);
                } catch (Exception e) {
                    e.Dump();
                } finally {
                    _powershell.WaitForAvailable();
                    _powershell["request"] = null;

                    // it's ok if someone else calls into this module now.
                    _reentrancyLock.Set();
                }



                return(null);
            }
        }
Ejemplo n.º 16
0
 public abstract bool YieldResult(PsRequest r);