Continuous Deployment with Natural – Legacy Coder Podcast #6

Continuous Deployment with Software AG's Adabas/Natural

After you have automated the build process for your application based on Software AG’s Adabas and Natural it’s time to take the next step and also deploy the changes to production after each push to Git! I’ll tell you how in the sixth episode of the Legacy Coder Podcast.

Recap: Automating your build process with Continuous Integration

  • Listen to Episode 2 of the Legacy Coder Podcast for an introduction on why you should automate everything from compilation to deployment.
  • What is Continuous Integration?
    • CI is a software development practice. Every developer integrates (i.e. merges) at least daily. Each integration is built and tested automatically.
    • This leads to less integration problems and faster deployment cycles.
  • What can go wrong when manually deploying to production (or the next stage)?
    • Finding all the modules that you need to deploy.
    • NAT0082 Invalid command, or Subprogram does not exist
    • NAT0936 Format/length conflict in parameter
    • NAT0933 GDA time-stamp conflict
      The infamous GDA Timestamp Conflict in Software AG's Natural
    • Separating different features in the same modules from each other.
      Manually merging features in changed Natural modules with WinMerge
    • Nested functions or other dependent modules can’t be compiled.
    • Compile errors nobody cares about (anymore).

Continuous Deployment with Blue/Green Deployments

  • Basic Definitions
    • What is Continuous Delivery?
      • CD builds on top of CI and makes sure that the software can be released at any time. The deployment process has to be fully automated. You just need to push a button to deploy your software to the target environment.
    • What is Continuous Deployment?
      • CD goes even one step further and automatically deploys the software to production if all steps of the deployment pipeline pass. Finally, no more “release days”!
    • What is a Deployment Pipeline?
      • The deployment pipeline defines all the steps (called “stages”) necessary to build and deploy a new version of the software. Usually, there are stages for compiling, testing, packaging and deploying the application.
        Deployment Pipeline for Natural
    • What is Pipeline as Code?
      • Instead of manually creating the deployment pipeline in a CI server like Jenkins you can define all the necessary steps in a domain specific language that the CI server can execute. All the information needed to build and deploy the application are now contained inside the repository.
    • What are Blue/Green Deployments?
      • To be able to deploy to production while users and batch jobs are still using the environment you need another target environment for the deployment process. If everything works as expected you can simply switch to the new environment.
        Blue/Green Deployments for Natural with different FUsers
  • Advantages of a fully automated deployment process with blue/green deployments
    • No more missing files, GDA timestamp conflicts, or format/length conflicts.
    • Fast feedback (“Fail Fast”) for the developers, problems are visible immediately.
    • You can reliably and easily roll back to a previous state if something breaks.
    • Interactive tests in the production environment are possible.
    • Running processes and interactive session won’t be disturbed.
    • Deployments don’t need to be done in the evenings or on weekends.
    • No more annoying tasks for the (expensive) software developers.

