Exemple #1
0
        public void WhenFilePathEndsWithDot_ShouldReturnEmpty( )
        {
            var    fixture = new Fixture( );
            string result  = LinuxPath.GetExtension("/some/path/{0}.".With(fixture.Create("file-")));

            Assert.Equal(string.Empty, result);
        }
Exemple #2
0
        public void WhenFilePathContainsExtension_ShouldReturnExtension()
        {
            var    fixture = new Fixture( );
            string result  = LinuxPath.GetExtension("/some/path/{0}.ext".With(fixture.Create("file-")));

            Assert.Equal(".ext", result);
        }
Exemple #3
0
        public void WhenPathDoesNotFile_ShouldReturnEmpty( )
        {
            var    fixture = new Fixture( );
            string result  = LinuxPath.GetExtension("/some/path/{0}/".With(fixture.Create("path-")));

            Assert.Equal(string.Empty, result);
        }
Exemple #4
0
        /// <summary>
        /// this is a fallback if the mkdir -p fails for somereason
        /// </summary>
        /// <param name="path"></param>
        internal void MakeDirectoryFallbackInternal(string path, CommandErrorReceiver cer)
        {
            string[]  segs    = path.Split(new char[] { LinuxPath.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
            FileEntry current = Device.FileListingService.Root;

            foreach (var pathItem in segs)
            {
                FileEntry[] entries = Device.FileListingService.GetChildren(current, true, null);
                bool        found   = false;
                foreach (var e in entries)
                {
                    if (string.Compare(e.Name, pathItem, false) == 0)
                    {
                        current = e;
                        found   = true;
                        break;
                    }
                }

                if (!found)
                {
                    current = FileEntry.FindOrCreate(Device, LinuxPath.Combine(current.FullPath, pathItem + new string(new char[] { LinuxPath.DirectorySeparatorChar })));
                    Device.ExecuteShellCommand("mkdir {0}", cer, current.FullEscapedPath);
                }
            }
        }
Exemple #5
0
 public void ChangeExtension()
 {
     Assert.Equal("test.one", LinuxPath.ChangeExtension("test", "one"));
     Assert.Equal("test.one", LinuxPath.ChangeExtension("test.zero", "one"));
     Assert.Equal("/foo/test.one", LinuxPath.ChangeExtension("\\foo\\test", "one"));
     Assert.Equal("/foo/test.one", LinuxPath.ChangeExtension("\\foo\\test.zero", "one"));
 }
Exemple #6
0
        public void WhenPathIsNull_ShouldReturnNull( )
        {
            var fixture = new Fixture( );
            var result  = LinuxPath.GetFileName(null);

            Assert.Null(result);
        }
Exemple #7
0
        /// <summary>
        /// Edits the [neon-proxy-public-bridge.sh] and [neon-proxy-private-bridge.sh]
        /// scripts to remove the [VAULT_CREDENTIALS] environment variable so the new
        /// .NET based proxy bridge image will work properly.
        /// </summary>
        /// <param name="node">The target node.</param>
        private void UpdateProxyBridgeScripts(SshProxy <NodeDefinition> node)
        {
            var scriptNames =
                new string[]
            {
                "neon-proxy-public-bridge.sh",
                "neon-proxy-private-bridge.sh"
            };

            foreach (var scriptName in scriptNames)
            {
                var scriptPath = LinuxPath.Combine(HiveHostFolders.Scripts, scriptName);
                var scriptText = node.DownloadText(scriptName);
                var sbEdited   = new StringBuilder();

                using (var reader = new StringReader(scriptText))
                {
                    foreach (var line in reader.Lines())
                    {
                        if (!line.Contains("--env VAULT_CREDENTIALS="))
                        {
                            sbEdited.AppendLineLinux(line);
                        }
                    }
                }

                node.UploadText(scriptPath, sbEdited.ToString(), permissions: "700");
            }
        }
Exemple #8
0
        /// <summary>
        /// Starts a neonHIVE related Docker container on a node and also uploads a script
        /// to make it easy to restart the container manually or for hive updates.
        /// </summary>
        /// <param name="node">The target hive node.</param>
        /// <param name="containerName">Identifies the container.</param>
        /// <param name="image">The Docker image to be used by the container.</param>
        /// <param name="runOptions">Optional run options (defaults to <see cref="RunOptions.FaultOnError"/>).</param>
        /// <param name="commands">The commands required to start the container.</param>
        /// <remarks>
        /// <para>
        /// This method performs the following steps:
        /// </para>
        /// <list type="number">
        ///     <item>
        ///     Passes <paramref name="image"/> to <see cref="Program.ResolveDockerImage(string)"/> to
        ///     obtain the actual image to be started.
        ///     </item>
        ///     <item>
        ///     Generates the first few lines of the script file that sets the
        ///     default image as the <c>TARGET_IMAGE</c> macro and then overrides
        ///     this with the script parameter (if there is one).
        ///     </item>
        ///     <item>
        ///     Appends the commands to the script, replacing any text that matches
        ///     <see cref="ImagePlaceholderArg"/> with <c>${TARGET_IMAGE}</c> to make it easy
        ///     for services to be upgraded later.
        ///     </item>
        ///     <item>
        ///     Starts the container.
        ///     </item>
        ///     <item>
        ///     Uploads the generated script to the node to [<see cref="HiveHostFolders.Scripts"/>/<paramref name="containerName"/>.sh].
        ///     </item>
        /// </list>
        /// </remarks>
        public static void StartContainer(SshProxy <NodeDefinition> node, string containerName, string image, RunOptions runOptions = RunOptions.FaultOnError, params IBashCommandFormatter[] commands)
        {
            Covenant.Requires <ArgumentNullException>(node != null);
            Covenant.Requires <ArgumentNullException>(!string.IsNullOrWhiteSpace(containerName));
            Covenant.Requires <ArgumentNullException>(!string.IsNullOrWhiteSpace(image));
            Covenant.Requires <ArgumentNullException>(commands != null);
            Covenant.Requires <ArgumentNullException>(commands.Length > 0);

            node.Status = $"start: {containerName}";

            // Generate the container start script.

            var script = CreateStartScript(containerName, image, true, commands);

            // Upload the script to the target node and set permissions.

            var scriptPath = LinuxPath.Combine(HiveHostFolders.Scripts, $"{containerName}.sh");

            node.UploadText(scriptPath, script);
            node.SudoCommand($"chmod 740 {scriptPath}");

            // Run the script without a parameter to start the container.

            node.IdempotentDockerCommand($"setup/{containerName}", null, runOptions, scriptPath);

            node.Status = string.Empty;
        }
Exemple #9
0
        public void SyncServicePullFileTest()
        {
            Device             device             = GetFirstDevice();
            FileListingService fileListingService = new FileListingService(device);

            using (ISyncService sync = device.SyncService)
            {
                String    rfile  = "/sdcard/bootanimations/bootanimation-cm.zip";
                FileEntry rentry = fileListingService.FindFileEntry(rfile);

                String     lpath  = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                String     lfile  = Path.Combine(lpath, LinuxPath.GetFileName(rfile));
                FileInfo   lfi    = new FileInfo(lfile);
                SyncResult result = sync.PullFile(rfile, lfile, new FileSyncProgressMonitor());

                Assert.IsTrue(lfi.Exists);
                Assert.IsTrue(ErrorCodeHelper.RESULT_OK == result.Code, ErrorCodeHelper.ErrorCodeToString(result.Code));
                lfi.Delete();

                result = sync.PullFile(rentry, lfile, new FileSyncProgressMonitor());
                Assert.IsTrue(lfi.Exists);
                Assert.IsTrue(ErrorCodeHelper.RESULT_OK == result.Code, ErrorCodeHelper.ErrorCodeToString(result.Code));
                lfi.Delete();
            }
        }
Exemple #10
0
        /// <summary>
        /// <para>
        /// Installs the tool scripts, making them executable.
        /// </para>
        /// <note>
        /// Any <b>".sh"</b> file extensions will be removed for ease-of-use.
        /// </note>
        /// </summary>
        /// <param name="controller">The setup controller.</param>
        public void BaseInstallToolScripts(ISetupController controller)
        {
            Covenant.Requires <ArgumentException>(controller != null, nameof(controller));

            InvokeIdempotent("base/tool-scripts",
                             () =>
            {
                controller.LogProgress(this, verb: "setup", message: "tools (base)");

                // Upload any tool scripts to the neonKUBE bin folder, stripping
                // the [*.sh] file type (if present) and then setting execute
                // permissions.

                var scriptsFolder = KubeHelper.Resources.GetDirectory("/Tools");        // $hack(jefflill): https://github.com/nforgeio/neonKUBE/issues/1121

                foreach (var file in scriptsFolder.GetFiles())
                {
                    var targetName = file.Name;

                    if (Path.GetExtension(targetName) == ".sh")
                    {
                        targetName = Path.GetFileNameWithoutExtension(targetName);
                    }

                    using (var toolStream = file.OpenStream())
                    {
                        UploadText(LinuxPath.Combine(KubeNodeFolder.Bin, targetName), toolStream, permissions: "744");
                    }
                }
            });
        }
Exemple #11
0
        /// <summary>
        /// Pushes a file to device
        /// </summary>
        /// <param name="localFilePath">the absolute path to file on local host</param>
        /// <returns>destination path on device for file</returns>
        /// <exception cref="IOException">if fatal error occurred when pushing file</exception>
        public String SyncPackageToDevice(String localFilePath)
        {
            try {
                String packageFileName = Path.GetFileName(localFilePath);
                // only root has access to /data/local/tmp/... not sure how adb does it then...
                // workitem: 16823
                // workitem: 19711
                String remoteFilePath = LinuxPath.Combine(TEMP_DIRECTORY_FOR_INSTALL, packageFileName);

                Console.WriteLine(String.Format("Uploading {0} onto device '{1}'", packageFileName, SerialNumber));
                Log.d(packageFileName, String.Format("Uploading {0} onto device '{1}'", packageFileName, SerialNumber));

                SyncService sync = SyncService;
                if (sync != null)
                {
                    String message = String.Format("Uploading file onto device '{0}'", SerialNumber);
                    Log.d(LOG_TAG, message);
                    SyncResult result = sync.PushFile(localFilePath, remoteFilePath, SyncService.NullProgressMonitor);

                    if (result.Code != ErrorCodeHelper.RESULT_OK)
                    {
                        throw new IOException(String.Format("Unable to upload file: {0}", result.Message));
                    }
                }
                else
                {
                    throw new IOException("Unable to open sync connection!");
                }
                return(remoteFilePath);
            } catch (IOException e) {
                Log.e(LOG_TAG, String.Format("Unable to open sync connection! reason: {0}", e.Message));
                throw;
            }
        }
Exemple #12
0
        /// <summary>
        /// Recursively fills the pathBuilder with the full path
        /// </summary>
        /// <param name="pathBuilder">a StringBuilder used to create the path.</param>
        /// <param name="escapePath">Whether the path need to be escaped for consumption by a shell command line.</param>
        /// <param name="resolveLinks">if set to <see langword="true"/> [resolve links].</param>
        protected void FillPathBuilder(StringBuilder pathBuilder, bool escapePath, bool resolveLinks)
        {
            if (IsRoot)
            {
                return;
            }

            // If the symlink is an absolute path, we don't need to recurse.
            if (resolveLinks &&
                !string.IsNullOrEmpty(LinkName) &&
                LinuxPath.IsPathRooted(LinkName))
            {
                pathBuilder.Append(escapePath ? LinuxPath.Quote(LinkName) : LinkName);
            }
            else
            {
                // Else, get the path of the parent.
                if (Parent != null)
                {
                    Parent.FillPathBuilder(pathBuilder, escapePath, resolveLinks);
                }

                String n = resolveLinks && !String.IsNullOrEmpty(LinkName) ? LinkName : Name;

                if (n[0] != LinuxPath.DirectorySeparatorChar)
                {
                    pathBuilder.Append(LinuxPath.DirectorySeparatorChar);
                }

                pathBuilder.Append(escapePath ? LinuxPath.Quote(n) : n);
            }
        }
Exemple #13
0
        public void WhenPathIsRelative_ShouldReturnRelativeCurrentPath( )
        {
            var fixture = new Fixture( );
            var path    = fixture.Create("path-");
            var result  = LinuxPath.GetPathRoot(path);

            Assert.Equal("./", result);
        }
Exemple #14
0
        public void IsPathRooted()
        {
            Assert.True(LinuxPath.IsPathRooted("\\one\\two\\three.txt"));
            Assert.True(LinuxPath.IsPathRooted("/one/two/three.txt"));

            Assert.False(LinuxPath.IsPathRooted("one\\two\\three"));
            Assert.False(LinuxPath.IsPathRooted("one/two/three"));
        }
Exemple #15
0
        public void HasExtension()
        {
            Assert.True(LinuxPath.HasExtension("\\one\\two\\three.txt"));
            Assert.True(LinuxPath.HasExtension("/one/two/three.txt"));

            Assert.False(LinuxPath.HasExtension("\\one\\two\\three"));
            Assert.False(LinuxPath.HasExtension("/one/two/three"));
        }
        public void WhenPathRelative_ShouldReturnRelativePath( )
        {
            var    fixture = new Fixture( );
            var    p       = fixture.Create("path");
            string result  = LinuxPath.GetDirectoryName(p);

            Assert.Equal("./{0}/".With(p), result);
        }
Exemple #17
0
        public void When2ArgsAndPath1IsEmptyAndPath2IsRooted_ShouldReturnRootedPath2( )
        {
            var fixture = new Fixture( );
            var p2      = fixture.Create("/path2-");
            var result  = LinuxPath.Combine(string.Empty, p2);

            Assert.Equal("/{0}/".With(p2).REReplace("//", "/"), result);
        }
Exemple #18
0
        public void When2ArgsAndPath1IsEmpty_ShouldReturnRelativePath2( )
        {
            var fixture = new Fixture( );
            var p2      = fixture.Create("path2-");
            var result  = LinuxPath.Combine(string.Empty, p2);

            Assert.Equal("./{0}/".With(p2), result);
        }
Exemple #19
0
        public void When4ArgsAndPath4IsNull_ShouldThrowArgumentNullException( )
        {
            var fixture = new Fixture( );

            Assert.Throws <ArgumentNullException> (() => {
                var result = LinuxPath.Combine(fixture.Create("path1"), fixture.Create("path2"), fixture.Create("path3"), null);
            });
        }
Exemple #20
0
        public void WhenPathDoesNotHaveFile_ShouldReturnFalse( )
        {
            var fixture = new Fixture( );
            var path    = "/path/to/file/";
            var result  = LinuxPath.HasExtension(path);

            Assert.False(result);
        }
        public void WhenPathRooted_ShouldReturnRootPath( )
        {
            var    fixture = new Fixture( );
            var    p       = "/{0}/".With(fixture.Create("path"));
            string result  = LinuxPath.GetDirectoryName(p);

            Assert.Equal(p, result);
        }
Exemple #22
0
        public void WhenPathDoesNotContainCharactersToEscape_ShouldReturnPathUnchanged( )
        {
            var fixture = new Fixture( );
            var p1      = fixture.Create("p1-");
            var result  = LinuxPath.Escape(p1);

            Assert.Equal(p1, result);
        }
Exemple #23
0
        public void WhenPathIsRooted_ShouldReturnRootPath()
        {
            var fixture = new Fixture( );
            var path    = fixture.Create("/path-");
            var result  = LinuxPath.GetPathRoot(path);

            Assert.Equal("/", result);
        }
Exemple #24
0
        public void When2ArgsAndPathsHaveSeparators_ShouldReturnCombined( )
        {
            var fixture = new Fixture( );
            var p1      = "{0}/".With(fixture.Create("/path1"));
            var p2      = fixture.Create("path2");
            var result  = LinuxPath.Combine(p1, p2);

            Assert.Equal("{0}/{1}".With(p1, p2).REReplace("//", "/"), result);
        }
Exemple #25
0
        public void When2ArgsAndPath2IsRooted_ShouldReturnPath2( )
        {
            var fixture = new Fixture( );
            var p1      = fixture.Create("/path1-");
            var p2      = fixture.Create("/path2-");
            var result  = LinuxPath.Combine(p1, p2);

            Assert.Equal("{0}/".With(p2), result);
        }
Exemple #26
0
        public void WhenArgsArrayIsNull_ShouldThrowArgumentNullException( )
        {
            var fixture = new Fixture( );

            string[] args = null;
            Assert.Throws <ArgumentNullException> (() => {
                LinuxPath.Combine(args);
            });
        }
Exemple #27
0
        public void WhenValueDoesNotHaveSpace_ShouldReturnValue( )
        {
            var fixture = new Fixture( );

            var val    = fixture.Create("value-");
            var result = LinuxPath.Quote(val);

            Assert.Equal(val, result);
        }
Exemple #28
0
        public void WhenValueHasSpace_ShouldReturnQuotedValue()
        {
            var fixture = new Fixture( );

            var val    = fixture.Create("value ");
            var result = LinuxPath.Quote(val);

            Assert.Equal("\"{0}\"".With(val), result);
        }
Exemple #29
0
        public void WhenPathHasExtension_ShouldReturnTrue( )
        {
            var fixture = new Fixture( );
            var file    = fixture.Create("file-");
            var path    = "/path/to/file/{0}.ext".With(file);
            var result  = LinuxPath.HasExtension(path);

            Assert.True(result);
        }
Exemple #30
0
        public void WhenPathDoesNotHaveExtension_ShouldReturnFalse( )
        {
            var fixture = new Fixture( );
            var file    = fixture.Create("file-");
            var path    = "/path/to/file/{0}".With(file);
            var result  = LinuxPath.HasExtension(path);

            Assert.False(result);
        }