Coverage Report

Created: 2026-08-22 06:42

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/netcdf-c/libnczarr/zsync.c
Line
Count
Source
1
/*********************************************************************
2
 *   Copyright 1993, UCAR/Unidata
3
 *   See netcdf/COPYRIGHT file for copying and redistribution conditions.
4
 *********************************************************************/
5
6
#include "zincludes.h"
7
#include "zfilter.h"
8
#include <stddef.h>
9
#include "ncutil.h"
10
11
#ifndef nulldup
12
#define nulldup(x) ((x)?strdup(x):(x))
13
#endif
14
15
#undef FILLONCLOSE
16
17
/*mnemonics*/
18
#define DICTOPEN '{'
19
#define DICTCLOSE '}'
20
21
/* Forward */
22
static int ncz_collect_dims(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, NCjson** jdimsp);
23
static int ncz_sync_var(NC_FILE_INFO_T* file, NC_VAR_INFO_T* var, int isclose);
24
25
static int download_jatts(NC_FILE_INFO_T* file, NC_OBJ* container, const NCjson** jattsp, const NCjson** jtypesp);
26
static int zconvert(const NCjson* src, nc_type typeid, size_t typelen, int* countp, NCbytes* dst);
27
static int computeattrinfo(const char* name, const NCjson* jtypes, nc_type typehint, int purezarr, NCjson* values,
28
    nc_type* typeidp, size_t* typelenp, size_t* lenp, void** datap);
29
static int parse_group_content(const NCjson* jcontent, NClist* dimdefs, NClist* varnames, NClist* subgrps);
30
static int parse_group_content_pure(NCZ_FILE_INFO_T*  zinfo, NC_GRP_INFO_T* grp, NClist* varnames, NClist* subgrps);
31
static int define_grp(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp);
32
static int define_dims(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, NClist* diminfo);
33
static int define_vars(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, NClist* varnames);
34
static int define_var1(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, const char* varname);
35
static int define_subgrps(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, NClist* subgrpnames);
36
static int searchvars(NCZ_FILE_INFO_T*, NC_GRP_INFO_T*, NClist*);
37
static int searchsubgrps(NCZ_FILE_INFO_T*, NC_GRP_INFO_T*, NClist*);
38
static int locategroup(NC_FILE_INFO_T* file, size_t nsegs, NClist* segments, NC_GRP_INFO_T** grpp);
39
static int createdim(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, const char* name, size64_t dimlen, NC_DIM_INFO_T** dimp);
40
static int parsedimrefs(NC_FILE_INFO_T*, NClist* dimnames,  size64_t* shape, NC_DIM_INFO_T** dims, int create);
41
static int decodeints(const NCjson* jshape, size64_t* shapes);
42
static int computeattrdata(nc_type typehint, nc_type* typeidp, const NCjson* values, size_t* typelenp, size_t* lenp, void** datap);
43
static int computedimrefs(NC_FILE_INFO_T* file, NC_VAR_INFO_T* var, int purezarr, int xarray, int ndims, NClist* dimnames, size64_t* shapes, NC_DIM_INFO_T** dims);
44
static int json_convention_read(const NCjson* jdict, NCjson** jtextp);
45
static int ncz_validate(NC_FILE_INFO_T* file);
46
static int insert_attr(NCjson* jatts, NCjson* jtypes, const char* aname, NCjson* javalue, const char* atype);
47
static int insert_nczarr_attr(NCjson* jatts, NCjson* jtypes);
48
static int upload_attrs(NC_FILE_INFO_T* file, NC_OBJ* container, NCjson* jatts);
49
static int getnczarrkey(NC_OBJ* container, const char* name, const NCjson** jncxxxp);
50
static int downloadzarrobj(NC_FILE_INFO_T*, struct ZARROBJ* zobj, const char* fullpath, const char* objname);
51
static int dictgetalt(const NCjson* jdict, const char* name, const char* alt, const NCjson** jvaluep);
52
53
/**************************************************/
54
/**************************************************/
55
/* Synchronize functions to make map and memory
56
be consistent. There are two sets of functions,
57
1) _sync_ - push memory to map (optionally create target)
58
2) _read_ - pull map data into memory
59
These functions are generally non-recursive. It is assumed
60
that the recursion occurs in the caller's code.
61
*/
62
63
/**
64
 * @internal Synchronize file metadata from memory to map.
65
 *
66
 * @param file Pointer to file info struct.
67
 *
68
 * @return ::NC_NOERR No error.
69
 * @author Dennis Heimbigner
70
 */
71
int
72
ncz_sync_file(NC_FILE_INFO_T* file, int isclose)
73
0
{
74
0
    int stat = NC_NOERR;
75
0
    NCjson* json = NULL;
76
77
0
    NC_UNUSED(isclose);
78
79
0
    LOG((3, "%s: file: %s", __func__, file->controller->path));
80
0
    ZTRACE(3,"file=%s isclose=%d",file->controller->path,isclose);
81
82
    /* Write out root group recursively */
83
0
    if((stat = ncz_sync_grp(file, file->root_grp, isclose)))
84
0
        goto done;
85
86
0
    stat = NCZMD_consolidate((NCZ_FILE_INFO_T*)file->format_file_info);
87
0
done:
88
0
    NCJreclaim(json);
89
0
    return ZUNTRACE(stat);
90
0
}
91
92
/**
93
 * @internal Synchronize dimension data from memory to map.
94
 *
95
 * @param grp Pointer to grp struct containing the dims.
96
 *
97
 * @return ::NC_NOERR No error.
98
 * @author Dennis Heimbigner
99
 */
100
static int
101
ncz_collect_dims(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, NCjson** jdimsp)
102
0
{
103
0
    int stat=NC_NOERR;
104
0
    size_t i;
105
0
    NCjson* jdims = NULL;
106
0
    NCjson* jdimsize = NULL;
107
0
    NCjson* jdimargs = NULL;
108
109
0
    LOG((3, "%s: ", __func__));
110
0
    ZTRACE(3,"file=%s grp=%s",file->controller->path,grp->hdr.name);
111
112
0
    NCJnew(NCJ_DICT,&jdims);
113
0
    for(i=0; i<ncindexsize(grp->dim); i++) {
114
0
  NC_DIM_INFO_T* dim = (NC_DIM_INFO_T*)ncindexith(grp->dim,i);
115
0
  char slen[128];
116
117
0
        snprintf(slen,sizeof(slen),"%llu",(unsigned long long)dim->len);
118
0
  NCJnewstring(NCJ_INT,slen,&jdimsize);
119
120
  /* If dim is not unlimited, then write in the old format to provide
121
           maximum back compatibility.
122
        */
123
0
  if(dim->unlimited) {
124
0
      NCJnew(NCJ_DICT,&jdimargs);
125
0
      if((stat = NCJaddstring(jdimargs,NCJ_STRING,"size"))<0) {stat = NC_EINVAL; goto done;}
126
0
      if((stat = NCJappend(jdimargs,jdimsize))<0) {stat = NC_EINVAL; goto done;}
127
0
      jdimsize = NULL;
128
0
        if((stat = NCJaddstring(jdimargs,NCJ_STRING,"unlimited"))<0) {stat = NC_EINVAL; goto done;}
129
0
      if((stat = NCJaddstring(jdimargs,NCJ_INT,"1"))<0) {stat = NC_EINVAL; goto done;}
130
0
  } else { /* !dim->unlimited */
131
0
      jdimargs = jdimsize;
132
0
      jdimsize = NULL;
133
0
  }
134
0
  if((stat = NCJaddstring(jdims,NCJ_STRING,dim->hdr.name))<0) {stat = NC_EINVAL; goto done;}
135
0
  if((stat = NCJappend(jdims,jdimargs))<0) {stat = NC_EINVAL; goto done;}
136
0
    }
137
0
    if(jdimsp) {*jdimsp = jdims; jdims = NULL;}
138
0
done:
139
0
    NCJreclaim(jdims);
140
0
    return ZUNTRACE(THROW(stat));
141
0
}
142
143
/**
144
 * @internal Recursively synchronize group from memory to map.
145
 *
146
 * @param file Pointer to file struct
147
 * @param grp Pointer to grp struct
148
 *
149
 * @return ::NC_NOERR No error.
150
 * @author Dennis Heimbigner
151
 */
152
int
153
ncz_sync_grp(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, int isclose)
154
0
{
155
0
    int stat = NC_NOERR;
156
0
    size_t i;
157
0
    NCZ_FILE_INFO_T* zinfo = NULL;
158
0
    char version[1024];
159
0
    int purezarr = 0;
160
0
    NCZMAP* map = NULL;
161
0
    char* key = NULL;
162
0
    NCjson* json = NULL;
163
0
    NCjson* jgroup = NULL;
164
0
    NCjson* jdims = NULL;
165
0
    NCjson* jvars = NULL;
166
0
    NCjson* jsubgrps = NULL;
167
0
    NCjson* jnczgrp = NULL;
168
0
    NCjson* jsuper = NULL;
169
0
    NCjson* jtmp = NULL;
170
0
    NCjson* jatts = NULL;
171
0
    NCjson* jtypes = NULL;
172
173
0
    LOG((3, "%s: dims: %s", __func__, key));
174
0
    ZTRACE(3,"file=%s grp=%s isclose=%d",file->controller->path,grp->hdr.name,isclose);
175
176
0
    zinfo = file->format_file_info;
177
0
    map = zinfo->map;
178
179
0
    purezarr = (zinfo->controls.flags & FLAG_PUREZARR)?1:0;
180
181
    /* build Z2GROUP contents */
182
0
    NCJnew(NCJ_DICT,&jgroup);
183
0
    snprintf(version,sizeof(version),"%d",zinfo->format.zarr);
184
0
    if((stat = NCJaddstring(jgroup,NCJ_STRING,"zarr_format"))<0) {stat = NC_EINVAL; goto done;}
185
0
    if((stat = NCJaddstring(jgroup,NCJ_INT,version))<0) {stat = NC_EINVAL; goto done;}
186
187
    /* Write to map */
188
0
    NCZ_grpkey(grp,&key);
189
0
    if((stat=NCZMD_update_json_group(zinfo,key,(const NCjson*)jgroup))) goto done;
190
0
    nullfree(key); key = NULL;
191
192
0
    if(!purezarr) {
193
0
        if(grp->parent == NULL) { /* Root group */
194
      /* create superblock */
195
0
            snprintf(version,sizeof(version),NCZARR_FORMAT_VERSION_TEMPLATE, zinfo->format.nczarr);
196
0
      NCJnew(NCJ_DICT,&jsuper);
197
0
      if((stat = NCJinsertstring(jsuper,"version",version))<0) {stat = NC_EINVAL; goto done;}
198
0
  }
199
        /* Create dimensions dict */
200
0
        if((stat = ncz_collect_dims(file,grp,&jdims))) goto done;
201
202
        /* Create vars list */
203
0
        NCJnew(NCJ_ARRAY,&jvars);
204
0
        for(i=0; i<ncindexsize(grp->vars); i++) {
205
0
      NC_VAR_INFO_T* var = (NC_VAR_INFO_T*)ncindexith(grp->vars,i);
206
0
      if((stat = NCJaddstring(jvars,NCJ_STRING,var->hdr.name))<0) {stat = NC_EINVAL; goto done;}
207
0
        }
208
209
        /* Create subgroups list */
210
0
        NCJnew(NCJ_ARRAY,&jsubgrps);
211
0
        for(i=0; i<ncindexsize(grp->children); i++) {
212
0
      NC_GRP_INFO_T* g = (NC_GRP_INFO_T*)ncindexith(grp->children,i);
213
0
      if((stat = NCJaddstring(jsubgrps,NCJ_STRING,g->hdr.name))<0) {stat = NC_EINVAL; goto done;}
214
0
        }
215
        /* Create the "_nczarr_group" dict */
216
0
        NCJnew(NCJ_DICT,&jnczgrp);
217
        /* Insert the various dicts and arrays */
218
0
        if((stat = NCJinsert(jnczgrp,"dimensions",jdims))<0) {stat = NC_EINVAL; goto done;}
219
0
        jdims = NULL; /* avoid memory problems */
220
0
        if((stat = NCJinsert(jnczgrp,"arrays",jvars))<0) {stat = NC_EINVAL; goto done;}
221
0
        jvars = NULL; /* avoid memory problems */
222
0
        if((stat = NCJinsert(jnczgrp,"groups",jsubgrps))<0) {stat = NC_EINVAL; goto done;}
223
0
        jsubgrps = NULL; /* avoid memory problems */
224
0
    }
225
226
    /* Build the .zattrs object */
227
0
    assert(grp->att);
228
0
    NCJnew(NCJ_DICT,&jatts);
229
0
    NCJnew(NCJ_DICT,&jtypes);
230
0
    if((stat = ncz_sync_atts(file, (NC_OBJ*)grp, grp->att, jatts, jtypes, isclose))) goto done;
231
232
0
    if(!purezarr && jnczgrp != NULL) {
233
        /* Insert _nczarr_group */
234
0
        if((stat=insert_attr(jatts,jtypes,NCZ_V2_GROUP,jnczgrp,"|J0"))) goto done;
235
0
  jnczgrp = NULL;
236
0
    }
237
238
0
    if(!purezarr && jsuper != NULL) {
239
        /* Insert superblock */
240
0
        if((stat=insert_attr(jatts,jtypes,NCZ_V2_SUPERBLOCK,jsuper,"|J0"))) goto done;
241
0
  jsuper = NULL;
242
0
    }
243
244
    /* As a last mod to jatts, insert the jtypes as an attribute */
245
0
    if(!purezarr && jtypes != NULL) {
246
0
  if((stat = insert_nczarr_attr(jatts,jtypes))) goto done;
247
0
  jtypes = NULL;
248
0
    }
249
250
    /* Write out the .zattrs */
251
0
    nullfree(key);
252
0
    NCZ_grpkey(grp,&key);
253
0
    if((stat = NCZMD_update_json_attrs(zinfo, key, (const NCjson *)jatts))) goto done;
254
255
    /* Now synchronize all the variables */
256
0
    for(i=0; i<ncindexsize(grp->vars); i++) {
257
0
  NC_VAR_INFO_T* var = (NC_VAR_INFO_T*)ncindexith(grp->vars,i);
258
0
  if((stat = ncz_sync_var(file,var,isclose))) goto done;
259
0
    }
260
261
    /* Now recurse to synchronize all the subgrps */
262
0
    for(i=0; i<ncindexsize(grp->children); i++) {
263
0
  NC_GRP_INFO_T* g = (NC_GRP_INFO_T*)ncindexith(grp->children,i);
264
0
  if((stat = ncz_sync_grp(file,g,isclose))) goto done;
265
0
    }
266
267
0
done:
268
0
    NCJreclaim(jtmp);
269
0
    NCJreclaim(jsuper);
270
0
    NCJreclaim(json);
271
0
    NCJreclaim(jgroup);
272
0
    NCJreclaim(jdims);
273
0
    NCJreclaim(jvars);
274
0
    NCJreclaim(jsubgrps);
275
0
    NCJreclaim(jnczgrp);
276
0
    NCJreclaim(jtypes);
277
0
    NCJreclaim(jatts);
278
0
    nullfree(key);
279
0
    return ZUNTRACE(THROW(stat));
280
0
}
281
282
/**
283
 * @internal Synchronize variable meta data from memory to map.
284
 *
285
 * @param file Pointer to file struct
286
 * @param var Pointer to var struct
287
 * @param isclose If this called as part of nc_close() as opposed to nc_enddef().
288
 *
289
 * @return ::NC_NOERR No error.
290
 * @author Dennis Heimbigner
291
 */