Continuous Deployment for Software AG’s Natural

  • These are the tools we use for our CI/CD process (most are Open Source).
    • Git for version control.
    • Gradle as a wrapper for SAG’s Ant script.
    • Jenkins as a CI server.
    • A custom Java program for compiling Natural on the target environment.
    • NatUnit for unit testing.
    • NaturalONE with additional plugins for NatUnit and staging.
    • Redmine for documentation and communication with subject matter experts.
    • Our former apprentice Jonas built a build lamp with a Raspberry Pi that shows the current state of our Natural build.
      Build lamp for Natural above the coffee machine
  • Implementation at AO
    • AO doesn’t have a single pipeline but 3 different ones for each individual branch: DEV, QA, and PROD. The core stages are identical, but they contain individual steps, e.g. for testing and deployment.
      • DEV: only one target FUser that’s overwritten every time, QA: Blue/Green Deployment with instant switch, PROD: Blue/Green Deployment with nightly switch so the users aren’t disturbed.
        Continuous Delivery Pipelines for Software AG's Natural at ALTE OLDENBURGER
    • Before the pipeline can do its job, the developer needs to decide which modules to stage. This is done with Redmine where each changed module is assigned to an issue.
      • An Eclipse plugin developed by ALTE OLDENBURGER searches for all modules assigned to a given issue number and stages them. After a push to Git the pipeline starts.
        Eclipse Workflow Plugin for staging Natural modules with the help of Redmine
    • The first stage of the pipeline checks out the latest version of the Natural sources from Git.
    • After that the target Fuser gets erased and recreated from scratch.
    • We use SAG’s Ant script to upload the sources to the target server.
    • We do a full build every time, not an incremental build.
      • Compile errors are formatted as JUnit results so they can be displayed inside Jenkins.
      • We don’t use SAG’s script for that because it doesn’t follow the StepLib chain (for whatever reason).
    • After the compilation additional test data for testing legacy modules that rely on a certain database state are imported into Adabas.
    • Now the unit and integration tests are executed.
    • If the tests pass, the application is deployed into the next “free” FUser.
    • After the deployment the current FUser may be set to the new one. But this depends on the environment.
    • After the release is done there are a few additional steps required, e.g. restarting the Natural RPC servers against the new FUser.
    • After each production release a tag in Git is created.
    • And finally a changelog is generated from these Git tags.

How to start with Continuous Deployment for Natural

  • First of all: use Git (or any other version control system, but I would prefer Git). Make your current production sources the new master branch and add development sources on top of that into a new branch.
  • Switch to NaturalONE. Not only do you get a modern IDE with features like Code Completion, but more importantly you get the possibility to use version control from within NaturalONE. Your repository is now the source of truth (and not the server).
  • Make your codebase compile! Don‘t allow any compilation error whatsoever!
  • Add an additional FUser for the automated deployment after each push to Git.
  • Generate the deployment script from within NaturalONE and put it into a Jenkins build. You don‘t need to create a Jenkinsfile yet. Start small!
  • Start writing automated tests, e.g. with NatUnit. By the way: It’s open source! Feel free to use and modify it. https://sourceforge.net/projects/natunit/

Recommended reading

Links

What is Legacy Code? – Legacy Coder Podcast #5

What is Legacy Code?

This podcast is called “Legacy Coder” but what exactly is legacy code? I talk about my definition of the term in the fifth episode of the Legacy Coder Podcast.

Legacy Code?

  • What is Legacy Code?
    • Definition by Michael Feathers: “Code without tests.”
    • Code of a certain age.
      • Brown field instead of green field.
    • “Old” languages or platforms.
      • Natural, COBOL, ABAP, Mainframes.
      • But also J2EE.
    • Code that’s hard to change or maintain.
      • You can write “new” legacy code.
      • You can also write legacy code in modern languages like Java or C#.
    • Big Balls of Mud, Monoliths.
      • Duplicated code.
      • Hard to separate into individual pieces of functionality for reuse.
      • Different concerns are bundled together (see title image).
    • Code that lacks certain quality characteristics.
      • Not readable, not modularized, not consistent, hard to understand, deeply nested, similar things are done differently, no patterns.
  • How can you get rid of legacy code?
    • Why would you want to get rid of the code in the first place?
      • “Don’t forget – having legacy software is often a sign of success. Your business was successful to last long enough for your software to become legacy.” [Sam Newman]
      • High maintenance costs, aging/retiring workforce, unable to implement new requirements.
    • A big rewrite is almost never the answer. But sometimes.
    • Gradually improve the quality of your codebase.
      • Introduce tests, e.g. compare log files before/after.
    • Integrate the legacy code base into your modern architecture, e.g. with webMethods and EntireX for Adabas/Natural applications.

A short piece of Legacy Code in (pseudo) Natural

Here’s how many of the old Natural modules I encounter in my day job look like:

DEFINE DATA
LOCAL USING DDMVIEW
END-DEFINE

READ IMPORTANT-DDM BY SUPERDESCRIPTOR

    IF IMPORTANT-DDM.FIELD EQ 1
        ADD 100 TO IMPORTANT-DDM.FIELD
        UPDATE
        END TRANSACTION
    ELSE
        ESCAPE TOP
    END-IF

    INPUT USING MAP 'OUTPUT'

