Максимов     Switch to english version       На главную страницу     Работа, обучение, резюме, профессиональные интересы     Хобби     Контакты
Алексей Владимирович  

        

2012.04.14 - Oracle 11.2.0.2: no patch sets anymore

Starting with 11.2.0.2, each patch-set (like 11.2.0.2 or 11.2.0.3) is supplied as a whole set of files. In other words, you don't need to install base release — just use patch-set to install software from scratch. Described in My Oracle Support article 1189783.1.

By the way, did you know that My Oracle Support nowadays has HTML-only version?

2012.04.10 - Bedtime reading

RAC training:

RAC Attack - Oracle Cluster Database at Home
Oracle Database 11g Release 2 RAC On Linux Using VirtualBox
forums.oracle.com: Killed /u01/app/11.2.0/grid/root.sh, how can i re-execute again?
Deconfiguring Oracle Clusterware Without Removing Binaries

David Marcos' Blog: How to copy SQL Profile from one database to another one

1. Create staging table to store the SQL Profiles to be copied on Source database:
SQL> EXEC DBMS_SQLTUNE.CREATE_STGTAB_SQLPROF (table_name => 'PROFILE_STGTAB');

2. Copy SQL Profiles from SYS to the staging table:
SQL> EXEC DBMS_SQLTUNE.PACK_STGTAB_SQLPROF (profile_category => '%', staging_table_name => 'PROFILE_STGTAB');

As I needed to copy all SQL Profiles on my database '%' value for profile_category was the best option.

3. Export staging table.

4. Create staging table on Destination Database:
SQL> EXEC DBMS_SQLTUNE.CREATE_STGTAB_SQLPROF (table_name => 'PROFILE_STGTAB');

5. Import data on Destination database.

6. Create SQL Profiles on Destination database using data stored on staging table:
SQL> EXEC DBMS_SQLTUNE.UNPACK_STGTAB_SQLPROF(replace => TRUE, staging_table_name => 'PROFILE_STGTAB');

I used replace = TRUE as I needed to have the same SQL Profiles on both databases.

Refer to http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_sqltun.htm#CACFCAEC for a full list of parameters and options.

Oracle — Query block naming

Use the QB_NAME hint to define a name for a query block. This name can then be used in another query block to hint tables appearing in the named query block.

... and this one: Specifying a Query Block in a Hint

Whole bunch on profiles:

Kerry Osborne's Oracle Blog: SQL Profiles
Kerry Osborne's Oracle Blog: Single Hint SQL Profiles
Plan stability in 10g - using existing cursors to create Stored Outlines and SQL profiles

2012.03.10 - Drivers and exhausts

I have been attending Chris Date's seminar on writing effective SQL code in Wellington, New Zealand. The seminar itself requires a separate article as it was terrific experience, really. What I would like to share has nothing common with that seminar.

We had a chat on one of those eat-and-talk breaks with an awesome lady from Fronde. One of the topics discussed was IT problem solving drivers.

— You know, one of huge problems with New Zealand IT is that the driver is incorrect. I am not talking about those "hands.sys", instead, I mean real drivers. I lot of projects here are skills-driven, not task-driven.

— What do you mean?

— Well, that's easy. You, as a company, got a project to do. To choose and implement a solution to a given problem. It's 21st century around, you know, and lots of problems have best known, or at least preferable solutions. For example, desktop system is either Windows or Mac OS, leaning towards Windows for a reason. What I am talking about is — in lots of cases people don't choose best or at least known to be good solution because of various reasons... Lack of people with proper skills, policies against those known to be optimal solutions... executive decisions... etc etc.

— Yes, we do have problems with skills... We are small country, you know. We try to stick with a budget.

— That applies to small companies and small projects, no doubts. But when we speak about medium to large size enterprises, or government... I don't think it applies. You have no skills? Bloody get one through hiring or training. Don't stick to ancient solutions just because there's no one in your possession who can do better!!! It's a task thing, and any solution should be task-driven, at the first place, huh?

On and on. I do think they bought into the idea, but unfortunately I don't think that it will change anything. I wish at some moment of my career I would be able to be task-driven, rather then policy-, money-, skills- or some-other-nice-crap-driven... I really wish I will.

I should have, probably, said that immigration for those skilled is not a problem if they are properly sponsored. I should, perhaps, have said that this shit causes usual quality of IT solutions here, which is, well, "good enough" but not "good" in lots of cases. I might have said that given total IT budget in many projects... you might have thought about everything ranging from hiring a person to upskilling staff, rather than being involved in questionable outsourcing that in fact adds costs rather than cuts them. I should have said about those bespoken policies... Policies are good, they streamline process as any reasonable rule do, but they do not if they interfere with practice of utilizing an appropriate solution for a problem, solution that is already known, adopted and tested by many. Yes, I definitely should have. But we ran out of time and coffee... And by and large it would not have any influence, I believe. This is whole other story though.

2012.03.09 - Chris Date in Wellington

Attended Chris Date's seminar in Wellington. Ansolutely outstanding oldie with goldie ideas and presentation skills. I mean, really.

2011.09.02 - CREATE DATABASE LINK in another user's schema

Solution is taken from https://forums.oracle.com/forums/thread.jspa?threadID=507523

Problem: it is impossible to create database links in different user's schema in Oracle database. Reproduced in 9i and 10g.

Details:

SQL> CONN / AS SYSDBA
Connected.

SQL> CREATE DATABASE LINK testlink USING 'test';
Database link created.

SQL> DROP DATABASE LINK testlink;
Database link dropped.

-- testuser has CREATE DATABASE LINK privilege
SQL> ALTER SESSION SET CURRENT_SCHEMA=testuser;
Session altered.

SQL> CREATE DATABASE LINK testlink USING 'test';
CREATE DATABASE LINK test USING 'test'
                     *
ERROR at line 1:
ORA-01031: insufficient privileges

SQL> CONN testuser
Enter password:***
Connected.

SQL> CREATE DATABASE LINK testlink USING 'test';
Database link created.

SQL> DROP DATABASE LINK testlink;
Database link dropped.

Further explanation: dot in database link name is perceived as a part of database link name rather than component delimiter. But this is not just problem with naming, the option is completely barred (check out my attempt to switch current schema above). Refer to http://download.oracle.com/docs/cd/B14117_01/server.101/b10759/statements_5005.htm for further information.

Solution: as discussed in the article, create procedure in target schema and invoke the procedure [within context and under rights of target schema — that is by default]. Target user, obviously, must have CREATE PROCEDURE and CREATE DATABASE LINKS privileges. Those must be granted directly rather than through roles.

SQL> CONN / AS SYSDBA
Connected.

SQL> CREATE USER testuser IDENTIFIED BY test ACCOUNT UNLOCK;
User created.

SQL> GRANT CREATE PROCEDURE TO testuser;
Grant succeeded.

SQL> GRANT CREATE DATABASE LINK TO testuser;
Grant succeeded.

SQL> CREATE OR REPLACE PROCEDURE testuser.crlink AS
  2  BEGIN
  3  EXECUTE IMMEDIATE 'CREATE DATABASE LINK testlink USING ''test''';
  4  END;
  5  /
Procedure created.

SQL> EXEC testuser.crlink;
PL/SQL procedure successfully completed.

SQL> SELECT owner, db_link FROM dba_db_links;

OWNER      DB_LINK
---------- -----------------------
TESTUSER   TESTLINK.MYDOMAIN.COM
     

What about exporting and importing schemas with database links?.. Don't think it will work if import is done under user other than schema owner. Too lazy to test (yet).

2011.07.10 - Join/Concatenation bug

Hit another nice one in Oracle 10.2.0.4 EE...

Problem: query returns wrong results if concatenation aka OR/IN expansion is used. Same query produces correct result if forced to NO_EXPAND whether directly or indirectly. Plans differ by presence of concatenation and by index scan type.

Details:

SQL statement:

SELECT <...>
  FROM device_table
    LEFT join device_table_event
      ON dte_device_id = dt_id
    LEFT JOIN client_devt_event
      ON (
        client_devt_event.client_id = device_table.dt_client_id
        AND client_devt_event.device_type_id = device_table.dt_device_type_id)
    LEFT JOIN devtype_classifier
      ON devtype_classifier.dtc_device_type_id = device_table.dt_device_type_id
    LEFT JOIN event_classifier
      ON (
        ecl_id = dte_ecl_id
        OR ecl_id = client_devt_event.event_class_id
        OR ecl_id = dtc_evt_classification_id)
  WHERE
    dt_device_name LIKE '%.SCOTT';
This plan produces incorrect results (join predicate never matches any rows from EVENT_CLASSIFIER):
------------------------------------------------------------------------------------------------------
| Id  | Operation                      | Name                | Rows  | Bytes | Cost (%CPU)| Time     |
------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT               |                     | 84965 |  9044K|  6308   (1)| 00:01:16 |
|   1 |  NESTED LOOPS OUTER            |                     | 84965 |  9044K|  6308   (1)| 00:01:16 |
|*  2 |   HASH JOIN RIGHT OUTER        |                     | 28322 |  2212K|   103   (2)| 00:00:02 |
|   3 |    INDEX FAST FULL SCAN        | PK_DEVTYPE_CLASS    |   764 |  6112 |     2   (0)| 00:00:01 |
|*  4 |    HASH JOIN OUTER             |                     |   761 | 54792 |   100   (1)| 00:00:02 |
|*  5 |     HASH JOIN OUTER            |                     |   369 | 22878 |    89   (2)| 00:00:02 |
|*  6 |      TABLE ACCESS FULL         | DEVICE_TABLE        |   369 | 18081 |    85   (0)| 00:00:02 |
|   7 |      TABLE ACCESS FULL         | CLIENT_DEVT_EVENT   |  2388 | 31044 |     3   (0)| 00:00:01 |
|   8 |     TABLE ACCESS FULL          | DEVICE_TABLE_EVENT  | 15608 |   152K|    11   (0)| 00:00:01 |
|   9 |   VIEW                         |                     |     3 |    87 |     0   (0)| 00:00:01 |
|  10 |    CONCATENATION               |                     |       |       |            |          |
|  11 |     TABLE ACCESS BY INDEX ROWID| EVENT_CLASSIFIER    |     1 |    37 |     2   (0)| 00:00:01 |
|* 12 |      INDEX UNIQUE SCAN         | PK_EVENT_CLASSIFIER |     1 |       |     1   (0)| 00:00:01 |
|  13 |     TABLE ACCESS BY INDEX ROWID| EVENT_CLASSIFIER    |     1 |    37 |     2   (0)| 00:00:01 |
|* 14 |      INDEX UNIQUE SCAN         | PK_EVENT_CLASSIFIER |     1 |       |     1   (0)| 00:00:01 |
|  15 |     TABLE ACCESS BY INDEX ROWID| EVENT_CLASSIFIER    |     1 |    37 |     2   (0)| 00:00:01 |
|* 16 |      INDEX UNIQUE SCAN         | PK_EVENT_CLASSIFIER |     1 |       |     1   (0)| 00:00:01 |
------------------------------------------------------------------------------------------------------
   2 - access("DEVTYPE_CLASSIFIER"."DTC_DEVICE_TYPE_ID"(+)="DEVICE_TABLE"."DT_DEVICE_TYPE_ID")
   4 - access("DTE_DEVICE_ID"(+)="DT_ID")
   5 - access("CLIENT_DEVT_EVENT"."DEVICE_TYPE_ID"(+)="DEVICE_TABLE"."DT_DEVICE_TYPE_ID" AND
              "CLIENT_DEVT_EVENT"."CLIENT_ID"(+)="DEVICE_TABLE"."DT_CLIENT_ID")
   6 - filter("DEVICE_TABLE"."DT_DEVICE_NAME" LIKE '%.SCOTT')
  12 - access("ECL_ID"="DEVICE_TABLE_EVENT"."DTE_ECL_ID")
  14 - access("ECL_ID"="CLIENT_DEVT_EVENT"."EVENT_CLASS_ID")
       filter(LNNVL("ECL_ID"="DEVICE_TABLE_EVENT"."DTE_ECL_ID"))
  16 - access("ECL_ID"="DEVTYPE_CLASSIFIER"."DTC_EVT_CLASSIFICATION_ID")
       filter(LNNVL("ECL_ID"="CLIENT_DEVT_EVENT"."EVENT_CLASS_ID") AND
              LNNVL("ECL_ID"="DEVICE_TABLE_EVENT"."DTE_ECL_ID"))
