Wednesday, May 27, 2020

Oracle Transparent Application Failover (TAF)

TAF is based on OCI (Oracle Call Interface). So every client using OCI can/may profit from TAF.
JDBC Thick requires an Oracle Client to be installed, hence you have OCI and therefore TAF.
JDBC Thin does not require an Oracle Client to be installed (just the appropriate JAR files) and is not based on OCI, hence NO TAF.

You need to install the Oracle instant client first.

Below is a client-side TAF setup


tnsnames.ora
RACPROD =
  (DESCRIPTION=
    (FAILOVER = ON)
    (ADDRESS=
      (PROTOCOL=TCP)
      (HOST=rac-scan.leavemealone.local)
      (PORT=1521)
    )
    (CONNECT_DATA=
      (SERVER=dedicated)
      (SERVICE_NAME=prod.leavemealone.local)
      (FAILOVER_MODE = (TYPE = SELECT)(METHOD = BASIC)(RETRIES = 10)(DELAY = 5))
    )
  )

SQL*Plus with TAF
sqlplus accdb@racprod

SQLcl with TAF
sqlcl accdb@jdbc:oracle:oci:@(DESCRIPTION=(FAILOVER=on)(ADDRESS=(PROTOCOL=TCP) (HOST=rac-scan.leavemealone.local)(PORT=1521))(CONNECT_DATA= (SERVICE_NAME=prod.leavemealone.local)(FAILOVER_MODE = (TYPE = SELECT)(METHOD = BASIC)(RETRIES = 10)(DELAY = 5))))

SQL Developer with TAF
Change connection type to Advanced and then put this in Custom JDBC URL
jdbc:oracle:oci:@(DESCRIPTION=(FAILOVER=on)(ADDRESS=(PROTOCOL=TCP) (HOST=rac-scan.leavemealone.local)(PORT=1521))(CONNECT_DATA= (SERVICE_NAME=prod.leavemealone.local)(FAILOVER_MODE = (TYPE = SELECT)(METHOD = BASIC)(RETRIES = 10)(DELAY = 5))))

Below is a server-side TAF setup


Add and review TAF service
srvctl add service -d orcl -s prodtaf.leavemealone.local -m BASIC -e SELECT -z 180 -w 5 -j LONG -r "ORCL1,ORCL2"
-pdb prod
srvctl start service -d orcl -s prodtaf.leavemealone.local
srvctl config service -d orcl -s prodtaf.leavemealone.local
Service name: prodtaf.leavemealone.local
Server pool:
Cardinality: 2
Service role: PRIMARY
Management policy: AUTOMATIC
DTP transaction: false
AQ HA notifications: false
Global: false
Commit Outcome: false
Failover type: SELECT
Failover method: BASIC
TAF failover retries: 180
TAF failover delay: 5
Failover restore: NONE
Connection Load Balancing Goal: LONG
Runtime Load Balancing Goal: NONE
TAF policy specification: NONE
Edition:
Pluggable database name: prod
Maximum lag time: ANY
SQL Translation Profile:
Retention: 86400 seconds
Replay Initiation Time: 300 seconds
Drain timeout:
Stop option:
Session State Consistency: DYNAMIC
GSM Flags: 0
Service is enabled
Preferred instances: orcl1,orcl2
Available instances:
CSS critical: no

tnsnames.ora
RACPROD =
  (DESCRIPTION=
    (ADDRESS=
      (PROTOCOL=TCP)
      (HOST=rac-scan.leavemealone.local)
      (PORT=1521)
    )
    (CONNECT_DATA=
      (SERVER=dedicated)
      (SERVICE_NAME=prodtaf.leavemealone.local)
    )
  )

SQL*Plus with TAF
sqlplus accdb@racprod

SQLcl with TAF
sqlcl accdb@jdbc:oracle:oci:@(DESCRIPTION= (ADDRESS=(PROTOCOL=TCP) (HOST=rac-scan.leavemealone.local)(PORT=1521))(CONNECT_DATA= (SERVICE_NAME=prodtaf.leavemealone.local)))