END-READ

END

Database access, business logic, and the presentation of the results to the user (UI) are all bundled together into a single module. This becomes a maintenance nightmare quickly and is very hard to test because the individual concerns can’t be separated for testing.

This module could be split up into 5 different modules that only do one thing, can therefore be reused in different scenarios, and can easily be (unit) tested:

  • Reading the database (e.g. subroutine READ-DATA)
  • Processing the data, a.k.a. your “business logic” (e.g. subroutine PROCESS-DATA)
  • Saving data to the database (e.g. subroutine SAVE-DATA)
  • Showing the results to the user (e.g. subroutine DISPLAY-DATA)
  • Orchestrating the individual steps to implement the whole use case (the main program)

Here’s how the refactored main program would look like:

DEFINE DATA
LOCAL USING ARRDATA
END-DEFINE

PERFORM READ-DATA ARRDATA
PERFORM PROCESS-DATA ARRDATA
PERFORM SAVE-DATA ARRDATA
PERFORM DISPLAY-DATA ARRDATA

END

Recommended reading (and hearing)

In his book Working Effectively with Legacy Code* Michael Feathers shows different ways of introducing automated tests into a legacy code base. He uses C++ in his examples but the underlying ideas can be applied to any other programming language, too.

Michael Feathers - Working Effectively with Legacy Code (Robert C. Martin Series) (Affiliate)*

Robert C. Martin wrote my all time favourite book for software developers: Clean Code*. If you haven’t read it already, grab a copy now and read it from front to back! No matter what programming language you’re using, you will definitely find lots of ways to improve your existing code in here.

Robert C. Martin - Clean Code: A Handbook of Agile Software Craftsmanship (Affiliate)*

In the very first episode of this podcast I talked about how to unit test your Natural application. In my opinion, that’s a very important step in modernizing a legacy code base.

Unit Testing Natural Applications - Legacy Coder Podcast #1

Links

How to deploy to JBoss EAP 7 with Gradle, Cargo, and Jenkins

It took me quite a while to get my Java EE 7 application automatically deployed to a target JBoss EAP 7 server from within Jenkins using Gradle as the build tool and Cargo for managing the deployment. So here’s my final solution for you to use! 😉

build.gradle

dependencies {
    classpath 'com.bmuschko:gradle-cargo-plugin:2.2.3'
}

apply plugin: 'com.bmuschko.cargo'

dependencies {
    cargo "org.codehaus.cargo:cargo-core-uberjar:1.5.0",
          "org.codehaus.cargo:cargo-ant:1.5.0",
          "org.wildfly:wildfly-controller-client:8.2.1.Final"
}

cargo {
    containerId = 'wildfly10x'

    deployable {
        context = 'MyContext'
    }

    remote {
        hostname = '10.1.1.1'
        username = 'remote'
        password = 'remote'

        containerProperties {
            property 'cargo.jboss.management-http.port', 9990
        }
    }
}

Jenkinsfile

stage("Deployment") {
    bat('gradlew cargoRedeployRemote --stacktrace')
}

Deploying to JBoss EAP 7 is the same as deploying to Wildfly 10

First of all, there’s no Cargo containerId for JBoss EAP 7. However, you can use Wildfly 10 instead, as you can read here: Codehaus Cargo – WildFly 10.x:

The WildFly 10.x container can be used with the JBoss Enterprise Application Platform (EAP) version 7; i.e. the version released in May 2016

Finding the right versions of Cargo and its Gradle plugin

You need to use the right versions of Cargo and the Cargo Gradle plugin. I’ve found that version 2.2.3 of the Gradle plugin and version 1.5.0 of Cargo itself work fine with Wildfly 10/JBoss EAP 7 (see Execution failed for task ‘:cargoRunLocal’. #152). The latest versions as of this writing of Cargo (1.6.6) and the plugin (2.3) also work in my environment.

If the versions don’t work correctly, you might get an error like this:

> gradle cargoRedeployRemote

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':cargoRedeployRemote'.
> org.codehaus.cargo.container.ContainerException: Cannot create configuration. 
There's no registered configuration for the parameters (container [id = [wildfly10x],
type = [remote]], configuration type [runtime]). Actually there are no valid types
registered for this configuration. Maybe you've made a mistake spelling it?