292
static int
293
ncz_sync_var_meta(NC_FILE_INFO_T* file, NC_VAR_INFO_T* var, int isclose)
294
0
{
295
0
    size_t i;
296
0
    int stat = NC_NOERR;
297
0
    NCZ_FILE_INFO_T* zinfo = NULL;
298
0
    char number[1024];
299
0
    NCZMAP* map = NULL;
300
0
    char* key = NULL;
301
0
    char* dimpath = NULL;
302
0
    NClist* dimrefs = NULL;
303
0
    NCjson* jvar = NULL;
304
0
    NCjson* jncvar = NULL;
305
0
    NCjson* jdimrefs = NULL;
306
0
    NCjson* jtmp = NULL;
307
0
    NCjson* jfill = NULL;
308
0
    NCjson* jatts = NULL;
309
0
    NCjson* jtypes = NULL;
310
0
    char* dtypename = NULL;
311
0
    int purezarr = 0;
312
0
    size64_t shape[NC_MAX_VAR_DIMS];
313
0
    NCZ_VAR_INFO_T* zvar = var->format_var_info;
314
#ifdef NETCDF_ENABLE_NCZARR_FILTERS
315
    NClist* filterchain = NULL;
316
    NCjson* jfilter = NULL;
317
#endif
318
319
0
    ZTRACE(3,"file=%s var=%s isclose=%d",file->controller->path,var->hdr.name,isclose);
320
321
0
    zinfo = file->format_file_info;
322
0
    map = zinfo->map;
323
324
0
    purezarr = (zinfo->controls.flags & FLAG_PUREZARR)?1:0;
325
326
    /* Make sure that everything is established */
327
    /* ensure the fill value */
328
0
    if((stat = NCZ_ensure_fill_value(var))) goto done; /* ensure var->fill_value is set */
329
0
    assert(var->no_fill || var->fill_value != NULL);
330
    /* ensure the chunk cache */
331
0
    if((stat = NCZ_adjust_var_cache(var))) goto done;
332
    /* rebuild the fill chunk */
333
0
    if((stat = NCZ_ensure_fill_chunk(zvar->cache))) goto done;
334
#ifdef NETCDF_ENABLE_NCZARR_FILTERS
335
    /* Build the filter working parameters for any filters */
336
    if((stat = NCZ_filter_setup(var))) goto done;
337
#endif
338
339
    /* Construct var path */
340
0
    if((stat = NCZ_varkey(var,&key)))
341
0
  goto done;
342
343
    /* Create the zarray json object */
344
0
    NCJnew(NCJ_DICT,&jvar);
345
346
    /* zarr_format key */
347
0
    snprintf(number,sizeof(number),"%d",zinfo->format.zarr);
348
0
    if((stat = NCJaddstring(jvar,NCJ_STRING,"zarr_format"))<0) {stat = NC_EINVAL; goto done;}
349
0
    if((stat = NCJaddstring(jvar,NCJ_INT,number))<0) {stat = NC_EINVAL; goto done;}
350
351
    /* Collect the shape vector */
352
0
    for(i=0;i<var->ndims;i++) {
353
0
  NC_DIM_INFO_T* dim = var->dim[i];
354
0
  shape[i] = dim->len;
355
0
    }
356
    /* but might be scalar */
357
0
    if(var->ndims == 0)
358
0
        shape[0] = 1;
359
360
    /* shape key */
361
    /* Integer list defining the length of each dimension of the array.*/
362
    /* Create the list */
363
0
    NCJnew(NCJ_ARRAY,&jtmp);
364
0
    if(zvar->scalar && !purezarr) {
365
0
  NCJaddstring(jtmp,NCJ_INT,"1");
366
0
    } else for(i=0;i<var->ndims;i++) {
367
0
  snprintf(number,sizeof(number),"%llu",shape[i]);
368
0
  NCJaddstring(jtmp,NCJ_INT,number);
369
0
    }
370
0
    if((stat = NCJinsert(jvar,"shape",jtmp))<0) {stat = NC_EINVAL; goto done;}
371
0
    jtmp = NULL;
372
373
    /* dtype key */
374
    /* A string or list defining a valid data type for the array. */
375
0
    if((stat = NCJaddstring(jvar,NCJ_STRING,"dtype"))<0) {stat = NC_EINVAL; goto done;}
376
0
    { /* Add the type name */
377
0
  int endianness = var->type_info->endianness;
378
0
  int atomictype = var->type_info->hdr.id;
379
0
  assert(atomictype > 0 && atomictype <= NC_MAX_ATOMIC_TYPE);
380
0
  if((stat = ncz_nctype2dtype(atomictype,endianness,purezarr,NCZ_get_maxstrlen((NC_OBJ*)var),&dtypename))) goto done;
381
0
  if((stat = NCJaddstring(jvar,NCJ_STRING,dtypename))<0) {stat = NC_EINVAL; goto done;}
382
0
  nullfree(dtypename); dtypename = NULL;
383
0
    }
384
385
    /* chunks key */
386
    /* The zarr format does not support the concept
387
       of contiguous (or compact), so it will never appear in the read case.
388
    */
389
    /* list of chunk sizes */
390
0
    if((stat = NCJaddstring(jvar,NCJ_STRING,"chunks"))<0) {stat = NC_EINVAL; goto done;}
391
    /* Create the list */
392
0
    NCJnew(NCJ_ARRAY,&jtmp);
393
0
    if(zvar->scalar && !purezarr) {
394
0
  NCJaddstring(jtmp,NCJ_INT,"1"); /* one chunk of size 1 */
395
0
    } else for(i=0;i<var->ndims;i++) {
396
0
  size64_t len = var->chunksizes[i];
397
0
  snprintf(number,sizeof(number),"%lld",len);
398
0
  NCJaddstring(jtmp,NCJ_INT,number);
399
0
    }
400
0
    if((stat = NCJappend(jvar,jtmp))<0) {stat = NC_EINVAL; goto done;}
401
0
    jtmp = NULL;
402
403
    /* fill_value key */
404
0
    if(var->no_fill) {
405
0
  NCJnew(NCJ_NULL,&jfill);
406
0
    } else {/*!var->no_fill*/
407
0
  int atomictype = var->type_info->hdr.id;
408
0
        if(var->fill_value == NULL) {
409
0
       if((stat = NCZ_ensure_fill_value(var))) goto done;
410
0
  }
411
        /* Convert var->fill_value to a string */
412
0
  if((stat = NCZ_stringconvert(atomictype,1,var->fill_value,&jfill))) goto done;
413
0
  assert(jfill->sort != NCJ_ARRAY);
414
0
    }
415
0
    if((stat = NCJinsert(jvar,"fill_value",jfill))<0) {stat = NC_EINVAL; goto done;}
416
0
    jfill = NULL;
417
418
    /* order key */
419
0
    if((stat = NCJaddstring(jvar,NCJ_STRING,"order"))<0) {stat = NC_EINVAL; goto done;}
420
    /* "C" means row-major order, i.e., the last dimension varies fastest;
421
       "F" means column-major order, i.e., the first dimension varies fastest.*/
422
    /* Default to C for now */
423
0
    if((stat = NCJaddstring(jvar,NCJ_STRING,"C"))<0) {stat = NC_EINVAL; goto done;}
424
425
    /* Compressor and Filters */
426
    /* compressor key */
427
    /* From V2 Spec: A JSON object identifying the primary compression codec and providing
428
       configuration parameters, or ``null`` if no compressor is to be used. */
429
0
    if((stat = NCJaddstring(jvar,NCJ_STRING,"compressor"))<0) {stat = NC_EINVAL; goto done;}
430
#ifdef NETCDF_ENABLE_NCZARR_FILTERS
431
    filterchain = (NClist*)var->filters;
432
    if(nclistlength(filterchain) > 0) {
433
  struct NCZ_Filter* filter = (struct NCZ_Filter*)nclistget(filterchain,nclistlength(filterchain)-1);
434
        /* encode up the compressor */
435
        if((stat = NCZ_filter_jsonize(file,var,filter,&jtmp))) goto done;
436
    } else
437
#endif
438
0
    { /* no filters at all */
439
        /* Default to null */
440
0
        NCJnew(NCJ_NULL,&jtmp);
441
0
    }
442
0
    if(jtmp && (stat = NCJappend(jvar,jtmp))<0) {stat = NC_EINVAL; goto done;}
443
0
    jtmp = NULL;
444
445
    /* filters key */
446
    /* From V2 Spec: A list of JSON objects providing codec configurations,
447
       or null if no filters are to be applied. Each codec configuration
448
       object MUST contain a "id" key identifying the codec to be used. */
449
    /* A list of JSON objects providing codec configurations, or ``null``
450
       if no filters are to be applied. */
451
0
    if((stat = NCJaddstring(jvar,NCJ_STRING,"filters"))<0) {stat = NC_EINVAL; goto done;}
452
#ifdef NETCDF_ENABLE_NCZARR_FILTERS
453
    if(nclistlength(filterchain) > 1) {
454
  size_t k;
455
  /* jtmp holds the array of filters */
456
  NCJnew(NCJ_ARRAY,&jtmp);
457
  for(k=0;k<nclistlength(filterchain)-1;k++) {
458
      struct NCZ_Filter* filter = (struct NCZ_Filter*)nclistget(filterchain,k);
459
      /* encode up the filter as a string */
460
      if((stat = NCZ_filter_jsonize(file,var,filter,&jfilter))) goto done;
461
      if((stat = NCJappend(jtmp,jfilter))<0) {stat = NC_EINVAL; goto done;}
462
  }
463
    } else
464
#endif
465
    /* no filters at all */
466
0
    NCJnew(NCJ_NULL,&jtmp);
467
0
    if((stat = NCJappend(jvar,jtmp))<0) {stat = NC_EINVAL; goto done;}
468
0
    jtmp = NULL;
469
470
    /* dimension_separator key */
471
    /* Single char defining the separator in chunk keys */
472
0
    if(zvar->dimension_separator != DFALT_DIM_SEPARATOR) {
473
0
  char sep[2];
474
0
  sep[0] = zvar->dimension_separator;/* make separator a string*/
475
0
  sep[1] = '\0';
476
0
        NCJnewstring(NCJ_STRING,sep,&jtmp);
477
0
        if((stat = NCJinsert(jvar,"dimension_separator",jtmp))<0) {stat = NC_EINVAL; goto done;}
478
0
        jtmp = NULL;
479
0
    }
480
481
0
    nullfree(key);
482
0
    key = NULL;
483
0
    NCZ_varkey(var, &key);
484
0
    if((stat=NCZMD_update_json_array(zinfo,key,(const NCjson*)jvar))) {
485
0
        goto done;
486
0
    }
487
488
    /* Capture dimref names as FQNs */
489
0
    if(var->ndims > 0) {
490
0
        if((dimrefs = nclistnew())==NULL) {stat = NC_ENOMEM; goto done;}
491
0
  for(i=0;i<var->ndims;i++) {
492
0
      NC_DIM_INFO_T* dim = var->dim[i];
493
0
      if((stat = NCZ_dimkey(dim,&dimpath))) goto done;
494
0
      nclistpush(dimrefs,dimpath);
495
0
      dimpath = NULL;
496
0
  }
497
0
    }
498
499
    /* Build the NCZ_V2_ARRAY object */
500
0
    {
501
  /* Create the dimrefs json object */
502
0
  NCJnew(NCJ_ARRAY,&jdimrefs);
503
0
  for(i=0;i<nclistlength(dimrefs);i++) {
504
0
      const char* dim = nclistget(dimrefs,i);
505
0
      NCJaddstring(jdimrefs,NCJ_STRING,dim);
506
0
  }
507
0
  NCJnew(NCJ_DICT,&jncvar);
508
509
  /* Insert dimension_referencess  */
510
0
  if((stat = NCJinsert(jncvar,"dimension_references",jdimrefs))<0) {stat = NC_EINVAL; goto done;}
511
0
  jdimrefs = NULL; /* Avoid memory problems */
512
513
  /* Add the _Storage flag */
514
  /* Record if this is a scalar */
515
0
  if(var->ndims == 0) {
516
0
      NCJnewstring(NCJ_INT,"1",&jtmp);
517
0
      if((stat = NCJinsert(jncvar,"scalar",jtmp))<0) {stat = NC_EINVAL; goto done;}
518
0
      jtmp = NULL;
519
0
  }
520
  /* everything looks like it is chunked */
521
0
  NCJnewstring(NCJ_STRING,"chunked",&jtmp);
522
0
  if((stat = NCJinsert(jncvar,"storage",jtmp))<0) {stat = NC_EINVAL; goto done;}
523
0
  jtmp = NULL;
524
0
    }
525
526
    /* Build .zattrs object */
527
0
    assert(var->att);
528
0
    NCJnew(NCJ_DICT,&jatts);
529
0
    NCJnew(NCJ_DICT,&jtypes);
530
0
    if((stat = ncz_sync_atts(file,(NC_OBJ*)var, var->att, jatts, jtypes, isclose))) goto done;
531
532
0
    if(!purezarr && jncvar != NULL) {
533
        /* Insert _nczarr_array */
534
0
        if((stat=insert_attr(jatts,jtypes,NCZ_V2_ARRAY,jncvar,"|J0"))) goto done;
535
0
  jncvar = NULL;
536
0
    }
537
538
    /* As a last mod to jatts, optionally insert the jtypes as an attribute and add _nczarr_attr as attribute*/
539
0
    if(!purezarr && jtypes != NULL) {
540
0
  if((stat = insert_nczarr_attr(jatts,jtypes))) goto done;
541
0
  jtypes = NULL;
542
0
    }
543
544
    /* Write out the .zattrs */
545
0
    nullfree(key);
546
0
    key = NULL;
547
0
    NCZ_varkey(var, &key);
548
0
    if((stat = NCZMD_update_json_attrs(zinfo, key, jatts))) goto done;
549
550
0
    var->created = 1;
551
552
0
done:
553
0
    nclistfreeall(dimrefs);
554
0
    nullfree(key);
555
0
    nullfree(dtypename);
556
0
    nullfree(dimpath);
557
0
    NCJreclaim(jvar);
558
0
    NCJreclaim(jncvar);
559
0
    NCJreclaim(jtmp);
560
0
    NCJreclaim(jfill);
561
0
    NCJreclaim(jatts);
562
0
    NCJreclaim(jtypes);
563
0
    return ZUNTRACE(THROW(stat));
564
0
}
565
566
/**
567
 * @internal Synchronize variable meta data and data from memory to map.
568
 *
569
 * @param file Pointer to file struct
570
 * @param var Pointer to var struct
571
 * @param isclose If this called as part of nc_close() as opposed to nc_enddef().
572
 *
573
 * @return ::NC_NOERR No error.
574
 * @author Dennis Heimbigner
575
 */
