예제 #1
0
        public override RuntimeValue Evaluate(IVariableFunctionContext context)
        {
            if (!(context is IOperationExecutionContext execContext))
            {
                throw new NotSupportedException("This function can currently only be used within an execution.");
            }

            var job = new ExecutePowerShellJob
            {
                CollectOutput = true,
                ScriptText    = this.ScriptText,
                Variables     = PowerShellScriptRunner.ExtractVariables(this.ScriptText, execContext)
            };

            var jobExecuter = execContext.Agent.GetService <IRemoteJobExecuter>();
            var result      = (ExecutePowerShellJob.Result)jobExecuter.ExecuteJobAsync(job, execContext.CancellationToken).GetAwaiter().GetResult();

            if (result.Output.Count == 1)
            {
                return(result.Output[0]);
            }
            else
            {
                return(new RuntimeValue(result.Output));
            }
        }
예제 #2
0
        protected override object EvaluateScalar(IVariableFunctionContext context)
        {
            var execContext = context as IOperationExecutionContext;

            if (execContext != null)
            {
                var fileOps = execContext.Agent.GetService <IFileOperationsExecuter>();

                if (this.AdditionalPaths == null)
                {
                    return(fileOps.CombinePath(this.Path1, this.Path2));
                }
                else
                {
                    return(fileOps.CombinePath(new[] { this.Path1, this.Path2 }.Concat(this.AdditionalPaths).ToArray()));
                }
            }
            else
            {
                if (this.AdditionalPaths == null)
                {
                    return(PathEx.Combine(this.Path1, this.Path2));
                }
                else
                {
                    return(PathEx.Combine(new[] { this.Path1, this.Path2 }.Concat(this.AdditionalPaths).ToArray()));
                }
            }
        }
예제 #3
0
        private string AssembleImageName(IVariableFunctionContext context)
        {
            var containerSource = (ContainerSource)SecureResource.Create(this.ContainerSource, (IResourceResolutionContext)context);
            var containerId     = new ContainerId(this.ContainerSource, containerSource?.RegistryPrefix, this.RepositoryName, this.Tag);

            return(containerId.FullName);
        }
        public override RuntimeValue Evaluate(IVariableFunctionContext context)
        {
            var map = new Dictionary <string, RuntimeValue>(this.Map);

            map.Add(this.Key, this.Value);
            return(new RuntimeValue(map));
        }
        protected override object EvaluateScalar(IVariableFunctionContext context)
        {
            var execContext = context as IOperationExecutionContext;

            if (execContext == null)
            {
                throw new VariableFunctionException("Execution context is not available.");
            }

            var path = execContext.ResolvePath(this.FileName);

            var fileOps = execContext.Agent.GetService <IFileOperationsExecuter>();

            using (var file = fileOps.OpenFile(path, FileMode.Open, FileAccess.Read))
                using (var reader = new StreamReader(file))
                {
                    if (this.MaxLength == null)
                    {
                        return(reader.ReadToEnd());
                    }
                    else
                    {
                        int index  = 0;
                        int length = (int)this.MaxLength;
                        var buffer = new char[length];
                        int read;
                        while ((read = reader.ReadBlock(buffer, index, length - index)) > 0)
                        {
                            index += read;
                        }

                        return(new string(buffer, 0, index));
                    }
                }
        }
        protected override IEnumerable EvaluateVector(IVariableFunctionContext context)
        {
            var results = new List <string>();

            int?groupIndex = AH.ParseInt(this.MatchGroup);

            foreach (Match m in Regex.Matches(this.Text ?? string.Empty, this.MatchExpression ?? string.Empty, RegexOptions.None, new TimeSpan(0, 0, 30)))
            {
                if (groupIndex.HasValue)
                {
                    var group = m.Groups[groupIndex.Value];
                    if (group.Success)
                    {
                        results.Add(group.Value);
                    }
                }
                else if (!string.IsNullOrEmpty(this.MatchGroup))
                {
                    var group = m.Groups[this.MatchGroup];
                    if (group.Success)
                    {
                        results.Add(group.Value);
                    }
                }
                else
                {
                    results.Add(m.Value);
                }
            }

            return(results);
        }
예제 #7
0
        protected override object EvaluateScalar(IVariableFunctionContext context)
        {
            var operationContext = context as IOperationExecutionContext;

            if (operationContext == null)
            {
                throw new InvalidOperationException("Operation execution context is not available.");
            }

            var env     = operationContext.Agent.GetService <IRemoteProcessExecuter>();
            var antPath = env.GetEnvironmentVariableValue("M2_HOME");

            if (string.IsNullOrEmpty(antPath))
            {
                return(string.Empty);
            }

            var fileOps = operationContext.Agent.GetService <IFileOperationsExecuter>();

            antPath = fileOps.CombinePath(antPath, "bin", "mvn");
            if (fileOps.FileExists(antPath))
            {
                return(antPath);
            }

            return(antPath + ".bat");
        }