Deploying to JBoss EAP 7 with the Wildfly Controller Client

Cargo needs a controller client to be able to deploy artifacts to a remote Wildfly 10/JBoss EAP 7 as you can read here: Codehaus Cargo – JBoss Remote Deployer. I’ve found that version 8.2.1.Final of the Wildfly Controller Client org.wildfly:wildfly-controller-client works fine. However, the latest version of org.wildfly.core:wildfly-controller-client (3.0.10.Final) also works.

You need to add it to cargo.dependencies in your build script as shown above. Otherwise you might end up with an error message like this:

> gradle cargoRedeployRemote

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':cargoRedeployRemote'.
> org.codehaus.cargo.container.ContainerException: Failed to create deployer
with implementation class org.codehaus.cargo.container.wildfly.WildFly10xRemoteDeployer
for the parameters (container [id = [wildfly10x]], deployer type [remote]).

Changing the JBoss management port

In my case, the target JBoss server uses a different port for remote management. The default is 9990, but I use 19990. Simply adding cargo.port = 19990 to the build file didn’t cut it:

> org.codehaus.cargo.util.CargoException: HTTP request failed, response code: -1,
response message: java.net.ConnectException: Connection refused: connect, response body: null

And by adding --info to the call to gradle I got:

Starting action 'redeploy' for remote container 'wildfly10x' on 'http://localhost:9990'

It took me a while to find the correct way of telling Cargo to use the custom port. The Cargo documentation (see Codehaus Cargo – JBoss Remote Deployer) states:

WildFly 8.x, 9.x and 10.x use the cargo.jboss.management-http.port port

However, setting this property isn’t as easy as adding cargo.jboss.management-http.port = 19990 to your build file, because this results in:

(cargo.jboss.management - http.port) is a binary expression, but it should be a variable expression

And adding the following lines…

cargo {
    jboss {
        management-http {
            port = 19990
        }
    }
}

…leads to a different error:

> Could not find method jboss() for arguments [cargo_61gwz9gjyqje40dvlr47klkas$_run_closure3$_closure6@22ff8f9]
on object of type com.bmuschko.gradle.cargo.convention.CargoPluginExtension.

Finally, I’ve found the right way of setting the property in this article: Local redeployment #123

containerProperties {
    property 'cargo.jboss.management-http.port', 19990
}

However, if you use the newest versions of Cargo and the plugin cargo.port = 19990 seems to work again.

Example build.gradle using the latest versions of Cargo and the plugin

dependencies {
    classpath 'com.bmuschko:gradle-cargo-plugin:2.3'
}

apply plugin: 'com.bmuschko.cargo'

dependencies {
    cargo "org.codehaus.cargo:cargo-core-uberjar:1.5.0",
          "org.codehaus.cargo:cargo-ant:1.5.0",
          "org.wildfly.core:wildfly-controller-client:3.0.10.Final"
}

cargo {
    containerId = 'wildfly10x'
    port = 9990

    deployable {
        context = 'MyContext'
    }

    remote {
        hostname = '10.1.1.1'
        username = 'remote'
        password = 'remote'
    }
}

Presidents Meeting and German Natural User Group – Legacy Coder Podcast #4

Presidents Meeting and German Natural User Group

Let’s talk about what was presented and discussed at Software AG’s User Group Presidents Meeting and the German Natural User Group in Darmstadt in November 2017 in episode four of the Legacy Coder Podcast.