576
static int
577
ncz_sync_var(NC_FILE_INFO_T* file, NC_VAR_INFO_T* var, int isclose)
578
0
{
579
0
    int stat = NC_NOERR;
580
0
    NCZ_VAR_INFO_T* zvar = var->format_var_info;
581
582
0
    ZTRACE(3,"file=%s var=%s isclose=%d",file->controller->path,var->hdr.name,isclose);
583
584
0
    if(isclose) {
585
0
  if((stat = ncz_sync_var_meta(file,var,isclose))) goto done;
586
0
    }
587
588
    /* flush only chunks that have been written */
589
0
    if(zvar->cache) {
590
0
        if((stat = NCZ_flush_chunk_cache(zvar->cache)))
591
0
      goto done;
592
0
    }
593
594
0
done:
595
0
    return ZUNTRACE(THROW(stat));
596
0
}
597
598
599
/*
600
Flush all chunks to disk. Create any that are missing
601
and fill as needed.
602
*/
603
int
604
ncz_write_var(NC_VAR_INFO_T* var)
605
0
{
606
0
    int stat = NC_NOERR;
607
0
    NCZ_VAR_INFO_T* zvar = (NCZ_VAR_INFO_T*)var->format_var_info;
608
609
0
    ZTRACE(3,"var=%s",var->hdr.name);
610
611
    /* Flush the cache */
612
0
    if(zvar->cache) {
613
0
        if((stat = NCZ_flush_chunk_cache(zvar->cache))) goto done;
614
0
    }
615
616
#ifdef FILLONCLOSE
617
    /* If fill is enabled, then create missing chunks */
618
    if(!var->no_fill) {
619
        int i;
620
    NCZOdometer* chunkodom =  NULL;
621
    NC_FILE_INFO_T* file = var->container->nc4_info;
622
    NCZ_FILE_INFO_T* zfile = (NCZ_FILE_INFO_T*)file->format_file_info;
623
    NCZMAP* map = zfile->map;
624
    size64_t start[NC_MAX_VAR_DIMS];
625
    size64_t stop[NC_MAX_VAR_DIMS];
626
    size64_t stride[NC_MAX_VAR_DIMS];
627
    char* key = NULL;
628
629
    if(var->ndims == 0) { /* scalar */
630
  start[i] = 0;
631
  stop[i] = 1;
632
        stride[i] = 1;
633
    } else {
634
        for(i=0;i<var->ndims;i++) {
635
      size64_t nchunks = ceildiv(var->dim[i]->len,var->chunksizes[i]);
636
      start[i] = 0;
637
      stop[i] = nchunks;
638
      stride[i] = 1;
639
        }
640
    }
641
642
    {
643
  if(zvar->scalar) {
644
      if((chunkodom = nczodom_new(1,start,stop,stride,stop))==NULL)
645
  } else {
646
      /* Iterate over all the chunks to create missing ones */
647
      if((chunkodom = nczodom_new(var->ndims,start,stop,stride,stop))==NULL)
648
          {stat = NC_ENOMEM; goto done;}
649
  }
650
  for(;nczodom_more(chunkodom);nczodom_next(chunkodom)) {
651
      size64_t* indices = nczodom_indices(chunkodom);
652
      /* Convert to key */
653
      if((stat = NCZ_buildchunkpath(zvar->cache,indices,&key))) goto done;
654
      switch (stat = nczmap_exists(map,key)) {
655
      case NC_NOERR: goto next; /* already exists */
656
      case NC_EEMPTY: break; /* does not exist, create it with fill */
657
      default: goto done; /* some other error */
658
      }
659
            /* If we reach here, then chunk does not exist, create it with fill */
660
      assert(zvar->cache->fillchunk != NULL);
661
      if((stat=nczmap_write(map,key,0,zvar->cache->chunksize,zvar->cache->fillchunk))) goto done;
662
next:
663
      nullfree(key);
664
      key = NULL;
665
  }
666
    }
667
    nczodom_free(chunkodom);
668
    nullfree(key);
669
    }
670
#endif /*FILLONCLOSE*/
671
672
0
done:
673
0
    return ZUNTRACE(THROW(stat));
674
0
}
675
676
/**
677
 * @internal Synchronize attribute data from memory to map.
678
 *
679
 * @param file
680
 * @param container Pointer to grp|var struct containing the attributes
681
 * @param attlist
682
 * @param jattsp
683
 * @param jtypesp
684
 *
685
 * @return ::NC_NOERR No error.
686
 * @author Dennis Heimbigner
687
 */
688
int
689
ncz_sync_atts(NC_FILE_INFO_T* file, NC_OBJ* container, NCindex* attlist, NCjson* jatts, NCjson* jtypes, int isclose)
690
0
{
691
0
    int stat = NC_NOERR;
692
0
    size_t i;
693
0
    NCZ_FILE_INFO_T* zinfo = NULL;
694
0
    NCjson* jdimrefs = NULL;
695
0
    NCjson* jdict = NULL;
696
0
    NCjson* jint = NULL;
697
0
    NCjson* jdata = NULL;
698
0
    char* key = NULL;
699
0
    char* content = NULL;
700
0
    char* dimpath = NULL;
701
0
    int isxarray = 0;
702
0
    int inrootgroup = 0;
703
0
    NC_VAR_INFO_T* var = NULL;
704
0
    NC_GRP_INFO_T* grp = NULL;
705
0
    char* tname = NULL;
706
0
    int purezarr = 0;
707
0
    int endianness = (NC_isLittleEndian()?NC_ENDIAN_LITTLE:NC_ENDIAN_BIG);
708
709
0
    NC_UNUSED(isclose);
710
    
711
0
    LOG((3, "%s", __func__));
712
0
    ZTRACE(3,"file=%s container=%s |attlist|=%u",file->controller->path,container->name,(unsigned)ncindexsize(attlist));
713
    
714
0
    if(container->sort == NCVAR) {
715
0
        var = (NC_VAR_INFO_T*)container;
716
0
  if(var->container && var->container->parent == NULL)
717
0
      inrootgroup = 1;
718
0
    } else if(container->sort == NCGRP) {
719
0
        grp = (NC_GRP_INFO_T*)container;
720
0
    }
721
    
722
0
    zinfo = file->format_file_info;
723
0
    purezarr = (zinfo->controls.flags & FLAG_PUREZARR)?1:0;
724
0
    if(zinfo->controls.flags & FLAG_XARRAYDIMS) isxarray = 1;
725
726
0
    if(ncindexsize(attlist) > 0) {
727
        /* Walk all the attributes convert to json and collect the dtype */
728
0
        for(i=0;i<ncindexsize(attlist);i++) {
729
0
      NC_ATT_INFO_T* a = (NC_ATT_INFO_T*)ncindexith(attlist,i);
730
0
      size_t typesize = 0;
731
0
      if(a->nc_typeid > NC_MAX_ATOMIC_TYPE)
732
0
          {stat = (THROW(NC_ENCZARR)); goto done;}
733
0
      if(a->nc_typeid == NC_STRING)
734
0
          typesize = (size_t)NCZ_get_maxstrlen(container);
735
0
      else
736
0
          {if((stat = NC4_inq_atomic_type(a->nc_typeid,NULL,&typesize))) goto done;}
737
      /* Convert to storable json */
738
0
      if((stat = NCZ_stringconvert(a->nc_typeid,a->len,a->data,&jdata))) goto done;
739
740
      /* Collect the corresponding dtype */
741
0
            if((stat = ncz_nctype2dtype(a->nc_typeid,endianness,purezarr,typesize,&tname))) goto done;
742
743
      /* Insert the attribute; consumes jdata */
744
0
      if((stat = insert_attr(jatts,jtypes,a->hdr.name, jdata, tname))) goto done;
745
746
      /* cleanup */
747
0
            nullfree(tname); tname = NULL;
748
0
      jdata = NULL;
749
750
0
        }
751
0
    }
752
    /* Construct container path */
753
0
    if(container->sort == NCGRP)
754
0
  stat = NCZ_grpkey(grp,&key);
755
0
    else
756
0
  stat = NCZ_varkey(var,&key);
757
0
    if(stat)
758
0
  goto done;
759
760
0
    if(container->sort == NCVAR) { 
761
0
        if(isxarray) {
762
      /* Optionally insert XARRAY-related attributes:
763
    - XARRAYSCALAR
764
    - _ARRAY_ATTRIBUTE
765
      */
766
0
      NCJnew(NCJ_ARRAY,&jdimrefs);
767
      /* Fake the scalar case */
768
0
      if(var->ndims == 0 && !purezarr)
769
0
          NCJaddstring(jdimrefs,NCJ_STRING,XARRAYSCALAR);
770
      /* Walk the dimensions and capture the names */
771
0
      for(i=0;i<var->ndims;i++) {
772
0
    char* dimname;
773
0
          NC_DIM_INFO_T* dim = var->dim[i];
774
0
    dimname = strdup(dim->hdr.name);
775
0
    if(dimname == NULL) {stat = NC_ENOMEM; goto done;}
776
0
          NCJaddstring(jdimrefs,NCJ_STRING,dimname);
777
0
            nullfree(dimname); dimname = NULL;
778
0
      }
779
      /* Add the _ARRAY_DIMENSIONS attribute */
780
0
      if((stat = NCJinsert(jatts,NC_XARRAY_DIMS,jdimrefs))<0) {stat = NC_EINVAL; goto done;}
781
0
      jdimrefs = NULL;
782
0
        }
783
0
    }
784
    /* Add Quantize Attribute */
785
0
    if(container->sort == NCVAR && var && var->quantize_mode > 0) {    
786
0
  char mode[64];
787
0
  snprintf(mode,sizeof(mode),"%d",var->nsd);
788
0
        NCJnewstring(NCJ_INT,mode,&jint);
789
  /* Insert the quantize attribute */
790
0
  switch (var->quantize_mode) {
791
0
  case NC_QUANTIZE_BITGROOM:
792
0
      if((stat = NCJinsert(jatts,NC_QUANTIZE_BITGROOM_ATT_NAME,jint))<0) {stat = NC_EINVAL; goto done;} 
793
0
      jint = NULL;
794
0
      break;
795
0
  case NC_QUANTIZE_GRANULARBR:
796
0
      if((stat = NCJinsert(jatts,NC_QUANTIZE_GRANULARBR_ATT_NAME,jint))<0) {stat = NC_EINVAL; goto done;} 
797
0
      jint = NULL;
798
0
      break;
799
0
  case NC_QUANTIZE_BITROUND:
800
0
      if((stat = NCJinsert(jatts,NC_QUANTIZE_BITROUND_ATT_NAME,jint))<0) {stat = NC_EINVAL; goto done;} 
801
0
      jint = NULL;
802
0
      break;
803
0
  default: break;
804
0
  }
805
0
    }
806
807
0
done:
808
0
    nullfree(key);
809
0
    nullfree(content);
810
0
    nullfree(dimpath);
811
0
    nullfree(tname);
812
0
    NCJreclaim(jdimrefs);
813
0
    NCJreclaim(jdict);
814
0
    NCJreclaim(jint);
815
0
    NCJreclaim(jdata);
816
0
    return ZUNTRACE(THROW(stat));
817
0
}
818
819
820
/**************************************************/
821
822
/**
823
@internal Extract attributes from a group or var and return
824
the corresponding NCjson dict.
825
@param map - [in] the map object for storage
826
@param container - [in] the containing object
827
@param jattsp    - [out] the json for .zattrs || NULL if not found
828
@param jtypesp   - [out] the json attribute type dict || NULL
829
@param jnczgrp   - [out] the json for _nczarr_group || NULL
830
@param jnczarray - [out] the json for _nczarr_array || NULL
831
@return NC_NOERR
832
@return NC_EXXX
833
@author Dennis Heimbigner
834
*/
835
static int
836
download_jatts(NC_FILE_INFO_T* file, NC_OBJ* container, const NCjson** jattsp, const NCjson** jtypesp)
837
0
{
838
0
    int stat = NC_NOERR;
839
0
    const NCjson* jatts = NULL;
840
0
    const NCjson* jtypes = NULL;
841
0
    const NCjson* jnczattr = NULL;
842
0
    NC_GRP_INFO_T* grp = NULL;
843
0
    NC_VAR_INFO_T* var = NULL;
844
0
    NCZ_GRP_INFO_T* zgrp = NULL;
845
0
    NCZ_VAR_INFO_T* zvar = NULL;
846
0
    NCZ_FILE_INFO_T* zinfo = (NCZ_FILE_INFO_T*)file->format_file_info;
847
0
    int purezarr = 0;
848
0
    int zarrkey = 0;
849
850
0
    ZTRACE(3,"container=%s ",container->name);
851
852
0
    purezarr = (zinfo->controls.flags & FLAG_PUREZARR)?1:0;
853
0
    zarrkey = (zinfo->controls.flags & FLAG_NCZARR_KEY)?1:0;
854
855
0
    if(container->sort == NCGRP) {
856
0
  grp = (NC_GRP_INFO_T*)container;
857
0
  zgrp = (NCZ_GRP_INFO_T*)grp->format_grp_info; 
858
0
  jatts = zgrp->zgroup.atts;
859
0
    } else {
860
0
  var = (NC_VAR_INFO_T*)container;
861
0
  zvar = (NCZ_VAR_INFO_T*)var->format_var_info;
862
0
  jatts = zvar->zarray.atts;
863
0
    }
864
0
    assert(purezarr || zarrkey || jatts != NULL);
865
866
0
    if(jatts != NULL) {
867
  /* Get _nczarr_attr from .zattrs */
868
0
        if((stat = NCJdictget(jatts,NCZ_V2_ATTR,&jnczattr))<0) {stat = NC_EINVAL; goto done;}
869
0
  if(jnczattr != NULL) {
870
      /* jnczattr attribute should be a dict */
871
0
      if(NCJsort(jnczattr) != NCJ_DICT) {stat = (THROW(NC_ENCZARR)); goto done;}
872
      /* Extract "types"; may not exist if only hidden attributes are defined */
873
0
      if((stat = NCJdictget(jnczattr,"types",&jtypes))<0) {stat = NC_EINVAL; goto done;}
874
0
      if(jtypes != NULL) {
875
0
          if(NCJsort(jtypes) != NCJ_DICT) {stat = (THROW(NC_ENCZARR)); goto done;}
876
0
      }
877
0
  }
878
0
    }
879
0
    if(jattsp) {*jattsp = jatts; jatts = NULL;}
880
0
    if(jtypes) {*jtypesp = jtypes; jtypes = NULL;}
881
882
0
done:
883
0
    return ZUNTRACE(THROW(stat));
884
0
}
885
886
/* Convert a JSON singleton or array of strings to a single string */
887
static int
888
zcharify(const NCjson* src, NCbytes* buf)
889
0
{
890
0
    int stat = NC_NOERR;
891
0
    size_t i;
892
0
    struct NCJconst jstr;
893
894
0
    memset(&jstr,0,sizeof(jstr));
895
896
0
    if(NCJsort(src) != NCJ_ARRAY) { /* singleton */
897
0
        if((stat = NCJcvt(src, NCJ_STRING, &jstr))<0) {stat = NC_EINVAL; goto done;}
898
0
        ncbytescat(buf,jstr.sval);
899
0
    } else for(i=0;i<NCJarraylength(src);i++) {
900
0
  NCjson* value = NCJith(src,i);
901
0
  if((stat = NCJcvt(value, NCJ_STRING, &jstr))<0) {stat = NC_EINVAL; goto done;}
902
0
  ncbytescat(buf,jstr.sval);
903
0
        nullfree(jstr.sval);jstr.sval = NULL;
904
0
    }
905
0
done:
906
0
    nullfree(jstr.sval);
907
0
    return stat;
908
0
}
909
910
/* Convert a json value to actual data values of an attribute. */
911
static int
912
zconvert(const NCjson* src, nc_type typeid, size_t typelen, int* countp, NCbytes* dst)
913
0
{
914
0
    int stat = NC_NOERR;
915
0
    int i;
916
0
    int count = 0;
917
    
918
0
    ZTRACE(3,"src=%s typeid=%d typelen=%u",NCJtotext(src,0),typeid,typelen);
919
      
920
    /* 3 cases:
921
       (1) singleton atomic value
922
       (2) array of atomic values
923
       (3) other JSON expression
924
    */
925
0
    switch (NCJsort(src)) {
926
0
    case NCJ_INT: case NCJ_DOUBLE: case NCJ_BOOLEAN: /* case 1 */
927
0
  count = 1;
928
0
  if((stat = NCZ_convert1(src, typeid, dst)))
929
0
      goto done;
930
0
  break;
931
932
0
    case NCJ_ARRAY:
933
0
        if(typeid == NC_CHAR) {
934
0
      if((stat = zcharify(src,dst))) goto done;
935
0
      count = ncbyteslength(dst);
936
0
        } else {
937
0
      count = NCJarraylength(src);
938
0
      for(i=0;i<count;i++) {
939
0
          NCjson* value = NCJith(src,i);
940
0
                if((stat = NCZ_convert1(value, typeid, dst))) goto done;
941
0
      }
942
0
  }
943
0
  break;
944
0
    case NCJ_STRING:
945
0
  if(typeid == NC_CHAR) {
946
0
      if((stat = zcharify(src,dst))) goto done;
947
0
      count = ncbyteslength(dst);
948
      /* Special case for "" */
949
0
      if(count == 0) {
950
0
          ncbytesappend(dst,'\0');
951
0
          count = 1;
952
0
      }
953
0
  } else {
954
0
      if((stat = NCZ_convert1(src, typeid, dst))) goto done;
955
0
      count = 1;
956
0
  }
957
0
  break;
958
0
    default: stat = (THROW(NC_ENCZARR)); goto done;
959
0
    }
960
0
    if(countp) *countp = count;
961
962
0
done:
963
0
    return ZUNTRACE(THROW(stat));
964
0
}
965
966
/*
967
Extract type and data for an attribute
968
*/
969
static int
970
computeattrinfo(const char* name, const NCjson* jtypes, nc_type typehint, int purezarr, NCjson* values,
971
    nc_type* typeidp, size_t* typelenp, size_t* lenp, void** datap)