예제 #8
0
        public override RuntimeValue Evaluate(IVariableFunctionContext context)
        {
            var value = this.Map
                        .Where(kv => kv.Key != this.Key)
                        .ToDictionary(kv => kv.Key, kv => kv.Value);

            return(new RuntimeValue(value));
        }
        protected override IEnumerable EvaluateVector(IVariableFunctionContext context)
        {
            if (this.Count < 0)
            {
                throw new VariableFunctionArgumentException("Count cannot be negative.");
            }

            return(Enumerable.Range(this.Start, this.Count));
        }
 protected override object EvaluateScalar(IVariableFunctionContext context)
 {
     if (this.IgnoreCase)
     {
         return(Regex.Replace(this.Text, Regex.Escape(this.Value), this.ReplaceWith, RegexOptions.IgnoreCase));
     }
     else
     {
         return(this.Text.Replace(this.Value, this.ReplaceWith));
     }
 }
예제 #11
0
        private string Serialize(IVariableFunctionContext context)
        {
            // Empty string is interpreted as a password to make the two-argument version of this function keep its existing behavior.
            if (this.Password == null)
            {
                var credential = SecureCredentials.TryCreate(this.UserName, (ICredentialResolutionContext)context);
                if (credential is Credentials.UsernamePasswordCredentials upcred)
                {
                    this.UserName = upcred.UserName;
                    this.Password = upcred.Password;
                }
                else
                {
                    throw new InvalidOperationException($"No such UsernamePassword credential: {this.UserName}");
                }
            }

            var userName = InedoLib.UTF8Encoding.GetBytes(this.UserName ?? string.Empty);
            var password = default(IntPtr);

            try
            {
                password = Marshal.SecureStringToBSTR(this.Password ?? new SecureString());
                unsafe
                {
                    int passwordByteCount = InedoLib.UTF8Encoding.GetByteCount((char *)password, this.Password.Length);
                    var buffer            = new byte[userName.Length + passwordByteCount + (sizeof(int) * 2)];
                    try
                    {
                        fixed(byte *bufferPtr = buffer)
                        {
                            *(int *)&bufferPtr[0] = userName.Length;
                            Marshal.Copy(userName, 0, new IntPtr(&bufferPtr[sizeof(int)]), userName.Length);

                            *(int *)&bufferPtr[userName.Length + sizeof(int)] = passwordByteCount;
                            InedoLib.UTF8Encoding.GetBytes((char *)password.ToPointer(), this.Password.Length, &bufferPtr[userName.Length + (sizeof(int) * 2)], passwordByteCount);
                        }

                        return(Prefix + Convert.ToBase64String(buffer));
                    }
                    finally
                    {
                        Array.Clear(buffer, 0, buffer.Length);
                    }
                }
            }
            finally
            {
                if (password != default)
                {
                    Marshal.ZeroFreeBSTR(password);
                }
            }
        }
        public override RuntimeValue Evaluate(IVariableFunctionContext context)
        {
            if (string.IsNullOrEmpty(this.VariableName))
            {
                return(false);
            }

            RuntimeValueType[] types;
            if (string.Equals(this.VariableType, "scalar", StringComparison.OrdinalIgnoreCase))
            {
                types = new[] { RuntimeValueType.Scalar }
            }
            ;
            else if (string.Equals(this.VariableType, "vector", StringComparison.OrdinalIgnoreCase))
            {
                types = new[] { RuntimeValueType.Vector }
            }
            ;
            else if (string.Equals(this.VariableType, "map", StringComparison.OrdinalIgnoreCase))
            {
                types = new[] { RuntimeValueType.Map }
            }
            ;
            else
            {
                types = new[] { RuntimeValueType.Scalar, RuntimeValueType.Vector, RuntimeValueType.Map }
            };

            var execContext = context as IOperationExecutionContext;

            if (execContext == null)
            {
                return(null);
            }

            foreach (var type in types)
            {
                var variableName = new RuntimeVariableName(this.VariableName, type);
                var value        = execContext.TryGetVariableValue(variableName);
                if (value != null)
                {
                    return(value.Value);
                }

                var functionValue = execContext.TryGetFunctionValue(variableName.ToString());
                if (functionValue != null)
                {
                    return(functionValue.Value);
                }
            }

            return(null);
        }
    }