User Group Presidents Meeting

  • What’s the point of the meeting?
    Welcome to the International User Groups Presidents Meeting

    • Planning the International User Groups Conference (topics, date, venue etc.).
  • What was presented by Software AG?
    • Software AG’s revenue is now > 1 Billion. 4,400 employees all over the world. Ca. 25% Adabas/Natural.
    • 70% of the largest 1,000 companies worldwide use Software AG products.
    • ADAMOS: Joint Venture with big machine builders like Zeiss and Dürr.
    • Don’t rip and replace! Modernize!
    • 3 big moves: Adabas/Natural, integration with webMethods, IoT (1 bn. investment).
    • Modern architecture: System of Records, Integration, IoT/AI.
    • Software AG named by Gartner as leader in Streaming Analytics, InMemory Databases.
  • What was discussed with regards to Adabas/Natural?
    • Don’t separate Adabas and Natural. There will be only one conference for both technologies with a single keynote.
    • Max. 30min presentations, time restrictions for information about business, platform, environment.
    • Natuaral customer base: Mainframe vs. LUW: 50%/50%
    • A workshop for Natural developers would be interesting (best practices, architecture, training).
    • A Hackathon will not be possible at IUGC.
    • How to find/meet other customers with similar problems?
  • Topics for IUGC 2018 in Berlin
    • Already 5-6 presentations submitted.
    • NaturalONE (new features, introducing the IDE etc.)
    • DevOps (CI, Docker, etc.)
    • Rehosting (Mainframe -> LUW)
    • Who uses or plans to use Cloud Computing?
    • 2050 readiness award
  • International User Group Conference 2018 in Berlin
    Members of Software AG's International User Groups

    • Registration is open!

German Natural User Group

  • Ca. 60 attendees from all over Germany.
    About 60 Natural Developers get together for the German Natural User Group in November 2017 in Darmstadt
  • Quite a few “young” Natural developers were present. The “Generational Change” starts…
    Young Natural Developers at the German Natural User Group in Darmstadt in November 2017
  • I’m the new speaker of the German Natural User Group.
    Stefan Macke is the new speaker of the German Natural User Group
  • Topics of the talks
    • zIIP enablement for Adabas/Natural
    • New features of EntireX
    • How to develop your own Eclipse plugins for NaturalONE
      How to develop your own Eclipse plugin for NaturalONE

    • New features in Natural und NaturalONE
      Code Coverage in NaturalONE

      • Natural editor will be shut down with release in fall of 2018. There are still many customers that have concerns.
    • Adabas and Natural in a Docker container, started via Alexa
      Adabas now runs in a Docker container
    • Visualizing Adabas Events with ElasticSearch and Kibana
      Adabas pushes events to ElasticSearch that can be visualized with Kibana
    • RealHtml4Natural – an alternative webframework for Natural build on top of the Natural Native Interfaces and distributed under the GPL-3.0 license.

Call to Action

Start Tweeting with #AdabasNatural2050 and #IUGC18!

Links

Modern Natural Development with NaturalONE – Legacy Coder Podcast #3

Modern Natural Development with NaturalONE

Why would anyone dismiss the good old Natural editor and switch over to NaturalONE? Let’s find out what features NaturalONE has to offer in the third episode of the Legacy Coder Podcast.

Why should you switch over to NaturalONE?

  • Increased developer productivity
    • Use Copy and Paste (duh!) for high quality Natural programming 😉
    • Syntax Highlighting will help you understand the source code faster.
    • Make use of intelligent search and replace features with regular expressions.
    • Code Completion makes you type way less than before.
      Code Completion in NaturalONE
    • Code Navigation (jump to a variable definition etc.) lets you explore the code base with a few keystrokes.
    • You can use Code Folding for focussing on the really important stuff.
    • Multiple compile errors are displayed instantly without uploading the source to the server.
      Multiple compile errors in NaturalONE
  • Repository based development
    • Finally develop software like the cool kids do!
    • Every code change is documented and can be rolled back with just a few commands. It can even be attached to an issue tracker like Jira or Redmine.
      Git integration in NaturalONE
    • You can try out new things in an isolated environment.
    • You can automate your coding with code generators like Xtext.
  • Modernize your development environment
    • Share knowledge and open up towards other (maybe younger) developers (Java etc.).
    • Be and stay attractive as a company to new employees.
    • Automate your build process
    • NaturalONE is Software AG’s platform of choice for the future.
    • The old Natural editor will be shut down!
  • Extendable with additional plugins
    • Software AG’s innovations will only take place in NaturalONE (e.g. Code Coverage, Screen Testing).
    • Attach your IDE to an issue tracker like Jira or Redmine with Mylyn.
    • Use Snipmatch for even less typing. Plugin Snipmatch used in NaturalONE
    • Create your own extensions (e.g. NatUnit) for whatever requirement you have.
      Our own NatUnit plugin used in NaturalONE