This one produces expected results:
------------------------------------------------------------------------------------------------------
| Id  | Operation              | Name                        | Rows  | Bytes | Cost (%CPU)| Time     |
------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT       |                             |  1161K|    95M|  6312   (1)| 00:01:16 |
|   1 |  NESTED LOOPS OUTER    |                             |  1161K|    95M|  6312   (1)| 00:01:16 |
|*  2 |   HASH JOIN RIGHT OUTER|                             | 28322 |  2212K|   103   (2)| 00:00:02 |
|   3 |    INDEX FAST FULL SCAN| PK_DEVTYPE_CLASS            |   764 |  6112 |     2   (0)| 00:00:01 |
|*  4 |    HASH JOIN OUTER     |                             |   761 | 54792 |   100   (1)| 00:00:02 |
|*  5 |     HASH JOIN OUTER    |                             |   369 | 22878 |    89   (2)| 00:00:02 |
|*  6 |      TABLE ACCESS FULL | DEVICE_TABLE                |   369 | 18081 |    85   (0)| 00:00:02 |
|   7 |      TABLE ACCESS FULL | CLIENT_DEVT_EVENT           |  2388 | 31044 |     3   (0)| 00:00:01 |
|   8 |     TABLE ACCESS FULL  | DEVICE_TABLE_EVENT          | 15608 |   152K|    11   (0)| 00:00:01 |
|   9 |   VIEW                 |                             |    41 |   246 |     0   (0)| 00:00:01 |
|* 10 |    INDEX FAST FULL SCAN| PK_EVENT_CLASSIFIER         |     3 |    18 |     2   (0)| 00:00:01 |
------------------------------------------------------------------------------------------------------
   2 - access("DEVTYPE_CLASSIFIER"."DTC_DEVICE_TYPE_ID"(+)="DEVICE_TABLE"."DT_DEVICE_TYPE_ID")
   4 - access("DTE_DEVICE_ID"(+)="DT_ID")
   5 - access("CLIENT_DEVT_EVENT"."DEVICE_TYPE_ID"(+)="DEVICE_TABLE"."DT_DEVICE_TYPE_ID"
              AND "CLIENT_DEVT_EVENT"."CLIENT_ID"(+)="DEVICE_TABLE"."DT_CLIENT_ID")
   6 - filter("DEVICE_TABLE"."DT_DEVICE_NAME" LIKE '%.SCOTT')
  10 - filter("ECL_ID"="DEVTYPE_CLASSIFIER"."DTC_EVT_CLASSIFICATION_ID" OR
              "ECL_ID"="CLIENT_DEVT_EVENT"."EVENT_CLASS_ID" OR
              "ECL_ID"="DEVICE_TABLE_EVENT"."DTE_ECL_ID")

I found some CONCAT-related bugs on metalink, but none matches this case. There are no functional indexes, for instance. These are just plain table with plain B-tree indexes. Nothing special. By the way, changing join method — say, to nested loops — did not help either.