SQL Developer with TAF
Change connection type to Advanced and then put this in Custom JDBC URL
jdbc:oracle:oci:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP) (HOST=rac-scan.leavemealone.local)(PORT=1521))(CONNECT_DATA= (SERVICE_NAME=prodtaf.leavemealone.local)))

To verify the connection is actually using TAF
SELECT inst_id,
         machine,
         program,
         username,
         logon_time,
         failover_type,
         failover_method,
         failed_over
    FROM gv$session
ORDER BY logon_time DESC;

APEX Office Print plug-in upgrade script

Run the script connected to SQLcl as the owner (parsing schema) of the application.
We need to repeat this script for each application.

DECLARE
    l_workspace_id   NUMBER;
BEGIN
    SELECT workspace_id
      INTO l_workspace_id
      FROM apex_workspaces
     WHERE workspace = 'OPTRUST';

    --
    apex_application_install.set_workspace_id (l_workspace_id);
    apex_application_install.set_application_id (&1);
    apex_application_install.generate_offset;
    apex_application_install.set_schema ('OPTRUST');
END;
/

@dynamic_action_plugin_be_apexrnd_aop_convert_da.sql
@dynamic_action_plugin_be_apexrnd_aop_da.sql
@process_type_plugin_be_apexrnd_aop.sql
COMMIT;

Thursday, May 21, 2020

Fine-Grained Access to External Network Services

Oracle Database 11g Release 1 (11.1) includes fine-grained access control to the UTL_TCP, UTL_SMTP, UTL_MAIL, UTL_HTTP, or UTL_INADDR packages using Oracle XML DB. If you have applications that use one of these packages, you must install Oracle XML DB if it is not already installed. You must also configure network access control lists (ACLs) in the database before these packages can work as they did in prior releases.

The following example first looks for any ACL currently assigned to host_name. If one is found, then the example grants user_name the CONNECT privilege in the ACL only if that user does not already have it. If no ACL exists for host_name, then the example creates a new ACL called ACL_name, grants the CONNECT privilege to user_name, and assigns the ACL to host_name.

DECLARE
acl_path     VARCHAR2 (4000);
v_hostname   VARCHAR2 (200)  := 'xxx.leavemealone.local';
v_user       VARCHAR2 (30)   := 'APEX_050100';
BEGIN
SELECT acl
INTO acl_path
FROM dba_network_acls
WHERE HOST = v_hostname AND lower_port IS NULL AND upper_port IS NULL;

IF dbms_network_acl_admin.check_privilege (acl_path, v_user, 'connect') IS NULL
THEN
dbms_network_acl_admin.add_privilege (acl_path, v_user, TRUE, 'connect');
END IF;
EXCEPTION
WHEN NO_DATA_FOUND
THEN
dbms_network_acl_admin.create_acl ('send_mail.xml', 'send_mail ACL', v_user, TRUE, 'connect');
dbms_network_acl_admin.assign_acl ('send_mail.xml', v_hostname, 25, 25);
END;
/
COMMIT;


New way of adding ACL in Oracle 12c
BEGIN
  DBMS_NETWORK_ACL_ADMIN.append_host_ace (
    host       => 'xxx.leavemealone.local', 
    lower_port => 25,
    upper_port => 25,
    ace        => xs$ace_type(privilege_list => xs$name_list('connect'),
                              principal_name => 'APEX_050100',
                              principal_type => xs_acl.ptype_db)); 
END;
/
COMMIT;

Check ACL and privileges under SYS
SELECT * FROM dba_network_acls;

SELECT * FROM dba_network_acl_privileges order by principal;

Add missing ACL after upgrading APEX
BEGIN
DBMS_NETWORK_ACL_ADMIN.add_privilege ('/sys/acls/power_users.xml',
'APEX_050100',
TRUE,
'connect');
DBMS_NETWORK_ACL_ADMIN.add_privilege ('/sys/acls/send_mail.xml',
'APEX_050100',
TRUE,
'connect');
END;