Recommended reading

  • NaturalOne Debugging

Links

Automating Your Natural Build Process – Legacy Coder Podcast #2

Automating Your Natural Build Process

How can you automate the build process for your application based on Software AG’s Adabas and Natural? I talk about our journey towards a completely automated build from scratch after each push to Git in the second episode of the Legacy Coder Podcast.

How to automate the build process for an Adabas/Natural application

  • Why would I want to automate the build process?
    • What hurts should be done more often!
    • No more long integration phases before each release!
    • You’ll get a faster time to market for new features.
    • You can get rid of knowledge silos concerning the release of your application.
  • What steps may need to be automated?
    • Upload (transfering the Natural source code to the server)
    • Compile (CATALOG, STOW, CATALL etc.)
    • Unit Tests (e.g. with NatUnit, see Unit Testing Natural Applications)
    • Deployment (the actual release of the new version on the target stage)
    • Restarting RPC servers or whatever individual steps might be necessary in your environment
  • What tools are available for automating the Natural build process?
    • It all starts with Git or any other versioning control system (Subversion, TFS, CVS).
    • You can use Jenkins for Continuous Integration.
    • Software AG’s command line tools (ftouch etc.) can be scripted.
    • Even the CATALL can be scripted by calling into Natural BATCHMODE.
    • NaturalONE’s ant scripts for uploading and compiling Natural sources.
    • Any additional tool that you might need (Bash scripts etc.)
  • How can I get started?
    • Make your project fully compilable. There can be no compile errors whatsoever.
    • Start with a single step, e.g. automate only the compile step first.
    • Script everything (e.g. with Bash) right from the beginning. You can easily call these scripts from Jenkins later on.
    • Hook Jenkins up to your source code repository. It provides plugins for every major system (e.g. Git, Subversion).
    • Try to automate the build with Jenkins. It’s completely free and easy to setup. Perhaps ask a Java colleague if he can help you.
  • How can you go even further than what’s possible today?
    • Try to automate imports of Adabas data that’s important for your application.
    • Try to automate Adabas schema migrations.
    • Implement feature toggles for more fine grained control over your application’s functionality at runtime.

Recommended reading

Links

Unit Testing Natural Applications – Legacy Coder Podcast #1

Unit Tests for Natural Applications with NatUnit

Unit testing with Software AG’s Natural – is that even possible? Let’s find out in the very first episode of the Legacy Coder Podcast.

Unit testing Natural applications

  • Why would I want to unit test my Natural code?
    • You get instant feedback whether your code works. That’s fun! 😀
    • You get a safety net for refactoring and optimizing your Natural code.
    • You can catch regression as early as possible. That makes evolving your code base easy and painless.
    • Unit tests can be integrated into your build process (Continuous Integration, Continuous Delivery, Continuous Deployment).
    • Unit tests are the first step on your way to a fully automated build process.
  • What tools are available for unit tests with Natural?
    • Subprogram testing within NaturalONE
      • Only subprograms can be tested.
      • Different “language” for defining your tests.
      • Tests have to be defined manually from a GUI.
      • Tests cannot be executed from within Natural itself.
      • Proprietary software maintained by Software AG.
      • Professional support by Software AG is available.
    • NatUnit – an open source framework for unit testing with Natural
      • Everything that can be called from a subprogram can be tested (subprogram, subroutine, function).
      • Tests are written in the same language that is used for production code.
      • Tests can be written as Natural code with full IDE support.
      • Tests can be executed within any Natural runtime.
      • Open source project that can be extended by everybody – including yourself.
      • There’s no professional support for the framework.
  • What do I have to do differently when writing testable Natural modules?
    • You need more fine grained modularization!
    • You have to decouple the User Interface, Database access, and the core Business Logic from each other.
    • You need to extract the functionality to test into its own callable module.