972
0
{
973
0
    int stat = NC_NOERR;
974
0
    size_t i;
975
0
    size_t len, typelen;
976
0
    void* data = NULL;
977
0
    nc_type typeid;
978
979
0
    ZTRACE(3,"name=%s typehint=%d purezarr=%d values=|%s|",name,typehint,purezarr,NCJtotext(values,0));
980
981
    /* Get type info for the given att */
982
0
    typeid = NC_NAT;
983
0
    for(i=0;i<NCJdictlength(jtypes);i++) {
984
0
  NCjson* akey = NCJdictkey(jtypes,i);
985
0
  if(strcmp(NCJstring(akey),name)==0) {
986
0
      const NCjson* avalue = NULL;
987
0
      NCJdictget(jtypes,NCJstring(akey),&avalue);
988
0
      if((stat = ncz_dtype2nctype(NCJstring(avalue),typehint,purezarr,&typeid,NULL,NULL))) goto done;
989
//    if((stat = ncz_nctypedecode(atype,&typeid))) goto done;
990
0
      break;
991
0
  }
992
0
    }
993
0
    if(typeid > NC_MAX_ATOMIC_TYPE)
994
0
  {stat = NC_EINTERNAL; goto done;}
995
    /* Use the hint if given one */
996
0
    if(typeid == NC_NAT)
997
0
        typeid = typehint;
998
999
0
    if((stat = computeattrdata(typehint, &typeid, values, &typelen, &len, &data))) goto done;
1000
1001
0
    if(typeidp) *typeidp = typeid;
1002
0
    if(lenp) *lenp = len;
1003
0
    if(typelenp) *typelenp = typelen;
1004
0
    if(datap) {*datap = data; data = NULL;}
1005
1006
0
done:
1007
0
    nullfree(data);
1008
0
    return ZUNTRACEX(THROW(stat),"typeid=%d typelen=%d len=%u",*typeidp,*typelenp,*lenp);
1009
0
}
1010
1011
/*
1012
Extract data for an attribute
1013
*/
1014
static int
1015
computeattrdata(nc_type typehint, nc_type* typeidp, const NCjson* values, size_t* typelenp, size_t* countp, void** datap)
1016
0
{
1017
0
    int stat = NC_NOERR;
1018
0
    NCbytes* buf = ncbytesnew();
1019
0
    size_t typelen;
1020
0
    nc_type typeid = NC_NAT;
1021
0
    NCjson* jtext = NULL;
1022
0
    int reclaimvalues = 0;
1023
0
    int isjson = 0; /* 1 => attribute value is neither scalar nor array of scalars */
1024
0
    int count = 0; /* no. of attribute values */
1025
1026
0
    ZTRACE(3,"typehint=%d typeid=%d values=|%s|",typehint,*typeidp,NCJtotext(values,0));
1027
1028
    /* Get assumed type */
1029
0
    if(typeidp) typeid = *typeidp;
1030
0
    if(typeid == NC_NAT && !isjson) {
1031
0
        if((stat = NCZ_inferattrtype(values,typehint, &typeid))) goto done;
1032
0
    }
1033
1034
    /* See if this is a simple vector (or scalar) of atomic types */
1035
0
    isjson = NCZ_iscomplexjson(values,typeid);
1036
1037
0
    if(isjson) {
1038
  /* Apply the JSON attribute convention and convert to JSON string */
1039
0
  typeid = NC_CHAR;
1040
0
  if((stat = json_convention_read(values,&jtext))) goto done;
1041
0
  values = jtext; jtext = NULL;
1042
0
  reclaimvalues = 1;
1043
0
    } 
1044
1045
0
    if((stat = NC4_inq_atomic_type(typeid, NULL, &typelen)))
1046
0
        goto done;
1047
1048
    /* Convert the JSON attribute values to the actual netcdf attribute bytes */
1049
0
    if((stat = zconvert(values,typeid,typelen,&count,buf))) goto done;
1050
1051
0
    if(typelenp) *typelenp = typelen;
1052
0
    if(typeidp) *typeidp = typeid; /* return possibly inferred type */
1053
0
    if(countp) *countp = (size_t)count;
1054
0
    if(datap) *datap = ncbytesextract(buf);
1055
1056
0
done:
1057
0
    ncbytesfree(buf);
1058
0
    if(reclaimvalues) NCJreclaim((NCjson*)values); /* we created it */
1059
0
    return ZUNTRACEX(THROW(stat),"typelen=%d count=%u",(typelenp?*typelenp:0),(countp?*countp:-1));
1060
0
}
1061
1062
/**
1063
 * @internal Read file data from map to memory.
1064
 *
1065
 * @param file Pointer to file info struct.
1066
 *
1067
 * @return ::NC_NOERR No error.
1068
 * @author Dennis Heimbigner
1069
 */
1070
int
1071
ncz_read_file(NC_FILE_INFO_T* file)
1072
0
{
1073
0
    int stat = NC_NOERR;
1074
0
    NCjson* json = NULL;
1075
1076
0
    LOG((3, "%s: file: %s", __func__, file->controller->path));
1077
0
    ZTRACE(3,"file=%s",file->controller->path);
1078
    
1079
    /* _nczarr should already have been read in ncz_open_dataset */
1080
1081
    /* Now load the groups starting with root */
1082
0
    if((stat = define_grp(file,file->root_grp)))
1083
0
  goto done;
1084
1085
0
done:
1086
0
    NCJreclaim(json);
1087
0
    return ZUNTRACE(stat);
1088
0
}
1089
1090
/**
1091
 * @internal Read group data from map to memory
1092
 *
1093
 * @param file Pointer to file struct
1094
 * @param grp Pointer to grp struct
1095
 *
1096
 * @return ::NC_NOERR No error.
1097
 * @author Dennis Heimbigner
1098
 */
1099
static int
1100
define_grp(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp)
1101
0
{
1102
0
    int stat = NC_NOERR;
1103
0
    NCZ_FILE_INFO_T* zinfo = NULL;
1104
0
    NCZ_GRP_INFO_T* zgrp = NULL;
1105
0
    char* key = NULL;
1106
0
    NCjson* json = NULL;
1107
0
    const NCjson* jgroup = NULL;
1108
0
    const NCjson* jattrs = NULL;
1109
0
    const NCjson* jnczgrp = NULL;
1110
0
    NClist* dimdefs = nclistnew();
1111
0
    NClist* varnames = nclistnew();
1112
0
    NClist* subgrps = nclistnew();
1113
0
    int purezarr = 0;
1114
1115
0
    LOG((3, "%s: dims: %s", __func__, key));
1116
0
    ZTRACE(3,"file=%s grp=%s",file->controller->path,grp->hdr.name);
1117
    
1118
0
    zinfo = file->format_file_info;
1119
0
    zgrp = grp->format_grp_info;
1120
1121
0
    purezarr = (zinfo->controls.flags & FLAG_PUREZARR)?1:0;
1122
1123
    /* Construct grp path */
1124
0
    if((stat = NCZ_grpkey(grp,&key))) goto done;
1125
1126
    /* Download .zgroup and .zattrs */
1127
0
    nullfree(zgrp->zgroup.prefix);
1128
0
    zgrp->zgroup.prefix = strdup(key);
1129
0
    NCJreclaim(zgrp->zgroup.obj);
1130
0
    NCJreclaim(zgrp->zgroup.atts);
1131
0
    if ((stat = NCZMD_fetch_json_group(zinfo, key, &zgrp->zgroup.obj)) \
1132
0
    || (stat = NCZMD_fetch_json_attrs(zinfo, key, &zgrp->zgroup.atts))) {
1133
0
        goto done;
1134
0
    }
1135
0
    jgroup = zgrp->zgroup.obj;
1136
0
    jattrs = zgrp->zgroup.atts;
1137
1138
0
    if(purezarr) {
1139
0
  if((stat = parse_group_content_pure(zinfo,grp,varnames,subgrps)))
1140
0
      goto done;
1141
0
        purezarr = 1;
1142
0
    } else { /*!purezarr*/
1143
0
  if(jgroup == NULL) { /* does not exist, use search */
1144
0
            if((stat = parse_group_content_pure(zinfo,grp,varnames,subgrps))) goto done;
1145
0
      purezarr = 1;
1146
0
  }
1147
0
  if(jattrs == NULL)  { /* does not exist, use search */
1148
0
            if((stat = parse_group_content_pure(zinfo,grp,varnames,subgrps))) goto done;
1149
0
      purezarr = 1;
1150
0
  } else { /* Extract the NCZ_V2_GROUP attribute*/
1151
0
            if((stat = getnczarrkey((NC_OBJ*)grp,NCZ_V2_GROUP,&jnczgrp))) goto done;
1152
0
  }
1153
0
  nullfree(key); key = NULL;
1154
0
  if(jnczgrp) {
1155
            /* Pull out lists about group content */
1156
0
      if((stat = parse_group_content(jnczgrp,dimdefs,varnames,subgrps)))
1157
0
          goto done;
1158
0
  }
1159
0
    }
1160
1161
0
    if(!purezarr) {
1162
  /* Define dimensions */
1163
0
  if((stat = define_dims(file,grp,dimdefs))) goto done;
1164
0
    }
1165
1166
    /* Define vars taking xarray into account */
1167
0
    if((stat = define_vars(file,grp,varnames))) goto done;
1168
1169
    /* Define sub-groups */
1170
0
    if((stat = define_subgrps(file,grp,subgrps))) goto done;
1171
1172
0
done:
1173
0
    NCJreclaim(json);
1174
0
    nclistfreeall(dimdefs);
1175
0
    nclistfreeall(varnames);
1176
0
    nclistfreeall(subgrps);
1177
0
    nullfree(key);
1178
0
    return ZUNTRACE(stat);
1179
0
}
1180
1181
1182
/**
1183
@internal Read attributes from a group or var and create a list
1184
of annotated NC_ATT_INFO_T* objects. This will process
1185
_NCProperties attribute specially.
1186
@param zfile - [in] the containing file (annotation)
1187
@param container - [in] the containing object
1188
@return NC_NOERR
1189
@author Dennis Heimbigner
1190
*/
1191
int
1192
ncz_read_atts(NC_FILE_INFO_T* file, NC_OBJ* container)
1193
0
{
1194
0
    int stat = NC_NOERR;
1195
0
    size_t i;
1196
0
    char* fullpath = NULL;
1197
0
    char* key = NULL;
1198
0
    NCZ_FILE_INFO_T* zinfo = NULL;
1199
0
    NC_VAR_INFO_T* var = NULL;
1200
0
    NCZ_VAR_INFO_T* zvar = NULL;
1201
0
    NC_GRP_INFO_T* grp = NULL;
1202
0
    NCZ_GRP_INFO_T* zgrp = NULL;
1203
0
    NC_ATT_INFO_T* att = NULL;
1204
0
    NCindex* attlist = NULL;
1205
0
    nc_type typeid;
1206
0
    size_t len, typelen;
1207
0
    void* data = NULL;
1208
0
    NC_ATT_INFO_T* fillvalueatt = NULL;
1209
0
    nc_type typehint = NC_NAT;
1210
0
    int purezarr,zarrkeys;
1211
0
    const NCjson* jattrs = NULL;
1212
0
    const NCjson* jtypes = NULL;
1213
0
    struct ZARROBJ* zobj = NULL;
1214
1215
0
    ZTRACE(3,"file=%s container=%s",file->controller->path,container->name);
1216
1217
0
    zinfo = file->format_file_info;
1218
0
    purezarr = (zinfo->controls.flags & FLAG_PUREZARR)?1:0;
1219
0
    zarrkeys = (zinfo->controls.flags & FLAG_NCZARR_KEY)?1:0;
1220
 
1221
0
    if(container->sort == NCGRP) { 
1222
0
  grp = ((NC_GRP_INFO_T*)container);
1223
0
  attlist =  grp->att;
1224
0
        zgrp = (NCZ_GRP_INFO_T*)(grp->format_grp_info);
1225
0
  zobj = &zgrp->zgroup;
1226
0
    } else {
1227
0
  var = ((NC_VAR_INFO_T*)container);
1228
0
  attlist =  var->att;
1229
0
        zvar = (NCZ_VAR_INFO_T*)(var->format_var_info);
1230
0
  zobj = &zvar->zarray;
1231
0
    }
1232
0
    assert(purezarr || zarrkeys || zobj->obj != NULL);
1233
1234
0
    if((stat = download_jatts(file, container, &jattrs, &jtypes))) goto done;
1235
1236
0
    if(jattrs != NULL) {
1237
  /* Iterate over the attributes to create the in-memory attributes */
1238
  /* Watch for special cases: _FillValue and  _ARRAY_DIMENSIONS (xarray), etc. */
1239
0
  for(i=0;i<NCJdictlength(jattrs);i++) {
1240
0
      NCjson* key = NCJdictkey(jattrs,i);
1241
0
      NCjson* value = NCJdictvalue(jattrs,i);
1242
0
      const NC_reservedatt* ra = NULL;
1243
0
      int isfillvalue = 0;
1244
0
          int isdfaltmaxstrlen = 0;
1245
0
            int ismaxstrlen = 0;
1246
0
      const char* aname = NCJstring(key);
1247
      /* See if this is a notable attribute */
1248
0
      if(var != NULL && strcmp(aname,NC_ATT_FILLVALUE)==0) isfillvalue = 1;
1249
0
      if(grp != NULL && grp->parent == NULL && strcmp(aname,NC_NCZARR_DEFAULT_MAXSTRLEN_ATTR)==0)
1250
0
          isdfaltmaxstrlen = 1;
1251
0
      if(var != NULL && strcmp(aname,NC_NCZARR_MAXSTRLEN_ATTR)==0)
1252
0
          ismaxstrlen = 1;
1253
1254
      /* See if this is reserved attribute */
1255
0
      ra = NC_findreserved(aname);
1256
0
      if(ra != NULL) {
1257
    /* case 1: name = _NCProperties, grp=root, varid==NC_GLOBAL */
1258
0
    if(strcmp(aname,NCPROPS)==0 && grp != NULL && file->root_grp == grp) {
1259
        /* Setup provenance */
1260
0
        if(NCJsort(value) != NCJ_STRING)
1261
0
      {stat = (THROW(NC_ENCZARR)); goto done;} /*malformed*/
1262
0
        if((stat = NCZ_read_provenance(file,aname,NCJstring(value))))
1263
0
      goto done;
1264
0
    }
1265
    /* case 2: name = _ARRAY_DIMENSIONS, sort==NCVAR, flags & HIDDENATTRFLAG */
1266
0
    if(strcmp(aname,NC_XARRAY_DIMS)==0 && var != NULL && (ra->flags & HIDDENATTRFLAG)) {
1267
                /* store for later */
1268
0
        size_t i;
1269
0
        assert(NCJsort(value) == NCJ_ARRAY);
1270
0
        if((zvar->xarray = nclistnew())==NULL)
1271
0
            {stat = NC_ENOMEM; goto done;}
1272
0
        for(i=0;i<NCJarraylength(value);i++) {
1273
0
      const NCjson* k = NCJith(value,i);
1274
0
      assert(k != NULL && NCJsort(k) == NCJ_STRING);
1275
0
      nclistpush(zvar->xarray,strdup(NCJstring(k)));
1276
0
        }
1277
0
    }
1278
    /* case other: if attribute is hidden */
1279
0
    if(ra->flags & HIDDENATTRFLAG) continue; /* ignore it */
1280
0
      }
1281
0
      typehint = NC_NAT;
1282
0
      if(isfillvalue)
1283
0
          typehint = var->type_info->hdr.id ; /* if unknown use the var's type for _FillValue */
1284
      /* Create the attribute */
1285
      /* Collect the attribute's type and value  */
1286
0
      if((stat = computeattrinfo(aname,jtypes,typehint,purezarr,value,
1287
0
           &typeid,&typelen,&len,&data)))
1288
0
    goto done;
1289
0
      if((stat = ncz_makeattr(container,attlist,aname,typeid,len,data,&att)))
1290
0
    goto done;
1291
      /* No longer need this copy of the data */
1292
0
        if((stat = NC_reclaim_data_all(file->controller,att->nc_typeid,data,len))) goto done;           
1293
0
      data = NULL;
1294
0
      if(isfillvalue)
1295
0
          fillvalueatt = att;
1296
0
      if(ismaxstrlen && att->nc_typeid == NC_INT)
1297
0
          zvar->maxstrlen = ((int*)att->data)[0];
1298
0
      if(isdfaltmaxstrlen && att->nc_typeid == NC_INT)
1299
0
          zinfo->default_maxstrlen = ((int*)att->data)[0];
1300
0
  }
1301
0
    }
1302
    /* If we have not read a _FillValue, then go ahead and create it */
1303
0
    if(fillvalueatt == NULL && container->sort == NCVAR) {
1304
0
  if((stat = ncz_create_fillvalue((NC_VAR_INFO_T*)container)))
1305
0
      goto done;
1306
0
    }
1307
1308
    /* Remember that we have read the atts for this var or group. */
1309
0
    if(container->sort == NCVAR)
1310
0
  ((NC_VAR_INFO_T*)container)->atts_read = 1;
1311
0
    else
1312
0
  ((NC_GRP_INFO_T*)container)->atts_read = 1;
1313
1314
0
done:
1315
0
    if(data != NULL)
1316
0
        stat = NC_reclaim_data(file->controller,att->nc_typeid,data,len);
1317
0
    nullfree(fullpath);
1318
0
    nullfree(key);
1319
0
    return ZUNTRACE(THROW(stat));
1320
0
}
1321
1322
/**
1323
 * @internal Materialize dimensions into memory
1324
 *
1325
 * @param file Pointer to file info struct.
1326
 * @param grp Pointer to grp info struct.
1327
 * @param diminfo List of (name,length,isunlimited) triples
1328
 *
1329
 * @return ::NC_NOERR No error.
1330
 * @author Dennis Heimbigner
1331
 */
