transitioning to net core on red hat enterprise linux

69 87 0
transitioning to net core on red hat enterprise linux

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Programming Transitioning to NET Core on Red Hat Enterprise Linux Don Schenck Transitioning to NET Core on Red Hat Enterprise Linux by Don Schenck Copyright © 2017 O’Reilly Media All rights reserved Printed in the United States of America Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472 O’Reilly books may be purchased for educational, business, or sales promotional use Online editions are also available for most titles (http://oreilly.com/safari) For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com Editors: Nan Barber and Susan Conant Production Editor: Melanie Yarbrough Copyeditor: Gillian McGarvey Proofreader: Jasmine Kwityn Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Rebecca Demarest September 2016: First Edition Revision History for the First Edition 2016-09-20: First Release 2016-10-21: Second Release 2016-12-06: Third Release The O’Reilly logo is a registered trademark of O’Reilly Media, Inc Transitioning to NET Core on Red Hat Enterprise Linux, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work Use of the information and instructions contained in this work is at your own risk If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights 978-1-491-97055-3 [LSI] What to Expect from This Book This book is targeted at—but not limited to—.NET developers with any level of experience Starting with a basic “Hello World” console application, it moves along through ASP.NET, MVC, and Entity Framework applications, eventually arriving at a full-featured application running in a Linux container Because the code in this book is limited to C#, your existing knowledge of NET and C# will largely determine the speed at which you progress through this volume More experienced developers will be interested in the few key differences when developing for Linux (and there are quite a few), whereas beginning developers can use this book to learn more advanced programming techniques—the fact that those techniques are related to NET Core is just icing on the cake If you’ve spent most of your time writing code in a language other than C#, with Linux as your native operating system, don’t fret Though knowledge of C# is highly recommended, even a novice developer with a desire to learn can use this volume, perhaps in concert with another manual that guides the reader in C# development Some Assumptions This book assumes some previous experience with the NET Framework Again, while it’s technically not necessary to have prior knowledge when you begin reading, you will need to be familiar with NET (either by experience or education) to understand what’s happening Again, not to worry—the knowledge needed isn’t as deep as you might fear Grasp a few key concepts and you’ll be good to go For the purposes of simplicity, the Linux distribution used in the examples will be Red Hat Enterprise Linux (RHEL) Any adjustments necessary for other Linux distributions will be pointed out as we go Your Environment To follow along with the narrative and code, you need to install the Red Hat Container Development Kit (CDK) and clone or download a repository from GitHub Step-by-step instructions are provided in Chapter Formatting The following typographical conventions are used in this book: Text will be in the typeface you are reading now // Code is formatted like this: using System; namespace ConsoleApplication { public class Program { public static void Main(string[] args) { Console.WriteLine("Hello World!"); } } } Command-line commands will be shown like this Italic Indicates new terms, URLs, email addresses, filenames, and file extensions Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords Constant width bold Shows commands or other text that should be typed literally by the user Constant width italic Shows text that should be replaced with user-supplied values or by values determined by context TIP This element signifies a tip or suggestion NOTE This element signifies a general note WARNING This element indicates a warning or caution NET Core Is the Future In November 2014, Microsoft announced that the NET Framework would be transitioned to an open source development model This announcement was met with surprise and open arms by the NET community Although Microsoft had, up to that moment, done an admirable job of soliciting input from developers about NET features and bugs, making the source available meant a much higher level of engagement The standard open source model of using a GitHub repo—with issues, milestones, pull requests, and the related discussions—meant that anyone, anywhere could have instant and transparent access to the development team Developers could participate in discussions and research defects and workarounds Schedules and roadmaps would now be available to everyone, leading to more realistic expectations Surprise announcements would give way to planned milestones Meanwhile, developers outside the NET world saw this as an opportunity to bring their open source experience and knowledge to one of the more pervasive software development platforms The free exchange of ideas, code reviews, and sense of community found its place inside the Microsoft-centric developer’s world The infusion of non-.NET developers meant that “dot netters” could gain a broader view of development in general This is a very good thing This is the new model This is the future .NET Core is not just another NET Framework Rather, it is the future of NET Microsoft has stated that the previous framework, 4.6.1, will still be supported, and bug fixes will be applied, but any new NET features will be reserved for NET Core Using NET Core as your basis for future work is in line with Microsoft’s stated intentions While migrating existing code to NET Core may or may not be a good idea, future development should be based on NET Core if possible In short, this is the NET Framework Period Full stop What’s Missing Because some parts of NET are either specific to Windows or outdated, not everything made the journey from proprietary software to the open source model and NET Core 1.0 Here’s a list of some of the things that didn’t make the transition: MWF (Windows Forms) Web forms WCF (SOAP) In addition, some things haven’t been ported yet—perhaps the biggest being SignalR Microsoft has publicly stated that SignalR will be ported to NET Core NOTE From this point on, unless the difference is worth noting, references to NET CoreCLR, CoreFX, and the like, will be simplified to “.NET” What’s New NET is more modular now, which is a definite benefit from starting over when designing the framework Parts that were previously included by default are now excluded by default Even what may seem to be the most basic items, such as the ability to render static files in an ASP.NET page, are now optional This means that you need to be more expressive in your coding, but it also results in performance improvements The trade-off is worth the cost: writing code is easier than optimizing code Chapter 10 Editing from Windows Running Linux in a VM is a great solution for Windows developers who prefer to stay in their Windows development environment Whether the VM runs on your local machine or in the cloud, you can use it to develop NET code while keeping your Windows desktop environment undisturbed If you are running Linux in a “headless” configuration, that means you don’t have access to a UI for the OS While you can edit code using vi, one of Linux’s command line–based editors, it doesn’t support IntelliSense, color coding, tree views of projects, and various other features In short, it is quite the suboptimal environment Wouldn’t it be great if you could open VS Code or Visual Studio and edit the code on your Linux VM? Well, you can You can keep and run your code in Linux while, at the same time, editing it from Visual Studio or VS Code running in Windows Figure 10-1 illustrates the idea Figure 10-1 Edit your Linux code from the Windows desktop Within your Windows desktop environment, run your editor (any editor will work; we’ll assume you’re using VS Code) and point it to a folder that is shared between your Windows host and the Linux VM Any changes on either side are reflected on the other, as you would expect FOLDERS VERSUS DIRECTORIES In this chapter, “folder” is used when discussing the Windows environment, and “directory” is used when discussing the Linux environment These seem to be the standard terms for these environments The Key: Sharing The following example assumes you have installed your VM using the instructions in Chapter This installation uses Vagrant and Virtual Box to host your VM If you are using a RHEL image in HyperV, for example, you’ll need to enable folder sharing using cifs Details about using cifs to share a folder can be found by searching the Red Hat Customer Portal Using the Red Hat Container Developer Kit (CDK), found at the CDK download page, setting up a shared folder/directory is simple and takes just five steps Step 1: Create a Share on Your Windows PC We’ll be using the command line to create and share a folder in Windows, so open Powershell using the “Run as Administrator” option For this example, we’ll keep it simple and put a share directly off the root of the C drive Create a folder, giving it any name; we’ll use “LinuxShare” NEW-ITEM C:\SharedWithVM -type directory PowerShell will verify the new folder: Directory: C:\ Mode -d - LastWriteTime Length Name -8/8/2016 3:59 PM SharedCode Step 2: Share the Folder Now that the folder is created, use the following command to create a Windows shared folder: New-SmbShare -Name ShareWithVM -Path C:\ShareWithVM -FullAccess Username Replace Username with your Windows username Step 3: Share the Folder with Your Linux VM Because we’re using Vagrant (as part of the Red Hat CDK), you can share the folder between Windows and Linux by adding the following entry to your Vagrantfile: synced_folder "\\ShareWithVM", ​ "/sharewithvm", ​ type: "smb", ​ smb_username: "username", ​ smb_password: "password" Replace username and password with your Windows logon username and password If you are using a PC that is not joined to a domain (e.g., your home PC), and if your account is linked to a Microsoft account, you’ll need to use your Microsoft account information here Step 4: Restart the VM With the changes made, enable them by restarting your VM: vagrant reload Step 5: Move into the VM and View the Directory Next, ssh into the VM: vagrant ssh Finally, you can view the contents of the shared directory: ls /sharewithvm Now, anything you place into this directory is available from both the Linux VM and your Windows desktop Open Visual Studio or VS Code and you will be able to edit your code In the next chapter, we’ll see how you can run and debug your code, which is running in a Linux VM, from Visual Studio running on Windows Chapter 11 “Off-Road” Debugging When I first heard about debugging NET on Linux from Visual Studio, I was both excited about the idea and curious about how it was done What I didn’t wonder about at the time was what it was called It wasn’t too long, however, before I heard it called “off-road debugging” and fell in love with the term After all, this is certainly “off the beaten path” when it comes to debugging At the time of writing (August 2016), this is most definitely not a point-and-click procedure In fact, there are five steps to get started—although after the initial setup, it’s rather simple and fast for future debugging Once a VM is configured to allow off-road debugging, adding this feature to a project is one step to configure and one command to launch I have no insight, but I wouldn’t be surprised if this isn’t folded into a future release of NET tooling ASSOCIATED SOURCE CODE The source code can be found in the /NetOnLinuxBook/HelloMvcApi/ directory Installation and Configuration Because this feature is not built into the current NET tooling, we’ll need to install and configure it It takes six steps, but the first four steps are done only once per VM; the final two steps are done once for each project This way, once you’ve set things up, it just takes a quick configuration in your project and you’re ready to debug from inside Visual Studio Step 1: Enable Visual Studio on Windows You need Visual Studio 2015 Update or newer to enable debugging Any version works, including the no-charge Community Edition MIDebugEngine is the Windows-side executable that talks to the Linux-side application To enable MIDebugEngine you need to enable C++ iOS development: Open the Programs and Features applet in the Control Panel Right-click on Microsoft Visual Studio 2015 and select the Change option When the dialog box appears, select the Modify button Navigate to Cross Platform Mobile Development→Visual C++ Mobile Development→Visual C++ iOS Development and enable debugging Step 2: Install CLRDBG on the Linux VM CLRDBG is the new cross-platform command-line debugger from Microsoft, used for debugging NET Core code It’s based on the same debugger that’s been built into Visual Studio, which was then made to run on all platforms: Windows, Linux, and OS X A wrapper, which allows CLRDBG to talk to the underlying Machine Interface (MI) layer, was added as the command line tool Installation is a snap—it just takes one simple command: curl -sSL https://raw.githubusercontent.com/Microsoft/MIEngine/ getclrdbg-release/scripts/GetClrDbg.sh | bash /dev/stdin vs2015u2 ~/clrdbg This command reads a script from the GitHub repo and executes it, installing CLRDBG You can install it into any directory; I suggest ~/clrdbg because it’s easy to remember Step 3: Set Up SSH This is the longest step but once it’s done you won’t need to it again SSH, or Secure Shell, allows you to securely connect to your VM from the Windows machine This connection allows you to control the debugging from Visual Studio on your Windows machine While Microsoft has promised SSH as part of a future release of Windows, we need it now PuTTY is the de facto standard in the Windows world; it can be downloaded from the PuTTY page For debugging, we won’t need a graphical interface for PuTTY; we will connect from the command line Though we don’t need putty.exe, we need a desktop tool—PuTTYgen.exe—to configure secure keys that allow us to authenticate the Windows session against the Linux VM We’ll also be using the plink.exe tool, which can also be downloaded from the same site Download PuTTYgen.exe and plink.exe and put them anywhere A good place (because it’s easy to remember) is C:\mytools With the tool in hand, we can generate public and private keys to be used for authentication Run PuTTYgen.exe and click the Generate button (as shown in Figure 11-1), then follow the instructions on the screen This will create public and private keys that allow us to gain access to the Linux VM from a command line Figure 11-1 Using PuTTYgen to generate public and private keys Click “Save private key,” as shown in Figure 11-2, to save the private key to a file on your hard drive I’ll use C:\mytools\private_key.ppk for this example If a prompt asks if you want to save without a passphrase, select Yes Next, select the “Public key for pasting into OpenSSH authorized_keys file:” contents and copy it to your clipboard, making certain that all of the characters are selected Figure 11-2 Paste this public key into ~/.ssh/authorized_keys In the VM, paste the public key to the end of the file ~/.ssh/authorized_keys The easiest way is to use the vi editor If you’re not familiar with vi, I suggest finding a good cheat sheet on the Internet Jokes are made about attempts to simply exit vi—yes, it’s that different from any Windows editor! Trust me; you want a cheat sheet Once this is done, the Windows ssh client will pass the contents of the private key (in C:\mytools\private_key.ppk) to the VM, where OpenSSH will use an encryption algorithm to generate a key to compare to the contents of the ~/.ssh.authorized_keys file to grant or deny access You can test everything with the following command, substituting your Windows username where needed: c:\mytools\plink.exe -i c:\mytools\private_key.ppk vagrant@127.0.0.1 -P 2222 -batch -t echo "SSH Successful!" You should see something like what’s shown in Figure 11-3 Figure 11-3 A successful command-line ssh test Step 4: Share a Folder/Directory Step 4: Share a Folder/Directory If you completed the steps in Chapter 10, you’ve already done this Otherwise, refer to that chapter to share a folder/directory between Windows and the Linux VM At this point, open Visual Studio and point it to the project.json file in your project If you see errors, you can ignore them Step 5: Create Launch Options File When you launch the debugger, the launch options file provides the necessary parameters I this in Visual Studio, adding the file to the root of the project You can give it any name—I call it OffRoadDebug.xml The contents should reflect your environment, as the following does for our example: Most of the contents are self-explanatory, but there are some things to note: PipePath points to the plink.exe that was downloaded from the PuTTY website This is the command-line SSH tool PipeArguments includes a reference to the CLRDBG utility that was installed on the Linux VM in Step If you installed it in a different path, you need to alter this The ExePath refers to dotnet because that is the process that actually runs your application in Linux Your application is a DLL that dotnet executes WorkingDirectory points to the DLL as is resides on the VM ExeArguments is a path to the DLL, typically underneath your WorkingDirectory If you built the DLL and set a different directory as the output path, you need to supply the directory path here In our example, the project is called mvc, so the library is mvc.dll This must exist before you start debugging, so you need to run dotnet build on your VM first Each project will have a file like this Step 5: Create Launch Options File and Step 6: Start Debugging are the two steps you’ll need to for each project you want to debug Step 6: Start Debugging Open a command window in your Visual Studio IDE (Menu→View→Other Windows→Command Window) and type the following command, replacing the path to the options file (/OptionsFile) with the path to your OffRoadDebug.xml file: Debug.MIDebugLaunch ​ /Executable:dotnet ​ /OptionsFile:C:\src\mvc\OffRoadDebug.xml With this, your application will launch and you can set breakpoints and see variable values just as in Windows Note that if you view your VM session in a terminal session, you will not see the application running However, you can use the following command to verify that your command is running: ps -a You should expect an output that is similar to the one shown in Figure 11-4 Figure 11-4 The dotnet process Running this command, ps a, will show the dotnet command running with your DLL as the command parameter, as shown in Figure 11-5 Figure 11-5 dotnet running an application Finally, point your browser to the URL (10.1.2.2:5000 if using the Red Hat CDK) and you’ll see your website Happy debugging! Chapter 12 .NET Core, Linux, and Containers Microservices are the latest rage (or fad, depending on your view), and they go hand in hand with Linux containers Realizing that a VM is overkill for running one microservice, Linux containers fit the bill perfectly Small, quick to create, and highly portable, containers are here to stay Although NET is new to the Linux world, it is already a viable choice for creating container-based microservices Where the old NET required large swaths of disk space and memory, the new, more modular and lightweight version means that using a container is a valid choice For example, the difference between a RHEL image and a RHEL image with NET is only 140 MB Clearly, this is not your father’s NET Creating a container image using the Red Hat image as a base involves a few tricks This is because the image supplied by Red Hat is intended for use with their OpenShift container platform ASSOCIATED SOURCE CODE The source code used was created in Chapter Building the Image For now, let’s see how to build an image that we can use outside of OpenShift We’ll start by creating a new NET project in a new directory: mkdir mvc_docker cd mvc_docker dotnet new -t web Remember to change the Program.cs class to use the proper URL: http://0.0.0.0:5000 With the basic MVC application built, it’s time to construct the image Note that for this example you will need to have your VM registered with the Red Hat subscription manager This is because when building the image, the build command will inherit any necessary rights from the host—in this case, your VM You are prompted to register the VM when it starts (during vagrant up) If you didn’t register it then, you need to run vagrant halt and then vagrant up and select the option to register Configuring the Image The next step is to create the configuration to hold the image build instructions The following example uses the RHEL NET image to build an image containing your application Create a file named Dockerfile and add the following: FROM registry.access.redhat.com/dotnet/dotnetcore-10-rhel7 ADD /opt/app-root/src/ WORKDIR /opt/app-root/src/ EXPOSE 5000 RUN ["/bin/bash", "-c", ​ "/opt/rh/rh-dotnetcore10/root/usr/bin/dotnet restore"] RUN ["/bin/bash", "-c", ​ "/opt/rh/rh-dotnetcore10/root/usr/bin/dotnet build"] CMD ["/bin/bash", "-c", ​ "/opt/rh/rh-dotnetcore10/root/usr/bin/dotnet run"] If this is new to you, don’t fret I’ll explain it from top to bottom: FROM registry.access.redhat.com/dotnet/dotnetcore-10-rhel7 This uses the official “.NET on RHEL” image as supplied by Red Hat Because it’s the official image, it will contain a version of RHEL and the latest version of NET ADD /opt/app-root/src/ This copies the contents of the current directory to the target directory in the image This is where the application ends up WORKDIR /opt/app-root/src/ This sets the working directory in your image EXPOSE 5000 When running in a container, you need to specify which port(s) will be exposed to the outside world In this case, it’s port 5000 This does not need to match your application; you can map your application’s port to this setting Without this setting, a port will be automatically assigned RUN ["/bin/bash", "-c", "/opt/rh/rh-dotnetcore10/root/usr/bin/dotnet restore"] Using RUN causes the command that follows it to be executed when the image is being built In our case, we’re running dotnet restore in order to get all the dependencies into our image RUN ["/bin/bash", "-c", "/opt/rh/rh-dotnetcore10/root/usr/bin/dotnet build"] This will build the application while the image is being created We don’t want it to build at runtime, as that will increase the container startup time Build it now, once, and save time every time this image is used CMD ["/bin/bash", "-c", "/opt/rh/rh-dotnetcore10/root/usr/bin/dotnet run"] Using CMD causes the command that follows it to be executed when a container that uses this image is started This is not executed during the build phase With this in place, we build the image with the following command: docker build -t mvc_docker The -t option allows you to name and tag the image for later reference By default, using a single name (it must be all lowercase) will create a tag of :latest The preceding example would yield mvc_docker:latest You can create your own, for example: docker build -t mvc_docker:v1 docker build -t mvc_docker:v2 and so on Finally, notice the period at the end of the command This tells the build command to use the configuration file (Dockerfile) in the current directory A lot more is available when building For more information, use the docker build help command Running the Image in a Container Once this image is built, we can run it and view the web page Before that, you can view information about the image by running docker images, which lists all of your images Notice the size of the image, which now includes the bits for RHEL, NET, and your application Detailed information about your image—it’s interesting and worth viewing—can be obtained with the command docker inspect mvc_docker:latest Finally, to run the image, use the following command: docker run -d -p 5000:5000 mvc_docker:latest After this, open a browser and point it to the IP address 10.1.2.2:5000, where you’ll see your basic MVC website running in a container, using NET on Linux Chapter 13 Final Notes One of the challenges of writing a book is weighing time-to-create versus time-to-staleness of the content Take too long to write a book and by the time it’s finished it’s outdated With that in mind, this tome was written with one intent: to get the reader moving in the right direction as quickly as possible It’s not the be-all and end-all of NET on Linux, and there’s a lot more that can be covered But with this in hand, a willingness to learn and experiment, and some deft web search skills, the reader can be cranking out first-class NET applications just like that (snaps fingers) More and deeper coverage can be found on my ever-expanding web presence; simply visit redhatloves.net on a regular basis to stay up to date or learn more Another valuable website is obviously Microsoft’s NET Core page Finally, I’d be remiss if I didn’t give a solid “thank you” to my greatest inspiration and teacher, who —in 1991—taught me the single most important thing to remember: When you write code, it’s not a communication between a programmer and a machine; it’s a communication between a programmer and another programmer Thank you, Paul Conte About the Author A developer since the beginning of time, Don Schenck is currently a Director of Developer Experience at Red Hat, with a focus on Microsoft NET on Linux His mission is to bring NET developers into the Linux and open source communities Prior to Red Hat, Don was a frontend and mobile developer He enjoys—no, loves—cooking and hates the designated hitter rule

Ngày đăng: 04/03/2019, 16:14

Từ khóa liên quan

Mục lục

  • What to Expect from This Book

    • Some Assumptions

    • Your Environment

    • Formatting

    • .NET Core Is the Future

    • What’s Missing

    • What’s New

    • 1. Setting Up Your Environment

      • Your Red Hat Account

      • Installing the CDK

      • Disable Hyper-V

      • Start Your VM

      • Getting the Source Code

      • 2. Getting Started: From Zero to “Hello World” in One Chapter

        • From Zero to “Hello World” in One Chapter

        • Overview of .NET

        • Installing .NET

          • .NET CLR

          • .NET CoreFX

          • .NET CLI

          • ASP.NET Core

          • Tooling

          • Installation Instructions

          • Other Linux Distros

Tài liệu cùng người dùng

Tài liệu liên quan