NatUnit in action

Here are a few screenshot of our NatUnit Eclipse plugin in action.

You can run a NatUnit test from within the IDE.

NatUnit Eclipse Plugin: RunAs NatUnit Test

If the tests are successful, you instantly see the famous “green bar”.

NatUnit Eclipse Plugin: Successful Test

And if the tests are broken, you’ll definitely notice that, too. 😉

NatUnit Eclipse Plugin: Failing Test

Recommended reading

Links

Introduction to the show and the host – Legacy Coder Podcast #0

Legacy Coder Podcast Episode 0: Introduction to the show and the host

Who is this guy and what the heck does he know about Software AG’s Adabas and Natural? I’ll show you in the pre-episode zero of the Legacy Coder Podcast.

Introduction to the podcast and myself

  • My experience with Adabas and Natural.
    • I’m programming with Natural since 2003.
    • I’m the president of the International Natural User Group since 2016.
    • I co-authored NatUnit (as part of my Master’s thesis) and L4N.
    • My main job is integrating Adabas/Natural into a modern SOA with webMethods Integration Server.
    • In the last few months I automated and modernized the Natural build process with Git, Jenkins, Java, and NaturalONE.
    • My biggest Natural project so far was the migration of an insurance system from Oracle/Java to Adabas/Natural.
    • I frequently speak at local and international user groups and conferences (e.g. Innovation World, Innovation Tour, IUG).
    • Our Natural code base: ~6 million LOC, ~19.000 modules.
  • My professional experience.
    • I studied business computer science (Bachelor’s degree) and software engineering (Master’s degree).
    • I train new hires and apprentices at ALTE OLDENBURGER Krankenversicherung AG in Germany.
    • I also use a few additional languages: Java, C#, PHP, Ruby.
    • I’m a software architect since 2014.
    • I work as an associate professor for programming and software engineering at PHWT since 2009.
  • My personal life.
    • I’m married.
    • I have two dogs.
    • I like taking photos.
    • I run a podcast for aspiring software developers in German.
    • I organize my own user group and conference for software developers.
    • You can find me almost everywhere: LinkedIn, Twitter, Instagram etc.

Links

Exception-like error handling in Software AG’s Natural

Error handling in Software AG’s Natural can be done in a way that resembles Exception handling in object-oriented languages like Java.

throw

Instead of throwing an Exception, you raise an error simply by assigning a value to the system variable *ERROR-NR. As soon as a statement like the following is executed, the current program flow is interrupted and the nearest ON ERROR block is executed.

*ERROR-NR := 1234

In fact, we use exactly this feature for raising assertion errors in NatUnit.

catch

You can handle a Natural error in an ON ERROR block anywhere inside your code. Just like an Exception travels up through the call stack to get caught in the nearest try-catch block, a Natural error is handled in the nearest ON ERROR block.

Here’s an example of an ON ERROR block that exits the current module and marks the error as handled:

ON ERROR
    /* do something about it */
    ESCAPE MODULE
END-ERROR

catch (SpecificException e)

You can only define a single ON ERROR block in each Natural module. So if you need to handle specific errors in a different way, you need to have some kind of distinction logic like this:

ON ERROR
    IF *ERROR-NR EQ 1234
        /* do something about it */
        ESCAPE MODULE
    END-IF
END-ERROR

Or if you need to distinguish between multiple errors:

ON ERROR
    DECIDE ON FIRST VALUE OF *ERROR-NR
        VALUE 1234
            /* do something about it */
            ESCAPE MODULE
        VALUE 1235
            /* do something about it */
            ESCAPE MODULE
        NONE IGNORE
    END-DECIDE