1332
static int
1333
define_dims(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, NClist* diminfo)
1334
0
{
1335
0
    size_t i;
1336
0
    int stat = NC_NOERR;
1337
1338
0
    ZTRACE(3,"file=%s grp=%s |diminfo|=%u",file->controller->path,grp->hdr.name,nclistlength(diminfo));
1339
1340
    /* Reify each dim in turn */
1341
0
    for(i = 0; i < nclistlength(diminfo); i+=3) {
1342
0
  NC_DIM_INFO_T* dim = NULL;
1343
0
  size64_t len = 0;
1344
0
  long long isunlim = 0;
1345
0
  const char* name = nclistget(diminfo,i);
1346
0
  const char* slen = nclistget(diminfo,i+1);
1347
0
  const char* sisunlimited = nclistget(diminfo,i+2);
1348
1349
  /* Create the NC_DIM_INFO_T object */
1350
0
  sscanf(slen,"%lld",&len); /* Get length */
1351
0
  if(sisunlimited != NULL)
1352
0
      sscanf(sisunlimited,"%lld",&isunlim); /* Get unlimited flag */
1353
0
  else
1354
0
      isunlim = 0;
1355
0
  if((stat = nc4_dim_list_add(grp, name, (size_t)len, -1, &dim)))
1356
0
      goto done;
1357
0
  dim->unlimited = (isunlim ? 1 : 0);
1358
0
  if((dim->format_dim_info = calloc(1,sizeof(NCZ_DIM_INFO_T))) == NULL)
1359
0
      {stat = NC_ENOMEM; goto done;}
1360
0
  ((NCZ_DIM_INFO_T*)dim->format_dim_info)->common.file = file;
1361
0
    }
1362
1363
0
done:
1364
0
    return ZUNTRACE(THROW(stat));
1365
0
}
1366
1367
1368
/**
1369
 * @internal Materialize single var into memory;
1370
 * Take xarray and purezarr into account.
1371
 *
1372
 * @param file Pointer to file info struct.
1373
 * @param grp Pointer to grp info struct.
1374
 * @param varname name of variable in this group
1375
 *
1376
 * @return ::NC_NOERR No error.
1377
 * @author Dennis Heimbigner
1378
 */