Duplicate ACL for one schema. In this example, we use APEX_200200. Copy the creation script output and run it on the destination database.
SELECT    'BEGIN DBMS_NETWORK_ACL_ADMIN.append_host_ace (
            HOST         => '''
       || dna.HOST
       || ''',
            lower_port   => '
       || dna.lower_port
       || ',
            upper_port   => '
       || dna.upper_port
       || ',
            ace          =>
                xs$ace_type (privilege_list   => xs$name_list (''connect''),
                             principal_name   => '''
       || dnap.principal
       || ''',
                             principal_type   => xs_acl.ptype_db)); END;
                             /' v_sql
  FROM dba_network_acls dna, dba_network_acl_privileges dnap
 WHERE dna.aclid = dnap.aclid AND dnap.principal = 'APEX_200200';

Saturday, May 9, 2020

Export APEX application/workspace with SQLcl

Export one application

apex export -applicationid 102 -split -skipExportDate -expTranslations -expPubReports -expSupportingObjects N -dir c:\backup

Export all applications

apex export -instance -applicationid 100 -split -skipExportDate -expTranslations -expPubReports -expSupportingObjects N -dir c:\backup

Export all workspaces

apex export -expWorkspace -applicationid 100 -expFiles -skipExportDate -dir c:\backup

Wednesday, February 26, 2020

How to Resolve “ORA-29548: Java system class reported”

After applying Jan 14th 2020 CPU patch, one of the java program in the database getting error.
ORA-29548: Java system class reported: joxcsys: release mismatch, 
12.2.0.1.180717 1.8 in database (classes.bin) vs 12.2.0.1.0 1.8 in executable

Run this in sqlplus to resolve the issue.
@?/javavm/install/update_javavm_db.sql

Thursday, November 7, 2019

Tuning Tomcat 9 for APEX/ORDS in Production

Logging

Configuration File: $CATALINA_HOME/conf/logging.properties
Change all occurrences of FINE and INFO to WARNING or SEVERE

JVM Options

Run tomcat9w.exe
Change Initial Memory pool and Maximum memory pool to 4096.


Main Tomcat Server Configurations

Configuration File: $CATALINA_HOME/conf/server.xml
<Connector port="443" protocol="org.apache.coyote.http11.Http11AprProtocol" 
  SSLEnabled="true" scheme="https" secure="true"
  maxHttpHeaderSize="32767"
  compression="on"
  disableUploadTimeout="true">
  <UpgradeProtocol overheadDataThreshold="0" compression="on" className="org.apache.coyote.http2.Http2Protocol" />

...

</Connector>

Close to the end of server.xml
<Host name="localhost" appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <Context path="/ords" reloadable="false" />

...

</Host>

Oracle REST Data Service

Configuration File: defaults.xml
Change the limits
<entry key="cache.metadata.enabled">true</entry>
<entry key="jdbc.InitialLimit">20</entry>
<entry key="jdbc.MinLimit">20</entry>
<entry key="jdbc.MaxLimit">50</entry>
<entry key="jdbc.MaxStatementsLimit">20</entry>

Wednesday, September 11, 2019

UNDO tablespace growing non-stop Part 2

This the original post and afterward we find out the culprit is the Flashback Data Archive (FDA).

It is a simple fix. We just need to bounce the FDA and within a few hours, oracle should release all the spaces.

BEGIN
  dbms_flashback_archive.disable_application(application_name => 'PARIS_AUDIT');
  dbms_flashback_archive.enable_application(application_name => 'PARIS_AUDIT');
END;
/

Thursday, July 11, 2019

Oracle sql statement audit for an user

Enable Audit for an user
CREATE AUDIT POLICY penweb_api_audit_policy
ACTIONS DELETE, INSERT, UPDATE, SELECT
WHEN    'SYS_CONTEXT(''USERENV'', ''SESSION_USER'') = ''PENWEB_API'''
EVALUATE PER SESSION;

AUDIT POLICY penweb_api_audit_policy;

SELECT object_schema,
object_name,
object_type,
audit_option,
condition_eval_opt,
audit_condition
FROM   audit_unified_policies
WHERE  policy_name = 'PENWEB_API_AUDIT_POLICY';

SELECT * FROM AUDIT_UNIFIED_ENABLED_POLICIES;