END-ERROR

re-throw

If you can’t handle the error in an ON ERROR block, but you want to log it or do something else with it before letting the next ON ERROR block handle it, you don’t need to do anything at all, because that’s the default behaviour.

However, if you exit the ON ERROR block with any statement from the following list, the error is marked as handled and the normal control flow (in the calling module of the module containing the ON ERROR block) is continued. So be sure not to exit the block with any of these statements.

Exiting from an ON ERROR Block:
An ON ERROR block may be exited by using a FETCH, STOP, TERMINATE, RETRY, ESCAPE ROUTINE or ESCAPE MODULE statement. If the block is not exited using one of these statements, standard error message processing is performed and program execution is terminated.

Here’s an example of such a “re-throw”:

ON ERROR
    IF *ERROR-NR EQ 1234
        /* log the error */
        /* DON'T exit with `FETCH`, `STOP`, `TERMINATE`, `RETRY`, `ESCAPE ROUTINE` or `ESCAPE MODULE` */
    END-IF
END-ERROR

Checking which error occurred

Even if you “handle” the Natural error in an ON ERROR block, e.g. by using ESCAPE MODULE, the system variable *ERROR-NR isn’t reset to 0. You need to do that yourself, if you need to. If you don’t, the variable can be used in the calling module to check whether an error (that was handled) occured. By the way, the system variable *ERROR-LINE contains the line number of the statement that raised the error.

CALLER

CALLNAT 'CALLEE'
IF *ERROR-NR NE 0
    WRITE 'Error' *ERROR-NR 'occurred in line' *ERROR-LINE 'while calling CALLEE'
    /* prints: "Error     1234 occurred while calling CALLEE" */
END-IF
END

CALLEE

*ERROR-NR := 1234
ON ERROR
    ESCAPE MODULE
END-ERROR
END

If you don’t want any caller to know that an error occurred, simply reset *ERROR-NR:

ON ERROR
    RESET *ERROR-NR
    ESCAPE MODULE
END-ERROR

Global error handler (like a try-catch in main())

You can define a global error handler by setting the system variable *ERROR-TA to the name of a Natural module. In case of an error, Natural automatically calls this module (which has to be a program) and puts information about the error on the stack. The system variables *ERROR-NR and *ERROR-LINE will be reset at this point, so the error handler has to read the information from the stack with INPUT.

CALLER

*ERROR-TA := 'HANDLER'
CALLNAT 'CALLEE'
END

CALLEE

*ERROR-NR := 1234
END

HANDLER

DEFINE DATA LOCAL
1 #ERROR-NR           (N5)
1 #LINE               (N4)
1 #STATUS-CODE        (A1)
1 #PROGRAM            (A8)
1 #LEVEL              (N2)
1 #LEVELI4            (I4)
1 #POSITION-IN-LINE   (N3)
1 #LENGTH-OF-ITEM     (N3)
END-DEFINE

/* read error information from stack */
INPUT #ERROR-NR #LINE #STATUS-CODE #PROGRAM #LEVEL #LEVELI4

WRITE #ERROR-NR #LINE #STATUS-CODE #PROGRAM #LEVEL #LEVELI4 #STATUS-CODE
WRITE *ERROR-NR *ERROR-LINE

END

Output:

1234    10 O CALLEE     2           0 O
     0     0

For more information about the error information on the stack take a look at the section Using an Error Transaction Program in the Natural documentation.

Getting more information about errors programmatically

If you need to find out more about the current error, e.g. in your ON ERROR block, there are quite a few User Exits that deal with errors:

  • USR0040N: Get type of last error
  • USR1016N: Get error level for error in nested copycodes
  • USR2001N: Get information on last error
  • USR2006N: Get information from error message collector
  • USR2007N: Get or set data for RPC default server
  • USR2010N: Get error information on last database call
  • USR2026N: Get TECH information
  • USR2030N: Get dynamic error message parts from the last error
  • USR3320N: Find user short error message (including steplibs search)
  • USR4214N: Get program level information