1379
static int
1380
define_var1(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, const char* varname)
1381
0
{
1382
0
    int stat = NC_NOERR;
1383
0
    size_t j;
1384
0
    NCZ_FILE_INFO_T* zinfo = NULL;
1385
0
    int purezarr = 0;
1386
0
    int xarray = 0;
1387
    /* per-variable info */
1388
0
    NC_VAR_INFO_T* var = NULL;
1389
0
    NCZ_VAR_INFO_T* zvar = NULL;
1390
0
    const NCjson* jvar = NULL;
1391
0
    const NCjson* jatts = NULL; /* corresponding to jvar */
1392
0
    const NCjson* jncvar = NULL;
1393
0
    const NCjson* jdimrefs = NULL;
1394
0
    const NCjson* jvalue = NULL;
1395
0
    char* key = NULL;
1396
0
    size64_t* shapes = NULL;
1397
0
    NClist* dimnames = NULL;
1398
0
    int varsized = 0;
1399
0
    int suppress = 0; /* Abort processing of this variable */
1400
0
    nc_type vtype = NC_NAT;
1401
0
    int vtypelen = 0;
1402
0
    size_t rank = 0;
1403
0
    size_t zarr_rank = 0; /* Need to watch out for scalars */
1404
#ifdef NETCDF_ENABLE_NCZARR_FILTERS
1405
    const NCjson* jfilter = NULL;
1406
    int chainindex = 0;
1407
#endif
1408
1409
0
    ZTRACE(3,"file=%s grp=%s varname=%s",file->controller->path,grp->hdr.name,varname);
1410
1411
0
    zinfo = file->format_file_info;
1412
1413
0
    if(zinfo->controls.flags & FLAG_PUREZARR) purezarr = 1;
1414
0
    if(zinfo->controls.flags & FLAG_XARRAYDIMS) {xarray = 1;}
1415
1416
0
    dimnames = nclistnew();
1417
1418
0
    if((stat = nc4_var_list_add2(grp, varname, &var)))
1419
0
  goto done;
1420
1421
    /* And its annotation */
1422
0
    if((zvar = calloc(1,sizeof(NCZ_VAR_INFO_T)))==NULL)
1423
0
  {stat = NC_ENOMEM; goto done;}
1424
0
    var->format_var_info = zvar;
1425
0
    zvar->common.file = file;
1426
1427
    /* pretend it was created */
1428
0
    var->created = 1;
1429
1430
    /* Indicate we do not have quantizer yet */
1431
0
    var->quantize_mode = -1;
1432
1433
    /* Construct var path */
1434
0
    if((stat = NCZ_varkey(var,&key)))
1435
0
  goto done;
1436
1437
0
    if ((stat = NCZMD_fetch_json_array(zinfo, key, &zvar->zarray.obj)) \
1438
0
    || (stat = NCZMD_fetch_json_attrs(zinfo, key, &zvar->zarray.atts))) {
1439
0
        goto done;
1440
0
    }
1441
0
    jvar = zvar->zarray.obj;
1442
0
    jatts = zvar->zarray.atts;
1443
0
    assert(jvar == NULL || NCJsort(jvar) == NCJ_DICT);
1444
0
    assert(jatts == NULL || NCJsort(jatts) == NCJ_DICT);
1445
1446
    /* Verify the format */
1447
0
    {
1448
0
  int version;
1449
0
  if((stat = NCJdictget(jvar,"zarr_format",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1450
0
  sscanf(NCJstring(jvalue),"%d",&version);
1451
0
  if(version != zinfo->format.zarr)
1452
0
      {stat = (THROW(NC_ENCZARR)); goto done;}
1453
0
    }
1454
1455
    /* Set the type and endianness of the variable */
1456
0
    {
1457
0
  int endianness;
1458
0
  if((stat = NCJdictget(jvar,"dtype",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1459
  /* Convert dtype to nc_type + endianness */
1460
0
  if((stat = ncz_dtype2nctype(NCJstring(jvalue),NC_NAT,purezarr,&vtype,&endianness,&vtypelen)))
1461
0
      goto done;
1462
0
  if(vtype > NC_NAT && vtype <= NC_MAX_ATOMIC_TYPE) {
1463
      /* Locate the NC_TYPE_INFO_T object */
1464
0
      if((stat = ncz_gettype(file,grp,vtype,&var->type_info)))
1465
0
    goto done;
1466
0
  } else {stat = NC_EBADTYPE; goto done;}
1467
#if 0 /* leave native in place */
1468
  if(endianness == NC_ENDIAN_NATIVE)
1469
      endianness = zinfo->native_endianness;
1470
  if(endianness == NC_ENDIAN_NATIVE)
1471
      endianness = (NC_isLittleEndian()?NC_ENDIAN_LITTLE:NC_ENDIAN_BIG);
1472
  if(endianness == NC_ENDIAN_LITTLE || endianness == NC_ENDIAN_BIG) {
1473
      var->endianness = endianness;
1474
  } else {stat = NC_EBADTYPE; goto done;}
1475
#else
1476
0
  var->endianness = endianness;
1477
0
#endif
1478
0
  var->type_info->endianness = var->endianness; /* Propagate */
1479
0
  if(vtype == NC_STRING) {
1480
0
      zvar->maxstrlen = vtypelen;
1481
0
      vtypelen = sizeof(char*); /* in-memory len */
1482
0
      if(zvar->maxstrlen <= 0) zvar->maxstrlen = NCZ_get_maxstrlen((NC_OBJ*)var);
1483
0
  }
1484
0
    }
1485
1486
0
    if(!purezarr) {
1487
0
  if(jatts == NULL) {stat = NC_ENCZARR; goto done;}
1488
  /* Extract the _NCZARR_ARRAY values */
1489
  /* Do this first so we know about storage esp. scalar */
1490
  /* Extract the NCZ_V2_ARRAY dict */
1491
0
  if((stat = getnczarrkey((NC_OBJ*)var,NCZ_V2_ARRAY,&jncvar))) goto done;
1492
0
  if(jncvar == NULL) {stat = NC_ENCZARR; goto done;}
1493
0
  assert((NCJsort(jncvar) == NCJ_DICT));
1494
  /* Extract scalar flag */
1495
0
  if((stat = NCJdictget(jncvar,"scalar",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1496
0
  if(jvalue != NULL) {
1497
0
      var->storage = NC_CHUNKED;
1498
0
      zvar->scalar = 1;
1499
0
  }
1500
  /* Extract storage flag */
1501
0
  if((stat = NCJdictget(jncvar,"storage",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1502
0
  if(jvalue != NULL)
1503
0
      var->storage = NC_CHUNKED;
1504
  /* Extract dimrefs list  */
1505
0
  if((stat = dictgetalt(jncvar,"dimension_references","dimrefs",&jdimrefs))) goto done;
1506
0
  if(jdimrefs != NULL) { /* Extract the dimref names */
1507
0
      assert((NCJsort(jdimrefs) == NCJ_ARRAY));
1508
0
      if(zvar->scalar) {
1509
0
    assert(NCJarraylength(jdimrefs) == 0);         
1510
0
      } else {
1511
0
    rank = NCJarraylength(jdimrefs);
1512
0
    for(j=0;j<rank;j++) {
1513
0
        const NCjson* dimpath = NCJith(jdimrefs,j);
1514
0
        assert(NCJsort(dimpath) == NCJ_STRING);
1515
0
        nclistpush(dimnames,strdup(NCJstring(dimpath)));
1516
0
    }
1517
0
      }
1518
0
      jdimrefs = NULL; /* avoid double free */
1519
0
  } /* else  simulate it from the shape of the variable */
1520
0
    }
1521
1522
    /* Capture dimension_separator (must precede chunk cache creation) */
1523
0
    {
1524
0
  NCglobalstate* ngs = NC_getglobalstate();
1525
0
  assert(ngs != NULL);
1526
0
  zvar->dimension_separator = 0;
1527
0
  if((stat = NCJdictget(jvar,"dimension_separator",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1528
0
  if(jvalue != NULL) {
1529
      /* Verify its value */
1530
0
      if(NCJsort(jvalue) == NCJ_STRING && NCJstring(jvalue) != NULL && strlen(NCJstring(jvalue)) == 1)
1531
0
         zvar->dimension_separator = NCJstring(jvalue)[0];
1532
0
  }
1533
  /* If value is invalid, then use global default */
1534
0
  if(!islegaldimsep(zvar->dimension_separator))
1535
0
      zvar->dimension_separator = ngs->zarr.dimension_separator; /* use global value */
1536
0
  assert(islegaldimsep(zvar->dimension_separator)); /* we are hosed */
1537
0
    }
1538
1539
    /* fill_value; must precede calls to adjust cache */
1540
0
    {
1541
0
  if((stat = NCJdictget(jvar,"fill_value",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1542
0
  if(jvalue == NULL || NCJsort(jvalue) == NCJ_NULL)
1543
0
      var->no_fill = 1;
1544
0
  else {
1545
0
      size_t fvlen;
1546
0
      nc_type atypeid = vtype;
1547
0
      var->no_fill = 0;
1548
0
      if((stat = computeattrdata(var->type_info->hdr.id, &atypeid, jvalue, NULL, &fvlen, &var->fill_value)))
1549
0
    goto done;
1550
0
      assert(atypeid == vtype);
1551
      /* Note that we do not create the _FillValue
1552
         attribute here to avoid having to read all
1553
         the attributes and thus foiling lazy read.*/
1554
0
  }
1555
0
    }
1556
1557
    /* shape */
1558
0
    {
1559
0
  if((stat = NCJdictget(jvar,"shape",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1560
0
  if(NCJsort(jvalue) != NCJ_ARRAY) {stat = (THROW(NC_ENCZARR)); goto done;}
1561
  
1562
  /* Process the rank */
1563
0
  zarr_rank = NCJarraylength(jvalue);
1564
0
  if(zarr_rank == 0) {
1565
      // No shape, no chunks, no (xarray) dimensions => scalar
1566
0
      if(zvar->xarray == NULL) {
1567
      // get xarray attributes
1568
0
      if((stat = ncz_read_atts(file,(NC_OBJ*)var))) goto done;
1569
0
      }
1570
0
      if(NC_NOERR == (stat = NCJdictget(jvar,"chunks",&jvalue)) && \
1571
0
      jvalue && NCJsort(jvalue) == NCJ_ARRAY && NCJarraylength(jvalue) == 0 && \
1572
0
      xarray && nclistlength(zvar->xarray) == 0) {
1573
0
      zvar->scalar = 1;
1574
      /* Save the rank of the variable */
1575
0
      if ((stat = nc4_var_set_ndims(var,1)))
1576
0
        goto done;
1577
0
      }else{
1578
      /* suppress variable */
1579
0
      ZLOG(NCLOGWARN,"Empty shape for variable %s suppressed",var->hdr.name);
1580
0
      suppress = 1;
1581
0
      goto suppressvar;
1582
0
      }
1583
0
  }
1584
1585
0
  if(zvar->scalar) {
1586
0
      rank = 0;
1587
0
      zarr_rank = 1; /* Zarr does not support scalars */
1588
0
  } else 
1589
0
      rank = (zarr_rank = NCJarraylength(jvalue));
1590
1591
0
  if(zarr_rank > 0) {
1592
      /* Save the rank of the variable */
1593
0
      if((stat = nc4_var_set_ndims(var, rank))) goto done;
1594
      /* extract the shapes */
1595
0
      if((shapes = (size64_t*)malloc(sizeof(size64_t)*(size_t)zarr_rank)) == NULL)
1596
0
    {stat = (THROW(NC_ENOMEM)); goto done;}
1597
0
      if((stat = decodeints(jvalue, shapes))) goto done;
1598
0
  }
1599
0
    }
1600
1601
    /* chunks */
1602
0
    {
1603
0
  size64_t chunks[NC_MAX_VAR_DIMS];
1604
0
  if((stat = NCJdictget(jvar,"chunks",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1605
0
  if(jvalue != NULL && NCJsort(jvalue) != NCJ_ARRAY)
1606
0
      {stat = (THROW(NC_ENCZARR)); goto done;}
1607
  /* Verify the rank */
1608
0
  if(zvar->scalar || zarr_rank == 0) {
1609
0
      if(var->ndims != 0)
1610
0
    {stat = (THROW(NC_ENCZARR)); goto done;}
1611
0
      zvar->chunkproduct = 1;
1612
0
      zvar->chunksize = zvar->chunkproduct * var->type_info->size;
1613
      /* Create the cache */
1614
0
      if((stat = NCZ_create_chunk_cache(var,var->type_info->size*zvar->chunkproduct,zvar->dimension_separator,&zvar->cache)))
1615
0
    goto done;
1616
0
  } else {/* !zvar->scalar */
1617
0
      if(zarr_rank == 0) {stat = NC_ENCZARR; goto done;}
1618
0
      var->storage = NC_CHUNKED;
1619
0
      if(var->ndims != rank)
1620
0
    {stat = (THROW(NC_ENCZARR)); goto done;}
1621
0
      if((var->chunksizes = malloc(sizeof(size_t)*(size_t)zarr_rank)) == NULL)
1622
0
    {stat = NC_ENOMEM; goto done;}
1623
0
      if((stat = decodeints(jvalue, chunks))) goto done;
1624
      /* validate the chunk sizes */
1625
0
      zvar->chunkproduct = 1;
1626
0
      for(j=0;j<rank;j++) {
1627
0
    if(chunks[j] == 0)
1628
0
        {stat = (THROW(NC_ENCZARR)); goto done;}
1629
0
    var->chunksizes[j] = (size_t)chunks[j];
1630
0
    zvar->chunkproduct *= chunks[j];
1631
0
      }
1632
0
      zvar->chunksize = zvar->chunkproduct * var->type_info->size;
1633
      /* Create the cache */
1634
0
      if((stat = NCZ_create_chunk_cache(var,var->type_info->size*zvar->chunkproduct,zvar->dimension_separator,&zvar->cache)))
1635
0
    goto done;
1636
0
  }
1637
0
  if((stat = NCZ_adjust_var_cache(var))) goto done;
1638
0
    }
1639
    /* Capture row vs column major; currently, column major not used*/
1640
0
    {
1641
0
  if((stat = NCJdictget(jvar,"order",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1642
0
  if(strcmp(NCJstring(jvalue),"C") > 0)
1643
0
      ((NCZ_VAR_INFO_T*)var->format_var_info)->order = 1;
1644
0
  else ((NCZ_VAR_INFO_T*)var->format_var_info)->order = 0;
1645
0
    }
1646
    /* filters key */
1647
    /* From V2 Spec: A list of JSON objects providing codec configurations,
1648
       or null if no filters are to be applied. Each codec configuration
1649
       object MUST contain a "id" key identifying the codec to be used. */
1650
    /* Do filters key before compressor key so final filter chain is in correct order */
1651
0
    {
1652
#ifdef NETCDF_ENABLE_NCZARR_FILTERS
1653
  if(var->filters == NULL) var->filters = (void*)nclistnew();
1654
  if(zvar->incompletefilters == NULL) zvar->incompletefilters = (void*)nclistnew();
1655
  chainindex = 0; /* track location of filter in the chain */
1656
  if((stat = NCZ_filter_initialize())) goto done;
1657
  if((stat = NCJdictget(jvar,"filters",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1658
  if(jvalue != NULL && NCJsort(jvalue) != NCJ_NULL) {
1659
      int k;
1660
      if(NCJsort(jvalue) != NCJ_ARRAY) {stat = NC_EFILTER; goto done;}
1661
      for(k=0;;k++) {
1662
    jfilter = NULL;
1663
    jfilter = NCJith(jvalue,k);
1664
    if(jfilter == NULL) break; /* done */
1665
    if(NCJsort(jfilter) != NCJ_DICT) {stat = NC_EFILTER; goto done;}
1666
    if((stat = NCZ_filter_build(file,var,jfilter,chainindex++))) goto done;
1667
      }
1668
  }
1669
#endif
1670
0
    }
1671
1672
    /* compressor key */
1673
    /* From V2 Spec: A JSON object identifying the primary compression codec and providing
1674
       configuration parameters, or ``null`` if no compressor is to be used. */
1675
#ifdef NETCDF_ENABLE_NCZARR_FILTERS
1676
    { 
1677
  if(var->filters == NULL) var->filters = (void*)nclistnew();
1678
  if((stat = NCZ_filter_initialize())) goto done;
1679
  if((stat = NCJdictget(jvar,"compressor",&jfilter))<0) {stat = NC_EINVAL; goto done;}
1680
  if(jfilter != NULL && NCJsort(jfilter) != NCJ_NULL) {
1681
      if(NCJsort(jfilter) != NCJ_DICT) {stat = NC_EFILTER; goto done;}
1682
      if((stat = NCZ_filter_build(file,var,jfilter,chainindex++))) goto done;
1683
  }
1684
    }
1685
    /* Suppress variable if there are filters and var is not fixed-size */
1686
    if(varsized && nclistlength((NClist*)var->filters) > 0)
1687
  suppress = 1;
1688
#endif
1689
0
    if(zarr_rank > 0) {
1690
0
  if((stat = computedimrefs(file, var, purezarr, xarray, rank, dimnames, shapes, var->dim)))
1691
0
      goto done;
1692
0
  if(!zvar->scalar) {
1693
      /* Extract the dimids */
1694
0
      for(j=0;j<rank;j++)
1695
0
    var->dimids[j] = var->dim[j]->hdr.id;
1696
0
  }
1697
0
    }
1698
1699
#ifdef NETCDF_ENABLE_NCZARR_FILTERS
1700
    if(!suppress) {
1701
  /* At this point, we can finalize the filters */
1702
  if((stat = NCZ_filter_setup(var))) goto done;
1703
    }
1704
#endif
1705
1706
0
suppressvar:
1707
0
    if(suppress) {
1708
  /* Reclaim NCZarr variable specific info */
1709
0
  (void)NCZ_zclose_var1(var);
1710
  /* Remove from list of variables and reclaim the top level var object */
1711
0
  (void)nc4_var_list_del(grp, var);
1712
0
  var = NULL;
1713
0
    }
1714
1715
0
done:
1716
0
    nclistfreeall(dimnames); dimnames = NULL;
1717
0
    nullfree(shapes); shapes = NULL;
1718
0
    nullfree(key); key = NULL;
1719
0
    return ZUNTRACE(stat);
1720
0
}
1721
1722
/**
1723
 * @internal Materialize vars into memory;
1724
 * Take xarray and purezarr into account.
1725
 *
1726
 * @param file Pointer to file info struct.
1727
 * @param grp Pointer to grp info struct.
1728
 * @param varnames List of names of variables in this group
1729
 *
1730
 * @return ::NC_NOERR No error.
1731
 * @author Dennis Heimbigner
1732
 */
1733
static int
1734
define_vars(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, NClist* varnames)
1735
0
{
1736
0
    int stat = NC_NOERR;
1737
0
    size_t i;
1738
1739
0
    ZTRACE(3,"file=%s grp=%s |varnames|=%u",file->controller->path,grp->hdr.name,nclistlength(varnames));
1740
1741
    /* Load each var in turn */
1742
0
    for(i = 0; i < nclistlength(varnames); i++) {
1743
0
  const char* varname = (const char*)nclistget(varnames,i);
1744
0
        if((stat = define_var1(file,grp,varname))) goto done;
1745
0
  varname = nclistget(varnames,i);
1746
0
    }
1747
1748
0
done:
1749
0
    return ZUNTRACE(stat);
1750
0
}
1751
1752
/**
1753
 * @internal Materialize subgroups into memory
1754
 *
1755
 * @param file Pointer to file info struct.
1756
 * @param grp Pointer to grp info struct.
1757
 * @param subgrpnames List of names of subgroups in this group
1758
 *
1759
 * @return ::NC_NOERR No error.
1760
 * @author Dennis Heimbigner
1761
 */
1762
static int
1763
define_subgrps(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, NClist* subgrpnames)
1764
0
{
1765
0
    size_t i;
1766
0
    int stat = NC_NOERR;
1767
1768
0
    ZTRACE(3,"file=%s grp=%s |subgrpnames|=%u",file->controller->path,grp->hdr.name,nclistlength(subgrpnames));
1769
1770
    /* Load each subgroup name in turn */
1771
0
    for(i = 0; i < nclistlength(subgrpnames); i++) {
1772
0
  NC_GRP_INFO_T* g = NULL;
1773
0
  const char* gname = nclistget(subgrpnames,i);
1774
0
  char norm_name[NC_MAX_NAME];
1775
  /* Check and normalize the name. */
1776
0
  if((stat = nc4_check_name(gname, norm_name)))
1777
0
      goto done;
1778
0
  if((stat = nc4_grp_list_add(file, grp, norm_name, &g)))
1779
0
      goto done;
1780
0
  if(!(g->format_grp_info = calloc(1, sizeof(NCZ_GRP_INFO_T))))
1781
0
      {stat = NC_ENOMEM; goto done;}
1782
0
  ((NCZ_GRP_INFO_T*)g->format_grp_info)->common.file = file;
1783
0
    }
1784
1785
    /* Recurse to fill in subgroups */
1786
0
    for(i=0;i<ncindexsize(grp->children);i++) {
1787
0
  NC_GRP_INFO_T* g = (NC_GRP_INFO_T*)ncindexith(grp->children,i);
1788
0
  if((stat = define_grp(file,g)))
1789
0
      goto done;
1790
0
    }
1791
1792
0
done:
1793
0
    return ZUNTRACE(THROW(stat));
1794
0
}
1795
1796
1797
/**************************************************/
1798
/* Utilities */
1799
1800
static int
1801
parse_group_content(const NCjson* jcontent, NClist* dimdefs, NClist* varnames, NClist* subgrps)
1802
0
{
1803
0
    int stat = NC_NOERR;
1804
0
    size_t i;
1805
0
    const NCjson* jvalue = NULL;
1806
1807
0
    ZTRACE(3,"jcontent=|%s| |dimdefs|=%u |varnames|=%u |subgrps|=%u",NCJtotext(jcontent,0),(unsigned)nclistlength(dimdefs),(unsigned)nclistlength(varnames),(unsigned)nclistlength(subgrps));
1808
1809
0
    if((stat=dictgetalt(jcontent,"dimensions","dims",&jvalue))) goto done;
1810
0
    if(jvalue != NULL) {
1811
0
  if(NCJsort(jvalue) != NCJ_DICT) {stat = (THROW(NC_ENCZARR)); goto done;}
1812
  /* Extract the dimensions defined in this group */
1813
0
  for(i=0;i<NCJdictlength(jvalue);i++) {
1814
0
      const NCjson* jname = NCJdictkey(jvalue,i);
1815
0
      const NCjson* jleninfo = NCJdictvalue(jvalue,i);
1816
0
          const NCjson* jtmp = NULL;
1817
0
            const char* slen = "0";
1818
0
            const char* sunlim = "0";
1819
0
      char norm_name[NC_MAX_NAME + 1];
1820
      /* Verify name legality */
1821
0
      if((stat = nc4_check_name(NCJstring(jname), norm_name)))
1822
0
    {stat = NC_EBADNAME; goto done;}
1823
      /* check the length */
1824
0
            if(NCJsort(jleninfo) == NCJ_DICT) {
1825
0
    if((stat = NCJdictget(jleninfo,"size",&jtmp))<0) {stat = NC_EINVAL; goto done;}
1826
0
    if(jtmp== NULL)
1827
0
        {stat = NC_EBADNAME; goto done;}
1828
0
    slen = NCJstring(jtmp);
1829
    /* See if unlimited */
1830
0
    if((stat = NCJdictget(jleninfo,"unlimited",&jtmp))<0) {stat = NC_EINVAL; goto done;}
1831
0
          if(jtmp == NULL) sunlim = "0"; else sunlim = NCJstring(jtmp);
1832
0
            } else if(jleninfo != NULL && NCJsort(jleninfo) == NCJ_INT) {
1833
0
    slen = NCJstring(jleninfo);   
1834
0
      } else
1835
0
    {stat = NC_ENCZARR; goto done;}
1836
0
      nclistpush(dimdefs,strdup(norm_name));
1837
0
      nclistpush(dimdefs,strdup(slen));
1838
0
          nclistpush(dimdefs,strdup(sunlim));
1839
0
  }
1840
0
    }
1841
1842
0
    if((stat=dictgetalt(jcontent,"arrays","vars",&jvalue))) goto done;
1843
0
    if(jvalue != NULL) {
1844
  /* Extract the variable names in this group */
1845
0
  for(i=0;i<NCJarraylength(jvalue);i++) {
1846
0
      NCjson* jname = NCJith(jvalue,i);
1847
0
      char norm_name[NC_MAX_NAME + 1];
1848
      /* Verify name legality */
1849
0
      if((stat = nc4_check_name(NCJstring(jname), norm_name)))
1850
0
    {stat = NC_EBADNAME; goto done;}
1851
0
      nclistpush(varnames,strdup(norm_name));
1852
0
  }
1853
0
    }
1854
1855
0
    if((stat = NCJdictget(jcontent,"groups",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1856
0
    if(jvalue != NULL) {
1857
  /* Extract the subgroup names in this group */
1858
0
  for(i=0;i<NCJarraylength(jvalue);i++) {
1859
0
      NCjson* jname = NCJith(jvalue,i);
1860
0
      char norm_name[NC_MAX_NAME + 1];
1861
      /* Verify name legality */
1862
0
      if((stat = nc4_check_name(NCJstring(jname), norm_name)))
1863
0
    {stat = NC_EBADNAME; goto done;}
1864
0
      nclistpush(subgrps,strdup(norm_name));
1865
0
  }
1866
0
    }
1867
1868
0
done:
1869
0
    return ZUNTRACE(THROW(stat));
1870
0
}
1871
1872
static int
1873
parse_group_content_pure(NCZ_FILE_INFO_T*  zinfo, NC_GRP_INFO_T* grp, NClist* varnames, NClist* subgrps)
1874
0
{
1875
0
    int stat = NC_NOERR;
1876
0
    char *key = NULL;
1877
1878
0
    ZTRACE(3,"zinfo=%s grp=%s |varnames|=%u |subgrps|=%u",zinfo->common.file->controller->path,grp->hdr.name,(unsigned)nclistlength(varnames),(unsigned)nclistlength(subgrps));
1879
1880
0
    if ((stat = NCZ_grpkey(grp,&key))){
1881
0
        goto done;
1882
0
    }
1883
0
    nclistclear(varnames);
1884
0
    nclistclear(subgrps);
1885
0
    if((stat = NCZMD_list_nodes(zinfo, key, subgrps, varnames))) goto done;
1886
1887
0
done:
1888
0
    nullfree(key);
1889
0
    return ZUNTRACE(THROW(stat));
1890
0
}
1891
1892
/* Convert a list of integer strings to 64 bit dimension sizes (shapes) */
1893
static int
1894
decodeints(const NCjson* jshape, size64_t* shapes)
1895
0
{
1896
0
    int stat = NC_NOERR;
1897
0
    size_t i;
1898
1899
0
    for(i=0;i<NCJarraylength(jshape);i++) {
1900
0
  struct ZCVT zcvt;
1901
0
  nc_type typeid = NC_NAT;
1902
0
  NCjson* jv = NCJith(jshape,i);
1903
0
  if((stat = NCZ_json2cvt(jv,&zcvt,&typeid))) goto done;
1904
0
  switch (typeid) {
1905
0
  case NC_INT64:
1906
0
  if(zcvt.int64v < 0) {stat = (THROW(NC_ENCZARR)); goto done;}
1907
0
      shapes[i] = (size64_t)zcvt.int64v;
1908
0
      break;
1909
0
  case NC_UINT64:
1910
0
      shapes[i] = (size64_t)zcvt.uint64v;
1911
0
      break;
1912
0
  default: {stat = (THROW(NC_ENCZARR)); goto done;}
1913
0
  }
1914
0
    }
1915
1916
0
done:
1917
0
    return THROW(stat);
1918
0
}
1919
1920
/* This code is a subset of NCZ_def_dim */
1921
static int
1922
createdim(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, const char* name, size64_t dimlen, NC_DIM_INFO_T** dimp)
1923
0
{
1924
0
    int stat = NC_NOERR;
1925
0
    NC_DIM_INFO_T* thed = NULL;
1926
0
    if(grp == NULL) grp = file->root_grp;
1927
1928
0
    if((stat = nc4_dim_list_add(grp, name, (size_t)dimlen, -1, &thed)))
1929
0
        goto done;
1930
0
    assert(thed != NULL);
1931
    /* Create struct for NCZ-specific dim info. */
1932
0
    if (!(thed->format_dim_info = calloc(1, sizeof(NCZ_DIM_INFO_T))))
1933
0
  {stat = NC_ENOMEM; goto done;}
1934
0
    ((NCZ_DIM_INFO_T*)thed->format_dim_info)->common.file = file;
1935
0
    *dimp = thed; thed = NULL;
1936
0
done:
1937
0
    return stat;
1938
0
}
1939
1940
1941
/*
1942
Given a list of segments, find corresponding group.
1943
*/
1944
static int
1945
locategroup(NC_FILE_INFO_T* file, size_t nsegs, NClist* segments, NC_GRP_INFO_T** grpp)
1946
0
{
1947
0
    size_t i, j;
1948
0
    int found, stat = NC_NOERR;
1949
0
    NC_GRP_INFO_T* grp = NULL;
1950
1951
0
    grp = file->root_grp;
1952
0
    for(i=0;i<nsegs;i++) {
1953
0
  const char* segment = nclistget(segments,i);
1954
0
  char norm_name[NC_MAX_NAME];
1955
0
  found = 0;
1956
0
  if((stat = nc4_check_name(segment,norm_name))) goto done;
1957
0
  for(j=0;j<ncindexsize(grp->children);j++) {
1958
0
      NC_GRP_INFO_T* subgrp = (NC_GRP_INFO_T*)ncindexith(grp->children,j);
1959
0
      if(strcmp(subgrp->hdr.name,norm_name)==0) {
1960
0
    grp = subgrp;
1961
0
    found = 1;
1962
0
    break;
1963
0
      }
1964
0
  }
1965
0
  if(!found) {stat = NC_ENOGRP; goto done;}
1966
0
    }
1967
    /* grp should be group of interest */
1968
0
    if(grpp) *grpp = grp;
1969
1970
0
done:
1971
0
    return THROW(stat);
1972
0
}
1973
1974
static int
1975
parsedimrefs(NC_FILE_INFO_T* file, NClist* dimnames, size64_t* shape, NC_DIM_INFO_T** dims, int create)
1976
0
{
1977
0
    size_t i;
1978
0
    int stat = NC_NOERR;
1979
0
    NClist* segments = NULL;
1980
1981
0
    for(i=0;i<nclistlength(dimnames);i++) {
1982
0
  NC_GRP_INFO_T* g = NULL;
1983
0
  NC_DIM_INFO_T* d = NULL;
1984
0
  size_t j;
1985
0
  const char* dimpath = nclistget(dimnames,i);
1986
0
  const char* dimname = NULL;
1987
1988
  /* Locate the corresponding NC_DIM_INFO_T* object */
1989
0
  nclistfreeall(segments);
1990
0
  segments = nclistnew();
1991
0
  if((stat = ncz_splitkey(dimpath,segments)))
1992
0
      goto done;
1993
0
  if((stat=locategroup(file,nclistlength(segments)-1,segments,&g)))
1994
0
      goto done;
1995
  /* Lookup the dimension */
1996
0
  dimname = nclistget(segments,nclistlength(segments)-1);
1997
0
  d = NULL;
1998
0
  dims[i] = NULL;
1999
0
  for(j=0;j<ncindexsize(g->dim);j++) {
2000
0
      d = (NC_DIM_INFO_T*)ncindexith(g->dim,j);
2001
0
      if(strcmp(d->hdr.name,dimname)==0) {
2002
0
    dims[i] = d;
2003
0
    break;
2004
0
      }
2005
0
  }
2006
0
  if(dims[i] == NULL && create) {
2007
      /* If not found and create then create it */
2008
0
      if((stat = createdim(file, g, dimname, shape[i], &dims[i])))
2009
0
          goto done;
2010
0
  } else {
2011
      /* Verify consistency */
2012
0
      if(dims[i]->len != shape[i])
2013
0
          {stat = NC_EDIMSIZE; goto done;}
2014
0
  }
2015
0
  assert(dims[i] != NULL);
2016
0
    }
2017
0
done:
2018
0
    nclistfreeall(segments);
2019
0
    return THROW(stat);
2020
0
}
2021
2022
/**
2023
 * @internal Get the metadata for a variable.
2024
 *
2025
 * @param var Pointer to var info struct.
2026
 *
2027
 * @return ::NC_NOERR No error.
2028
 * @return ::NC_EBADID Bad ncid.
2029
 * @return ::NC_ENOMEM Out of memory.
2030
 * @return ::NC_EHDFERR HDF5 returned error.
2031
 * @return ::NC_EVARMETA Error with var metadata.
2032
 * @author Ed Hartnett
2033
 */
2034
int
2035
ncz_get_var_meta(NC_FILE_INFO_T* file, NC_VAR_INFO_T* var)
2036
0
{
2037
0
    int retval = NC_NOERR;
2038
2039
0
    assert(file && var && var->format_var_info);
2040
0
    LOG((3, "%s: var %s", __func__, var->hdr.name));
2041
0
    ZTRACE(3,"file=%s var=%s",file->controller->path,var->hdr.name);
2042
    
2043
    /* Have we already read the var metadata? */
2044
0
    if (var->meta_read)
2045
0
  goto done;
2046
2047
#ifdef LOOK
2048
    /* Get the current chunk cache settings. */
2049
    if ((access_pid = H5Dget_access_plist(hdf5_var->hdf_datasetid)) < 0)
2050
  BAIL(NC_EVARMETA);
2051
2052
    /* Learn about current chunk cache settings. */
2053
    if ((H5Pget_chunk_cache(access_pid, &(var->chunk_cache_nelems),
2054
          &(var->chunk_cache_size), &rdcc_w0)) < 0)
2055
  BAIL(NC_EHDFERR);
2056
    var->chunk_cache_preemption = rdcc_w0;
2057
2058
    /* Get the dataset creation properties. */
2059
    if ((propid = H5Dget_create_plist(hdf5_var->hdf_datasetid)) < 0)
2060
  BAIL(NC_EHDFERR);
2061
2062
    /* Get var chunking info. */
2063
    if ((retval = get_chunking_info(propid, var)))
2064
  BAIL(retval);
2065
2066
    /* Get filter info for a var. */
2067
    if ((retval = get_filter_info(propid, var)))
2068
  BAIL(retval);
2069
2070
    /* Get fill value, if defined. */
2071
    if ((retval = get_fill_info(propid, var)))
2072
  BAIL(retval);
2073
2074
    /* Is this a deflated variable with a chunksize greater than the
2075
     * current cache size? */
2076
    if ((retval = nc4_adjust_var_cache(var)))
2077
  BAIL(retval);
2078
2079
    /* Is there an attribute which means quantization was used? */
2080
    if ((retval = get_quantize_info(var)))
2081
  BAIL(retval);
2082
2083
    if (var->coords_read && !var->dimscale)
2084
  if ((retval = get_attached_info(var, hdf5_var, var->ndims, hdf5_var->hdf_datasetid)))
2085
      goto done;;
2086
#endif
2087
2088
    /* Remember that we have read the metadata for this var. */
2089
0
    var->meta_read = NC_TRUE;
2090
0
done:
2091
0
    return ZUNTRACE(retval);
2092
0
}
2093
2094
/* Compute the set of dim refs for this variable, taking purezarr and xarray into account */
2095
static int
2096
computedimrefs(NC_FILE_INFO_T* file, NC_VAR_INFO_T* var, int purezarr, int xarray, int ndims, NClist* dimnames, size64_t* shapes, NC_DIM_INFO_T** dims)
2097
0
{
2098
0
    int stat = NC_NOERR;
2099
0
    size_t i;
2100
0
    int createdims = 0; /* 1 => we need to create the dims in current group
2101
                                if they do not already exist */
2102
0
    NCZ_FILE_INFO_T* zfile = (NCZ_FILE_INFO_T*)file->format_file_info;
2103
0
    NCZ_VAR_INFO_T* zvar = (NCZ_VAR_INFO_T*)(var->format_var_info);
2104
0
    NCjson* jatts = NULL;
2105
0
    NC_GRP_INFO_T* grp = var->container; /* Immediate parent group for var */
2106
0
    char* grpfqn = NULL; /* FQN for grp */
2107
2108
0
    ZTRACE(3,"file=%s var=%s purezarr=%d xarray=%d ndims=%d shape=%s",
2109
0
      file->controller->path,var->hdr.name,purezarr,xarray,(int)ndims,nczprint_vector(ndims,shapes));
2110
0
    assert(zfile && zvar);
2111
2112
0
    if(purezarr && xarray) {/* Read in the attributes to get xarray dimdef attribute; Note that it might not exist */
2113
  /* Note that if xarray && !purezarr, then xarray will be superseded by the nczarr dimensions key */
2114
0
        char zdimname[4096];
2115
0
  if(zvar->xarray == NULL) {
2116
0
      assert(nclistlength(dimnames) == 0);
2117
0
      if((stat = ncz_read_atts(file,(NC_OBJ*)var))) goto done;
2118
0
  }
2119
0
  if(zvar->xarray != NULL) {
2120
0
      size_t len;
2121
      /* get the FQN of the current group */
2122
0
      if((stat = NCZ_grpkey(grp, &grpfqn))) goto done;
2123
0
      assert(grpfqn != NULL);
2124
0
      len = strlen(grpfqn);
2125
0
      assert(len > 0);
2126
      /* supress any trailing '/' */
2127
0
      if(grpfqn[len - 1] == '/') grpfqn[len -1] = '\0';
2128
      /* convert xarray to FQN dimnames */
2129
0
      for(i=0;i<nclistlength(zvar->xarray);i++) {
2130
0
          snprintf(zdimname,sizeof(zdimname),"%s/%s",grpfqn,(const char*)nclistget(zvar->xarray,i));
2131
0
          nclistpush(dimnames,strdup(zdimname));
2132
0
      }
2133
0
  }
2134
0
  createdims = 1; /* may need to create them */
2135
0
    }
2136
2137
    /* If pure zarr and we have no dimref names, then fake it */
2138
    /* Note that to avoid creating duplicates of anonymous dims, we create dim in root group */
2139
0
    if(purezarr && nclistlength(dimnames) == 0) {
2140
0
  int i;
2141
0
  createdims = 1;
2142
0
        for(i=0;i<ndims;i++) {
2143
      /* Compute the set of absolute paths to dimrefs */
2144
0
            char zdimname[4096];
2145
0
      snprintf(zdimname,sizeof(zdimname),"/%s_%llu",NCDIMANON,shapes[i]);
2146
0
      nclistpush(dimnames,strdup(zdimname));
2147
0
  }
2148
0
    }
2149
2150
    /* Now, use dimnames to get the dims; create if necessary */
2151
0
    if((stat = parsedimrefs(file,dimnames,shapes,dims,createdims)))
2152
0
        goto done;
2153
2154
0
done:
2155
0
    nullfree(grpfqn);
2156
0
    NCJreclaim(jatts);
2157
0
    return ZUNTRACE(THROW(stat));
2158
0
}
2159
2160
/**
2161
Implement the JSON convention:
2162
Stringify it as the value and make the attribute be of type "char".
2163
*/
2164
2165
static int
2166
json_convention_read(const NCjson* json, NCjson** jtextp)
2167
0
{
2168
0
    int stat = NC_NOERR;
2169
0
    NCjson* jtext = NULL;
2170
0
    char* text = NULL;
2171
2172
0
    if(json == NULL) {stat = NC_EINVAL; goto done;}
2173
0
    if(NCJunparse(json,0,&text)) {stat = NC_EINVAL; goto done;}
2174
0
    NCJnewstring(NCJ_STRING,text,&jtext);
2175
0
    *jtextp = jtext; jtext = NULL;
2176
0
done:
2177
0
    NCJreclaim(jtext);
2178
0
    nullfree(text);
2179
0
    return stat;
2180
0
}
2181
2182
#if 0
2183
/**
2184
Implement the JSON convention:
2185
Parse it as JSON and use that as its value in .zattrs.
2186
*/
2187
static int
2188
json_convention_write(size_t len, const void* data, NCjson** jsonp, int* isjsonp)
2189
{
2190
    int stat = NC_NOERR;
2191
    NCjson* jexpr = NULL;
2192
    int isjson = 0;
2193
2194
    assert(jsonp != NULL);
2195
    if(NCJparsen(len,(char*)data,0,&jexpr)) {
2196
  /* Ok, just treat as sequence of chars */
2197
  NCJnewstringn(NCJ_STRING, len, data, &jexpr);
2198
    }
2199
    isjson = 1;
2200
    *jsonp = jexpr; jexpr = NULL;
2201
    if(isjsonp) *isjsonp = isjson;
2202
done:
2203
    NCJreclaim(jexpr);
2204
    return stat;
2205
}
2206
#endif
2207
2208
#if 0
2209
/* Convert an attribute "types list to an envv style list */
2210
static int
2211
jtypes2atypes(NCjson* jtypes, NClist* atypes)
2212
{
2213
    int stat = NC_NOERR;
2214
    size_t i;
2215
    for(i=0;i<NCJdictlength(jtypes);i++) {
2216
  const NCjson* key = NCJdictkey(jtypes,i);
2217
  const NCjson* value = NCJdictvalue(jtypes,i);
2218
  if(NCJsort(key) != NCJ_STRING) {stat = (THROW(NC_ENCZARR)); goto done;}
2219
  if(NCJsort(value) != NCJ_STRING) {stat = (THROW(NC_ENCZARR)); goto done;}
2220
  nclistpush(atypes,strdup(NCJstring(key)));
2221
  nclistpush(atypes,strdup(NCJstring(value)));
2222
    }
2223
done:
2224
    return stat;
2225
}
2226
#endif
2227
2228
/* See if there is reason to believe the specified path is a legitimate (NC)Zarr file
2229
 * Do a breadth first walk of the tree starting at file path.
2230
 * @param file to validate
2231
 * @return NC_NOERR if it looks ok
2232
 * @return NC_ENOTNC if it does not look ok
2233
 */
2234
static int
2235
ncz_validate(NC_FILE_INFO_T* file)
2236
0
{
2237
0
    int stat = NC_NOERR;
2238
0
    NCZ_FILE_INFO_T* zinfo = (NCZ_FILE_INFO_T*)file->format_file_info;
2239
0
    int validate = 0;
2240
0
    NCbytes* prefix = ncbytesnew();
2241
0
    NClist* queue = nclistnew();
2242
0
    NClist* nextlevel = nclistnew();
2243
0
    NCZMAP* map = zinfo->map;
2244
0
    char* path = NULL;
2245
0
    char* segment = NULL;
2246
0
    size_t seglen;
2247
0
      
2248
0
    ZTRACE(3,"file=%s",file->controller->path);
2249
0
2250
0
    path = strdup("/");
2251
0
    nclistpush(queue,path);
2252
0
    path = NULL;
2253
0
    do {
2254
0
        nullfree(path); path = NULL;
2255
0
  /* This should be full path key */
2256
0
  path = nclistremove(queue,0); /* remove from front of queue */
2257
0
  /* get list of next level segments (partial keys) */
2258
0
  assert(nclistlength(nextlevel)==0);
2259
0
        if((stat=nczmap_search(map,path,nextlevel))) {validate = 0; goto done;}
2260
0
        /* For each s in next level, test, convert to full path, and push onto queue */
2261
0
  while(nclistlength(nextlevel) > 0) {
2262
0
            segment = nclistremove(nextlevel,0);
2263
0
            seglen = nulllen(segment);
2264
0
      if((seglen >= 2 && memcmp(segment,".z",2)==0) || (seglen >= 4 && memcmp(segment,".ncz",4)==0)) {
2265
0
    validate = 1;
2266
0
          goto done;
2267
0
       }
2268
0
       /* Convert to full path */
2269
0
       ncbytesclear(prefix);
2270
0
       ncbytescat(prefix,path);
2271
0
       if(strlen(path) > 1) ncbytescat(prefix,"/");
2272
0
       ncbytescat(prefix,segment);
2273
0
       /* push onto queue */
2274
0
       nclistpush(queue,ncbytesextract(prefix));
2275
0
       nullfree(segment); segment = NULL;
2276
0
   }
2277
0
    } while(nclistlength(queue) > 0);
2278
0
done:
2279
0
    if(!validate) stat = NC_ENOTNC;
2280
0
    nullfree(path);
2281
0
    nullfree(segment);
2282
0
    nclistfreeall(queue);
2283
0
    nclistfreeall(nextlevel);
2284
0
    ncbytesfree(prefix);
2285
0
    return ZUNTRACE(THROW(stat));
2286
0
}
2287
2288
/**
2289
Insert an attribute into a list of attribute, including typing
2290
Takes control of javalue.
2291
@param jatts
2292
@param jtypes
2293
@param aname
2294
@param javalue
2295
*/
2296
static int
2297
insert_attr(NCjson* jatts, NCjson* jtypes, const char* aname, NCjson* javalue, const char* atype)
2298
0
{
2299
0
    int stat = NC_NOERR;
2300
0
    if(jatts != NULL) {
2301
0
  if(jtypes != NULL) {
2302
0
            NCJinsertstring(jtypes,aname,atype);
2303
0
  }
2304
0
        NCJinsert(jatts,aname,javalue);
2305
0
    }
2306
0
    return THROW(stat);
2307
0
}
2308
2309
/**
2310
Insert _nczarr_attr into .zattrs
2311
Take control of jtypes
2312
@param jatts
2313
@param jtypes
2314
*/
2315
static int
2316
insert_nczarr_attr(NCjson* jatts, NCjson* jtypes)
2317
0
{
2318
0
    NCjson* jdict = NULL;
2319
0
    if(jatts != NULL && jtypes != NULL) {
2320
0
  NCJinsertstring(jtypes,NCZ_V2_ATTR,"|J0"); /* type for _nczarr_attr */
2321
0
        NCJnew(NCJ_DICT,&jdict);
2322
0
        NCJinsert(jdict,"types",jtypes);
2323
0
        NCJinsert(jatts,NCZ_V2_ATTR,jdict);
2324
0
        jdict = NULL;
2325
0
    }
2326
0
    return NC_NOERR;
2327
0
}
2328
2329
/**
2330
Upload a .zattrs object
2331
Optionally take control of jatts and jtypes
2332
@param file
2333
@param container
2334
@param jattsp
2335
@param jtypesp
2336
*/
2337
static int
2338
upload_attrs(NC_FILE_INFO_T* file, NC_OBJ* container, NCjson* jatts)
2339
0
{
2340
0
    int stat = NC_NOERR;
2341
0
    NCZ_FILE_INFO_T* zinfo = NULL;
2342
0
    NC_VAR_INFO_T* var = NULL;
2343
0
    NC_GRP_INFO_T* grp = NULL;
2344
0
    NCZMAP* map = NULL;
2345
0
    char* fullpath = NULL;
2346
0
    char* key = NULL;
2347
0
2348
0
    ZTRACE(3,"file=%s grp=%s",file->controller->path,container->name);
2349
0
2350
0
    if(jatts == NULL) goto done;    
2351
0
2352
0
    zinfo = file->format_file_info;
2353
0
    map = zinfo->map;
2354
0
2355
0
    if(container->sort == NCVAR) {
2356
0
        var = (NC_VAR_INFO_T*)container;
2357
0
    } else if(container->sort == NCGRP) {
2358
0
        grp = (NC_GRP_INFO_T*)container;
2359
0
    }
2360
0
2361
0
    /* Construct container path */
2362
0
    if(container->sort == NCGRP)
2363
0
  stat = NCZ_grpkey(grp,&fullpath);
2364
0
    else
2365
0
  stat = NCZ_varkey(var,&fullpath);
2366
0
    if(stat) goto done;
2367
0
2368
0
    /* write .zattrs*/
2369
0
    if((stat = nczm_concat(fullpath,Z2ATTRS,&key))) goto done;
2370
0
    if((stat=NCZ_uploadjson(map,key,jatts))) goto done;
2371
0
    nullfree(key); key = NULL;
2372
0
2373
0
done:
2374
0
    nullfree(fullpath);
2375
0
    return ZUNTRACE(THROW(stat));
2376
0
}
2377
2378
#if 0
2379
/**
2380
@internal Get contents of a meta object; fail it it does not exist
2381
@param zmap - [in] map
2382
@param key - [in] key of the object
2383
@param jsonp - [out] return parsed json || NULL if not exists
2384
@return NC_NOERR
2385
@return NC_EXXX
2386
@author Dennis Heimbigner
2387
*/
2388
static int
2389
readarray(NCZMAP* zmap, const char* key, NCjson** jsonp)
2390
{
2391
    int stat = NC_NOERR;
2392
    NCjson* json = NULL;
2393
2394
    if((stat = NCZ_downloadjson(zmap,key,&json))) goto done;
2395
    if(json != NULL && NCJsort(json) != NCJ_ARRAY) {stat = NC_ENCZARR; goto done;}
2396
    if(jsonp) {*jsonp = json; json = NULL;}
2397
done:
2398
    NCJreclaim(json);
2399
    return stat;
2400
}
2401
#endif
2402
2403
/* Get one of two key values from a dict */
2404
static int
2405
dictgetalt(const NCjson* jdict, const char* name, const char* alt, const NCjson** jvaluep)
2406
0
{
2407
0
    int stat = NC_NOERR;
2408
0
    const NCjson* jvalue = NULL;
2409
0
    if((stat = NCJdictget(jdict,name,&jvalue))<0) {stat = NC_EINVAL; goto done;} /* try this first */
2410
0
    if(jvalue == NULL) {
2411
0
        if((stat = NCJdictget(jdict,alt,&jvalue))<0) {stat = NC_EINVAL; goto done;} /* try this alternative*/
2412
0
    }
2413
0
    if(jvaluep) *jvaluep = jvalue;
2414
0
done:
2415
0
    return THROW(stat);
2416
0
}
2417
2418
/* Get _nczarr_xxx from either .zXXX or .zattrs */
2419
static int
2420
getnczarrkey(NC_OBJ* container, const char* name, const NCjson** jncxxxp)
2421
0
{
2422
0
    int stat = NC_NOERR;
2423
0
    const NCjson* jxxx = NULL;
2424
0
    NC_GRP_INFO_T* grp = NULL;
2425
0
    NC_VAR_INFO_T* var = NULL;
2426
0
    struct ZARROBJ* zobj = NULL;
2427
2428
    /* Decode container */
2429
0
    if(container->sort == NCGRP) {
2430
0
  grp = (NC_GRP_INFO_T*)container;
2431
0
  zobj = &((NCZ_GRP_INFO_T*)grp->format_grp_info)->zgroup;
2432
0
    } else {
2433
0
  var = (NC_VAR_INFO_T*)container;
2434
0
  zobj = &((NCZ_VAR_INFO_T*)var->format_var_info)->zarray;
2435
0
    }
2436
2437
    /* Try .zattrs first */
2438
0
    if(zobj->atts != NULL) {
2439
0
  jxxx = NULL;
2440
0
        if((stat = NCJdictget(zobj->atts,name,&jxxx))<0) {stat = NC_EINVAL; goto done;}
2441
0
    }
2442
0
    if(jxxx == NULL) {
2443
        /* Try .zxxx second */
2444
0
  if(zobj->obj != NULL) {
2445
0
            if((stat = NCJdictget(zobj->obj,name,&jxxx))<0) {stat = NC_EINVAL; goto done;}
2446
0
  }
2447
0
  if(jxxx != NULL)
2448
0
        zobj->nczv1 = 1; /* Mark as old style with _nczarr_xxx in obj not attributes */
2449
0
    }
2450
0
    if(jncxxxp) *jncxxxp = jxxx;
2451
0
done:
2452
0
    return THROW(stat);
2453
0
}
2454
2455
static int
2456
downloadzarrobj(NC_FILE_INFO_T* file, struct ZARROBJ* zobj, const char* fullpath, const char* objname)
2457
0
{
2458
0
    int stat = NC_NOERR;
2459
0
    char* key = NULL;
2460
0
    NCZMAP* map = ((NCZ_FILE_INFO_T*)file->format_file_info)->map;
2461
0
2462
0
    /* Download .zXXX and .zattrs */
2463
0
    nullfree(zobj->prefix);
2464
0
    zobj->prefix = strdup(fullpath);
2465
0
    NCJreclaim(zobj->obj); zobj->obj = NULL;
2466
0
    NCJreclaim(zobj->atts); zobj->obj = NULL;
2467
0
    if((stat = nczm_concat(fullpath,objname,&key))) goto done;
2468
0
    if((stat=NCZ_downloadjson(map,key,&zobj->obj))) goto done;
2469
0
    nullfree(key); key = NULL;
2470
0
    if((stat = nczm_concat(fullpath,Z2ATTRS,&key))) goto done;
2471
0
    if((stat=NCZ_downloadjson(map,key,&zobj->atts))) goto done;
2472
0
done:
2473
0
    nullfree(key);
2474
0
    return THROW(stat);
2475
0
}