Upgrade to Pro — share decks privately, control downloads, hide ads and more …

CodeFest 2018. Raffaele Rialdi (Vevy Europe) — A conversation and demos about NetCore 2 running on Linux

CodeFest 2018. Raffaele Rialdi (Vevy Europe) — A conversation and demos about NetCore 2 running on Linux

Посмотрите выступление Raffaele: https://2018.codefest.ru/lecture/1334/

Do you have doubts, questions on Netcore? Do you want to see the demos running on Linux (and Windows, why not) and on the Raspberry PI? This slot is dedicated to all of you that want to understand the use-cases, the practical problems and want to touch the code and evaluate what is going on. I reccomend to participate to my other session "Writing IoT applications with NetCore 2.1 on the Raspberry PI" before, even if it is not mandatory :)

CodeFest

April 05, 2018
Tweet

More Decks by CodeFest

Other Decks in Programming

Transcript

  1. A conversation and demos about NetCore 2 running on Linux

    Raffaele Rialdi Senior Software Architect Vevy Europe @raffaeler [email protected]
  2. • Do you have doubts, questions on Netcore? Do you

    want to see the demos running on Linux (and Windows, why not) and on the Raspberry PI? This slot is dedicated to all of you that want to understand the use-cases, the practical problems and want to touch the code and evaluate what is going on. I reccomend to participate to my other session "Writing IoT applications with NetCore 2.1 on the Raspberry PI" before, even if it is not mandatory :)
  3. Who am I? • Raffaele Rialdi, Senior Software Architect in

    Vevy Europe – Italy @raffaeler also known as "Raf" • Consultant in many industries Manufacturing, racing, healthcare, financial, … • Speaker and Trainer around the globe (development and security) Italy, Romania, Bulgaria, Russia (CodeFest 2017, DotNext), USA, … • And proud member of the great Microsoft MVP family since 2003
  4. Developer choices • Developing on the same Linux distribution •

    VS Code IDE is very good and runs on Linux too • Does not run on ARM based devices • Far from being a full VS2017 experience • Developing on Windows and deploying on Linux • Targeting a VM ensure the full-fidelity on Linux • Targeting the Windows-Linux subsystem works in most cases too • VS2017 is still the best choice as IDE / Debugger • Developing on Windows and deploying in a Docker container • Best isolation ever because the container is re-created • VS2017 has a great Docker integration
  5. Linux: which distribution? • NetCore 2.0 already supports: • Red

    Hat, Ubuntu, Debian (compreso Raspbian - Raspberry PI), Fedora, CentOS / Oracle, OpenSuse (SLES), Linux Mint • NetCore 2.1 (currently in preview) add the support for: • Alpine Linux, Bionic and others • Pick the one you are more comfortable with • Install the pre-requisites • https://docs.microsoft.com/en-us/dotnet/core/linux-prerequisites?tabs=netcore2x
  6. Provisioning a Linux machine • Enable SSH on Linux (or

    Windows-Linux subsystem) • openssh-server on Ubuntu • Use the raspi-config utility on Raspberry PI • SSH + SCP Client: Putty, WinSCP, Bitvise • Install the SDK or the runtime (not needed) • https://www.microsoft.com/net/download/linux • Optional: • net-tools (network utility for Linux) • lldb (debugger) • build-essential (C/C++ build packages and related tools)
  7. NetCore 2.x • Executables • Console and ASP.NET Core (which

    is also a console!) • Libraries: netstandard or NetCore • Best choice: netstandard 2.0 • Library for wide consumption: prefer a lower version • Use NetCore on libraries only if you can't use netstandard (quite rare) • Native projects • Visual C++ also supports Linux (and Android) • Better exporting "C-style" calls and not "C++" classes/methods • Nuget allows picking the right native dll depending on the current Platform
  8. Configure TLS in Kestrel via configuration files • AspNetCore 2.0

    can't configure TLS via configuration files • Raf remedy: • https://github.com/aspnet/KestrelHttpServer/issues/1851#issuecomment-319718914 • It is also necessary: • RequireHttpsAttribute • Redirect to Https • Buy or create a certificate • makecert • DeployManager (by Raf) • openssl • Note: certificate must have a "SAN" field public void ConfigureServices(... { svc.Configure<MvcOptions>(options => { options.Filters.Add( new RequireHttpsAttribute()); } } public void Configure(... { var options = new RewriteOptions() .AddRedirectToHttps(); app.UseRewriter(options); }
  9. ASP.NET Core Cross-Platform • Base templates work everywhere • The

    "Identity" feature requires EFCore. • EF Providers: SQL Server on Windows or Linux, Postgre, Sqlite (low stress) • SQLite nuget packages: • Microsoft.EntityFrameworkCore.Sqlite • Microsoft.EntityFrameworkCore.Sqlite.Design • SQLitePCLRaw.lib.e_sqlite3.linux • Websockets • Requires nuget package: Microsoft.AspNetCore.WebSockets
  10. When and how using Sqlite • Very low-traffic • Testing

    in containers • Administration or low-traffic logs services.AddDbContext<MyContext>(options => options.UseSqlite(Configuration.GetConnectionString("Sqlite"))); //options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb; Database=aspnet-PiTerminal-478; Trusted_Connection=True; MultipleActiveResultSets=true", "Sqlite": "Data Source=db.sqlite" Add-Migration InitialCreate -Context MyContext Update-Database -Context MyContext
  11. Docker • Installing on Linux • curl –sSL https://get.docker.com |

    sh • Installing on Windows • Docker Client MSI Setup • VS 2017 and VS Code have a great integration • otherwise • Using the CLI • docker build –t myApp . • docker run –p 5000:5000 myApp
  12. Debugging su Linux • Using debugger • Version 2.0 uses

    version 3.6 (LLDB-3.6) • Version 2.1 uses version 3.9 (LLDB-3.9) • "Attach a process" scenario • ps -ejH  to get the PID • Launch lldb • Attach the process • Break it • Load the SOS plugin sudo apt-get install lldb-3.6 100488 100488 100488 pts/4 00:00:00 bash 104847 104847 100488 pts/4 00:00:06 dotnet 104929 104847 100488 pts/4 00:00:00 dotnet sudo lldb-3.6 (lldb) process attach -p 104929 (lldb) plugin load /usr/share/dotnet/shared/Microsoft.NETCore.App/2.0.0/libsosplugin.so (lldb) setclrpath /usr/share/dotnet/shared/Microsoft.NETCore.App/2.0.0 (lldb) sos
  13. SOS (Son of Strike) on Linux sos  lists the

    commands pe  shows the exception (if any) clrstack  shows the current stack dso  shows the objects on the stack dumpheap  shows the heap (!!) dumpheap -t (MT hex number) dumpobj (address) gcroot  shows object roots Object Inspection Examining code and stacks ------------------------- -------------------------- DumpObj (dumpobj) Threads (clrthreads) DumpArray ThreadState DumpStackObjects (dso) IP2MD (ip2md) DumpHeap (dumpheap) u (clru) DumpVC DumpStack (dumpstack) GCRoot (gcroot) EEStack (eestack) PrintException (pe) ClrStack (clrstack) GCInfo EHInfo bpmd (bpmd) Examining CLR data structures Diagnostic Utilities ----------------------------- ------------------------ DumpDomain VerifyHeap EEHeap (eeheap) FindAppDomain Name2EE (name2ee) DumpLog (dumplog) DumpMT (dumpmt) DumpClass (dumpclass) DumpMD (dumpmd) Token2EE DumpModule (dumpmodule) DumpAssembly DumpRuntimeTypes DumpIL (dumpil) DumpSig DumpSigElem Examining the GC history Other ----------------------------- ------------------------ HistInit (histinit) FAQ HistRoot (histroot) CreateDump (createdump) HistObj (histobj) Help (soshelp) HistObjFind (histobjfind) HistClear (histclear)
  14. Deployment: dotnet publish • On Windows use 'dotnet publish' to

    create a folder with all the files • If the runtime already has the shared runtime: • dotnet publish -c Release -r linux-arm --self-contained=false -o c:\temp • Copy the folder on Linux • Run with: dotnet myapp.dll • Otherwise the "Self Contained Deployment" including the CLR • dotnet publish -c Release -r linux-arm --self-contained -o c:\temp • Copy the folder on Linux • Require the executable attribute: chmod +x myapp • Run with: ./myapp
  15. Continuous Deployment (CD) DeployTool (Raf) https://github.com/raffaeler/DeployTool 1. Create a configuration

    file 2. Start the tool "dotnet-deploy interact" 3. Use the menu to run the desired config Fully documented on the GitHub repo { "Description": "Raspberry", "Ssh": { "Host": "pi-atd01", "Username": "pi", "EncryptedPassword": "…" }, "Actions": [ { "ActionName": "DotnetPublishAction", "OutputFolder": "release-linux-arm", "RuntimeIdentifier": "linux-arm", "Configuration": "Release", "IsSelfContained": true }, { "ActionName": "SshCopyToRemoteAction", "LocalItems": [ "$(publishdir)", "db.sqlite", "pi1-cert.pfx" ], "RemoteFolder": "/home/pi/$(projectname)", "Recurse": true } ] } Deploy Configuration
  16. ASP.NET Core HTTP server • ASP.NET Core uses the "Kestrel"

    web server • It can be exposed directly, very lightweight and fast • Supported protocols: HTTP, HTTPS, Websocket • Publishing by hostname or URL requires a reverse proxy • Reverse Proxies options: • Linux: Nginx • Windows: IIS with the "Aspnet Core" module • IIS is just used as a reverse proxy on Windows
  17. Installing and configuring nginx // UseForwardedHeaders must come before UseAuthentication

    app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); sudo apt-get install nginx sudo nano /etc/nginx/sites-available/default sudo service nginx start server { listen 80; location / { proxy_pass http://localhost:5000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection keep-alive; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } ASP.NET Core Bash Configuring Nginx
  18. Run a process as a service using systemd • Create

    a systemd configuration • Create a service user • Enable and start the service: • systemctl enable myApp.service • systemctl start myApp.service • systemctl status myApp.service • Watch the logs • sudo journalctl -fu myApp.service • --since "2017-10-18" • --until "2017-12-18 04:00" [Unit] Description=My ASP.NET Core App [Service] WorkingDirectory=/var/aspnetcore/myApp ExecStart=/usr/bin/dotnet /var/aspnetcore/myApp/myApp.dll Restart=always RestartSec=10 # Restart (sec) if crashes SyslogIdentifier=dotnet-myApp User=www-data Environment=ASPNETCORE_ENVIRONMENT=Production Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=fals e [Install] WantedBy=multi-user.target /etc/systemd/system/myApp.service
  19. Raspberry PI • Full tutorials: https://github.com/raffaeler/raspberrypi • Package requirements: •

    sudo apt-get install libunwind8 libunwind8-dev gettext libicu-dev liblttng-ust- dev libcurl4-openssl-dev libssl-dev uuid-dev unzip • SDK available since 2.1, Runtime is optional • Netcore libraries (GPIO and peripherals) • Unosquare.Raspberry.IO by Unosquare Labs • Pi.IO by Peter Marcu • Peripheral access requires root permissions