Check the Audit trail
EXEC DBMS_AUDIT_MGMT.flush_unified_audit_trail;

SELECT *
FROM   unified_audit_trail
WHERE  dbusername = 'PENWEB_API'
ORDER BY event_timestamp desc;

Remove Audit
NOAUDIT POLICY penweb_api_audit_policy;
DROP AUDIT POLICY penweb_api_audit_policy;

Monday, June 17, 2019

Remote Desktop Services Manager Command Line

From time to time, we cannot RDP into servers because the maximum # of users limit has been reached.
Here is what we do to kill the orphan sessions to make room.

List of Sessions

C:\Users\CyberArkDBA>qwinsta /server:parisdb02p
SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
services                                    0  Disc
console                                     1  Conn
CyberArkDBA                                 9  Disc
31c5ce94259d4...                        65536  Listen
rdp-tcp                                 65537  Listen

Reset a Session

Look for the ID that you want to reset. In this case, it is ID #9.
C:\Users\CyberArkDBA>rwinsta 9 /server:parisdb02p /V

List of Sessions again

C:\Users\CyberArkDBA>qwinsta /server:parisdb02p
SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
services                                    0  Disc
console                                     1  Conn
31c5ce94259d4...                        65536  Listen
rdp-tcp                                 65537  Listen

Tuesday, May 14, 2019

ORDS OAuth 2 Client Credentials

Setup Auto REST for one table with OAuth2
BEGIN
  oauth.create_client(p_name => 'OAuth2 Dynamics Document Client', p_grant_type => 'client_credentials', p_owner => 'LEAVEMEALONE', 
    p_description => 'A client for Dynamics Document', 
    p_support_email   => 'no-reply@leavemealone.com', 
    p_privilege_names => 'oracle.dbtools.autorest.privilege.LEAVEMEALONE');
  ords.enable_object(p_schema => 'LEAVEMEALONE', p_object => 'AD_USER', p_object_alias => 'ad_user', p_auto_rest_auth => true);
  oauth.grant_client_role(p_client_name => 'OAuth2 Dynamics Document Client', p_role_name => 'oracle.dbtools.role.autorest.LEAVEMEALONE');
  oauth.grant_client_role(p_client_name => 'OAuth2 Dynamics Document Client', p_role_name => 'oracle.dbtools.role.autorest.LEAVEMEALONE.AD_USER');
  COMMIT;
END;
/

Find out the CLIENT_ID and CLIENT_SECRET to retrieve the ACCESS_TOKEN
SELECT
*
FROM   user_ords_clients;

        ID NAME                            CLIENT_ID                        CLIENT_SECRET                   
---------- ------------------------------- -------------------------------- --------------------------------       
     10130 OAuth2 Dynamics Document Client K5DGLFxUHTbQ_yCaSc1y3A..         SCtjsrfxag2DWcQ35TjFuw..        

SELECT
  client_name,
  role_name
FROM
  user_ords_client_roles;

CLIENT_NAME                     ROLE_NAME
------------------------------- -------------------------------------------------
OAuth2 Dynamics Document Client oracle.dbtools.role.autorest.LEAVEMEALONE
OAuth2 Dynamics Document Client oracle.dbtools.role.autorest.LEAVEMEALONE.ADUSER

Retrieve ACCESS_TOKEN
curl --request POST \
--url https://tst-opptools.leavemealone.com/ords/uat12c/opt/oauth/token \
--header 'Accept: */*' \
--header 'Authorization: Basic N1V1MHVtRy13bnBxWWg3WWtHOUtCQS4uOnptTjE4VnVhQlBpX2FpVEJCcnJncXcuLg==' \
--header 'Cache-Control: no-cache' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Host: tst-opptools.leavemealone.com' \
--header 'accept-encoding: gzip, deflate' \
--header 'cache-control: no-cache' \
--header 'content-length: 29' \
--data grant_type=client_credentials
Response
{
    "access_token": "-YDi4OaEGgN-mgjGcUfYrg",
    "token_type": "bearer",
    "expires_in": 3600
}