예제 #13
0
 protected override object EvaluateScalar(IVariableFunctionContext context)
 {
     try
     {
         return(Regex.Replace(this.Text ?? string.Empty, this.MatchExpression ?? string.Empty, this.ReplaceWith ?? string.Empty, RegexOptions.None, new TimeSpan(0, 0, 30)));
     }
     catch (ArgumentException ex)
     {
         throw new ExecutionFailureException($"Error evaluating regex \"{this.MatchExpression}\": {ex.Message}");
     }
 }
예제 #14
0
        public override RuntimeValue Evaluate(IVariableFunctionContext context)
        {
            var execContext = context as IOperationExecutionContext;

            if (execContext == null)
            {
                throw new NotSupportedException("This function can currently only be used within an execution.");
            }

            return(execContext.ExpandVariables(this.Text));
        }
예제 #15
0
 protected override object EvaluateScalar(IVariableFunctionContext context)
 {
     if (string.IsNullOrEmpty(this.Format))
     {
         return(DateTime.UtcNow.ToString("yyyy-MM-ddThh:mm:ss"));
     }
     else
     {
         return(DateTime.UtcNow.ToString(this.Format));
     }
 }
        protected override object EvaluateScalar(IVariableFunctionContext context)
        {
            if (!Enum.TryParse <Environment.SpecialFolder>(this.Name, out var result))
            {
                throw new ExecutionFailureException("Invalid special folder name: " + this.Name);
            }

            if (context is IOperationExecutionContext c && c.Agent != null)
            {
                var remote = c.Agent.GetService <IRemoteMethodExecuter>();
                return(remote.InvokeFunc(Environment.GetFolderPath, result));
            }
        protected override object EvaluateScalar(IVariableFunctionContext context)
        {
            foreach (var arg in this.Arguments ?? Enumerable.Empty <string>())
            {
                if (!string.IsNullOrWhiteSpace(arg))
                {
                    return(arg);
                }
            }

            return(string.Empty);
        }
        protected override IEnumerable EvaluateVector(IVariableFunctionContext context)
        {
            int?roleId = FindRole(this.RoleName, context);

            if (roleId == null)
            {
                return(null);
            }

            return(SDK.GetServersInRole(roleId.Value)
                   .Where(s => this.IncludeInactive || s.Active)
                   .Select(s => s.Name));
        }
예제 #19
0
        protected override IEnumerable EvaluateVector(IVariableFunctionContext context)
        {
            int?environmentId = FindEnvironment(this.EnvironmentName, context);

            if (environmentId == null)
            {
                return(null);
            }

            return(SDK.GetServersInEnvironment(environmentId.Value)
                   .Where(s => this.IncludeInactive || s.Active)
                   .Select(s => s.Name));
        }
        protected override object EvaluateScalar(IVariableFunctionContext context)
        {
            var execContext = context as IOperationExecutionContext;

            if (execContext == null)
            {
                throw new VariableFunctionException("Execution context is not available.");
            }

            var remote = execContext.Agent.GetService <IRemoteProcessExecuter>();

            return(remote.GetEnvironmentVariableValue(this.EnvironmentVariableName) ?? string.Empty);
        }
        protected override object EvaluateScalar(IVariableFunctionContext context)
        {
            int?serverId = (context as IStandardContext)?.ServerId;

            if (serverId != null)
            {
                return(SDK.GetServers(true).FirstOrDefault(s => s.Id == serverId)?.Name);
            }
            else
            {
                return(string.Empty);
            }
        }
예제 #22
0
        private int?FindEnvironment(string environmentName, IVariableFunctionContext context)
        {
            var allEnvironments = SDK.GetEnvironments();

            if (!string.IsNullOrEmpty(environmentName))
            {
                return(allEnvironments.FirstOrDefault(e => e.Name.Equals(environmentName, StringComparison.OrdinalIgnoreCase))?.Id);
            }
            else
            {
                return(context.EnvironmentId);
            }
        }
예제 #23
0
        private int?FindRole(string roleName, IVariableFunctionContext context)
        {
            var allRoles = SDK.GetServerRoles();

            if (!string.IsNullOrEmpty(roleName))
            {
                return(allRoles.FirstOrDefault(r => r.Name.Equals(roleName, StringComparison.OrdinalIgnoreCase))?.Id);
            }
            else
            {
                return((context as IStandardContext)?.ServerRoleId);
            }
        }
        protected override object EvaluateScalar(IVariableFunctionContext context)
        {
            var execContext = context as IOperationExecutionContext;

            if (execContext == null)
            {
                throw new VariableFunctionException("Execution context is not available.");
            }

            return(execContext.Agent
                   .GetService <IFileOperationsExecuter>()
                   .DirectoryExists(execContext.ResolvePath(this.DirectoryName)));
        }
 protected override object EvaluateScalar(IVariableFunctionContext context)
 {
     using (var writer = new StringWriter())
     {
         using (var json = new JsonTextWriter(writer)
         {
             CloseOutput = false
         })
         {
             WriteJson(json, this.Data);
         }
         return(writer.ToString());
     }
 }
예제 #26
0
        protected override IEnumerable EvaluateVector(IVariableFunctionContext context)
        {
            var execContext = context as IOperationExecutionContext;

            if (execContext == null)
            {
                throw new VariableFunctionException("Execution context is not available.");
            }

            var fileOps   = execContext.Agent.GetService <IFileOperationsExecuter>();
            var fileInfos = fileOps.GetFileSystemInfosAsync(execContext.WorkingDirectory, new MaskingContext(this.Includes, this.Excludes)).Result();

            return(fileInfos.Select(fi => fi.FullName));
        }
        protected override IEnumerable EvaluateVector(IVariableFunctionContext context)
        {
            var list = this.List.ToList();

            if (this.Index.HasValue)
            {
                list.Insert(this.Index.Value, this.Item);
            }
            else
            {
                list.Add(this.Item);
            }
            return(list);
        }
예제 #28
0
        protected override object EvaluateScalar(IVariableFunctionContext context)
        {
            var name = Inedo.Extensibility.Credentials.CredentialName.TryParse(this.CredentialName);

            if (name == null)
            {
                throw new ExecutionFailureException(true, $"The specified credential name \"{this.CredentialName}\" is invalid.");
            }

            // need to resolve credential type name if it's not specified with the scope resolution operator
            if (name.TypeName == null)
            {
                var types = (from c in SDK.GetCredentials()
                             where string.Equals(c.Name, name.Name, StringComparison.OrdinalIgnoreCase)
                             select c.LegacyResourceCredentialTypeName).ToHashSet(StringComparer.OrdinalIgnoreCase);

                if (types.Count == 0)
                {
                    throw new ExecutionFailureException(true, $"There are no credentials named \"{name.Name}\" found in the system.");
                }
                if (types.Count > 1)
                {
                    throw new ExecutionFailureException(true, $"There are multiple credential types with the name \"{name.Name}\" found in the system. Use the scope resolution operator (i.e. ::) to specify a type, for example: UsernamePassword::{name.Name}");
                }

                name = new CredentialName(types.First(), name.Name);
            }

            var credential = ResourceCredentials.TryCreate(name.TypeName, name.Name, environmentId: context.EnvironmentId, applicationId: context.ProjectId, inheritFromParent: true);

            if (credential == null)
            {
                throw new ExecutionFailureException($"Could not find a {name.TypeName} Resource Credentials named \"{name.Name}\"; this error may occur if you renamed a credential, or the application or environment in context does not match any existing credentials. To resolve, edit this item, property, or operation's configuration, ensure a valid credential for the application/environment in context is selected, and then save.");
            }

            if (!(credential is JenkinsLegacyCredentials))
            {
                throw new ExecutionFailureException($"Resource Credential \"{name.Name}\" is not a Jenkins Credential.");
            }

            var jenkins = (JenkinsLegacyCredentials)credential;

            UriBuilder uri = new UriBuilder(jenkins.ServerUrl)
            {
                Path = JenkinsClient.GetPath(this.JobName, this.BranchName, this.BuildNumber)
            };

            return(uri.ToString());
        }
예제 #29
0
        public async Task <RuntimeValue> EvaluateAsync(IVariableFunctionContext context)
        {
            var execContext = context as IOperationExecutionContext;

            if (execContext == null)
            {
                throw new VariableFunctionException("Execution context is not available.");
            }

            var fileOps = await execContext.Agent.GetServiceAsync <IFileOperationsExecuter>().ConfigureAwait(false);

            var fileInfos = await fileOps.GetFileSystemInfosAsync(execContext.WorkingDirectory, new MaskingContext(this.Includes, this.Excludes)).ConfigureAwait(false);

            return(new RuntimeValue(fileInfos.Select(fi => new RuntimeValue(fi.FullName))));
        }
예제 #30
0
        protected override object EvaluateScalar(IVariableFunctionContext context)
        {
            var chars = (from s in this.CharactersToTrim ?? new string[0]
                         where s.Length == 1
                         select s[0]).ToArray();

            if (chars.Length > 0)
            {
                return(this.Text.TrimEnd(chars));
            }
            else
            {
                return(this.Text.TrimEnd());
            }
        }