It was recommended to the requestor to force execution plan without concatenation ;-( Workaround only.

2010.12.31 - oops proxy, FreeBSD & IPL_NAT

Oops — старая, поросшая мохом софтина и прочая и прочая. Ниипет. Главное, что работает. К сожалению, не всегда компилируется с первого раза...

Отсюда:

# uname -a
FreeBSD test.testdomain.com 6.4-RELEASE FreeBSD 6.4-RELEASE
# env CPPFLAGS=-I/usr/local/BerkeleyDB/include LDFLAGS=-L/usr/local/BerkeleyDB/lib ./configure --prefix=/usr/local
...
# gmake
...
transparent.c: In function `redir':
transparent.c:217: error: `IPL_NAT' undeclared (first use in this function)
transparent.c:217: error: (Each undeclared identifier is reported only once
transparent.c:217: error: for each function it appears in.)
gmake[2]: *** [transparent.so] Error 1
gmake[2]: Leaving directory `/var/dist/1/oops-1.5.23/src/modules'
gmake[1]: *** [modules] Error 2
gmake[1]: Leaving directory `/var/dist/1/oops-1.5.23/src'
gmake: *** [all] Error 2
# mv src/modules/transparent.c src/modules/transparent.c.orig
# sed '1,$s/IPL_NAT/IPNAT_NAME/g' src/modules/transparent.c.orig > src/modules/transparent.c
# gmake
...
lib.c: In function `str_to_sa':
lib.c:310: warning: passing arg 5 of `gethostbyname_r' from incompatible pointer type
lib.c:310: error: too few arguments to function `gethostbyname_r'
lib.c:310: warning: assignment makes pointer from integer without a cast
gmake[1]: *** [lib.o] Error 1
gmake[1]: Leaving directory `/var/dist/1/oops-1.5.23/src'
gmake: *** [all] Error 2
# echo "--- src/lib.c.orig
+++ src/lib.c
@@ -285,6 +285,7 @@
 #if    defined(HAVE_GETHOSTBYNAME_R)
                        struct hostent  *he;
                        struct hostent  he_b;
+#define LINUX
 #if     defined(LINUX)
                        struct hostent  *he_x;
 #elif   defined(_AIX)" | patch
# gmake

2010.12.23 - debug ip packet dump

Отсюда:

You really don't want to do "debug ip packet detail" if you are connected via telnet/ssh and are logging to anything other than the internal buffer. Otherwise the debug will capture the output going to the screen and/or syslog server and you'll get this nifty loop loop of doom as the debug causes more packets to dump from the debug.

Even going to the buffer (which will scroll like crazy if the router is moving much traffic at all) this will still add load to the router's CPU so be careful with this. If you have a way to narrow down what you are looking for make an ACL to only match those packets, and put the ACL number after the debug command as in "debug ip packet detail 122". This will give you less output to dig through and limit the overhead of logging every packet.

Finally, if you're really feeling brave or are doing this in a lab where you can take risks, there is an undocumented mode in most IOS versions called "debug ip packet dump" that will dump the entire contents of the packets, as tcpdump would. All the stuff above about overhead, etc. goes triple for this. The reason it's undocumented is so people don't complain to Cisco if they crash their router with this command.

Действительно, пишет довольно много, и действительно, кладет роутер. Пример monitor session 1 <destination/source> 1 int fa 0/bla на той же странице у меня не заработал ни на одном из роутеров и свичей.

2010.12.19 - Железки

Я, значить, прикупил себе немного железок, а именно Yamaha Motif XF8, и к нему Mackie HR824 MK2. Желающие обозвать меня пижоном могут сразу идти лесом — на синте я пока играть не умею, только учусь, да и мониторные колонки к нему тоже, в общем, штука необязательная. И то, и другое куплено на вырост. Но, в общем, не о том речь.

Курю «Самоучитель игры на фортепиано» Мохель и Зиминой. К последним претензий нет, а вот к разработчикам нотной записи — есть. Сложно сказать, что именно они курили, однако трава была очень забористая. Хорошо, что эти люди не пишут пользовательские интерфейсы. Впрочем, что вы хотели — нотная запись существует в практически неизменном виде с XVII века. Я как-то затрудняюсь сказать, что еще с XVII века до сих пор используется и не претерпело каких-то серъезных изменений в свете чуток продвинувшейся за 300 лет технологии.

Конкретные претензии с точки зрения компьютерщика:

  • Систему бемолей и диезов придумал ПП (полный пидорас). Они исключительно затрудняют восприятие того, что вообще надо нажимать и как оно должно звучать.
  • Можно было бы как-то графически разделить октавы на нотоносце.
  • Обозначения стиля игры, как-то: «не скоро», «довольно живо», «размеренно» придумала, наверное, та же личность. Пока до конца не понятно, как их формализировать... понятно только, что на понятном нормальному гику языке эту называется «профиль» и определяет относительную скорость и громкость воспроизведения.
  • Музякальная клавиатура — это нечто. Я все понимаю, но дизайнер, очевидно, не предполагал, что на ней когда-то будут играть люди. Понятно, что в XVII веке были некоторые технологические ограничения на процесс производства пианино, то с тех пор все-таки прошло уже больше 300 лет, и пора бы, наверное, сделать небольшой апгрейд. Для сравнения: на стандартной компьютерной клавиатуре порядка 100 клавиш, занимает она места раза этак в 4 меньше. Думаю, что при желании можно было бы придумать что-то юзабельное — просто всем вроде бы пофиг.

После пары часов разучивания гамм создалось впечатление, что мой мозг вы#бан. Мне сказали, что это распространенный эффект и буквально через 3 года напряженных занятий он пройдет. Воодушевлен.

Колонками доволен и присоединяюсь к многочисленным восторженным обзорам. Это один из тех немногих случаев, когда охренительные характериктики (по факту нелинейность АЧХ не превышает +/- 2dB на всем диапазоне от 20Гц до 20КГц) на 100% подкрепляются субъективным впечатлением (звучат они, другими словами, не менее охренительно, чем их характеристики выглядят на бумаге).

2010.10.07 - BRAINDUMP: printing to Oracle's alert.log

Sometimes it could be useful to print out some mess directly into alert.log. The very first thing that comes to my mind is debug, especially when it should be lightweight and/or relieble and/or easily readable by external means. After all, it's the easiest thing to implement.

So, for up to 10g (tested working 8i, 9i, 10g):

     sys.dbms_system.ksdwrt(2,'...');
where the first parameter is bitmap value that indicates the destination:
1 - trace file,
2 - alert.log,
3 - both.

Few words on security: it is recommended to specify SYS schema explicitly wherever and whenever you call a procedure under high-privileged context, like trigger. Guess what happens if somebody declare global synonym with the same name... Yeah, this is it.

From here. Mr. Burleson outlines another useful idea &mdash it is actually possible to read from alert.log. It could be useful for various kind of monitoring driven from the database. It is especially easy from 11g onwards with X$DBGALERTEXT whereas in previous versions it's a bit cumbersome (external table or utl_file), as well as parsing raw text is not easy task.

2010.09.15 - Cisco 7975 phone reset

To reset (reload, reboot) Cisco 7975, you need to press Settings or Directory and then **#**. Be patient and wait at least 10 seconds. The key combination appears be the same for entire java model line &mdash 79x1, 79x2, 79x5.

If you try to enter the command as a phone number, nothing happens, by the way.

2010.09.10 - G.722 setup

Got Cisco 7975 IP phone to play with. It has a lot of advantages over my current phones, to name few — wideband G.722 audio support and backlit color touch-screen display. Frankly, I don't use touch screen a lot so probably there is no much difference between 7965 and 7975.

It seems that by default the phone has it's wideband support off, e. g. it does not advertise G.722 capabilities, as per following debug output from Asterisk:

     AstSVR*CLI> sip set debug on
     <...>
     Capabilities: us - 0x8100e (gsm|ulaw|alaw|g722|h263),
       peer - audio=0x50c (ulaw|alaw|g729|ilbc)/video=0x0 (nothing)/text=0x0 (nothing),
       combined - 0xc (ulaw|alaw)
     <...>

To make phone work with wideband you need at least to add

     <g722CodecSupport>2</g722CodecSupport>
to <vendorConfig> section and
     <advertiseG722Codec>1</advertiseG722Codec>
to section.

You can also change the following default values of headset and handset capabilities in <vendorConfig>:

     <headsetWidebandUIControl>0</headsetWidebandUIControl>
     <handsetWidebandUIControl>0</handsetWidebandUIControl>
     <headsetWidebandEnable>0</headsetWidebandEnable>
     <handsetWidebandEnable>1</handsetWidebandEnable>

Asterisk has native support of G.722 starting with version 1.6. There is a patch for 1.4 that enables G.722 in that version, but I didn't look into it very closely as I moved off 1.4 some time ago.

So, now my peer configuration looks like this:

     AstSVR$ cat ~/etc/sip.conf
     <...>
     [testextension]
     <...>
     dtmfmode=rfc2833
     disallow=all
     allow=ulaw
     allow=alaw
     allow=gsm
     allow=g722
     allow=ilbc
     <...>
... and debug output like this:
     AstSVR*CLI> sip set debug on
     <...>
     Capabilities: us - 0x8100e (gsm|ulaw|alaw|g722|h263),
       peer - audio=0x150c (ulaw|alaw|g729|ilbc|g722)/video=0x0 (nothing)/text=0x0 (nothing),
       combined - 0x100c (ulaw|alaw|g722)
     <...>

As per audio quality — I have unfortunately no means of testing phone-to-phone link yet, but if you have G.722 core prompts and extra sounds installed, you can test it against, say, voice mail or listen to some on-hold music.

To my audioplilious opinion, G.722 is still not enough to listen Chopin over a phone, but it seems to be quite good "lifelike" thing for voice calls. The difference between G.711 and G.722 is great for the same 64K / 87kbit bandwidth, pretty much like difference between G.729 and G.711.

See also: Asterisk codec reference.

2010.10.05 - Cadences

Finally I got pissed off with my D-Link 7022S, particularly with its behaviour regarding busy tone cadences. Right ones can be easily found on the net, but just setting 425Hz/350ms/0Hz/350ms is not enough. First, i needed to fine tune line gain to get em working at all. Second, I had to set up correct silence-activated call cutout threshold, because sometimes busytone cutoff does not work properly and fortunately my PSTN provider just falls back to silence after a minute of busy tone. The task is really aggravated by line noise... Bloody nightmare.

However, after about 1 hour of trying, I figured out right combination of busytone cadence, line gain and silence threshold to get something more or less reliable. What I was absolutely unable to do is to make ATA wait for PSTN answer to start RTP stream. ATA itself seems to support it (by detecting ring tone - while it's ringing, ATA returns RINGING SIP state and does not start RTP stream). However, PSTN gives out three-staged ascending tone while connecting, 950Hz/330ms/1400Hz/330ms/1800Hz/330ms, before anything else, and it makes ATA think somebody has answered, then there could be some amount of silence, and then goes dial/busy/congestion etc. It does not seem possible to make ATA deal with this mess properly...

2010.09.15 - Cisco 7975 - get some coffee...

Got my first Java-based Cisco phone, which just happened to be Cisco 7945. Nice piece of hardware, really well built, exceptional user interface, though setting up and upgrading is absolute f*ckup.

Quick facts:

  • It's good to upgrade to 8.5.something firmware because of bugs. If you, however, upgrade from 8.3.something or even older release, it's impossible to upgrade directly to any release after 8.5.2, even to 8.5.2 SR1. Upgrade to at most 8.5.2 first instead (i've used 8.4.2 by the way), and only then upgrade to post-8.5.2.
  • Do not use 9.x. There are no known working configs for this release. The phone just don't try to register with Asterisk or whatever is used as third-party SIP service.
  • G.722 codec is still switched off by default. WHY?!
  • G.722 is REALLY good. I cannot invent more exact definition than Cisco use - it's lifelike. The difference between G.711 and G.722 is much greater than difference between G.729 and G.711. And G.722 still uses 64kbit raw RTP, that is around 86kbit UDP.
  • Asterisk 1.6 supports G.722, including transcoding, out of the box. Codec name is, guess, g722. Sound quality is not good when transcoding is done by Asterisk though, it is much better to get the phone natively with the codec the other party use.

2010.08.23 - Another faulty 1SHDSL-V3

Short story in a few lines: before buying/selling this one, put it into a router and make sure the card lights up OK led on the card itself, WIC OK on the router does not really matter. Otherwise you are likely to deal with faulty card. Off course you need right IOS featureset and revision number that supports this type of WIC. Long story follows...

I use these Cisco WIC in my home internet line. Quite a long story, but if told short, (1) standard provider means of setting up last mile access are not really reliable on this particular line, you get drops, low speed, disconnects and all that kind of stuff, and the only way they can help is to drop speed down to the floor using DSLAM settings, and (2) I need uplink as well. There are also other causes why I don't use damn plain ADSL.

So, I have 2 17xx routers, one sitting exchange side, another — in my premises. Exchange one is terminating PPPoE and is physically coupled to the provider's equipment using Ethernet, and there are two SHDSL copper pairs going down to the premises, each connected to the separate WIC. Yes I know that's weird, but I am the weird guy, and yes, I know 1SHDSL-V3 support operation over 2 pairs — the problem with that is if the WIC is configured in 4-line mode, and one of the pairs is missing, you get no traffic at all (shame on Cisco). Another point is that lines need to have same speed, and this speed has to be set manually. So I have a router with Ethernet, PPPoE, 2 x 1SHDSL-V3's sitting in exchange, and nearly the same spec'd box in my premises. Porn goes over 2 pairs, eigrp, packet-level load balancing and failover, all sweet. Getting my 4 mbps upstream and 4 mbps downstream, simultaneously.

Though I am not really pleased I have no backup. I do have another router ready in case some of prod ones break, but I have only one spare SHDSL WIC, and I desperately trying to get another one keeping my pants up. In other words, I cannot afford buying one brand new from Cisco.

This is not that easy. I've been facing faulty WICs 2 times in a row, and that's how they break...

     Hi,

     The WIC seams to be dead. I've seen such problem before.

     It does show properly in sho diag/sho ver and everything seems to be okay, like

     gw#sho ver

     <...>

     gw uptime is 4 minutes
     System returned to ROM by power-on
     System image file is "flash:***-adventerprisek9-mz.124-24.T.bin"
     <...>

     Cisco *** (revision ***) with 357376K/35840K bytes of memory.
     Processor board ID ***
     1 DSL controller
     2 FastEthernet interfaces
     1 Virtual Private Network (VPN) Module

     gw#sho diag

     <...>

             WIC/HWIC Slot 1:
             GSI GSHDSL MULTI LINE ATM WIC

             Hardware Revision        : 0.0
             Top Assy. Part Number    : 800-26571-02
             Board Revision           : A1
             Deviation Number         : 0
             Fab Version              : 01
             PCB Serial Number        : ***
             RMA Test History         : 00
             RMA Number               : 0-0-0-0
             RMA History              : 00
             Version Identifier       : V02 
             Product (FRU) Number     : WIC-1SHDSL-V3
             EEPROM format version 4
             EEPROM contents (hex):
               0x00: 04 FF 40 04 DA 41 00 00 C0 46 03 20 00 67 CB 02
               0x10: 42 41 31 88 00 00 00 00 02 01 C1 8B 46 4F 43 31
               0x20: 30 34 37 30 57 42 58 03 00 81 00 00 00 00 04 00
               0x30: 89 56 30 32 20 CB 8D 57 49 43 2D 31 53 48 44 53
               0x40: 4C 2D 56 33 FF FF FF FF FF FF FF FF FF FF FF FF
               0x50: FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
               0x60: FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
               0x70: FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF

     ... but it does not really work - no WIC-specific commands are available
     when you try to configure it:

     gw(config)#controller DSL 0/1/0 
     gw(config-controller)#?
     Controller configuration commands:
       default      Set a command to its defaults
       description  Controller specific description
       exit         Exit from controller configuration mode
       help         Description of the interactive help system
       no           Negate a command or set its defaults

     gw(config-controller)#mode atm
                                ^
     % Invalid input detected at '^' marker.

     This is how it should be for WIC-1SHDSL-V3:

     rtr-dsv(config)#controller DSL 0
     rtr-dsv(config-controller)#?
     Controller configuration commands:
       default                Set a command to its defaults
       description            Controller specific description
       dsl-mode               SHDSL mode
       exit                   Exit from controller configuration mode
       help                   Description of the interactive help system
       ignore-error-duration  Number of seconds errors such as CRC are ignored
                              while the line is traning (default is 0)
       line-mode              line mode four-wire or two-wire
       line-rate              Configure SHDSL Line Rate
       line-term              Customer Premise or Central Office
       loopback               XDSL loopback test
       mode                   Configure the xdsl controller mode
       no                     Negate a command or set its defaults
       shutdown               Shutdown the xdsl controller
       snr                    SNR

     I've tested your controller in 2 different routers. IOS levels were
     sufficient, and I've used 1SHDSL-V3 WICs in these routers before.

     I had exactly the same problem with this type of WIC previously, and
     the seller considered WIC dead and made a refund. It seems that DSL
     chipset is dead, so router is able to see something is present in the
     slot, and even identify the card, but can not use it.

     You wrote the card is working pull.

     Was it actually connected to the line, where traffic did actually go?

     It is, unfortunately, quite difficult to say, without logging into the
     router, that the card is broken this way, unless it is actually used to
     pass traffic. The only outer sign that it's broken is it
     doesn't light OK led up, the one on the card - please note,
     if the router has WIC OK led as well, it does light up, but not
     the one on the card. I spent several days trying to isolate the problem,
     and finally one Cisco guy told me that this is the way these WICs
     sometimes die.

Okay, let's wais for another one to show up... Pity...

2010.08.20 - Tom Kyte seminar

Been to Tom Kyte seminar in WҐllingt®n. Got an excellent day. First, the stuff was really good, though I knew around 80% of what he was talking about, another 20% was due to 11g new features. But it was amazing even in spite of those eighty percent. Tom is an excellent speaker. An excellent speaker has a talent to put things out in easy to understand, easy to memorize, and really spectacular way. I value that qualities of a speaker, because I am trainer myself, and know what it takes to make good technical presentation.

And, hey Oracle sales, that was the first Oracle seminar ever when I had a copy of presentations the same day. For the previous ones, like Exadata, EM 11g, Oracle/Sun merger, I asked Oracle for presentations, got a reply that files will be made available, but it never was.

2009.11.24 - Natalia Nikolaeva

Got a spam regarding natalianikolaeva.ru. Well, not exact spam, but link exchange request that looks like spam. I consider the site to be quite good, so link exchange request is honoured.

2009.06.24 - Arano juice

From the cap of Arano juice:

     USE BY 01/07/2009
     SQUEEZED 11/06/09

Impressed.

2009.06.24 - Remove parameter from SPFILE

This feature is available in Oracle 9i+. To remove a parameter from spfile and reset it to default value run the following command:

     alter system reset sga_max_size scope=spfile sid='*';
sid is compulsory. scope is not, however, for most static parameters it is compulsory as well. Use "quotes" for _hidden_parameters. Taken from here.

2009.06.24 - shminfo_shmmax in Solaris 10

A good article for ORA-27102 followed by SVR4 Error: 22: Invalid argument is found here local copy.

As a side effect of learning this Oracle error — in Solaris 10 and, possibly, up, setting shmsys:shminfo_shmmax in /etc/system is no longer preferred way to control maximum allowed size of shared memory segment, and it's default value changed to 1/4 of physical memory instead of 8M.

Related: prtconf, id -p, prctl, projadd, projects -l.

2009.06.11 - Oracle Standby/Dataguard, different word sizes, architecture and OS

In Oracle Dataguard/Standby, both physical and logical, does standby site need to be the same architecture? Hardware? OS? OS bitness? OS release? OS patch level? Oracle EE/SE? Version and bitness? Patch level? Physical database (directory and file sizes) structure? Same parameters?

According to 9i and 10g docs, as well as Note 239941.1 — Supported Physical Standby Database Word Sizes,

  • Architecture: YES.
    If you run primary on SPARC, standby must run SPARC as well. Bitness could be different — see below.

  • Hardware: NO.
    You should, however, consider load capabilities of standby host for the case of real disaster. It is not recommended to have standby site less powerful than primary — because in case of a disaster, you are likely to require more processing power, for example, to process data loss or corruption.
    You should also consider licensing — you must license standby database separately, at least on per-CPU basis.

  • OS: YES as of docs and best practices. NO, as a matter of reality — for example, it's obvious that you can run primary site on RHEL and standby on CentOS, as long as Oracle image is the same.

  • OS bitness: NOT LOWER THAN ORACLE IMAGE.
    Both primary and standby hosts have to be able to run same-bitness Oracle image. You can not use primary 64-bit Oracle running on 64-bit host and 32-bit standby host just because 32-bit standby host can not run 64-bit Oracle image, because Oracle images needs to be the same, including bitness.

  • OS Release and patch level: NO as of docs. YES as of best practices — there is an excerpt from Note 239941.1:
        A heterogeneous configuration is not optimum for a High Availability and 
        Disaster Protection environment. The simplest configuration with the least 
        complexity and the highest levels of reliability and supportability are 
        homogeneous and symmetric configurations.
    
        Building and maintaining an HA configuration is complex enough, so why would 
        you comprise your HA by deploying these configurations?
    
        Think of the testing you should be doing before deploying a homogenous Data 
        Guard configuration. By going heterogeneous you are increasing the testing, 
        complexity and risk.
    
        There is also the application to consider. Does it really work transparently 
        on different OS releases with different bit-ness? Has the application and OS 
        utilities (e.g., file system, volume manager etc.) been validated in all these 
        different modes? Are there any operational differences between the two systems? 
        In theory no, but in the heat of a disaster failover, do you want to find some 
        OS/app/utility weirdness?
    
        A heterogeneous Data Guard configuration needs to be thoroughly tested before 
        deployment.
  • Oracle EE/SE: YES.
    You can't run DG on SE, however, you can run manual or scripted log application in Standard Edition. Dataguard is a feature of Enterprise Edition only.

  • Oracle Version, release and bitness: YES.

  • Oracle patchset (patch level): NO as of docs, YES as of best practices. Same note:
        Oracle Online Documentation states that the primary and standby databases must
        run the same maintenance release of Oracle (which is second number in version,
        for example, 10.2.0.4 stands for maintenance release 2), and both databases
        must have the same setting for the COMPATIBLE initialization parameter.
    
        For example, if your primary database is running release 8.1.7 with the 
        COMPATIBLE initialization parameter set to 8.1.0, then the standby database 
        can run any production 8.1 release, such as releases 8.1.5, 8.1.6 or 8.1.7, 
        as long as it also has COMPATIBLE set to 8.1.0.
    
        However, in this case, the standby database cannot run Oracle7 or release 8.0, 
        and COMPATIBLE cannot be set to any value other than 8.1.0 for the standby 
        database.
    
        While, in theory, this all works transparently, Oracle does not recommend you 
        to do it unless you can't avoid it.
  • Physical database (directory) structure: NO.
    Datafile sizes will be the same. Paths — do not. Though you can have some files completely missing on standby, as long as it is understood that you won't be able to use these files' content in case of standby database activation or opening it read only.

  • Same parameters: SOME.
    COMPATIBILITY needs to be the same. Obviously, database block size and name needs to be the same.

2009.06.08 - Validate online

Some people do not realize that ANALYZE TABLE VALIDATE STRUCTURE actually locks an object. You need to do it ONLINE, for example:

     ANALYZE TABLE <OWNER.TABLE_NAME> VALIDATE STRUCTURE CASCADE ONLINE;
Same applies to CREATE INDEX and ALTER INDEX REBUILD.

2009.06.08 - Physical Block Corruption

Further night time reading, highly recommended.
Note 403747.1 — FAQ: Physical Corruption
Note 28814.1 — Handling Oracle Block Corruptions in Oracle7/8/8i/9i/10g
Note 32969.1 — TECH: Database Block Checking Features
Note 33405.1 — Extracting Data from a Corrupt Table using SKIP_CORRUPT_BLOCKS or Event 10231

2009.06.08 - OFA

Got some night time reading — Optimal Flexible Architecture from Oracle© Database Installation Guide 11g Release 1 (11.1) for Solaris Operating System, P/N B32068-02.

It's never late to revisit the basic concepts.

2009.06.07 - Oracle Backup Solutions Program

Prior to buying some backup system for Oracle, consult this page first. Never believe to what sales person says.

2009.06.05 - renaming 8i Oracle database and ORA-01161

Tried to rename database according to some well-known instructions. Off course, it did not work through:

     CREATE CONTROLFILE REUSE DATABASE "NEWDBNAME" RESETLOGS NOARCHIVELOG
     *
     ERROR at line 1:
     ORA-01503: CREATE CONTROLFILE failed
     ORA-01161: database name OLDDBNAME in file header does not match given name of NEWDBNAME
     ORA-01110: data file 1: '/u01/oradata/NEWDBNAME/system01.dbf'

Correct command, actually, is

     CREATE CONTROLFILE REUSE SET DATABASE "NEWDBNAME" ...
(by the way, a clue is taken from Oracle forums). F#ck me, it seems that all these people, like Mr Burleson, didn't actually tried what they are suggesting to do.

However, this way i discovered nid command. Worth trying.

2009.06.05 - ORA-08103: object no longer exists at GATHER_STATS_JOB, 10g

Hit this error:

     GATHER_STATS_JOB encountered errors.  Check the trace file.
     Errors in file /path/to/bdump/directory/dbname_j002_7862.trc:
     ORA-08103: object no longer exists
Trace header:
     *** <date-time>
     *** ACTION NAME:(GATHER_STATS_JOB) <date-time>
     *** MODULE NAME:(DBMS_SCHEDULER) <date-time>
     *** SERVICE NAME:(SYS$USERS) <date-time>
     *** CLIENT ID:() <date-time>
     *** SESSION ID:(<sid>.<serial>) <date-time>

As for me, it could mean that user code has managed to drop a table or its index between GATHER_STATS_JOB has created a list of objects to gather stats on and actual object processing. Look at the bottom of trace file to find which table was it (could be also index on the table specified):

     <...>
     GATHER_STATS_JOB: GATHER_TABLE_STATS('"<owner>"','"<table_name>"','""', ...)
     ORA-08103: object no longer exists

There are some notes that it is recommended to switch this job off for instances running Oracle Apps 11i:

     SELECT job_name, job_type, program_name, schedule_name, job_class
       FROM dba_scheduler_jobs
       WHERE job_name = 'GATHER_STATS_JOB';
     EXECUTE dbms_scheduler.disable('GATHER_STATS_JOB');
     

2009.06.02 - RMAN adventures with CROSSCHECK

Dealing with RMAN on Oracle 10.2.0.4, with storage backend of some MML-based tape library, came across strange behaviour of RMAN and/or the bloody library.

The library itself has some retention policy, apparently set to two weeks (there are 2 options — "short term" and "long term", and, unfortunately, the vendor haven't got a moment to explain them in docs, but we see errors connected only to those backup sets that are more than 2 weeks old). Because RMAN retention is more than a fortnight, we getting these funny errors:

     RMAN-06207: WARNING: 10 objects could not be deleted for SBT_TAPE channel(s) due
     RMAN-06208:          to mismatched status.  Use CROSSCHECK command to fix status
     RMAN-06210: List of Mismatched objects
     RMAN-06211: ==========================
     RMAN-06212:   Object Type   Filename/Handle
     RMAN-06213: --------------- -----------------
     RMAN-06214: Backup Piece    ***
     RMAN-06214: Backup Piece    ***
     ...
While dealing with library stuff to increase retention, i decided to suppress these errors by doing the following each time DELETE OBSOLETE is called:
     run {
      allocate channel ch1 type &sbt_tape&
      parms="MML stuff";
      crosscheck backup;
      delete noprompt expired backup;
      crosscheck copy;
      delete noprompt expired copy;
      backup archivelog all delete all input;
      delete noprompt obsolete;
     }

There were, however, some occurencies where backup sets, obsolete due to RMAN's retention policy, were CROSSCHECKed as AVAILABLE, so RMAN does not try to delete them as a result of DELETE EXPIRED command,
BUT
few lines later DELETE OBSOLETE gives an error saying that these obsolete backup sets can not be deleted due to its mismatched status.

It seems that CROSSCHECK EXPIRED BACKUP does not 100% guarantee existence and availability of a backup set on a tape. Bloody disgusting.

2009.05.29 - rm /var/empty, FreeBSD, Operation not permitted

Surely, you are not going to delete /var/empty, in my case it was a backup restored from dump file. However,

     host# id 
     uid=0(root) gid=0(wheel) groups=0(wheel), 5(operator)
     host# ls -l
     total 2
     drwxr-xr-x  2 root  wheel  512 May 29 19:59 empty
     host# rm -rf empty
     rm: empty: Operation not permitted

WTF?! Am I root?! No, this is a dirty trick. To see what's happening, try

     host# ls -lo
     total 2
     drwxr-xr-x  2 root  wheel  schg 512 May 29 19:59 empty
and to fix,
     host# chflags noschg empty
     host# rmdir empty

For more information refer to man chflags.

2009.05.27 - DynaLink RTA 1320, Telstra, PPPoA

My ISP gave me a magic DSL modem which is router itself, but not so featured as my Cisco 1751. PPPoA turns to be an amazing technology: unlike PPPoE, it's quite impossible to terminate IP connection, e. g. have a real IP, on Windows XP, because the latter does not support PPPoA. After some investigations, found a way to hybridize RTA1320 and Cisco 1751 with 1ENET from WAN side.

According to User Manual, you should use Quick Setup. By the way, default username and password for WebUI is "admin". Configure automatic connection first, and then, using "Status" > "Internet Connection", find out VPI and VCI value for your ISP (0 and 100 for me respectively). Then enter "Quick Start" > "Quick Setup" again, clear "Auto Scan Internet Connection (PVC)" and enter VPI and VCI values you found from autoconfiguration. Then, select "Bridging" and encapsulation type "VC MUX". Select "None" at "WAN IP Settings" page. Leave LAN configuration intact (you will need it to access router's WebUI) and connect it to 1ENET.

PPPoA configuration is described here. However, as one noted, it is somewhat incomplete -- I can not enter it in my router... Still trying.

UPDATE. Seems to be impossible to terminate PPPoA over 1ENET on my Cisco. Instead, using Extended IP mode, and DHCP configuration on Cisco side, made it work.

UPDATE2. Remove all port mappings and virtual servers before activating Extended IP mode. I have some problems with VoIP, which could be consequence of not doing it.

2009.05.22 - If the script is running from console...

It's probably good idea to output some more diagnostic messages if the script is running from console instead of, say, cron job. To check if it is running from console, one could use somethig like

     if [ "`ps -o tty -p $$ | tail +2`" != "?" ] ; then
       ...

At least Linux- and Solaris-compatible.

2009.05.19 - Remove replication completely

Doing BAU, came across necessity to remove advanced replication (non-Streams) from the 10g database completely. Found this manual to be so good, that I even made a local copy. By the way, it does not just tell how to remove replication, it's full-featured example how to set up, manage and finally delete replication.

2009.05.14 - Oracle 8i, Windows 2000, logon as sysdba

No comments.

     SQLNET.AUTHENTICATION_SERVICES = (NONE)
     Windows 2000
     Logged on with domain account


     C:\>sqlplus "/ as sysdba"

     SQL*Plus: Release 8.1.7.0.0 - Production on Thu May 14 07:44:12 2009
     (c) Copyright 2000 Oracle Corporation.  All rights reserved.

     ERROR: ORA-12560: TNS:protocol adapter error

     Enter user-name:


     C:\>sqlplus "sys@dbname as sysdba"

     SQL*Plus: Release 8.1.7.0.0 - Production on Thu May 14 07:46:59 2009
     (c) Copyright 2000 Oracle Corporation.  All rights reserved.

     Enter password:
     ERROR: ORA-28009: connection to sys should be as sysdba or sysoper


     C:\>sqlplus /nolog

     SQL*Plus: Release 8.1.7.0.0 - Production on Thu May 14 07:48:30 2009

     (c) Copyright 2000 Oracle Corporation.  All rights reserved.

     SQL> connect sys@dbname as sysdba
     Enter password:
     ERROR: ORA-28009: connection to sys should be as sysdba or sysoper


     C:\>sqlplus "sys/password@dbname as sysdba"

     SQL*Plus: Release 8.1.7.0.0 - Production on Thu May 14 07:48:57 2009
     (c) Copyright 2000 Oracle Corporation.  All rights reserved.

     Connected to:
     Oracle8i Enterprise Edition Release 8.1.7.0.0 - Production
     JServer Release 8.1.7.0.0 - Production

     SQL>

2009.05.12 - Tuning hme interface on Sun SPARC box

Faced with the same problem as about a year ago — hme interface on Sun Ultra gives 128KByte/sec when connected to Cisco switch. To solve, ideally it is needed to connect the box to non-cisco switch (3Com, D-Link, unnamed $20 one, anything but Cisco) and/or put interface manually to half duplex mode.

The latter can be quite tricky: for hme that supports only 10 Mbit UTP media, one should

     # ndd -set /dev/hme adv_10hdx_cap 1
     # ndd -set /dev/hme adv_10fdx_cap 0
     # ndd -set /dev/hme adv_autoneg_cap 0
Connectivity might stop for a while or even broke permamently so make sure you have access to system console or another, non-hme, interface.

To fix these settings permanently, one should add the following to /etc/system:

     # set hme:hme_adv_10hdx_cap=0
     # set hme:hme_adv_10fdx_cap=1
     # set hme:hme_adv_autoneg_cap=0

Changing network settings per device is a bit different. For example, to set hme1 and only hme1 to forced 100 MBit Full Duplex mode, one should:

     # ndd -set /dev/hme instance 1
     # ndd -set /dev/hme adv_1000fdx_cap 0
     # ndd -set /dev/hme adv_1000hdx_cap 0
     # ndd -set /dev/hme adv_100fdx_cap 1
     # ndd -set /dev/hme adv_100hdx_cap 0
     # ndd -set /dev/hme adv_10fdx_cap 0
     # ndd -set /dev/hme adv_10hdx_cap 0
     # ndd -set /dev/hme adv_autoneg_cap 0

To get current mode:

     # ndd -get /dev/hme link_speed
       (0=10mbps 1=100mbps 1000=1gbps)
     # ndd -get /dev/hme link_mode
       (0=Half Duplex 1=Full Duplex)
     # ndd -get /dev/hme link_speed link_mode
       (all at once)
One more useful command:
     # ndd /dev/hme \?

Surprisingly, for ce and bge interfaces configuration is a bit different. Older drivers might fail to ndd -get speed and link mode, so you'll have to use netstat or kstat. Also, I am not really sure if /etc/system parameters will work for these interface types.

2009.05.12 - Checking recovery model in MSSQL 2000

Googling for "check recovery model server 2000" basically tells you about point-and-click administration, which is inapplicable should you ever have more than 100 databases on the same box.

In 2000, one could use following script:

     SELECT name, databasepropertyex(name, 'Recovery') recovery_model_desc FROM master..sysdatabases
In 2005, there is a dedicated field in sys.databases view:
     SELECT name, recovery_model_desc FROM master.sys.databases

2009.05.12 - ORA-07445[LXMCPEN] + ORA-00600[729]

Came across this one, Oracle 9.0 on SPARC Solaris.

Described in 338322.1 and 330864.1 and believed to be an effect of Bug 4451759. Happens during session cleanup, and when database links and session_cashed_cursors are used. The latter one, ORA-600 [729], naturally, is a diagnostic message saying that there was a space leak in UGA of a given amount of bytes. In a following example, 1600 bytes were leaked:

     ORA-00600: internal error code, arguments: [729], [1600], [space leak], [], [], [], [], []

To fix:

  • 9.2.0.6/7 + patch
  • 9.2.0.8
  • ALTER SYSTEM SET session_cached_cursors=0
  • Suppress ORA-600 [729] message for leaks up to X bytes using
    ALTER SYSTEM SET EVENTS '10262 trace name context forever, level X'

2009.05.07 - Migrating Oracle from 32-bit to 64-bit

I've made migration from Oracle 32-bit to Oracle 64-bit on SPARC Solaris once. As adviced by technical support, we migrated the database through exp/imp, because we've been told it is the only way to do this.

That wasn't completely right. According to 62290.1 "Changing between 32-bit and 64-bit Word Sizes", which is merely a bunch of extracts from Oracle9i Database Migration guide with some additions, it is possible to convert from 32-bit to 64-bit on any platform avoiding exp/imp for 8.0.x and up.

Never trust to sales representative, politician or technical support.

2009.05.07 - dbora, rc3.d

According to Release Notes for Oracle 10gR2 (this is for SPARC64, but it does not really matter — this is just the latest released one), the correct symbolic links for automated startup/shutdown are:

     AIX        # ln -s /etc/dbora /etc/rc.d/rc2.d/S99dbora
                # ln -s /etc/dbora /etc/rc.d/rc0.d/K01dbora

     HP-UX      # ln -s /sbin/init.d/dbora /sbin/rc3.d/S990dbora
                # ln -s /sbin/init.d/dbora /sbin/rc0.d/K001dbora

     Linux      # ln -s /etc/init.d/dbora /etc/rc.d/rc0.d/K01dbora
                # ln -s /etc/init.d/dbora /etc/rc.d/rc3.d/S99dbora
                # ln -s /etc/init.d/dbora /etc/rc.d/rc5.d/S99dbora

     Solaris    # ln -s /etc/init.d/dbora /etc/rc0.d/K01dbora
                # ln -s /etc/init.d/dbora /etc/rc3.d/S99dbora

     Tru64 UNIX # ln -s /sbin/init.d/dbora /sbin/rc3.d/S99dbora
                # ln -s /sbin/init.d/dbora /sbin/rc3.d/K01dbora

The same document says that Chaper 2, "Stopping and Starting Oracle Software" of Oracle Database Administrator's Reference for UNIX-Based Operating Systems gives you wrong list of symbolic links to be created.

2009.05.05 - QMail and its checks

I always use QMail + All In One patch for production mail servers and relays. However, I do question some particulars of its implementation. One of concerns are various checks that are done during SMTP conversation. At this time I am especially concerned about when to report a check outcome.

Check When reported Reason
Validity of source address After DATA To avoid loop checks triggered by smtp callback sender address validation. To allow proper logging of failed mail attempts — it is necessary to know at least sender and recipient email addresses.
Validity of destination address Immediately — after RCPT TO To allow smtp callback sender address validation to function properly. It checks for validity of a sender address by a result of RCPT TO.
"Not our message" After DATA To allow smtp callback sender address validation to function properly. SMTP callback from remote server often comes from >>, e. g. empty, address, so we need to allow an SMTP callbacker to issue RCPT TO and check for its result before we bounce it with "Not our message".

PS. Finally incorporated this changes to my QMail installation.

2009.04.30 - Cisco 7960, Asterisk

I finally made Cisco 7960G ip phone work with my Asterisk server and the rest VoIP network. The process itself wasn't that difficult, although i spent extra 3 hours just because one of the firewalls between Asterisk/ATA and Cisco 7960G didn't function properly (told to NAT certain port range for RTP traffic but silently dropping that packets).

The good news is that, compared to SJphone softphone i used before, C7960G has much better sound quality and link reliability.

The bad news is that C7960G SIP IOS apparently hasn't got any support of direct SIP dialling — that is, without any SIP proxies and PBXes, just point-to-point. Perhaps, it's possible with use of a dialplan, but i couldn't figure out which way.

Basically, tuning broke down into the following steps:

  • Obtain proper TFTP and DHCP servers and install.
  • Obtain and carefully place support files like SIP IOS, OS79xx.txt, site and phone configuration files, ringtones and ringtone index.
  • Switching off DHCP usage on the phone to speed up boot.
  • Switch off firewall on the box where TFTP/DHCP server is installed to allow traffic traversal.
  • Upgrade IOS.
  • Tweak configuration file: registration username/password, SIP proxy address and port number, RTP port range and control port, NAT settings.
  • Reconfigure Asterisk to add a new user and extension, and some options for NAT support that weren't necessary for SJPhone.
  • Tune firewall to allow traffic traversal for RTP and signalling.
  • Remove OS79xx.txt from TFTP directory to prevent the phone from constant upgrading of its IOS.

2009.04.30 - ORA-12638 Credential retrieval failed

"ORA-16384 Credential retrieval failed" happening on client machine running XP when connecting to Oracle XE running on, yes, another XP. Oracle forums suggested changing SQLNET.AUTHENTICATION_SERVICES to NONE (usually set to NTS and moreover, in this particular case it's me who set it to NTS to allow local SYSDBA login).

The cause of the problem, perhaps, was connected with domain authentication. This machine was a part of a domain, but it has desyncronized time — it was done intentionally to get the application "back in time". As NTS authentication is basically Windows authentication, it has something to do with windows domain, if a machine was a part of a domain. It was impossible to authenticate properly due to Kerberos tokens dependent on proper time. Frankly, i don't understant what the problem really is.

2009.04.30 - fuser for win32 (fuser.exe ;-)

Handle by Mark Russinovich will do.

They also point that Process Explorer does the same thing, but it is not clear to me how could one use Process Explorer to find out which process(es) lock(s) a file given.

2009.04.28 - Security freaks

Распространенная практика, когда на рабочие хосты ставят самый минимум софта, в частности, чтобы не создавать лишних дырок. Но вот это меня убило:

     [root@vm2 bin]# patch < dbstart_dbshut_standby_fix_10204.patch 
     -bash: patch: command not found

2009.04.27 - RMAN backup paradigm

Выбираемая политика бэкапа связана прежде всего с идеологией, регилией и другими высокими материями. Очень трудно делать выводы, которые были бы однозначно правильными.

10g. Primary и Standby DB, последняя использует Data Guard Managed Recovery в режиме Maximum Performance. На primary db имеем также RMAN, который регулярно делает резервные копии архивных логов и удаляет последние с диска.
Хотим, чтобы при недоступности standby db основная работала, и логи сохранялись до момента, когда standby станет доступным и заберет их, поэтому archive log destination, указывающий на standby, объявлен как OPTIONAL.
Хотим не размножать логи, чтобы не потреблять место и не плодить I/O, поэтому имеем только один Archive Log Destination, который MANDATORY и кладет логи на диск.

Проблема 1: выяснилось, что не примененные на standby логи не служат основанием для того, чтобы RMAN оставил логи на диске в primary db.

Решения:

  • объявить destination, который указывает на standby db, в качестве mandatory. При этом надо понимать, что недоступность standby db приведет к блокированию primary db, когда все группы online redo будут почемены как unarchived.
  • делаем 2 mandatory archive log destination. В один кладем логи для RMAN'а (и соответственно бэкапим/удаляем с предикатом LIKE ...), во второй — для передачи на standby. Не совсем понятно, как из второго чистить уже переданные логи.
  • при удалении логов вычислять на standby db номер последнего примененного лога примерно так:
             SELECT MAX(sequence#) FROM v$archived_log WHERE APPLIED = 'YES';
    и после этого использовать для бэкапа и очистки логов на primary db следующий скрипт:
             BACKUP DEVICE TYPE DISK ARCHIVELOG ALL NOT BACKED UP;
             DELETE NOPROMPT ARCHIVELOG
               UNTIL SEQUENCE <что получили из SQL выше>
               BACKED UP 1 TIMES TO DEVICE TYPE <куда бэкапим>;
    Усложняет процедуру бэкапа. Необходимо либо иметь пароль к SYS, закодированный plaintext'ом в скрипте бэкапа, либо ssh/rsh-линк с primary db на standby db.
  • при наличии внешнего мониторинга standby db и определенного количества свободного места на primary db можно использовать следующий скрипт:
             BACKUP DEVICE TYPE DISK ARCHIVELOG ALL NOT BACKED UP;
             DELETE NOPROMPT ARCHIVELOG TIME 'SYSDATE - 7';
    Неспортивно. Потенциальная опасность удалить непримененные лог, зависимость от системы мониторинга.
  • использовать на primary db следующую опцию RMAN'а: CONFIGURE ARCHIVELOG DELETION POLICY TO APPLIED ON STANDBY.
    Само по себе это не решит проблему, т. к. для удаления все равно достаточно, чтобы лог был передан на все mandatory standby destinations, а использование MANDATORY приведет к вероятности блокировки primary db после заполнения всех групп redo при недоступности standby db. Кроме того, использование политики APPLIED приведет к RMAN-8591, если ни одного mandatory standby destination не определено (см. Metalink Bug 5261960).
    Решение изложено в Metalink Article 728053.1 и 331924.1:
    • На primary и standby поставить _log_deletion_policy=ALL и перегрузить базу (нужно только в 10g, в 11 и далее все нормально).
    • На primary и standby в RMAN поставить
      CONFIGURE ARCHIVELOG DELETION POLICY TO APPLIED ON STANDBY;
    • Чистить логи на primary:
      DELETE NOPROMPT OBSOLETE ARCHIVELOG BACKED UP 1 TIMES TO DISK;
      ... и standby:
      DELETE NOPROMPT OBSOLETE ARCHIVELOG;

Проблема 2: надо чистить логи, переданные на standby и примененные там.

Решения:

  • использовать на standby db следующую опцию RMAN'а: CONFIGURE ARCHIVELOG DELETION POLICY TO APPLIED ON STANDBY. В качестве пререквизита должно быть использование Flash recovery area для хранения логов на standby db. В соответствии с документацией, "When the APPLIED ON STANDBY clause is configured on... <skipped> a standby database that has no mandatory cascading standby databases... <skipped> Then, these files are eligible for deletion... <skipped> Archived redo log files in the flash recovery area that were applied on the standby database." Надо бы потестировать.
  • Использовать опцию _log_deletion_policy=ALL (см. выше).

Более подробно про очистку логов с помощью политик, включая ситуацию с автоматической очисткой логов, если они помещены в Flash Recovery Area (описано в 464668). По понятиям RMAN'а, чтобы лог можно было почистить, после него должен быть какой-то бэкап (level 0, либо level > 0 с предыдущими бэкапами вплоть до level 0). Другими словами, чтобы можно было автоматически убивать примененные логи на standby db любым встроенным в Oracle способом, там должен время от времени запускаться бэкап базы. Логи будут удаляться только после того, как они будут "закрыты" более поздним бэкапом базы.

Если на standby места завались — отлично, но я считаю, что бессмысленно хранить на standby уже примененные логи. Мне не удалось добиться того, чтобы RMAN считал примененные логи ненужными без периодического бэкапа базы. Даже бэкап самих логов не делает исходные файлы логов OBSOLETE — следовательно, RMAN не будет их безопасно автоматически удалять (DELETE NOPROMPT OBSOLETE).

PS. Oracle ответил, что автоматически удалять логи сразу после наката на physical standby невозможно. Полезная, однако, штука Data Guard.

2009.04.16: Oracle Upgrade vs Auditing

Может, в мануале это и написано, но кто же их читает... В общем, перед апгрейдом Oracle крайне рекомендуется временно отрубить аудит, и сделать TRUNCATE на SYS.AUD$. Добрые люди подсказали.

2009.04.15: SQL Server 2005 — There was an unexpected failure during the setup wizard

Если вы видите при установке Microsoft SQL Server 2005 вот такую штуку...

     There was an unexpected failure during the setup wizard.
     You may review the setup logs and/or click the help button for more information.
... то первым делом проверьте, как вы назвали директории на жестком диске, куда скопированы образы дистрибутивных CD (если они у вас, конечно, были).

Правильная структура такая: некая директория, в ней поддиректории Servers и Tools, в которые скопированы первый и второй диски дистрибутива соответственно. Более подробно см. KB 916760: Error message when you install SQL Server 2005: "There was an unexpected failure during the setup wizard".

2009.04.14: Oracle Listener memory leak + performance degradation 9iR2-10gR1

Очень долго боролись c listener'ом на 9.2.0.8. На нескольких базах, где очень большое количество подключений-отключений, через некоторое время начинается шоу: listener начинает принимать подключения с задержкой, сначала по полсекунды, потом, по секунде, потом до нескольких секунд... Как только не лечили:

  • перегружали listener. Помогало, конечно, но автоматически я это был делать не готов, ибо боязно;
  • делили нагрузку разных баз между listener'ами. Смысл в том, что на хостах жили по нескольку баз, и изначально они обслуживались разными listener'ами, в результате проблемы возникали одновременно у всех. Разделение помогло увеличить время между проблемами, плюс страдала только одна база одновременно... в общем, фундаментально проблему так и не решили;
  • уменьшали, насколько можно, количество подключений от приложений — помогало, но session pooling у приложений был построен так дебильно, что в результате получали другую проблему — кучу сессий в базе, которые ничего не делали;
  • использовали prespawning, который, к слову, не поддерживается официально уже в 8i (говорят, используйте OPS, он же Shared Server). Надо сказать, проблему решить удалось... время, которое база работала нормально, увеличилось в пару раз.

Oracle признал проблему в двух Metalink-овских статьях: Bug 5576565 - Small listener memory leak per connection (Doc ID 5576565.8, 03-APR-2009) и Listener Leaking Memory And High CPU Utilization on Oracle 9.2.0.8 (Doc ID 557397.1, 09-JUN-2008).
В 5576565.8 говорится, что на всех платформах Oracle 9.2.0.8 ... 10.0.1.2 имеет небольшой memory leak в listener'е, проявляющийся при установке новых соединений. Oracle рекомендует применить 9.2.0.8 для Windows, где эта проблема решена, а на остальных платформах — периодически перестартовывать listener, либо см. ниже.
557397.1 добавляет, что кроме собственно memory leak возможны еще проблемы с производительностью, в частности, задержки и high CPU utilization. Там же есть патчи практически для всех распространенных UNIX-платформ. Что не может не радовать.

2009.04.14: Oracle Advanced Replication and triggers

Репликация — исключительно прозрачная для приложения штука. Это распространенное заблуждение. Предположим, имеем мы, скажем, табличку, в которой primary key заполняется с помощью триггера из последовательности. И включаем мы эту табличку в репликацию. Репликация сама по себе триггеры не обрабатывает, а потому получается, как минимум, что в разных базах имеем разные primary key... А как максимум — имеем конфликты репликации, если приложение использует для вставки записей логику INSERT, UPDATE.

Решение — использовать в начале каждого триггера код вида

     IF dbms_reputil.from_remote = true THEN
       return;
     END IF;
from_remote — надо сказать, несколько дезориентирует, т. к. эта штука бывает TRUE не только когда DML порожден из удаленной базы, а вообще когда DML порожден пакетами репликации.

2009.04.13: QMail Newr Pack ver. 0.1

Зае Устал ставить QMail вручную, сверху накатывать туеву хучу патчей, потом доводить напильником. Сделал некий набор дистрибутивов плюс скриптик, который все это счастье ставит сам. Этакий QMail 1.03 + UCSPI-TCP 0.88 + DaemonTools 0.76 + QMail AIO Patch rel. 16 + RBLSPP + QMail SPP 0.3 + ClamAV 0.95.1 + самописные скрипты.

Известные проблемы:

  1. RBLSPP в настоящее время не имеет ключика, устанавливающего тайм-аут на запрос к RBL. Надо дописывать.
  2. Было бы неплохо добавить поддержку SPF.
  3. ... и черно-серо-белых листов.

Убил примерно неделю на то, чтобы все это собрать и отладить, но довелен, как слон. Все-таки лень — великая сила.

2009.04.12: exp 8i fails with "ORA-00904: invalid column name" when no JVM loaded

Я, конечно, не знаю, у кого как, а вот у меня exp в 8.1.7.4 не работает в базе, где нет JVM. Экспорт хочет сделать

     SELECT SYNNAM, DBMS_JAVA.LONGNAME(SYNNAM), DBMS_JAVA.LONGNAME(SYNTAB),
       TABOWN, TABNODE, PUBLIC$, SYNOWN, SYNOWNID
     FROM SYS.EXU8SYN 
     WHERE SYNOWNID=:1 ORDER BY SYNTIME
а нету его, DBMS_JAVA.

Пришлось делать @?/javavm/install/initjvm.sql по наводке добрых людей.

2009.03.21: OpenLDAP + FreeBSD 6.4

Ставим openldap на FreeBSD 6.4. Разбираем грабли:

  • Не качаем свежий BerkeleyDB 4.7. Качаем старый как мир 4.5 с сайта Oracle.

2009.03.06: Oracle 10g security tips

Занимался секьюритью. Накопал ряд интересных моментов.

  • Начиная с Oracle 10gR2, профиль DEFAULT блокирует пользователя БД после 10 неудачных попыток входа.
  • Пользователя SYSTEM можно безопасно заблокировать в БД.
  • Полностью пользователя SYS заблокировать нельзя, т. к. даже под заблокированной учеткой SYS можно войти локально.
  • Чтобы заблокировать возможность удаленного входа под SYS, достаточно установить параметр REMOTE_LOGIN_PASSWORDFILE в значение NONE. Кстати, в 10g возможные значения этого параметра — NONE (т. е. для SYSOPER/SYSDBA возможно зайти только локально) и SHARED (т. е. файл паролей используется и там могут быть любые пользователи, которым назначены SYSOPER/SYSDBA, а не только SYS). Дефолтный EXCLUSIVE в 10g поддерживается для обратной совместимости и означает то же самое, что и SHARED.
  • Ну и, вообще-то, неплохо было бы иметь REMOTE_OS_AUTHENT=FALSE.

Что касается безопасности — наиболее разумным представляется план, когда

  • пользователи-люди имеют вменяемую политику блокирования и смены паролей;
  • пользователи-приложения и пользователи-бизнес-процессы не имеют политики блокирования, однако включен аудит неуспешных попыток входа и при возникновении более разумного количества неуспешных попыток в единицу времени — этим занимается администратор БД;
  • профиль DEFAULT не используется и имеет очень жесткую политику блокирования пользователей (типа дефолтной);
  • Аудит включен, логируются только неуспешные попытки входа (т. к. если будут проблемы с вставкой в таблицу AUD$ и будет включен аудит всех попыток входа, и успешных и неуспешных, то невозможность вставить запись в таблицу AUD$ приведет к тому, что даже легитимные попытки входа будут пресекаться).

2009.03.04: Oracle 9i + Linux x86_64 = RHEL5 sucks, RHEL 4 rocks

Ставил Oracle 9i на Linux x86_64. На Oracle Unbreakable Linux (по сути, RHEL). После танцев с бубном в течение 2 дней выяснилось, что на Release 5 update 3 оно не ставится в принципе, т. к. нужно даунгрейдить пакет, содержащий libc.so -- следовательно, даунгрейдить всю систему. Были также другие грабли в виде несуществующего пакета libXp.so. Где его брать, я не понял, поэтому подсунул из RHAS3. Началась же вся история с зависания инсталляции на 17%, что является известным косяком (только возможны разные причины — соответственно, решается тоже по-разному).

На Release 4 update 7 встало за исключением следующих моментов:

  • Не нашел пары пакетов, указанных в мануале Пушица для RHEL4. Поставил какие-то, подходящие по названию. Пару пакетов пришлось поставить с --nodeps, т. е. они зависели друг от друга. kernel-headers в дистрибутиве не нашел, поставил вместо него glibc-kernheaders, хотя это, скорее всего, можно было и не делать -- зависимости это все равно не удовлетворило, и зависящие от kernel-headers пакеты пришлось ставить с --nodeps. Такая же фигня с одним из XFree86-*.
  • libgcc_s_32.so: undefined reference to `dl_iterate_phdr@GLIBC_2.2.4'
    Лечим (взято здесь и здесь):
    su -
    # cd /usr/bin
    # mv ./gcc ./gcc296
    # mv ./gcc3 ./gcc

2009.03.03

Предыстория: Windows 2000, входим под доменным пользователем, включенным в группу ORA_DBA. Имеем правильно установленные переменные окружения ORACLE_HOME и ORACLE_SID. Oracle 8.1.7.4. Включены NTS.

     C:\Documents and Settings\domainuser>sqlplus "/ as sysdba"

     SQL*Plus: Release 8.1.7.0.0 - Production on Tue Mar 3 08:53:39 2009

     (c) Copyright 2000 Oracle Corporation.  All rights reserved.

     ERROR:
     ORA-12560: TNS:protocol adapter error

     Enter user-name:
Для контраста:
     C:\Documents and Settings\domainuser>sqlplus "/@database as sysdba"

     SQL*Plus: Release 8.1.7.0.0 - Production on Tue Mar 3 08:55:37 2009

     (c) Copyright 2000 Oracle Corporation.  All rights reserved.

     Connected to:
     Oracle8i Enterprise Edition Release 8.1.7.4.1 - Production
     JServer Release 8.1.7.4.1 - Production

     SQL>

2009.03.02

Йо майо. Оказывается, расположение временной директории в UNIX/Linux задается переменной TMPDIR, а вот если ее нет, тогда имеем /tmp. Интересно, а кроме админов, в курсе ли остальные... Ну там, программисты, например...

2009.02.18: Path MTU Discovery Black Hole, RFC 2923

Только что споткнулся вот об эти грабли:
http://www.opennet.ru/base/net/pppoe_mtu.txt.html

Если вкратце: выделенка на PPPoE глючит, соединения рвутся, иногда не устанавливаются. Проблема специфична для хостов или отдельных http-страниц. Ping (icmp) проблем не показывает. С самого гейта глюков нет, только с сети, находящейся за ним.

Вот решение:
http://www.cisco.com/en/US/docs/ios/12_2t/12_2t4/feature/guide/ft_admss.html

     interface Dialer1
      ...
      ip tcp mtu 1492
      ip tcp adjust-mss 1452

Рекомендуют еще ip policy route-map clear-df, но я не пробовал. И так работает.

2009.02.12

Didn't ever realize that utl_file_dir may contain a list of directories, like that:

     SQL> show parameter utl
     NAME                                TYPE    VALUE
     ----------------------------------- ------- ------------------------------
     utl_file_dir                        string  /var/dir1, /tmp/dir2, ...

2009.01.07

Toad sucks. "Tablespaces" tab is visible only if DBA extensions are installed... I'm curious if those require an additional licence and, hence, additional money (update: apparently, it is).

In some version of Oracle, possibly 10gR2, there was a change in DBMS_STATS package. In ancient times statid could be anything DBA wanted, since it is only a value to be copied into a stat table. Now statid must be an identifier, otherwise it spits out an error message.

2009.01.07

Getting TCP keepalive setting in Solaris:

     /usr/sbin/ndd -get /dev/tcp tcp_keepalive_interval
Setting TCP keepalive period:
     /usr/sbin/ndd -set /dev/tcp tcp_keepalive_interval 900000

The argument and value returned are in milliseconds.

Also got some useful tips on tuning Solaris from here.

2008.11.25

Самый быстрый способ выяснить, какие оракловые базы запущены на UNIX-хосте:

     ps -ef | grep pmon
В общем, сложно не согласиться.

2008.10.24

Есть такой оператор связи, Orange Niger. Звучит замечательно, но несколько неполиткорректно.

2008.09.26

Прочитал 10g Administration Workshop I и Introducing SQL в Академии ИТ. После прочтения Workshop'а осталось крайне негативное впечатление, по сравнению с DBA Fundamentals I для 8i и 9i. Злобные разработчики заменили действительно фундаментальный и полезный курс, включающий реальные знания, на курс вида "запустите Enterprise Manager и щелкните мышкой туда-то"... Было противно. Не удержался, нафаршировал в лекции много из того, что в учебнике предпочли опустить.

Что касается Introducing SQL — очень хороший курс, можно читать без подготовки. Фактически, как в отпуск на неделю сходил.

2008.08.19

Собрался сдавать экзамен на SCSA. Прихожу, значить, в Прометрик местный, говорю так и так... (Сколько сдавал экзамены в Оракл - всегда так делал, просто приходил и сдавал.)

В общем оказывается, что нельзя сдать экзамен вот так просто. Говорят, нужен ваучер, который нужно покупать у Sun. Хорошая сторона - экзамен по такому ваучеру стоит US$200, а не US$300. Плохая - после звонка в Москву выяснилось, что ваучер этот оплачивается банковским переводом (кредиткой нельзя, ё маё, мы в каком веке живем?) То есть необходимо еще ждать, пока деньги дойдут, и пока они там вручную все обработают. В общем, дело-то хорошее только есть у меня предчувствия. Смутные.

Наверное, это просто. Утром сегодня прихожу в банк. В ВТБ24, простояв в очереди примерно минут 30, узнаю, что нужно заполнить заявление. Заполняю. Пока заполняю, 2 из 3 окошек закрывается на обед, в оставшиеся собирается очередь. Таких же как я, которые что-то заполняли. Стою минут 30, после этого мне надоедает, шлю всех на### вежливо объясняю, что ценю свое время и валю откланиваюсь.

Захожу по дороге во все попадающиеся банки с вопросом, можно ли сделать у них такой перевод.

Другое отделение ВТБ24. На входе в операционный зал объявление, что вот как раз сегодня, 19 августа, они на лопате закрыты по техническим причинам. Упс.

Альфа-банк. "Да, можем" - отвечает с виду неглупая девушка-рецепшионист. "Вам придется открыть у нас счет, положить туда деньги, платить за обслуживание счета ежемесячно". Выяснив, что все это займет полчаса минимум, я вежливо посылаю ее подальше объясняю ей, что в таком объеме услуг не заинтересован, и делаю ручкой. Про себя думаю, что все-таки не "для успешных людей" Альфа-банк, а для терпеливых и богатых.

Промсвязьбанк. Падаю в осадок теряю дар речи, когда милая на вид девушка, явно не старше меня, говорит, что "сейчас все заняты, и мне никто не поможет, неужели я не вижу". А ведь ей еще детей рожать и рожать... И уже все пофиг. Хм. Ухожу в недоумении.

Ройал Кредит Банк. Сидит 3 операциониста и администратор. 2 операциониста сидят и треплются, всех отправляют к третьему. У третьего очередь, там фигней не занимаются - оформляют кредиты. На вопрос про возможность перевода местные начинают узнавать, какой перевод, да зачем, да на какие цели... Отвечаю "на поддержку международного терроризма, епт" "не ваше собачье дело" "за услуги обучения". Парень смотрит недоверчиво, говорит, "подождите, в вашем случае необходимо разобраться". Жду минут 10, сидеть негде, надоедает, поворачиваюсь к двери. 2 свободных операциониста смотрят мне вслед, как на ненормального.

Востокбизнесбанк. Заполняю заявление. Местные с подозрением смотрят на "... (236 долларов по курсу 24.4898, включая НДС 36 долларов)" и заявляют, что могут перевести доллары только через Western Union. После непродолжительного объяснения отправляют меня переписать заявление. Уфф. Всего через 2 часа активных поисков я, таки, экзамен оплатил. Интересно, через сколько бы Sun обанкротилась, если бы буржуи платили за ее услуги таким же образом. Впрочем, я неправ, банки бы, наверное, обанкротились быстрее.

2008.06.16

Говорят, что софт должен давать четкие и понятные диагностические сообщения. Посмотрим, как с этой задачей справляется Oracle.

Errors with log /oracle/.../arch/dbname_t1_123456.log
16 recovery slaves failed cleanup
Some recovered datafiles maybe left media fuzzy
Media recovery may continue but open resetlogs may fail

2008.06.14

Любят все-таки буржуйские агенства по подбору персонала разнообразные questionnaire'сы для заполнения присылать. Вопросы типа «Please list your top 5 technical skills/key strengths» меня всегда ставили в ступор, ну, админ он и в Африке админ, этим и силен. Тем не менее, попытался подойти к вопросу по-творчески. Вот что получилось:

  1. Quick and reliable problem solving (words of my business customers).
  2. Performance tuning and database troubleshooting.
  3. Possibility to think out of the border - means it is sometimes necessary to change business process or introduce a totally new approach rather than try to cope with complex problem in a usual policy-backed way.
  4. Minding about business continuity, ability to distinguish between operations that are possibly dangerous for production lifecycle and those which are not, ability to reduce system downtime as much as possible.
  5. Theoretical background - constant learning, keeping up with progress of the technology.
Дал почитать добрым людям. Вот их интерпретация:
  1. Быстро посылает нах.
  2. Troubleshooting после tuninga, валит все на оракловые баги.
  3. Постоянно требует дополнительно финансирования.
  4. Отказывается что-либо менять в продакшене.
  5. Очень изворотлив, очень сложно прижучить в случае п.п. 2, 3 и 4, а если даже получится, см. пункт 1.
Посмеялись вместе ;-)

2008.06.13

Второй раз наступаем на одни и те же грабли. Безобразие. Итак,

  • если имеем основную и standby базы,
  • если выполняем бэкап основной базы средствами RMAN,
  • если во время этого бэкапа делаем ALTER DATABASE DATAFILE ... RESIZE с уменьшением размера датафайла,
То:
  • во-первых, получаем ошибку ORA-19567: cannot shrink file ... because it is being backed up or copied (но размер все равно меняется),
  • во-вторых, на standby это изменение в логах не передается,
  • в-третьих, на основной базе заголовок файла портится, так что, например, резервное копирование этого файла средствами того же RMAN более невозможно (падает с ORA-19563: datafile header validation failed for file ...).
Уже однажды наступали, очень обидно. 9.2.0.8, sol10sparc64.

2008.06.12

Ужасы нашего городка. Имеем подмонтированную standby базу. Далее:

SQL> SELECT member FROM v$logfile;

MEMBER
--------------------------------------------------------------------------------
/dev/vx/rdsk/.../online_redo01.dbf
/dev/vx/rdsk/.../online_redo02.dbf
/dev/vx/rdsk/.../online_redo03.dbf
Тут же:
SQL> BEGIN
  2    FOR c IN (SELECT member FROM v$logfile) LOOP
  3      NULL;
  4    END LOOP;
  5  END;
  6  /
BEGIN
*
ERROR at line 1:
ORA-01219: database not open: queries allowed on fixed tables/views only
Офигеть, дайте две... 9.2.0.8, sol10sparc64.

2008.04.29

Умудрился с помощью способа, изложенного в ноте 274321.1, удалить некую злобную транзакцию. В результате система стала в забавное состояние: постоянно пытаясь очистить эту транзакцию, оракл в ALERT.LOG сообщал, что ее не существует. Проблема решилась не без помощи техподдержки, за что им отдельный респект (запостить сюда метод не могу).

Кто использует такой же метод со скрытым параметром _smu_debug_mode, крайне не рекомендую удалять что-либо кроме транзакций в состоянии forced rollback, может плохо закончится...

Кстати, вот полезный скрипт для очистки зависших распределенных транзакций. Этот скрипт вроде бы ни разу не приводил к возникновению проблем.

2007.08.09

Ставил Oracle 9.2.0.8 + CPU на SPARC Solaris 10. При установке CPU получили вот такое безобразие:
Verifying patch...
WARNING: Verification of 'ar' actions failed. This is a known issue for this platform. Please check the note 353150.1 on Metalink for the process to manually verify the files.

В ноте выяснилось, что надо взять лог и проверить в нем, на сколько изменились размеры файлов.
For example,
Source file name is : /u01/app/oracle/product/jan/5689875/files/lib/libplp9.a/piht.o, size is : 122728
Destination file name(from OracleHome) is : /u01/app/oracle/product/9.2.0.7/.patch_storage/verify/lib/libplp9.a/piht.o, size is : 122732

Если, грят, разница состаляет ровно 4 байта, то все OK.

Интересно, а автоматизировать эту проверку они не могли? Потратил полчаса, но налабал скрипт, ибо накатывать 17 патчей с такими вот ручными проверками на 2 машины совершенно не улыбалось.

2007.08.05

Бодался на sql.ru по поводу потери текущей Redo группы. Появилась интересная идея про возможность «положить» базу так, что после этого не нужно делать incomplete recovery и восстанавливаться из бэкапа, но то ли я чего-то не понимаю, то ли у айтишников напрочь отсутствует воображение.

2007.08.03

В очередной раз столкнулись с глюками при отображении планов в 9iR2. Правильное место, чтобы план смотреть -- трейс либо errorstack. V$SQLPLAN тоже порой рисует погоду, уж не говоря про explain plan.

2007.02.04

Все-таки Veritas NetBackup -- концептуально продуманная вещь. Я, наверное, минут 20 выяснял, как через его GUI-морду, которая jnbSA, изменить e-mail админстратора, так и не нашел. Из командной строки, однако же, это делается просто: /usr/openv/netbackup/bin/admincmd/bpconfig -ma <новый@адрес>. Все-таки есть в этом что-то правильное.

Follow-up: добрые люди подсказали, что

To set this option via the Java GUI:
1. Go to Host Properties | Master Servers in the GUI
2. Select the master server and double-click on it until the Properties window opens
3. Go to the Global Attributes section
4. Under Administrator e-mail address enter the email address to use
... за что им огромное спасибо.