Use the ACCESS_TOKEN to access table
curl --request GET \
--url https://tst-opptools.leavemealone.com/ords/uat12c/opt/ad_user/ \
--header 'Accept: */*' \
--header 'Authorization: Bearer -YDi4OaEGgN-mgjGcUfYrg' \
--header 'Cache-Control: no-cache' \
--header 'Connection: keep-alive' \
--header 'Host: tst-opptools.leavemealone.com' \
--header 'accept-encoding: gzip, deflate' \
--header 'cache-control: no-cache'

Thursday, March 14, 2019

Google Analytics with Oracle

1. Use Query Explorer to generate the list
https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A187243477&start-date=2019-01-01&end-date=2019-03-14&metrics=ga%3Ausers&dimensions=ga%3AdeviceCategory%2Cga%3AscreenResolution&sort=-ga%3Ausers&include-empty-rows=false&max-results=10

2. JSON Response
{
   "kind":"analytics#gaData",
   "id":"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:187243477&dimensions=ga:deviceCategory,ga:screenResolution&metrics=ga:users&sort=-ga:users&start-date=2019-01-01&end-date=2019-03-14&max-results=10",
   "query":{
      "start-date":"2019-01-01",
      "end-date":"2019-03-14",
      "ids":"ga:187243477",
      "dimensions":"ga:deviceCategory,ga:screenResolution",
      "metrics":[
         "ga:users"
      ],
      "sort":[
         "-ga:users"
      ],
      "start-index":1,
      "max-results":10
   },
   "itemsPerPage":10,
   "totalResults":39,
   "selfLink":"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:187243477&dimensions=ga:deviceCategory,ga:screenResolution&metrics=ga:users&sort=-ga:users&start-date=2019-01-01&end-date=2019-03-14&max-results=10",
   "nextLink":"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:187243477&dimensions=ga:deviceCategory,ga:screenResolution&metrics=ga:users&sort=-ga:users&start-date=2019-01-01&end-date=2019-03-14&start-index=11&max-results=10",
   "profileInfo":{
      "profileId":"187243477",
      "accountId":"131677935",
      "webPropertyId":"UA-131677935-1",
      "internalWebPropertyId":"191281733",
      "profileName":"All Web Site Data",
      "tableId":"ga:187243477"
   },
   "containsSampledData":false,
   "columnHeaders":[
      {
         "name":"ga:deviceCategory",
         "columnType":"DIMENSION",
         "dataType":"STRING"
      },
      {
         "name":"ga:screenResolution",
         "columnType":"DIMENSION",
         "dataType":"STRING"
      },
      {
         "name":"ga:users",
         "columnType":"METRIC",
         "dataType":"INTEGER"
      }
   ],
   "totalsForAllResults":{
      "ga:users":"130"
   },
   "rows":[
      [
         "desktop",
         "1920x1080",
         "34"
      ],
      [
         "desktop",
         "800x400",
         "32"
      ],
      [
         "desktop",
         "1600x900",
         "6"
      ],
      [
         "tablet",
         "1920x1080",
         "6"
      ],
      [
         "desktop",
         "1280x720",
         "4"
      ],
      [
         "desktop",
         "1368x912",
         "4"
      ],
      [
         "desktop",
         "1688x906",
         "2"
      ],
      [
         "desktop",
         "1824x1216",
         "2"
      ],
      [
         "desktop",
         "1829x1029",
         "2"
      ],
      [
         "desktop",
         "2057x1157",
         "2"
      ]
   ]
}

3. Parse the response into table records. We can now use the table records in report, grid, chart etc...
SELECT
    jt.*
FROM
        JSON_TABLE ( <<response data from above>>, '$'
            COLUMNS (
                "kind" VARCHAR2 ( 255 ) PATH '$.kind',
                "totalsforallresults" NUMBER PATH '$.totalsForAllResults."ga:users"',
                NESTED PATH '$.rows[*]'
                    COLUMNS (
                        "series" VARCHAR2 ( 255 ) PATH '$[0]' NULL ON ERROR,
                        "label" VARCHAR2 ( 255 ) PATH '$[1]' NULL ON ERROR,
                        "value" NUMBER PATH '$[2]' NULL ON ERROR
                    )
            )
        )
    jt